blob: 1ed8b74416b4cc18ef80bf707a0eb1e51ee61653 [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
Andy Hunga87e69c2019-10-18 10:07:40 -070069status_t MediaAnalyticsService::submitInternal(MediaAnalyticsItem *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -080070{
Ray Essickd38e1742017-01-23 15:17:06 -080071 // we control these, generally not trusting user input
Ray Essick3938dc62016-11-01 08:56:56 -070072 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Ray Essick721b7a02017-09-11 09:33:56 -070073 // round nsecs to seconds
Andy Hung17dbaf22019-10-11 14:06:31 -070074 now = (now + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
75 // TODO: if we convert to boot time, do we need to round timestamp?
Ray Essick3938dc62016-11-01 08:56:56 -070076 item->setTimestamp(now);
Ray Essickd38e1742017-01-23 15:17:06 -080077
Andy Hung17dbaf22019-10-11 14:06:31 -070078 const int pid = IPCThreadState::self()->getCallingPid();
79 const int uid = IPCThreadState::self()->getCallingUid();
80 const int uid_given = item->getUid();
81 const int pid_given = item->getPid();
Ray Essickd38e1742017-01-23 15:17:06 -080082
Andy Hung17dbaf22019-10-11 14:06:31 -070083 ALOGV("%s: caller has uid=%d, embedded uid=%d", __func__, uid, uid_given);
84 bool isTrusted;
85 switch (uid) {
86 case AID_DRM:
87 case AID_MEDIA:
88 case AID_MEDIA_CODEC:
89 case AID_MEDIA_EX:
90 case AID_MEDIA_DRM:
91 // trusted source, only override default values
92 isTrusted = true;
93 if (uid_given == -1) {
Ray Essickd38e1742017-01-23 15:17:06 -080094 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -070095 }
96 if (pid_given == -1) {
97 item->setPid(pid);
98 }
99 break;
100 default:
101 isTrusted = false;
102 item->setPid(pid);
103 item->setUid(uid);
104 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800105 }
106
Adam Stone21c72122017-09-05 19:02:06 -0700107 // Overwrite package name and version if the caller was untrusted.
108 if (!isTrusted) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700109 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Adam Stone21c72122017-09-05 19:02:06 -0700110 } else if (item->getPkgName().empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700111 // empty, so fill out both parts
112 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Ray Essickfa149562017-09-19 09:27:31 -0700113 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700114 // trusted, provided a package, do nothing
Adam Stone21c72122017-09-05 19:02:06 -0700115 }
116
Andy Hung17dbaf22019-10-11 14:06:31 -0700117 ALOGV("%s: given uid %d; sanitized uid: %d sanitized pkg: %s "
118 "sanitized pkg version: %lld",
119 __func__,
Adam Stone21c72122017-09-05 19:02:06 -0700120 uid_given, item->getUid(),
121 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700122 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700123
124 mItemsSubmitted++;
125
126 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700127 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700128 if (release) delete item;
129 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700130 }
131
Ray Essick92d23b42018-01-29 12:10:30 -0800132 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700133 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700134
Ray Essick92d23b42018-01-29 12:10:30 -0800135 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700136 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700137 if (release) delete item;
138 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700139 }
Ray Essick92d23b42018-01-29 12:10:30 -0800140
Andy Hung17dbaf22019-10-11 14:06:31 -0700141 // send to statsd
142 extern bool dump2Statsd(MediaAnalyticsItem *item); // extern hook
143 (void)dump2Statsd(item); // failure should be logged in function.
Ray Essick6ce27e52019-02-15 10:58:05 -0800144
Andy Hunga87e69c2019-10-18 10:07:40 -0700145 if (!release) item = item->dup();
Ray Essick92d23b42018-01-29 12:10:30 -0800146 saveItem(item);
Andy Hunga87e69c2019-10-18 10:07:40 -0700147 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700148}
149
Ray Essickb5fac8e2016-12-12 11:33:56 -0800150status_t MediaAnalyticsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700151{
Ray Essick3938dc62016-11-01 08:56:56 -0700152 String8 result;
153
154 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700155 result.appendFormat("Permission Denial: "
Ray Essick3938dc62016-11-01 08:56:56 -0700156 "can't dump MediaAnalyticsService from pid=%d, uid=%d\n",
157 IPCThreadState::self()->getCallingPid(),
158 IPCThreadState::self()->getCallingUid());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800159 write(fd, result.string(), result.size());
160 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700161 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800162
163 // crack any parameters
Andy Hung17dbaf22019-10-11 14:06:31 -0700164 const String16 protoOption("-proto");
Ray Essick583a23a2017-11-27 12:49:57 -0800165 int chosenProto = mDumpProtoDefault;
Andy Hung17dbaf22019-10-11 14:06:31 -0700166 const String16 clearOption("-clear");
Ray Essickf65f4212017-08-31 11:41:19 -0700167 bool clear = false;
Andy Hung17dbaf22019-10-11 14:06:31 -0700168 const String16 sinceOption("-since");
Ray Essickf65f4212017-08-31 11:41:19 -0700169 nsecs_t ts_since = 0;
Andy Hung17dbaf22019-10-11 14:06:31 -0700170 const String16 helpOption("-help");
171 const String16 onlyOption("-only");
Ray Essick783bd0d2018-01-11 11:10:35 -0800172 std::string only;
Andy Hung17dbaf22019-10-11 14:06:31 -0700173 const int n = args.size();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800174 for (int i = 0; i < n; i++) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800175 if (args[i] == clearOption) {
176 clear = true;
Ray Essickf65f4212017-08-31 11:41:19 -0700177 } else if (args[i] == protoOption) {
178 i++;
179 if (i < n) {
180 String8 value(args[i]);
Ray Essick583a23a2017-11-27 12:49:57 -0800181 int proto = MediaAnalyticsItem::PROTO_V0;
Ray Essickf65f4212017-08-31 11:41:19 -0700182 char *endp;
183 const char *p = value.string();
184 proto = strtol(p, &endp, 10);
185 if (endp != p || *endp == '\0') {
186 if (proto < MediaAnalyticsItem::PROTO_FIRST) {
187 proto = MediaAnalyticsItem::PROTO_FIRST;
188 } else if (proto > MediaAnalyticsItem::PROTO_LAST) {
189 proto = MediaAnalyticsItem::PROTO_LAST;
190 }
Ray Essick583a23a2017-11-27 12:49:57 -0800191 chosenProto = proto;
192 } else {
193 result.append("unable to parse value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700194 }
Ray Essick583a23a2017-11-27 12:49:57 -0800195 } else {
196 result.append("missing value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700197 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800198 } else if (args[i] == sinceOption) {
199 i++;
200 if (i < n) {
201 String8 value(args[i]);
202 char *endp;
203 const char *p = value.string();
204 ts_since = strtoll(p, &endp, 10);
205 if (endp == p || *endp != '\0') {
206 ts_since = 0;
207 }
208 } else {
209 ts_since = 0;
210 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800211 // command line is milliseconds; internal units are nano-seconds
Andy Hung17dbaf22019-10-11 14:06:31 -0700212 ts_since *= NANOS_PER_MILLISECOND;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700213 } else if (args[i] == onlyOption) {
214 i++;
215 if (i < n) {
216 String8 value(args[i]);
Ray Essickf65f4212017-08-31 11:41:19 -0700217 only = value.string();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700218 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800219 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700220 // TODO: consider function area dumping.
221 // dumpsys media.metrics audiotrack,codec
222 // or dumpsys media.metrics audiotrack codec
223
Ray Essick35ad27f2017-01-30 14:04:11 -0800224 result.append("Recognized parameters:\n");
225 result.append("-help this help message\n");
Ray Essick583a23a2017-11-27 12:49:57 -0800226 result.append("-proto # dump using protocol #");
Ray Essick35ad27f2017-01-30 14:04:11 -0800227 result.append("-clear clears out saved records\n");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700228 result.append("-only X process records for component X\n");
229 result.append("-since X include records since X\n");
230 result.append(" (X is milliseconds since the UNIX epoch)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800231 write(fd, result.string(), result.size());
232 return NO_ERROR;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800233 }
234 }
235
Andy Hung17dbaf22019-10-11 14:06:31 -0700236 {
237 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800238
Andy Hung17dbaf22019-10-11 14:06:31 -0700239 result.appendFormat("Dump of the %s process:\n", kServiceName);
240 dumpHeaders_l(result, chosenProto, ts_since);
241 dumpRecent_l(result, chosenProto, ts_since, only.c_str());
Ray Essick583a23a2017-11-27 12:49:57 -0800242
Andy Hung17dbaf22019-10-11 14:06:31 -0700243 if (clear) {
244 mItemsDiscarded += mItems.size();
245 mItems.clear();
246 // shall we clear the summary data too?
Ray Essick2e9c63b2017-03-29 15:16:44 -0700247 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700248 }
249
250 write(fd, result.string(), result.size());
251 return NO_ERROR;
252}
253
254// dump headers
Andy Hung17dbaf22019-10-11 14:06:31 -0700255void MediaAnalyticsService::dumpHeaders_l(String8 &result, int dumpProto, nsecs_t ts_since)
Ray Essick92d23b42018-01-29 12:10:30 -0800256{
Andy Hung17dbaf22019-10-11 14:06:31 -0700257 result.appendFormat("Protocol Version: %d\n", dumpProto);
258 if (MediaAnalyticsItem::isEnabled()) {
259 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800260 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700261 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800262 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700263 result.appendFormat(
264 "Since Boot: Submissions: %lld Accepted: %lld\n",
265 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
266 result.appendFormat(
267 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
268 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
269 (long long)mItemsDiscardedExpire);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800270 if (ts_since != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700271 result.appendFormat(
272 "Emitting Queue entries more recent than: %lld\n",
273 (long long)ts_since);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800274 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700275}
276
Andy Hung17dbaf22019-10-11 14:06:31 -0700277void MediaAnalyticsService::dumpRecent_l(
278 String8 &result, int dumpProto, nsecs_t ts_since, const char * only)
Ray Essick92d23b42018-01-29 12:10:30 -0800279{
Andy Hung17dbaf22019-10-11 14:06:31 -0700280 if (only != nullptr && *only == '\0') {
281 only = nullptr;
Ray Essickf65f4212017-08-31 11:41:19 -0700282 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700283 result.append("\nFinalized Metrics (oldest first):\n");
284 dumpQueue_l(result, dumpProto, ts_since, only);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800285
286 // show who is connected and injecting records?
287 // talk about # records fed to the 'readers'
288 // talk about # records we discarded, perhaps "discarded w/o reading" too
Ray Essick3938dc62016-11-01 08:56:56 -0700289}
Ray Essick92d23b42018-01-29 12:10:30 -0800290
Andy Hung17dbaf22019-10-11 14:06:31 -0700291void MediaAnalyticsService::dumpQueue_l(String8 &result, int dumpProto) {
292 dumpQueue_l(result, dumpProto, (nsecs_t) 0, nullptr /* only */);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800293}
294
Andy Hung17dbaf22019-10-11 14:06:31 -0700295void MediaAnalyticsService::dumpQueue_l(
296 String8 &result, int dumpProto, nsecs_t ts_since, const char * only) {
Ray Essick3938dc62016-11-01 08:56:56 -0700297 int slot = 0;
298
Ray Essick92d23b42018-01-29 12:10:30 -0800299 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700300 result.append("empty\n");
Ray Essick3938dc62016-11-01 08:56:56 -0700301 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700302 for (const auto &item : mItems) {
303 nsecs_t when = item->getTimestamp();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800304 if (when < ts_since) {
305 continue;
306 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700307 // TODO: Only should be a set<string>
308 if (only != nullptr &&
309 item->getKey() /* std::string */ != only) {
310 ALOGV("%s: omit '%s', it's not '%s'",
311 __func__, item->getKey().c_str(), only);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700312 continue;
313 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700314 result.appendFormat("%5d: %s\n",
315 slot, item->toString(dumpProto).c_str());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800316 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700317 }
318 }
Ray Essick3938dc62016-11-01 08:56:56 -0700319}
320
321//
322// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700323
Ray Essick72a436b2018-06-14 15:08:13 -0700324// if item != NULL, it's the item we just inserted
325// true == more items eligible to be recovered
326bool MediaAnalyticsService::expirations_l(MediaAnalyticsItem *item)
Ray Essick92d23b42018-01-29 12:10:30 -0800327{
Ray Essick72a436b2018-06-14 15:08:13 -0700328 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800329
Andy Hung17dbaf22019-10-11 14:06:31 -0700330 // check queue size
331 size_t overlimit = 0;
332 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
333 overlimit = mItems.size() - mMaxRecords;
334 if (overlimit > mMaxRecordsExpiredAtOnce) {
335 more = true;
336 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700337 }
338 }
339
Andy Hung17dbaf22019-10-11 14:06:31 -0700340 // check queue times
341 size_t expired = 0;
342 if (!more && mMaxRecordAgeNs > 0) {
343 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
344 // we check one at a time, skip search would be more efficient.
345 size_t i = overlimit;
346 for (; i < mItems.size(); ++i) {
347 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700348 nsecs_t when = oitem->getTimestamp();
Andy Hung17dbaf22019-10-11 14:06:31 -0700349 if (oitem.get() == item) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800350 break;
351 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700352 if (now > when && (now - when) <= mMaxRecordAgeNs) {
353 break; // TODO: if we use BOOTTIME, should be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700354 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700355 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700356 // this represents "one too many"; tell caller there are
357 // more to be reclaimed.
358 more = true;
359 break;
360 }
Ray Essick3938dc62016-11-01 08:56:56 -0700361 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700362 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700363 }
Ray Essick72a436b2018-06-14 15:08:13 -0700364
Andy Hung17dbaf22019-10-11 14:06:31 -0700365 if (const size_t toErase = overlimit + expired;
366 toErase > 0) {
367 mItemsDiscardedCount += overlimit;
368 mItemsDiscardedExpire += expired;
369 mItemsDiscarded += toErase;
370 mItems.erase(mItems.begin(), mItems.begin() + toErase); // erase from front
371 }
Ray Essick72a436b2018-06-14 15:08:13 -0700372 return more;
373}
374
Andy Hung17dbaf22019-10-11 14:06:31 -0700375void MediaAnalyticsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700376{
377 bool more;
378 do {
379 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700380 std::lock_guard _l(mLock);
381 more = expirations_l(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700382 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700383}
384
Andy Hung17dbaf22019-10-11 14:06:31 -0700385void MediaAnalyticsService::saveItem(MediaAnalyticsItem *item)
Ray Essick72a436b2018-06-14 15:08:13 -0700386{
Andy Hung17dbaf22019-10-11 14:06:31 -0700387 std::lock_guard _l(mLock);
388 // we assume the items are roughly in time order.
389 mItems.emplace_back(item);
390 ++mItemsFinalized;
391 if (expirations_l(item)
392 && (!mExpireFuture.valid()
393 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
394 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700395 }
Ray Essick3938dc62016-11-01 08:56:56 -0700396}
397
Andy Hung17dbaf22019-10-11 14:06:31 -0700398/* static */
399bool MediaAnalyticsService::isContentValid(const MediaAnalyticsItem *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800400{
Andy Hung17dbaf22019-10-11 14:06:31 -0700401 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800402 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700403 const std::string &key = item->getKey();
404 for (const char *allowedKey : {
405 "audiopolicy",
406 "audiorecord",
407 "audiothread",
408 "audiotrack",
409 "codec",
410 "extractor",
411 "nuplayer",
412 }) {
413 if (key == allowedKey) {
414 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800415 }
416 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700417 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700418 return false;
419}
420
Andy Hung17dbaf22019-10-11 14:06:31 -0700421// are we rate limited, normally false
422bool MediaAnalyticsService::isRateLimited(MediaAnalyticsItem *) const
423{
424 return false;
425}
426
427// How long we hold package info before we re-fetch it
428constexpr nsecs_t PKG_EXPIRATION_NS = 30 * 60 * NANOS_PER_SECOND; // 30 minutes
Ray Essickf65f4212017-08-31 11:41:19 -0700429
430// give me the package name, perhaps going to find it
Ray Essick92d23b42018-01-29 12:10:30 -0800431// manages its own mutex operations internally
Andy Hung17dbaf22019-10-11 14:06:31 -0700432void MediaAnalyticsService::UidInfo::setPkgInfo(
433 MediaAnalyticsItem *item, uid_t uid, bool setName, bool setVersion)
Ray Essick92d23b42018-01-29 12:10:30 -0800434{
Andy Hung17dbaf22019-10-11 14:06:31 -0700435 ALOGV("%s: uid=%d", __func__, uid);
Ray Essickfa149562017-09-19 09:27:31 -0700436
437 if (!setName && !setVersion) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700438 return; // setting nothing? strange
Ray Essickfa149562017-09-19 09:27:31 -0700439 }
440
Andy Hung17dbaf22019-10-11 14:06:31 -0700441 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
442 struct UidToPkgInfo mapping;
Ray Essick92d23b42018-01-29 12:10:30 -0800443 {
Andy Hung17dbaf22019-10-11 14:06:31 -0700444 std::lock_guard _l(mUidInfoLock);
445 auto it = mPkgMappings.find(uid);
446 if (it != mPkgMappings.end()) {
447 mapping = it->second;
448 ALOGV("%s: uid %d expiration %lld now %lld",
449 __func__, uid, (long long)mapping.expiration, (long long)now);
Ray Essick92d23b42018-01-29 12:10:30 -0800450 if (mapping.expiration <= now) {
451 // purge the stale entry and fall into re-fetching
Andy Hung17dbaf22019-10-11 14:06:31 -0700452 ALOGV("%s: entry for uid %d expired, now %lld",
453 __func__, uid, (long long)now);
454 mPkgMappings.erase(it);
455 mapping.uid = (uid_t)-1; // this is always fully overwritten
Ray Essick92d23b42018-01-29 12:10:30 -0800456 }
Ray Essickf65f4212017-08-31 11:41:19 -0700457 }
Ray Essick92d23b42018-01-29 12:10:30 -0800458 }
459
460 // if we did not find it
461 if (mapping.uid == (uid_t)(-1)) {
Ray Essick783bd0d2018-01-11 11:10:35 -0800462 std::string pkg;
Andy Hung17dbaf22019-10-11 14:06:31 -0700463 std::string installer;
Dianne Hackborn4e2eeff2017-11-27 14:01:29 -0800464 int64_t versionCode = 0;
Ray Essickf65f4212017-08-31 11:41:19 -0700465
Andy Hung17dbaf22019-10-11 14:06:31 -0700466 const struct passwd *pw = getpwuid(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700467 if (pw) {
468 pkg = pw->pw_name;
469 }
Ray Essickf65f4212017-08-31 11:41:19 -0700470
Ray Essickfa149562017-09-19 09:27:31 -0700471 sp<IServiceManager> sm = defaultServiceManager();
Andy Hung17dbaf22019-10-11 14:06:31 -0700472 sp<content::pm::IPackageManagerNative> package_mgr;
473 if (sm.get() == nullptr) {
474 ALOGE("%s: Cannot find service manager", __func__);
Ray Essickf65f4212017-08-31 11:41:19 -0700475 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700476 sp<IBinder> binder = sm->getService(String16("package_native"));
477 if (binder.get() == nullptr) {
478 ALOGE("%s: Cannot find package_native", __func__);
479 } else {
480 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
Ray Essickfa149562017-09-19 09:27:31 -0700481 }
482 }
483
Andy Hung17dbaf22019-10-11 14:06:31 -0700484 if (package_mgr != nullptr) {
Ray Essickfa149562017-09-19 09:27:31 -0700485 std::vector<int> uids;
486 std::vector<std::string> names;
Ray Essickfa149562017-09-19 09:27:31 -0700487 uids.push_back(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700488 binder::Status status = package_mgr->getNamesForUids(uids, &names);
Ray Essickfa149562017-09-19 09:27:31 -0700489 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700490 ALOGE("%s: getNamesForUids failed: %s",
491 __func__, status.exceptionMessage().c_str());
492 }
493 if (!names[0].empty()) {
494 pkg = names[0].c_str();
495 }
496 }
497
498 // strip any leading "shared:" strings that came back
499 if (pkg.compare(0, 7, "shared:") == 0) {
500 pkg.erase(0, 7);
501 }
502 // determine how pkg was installed and the versionCode
503 if (pkg.empty()) {
504 pkg = std::to_string(uid); // no name for us to manage
505 } else if (strchr(pkg.c_str(), '.') == NULL) {
506 // not of form 'com.whatever...'; assume internal and ok
507 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
508 // android.* packages are assumed fine
509 } else if (package_mgr.get() != nullptr) {
510 String16 pkgName16(pkg.c_str());
511 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
512 if (!status.isOk()) {
513 ALOGE("%s: getInstallerForPackage failed: %s",
514 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700515 }
516
Andy Hung17dbaf22019-10-11 14:06:31 -0700517 // skip if we didn't get an installer
518 if (status.isOk()) {
519 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
Ray Essickfa149562017-09-19 09:27:31 -0700520 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700521 ALOGE("%s: getVersionCodeForPackage failed: %s",
522 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700523 }
524 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700525
526 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
527 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
528
529 if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
530 // from play store, we keep info
531 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
532 // some google source, we keep info
533 } else if (strcmp(installer.c_str(), "preload") == 0) {
534 // preloads, we keep the info
535 } else if (installer.c_str()[0] == '\0') {
536 // sideload (no installer); report UID only
537 pkg = std::to_string(uid);
538 versionCode = 0;
539 } else {
540 // unknown installer; report UID only
541 pkg = std::to_string(uid);
542 versionCode = 0;
543 }
544 } else {
545 // unvalidated by package_mgr just send uid.
546 pkg = std::to_string(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700547 }
548
549 // add it to the map, to save a subsequent lookup
Andy Hung17dbaf22019-10-11 14:06:31 -0700550 std::lock_guard _l(mUidInfoLock);
551 // always overwrite
552 mapping.uid = uid;
553 mapping.pkg = std::move(pkg);
554 mapping.installer = std::move(installer);
555 mapping.versionCode = versionCode;
556 mapping.expiration = now + PKG_EXPIRATION_NS;
557 ALOGV("%s: adding uid %d pkg '%s' expiration: %lld",
Greg Kaiser6c36c782019-10-18 06:27:56 -0700558 __func__, uid, mapping.pkg.c_str(), (long long)mapping.expiration);
Andy Hung17dbaf22019-10-11 14:06:31 -0700559 mPkgMappings[uid] = mapping;
Ray Essickf65f4212017-08-31 11:41:19 -0700560 }
561
Ray Essickfa149562017-09-19 09:27:31 -0700562 if (mapping.uid != (uid_t)(-1)) {
563 if (setName) {
564 item->setPkgName(mapping.pkg);
565 }
566 if (setVersion) {
567 item->setPkgVersionCode(mapping.versionCode);
Ray Essickf65f4212017-08-31 11:41:19 -0700568 }
569 }
Ray Essickf65f4212017-08-31 11:41:19 -0700570}
571
Ray Essick3938dc62016-11-01 08:56:56 -0700572} // namespace android