blob: 33a5a90aacfe0c1b2dabf601758db01f416cb744 [file] [log] [blame]
Ray Essick3938dc62016-11-01 08:56:56 -07001/*
Ray Essick2e9c63b2017-03-29 15:16:44 -07002 * Copyright (C) 2017 The Android Open Source Project
Ray Essick3938dc62016-11-01 08:56:56 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ray Essick3938dc62016-11-01 08:56:56 -070017//#define LOG_NDEBUG 0
18#define LOG_TAG "MediaAnalyticsService"
19#include <utils/Log.h>
20
Ray Essick3938dc62016-11-01 08:56:56 -070021#include "MediaAnalyticsService.h"
22
Andy Hung17dbaf22019-10-11 14:06:31 -070023#include <pwd.h> //getpwuid
24
25#include <audio_utils/clock.h> // clock conversions
26#include <android/content/pm/IPackageManagerNative.h> // package info
27#include <binder/IPCThreadState.h> // get calling uid
28#include <cutils/properties.h> // for property_get
29#include <private/android_filesystem_config.h> // UID
30
Ray Essick3938dc62016-11-01 08:56:56 -070031namespace android {
32
Andy Hung1efc9c62019-12-03 13:43:33 -080033using namespace mediametrics;
34
Ray Essickf65f4212017-08-31 11:41:19 -070035// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070036// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070037// count: hard limit of # records
38// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070039//
Andy Hung17dbaf22019-10-11 14:06:31 -070040static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070041// 2019/6: average daily per device is currently 375-ish;
42// setting this to 2000 is large enough to catch most devices
43// we'll lose some data on very very media-active devices, but only for
44// the gms collection; statsd will have already covered those for us.
45// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070046static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070047
48// max we expire in a single call, to constrain how long we hold the
49// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070050static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070051
52// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070053
Ray Essick3938dc62016-11-01 08:56:56 -070054MediaAnalyticsService::MediaAnalyticsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -070055 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -070056 mMaxRecordAgeNs(kMaxRecordAgeNs),
Ray Essick72a436b2018-06-14 15:08:13 -070057 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce),
Andy Hung17dbaf22019-10-11 14:06:31 -070058 mDumpProtoDefault(MediaAnalyticsItem::PROTO_V1)
59{
60 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -070061}
62
Andy Hung17dbaf22019-10-11 14:06:31 -070063MediaAnalyticsService::~MediaAnalyticsService()
64{
65 ALOGD("%s", __func__);
66 // the class destructor clears anyhow, but we enforce clearing items first.
67 mItemsDiscarded += mItems.size();
68 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -070069}
70
Andy Hunga87e69c2019-10-18 10:07:40 -070071status_t MediaAnalyticsService::submitInternal(MediaAnalyticsItem *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -080072{
Ray Essickd38e1742017-01-23 15:17:06 -080073 // we control these, generally not trusting user input
Ray Essick3938dc62016-11-01 08:56:56 -070074 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Ray Essick721b7a02017-09-11 09:33:56 -070075 // round nsecs to seconds
Andy Hung17dbaf22019-10-11 14:06:31 -070076 now = (now + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
77 // TODO: if we convert to boot time, do we need to round timestamp?
Ray Essick3938dc62016-11-01 08:56:56 -070078 item->setTimestamp(now);
Ray Essickd38e1742017-01-23 15:17:06 -080079
Andy Hung17dbaf22019-10-11 14:06:31 -070080 const int pid = IPCThreadState::self()->getCallingPid();
81 const int uid = IPCThreadState::self()->getCallingUid();
82 const int uid_given = item->getUid();
83 const int pid_given = item->getPid();
Ray Essickd38e1742017-01-23 15:17:06 -080084
Andy Hung17dbaf22019-10-11 14:06:31 -070085 ALOGV("%s: caller has uid=%d, embedded uid=%d", __func__, uid, uid_given);
86 bool isTrusted;
87 switch (uid) {
88 case AID_DRM:
89 case AID_MEDIA:
90 case AID_MEDIA_CODEC:
91 case AID_MEDIA_EX:
92 case AID_MEDIA_DRM:
93 // trusted source, only override default values
94 isTrusted = true;
95 if (uid_given == -1) {
Ray Essickd38e1742017-01-23 15:17:06 -080096 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -070097 }
98 if (pid_given == -1) {
99 item->setPid(pid);
100 }
101 break;
102 default:
103 isTrusted = false;
104 item->setPid(pid);
105 item->setUid(uid);
106 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800107 }
108
Adam Stone21c72122017-09-05 19:02:06 -0700109 // Overwrite package name and version if the caller was untrusted.
110 if (!isTrusted) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700111 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Adam Stone21c72122017-09-05 19:02:06 -0700112 } else if (item->getPkgName().empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700113 // empty, so fill out both parts
114 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Ray Essickfa149562017-09-19 09:27:31 -0700115 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700116 // trusted, provided a package, do nothing
Adam Stone21c72122017-09-05 19:02:06 -0700117 }
118
Andy Hung17dbaf22019-10-11 14:06:31 -0700119 ALOGV("%s: given uid %d; sanitized uid: %d sanitized pkg: %s "
120 "sanitized pkg version: %lld",
121 __func__,
Adam Stone21c72122017-09-05 19:02:06 -0700122 uid_given, item->getUid(),
123 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700124 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700125
126 mItemsSubmitted++;
127
128 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700129 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700130 if (release) delete item;
131 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700132 }
133
Ray Essick92d23b42018-01-29 12:10:30 -0800134 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700135 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700136
Ray Essick92d23b42018-01-29 12:10:30 -0800137 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700138 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700139 if (release) delete item;
140 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700141 }
Ray Essick92d23b42018-01-29 12:10:30 -0800142
Andy Hung17dbaf22019-10-11 14:06:31 -0700143 // send to statsd
144 extern bool dump2Statsd(MediaAnalyticsItem *item); // extern hook
145 (void)dump2Statsd(item); // failure should be logged in function.
Ray Essick6ce27e52019-02-15 10:58:05 -0800146
Andy Hunga87e69c2019-10-18 10:07:40 -0700147 if (!release) item = item->dup();
Ray Essick92d23b42018-01-29 12:10:30 -0800148 saveItem(item);
Andy Hunga87e69c2019-10-18 10:07:40 -0700149 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700150}
151
Ray Essickb5fac8e2016-12-12 11:33:56 -0800152status_t MediaAnalyticsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700153{
Ray Essick3938dc62016-11-01 08:56:56 -0700154 String8 result;
155
156 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700157 result.appendFormat("Permission Denial: "
Ray Essick3938dc62016-11-01 08:56:56 -0700158 "can't dump MediaAnalyticsService from pid=%d, uid=%d\n",
159 IPCThreadState::self()->getCallingPid(),
160 IPCThreadState::self()->getCallingUid());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800161 write(fd, result.string(), result.size());
162 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700163 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800164
165 // crack any parameters
Andy Hung17dbaf22019-10-11 14:06:31 -0700166 const String16 protoOption("-proto");
Ray Essick583a23a2017-11-27 12:49:57 -0800167 int chosenProto = mDumpProtoDefault;
Andy Hung17dbaf22019-10-11 14:06:31 -0700168 const String16 clearOption("-clear");
Ray Essickf65f4212017-08-31 11:41:19 -0700169 bool clear = false;
Andy Hung17dbaf22019-10-11 14:06:31 -0700170 const String16 sinceOption("-since");
Ray Essickf65f4212017-08-31 11:41:19 -0700171 nsecs_t ts_since = 0;
Andy Hung17dbaf22019-10-11 14:06:31 -0700172 const String16 helpOption("-help");
173 const String16 onlyOption("-only");
Ray Essick783bd0d2018-01-11 11:10:35 -0800174 std::string only;
Andy Hung17dbaf22019-10-11 14:06:31 -0700175 const int n = args.size();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800176 for (int i = 0; i < n; i++) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800177 if (args[i] == clearOption) {
178 clear = true;
Ray Essickf65f4212017-08-31 11:41:19 -0700179 } else if (args[i] == protoOption) {
180 i++;
181 if (i < n) {
182 String8 value(args[i]);
Ray Essick583a23a2017-11-27 12:49:57 -0800183 int proto = MediaAnalyticsItem::PROTO_V0;
Ray Essickf65f4212017-08-31 11:41:19 -0700184 char *endp;
185 const char *p = value.string();
186 proto = strtol(p, &endp, 10);
187 if (endp != p || *endp == '\0') {
188 if (proto < MediaAnalyticsItem::PROTO_FIRST) {
189 proto = MediaAnalyticsItem::PROTO_FIRST;
190 } else if (proto > MediaAnalyticsItem::PROTO_LAST) {
191 proto = MediaAnalyticsItem::PROTO_LAST;
192 }
Ray Essick583a23a2017-11-27 12:49:57 -0800193 chosenProto = proto;
194 } else {
195 result.append("unable to parse value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700196 }
Ray Essick583a23a2017-11-27 12:49:57 -0800197 } else {
198 result.append("missing value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700199 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800200 } else if (args[i] == sinceOption) {
201 i++;
202 if (i < n) {
203 String8 value(args[i]);
204 char *endp;
205 const char *p = value.string();
206 ts_since = strtoll(p, &endp, 10);
207 if (endp == p || *endp != '\0') {
208 ts_since = 0;
209 }
210 } else {
211 ts_since = 0;
212 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800213 // command line is milliseconds; internal units are nano-seconds
Andy Hung17dbaf22019-10-11 14:06:31 -0700214 ts_since *= NANOS_PER_MILLISECOND;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700215 } else if (args[i] == onlyOption) {
216 i++;
217 if (i < n) {
218 String8 value(args[i]);
Ray Essickf65f4212017-08-31 11:41:19 -0700219 only = value.string();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700220 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800221 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700222 // TODO: consider function area dumping.
223 // dumpsys media.metrics audiotrack,codec
224 // or dumpsys media.metrics audiotrack codec
225
Ray Essick35ad27f2017-01-30 14:04:11 -0800226 result.append("Recognized parameters:\n");
227 result.append("-help this help message\n");
Ray Essick583a23a2017-11-27 12:49:57 -0800228 result.append("-proto # dump using protocol #");
Ray Essick35ad27f2017-01-30 14:04:11 -0800229 result.append("-clear clears out saved records\n");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700230 result.append("-only X process records for component X\n");
231 result.append("-since X include records since X\n");
232 result.append(" (X is milliseconds since the UNIX epoch)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800233 write(fd, result.string(), result.size());
234 return NO_ERROR;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800235 }
236 }
237
Andy Hung17dbaf22019-10-11 14:06:31 -0700238 {
239 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800240
Andy Hung17dbaf22019-10-11 14:06:31 -0700241 result.appendFormat("Dump of the %s process:\n", kServiceName);
242 dumpHeaders_l(result, chosenProto, ts_since);
243 dumpRecent_l(result, chosenProto, ts_since, only.c_str());
Ray Essick583a23a2017-11-27 12:49:57 -0800244
Andy Hung17dbaf22019-10-11 14:06:31 -0700245 if (clear) {
246 mItemsDiscarded += mItems.size();
247 mItems.clear();
248 // shall we clear the summary data too?
Ray Essick2e9c63b2017-03-29 15:16:44 -0700249 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700250 }
251
252 write(fd, result.string(), result.size());
253 return NO_ERROR;
254}
255
256// dump headers
Andy Hung17dbaf22019-10-11 14:06:31 -0700257void MediaAnalyticsService::dumpHeaders_l(String8 &result, int dumpProto, nsecs_t ts_since)
Ray Essick92d23b42018-01-29 12:10:30 -0800258{
Andy Hung17dbaf22019-10-11 14:06:31 -0700259 result.appendFormat("Protocol Version: %d\n", dumpProto);
260 if (MediaAnalyticsItem::isEnabled()) {
261 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800262 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700263 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800264 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700265 result.appendFormat(
266 "Since Boot: Submissions: %lld Accepted: %lld\n",
267 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
268 result.appendFormat(
269 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
270 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
271 (long long)mItemsDiscardedExpire);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800272 if (ts_since != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700273 result.appendFormat(
274 "Emitting Queue entries more recent than: %lld\n",
275 (long long)ts_since);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800276 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700277}
278
Andy Hung17dbaf22019-10-11 14:06:31 -0700279void MediaAnalyticsService::dumpRecent_l(
280 String8 &result, int dumpProto, nsecs_t ts_since, const char * only)
Ray Essick92d23b42018-01-29 12:10:30 -0800281{
Andy Hung17dbaf22019-10-11 14:06:31 -0700282 if (only != nullptr && *only == '\0') {
283 only = nullptr;
Ray Essickf65f4212017-08-31 11:41:19 -0700284 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700285 result.append("\nFinalized Metrics (oldest first):\n");
286 dumpQueue_l(result, dumpProto, ts_since, only);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800287
288 // show who is connected and injecting records?
289 // talk about # records fed to the 'readers'
290 // talk about # records we discarded, perhaps "discarded w/o reading" too
Ray Essick3938dc62016-11-01 08:56:56 -0700291}
Ray Essick92d23b42018-01-29 12:10:30 -0800292
Andy Hung17dbaf22019-10-11 14:06:31 -0700293void MediaAnalyticsService::dumpQueue_l(String8 &result, int dumpProto) {
294 dumpQueue_l(result, dumpProto, (nsecs_t) 0, nullptr /* only */);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800295}
296
Andy Hung17dbaf22019-10-11 14:06:31 -0700297void MediaAnalyticsService::dumpQueue_l(
298 String8 &result, int dumpProto, nsecs_t ts_since, const char * only) {
Ray Essick3938dc62016-11-01 08:56:56 -0700299 int slot = 0;
300
Ray Essick92d23b42018-01-29 12:10:30 -0800301 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700302 result.append("empty\n");
Ray Essick3938dc62016-11-01 08:56:56 -0700303 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700304 for (const auto &item : mItems) {
305 nsecs_t when = item->getTimestamp();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800306 if (when < ts_since) {
307 continue;
308 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700309 // TODO: Only should be a set<string>
310 if (only != nullptr &&
311 item->getKey() /* std::string */ != only) {
312 ALOGV("%s: omit '%s', it's not '%s'",
313 __func__, item->getKey().c_str(), only);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700314 continue;
315 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700316 result.appendFormat("%5d: %s\n",
317 slot, item->toString(dumpProto).c_str());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800318 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700319 }
320 }
Ray Essick3938dc62016-11-01 08:56:56 -0700321}
322
323//
324// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700325
Ray Essick72a436b2018-06-14 15:08:13 -0700326// if item != NULL, it's the item we just inserted
327// true == more items eligible to be recovered
328bool MediaAnalyticsService::expirations_l(MediaAnalyticsItem *item)
Ray Essick92d23b42018-01-29 12:10:30 -0800329{
Ray Essick72a436b2018-06-14 15:08:13 -0700330 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800331
Andy Hung17dbaf22019-10-11 14:06:31 -0700332 // check queue size
333 size_t overlimit = 0;
334 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
335 overlimit = mItems.size() - mMaxRecords;
336 if (overlimit > mMaxRecordsExpiredAtOnce) {
337 more = true;
338 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700339 }
340 }
341
Andy Hung17dbaf22019-10-11 14:06:31 -0700342 // check queue times
343 size_t expired = 0;
344 if (!more && mMaxRecordAgeNs > 0) {
345 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
346 // we check one at a time, skip search would be more efficient.
347 size_t i = overlimit;
348 for (; i < mItems.size(); ++i) {
349 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700350 nsecs_t when = oitem->getTimestamp();
Andy Hung17dbaf22019-10-11 14:06:31 -0700351 if (oitem.get() == item) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800352 break;
353 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700354 if (now > when && (now - when) <= mMaxRecordAgeNs) {
355 break; // TODO: if we use BOOTTIME, should be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700356 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700357 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700358 // this represents "one too many"; tell caller there are
359 // more to be reclaimed.
360 more = true;
361 break;
362 }
Ray Essick3938dc62016-11-01 08:56:56 -0700363 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700364 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700365 }
Ray Essick72a436b2018-06-14 15:08:13 -0700366
Andy Hung17dbaf22019-10-11 14:06:31 -0700367 if (const size_t toErase = overlimit + expired;
368 toErase > 0) {
369 mItemsDiscardedCount += overlimit;
370 mItemsDiscardedExpire += expired;
371 mItemsDiscarded += toErase;
372 mItems.erase(mItems.begin(), mItems.begin() + toErase); // erase from front
373 }
Ray Essick72a436b2018-06-14 15:08:13 -0700374 return more;
375}
376
Andy Hung17dbaf22019-10-11 14:06:31 -0700377void MediaAnalyticsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700378{
379 bool more;
380 do {
381 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700382 std::lock_guard _l(mLock);
383 more = expirations_l(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700384 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700385}
386
Andy Hung17dbaf22019-10-11 14:06:31 -0700387void MediaAnalyticsService::saveItem(MediaAnalyticsItem *item)
Ray Essick72a436b2018-06-14 15:08:13 -0700388{
Andy Hung17dbaf22019-10-11 14:06:31 -0700389 std::lock_guard _l(mLock);
390 // we assume the items are roughly in time order.
391 mItems.emplace_back(item);
392 ++mItemsFinalized;
393 if (expirations_l(item)
394 && (!mExpireFuture.valid()
395 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
396 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700397 }
Ray Essick3938dc62016-11-01 08:56:56 -0700398}
399
Andy Hung17dbaf22019-10-11 14:06:31 -0700400/* static */
401bool MediaAnalyticsService::isContentValid(const MediaAnalyticsItem *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800402{
Andy Hung17dbaf22019-10-11 14:06:31 -0700403 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800404 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700405 const std::string &key = item->getKey();
406 for (const char *allowedKey : {
407 "audiopolicy",
408 "audiorecord",
409 "audiothread",
410 "audiotrack",
411 "codec",
412 "extractor",
413 "nuplayer",
414 }) {
415 if (key == allowedKey) {
416 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800417 }
418 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700419 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700420 return false;
421}
422
Andy Hung17dbaf22019-10-11 14:06:31 -0700423// are we rate limited, normally false
424bool MediaAnalyticsService::isRateLimited(MediaAnalyticsItem *) const
425{
426 return false;
427}
428
429// How long we hold package info before we re-fetch it
430constexpr nsecs_t PKG_EXPIRATION_NS = 30 * 60 * NANOS_PER_SECOND; // 30 minutes
Ray Essickf65f4212017-08-31 11:41:19 -0700431
432// give me the package name, perhaps going to find it
Ray Essick92d23b42018-01-29 12:10:30 -0800433// manages its own mutex operations internally
Andy Hung17dbaf22019-10-11 14:06:31 -0700434void MediaAnalyticsService::UidInfo::setPkgInfo(
435 MediaAnalyticsItem *item, uid_t uid, bool setName, bool setVersion)
Ray Essick92d23b42018-01-29 12:10:30 -0800436{
Andy Hung17dbaf22019-10-11 14:06:31 -0700437 ALOGV("%s: uid=%d", __func__, uid);
Ray Essickfa149562017-09-19 09:27:31 -0700438
439 if (!setName && !setVersion) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700440 return; // setting nothing? strange
Ray Essickfa149562017-09-19 09:27:31 -0700441 }
442
Andy Hung17dbaf22019-10-11 14:06:31 -0700443 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
444 struct UidToPkgInfo mapping;
Ray Essick92d23b42018-01-29 12:10:30 -0800445 {
Andy Hung17dbaf22019-10-11 14:06:31 -0700446 std::lock_guard _l(mUidInfoLock);
447 auto it = mPkgMappings.find(uid);
448 if (it != mPkgMappings.end()) {
449 mapping = it->second;
450 ALOGV("%s: uid %d expiration %lld now %lld",
451 __func__, uid, (long long)mapping.expiration, (long long)now);
Ray Essick92d23b42018-01-29 12:10:30 -0800452 if (mapping.expiration <= now) {
453 // purge the stale entry and fall into re-fetching
Andy Hung17dbaf22019-10-11 14:06:31 -0700454 ALOGV("%s: entry for uid %d expired, now %lld",
455 __func__, uid, (long long)now);
456 mPkgMappings.erase(it);
457 mapping.uid = (uid_t)-1; // this is always fully overwritten
Ray Essick92d23b42018-01-29 12:10:30 -0800458 }
Ray Essickf65f4212017-08-31 11:41:19 -0700459 }
Ray Essick92d23b42018-01-29 12:10:30 -0800460 }
461
462 // if we did not find it
463 if (mapping.uid == (uid_t)(-1)) {
Ray Essick783bd0d2018-01-11 11:10:35 -0800464 std::string pkg;
Andy Hung17dbaf22019-10-11 14:06:31 -0700465 std::string installer;
Dianne Hackborn4e2eeff2017-11-27 14:01:29 -0800466 int64_t versionCode = 0;
Ray Essickf65f4212017-08-31 11:41:19 -0700467
Andy Hung17dbaf22019-10-11 14:06:31 -0700468 const struct passwd *pw = getpwuid(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700469 if (pw) {
470 pkg = pw->pw_name;
471 }
Ray Essickf65f4212017-08-31 11:41:19 -0700472
Ray Essickfa149562017-09-19 09:27:31 -0700473 sp<IServiceManager> sm = defaultServiceManager();
Andy Hung17dbaf22019-10-11 14:06:31 -0700474 sp<content::pm::IPackageManagerNative> package_mgr;
475 if (sm.get() == nullptr) {
476 ALOGE("%s: Cannot find service manager", __func__);
Ray Essickf65f4212017-08-31 11:41:19 -0700477 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700478 sp<IBinder> binder = sm->getService(String16("package_native"));
479 if (binder.get() == nullptr) {
480 ALOGE("%s: Cannot find package_native", __func__);
481 } else {
482 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
Ray Essickfa149562017-09-19 09:27:31 -0700483 }
484 }
485
Andy Hung17dbaf22019-10-11 14:06:31 -0700486 if (package_mgr != nullptr) {
Ray Essickfa149562017-09-19 09:27:31 -0700487 std::vector<int> uids;
488 std::vector<std::string> names;
Ray Essickfa149562017-09-19 09:27:31 -0700489 uids.push_back(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700490 binder::Status status = package_mgr->getNamesForUids(uids, &names);
Ray Essickfa149562017-09-19 09:27:31 -0700491 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700492 ALOGE("%s: getNamesForUids failed: %s",
493 __func__, status.exceptionMessage().c_str());
Andy Hungeff0d082019-12-03 12:23:45 -0800494 } else {
495 if (!names[0].empty()) {
496 pkg = names[0].c_str();
497 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700498 }
499 }
500
501 // strip any leading "shared:" strings that came back
502 if (pkg.compare(0, 7, "shared:") == 0) {
503 pkg.erase(0, 7);
504 }
505 // determine how pkg was installed and the versionCode
506 if (pkg.empty()) {
507 pkg = std::to_string(uid); // no name for us to manage
508 } else if (strchr(pkg.c_str(), '.') == NULL) {
509 // not of form 'com.whatever...'; assume internal and ok
510 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
511 // android.* packages are assumed fine
512 } else if (package_mgr.get() != nullptr) {
513 String16 pkgName16(pkg.c_str());
514 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
515 if (!status.isOk()) {
516 ALOGE("%s: getInstallerForPackage failed: %s",
517 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700518 }
519
Andy Hung17dbaf22019-10-11 14:06:31 -0700520 // skip if we didn't get an installer
521 if (status.isOk()) {
522 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
Ray Essickfa149562017-09-19 09:27:31 -0700523 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700524 ALOGE("%s: getVersionCodeForPackage failed: %s",
525 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700526 }
527 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700528
529 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
530 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
531
532 if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
533 // from play store, we keep info
534 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
535 // some google source, we keep info
536 } else if (strcmp(installer.c_str(), "preload") == 0) {
537 // preloads, we keep the info
538 } else if (installer.c_str()[0] == '\0') {
539 // sideload (no installer); report UID only
540 pkg = std::to_string(uid);
541 versionCode = 0;
542 } else {
543 // unknown installer; report UID only
544 pkg = std::to_string(uid);
545 versionCode = 0;
546 }
547 } else {
548 // unvalidated by package_mgr just send uid.
549 pkg = std::to_string(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700550 }
551
552 // add it to the map, to save a subsequent lookup
Andy Hung17dbaf22019-10-11 14:06:31 -0700553 std::lock_guard _l(mUidInfoLock);
554 // always overwrite
555 mapping.uid = uid;
556 mapping.pkg = std::move(pkg);
557 mapping.installer = std::move(installer);
558 mapping.versionCode = versionCode;
559 mapping.expiration = now + PKG_EXPIRATION_NS;
560 ALOGV("%s: adding uid %d pkg '%s' expiration: %lld",
Greg Kaiser6c36c782019-10-18 06:27:56 -0700561 __func__, uid, mapping.pkg.c_str(), (long long)mapping.expiration);
Andy Hung17dbaf22019-10-11 14:06:31 -0700562 mPkgMappings[uid] = mapping;
Ray Essickf65f4212017-08-31 11:41:19 -0700563 }
564
Ray Essickfa149562017-09-19 09:27:31 -0700565 if (mapping.uid != (uid_t)(-1)) {
566 if (setName) {
567 item->setPkgName(mapping.pkg);
568 }
569 if (setVersion) {
570 item->setPkgVersionCode(mapping.versionCode);
Ray Essickf65f4212017-08-31 11:41:19 -0700571 }
572 }
Ray Essickf65f4212017-08-31 11:41:19 -0700573}
574
Ray Essick3938dc62016-11-01 08:56:56 -0700575} // namespace android