blob: a131e1a252a65c084122bc5d50d8d315025ad3eb [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
Andy Hung17dbaf22019-10-11 14:06:31 -070025#include <android/content/pm/IPackageManagerNative.h> // package info
Andy Hung55aaf522019-12-03 15:07:51 -080026#include <audio_utils/clock.h> // clock conversions
Andy Hung17dbaf22019-10-11 14:06:31 -070027#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
Andy Hung55aaf522019-12-03 15:07:51 -080054/* static */
55nsecs_t MediaAnalyticsService::roundTime(nsecs_t timeNs)
56{
57 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
58}
59
Ray Essick3938dc62016-11-01 08:56:56 -070060MediaAnalyticsService::MediaAnalyticsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -070061 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -070062 mMaxRecordAgeNs(kMaxRecordAgeNs),
Ray Essick72a436b2018-06-14 15:08:13 -070063 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce),
Andy Hung17dbaf22019-10-11 14:06:31 -070064 mDumpProtoDefault(MediaAnalyticsItem::PROTO_V1)
65{
66 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -070067}
68
Andy Hung17dbaf22019-10-11 14:06:31 -070069MediaAnalyticsService::~MediaAnalyticsService()
70{
71 ALOGD("%s", __func__);
72 // the class destructor clears anyhow, but we enforce clearing items first.
73 mItemsDiscarded += mItems.size();
74 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -070075}
76
Andy Hunga87e69c2019-10-18 10:07:40 -070077status_t MediaAnalyticsService::submitInternal(MediaAnalyticsItem *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -080078{
Andy Hung55aaf522019-12-03 15:07:51 -080079 // calling PID is 0 for one-way calls.
80 const pid_t pid = IPCThreadState::self()->getCallingPid();
81 const pid_t pid_given = item->getPid();
82 const uid_t uid = IPCThreadState::self()->getCallingUid();
83 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -080084
Andy Hung55aaf522019-12-03 15:07:51 -080085 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
86 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -080087
Andy Hung17dbaf22019-10-11 14:06:31 -070088 bool isTrusted;
89 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -080090 case AID_AUDIOSERVER:
91 case AID_BLUETOOTH:
92 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -070093 case AID_DRM:
94 case AID_MEDIA:
95 case AID_MEDIA_CODEC:
96 case AID_MEDIA_EX:
97 case AID_MEDIA_DRM:
Andy Hung55aaf522019-12-03 15:07:51 -080098 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -070099 // trusted source, only override default values
100 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800101 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800102 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700103 }
Andy Hung55aaf522019-12-03 15:07:51 -0800104 if (pid_given == (pid_t)-1) {
105 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700106 }
107 break;
108 default:
109 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800110 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700111 item->setUid(uid);
112 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800113 }
114
Adam Stone21c72122017-09-05 19:02:06 -0700115 // Overwrite package name and version if the caller was untrusted.
116 if (!isTrusted) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700117 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Adam Stone21c72122017-09-05 19:02:06 -0700118 } else if (item->getPkgName().empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700119 // empty, so fill out both parts
120 mUidInfo.setPkgInfo(item, item->getUid(), true, true);
Ray Essickfa149562017-09-19 09:27:31 -0700121 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700122 // trusted, provided a package, do nothing
Adam Stone21c72122017-09-05 19:02:06 -0700123 }
124
Andy Hung17dbaf22019-10-11 14:06:31 -0700125 ALOGV("%s: given uid %d; sanitized uid: %d sanitized pkg: %s "
126 "sanitized pkg version: %lld",
127 __func__,
Adam Stone21c72122017-09-05 19:02:06 -0700128 uid_given, item->getUid(),
129 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700130 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700131
132 mItemsSubmitted++;
133
134 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700135 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700136 if (release) delete item;
137 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700138 }
139
Ray Essick92d23b42018-01-29 12:10:30 -0800140 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700141 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700142
Ray Essick92d23b42018-01-29 12:10:30 -0800143 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700144 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700145 if (release) delete item;
146 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700147 }
Ray Essick92d23b42018-01-29 12:10:30 -0800148
Andy Hung55aaf522019-12-03 15:07:51 -0800149 if (!isTrusted || item->getTimestamp() == 0) {
150 // WestWorld logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
151 // WallClockTimeNs (REALTIME). The new audio keys use BOOTTIME.
152 //
153 // TODO: Reevaluate time base with other teams.
154 const bool useBootTime = startsWith(item->getKey(), "audio.");
155 const int64_t now = systemTime(useBootTime ? SYSTEM_TIME_BOOTTIME : SYSTEM_TIME_REALTIME);
156 item->setTimestamp(now);
157 }
158
Andy Hung82a074b2019-12-03 14:16:45 -0800159 // now attach either the item or its dup to a const shared pointer
160 std::shared_ptr<const MediaAnalyticsItem> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800161
Andy Hung06f3aba2019-12-03 16:36:42 -0800162 (void)mAudioAnalytics.submit(sitem, isTrusted);
163
Andy Hung82a074b2019-12-03 14:16:45 -0800164 extern bool dump2Statsd(const std::shared_ptr<const MediaAnalyticsItem>& item);
165 (void)dump2Statsd(sitem); // failure should be logged in function.
166 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700167 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700168}
169
Ray Essickb5fac8e2016-12-12 11:33:56 -0800170status_t MediaAnalyticsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700171{
Ray Essick3938dc62016-11-01 08:56:56 -0700172 String8 result;
173
174 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700175 result.appendFormat("Permission Denial: "
Ray Essick3938dc62016-11-01 08:56:56 -0700176 "can't dump MediaAnalyticsService from pid=%d, uid=%d\n",
177 IPCThreadState::self()->getCallingPid(),
178 IPCThreadState::self()->getCallingUid());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800179 write(fd, result.string(), result.size());
180 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700181 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800182
183 // crack any parameters
Andy Hung17dbaf22019-10-11 14:06:31 -0700184 const String16 protoOption("-proto");
Ray Essick583a23a2017-11-27 12:49:57 -0800185 int chosenProto = mDumpProtoDefault;
Andy Hung17dbaf22019-10-11 14:06:31 -0700186 const String16 clearOption("-clear");
Ray Essickf65f4212017-08-31 11:41:19 -0700187 bool clear = false;
Andy Hung17dbaf22019-10-11 14:06:31 -0700188 const String16 sinceOption("-since");
Ray Essickf65f4212017-08-31 11:41:19 -0700189 nsecs_t ts_since = 0;
Andy Hung17dbaf22019-10-11 14:06:31 -0700190 const String16 helpOption("-help");
191 const String16 onlyOption("-only");
Ray Essick783bd0d2018-01-11 11:10:35 -0800192 std::string only;
Andy Hung17dbaf22019-10-11 14:06:31 -0700193 const int n = args.size();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800194 for (int i = 0; i < n; i++) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800195 if (args[i] == clearOption) {
196 clear = true;
Ray Essickf65f4212017-08-31 11:41:19 -0700197 } else if (args[i] == protoOption) {
198 i++;
199 if (i < n) {
200 String8 value(args[i]);
Ray Essick583a23a2017-11-27 12:49:57 -0800201 int proto = MediaAnalyticsItem::PROTO_V0;
Ray Essickf65f4212017-08-31 11:41:19 -0700202 char *endp;
203 const char *p = value.string();
204 proto = strtol(p, &endp, 10);
205 if (endp != p || *endp == '\0') {
206 if (proto < MediaAnalyticsItem::PROTO_FIRST) {
207 proto = MediaAnalyticsItem::PROTO_FIRST;
208 } else if (proto > MediaAnalyticsItem::PROTO_LAST) {
209 proto = MediaAnalyticsItem::PROTO_LAST;
210 }
Ray Essick583a23a2017-11-27 12:49:57 -0800211 chosenProto = proto;
212 } else {
213 result.append("unable to parse value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700214 }
Ray Essick583a23a2017-11-27 12:49:57 -0800215 } else {
216 result.append("missing value for -proto\n\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700217 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800218 } else if (args[i] == sinceOption) {
219 i++;
220 if (i < n) {
221 String8 value(args[i]);
222 char *endp;
223 const char *p = value.string();
224 ts_since = strtoll(p, &endp, 10);
225 if (endp == p || *endp != '\0') {
226 ts_since = 0;
227 }
228 } else {
229 ts_since = 0;
230 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800231 // command line is milliseconds; internal units are nano-seconds
Andy Hung17dbaf22019-10-11 14:06:31 -0700232 ts_since *= NANOS_PER_MILLISECOND;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700233 } else if (args[i] == onlyOption) {
234 i++;
235 if (i < n) {
236 String8 value(args[i]);
Ray Essickf65f4212017-08-31 11:41:19 -0700237 only = value.string();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700238 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800239 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700240 // TODO: consider function area dumping.
241 // dumpsys media.metrics audiotrack,codec
242 // or dumpsys media.metrics audiotrack codec
243
Ray Essick35ad27f2017-01-30 14:04:11 -0800244 result.append("Recognized parameters:\n");
245 result.append("-help this help message\n");
Ray Essick583a23a2017-11-27 12:49:57 -0800246 result.append("-proto # dump using protocol #");
Ray Essick35ad27f2017-01-30 14:04:11 -0800247 result.append("-clear clears out saved records\n");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700248 result.append("-only X process records for component X\n");
249 result.append("-since X include records since X\n");
250 result.append(" (X is milliseconds since the UNIX epoch)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800251 write(fd, result.string(), result.size());
252 return NO_ERROR;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800253 }
254 }
255
Andy Hung17dbaf22019-10-11 14:06:31 -0700256 {
257 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800258
Andy Hung17dbaf22019-10-11 14:06:31 -0700259 result.appendFormat("Dump of the %s process:\n", kServiceName);
260 dumpHeaders_l(result, chosenProto, ts_since);
261 dumpRecent_l(result, chosenProto, ts_since, only.c_str());
Ray Essick583a23a2017-11-27 12:49:57 -0800262
Andy Hung17dbaf22019-10-11 14:06:31 -0700263 if (clear) {
264 mItemsDiscarded += mItems.size();
265 mItems.clear();
266 // shall we clear the summary data too?
Ray Essick2e9c63b2017-03-29 15:16:44 -0700267 }
Andy Hung06f3aba2019-12-03 16:36:42 -0800268 // TODO: maybe consider a better way of dumping audio analytics info.
269 constexpr int32_t linesToDump = 1000;
270 result.append(mAudioAnalytics.dump(linesToDump).first.c_str());
Ray Essick2e9c63b2017-03-29 15:16:44 -0700271 }
272
273 write(fd, result.string(), result.size());
274 return NO_ERROR;
275}
276
277// dump headers
Andy Hung17dbaf22019-10-11 14:06:31 -0700278void MediaAnalyticsService::dumpHeaders_l(String8 &result, int dumpProto, nsecs_t ts_since)
Ray Essick92d23b42018-01-29 12:10:30 -0800279{
Andy Hung17dbaf22019-10-11 14:06:31 -0700280 result.appendFormat("Protocol Version: %d\n", dumpProto);
281 if (MediaAnalyticsItem::isEnabled()) {
282 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800283 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700284 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800285 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700286 result.appendFormat(
287 "Since Boot: Submissions: %lld Accepted: %lld\n",
288 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
289 result.appendFormat(
290 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
291 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
292 (long long)mItemsDiscardedExpire);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800293 if (ts_since != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700294 result.appendFormat(
295 "Emitting Queue entries more recent than: %lld\n",
296 (long long)ts_since);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800297 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700298}
299
Andy Hung17dbaf22019-10-11 14:06:31 -0700300void MediaAnalyticsService::dumpRecent_l(
301 String8 &result, int dumpProto, nsecs_t ts_since, const char * only)
Ray Essick92d23b42018-01-29 12:10:30 -0800302{
Andy Hung17dbaf22019-10-11 14:06:31 -0700303 if (only != nullptr && *only == '\0') {
304 only = nullptr;
Ray Essickf65f4212017-08-31 11:41:19 -0700305 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700306 result.append("\nFinalized Metrics (oldest first):\n");
307 dumpQueue_l(result, dumpProto, ts_since, only);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800308
309 // show who is connected and injecting records?
310 // talk about # records fed to the 'readers'
311 // talk about # records we discarded, perhaps "discarded w/o reading" too
Ray Essick3938dc62016-11-01 08:56:56 -0700312}
Ray Essick92d23b42018-01-29 12:10:30 -0800313
Andy Hung17dbaf22019-10-11 14:06:31 -0700314void MediaAnalyticsService::dumpQueue_l(String8 &result, int dumpProto) {
315 dumpQueue_l(result, dumpProto, (nsecs_t) 0, nullptr /* only */);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800316}
317
Andy Hung17dbaf22019-10-11 14:06:31 -0700318void MediaAnalyticsService::dumpQueue_l(
319 String8 &result, int dumpProto, nsecs_t ts_since, const char * only) {
Ray Essick3938dc62016-11-01 08:56:56 -0700320 int slot = 0;
321
Ray Essick92d23b42018-01-29 12:10:30 -0800322 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700323 result.append("empty\n");
Ray Essick3938dc62016-11-01 08:56:56 -0700324 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700325 for (const auto &item : mItems) {
326 nsecs_t when = item->getTimestamp();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800327 if (when < ts_since) {
328 continue;
329 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700330 // TODO: Only should be a set<string>
331 if (only != nullptr &&
332 item->getKey() /* std::string */ != only) {
333 ALOGV("%s: omit '%s', it's not '%s'",
334 __func__, item->getKey().c_str(), only);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700335 continue;
336 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700337 result.appendFormat("%5d: %s\n",
338 slot, item->toString(dumpProto).c_str());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800339 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700340 }
341 }
Ray Essick3938dc62016-11-01 08:56:56 -0700342}
343
344//
345// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700346
Ray Essick72a436b2018-06-14 15:08:13 -0700347// if item != NULL, it's the item we just inserted
348// true == more items eligible to be recovered
Andy Hung82a074b2019-12-03 14:16:45 -0800349bool MediaAnalyticsService::expirations_l(const std::shared_ptr<const MediaAnalyticsItem>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800350{
Ray Essick72a436b2018-06-14 15:08:13 -0700351 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800352
Andy Hung17dbaf22019-10-11 14:06:31 -0700353 // check queue size
354 size_t overlimit = 0;
355 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
356 overlimit = mItems.size() - mMaxRecords;
357 if (overlimit > mMaxRecordsExpiredAtOnce) {
358 more = true;
359 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700360 }
361 }
362
Andy Hung17dbaf22019-10-11 14:06:31 -0700363 // check queue times
364 size_t expired = 0;
365 if (!more && mMaxRecordAgeNs > 0) {
366 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
367 // we check one at a time, skip search would be more efficient.
368 size_t i = overlimit;
369 for (; i < mItems.size(); ++i) {
370 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700371 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800372 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800373 break;
374 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700375 if (now > when && (now - when) <= mMaxRecordAgeNs) {
376 break; // TODO: if we use BOOTTIME, should be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700377 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700378 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700379 // this represents "one too many"; tell caller there are
380 // more to be reclaimed.
381 more = true;
382 break;
383 }
Ray Essick3938dc62016-11-01 08:56:56 -0700384 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700385 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700386 }
Ray Essick72a436b2018-06-14 15:08:13 -0700387
Andy Hung17dbaf22019-10-11 14:06:31 -0700388 if (const size_t toErase = overlimit + expired;
389 toErase > 0) {
390 mItemsDiscardedCount += overlimit;
391 mItemsDiscardedExpire += expired;
392 mItemsDiscarded += toErase;
393 mItems.erase(mItems.begin(), mItems.begin() + toErase); // erase from front
394 }
Ray Essick72a436b2018-06-14 15:08:13 -0700395 return more;
396}
397
Andy Hung17dbaf22019-10-11 14:06:31 -0700398void MediaAnalyticsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700399{
400 bool more;
401 do {
402 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700403 std::lock_guard _l(mLock);
404 more = expirations_l(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700405 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700406}
407
Andy Hung82a074b2019-12-03 14:16:45 -0800408void MediaAnalyticsService::saveItem(const std::shared_ptr<const MediaAnalyticsItem>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700409{
Andy Hung17dbaf22019-10-11 14:06:31 -0700410 std::lock_guard _l(mLock);
411 // we assume the items are roughly in time order.
412 mItems.emplace_back(item);
413 ++mItemsFinalized;
414 if (expirations_l(item)
415 && (!mExpireFuture.valid()
416 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
417 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700418 }
Ray Essick3938dc62016-11-01 08:56:56 -0700419}
420
Andy Hung17dbaf22019-10-11 14:06:31 -0700421/* static */
422bool MediaAnalyticsService::isContentValid(const MediaAnalyticsItem *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800423{
Andy Hung17dbaf22019-10-11 14:06:31 -0700424 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800425 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700426 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800427 if (startsWith(key, "audio.")) return true;
Andy Hung17dbaf22019-10-11 14:06:31 -0700428 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800429 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700430 "audiopolicy",
431 "audiorecord",
432 "audiothread",
433 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800434 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700435 "codec",
436 "extractor",
437 "nuplayer",
438 }) {
439 if (key == allowedKey) {
440 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800441 }
442 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700443 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700444 return false;
445}
446
Andy Hung17dbaf22019-10-11 14:06:31 -0700447// are we rate limited, normally false
448bool MediaAnalyticsService::isRateLimited(MediaAnalyticsItem *) const
449{
450 return false;
451}
452
453// How long we hold package info before we re-fetch it
454constexpr nsecs_t PKG_EXPIRATION_NS = 30 * 60 * NANOS_PER_SECOND; // 30 minutes
Ray Essickf65f4212017-08-31 11:41:19 -0700455
456// give me the package name, perhaps going to find it
Ray Essick92d23b42018-01-29 12:10:30 -0800457// manages its own mutex operations internally
Andy Hung17dbaf22019-10-11 14:06:31 -0700458void MediaAnalyticsService::UidInfo::setPkgInfo(
459 MediaAnalyticsItem *item, uid_t uid, bool setName, bool setVersion)
Ray Essick92d23b42018-01-29 12:10:30 -0800460{
Andy Hung17dbaf22019-10-11 14:06:31 -0700461 ALOGV("%s: uid=%d", __func__, uid);
Ray Essickfa149562017-09-19 09:27:31 -0700462
463 if (!setName && !setVersion) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700464 return; // setting nothing? strange
Ray Essickfa149562017-09-19 09:27:31 -0700465 }
466
Andy Hung17dbaf22019-10-11 14:06:31 -0700467 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
468 struct UidToPkgInfo mapping;
Ray Essick92d23b42018-01-29 12:10:30 -0800469 {
Andy Hung17dbaf22019-10-11 14:06:31 -0700470 std::lock_guard _l(mUidInfoLock);
471 auto it = mPkgMappings.find(uid);
472 if (it != mPkgMappings.end()) {
473 mapping = it->second;
474 ALOGV("%s: uid %d expiration %lld now %lld",
475 __func__, uid, (long long)mapping.expiration, (long long)now);
Ray Essick92d23b42018-01-29 12:10:30 -0800476 if (mapping.expiration <= now) {
477 // purge the stale entry and fall into re-fetching
Andy Hung17dbaf22019-10-11 14:06:31 -0700478 ALOGV("%s: entry for uid %d expired, now %lld",
479 __func__, uid, (long long)now);
480 mPkgMappings.erase(it);
481 mapping.uid = (uid_t)-1; // this is always fully overwritten
Ray Essick92d23b42018-01-29 12:10:30 -0800482 }
Ray Essickf65f4212017-08-31 11:41:19 -0700483 }
Ray Essick92d23b42018-01-29 12:10:30 -0800484 }
485
486 // if we did not find it
487 if (mapping.uid == (uid_t)(-1)) {
Ray Essick783bd0d2018-01-11 11:10:35 -0800488 std::string pkg;
Andy Hung17dbaf22019-10-11 14:06:31 -0700489 std::string installer;
Dianne Hackborn4e2eeff2017-11-27 14:01:29 -0800490 int64_t versionCode = 0;
Ray Essickf65f4212017-08-31 11:41:19 -0700491
Andy Hung17dbaf22019-10-11 14:06:31 -0700492 const struct passwd *pw = getpwuid(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700493 if (pw) {
494 pkg = pw->pw_name;
495 }
Ray Essickf65f4212017-08-31 11:41:19 -0700496
Ray Essickfa149562017-09-19 09:27:31 -0700497 sp<IServiceManager> sm = defaultServiceManager();
Andy Hung17dbaf22019-10-11 14:06:31 -0700498 sp<content::pm::IPackageManagerNative> package_mgr;
499 if (sm.get() == nullptr) {
500 ALOGE("%s: Cannot find service manager", __func__);
Ray Essickf65f4212017-08-31 11:41:19 -0700501 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700502 sp<IBinder> binder = sm->getService(String16("package_native"));
503 if (binder.get() == nullptr) {
504 ALOGE("%s: Cannot find package_native", __func__);
505 } else {
506 package_mgr = interface_cast<content::pm::IPackageManagerNative>(binder);
Ray Essickfa149562017-09-19 09:27:31 -0700507 }
508 }
509
Andy Hung17dbaf22019-10-11 14:06:31 -0700510 if (package_mgr != nullptr) {
Ray Essickfa149562017-09-19 09:27:31 -0700511 std::vector<int> uids;
512 std::vector<std::string> names;
Ray Essickfa149562017-09-19 09:27:31 -0700513 uids.push_back(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700514 binder::Status status = package_mgr->getNamesForUids(uids, &names);
Ray Essickfa149562017-09-19 09:27:31 -0700515 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700516 ALOGE("%s: getNamesForUids failed: %s",
517 __func__, status.exceptionMessage().c_str());
Andy Hungeff0d082019-12-03 12:23:45 -0800518 } else {
519 if (!names[0].empty()) {
520 pkg = names[0].c_str();
521 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700522 }
523 }
524
525 // strip any leading "shared:" strings that came back
526 if (pkg.compare(0, 7, "shared:") == 0) {
527 pkg.erase(0, 7);
528 }
529 // determine how pkg was installed and the versionCode
530 if (pkg.empty()) {
531 pkg = std::to_string(uid); // no name for us to manage
532 } else if (strchr(pkg.c_str(), '.') == NULL) {
533 // not of form 'com.whatever...'; assume internal and ok
534 } else if (strncmp(pkg.c_str(), "android.", 8) == 0) {
535 // android.* packages are assumed fine
536 } else if (package_mgr.get() != nullptr) {
537 String16 pkgName16(pkg.c_str());
538 binder::Status status = package_mgr->getInstallerForPackage(pkgName16, &installer);
539 if (!status.isOk()) {
540 ALOGE("%s: getInstallerForPackage failed: %s",
541 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700542 }
543
Andy Hung17dbaf22019-10-11 14:06:31 -0700544 // skip if we didn't get an installer
545 if (status.isOk()) {
546 status = package_mgr->getVersionCodeForPackage(pkgName16, &versionCode);
Ray Essickfa149562017-09-19 09:27:31 -0700547 if (!status.isOk()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700548 ALOGE("%s: getVersionCodeForPackage failed: %s",
549 __func__, status.exceptionMessage().c_str());
Ray Essickfa149562017-09-19 09:27:31 -0700550 }
551 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700552
553 ALOGV("%s: package '%s' installed by '%s' versioncode %lld",
554 __func__, pkg.c_str(), installer.c_str(), (long long)versionCode);
555
556 if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
557 // from play store, we keep info
558 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
559 // some google source, we keep info
560 } else if (strcmp(installer.c_str(), "preload") == 0) {
561 // preloads, we keep the info
562 } else if (installer.c_str()[0] == '\0') {
563 // sideload (no installer); report UID only
564 pkg = std::to_string(uid);
565 versionCode = 0;
566 } else {
567 // unknown installer; report UID only
568 pkg = std::to_string(uid);
569 versionCode = 0;
570 }
571 } else {
572 // unvalidated by package_mgr just send uid.
573 pkg = std::to_string(uid);
Ray Essickfa149562017-09-19 09:27:31 -0700574 }
575
576 // add it to the map, to save a subsequent lookup
Andy Hung17dbaf22019-10-11 14:06:31 -0700577 std::lock_guard _l(mUidInfoLock);
578 // always overwrite
579 mapping.uid = uid;
580 mapping.pkg = std::move(pkg);
581 mapping.installer = std::move(installer);
582 mapping.versionCode = versionCode;
583 mapping.expiration = now + PKG_EXPIRATION_NS;
584 ALOGV("%s: adding uid %d pkg '%s' expiration: %lld",
Greg Kaiser6c36c782019-10-18 06:27:56 -0700585 __func__, uid, mapping.pkg.c_str(), (long long)mapping.expiration);
Andy Hung17dbaf22019-10-11 14:06:31 -0700586 mPkgMappings[uid] = mapping;
Ray Essickf65f4212017-08-31 11:41:19 -0700587 }
588
Ray Essickfa149562017-09-19 09:27:31 -0700589 if (mapping.uid != (uid_t)(-1)) {
590 if (setName) {
591 item->setPkgName(mapping.pkg);
592 }
593 if (setVersion) {
594 item->setPkgVersionCode(mapping.versionCode);
Ray Essickf65f4212017-08-31 11:41:19 -0700595 }
596 }
Ray Essickf65f4212017-08-31 11:41:19 -0700597}
598
Ray Essick3938dc62016-11-01 08:56:56 -0700599} // namespace android