blob: f0cb9c1e016f4f3900343e5771bc521a322a6474 [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
Ray Essickf65f4212017-08-31 11:41:19 -070033// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070034// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070035// count: hard limit of # records
36// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070037//
Andy Hung17dbaf22019-10-11 14:06:31 -070038static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070039// 2019/6: average daily per device is currently 375-ish;
40// setting this to 2000 is large enough to catch most devices
41// we'll lose some data on very very media-active devices, but only for
42// the gms collection; statsd will have already covered those for us.
43// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070044static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070045
46// max we expire in a single call, to constrain how long we hold the
47// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070048static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070049
50// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070051
Ray Essick3938dc62016-11-01 08:56:56 -070052MediaAnalyticsService::MediaAnalyticsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -070053 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -070054 mMaxRecordAgeNs(kMaxRecordAgeNs),
Ray Essick72a436b2018-06-14 15:08:13 -070055 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce),
Andy Hung17dbaf22019-10-11 14:06:31 -070056 mDumpProtoDefault(MediaAnalyticsItem::PROTO_V1)
57{
58 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -070059}
60
Andy Hung17dbaf22019-10-11 14:06:31 -070061MediaAnalyticsService::~MediaAnalyticsService()
62{
63 ALOGD("%s", __func__);
64 // the class destructor clears anyhow, but we enforce clearing items first.
65 mItemsDiscarded += mItems.size();
66 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -070067}
68
Ray Essick3938dc62016-11-01 08:56:56 -070069MediaAnalyticsItem::SessionID_t MediaAnalyticsService::generateUniqueSessionID() {
Andy Hung17dbaf22019-10-11 14:06:31 -070070 return ++mLastSessionID;
Ray Essick3938dc62016-11-01 08:56:56 -070071}
72
Andy Hung17dbaf22019-10-11 14:06:31 -070073// TODO: consider removing forcenew.
74MediaAnalyticsItem::SessionID_t MediaAnalyticsService::submit(
75 MediaAnalyticsItem *item, bool forcenew __unused)
Ray Essick92d23b42018-01-29 12:10:30 -080076{
Ray Essick92d23b42018-01-29 12:10:30 -080077 // fill in a sessionID if we do not yet have one
78 if (item->getSessionID() <= MediaAnalyticsItem::SessionIDNone) {
79 item->setSessionID(generateUniqueSessionID());
80 }
Ray Essick3938dc62016-11-01 08:56:56 -070081
Ray Essickd38e1742017-01-23 15:17:06 -080082 // we control these, generally not trusting user input
Ray Essick3938dc62016-11-01 08:56:56 -070083 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Ray Essick721b7a02017-09-11 09:33:56 -070084 // round nsecs to seconds
Andy Hung17dbaf22019-10-11 14:06:31 -070085 now = (now + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
86 // TODO: if we convert to boot time, do we need to round timestamp?
Ray Essick3938dc62016-11-01 08:56:56 -070087 item->setTimestamp(now);
Ray Essickd38e1742017-01-23 15:17:06 -080088
Andy Hung17dbaf22019-10-11 14:06:31 -070089 const int pid = IPCThreadState::self()->getCallingPid();
90 const int uid = IPCThreadState::self()->getCallingUid();
91 const int uid_given = item->getUid();
92 const int pid_given = item->getPid();
Ray Essickd38e1742017-01-23 15:17:06 -080093
Andy Hung17dbaf22019-10-11 14:06:31 -070094 ALOGV("%s: caller has uid=%d, embedded uid=%d", __func__, uid, uid_given);
95 bool isTrusted;
96 switch (uid) {
97 case AID_DRM:
98 case AID_MEDIA:
99 case AID_MEDIA_CODEC:
100 case AID_MEDIA_EX:
101 case AID_MEDIA_DRM:
102 // trusted source, only override default values
103 isTrusted = true;
104 if (uid_given == -1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800105 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700106 }
107 if (pid_given == -1) {
108 item->setPid(pid);
109 }
110 break;
111 default:
112 isTrusted = false;
113 item->setPid(pid);
114 item->setUid(uid);
115 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800116 }
117
Adam Stone21c72122017-09-05 19:02:06 -0700118 // Overwrite package name and version if the caller was untrusted.
119 if (!isTrusted) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700120 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Adam Stone21c72122017-09-05 19:02:06 -0700121 } else if (item->getPkgName().empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700122 // empty, so fill out both parts
123 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Ray Essickfa149562017-09-19 09:27:31 -0700124 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700125 // trusted, provided a package, do nothing
Adam Stone21c72122017-09-05 19:02:06 -0700126 }
127
Andy Hung17dbaf22019-10-11 14:06:31 -0700128 ALOGV("%s: given uid %d; sanitized uid: %d sanitized pkg: %s "
129 "sanitized pkg version: %lld",
130 __func__,
Adam Stone21c72122017-09-05 19:02:06 -0700131 uid_given, item->getUid(),
132 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700133 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700134
135 mItemsSubmitted++;
136
137 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700138 if (isContentValid(item, isTrusted) == false) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800139 delete item;
Ray Essick3938dc62016-11-01 08:56:56 -0700140 return MediaAnalyticsItem::SessionIDInvalid;
141 }
142
Ray Essick92d23b42018-01-29 12:10:30 -0800143 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700144 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700145
Ray Essick92d23b42018-01-29 12:10:30 -0800146 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700147 ALOGV("%s: dropping empty record...", __func__);
Ray Essick92d23b42018-01-29 12:10:30 -0800148 delete item;
Ray Essick92d23b42018-01-29 12:10:30 -0800149 return MediaAnalyticsItem::SessionIDInvalid;
Ray Essick3938dc62016-11-01 08:56:56 -0700150 }
Ray Essick92d23b42018-01-29 12:10:30 -0800151
Andy Hung17dbaf22019-10-11 14:06:31 -0700152 // send to statsd
153 extern bool dump2Statsd(MediaAnalyticsItem *item); // extern hook
154 (void)dump2Statsd(item); // failure should be logged in function.
Ray Essick6ce27e52019-02-15 10:58:05 -0800155
Andy Hung17dbaf22019-10-11 14:06:31 -0700156 // keep our copy
157 const MediaAnalyticsItem::SessionID_t id = item->getSessionID();
Ray Essick92d23b42018-01-29 12:10:30 -0800158 saveItem(item);
Ray Essick3938dc62016-11-01 08:56:56 -0700159 return id;
160}
161
Ray Essickb5fac8e2016-12-12 11:33:56 -0800162status_t MediaAnalyticsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700163{
Ray Essick3938dc62016-11-01 08:56:56 -0700164 String8 result;
165
166 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700167 result.appendFormat("Permission Denial: "
Ray Essick3938dc62016-11-01 08:56:56 -0700168 "can't dump MediaAnalyticsService from pid=%d, uid=%d\n",
169 IPCThreadState::self()->getCallingPid(),
170 IPCThreadState::self()->getCallingUid());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800171 write(fd, result.string(), result.size());
172 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700173 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800174
175 // crack any parameters
Andy Hung17dbaf22019-10-11 14:06:31 -0700176 const String16 protoOption("-proto");
Ray Essick583a23a2017-11-27 12:49:57 -0800177 int chosenProto = mDumpProtoDefault;
Andy Hung17dbaf22019-10-11 14:06:31 -0700178 const String16 clearOption("-clear");
Ray Essickf65f4212017-08-31 11:41:19 -0700179 bool clear = false;
Andy Hung17dbaf22019-10-11 14:06:31 -0700180 const String16 sinceOption("-since");
Ray Essickf65f4212017-08-31 11:41:19 -0700181 nsecs_t ts_since = 0;
Andy Hung17dbaf22019-10-11 14:06:31 -0700182 const String16 helpOption("-help");
183 const String16 onlyOption("-only");
Ray Essick783bd0d2018-01-11 11:10:35 -0800184 std::string only;
Andy Hung17dbaf22019-10-11 14:06:31 -0700185 const int n = args.size();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800186 for (int i = 0; i < n; i++) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800187 if (args[i] == clearOption) {
188 clear = true;
Ray Essickf65f4212017-08-31 11:41:19 -0700189 } else if (args[i] == protoOption) {
190 i++;
191 if (i < n) {
192 String8 value(args[i]);
Ray Essick583a23a2017-11-27 12:49:57 -0800193 int proto = MediaAnalyticsItem::PROTO_V0;
Ray Essickf65f4212017-08-31 11:41:19 -0700194 char *endp;
195 const char *p = value.string();
196 proto = strtol(p, &endp, 10);
197 if (endp != p || *endp == '\0') {
198 if (proto < MediaAnalyticsItem::PROTO_FIRST) {
199 proto = MediaAnalyticsItem::PROTO_FIRST;
200 } else if (proto > MediaAnalyticsItem::PROTO_LAST) {
201 proto = MediaAnalyticsItem::PROTO_LAST;
202 }
Ray Essick583a23a2017-11-27 12:49:57 -0800203 chosenProto = proto;
204 } else {
205 result.append("unable to parse value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700206 }
Ray Essick583a23a2017-11-27 12:49:57 -0800207 } else {
208 result.append("missing value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700209 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800210 } else if (args[i] == sinceOption) {
211 i++;
212 if (i < n) {
213 String8 value(args[i]);
214 char *endp;
215 const char *p = value.string();
216 ts_since = strtoll(p, &endp, 10);
217 if (endp == p || *endp != '\0') {
218 ts_since = 0;
219 }
220 } else {
221 ts_since = 0;
222 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800223 // command line is milliseconds; internal units are nano-seconds
Andy Hung17dbaf22019-10-11 14:06:31 -0700224 ts_since *= NANOS_PER_MILLISECOND;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700225 } else if (args[i] == onlyOption) {
226 i++;
227 if (i < n) {
228 String8 value(args[i]);
Ray Essickf65f4212017-08-31 11:41:19 -0700229 only = value.string();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700230 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800231 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700232 // TODO: consider function area dumping.
233 // dumpsys media.metrics audiotrack,codec
234 // or dumpsys media.metrics audiotrack codec
235
Ray Essick35ad27f2017-01-30 14:04:11 -0800236 result.append("Recognized parameters:\n");
237 result.append("-help this help message\n");
Ray Essick583a23a2017-11-27 12:49:57 -0800238 result.append("-proto # dump using protocol #");
Ray Essick35ad27f2017-01-30 14:04:11 -0800239 result.append("-clear clears out saved records\n");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700240 result.append("-only X process records for component X\n");
241 result.append("-since X include records since X\n");
242 result.append(" (X is milliseconds since the UNIX epoch)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800243 write(fd, result.string(), result.size());
244 return NO_ERROR;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800245 }
246 }
247
Andy Hung17dbaf22019-10-11 14:06:31 -0700248 {
249 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800250
Andy Hung17dbaf22019-10-11 14:06:31 -0700251 result.appendFormat("Dump of the %s process:\n", kServiceName);
252 dumpHeaders_l(result, chosenProto, ts_since);
253 dumpRecent_l(result, chosenProto, ts_since, only.c_str());
Ray Essick583a23a2017-11-27 12:49:57 -0800254
Andy Hung17dbaf22019-10-11 14:06:31 -0700255 if (clear) {
256 mItemsDiscarded += mItems.size();
257 mItems.clear();
258 // shall we clear the summary data too?
Ray Essick2e9c63b2017-03-29 15:16:44 -0700259 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700260 }
261
262 write(fd, result.string(), result.size());
263 return NO_ERROR;
264}
265
266// dump headers
Andy Hung17dbaf22019-10-11 14:06:31 -0700267void MediaAnalyticsService::dumpHeaders_l(String8 &result, int dumpProto, nsecs_t ts_since)
Ray Essick92d23b42018-01-29 12:10:30 -0800268{
Andy Hung17dbaf22019-10-11 14:06:31 -0700269 result.appendFormat("Protocol Version: %d\n", dumpProto);
270 if (MediaAnalyticsItem::isEnabled()) {
271 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800272 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700273 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800274 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700275 result.appendFormat(
276 "Since Boot: Submissions: %lld Accepted: %lld\n",
277 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
278 result.appendFormat(
279 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
280 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
281 (long long)mItemsDiscardedExpire);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800282 if (ts_since != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700283 result.appendFormat(
284 "Emitting Queue entries more recent than: %lld\n",
285 (long long)ts_since);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800286 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700287}
288
Andy Hung17dbaf22019-10-11 14:06:31 -0700289void MediaAnalyticsService::dumpRecent_l(
290 String8 &result, int dumpProto, nsecs_t ts_since, const char * only)
Ray Essick92d23b42018-01-29 12:10:30 -0800291{
Andy Hung17dbaf22019-10-11 14:06:31 -0700292 if (only != nullptr && *only == '\0') {
293 only = nullptr;
Ray Essickf65f4212017-08-31 11:41:19 -0700294 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700295 result.append("\nFinalized Metrics (oldest first):\n");
296 dumpQueue_l(result, dumpProto, ts_since, only);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800297
298 // show who is connected and injecting records?
299 // talk about # records fed to the 'readers'
300 // talk about # records we discarded, perhaps "discarded w/o reading" too
Ray Essick3938dc62016-11-01 08:56:56 -0700301}
Ray Essick92d23b42018-01-29 12:10:30 -0800302
Andy Hung17dbaf22019-10-11 14:06:31 -0700303void MediaAnalyticsService::dumpQueue_l(String8 &result, int dumpProto) {
304 dumpQueue_l(result, dumpProto, (nsecs_t) 0, nullptr /* only */);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800305}
306
Andy Hung17dbaf22019-10-11 14:06:31 -0700307void MediaAnalyticsService::dumpQueue_l(
308 String8 &result, int dumpProto, nsecs_t ts_since, const char * only) {
Ray Essick3938dc62016-11-01 08:56:56 -0700309 int slot = 0;
310
Ray Essick92d23b42018-01-29 12:10:30 -0800311 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700312 result.append("empty\n");
Ray Essick3938dc62016-11-01 08:56:56 -0700313 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700314 for (const auto &item : mItems) {
315 nsecs_t when = item->getTimestamp();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800316 if (when < ts_since) {
317 continue;
318 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700319 // TODO: Only should be a set<string>
320 if (only != nullptr &&
321 item->getKey() /* std::string */ != only) {
322 ALOGV("%s: omit '%s', it's not '%s'",
323 __func__, item->getKey().c_str(), only);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700324 continue;
325 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700326 result.appendFormat("%5d: %s\n",
327 slot, item->toString(dumpProto).c_str());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800328 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700329 }
330 }
Ray Essick3938dc62016-11-01 08:56:56 -0700331}
332
333//
334// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700335
Ray Essick72a436b2018-06-14 15:08:13 -0700336// if item != NULL, it's the item we just inserted
337// true == more items eligible to be recovered
338bool MediaAnalyticsService::expirations_l(MediaAnalyticsItem *item)
Ray Essick92d23b42018-01-29 12:10:30 -0800339{
Ray Essick72a436b2018-06-14 15:08:13 -0700340 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800341
Andy Hung17dbaf22019-10-11 14:06:31 -0700342 // check queue size
343 size_t overlimit = 0;
344 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
345 overlimit = mItems.size() - mMaxRecords;
346 if (overlimit > mMaxRecordsExpiredAtOnce) {
347 more = true;
348 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700349 }
350 }
351
Andy Hung17dbaf22019-10-11 14:06:31 -0700352 // check queue times
353 size_t expired = 0;
354 if (!more && mMaxRecordAgeNs > 0) {
355 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
356 // we check one at a time, skip search would be more efficient.
357 size_t i = overlimit;
358 for (; i < mItems.size(); ++i) {
359 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700360 nsecs_t when = oitem->getTimestamp();
Andy Hung17dbaf22019-10-11 14:06:31 -0700361 if (oitem.get() == item) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800362 break;
363 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700364 if (now > when && (now - when) <= mMaxRecordAgeNs) {
365 break; // TODO: if we use BOOTTIME, should be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700366 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700367 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700368 // this represents "one too many"; tell caller there are
369 // more to be reclaimed.
370 more = true;
371 break;
372 }
Ray Essick3938dc62016-11-01 08:56:56 -0700373 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700374 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700375 }
Ray Essick72a436b2018-06-14 15:08:13 -0700376
Andy Hung17dbaf22019-10-11 14:06:31 -0700377 if (const size_t toErase = overlimit + expired;
378 toErase > 0) {
379 mItemsDiscardedCount += overlimit;
380 mItemsDiscardedExpire += expired;
381 mItemsDiscarded += toErase;
382 mItems.erase(mItems.begin(), mItems.begin() + toErase); // erase from front
383 }
Ray Essick72a436b2018-06-14 15:08:13 -0700384 return more;
385}
386
Andy Hung17dbaf22019-10-11 14:06:31 -0700387void MediaAnalyticsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700388{
389 bool more;
390 do {
391 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700392 std::lock_guard _l(mLock);
393 more = expirations_l(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700394 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700395}
396
Andy Hung17dbaf22019-10-11 14:06:31 -0700397void MediaAnalyticsService::saveItem(MediaAnalyticsItem *item)
Ray Essick72a436b2018-06-14 15:08:13 -0700398{
Andy Hung17dbaf22019-10-11 14:06:31 -0700399 std::lock_guard _l(mLock);
400 // we assume the items are roughly in time order.
401 mItems.emplace_back(item);
402 ++mItemsFinalized;
403 if (expirations_l(item)
404 && (!mExpireFuture.valid()
405 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
406 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700407 }
Ray Essick3938dc62016-11-01 08:56:56 -0700408}
409
Andy Hung17dbaf22019-10-11 14:06:31 -0700410/* static */
411bool MediaAnalyticsService::isContentValid(const MediaAnalyticsItem *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800412{
Andy Hung17dbaf22019-10-11 14:06:31 -0700413 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800414 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700415 const std::string &key = item->getKey();
416 for (const char *allowedKey : {
417 "audiopolicy",
418 "audiorecord",
419 "audiothread",
420 "audiotrack",
421 "codec",
422 "extractor",
423 "nuplayer",
424 }) {
425 if (key == allowedKey) {
426 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800427 }
428 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700429 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700430 return false;
431}
432
Andy Hung17dbaf22019-10-11 14:06:31 -0700433// are we rate limited, normally false
434bool MediaAnalyticsService::isRateLimited(MediaAnalyticsItem *) const
435{
436 return false;
437}
438
439// How long we hold package info before we re-fetch it
440constexpr nsecs_t PKG_EXPIRATION_NS = 30 * 60 * NANOS_PER_SECOND; // 30 minutes
Ray Essickf65f4212017-08-31 11:41:19 -0700441
442// give me the package name, perhaps going to find it
Ray Essick92d23b42018-01-29 12:10:30 -0800443// manages its own mutex operations internally
Andy Hung17dbaf22019-10-11 14:06:31 -0700444void MediaAnalyticsService::UidInfo::setPkgInfo(
445 MediaAnalyticsItem *item, uid_t uid, bool setName, bool setVersion)
Ray Essick92d23b42018-01-29 12:10:30 -0800446{
Andy Hung17dbaf22019-10-11 14:06:31 -0700447 ALOGV("%s: uid=%d", __func__, uid);
Ray Essickfa149562017-09-19 09:27:31 -0700448
449 if (!setName && !setVersion) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700450 return; // setting nothing? strange
Ray Essickfa149562017-09-19 09:27:31 -0700451 }
452
Andy Hung17dbaf22019-10-11 14:06:31 -0700453 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
454 struct UidToPkgInfo mapping;
Ray Essick92d23b42018-01-29 12:10:30 -0800455 {
Andy Hung17dbaf22019-10-11 14:06:31 -0700456 std::lock_guard _l(mUidInfoLock);
457 auto it = mPkgMappings.find(uid);
458 if (it != mPkgMappings.end()) {
459 mapping = it->second;
460 ALOGV("%s: uid %d expiration %lld now %lld",
461 __func__, uid, (long long)mapping.expiration, (long long)now);
Ray Essick92d23b42018-01-29 12:10:30 -0800462 if (mapping.expiration <= now) {
463 // purge the stale entry and fall into re-fetching
Andy Hung17dbaf22019-10-11 14:06:31 -0700464 ALOGV("%s: entry for uid %d expired, now %lld",
465 __func__, uid, (long long)now);
466 mPkgMappings.erase(it);
467 mapping.uid = (uid_t)-1; // this is always fully overwritten
Ray Essick92d23b42018-01-29 12:10:30 -0800468 }
Ray Essickf65f4212017-08-31 11:41:19 -0700469 }
Ray Essick92d23b42018-01-29 12:10:30 -0800470 }
471
472 // if we did not find it
473 if (mapping.uid == (uid_t)(-1)) {
Ray Essick783bd0d2018-01-11 11:10:35 -0800474 std::string pkg;
Andy Hung17dbaf22019-10-11 14:06:31 -0700475 std::string installer;
Dianne Hackborn4e2eeff2017-11-27 14:01:29 -0800476 int64_t versionCode = 0;
Ray Essickf65f4212017-08-31 11:41:19 -0700477
Andy Hung17dbaf22019-10-11 14:06:31 -0700478 const struct passwd *pw = getpwuid(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700479 if (pw) {
480 pkg = pw->pw_name;
481 }
Ray Essickf65f4212017-08-31 11:41:19 -0700482
Ray Essickfa149562017-09-19 09:27:31 -0700483 sp<IServiceManager> sm = defaultServiceManager();
Andy Hung17dbaf22019-10-11 14:06:31 -0700484 sp<content::pm::IPackageManagerNative> package_mgr;
485 if (sm.get() == nullptr) {
486 ALOGE("%s: Cannot find service manager", __func__);
Ray Essickf65f4212017-08-31 11:41:19 -0700487 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700488 sp<IBinder> binder = sm->getService(String16("package_native"));
489 if (binder.get() == nullptr) {
490 ALOGE("%s: Cannot find package_native", __func__);
491 } else {
492 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
Ray Essickfa149562017-09-19 09:27:31 -0700493 }
494 }
495
Andy Hung17dbaf22019-10-11 14:06:31 -0700496 if (package_mgr != nullptr) {
Ray Essickfa149562017-09-19 09:27:31 -0700497 std::vector<int> uids;
498 std::vector<std::string> names;
Ray Essickfa149562017-09-19 09:27:31 -0700499 uids.push_back(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700500 binder::Status status = package_mgr->getNamesForUids(uids, &names);
Ray Essickfa149562017-09-19 09:27:31 -0700501 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700502 ALOGE("%s: getNamesForUids failed: %s",
503 __func__, status.exceptionMessage().c_str());
504 }
505 if (!names[0].empty()) {
506 pkg = names[0].c_str();
507 }
508 }
509
510 // strip any leading "shared:" strings that came back
511 if (pkg.compare(0, 7, "shared:") == 0) {
512 pkg.erase(0, 7);
513 }
514 // determine how pkg was installed and the versionCode
515 if (pkg.empty()) {
516 pkg = std::to_string(uid); // no name for us to manage
517 } else if (strchr(pkg.c_str(), '.') == NULL) {
518 // not of form 'com.whatever...'; assume internal and ok
519 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
520 // android.* packages are assumed fine
521 } else if (package_mgr.get() != nullptr) {
522 String16 pkgName16(pkg.c_str());
523 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
524 if (!status.isOk()) {
525 ALOGE("%s: getInstallerForPackage failed: %s",
526 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700527 }
528
Andy Hung17dbaf22019-10-11 14:06:31 -0700529 // skip if we didn't get an installer
530 if (status.isOk()) {
531 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
Ray Essickfa149562017-09-19 09:27:31 -0700532 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700533 ALOGE("%s: getVersionCodeForPackage failed: %s",
534 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700535 }
536 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700537
538 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
539 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
540
541 if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
542 // from play store, we keep info
543 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
544 // some google source, we keep info
545 } else if (strcmp(installer.c_str(), "preload") == 0) {
546 // preloads, we keep the info
547 } else if (installer.c_str()[0] == '\0') {
548 // sideload (no installer); report UID only
549 pkg = std::to_string(uid);
550 versionCode = 0;
551 } else {
552 // unknown installer; report UID only
553 pkg = std::to_string(uid);
554 versionCode = 0;
555 }
556 } else {
557 // unvalidated by package_mgr just send uid.
558 pkg = std::to_string(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700559 }
560
561 // add it to the map, to save a subsequent lookup
Andy Hung17dbaf22019-10-11 14:06:31 -0700562 std::lock_guard _l(mUidInfoLock);
563 // always overwrite
564 mapping.uid = uid;
565 mapping.pkg = std::move(pkg);
566 mapping.installer = std::move(installer);
567 mapping.versionCode = versionCode;
568 mapping.expiration = now + PKG_EXPIRATION_NS;
569 ALOGV("%s: adding uid %d pkg '%s' expiration: %lld",
Greg Kaiser6c36c782019-10-18 06:27:56 -0700570 __func__, uid, mapping.pkg.c_str(), (long long)mapping.expiration);
Andy Hung17dbaf22019-10-11 14:06:31 -0700571 mPkgMappings[uid] = mapping;
Ray Essickf65f4212017-08-31 11:41:19 -0700572 }
573
Ray Essickfa149562017-09-19 09:27:31 -0700574 if (mapping.uid != (uid_t)(-1)) {
575 if (setName) {
576 item->setPkgName(mapping.pkg);
577 }
578 if (setVersion) {
579 item->setPkgVersionCode(mapping.versionCode);
Ray Essickf65f4212017-08-31 11:41:19 -0700580 }
581 }
Ray Essickf65f4212017-08-31 11:41:19 -0700582}
583
Ray Essick3938dc62016-11-01 08:56:56 -0700584} // namespace android