blob: 4f3ac1ba8dbc13279661537072131fa446752301 [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
17// Proxy for media player implementations
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "MediaAnalyticsService"
21#include <utils/Log.h>
22
Ray Essick2e9c63b2017-03-29 15:16:44 -070023#include <stdint.h>
Ray Essick3938dc62016-11-01 08:56:56 -070024#include <inttypes.h>
25#include <sys/types.h>
26#include <sys/stat.h>
27#include <sys/time.h>
28#include <dirent.h>
Ray Essick72a436b2018-06-14 15:08:13 -070029#include <pthread.h>
Ray Essick3938dc62016-11-01 08:56:56 -070030#include <unistd.h>
31
32#include <string.h>
Ray Essickf65f4212017-08-31 11:41:19 -070033#include <pwd.h>
Ray Essick3938dc62016-11-01 08:56:56 -070034
35#include <cutils/atomic.h>
36#include <cutils/properties.h> // for property_get
37
38#include <utils/misc.h>
39
Ray Essickf65f4212017-08-31 11:41:19 -070040#include <android/content/pm/IPackageManagerNative.h>
41
Ray Essick3938dc62016-11-01 08:56:56 -070042#include <binder/IPCThreadState.h>
43#include <binder/IServiceManager.h>
44#include <binder/MemoryHeapBase.h>
45#include <binder/MemoryBase.h>
46#include <gui/Surface.h>
47#include <utils/Errors.h> // for status_t
48#include <utils/List.h>
49#include <utils/String8.h>
50#include <utils/SystemClock.h>
51#include <utils/Timers.h>
52#include <utils/Vector.h>
53
Ray Essick3938dc62016-11-01 08:56:56 -070054#include <media/IMediaHTTPService.h>
55#include <media/IRemoteDisplay.h>
56#include <media/IRemoteDisplayClient.h>
57#include <media/MediaPlayerInterface.h>
58#include <media/mediarecorder.h>
59#include <media/MediaMetadataRetrieverInterface.h>
60#include <media/Metadata.h>
61#include <media/AudioTrack.h>
62#include <media/MemoryLeakTrackUtil.h>
63#include <media/stagefright/MediaCodecList.h>
64#include <media/stagefright/MediaErrors.h>
65#include <media/stagefright/Utils.h>
66#include <media/stagefright/foundation/ADebug.h>
67#include <media/stagefright/foundation/ALooperRoster.h>
68#include <mediautils/BatteryNotifier.h>
69
70//#include <memunreachable/memunreachable.h>
71#include <system/audio.h>
72
73#include <private/android_filesystem_config.h>
74
75#include "MediaAnalyticsService.h"
76
Ray Essick3938dc62016-11-01 08:56:56 -070077namespace android {
78
Ray Essickf65f4212017-08-31 11:41:19 -070079 using namespace android::base;
80 using namespace android::content::pm;
81
Ray Essickf65f4212017-08-31 11:41:19 -070082// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070083// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070084// count: hard limit of # records
85// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070086//
87static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * (1000*1000*1000ll);
88static constexpr int kMaxRecords = 0;
89
90// max we expire in a single call, to constrain how long we hold the
91// mutex, which also constrains how long a client might wait.
92static constexpr int kMaxExpiredAtOnce = 50;
93
94// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070095
96static const char *kServiceName = "media.metrics";
97
Ray Essick3938dc62016-11-01 08:56:56 -070098void MediaAnalyticsService::instantiate() {
99 defaultServiceManager()->addService(
Ray Essick2e9c63b2017-03-29 15:16:44 -0700100 String16(kServiceName), new MediaAnalyticsService());
Ray Essick3938dc62016-11-01 08:56:56 -0700101}
102
Ray Essick3938dc62016-11-01 08:56:56 -0700103MediaAnalyticsService::MediaAnalyticsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700104 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700105 mMaxRecordAgeNs(kMaxRecordAgeNs),
Ray Essick72a436b2018-06-14 15:08:13 -0700106 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce),
Ray Essick583a23a2017-11-27 12:49:57 -0800107 mDumpProto(MediaAnalyticsItem::PROTO_V1),
108 mDumpProtoDefault(MediaAnalyticsItem::PROTO_V1) {
Ray Essick3938dc62016-11-01 08:56:56 -0700109
110 ALOGD("MediaAnalyticsService created");
Ray Essick3938dc62016-11-01 08:56:56 -0700111
112 mItemsSubmitted = 0;
113 mItemsFinalized = 0;
114 mItemsDiscarded = 0;
Ray Essickf65f4212017-08-31 11:41:19 -0700115 mItemsDiscardedExpire = 0;
116 mItemsDiscardedCount = 0;
Ray Essick3938dc62016-11-01 08:56:56 -0700117
118 mLastSessionID = 0;
119 // recover any persistency we set up
120 // etc
121}
122
123MediaAnalyticsService::~MediaAnalyticsService() {
124 ALOGD("MediaAnalyticsService destroyed");
125
Ray Essick92d23b42018-01-29 12:10:30 -0800126 while (mItems.size() > 0) {
127 MediaAnalyticsItem * oitem = *(mItems.begin());
128 mItems.erase(mItems.begin());
Ray Essickf65f4212017-08-31 11:41:19 -0700129 delete oitem;
130 mItemsDiscarded++;
131 mItemsDiscardedCount++;
132 }
Ray Essick3938dc62016-11-01 08:56:56 -0700133}
134
135
136MediaAnalyticsItem::SessionID_t MediaAnalyticsService::generateUniqueSessionID() {
137 // generate a new sessionid
138
139 Mutex::Autolock _l(mLock_ids);
140 return (++mLastSessionID);
141}
142
Ray Essickb5fac8e2016-12-12 11:33:56 -0800143// caller surrenders ownership of 'item'
Ray Essick92d23b42018-01-29 12:10:30 -0800144MediaAnalyticsItem::SessionID_t MediaAnalyticsService::submit(MediaAnalyticsItem *item, bool forcenew)
145{
146 UNUSED(forcenew);
Ray Essick3938dc62016-11-01 08:56:56 -0700147
Ray Essick92d23b42018-01-29 12:10:30 -0800148 // fill in a sessionID if we do not yet have one
149 if (item->getSessionID() <= MediaAnalyticsItem::SessionIDNone) {
150 item->setSessionID(generateUniqueSessionID());
151 }
Ray Essick3938dc62016-11-01 08:56:56 -0700152
Ray Essickd38e1742017-01-23 15:17:06 -0800153 // we control these, generally not trusting user input
Ray Essick3938dc62016-11-01 08:56:56 -0700154 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Ray Essick721b7a02017-09-11 09:33:56 -0700155 // round nsecs to seconds
156 now = ((now + 500000000) / 1000000000) * 1000000000;
Ray Essick3938dc62016-11-01 08:56:56 -0700157 item->setTimestamp(now);
158 int pid = IPCThreadState::self()->getCallingPid();
Ray Essick3938dc62016-11-01 08:56:56 -0700159 int uid = IPCThreadState::self()->getCallingUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800160
161 int uid_given = item->getUid();
162 int pid_given = item->getPid();
163
Ray Essick92d23b42018-01-29 12:10:30 -0800164 // although we do make exceptions for some trusted client uids
Ray Essickd38e1742017-01-23 15:17:06 -0800165 bool isTrusted = false;
166
Ray Essickf65f4212017-08-31 11:41:19 -0700167 ALOGV("caller has uid=%d, embedded uid=%d", uid, uid_given);
168
Ray Essickd38e1742017-01-23 15:17:06 -0800169 switch (uid) {
170 case AID_MEDIA:
171 case AID_MEDIA_CODEC:
172 case AID_MEDIA_EX:
173 case AID_MEDIA_DRM:
174 // trusted source, only override default values
Ray Essickf65f4212017-08-31 11:41:19 -0700175 isTrusted = true;
Ray Essickd38e1742017-01-23 15:17:06 -0800176 if (uid_given == (-1)) {
177 item->setUid(uid);
178 }
179 if (pid_given == (-1)) {
180 item->setPid(pid);
181 }
182 break;
183 default:
184 isTrusted = false;
185 item->setPid(pid);
186 item->setUid(uid);
187 break;
188 }
189
Adam Stone21c72122017-09-05 19:02:06 -0700190 // Overwrite package name and version if the caller was untrusted.
191 if (!isTrusted) {
Ray Essickfa149562017-09-19 09:27:31 -0700192 setPkgInfo(item, item->getUid(), true, true);
Adam Stone21c72122017-09-05 19:02:06 -0700193 } else if (item->getPkgName().empty()) {
Ray Essickfa149562017-09-19 09:27:31 -0700194 // empty, so fill out both parts
195 setPkgInfo(item, item->getUid(), true, true);
196 } else {
197 // trusted, provided a package, do nothing
Adam Stone21c72122017-09-05 19:02:06 -0700198 }
199
200 ALOGV("given uid %d; sanitized uid: %d sanitized pkg: %s "
Dianne Hackborn4e2eeff2017-11-27 14:01:29 -0800201 "sanitized pkg version: %" PRId64,
Adam Stone21c72122017-09-05 19:02:06 -0700202 uid_given, item->getUid(),
203 item->getPkgName().c_str(),
204 item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700205
206 mItemsSubmitted++;
207
208 // validate the record; we discard if we don't like it
Ray Essickd38e1742017-01-23 15:17:06 -0800209 if (contentValid(item, isTrusted) == false) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800210 delete item;
Ray Essick3938dc62016-11-01 08:56:56 -0700211 return MediaAnalyticsItem::SessionIDInvalid;
212 }
213
Ray Essick92d23b42018-01-29 12:10:30 -0800214 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700215 // sure it doesn't appear in the finalized list.
216 // XXX: this is for security / DOS prevention.
217 // may also require that we persist the unique sessionIDs
218 // across boots [instead of within a single boot]
219
Ray Essick92d23b42018-01-29 12:10:30 -0800220 if (item->count() == 0) {
221 // drop empty records
222 delete item;
223 item = NULL;
224 return MediaAnalyticsItem::SessionIDInvalid;
Ray Essick3938dc62016-11-01 08:56:56 -0700225 }
Ray Essick92d23b42018-01-29 12:10:30 -0800226
227 // save the new record
228 MediaAnalyticsItem::SessionID_t id = item->getSessionID();
229 saveItem(item);
230 mItemsFinalized++;
Ray Essick3938dc62016-11-01 08:56:56 -0700231 return id;
232}
233
Ray Essickf65f4212017-08-31 11:41:19 -0700234
Ray Essickb5fac8e2016-12-12 11:33:56 -0800235status_t MediaAnalyticsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700236{
Ray Essickb5fac8e2016-12-12 11:33:56 -0800237 const size_t SIZE = 512;
Ray Essick3938dc62016-11-01 08:56:56 -0700238 char buffer[SIZE];
239 String8 result;
240
241 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
242 snprintf(buffer, SIZE, "Permission Denial: "
243 "can't dump MediaAnalyticsService from pid=%d, uid=%d\n",
244 IPCThreadState::self()->getCallingPid(),
245 IPCThreadState::self()->getCallingUid());
246 result.append(buffer);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800247 write(fd, result.string(), result.size());
248 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700249 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800250
251 // crack any parameters
Ray Essickf65f4212017-08-31 11:41:19 -0700252 String16 protoOption("-proto");
Ray Essick583a23a2017-11-27 12:49:57 -0800253 int chosenProto = mDumpProtoDefault;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800254 String16 clearOption("-clear");
Ray Essickf65f4212017-08-31 11:41:19 -0700255 bool clear = false;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800256 String16 sinceOption("-since");
Ray Essickf65f4212017-08-31 11:41:19 -0700257 nsecs_t ts_since = 0;
Ray Essick35ad27f2017-01-30 14:04:11 -0800258 String16 helpOption("-help");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700259 String16 onlyOption("-only");
Ray Essick783bd0d2018-01-11 11:10:35 -0800260 std::string only;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800261 int n = args.size();
Ray Essickf65f4212017-08-31 11:41:19 -0700262
Ray Essickb5fac8e2016-12-12 11:33:56 -0800263 for (int i = 0; i < n; i++) {
264 String8 myarg(args[i]);
265 if (args[i] == clearOption) {
266 clear = true;
Ray Essickf65f4212017-08-31 11:41:19 -0700267 } else if (args[i] == protoOption) {
268 i++;
269 if (i < n) {
270 String8 value(args[i]);
Ray Essick583a23a2017-11-27 12:49:57 -0800271 int proto = MediaAnalyticsItem::PROTO_V0;
Ray Essickf65f4212017-08-31 11:41:19 -0700272 char *endp;
273 const char *p = value.string();
274 proto = strtol(p, &endp, 10);
275 if (endp != p || *endp == '\0') {
276 if (proto < MediaAnalyticsItem::PROTO_FIRST) {
277 proto = MediaAnalyticsItem::PROTO_FIRST;
278 } else if (proto > MediaAnalyticsItem::PROTO_LAST) {
279 proto = MediaAnalyticsItem::PROTO_LAST;
280 }
Ray Essick583a23a2017-11-27 12:49:57 -0800281 chosenProto = proto;
282 } else {
283 result.append("unable to parse value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700284 }
Ray Essick583a23a2017-11-27 12:49:57 -0800285 } else {
286 result.append("missing value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700287 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800288 } else if (args[i] == sinceOption) {
289 i++;
290 if (i < n) {
291 String8 value(args[i]);
292 char *endp;
293 const char *p = value.string();
294 ts_since = strtoll(p, &endp, 10);
295 if (endp == p || *endp != '\0') {
296 ts_since = 0;
297 }
298 } else {
299 ts_since = 0;
300 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800301 // command line is milliseconds; internal units are nano-seconds
302 ts_since *= 1000*1000;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700303 } else if (args[i] == onlyOption) {
304 i++;
305 if (i < n) {
306 String8 value(args[i]);
Ray Essickf65f4212017-08-31 11:41:19 -0700307 only = value.string();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700308 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800309 } else if (args[i] == helpOption) {
310 result.append("Recognized parameters:\n");
311 result.append("-help this help message\n");
Ray Essick583a23a2017-11-27 12:49:57 -0800312 result.append("-proto # dump using protocol #");
Ray Essick35ad27f2017-01-30 14:04:11 -0800313 result.append("-clear clears out saved records\n");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700314 result.append("-only X process records for component X\n");
315 result.append("-since X include records since X\n");
316 result.append(" (X is milliseconds since the UNIX epoch)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800317 write(fd, result.string(), result.size());
318 return NO_ERROR;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800319 }
320 }
321
322 Mutex::Autolock _l(mLock);
Ray Essick92d23b42018-01-29 12:10:30 -0800323 // mutex between insertion and dumping the contents
Ray Essickb5fac8e2016-12-12 11:33:56 -0800324
Ray Essick583a23a2017-11-27 12:49:57 -0800325 mDumpProto = chosenProto;
326
Ray Essick2e9c63b2017-03-29 15:16:44 -0700327 // we ALWAYS dump this piece
328 snprintf(buffer, SIZE, "Dump of the %s process:\n", kServiceName);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800329 result.append(buffer);
330
Ray Essick2e9c63b2017-03-29 15:16:44 -0700331 dumpHeaders(result, ts_since);
332
Ray Essick813b1b82018-01-16 15:10:06 -0800333 dumpRecent(result, ts_since, only.c_str());
Ray Essick2e9c63b2017-03-29 15:16:44 -0700334
335
336 if (clear) {
337 // remove everything from the finalized queue
Ray Essick92d23b42018-01-29 12:10:30 -0800338 while (mItems.size() > 0) {
339 MediaAnalyticsItem * oitem = *(mItems.begin());
340 mItems.erase(mItems.begin());
Ray Essick2e9c63b2017-03-29 15:16:44 -0700341 delete oitem;
342 mItemsDiscarded++;
343 }
344
345 // shall we clear the summary data too?
346
347 }
348
349 write(fd, result.string(), result.size());
350 return NO_ERROR;
351}
352
353// dump headers
Ray Essick92d23b42018-01-29 12:10:30 -0800354void MediaAnalyticsService::dumpHeaders(String8 &result, nsecs_t ts_since)
355{
Ray Essick2e9c63b2017-03-29 15:16:44 -0700356 const size_t SIZE = 512;
357 char buffer[SIZE];
358
Ray Essickf65f4212017-08-31 11:41:19 -0700359 snprintf(buffer, SIZE, "Protocol Version: %d\n", mDumpProto);
360 result.append(buffer);
361
Ray Essickb5fac8e2016-12-12 11:33:56 -0800362 int enabled = MediaAnalyticsItem::isEnabled();
363 if (enabled) {
Ray Essickd38e1742017-01-23 15:17:06 -0800364 snprintf(buffer, SIZE, "Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800365 } else {
Ray Essickd38e1742017-01-23 15:17:06 -0800366 snprintf(buffer, SIZE, "Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800367 }
368 result.append(buffer);
369
370 snprintf(buffer, SIZE,
Ray Essickf65f4212017-08-31 11:41:19 -0700371 "Since Boot: Submissions: %8" PRId64
Ray Essick92d23b42018-01-29 12:10:30 -0800372 " Accepted: %8" PRId64 "\n",
Ray Essickf65f4212017-08-31 11:41:19 -0700373 mItemsSubmitted, mItemsFinalized);
374 result.append(buffer);
375 snprintf(buffer, SIZE,
376 "Records Discarded: %8" PRId64
377 " (by Count: %" PRId64 " by Expiration: %" PRId64 ")\n",
378 mItemsDiscarded, mItemsDiscardedCount, mItemsDiscardedExpire);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800379 result.append(buffer);
380 if (ts_since != 0) {
381 snprintf(buffer, SIZE,
Ray Essick92d23b42018-01-29 12:10:30 -0800382 "Emitting Queue entries more recent than: %" PRId64 "\n",
Ray Essickb5fac8e2016-12-12 11:33:56 -0800383 (int64_t) ts_since);
384 result.append(buffer);
385 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700386}
387
Ray Essick2e9c63b2017-03-29 15:16:44 -0700388// the recent, detailed queues
Ray Essick92d23b42018-01-29 12:10:30 -0800389void MediaAnalyticsService::dumpRecent(String8 &result, nsecs_t ts_since, const char * only)
390{
Ray Essick2e9c63b2017-03-29 15:16:44 -0700391 const size_t SIZE = 512;
392 char buffer[SIZE];
Ray Essickb5fac8e2016-12-12 11:33:56 -0800393
Ray Essickf65f4212017-08-31 11:41:19 -0700394 if (only != NULL && *only == '\0') {
395 only = NULL;
396 }
397
Ray Essickb5fac8e2016-12-12 11:33:56 -0800398 // show the recently recorded records
Ray Essickd38e1742017-01-23 15:17:06 -0800399 snprintf(buffer, sizeof(buffer), "\nFinalized Metrics (oldest first):\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800400 result.append(buffer);
Ray Essick92d23b42018-01-29 12:10:30 -0800401 result.append(this->dumpQueue(ts_since, only));
Ray Essickb5fac8e2016-12-12 11:33:56 -0800402
403 // show who is connected and injecting records?
404 // talk about # records fed to the 'readers'
405 // talk about # records we discarded, perhaps "discarded w/o reading" too
Ray Essick3938dc62016-11-01 08:56:56 -0700406}
Ray Essick92d23b42018-01-29 12:10:30 -0800407
Ray Essick3938dc62016-11-01 08:56:56 -0700408// caller has locked mLock...
Ray Essick92d23b42018-01-29 12:10:30 -0800409String8 MediaAnalyticsService::dumpQueue() {
410 return dumpQueue((nsecs_t) 0, NULL);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800411}
412
Ray Essick92d23b42018-01-29 12:10:30 -0800413String8 MediaAnalyticsService::dumpQueue(nsecs_t ts_since, const char * only) {
Ray Essick3938dc62016-11-01 08:56:56 -0700414 String8 result;
415 int slot = 0;
416
Ray Essick92d23b42018-01-29 12:10:30 -0800417 if (mItems.empty()) {
Ray Essick3938dc62016-11-01 08:56:56 -0700418 result.append("empty\n");
419 } else {
Ray Essick92d23b42018-01-29 12:10:30 -0800420 List<MediaAnalyticsItem *>::iterator it = mItems.begin();
421 for (; it != mItems.end(); it++) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800422 nsecs_t when = (*it)->getTimestamp();
423 if (when < ts_since) {
424 continue;
425 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700426 if (only != NULL &&
427 strcmp(only, (*it)->getKey().c_str()) != 0) {
428 ALOGV("Omit '%s', it's not '%s'", (*it)->getKey().c_str(), only);
429 continue;
430 }
Ray Essick783bd0d2018-01-11 11:10:35 -0800431 std::string entry = (*it)->toString(mDumpProto);
Ray Essick35ad27f2017-01-30 14:04:11 -0800432 result.appendFormat("%5d: %s\n", slot, entry.c_str());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800433 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700434 }
435 }
436
437 return result;
438}
439
440//
441// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700442
Ray Essick72a436b2018-06-14 15:08:13 -0700443
444// we hold mLock when we get here
445// if item != NULL, it's the item we just inserted
446// true == more items eligible to be recovered
447bool MediaAnalyticsService::expirations_l(MediaAnalyticsItem *item)
Ray Essick92d23b42018-01-29 12:10:30 -0800448{
Ray Essick72a436b2018-06-14 15:08:13 -0700449 bool more = false;
450 int handled = 0;
Ray Essicke5db6db2017-11-10 15:54:32 -0800451
Ray Essickf65f4212017-08-31 11:41:19 -0700452 // keep removing old records the front until we're in-bounds (count)
Ray Essick72a436b2018-06-14 15:08:13 -0700453 // since we invoke this with each insertion, it should be 0/1 iterations.
Ray Essick3938dc62016-11-01 08:56:56 -0700454 if (mMaxRecords > 0) {
Ray Essick92d23b42018-01-29 12:10:30 -0800455 while (mItems.size() > (size_t) mMaxRecords) {
456 MediaAnalyticsItem * oitem = *(mItems.begin());
Ray Essicke5db6db2017-11-10 15:54:32 -0800457 if (oitem == item) {
458 break;
459 }
Ray Essick72a436b2018-06-14 15:08:13 -0700460 if (handled >= mMaxRecordsExpiredAtOnce) {
461 // unlikely in this loop
462 more = true;
463 break;
464 }
465 handled++;
Ray Essick92d23b42018-01-29 12:10:30 -0800466 mItems.erase(mItems.begin());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800467 delete oitem;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800468 mItemsDiscarded++;
Ray Essickf65f4212017-08-31 11:41:19 -0700469 mItemsDiscardedCount++;
470 }
471 }
472
Ray Essick72a436b2018-06-14 15:08:13 -0700473 // keep removing old records the front until we're in-bounds (age)
474 // limited to mMaxRecordsExpiredAtOnce items per invocation.
Ray Essickf65f4212017-08-31 11:41:19 -0700475 if (mMaxRecordAgeNs > 0) {
476 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
Ray Essick92d23b42018-01-29 12:10:30 -0800477 while (mItems.size() > 0) {
478 MediaAnalyticsItem * oitem = *(mItems.begin());
Ray Essickf65f4212017-08-31 11:41:19 -0700479 nsecs_t when = oitem->getTimestamp();
Ray Essicke5db6db2017-11-10 15:54:32 -0800480 if (oitem == item) {
481 break;
482 }
Ray Essickf65f4212017-08-31 11:41:19 -0700483 // careful about timejumps too
484 if ((now > when) && (now-when) <= mMaxRecordAgeNs) {
485 // this (and the rest) are recent enough to keep
486 break;
487 }
Ray Essick72a436b2018-06-14 15:08:13 -0700488 if (handled >= mMaxRecordsExpiredAtOnce) {
489 // this represents "one too many"; tell caller there are
490 // more to be reclaimed.
491 more = true;
492 break;
493 }
494 handled++;
Ray Essick92d23b42018-01-29 12:10:30 -0800495 mItems.erase(mItems.begin());
Ray Essickf65f4212017-08-31 11:41:19 -0700496 delete oitem;
497 mItemsDiscarded++;
498 mItemsDiscardedExpire++;
Ray Essick3938dc62016-11-01 08:56:56 -0700499 }
500 }
Ray Essick72a436b2018-06-14 15:08:13 -0700501
502 // we only indicate whether there's more to clean;
503 // caller chooses whether to schedule further cleanup.
504 return more;
505}
506
507// process expirations in bite sized chunks, allowing new insertions through
508// runs in a pthread specifically started for this (which then exits)
509bool MediaAnalyticsService::processExpirations()
510{
511 bool more;
512 do {
513 sleep(1);
514 {
515 Mutex::Autolock _l(mLock);
516 more = expirations_l(NULL);
517 if (!more) {
518 break;
519 }
520 }
521 } while (more);
522 return true; // value is for std::future thread synchronization
523}
524
525// insert appropriately into queue
526void MediaAnalyticsService::saveItem(MediaAnalyticsItem * item)
527{
528
529 Mutex::Autolock _l(mLock);
530 // mutex between insertion and dumping the contents
531
532 // we want to dump 'in FIFO order', so insert at the end
533 mItems.push_back(item);
534
535 // clean old stuff from the queue
536 bool more = expirations_l(item);
537
538 // consider scheduling some asynchronous cleaning, if not running
539 if (more) {
540 if (!mExpireFuture.valid()
541 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready) {
542
543 mExpireFuture = std::async(std::launch::async, [this]()
544 {return this->processExpirations();});
545 }
546 }
Ray Essick3938dc62016-11-01 08:56:56 -0700547}
548
Ray Essick783bd0d2018-01-11 11:10:35 -0800549static std::string allowedKeys[] =
Ray Essickd38e1742017-01-23 15:17:06 -0800550{
Ray Essick84e84a52018-05-03 18:45:07 -0700551 "audiopolicy",
Ray Essick8c22cb12018-01-24 11:00:36 -0800552 "audiorecord",
Eric Tanbc2a7732018-09-06 12:04:44 -0700553 "audiothread",
Ray Essick8c22cb12018-01-24 11:00:36 -0800554 "audiotrack",
Ray Essickd38e1742017-01-23 15:17:06 -0800555 "codec",
Ray Essick8c22cb12018-01-24 11:00:36 -0800556 "extractor",
557 "nuplayer",
Ray Essickd38e1742017-01-23 15:17:06 -0800558};
Ray Essick3938dc62016-11-01 08:56:56 -0700559
Ray Essickd38e1742017-01-23 15:17:06 -0800560static const int nAllowedKeys = sizeof(allowedKeys) / sizeof(allowedKeys[0]);
561
562// are the contents good
563bool MediaAnalyticsService::contentValid(MediaAnalyticsItem *item, bool isTrusted) {
564
565 // untrusted uids can only send us a limited set of keys
566 if (isTrusted == false) {
567 // restrict to a specific set of keys
Ray Essick783bd0d2018-01-11 11:10:35 -0800568 std::string key = item->getKey();
Ray Essickd38e1742017-01-23 15:17:06 -0800569
570 size_t i;
571 for(i = 0; i < nAllowedKeys; i++) {
572 if (key == allowedKeys[i]) {
573 break;
574 }
575 }
576 if (i == nAllowedKeys) {
577 ALOGD("Ignoring (key): %s", item->toString().c_str());
578 return false;
579 }
580 }
581
Ray Essick3938dc62016-11-01 08:56:56 -0700582 // internal consistency
583
584 return true;
585}
586
587// are we rate limited, normally false
Ray Essickb5fac8e2016-12-12 11:33:56 -0800588bool MediaAnalyticsService::rateLimited(MediaAnalyticsItem *) {
Ray Essick3938dc62016-11-01 08:56:56 -0700589
590 return false;
591}
592
Ray Essickfa149562017-09-19 09:27:31 -0700593// how long we hold package info before we re-fetch it
594#define PKG_EXPIRATION_NS (30*60*1000000000ll) // 30 minutes, in nsecs
Ray Essickf65f4212017-08-31 11:41:19 -0700595
596// give me the package name, perhaps going to find it
Ray Essick92d23b42018-01-29 12:10:30 -0800597// manages its own mutex operations internally
598void MediaAnalyticsService::setPkgInfo(MediaAnalyticsItem *item, uid_t uid, bool setName, bool setVersion)
599{
Ray Essickfa149562017-09-19 09:27:31 -0700600 ALOGV("asking for packagename to go with uid=%d", uid);
601
602 if (!setName && !setVersion) {
603 // setting nothing? strange
604 return;
605 }
606
607 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
608 struct UidToPkgMap mapping;
Ray Essick92d23b42018-01-29 12:10:30 -0800609 mapping.uid = (uid_t)(-1);
Ray Essickfa149562017-09-19 09:27:31 -0700610
Ray Essick92d23b42018-01-29 12:10:30 -0800611 {
612 Mutex::Autolock _l(mLock_mappings);
613 int i = mPkgMappings.indexOfKey(uid);
614 if (i >= 0) {
615 mapping = mPkgMappings.valueAt(i);
616 ALOGV("Expiration? uid %d expiration %" PRId64 " now %" PRId64,
617 uid, mapping.expiration, now);
618 if (mapping.expiration <= now) {
619 // purge the stale entry and fall into re-fetching
620 ALOGV("entry for uid %d expired, now= %" PRId64 "", uid, now);
621 mPkgMappings.removeItemsAt(i);
622 mapping.uid = (uid_t)(-1);
623 }
Ray Essickf65f4212017-08-31 11:41:19 -0700624 }
Ray Essick92d23b42018-01-29 12:10:30 -0800625 }
626
627 // if we did not find it
628 if (mapping.uid == (uid_t)(-1)) {
Ray Essick783bd0d2018-01-11 11:10:35 -0800629 std::string pkg;
Ray Essickfa149562017-09-19 09:27:31 -0700630 std::string installer = "";
Dianne Hackborn4e2eeff2017-11-27 14:01:29 -0800631 int64_t versionCode = 0;
Ray Essickf65f4212017-08-31 11:41:19 -0700632
Ray Essickfa149562017-09-19 09:27:31 -0700633 struct passwd *pw = getpwuid(uid);
634 if (pw) {
635 pkg = pw->pw_name;
636 }
Ray Essickf65f4212017-08-31 11:41:19 -0700637
Ray Essick92d23b42018-01-29 12:10:30 -0800638 // find the proper value
Ray Essickf65f4212017-08-31 11:41:19 -0700639
Ray Essickfa149562017-09-19 09:27:31 -0700640 sp<IBinder> binder = NULL;
641 sp<IServiceManager> sm = defaultServiceManager();
642 if (sm == NULL) {
643 ALOGE("defaultServiceManager failed");
Ray Essickf65f4212017-08-31 11:41:19 -0700644 } else {
Ray Essickfa149562017-09-19 09:27:31 -0700645 binder = sm->getService(String16("package_native"));
646 if (binder == NULL) {
647 ALOGE("getService package_native failed");
648 }
649 }
650
651 if (binder != NULL) {
652 sp<IPackageManagerNative> package_mgr = interface_cast<IPackageManagerNative>(binder);
653 binder::Status status;
654
655 std::vector<int> uids;
656 std::vector<std::string> names;
657
658 uids.push_back(uid);
659
660 status = package_mgr->getNamesForUids(uids, &names);
661 if (!status.isOk()) {
662 ALOGE("package_native::getNamesForUids failed: %s",
663 status.exceptionMessage().c_str());
664 } else {
665 if (!names[0].empty()) {
666 pkg = names[0].c_str();
667 }
668 }
669
670 // strip any leading "shared:" strings that came back
Ray Essick783bd0d2018-01-11 11:10:35 -0800671 if (pkg.compare(0, 7, "shared:") == 0) {
Ray Essickfa149562017-09-19 09:27:31 -0700672 pkg.erase(0, 7);
673 }
674
675 // determine how pkg was installed and the versionCode
676 //
677 if (pkg.empty()) {
678 // no name for us to manage
679 } else if (strchr(pkg.c_str(), '.') == NULL) {
680 // not of form 'com.whatever...'; assume internal and ok
681 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
682 // android.* packages are assumed fine
683 } else {
684 String16 pkgName16(pkg.c_str());
685 status = package_mgr->getInstallerForPackage(pkgName16, &installer);
686 if (!status.isOk()) {
687 ALOGE("package_native::getInstallerForPackage failed: %s",
688 status.exceptionMessage().c_str());
689 }
690
691 // skip if we didn't get an installer
692 if (status.isOk()) {
693 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
694 if (!status.isOk()) {
695 ALOGE("package_native::getVersionCodeForPackage failed: %s",
696 status.exceptionMessage().c_str());
697 }
698 }
699
700
Dianne Hackborn4e2eeff2017-11-27 14:01:29 -0800701 ALOGV("package '%s' installed by '%s' versioncode %" PRId64 " / %" PRIx64,
Ray Essickfa149562017-09-19 09:27:31 -0700702 pkg.c_str(), installer.c_str(), versionCode, versionCode);
703
704 if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
705 // from play store, we keep info
706 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
707 // some google source, we keep info
708 } else if (strcmp(installer.c_str(), "preload") == 0) {
709 // preloads, we keep the info
710 } else if (installer.c_str()[0] == '\0') {
711 // sideload (no installer); do not report
712 pkg = "";
713 versionCode = 0;
714 } else {
715 // unknown installer; do not report
716 pkg = "";
717 versionCode = 0;
718 }
719 }
720 }
721
722 // add it to the map, to save a subsequent lookup
723 if (!pkg.empty()) {
724 Mutex::Autolock _l(mLock_mappings);
725 ALOGV("Adding uid %d pkg '%s'", uid, pkg.c_str());
726 ssize_t i = mPkgMappings.indexOfKey(uid);
727 if (i < 0) {
728 mapping.uid = uid;
729 mapping.pkg = pkg;
730 mapping.installer = installer.c_str();
731 mapping.versionCode = versionCode;
732 mapping.expiration = now + PKG_EXPIRATION_NS;
733 ALOGV("expiration for uid %d set to %" PRId64 "", uid, mapping.expiration);
734
735 mPkgMappings.add(uid, mapping);
Ray Essickf65f4212017-08-31 11:41:19 -0700736 }
737 }
738 }
739
Ray Essickfa149562017-09-19 09:27:31 -0700740 if (mapping.uid != (uid_t)(-1)) {
741 if (setName) {
742 item->setPkgName(mapping.pkg);
743 }
744 if (setVersion) {
745 item->setPkgVersionCode(mapping.versionCode);
Ray Essickf65f4212017-08-31 11:41:19 -0700746 }
747 }
Ray Essickf65f4212017-08-31 11:41:19 -0700748}
749
Ray Essick3938dc62016-11-01 08:56:56 -0700750} // namespace android