blob: 028d41234dd0d702b876212c95cc0914834d1ccd [file] [log] [blame]
Dan Egnor4410ec82009-09-11 16:40:01 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
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
17package com.android.server;
18
Makoto Onuki0e623be2017-08-22 10:36:12 -070019import android.app.ActivityManager;
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -060020import android.app.AppOpsManager;
Dan Egnor4410ec82009-09-11 16:40:01 -070021import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
Joe Onorato8e566f32019-10-23 17:35:08 -070026import android.content.pm.PackageManager;
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070027import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080028import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070029import android.net.Uri;
Jeff Sharkey911d7f42013-09-05 18:11:45 -070030import android.os.Binder;
Dan Egnor3d40df32009-11-17 13:36:31 -080031import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080032import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070033import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080034import android.os.Handler;
Makoto Onukiff94e032017-08-08 14:58:19 -070035import android.os.Looper;
Craig Mautner26caf7a2012-03-04 17:17:59 -080036import android.os.Message;
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070037import android.os.ResultReceiver;
38import android.os.ShellCallback;
39import android.os.ShellCommand;
Dan Egnor4410ec82009-09-11 16:40:01 -070040import android.os.StatFs;
41import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070042import android.os.UserHandle;
Dan Egnor4410ec82009-09-11 16:40:01 -070043import android.provider.Settings;
zhouwenjie6a72b392019-10-25 19:22:40 -070044import android.service.dropbox.DropBoxManagerServiceDumpProto;
Makoto Onukiff94e032017-08-08 14:58:19 -070045import android.text.TextUtils;
Neil Fuller9aa7b742019-06-17 11:40:35 +010046import android.text.format.TimeMigrationUtils;
Makoto Onukiff94e032017-08-08 14:58:19 -070047import android.util.ArrayMap;
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070048import android.util.ArraySet;
Joe Onorato8a9b2202010-02-26 18:56:32 -080049import android.util.Slog;
zhouwenjie6a72b392019-10-25 19:22:40 -070050import android.util.proto.ProtoOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070051
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070052import com.android.internal.R;
53import com.android.internal.annotations.GuardedBy;
Makoto Onukiff94e032017-08-08 14:58:19 -070054import com.android.internal.annotations.VisibleForTesting;
Dan Egnorf18a01c2009-11-12 11:32:50 -080055import com.android.internal.os.IDropBoxManagerService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060056import com.android.internal.util.DumpUtils;
Makoto Onukiff94e032017-08-08 14:58:19 -070057import com.android.internal.util.ObjectUtils;
Dan Egnor95240272009-10-27 18:23:39 -070058
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -060059import libcore.io.IoUtils;
60
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070061import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070062import java.io.File;
63import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070064import java.io.FileOutputStream;
65import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070066import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070067import java.io.InputStreamReader;
68import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070069import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070070import java.util.ArrayList;
zhouwenjie6a72b392019-10-25 19:22:40 -070071import java.util.Arrays;
Dan Egnor4410ec82009-09-11 16:40:01 -070072import java.util.SortedSet;
73import java.util.TreeSet;
74import java.util.zip.GZIPOutputStream;
75
76/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080077 * Implementation of {@link IDropBoxManagerService} using the filesystem.
78 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070079 */
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070080public final class DropBoxManagerService extends SystemService {
Dan Egnorf18a01c2009-11-12 11:32:50 -080081 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070082 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070083 private static final int DEFAULT_MAX_FILES = 1000;
Makoto Onuki0e623be2017-08-22 10:36:12 -070084 private static final int DEFAULT_MAX_FILES_LOWRAM = 300;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070085 private static final int DEFAULT_QUOTA_KB = 5 * 1024;
86 private static final int DEFAULT_QUOTA_PERCENT = 10;
87 private static final int DEFAULT_RESERVE_PERCENT = 10;
Dan Egnor4410ec82009-09-11 16:40:01 -070088 private static final int QUOTA_RESCAN_MILLIS = 5000;
89
Dan Egnor3d40df32009-11-17 13:36:31 -080090 private static final boolean PROFILE_DUMP = false;
91
zhouwenjie6a72b392019-10-25 19:22:40 -070092 // Max number of bytes of a dropbox entry to write into protobuf.
93 private static final int PROTO_MAX_DATA_BYTES = 256 * 1024;
94
Dan Egnor4410ec82009-09-11 16:40:01 -070095 // TODO: This implementation currently uses one file per entry, which is
96 // inefficient for smallish entries -- consider using a single queue file
97 // per tag (or even globally) instead.
98
99 // The cached context and derived objects
100
Dan Egnor4410ec82009-09-11 16:40:01 -0700101 private final ContentResolver mContentResolver;
102 private final File mDropBoxDir;
103
104 // Accounting of all currently written log files (set in init()).
105
106 private FileList mAllFiles = null;
Makoto Onukiff94e032017-08-08 14:58:19 -0700107 private ArrayMap<String, FileList> mFilesByTag = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700108
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700109 private long mLowPriorityRateLimitPeriod = 0;
110 private ArraySet<String> mLowPriorityTags = null;
111
Dan Egnor4410ec82009-09-11 16:40:01 -0700112 // Various bits of disk information
113
114 private StatFs mStatFs = null;
115 private int mBlockSize = 0;
116 private int mCachedQuotaBlocks = 0; // Space we can use: computed from free space, etc.
117 private long mCachedQuotaUptimeMillis = 0;
118
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800119 private volatile boolean mBooted = false;
120
Craig Mautner26caf7a2012-03-04 17:17:59 -0800121 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700122 private final DropBoxManagerBroadcastHandler mHandler;
Craig Mautner26caf7a2012-03-04 17:17:59 -0800123
Makoto Onuki0e623be2017-08-22 10:36:12 -0700124 private int mMaxFiles = -1; // -1 means uninitialized.
125
Dan Egnor4410ec82009-09-11 16:40:01 -0700126 /** Receives events that might indicate a need to clean up files. */
127 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
128 @Override
129 public void onReceive(Context context, Intent intent) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700130 // For ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700131 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700132
133 // Run the initialization in the background (not this main thread).
134 // The init() and trimToFit() methods are synchronized, so they still
135 // block other users -- but at least the onReceive() call can finish.
136 new Thread() {
137 public void run() {
138 try {
139 init();
140 trimToFit();
141 } catch (IOException e) {
142 Slog.e(TAG, "Can't init", e);
143 }
144 }
145 }.start();
Dan Egnor4410ec82009-09-11 16:40:01 -0700146 }
147 };
148
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700149 private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
150 @Override
151 public void add(DropBoxManager.Entry entry) {
152 DropBoxManagerService.this.add(entry);
153 }
154
155 @Override
156 public boolean isTagEnabled(String tag) {
157 return DropBoxManagerService.this.isTagEnabled(tag);
158 }
159
160 @Override
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -0600161 public DropBoxManager.Entry getNextEntry(String tag, long millis, String callingPackage) {
162 return DropBoxManagerService.this.getNextEntry(tag, millis, callingPackage);
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700163 }
164
165 @Override
166 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
167 DropBoxManagerService.this.dump(fd, pw, args);
168 }
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700169
170 @Override
171 public void onShellCommand(FileDescriptor in, FileDescriptor out,
172 FileDescriptor err, String[] args, ShellCallback callback,
173 ResultReceiver resultReceiver) {
174 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
175 }
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700176 };
177
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700178 private class ShellCmd extends ShellCommand {
179 @Override
180 public int onCommand(String cmd) {
181 if (cmd == null) {
182 return handleDefaultCommands(cmd);
183 }
184 final PrintWriter pw = getOutPrintWriter();
185 try {
186 switch (cmd) {
187 case "set-rate-limit":
188 final long period = Long.parseLong(getNextArgRequired());
189 DropBoxManagerService.this.setLowPriorityRateLimit(period);
190 break;
191 case "add-low-priority":
192 final String addedTag = getNextArgRequired();
193 DropBoxManagerService.this.addLowPriorityTag(addedTag);
194 break;
195 case "remove-low-priority":
196 final String removeTag = getNextArgRequired();
197 DropBoxManagerService.this.removeLowPriorityTag(removeTag);
198 break;
199 case "restore-defaults":
200 DropBoxManagerService.this.restoreDefaults();
201 break;
202 default:
203 return handleDefaultCommands(cmd);
204 }
205 } catch (Exception e) {
206 pw.println(e);
207 }
208 return 0;
209 }
210
211 @Override
212 public void onHelp() {
213 PrintWriter pw = getOutPrintWriter();
214 pw.println("Dropbox manager service commands:");
215 pw.println(" help");
216 pw.println(" Print this help text.");
217 pw.println(" set-rate-limit PERIOD");
218 pw.println(" Sets low priority broadcast rate limit period to PERIOD ms");
219 pw.println(" add-low-priority TAG");
220 pw.println(" Add TAG to dropbox low priority list");
221 pw.println(" remove-low-priority TAG");
222 pw.println(" Remove TAG from dropbox low priority list");
223 pw.println(" restore-defaults");
224 pw.println(" restore dropbox settings to defaults");
225 }
226 }
227
228 private class DropBoxManagerBroadcastHandler extends Handler {
229 private final Object mLock = new Object();
230
231 static final int MSG_SEND_BROADCAST = 1;
232 static final int MSG_SEND_DEFERRED_BROADCAST = 2;
233
234 @GuardedBy("mLock")
235 private final ArrayMap<String, Intent> mDeferredMap = new ArrayMap();
236
237 DropBoxManagerBroadcastHandler(Looper looper) {
238 super(looper);
239 }
240
241 @Override
242 public void handleMessage(Message msg) {
243 switch (msg.what) {
244 case MSG_SEND_BROADCAST:
245 prepareAndSendBroadcast((Intent) msg.obj);
246 break;
247 case MSG_SEND_DEFERRED_BROADCAST:
248 Intent deferredIntent;
249 synchronized (mLock) {
250 deferredIntent = mDeferredMap.remove((String) msg.obj);
251 }
252 if (deferredIntent != null) {
253 prepareAndSendBroadcast(deferredIntent);
254 }
255 break;
256 }
257 }
258
259 private void prepareAndSendBroadcast(Intent intent) {
260 if (!DropBoxManagerService.this.mBooted) {
261 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
262 }
263 getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM,
264 android.Manifest.permission.READ_LOGS);
265 }
266
267 private Intent createIntent(String tag, long time) {
268 final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
269 dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
270 dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
271 return dropboxIntent;
272 }
273
274 /**
275 * Schedule a dropbox broadcast to be sent asynchronously.
276 */
277 public void sendBroadcast(String tag, long time) {
278 sendMessage(obtainMessage(MSG_SEND_BROADCAST, createIntent(tag, time)));
279 }
280
281 /**
282 * Possibly schedule a delayed dropbox broadcast. The broadcast will only be scheduled if
283 * no broadcast is currently scheduled. Otherwise updated the scheduled broadcast with the
284 * new intent information, effectively dropping the previous broadcast.
285 */
286 public void maybeDeferBroadcast(String tag, long time) {
287 synchronized (mLock) {
288 final Intent intent = mDeferredMap.get(tag);
289 if (intent == null) {
290 // Schedule new delayed broadcast.
291 mDeferredMap.put(tag, createIntent(tag, time));
292 sendMessageDelayed(obtainMessage(MSG_SEND_DEFERRED_BROADCAST, tag),
293 mLowPriorityRateLimitPeriod);
294 } else {
295 // Broadcast is already scheduled. Update intent with new data.
296 intent.putExtra(DropBoxManager.EXTRA_TIME, time);
297 final int dropped = intent.getIntExtra(DropBoxManager.EXTRA_DROPPED_COUNT, 0);
298 intent.putExtra(DropBoxManager.EXTRA_DROPPED_COUNT, dropped + 1);
299 return;
300 }
301 }
302 }
303 }
304
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700305 /**
306 * Creates an instance of managed drop box storage using the default dropbox
307 * directory.
308 *
309 * @param context to use for receiving free space & gservices intents
310 */
311 public DropBoxManagerService(final Context context) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700312 this(context, new File("/data/system/dropbox"), FgThread.get().getLooper());
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700313 }
314
Dan Egnor4410ec82009-09-11 16:40:01 -0700315 /**
316 * Creates an instance of managed drop box storage. Normally there is one of these
317 * run by the system, but others can be created for testing and other purposes.
318 *
319 * @param context to use for receiving free space & gservices intents
320 * @param path to store drop box entries in
321 */
Makoto Onukiff94e032017-08-08 14:58:19 -0700322 @VisibleForTesting
323 public DropBoxManagerService(final Context context, File path, Looper looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700324 super(context);
Dan Egnor4410ec82009-09-11 16:40:01 -0700325 mDropBoxDir = path;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700326 mContentResolver = getContext().getContentResolver();
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700327 mHandler = new DropBoxManagerBroadcastHandler(looper);
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700328 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700329
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700330 @Override
331 public void onStart() {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700332 publishBinderService(Context.DROPBOX_SERVICE, mStub);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800333
Dan Egnor4410ec82009-09-11 16:40:01 -0700334 // The real work gets done lazily in init() -- that way service creation always
335 // succeeds, and things like disk problems cause individual method failures.
336 }
337
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700338 @Override
339 public void onBootPhase(int phase) {
340 switch (phase) {
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600341 case PHASE_SYSTEM_SERVICES_READY:
342 IntentFilter filter = new IntentFilter();
343 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
344 getContext().registerReceiver(mReceiver, filter);
345
346 mContentResolver.registerContentObserver(
347 Settings.Global.CONTENT_URI, true,
348 new ContentObserver(new Handler()) {
349 @Override
350 public void onChange(boolean selfChange) {
351 mReceiver.onReceive(getContext(), (Intent) null);
352 }
353 });
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700354
355 getLowPriorityResourceConfigs();
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600356 break;
357
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700358 case PHASE_BOOT_COMPLETED:
359 mBooted = true;
360 break;
361 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700362 }
363
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700364 /** Retrieves the binder stub -- for test instances */
365 public IDropBoxManagerService getServiceStub() {
366 return mStub;
367 }
368
Dan Egnorf18a01c2009-11-12 11:32:50 -0800369 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700370 File temp = null;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700371 InputStream input = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700372 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700373 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700374 try {
Dan Egnor95240272009-10-27 18:23:39 -0700375 int flags = entry.getFlags();
Joe Onorato99598ee2019-02-11 15:55:13 +0000376 Slog.i(TAG, "add tag=" + tag + " isTagEnabled=" + isTagEnabled(tag)
377 + " flags=0x" + Integer.toHexString(flags));
Dan Egnorf18a01c2009-11-12 11:32:50 -0800378 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700379
380 init();
381 if (!isTagEnabled(tag)) return;
382 long max = trimToFit();
383 long lastTrim = System.currentTimeMillis();
384
385 byte[] buffer = new byte[mBlockSize];
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700386 input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700387
388 // First, accumulate up to one block worth of data in memory before
389 // deciding whether to compress the data or not.
390
391 int read = 0;
392 while (read < buffer.length) {
393 int n = input.read(buffer, read, buffer.length - read);
394 if (n <= 0) break;
395 read += n;
396 }
397
398 // If we have at least one block, compress it -- otherwise, just write
399 // the data in uncompressed form.
400
401 temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700402 int bufferSize = mBlockSize;
403 if (bufferSize > 4096) bufferSize = 4096;
404 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700405 FileOutputStream foutput = new FileOutputStream(temp);
406 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800407 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700408 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800409 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700410 }
411
412 do {
413 output.write(buffer, 0, read);
414
415 long now = System.currentTimeMillis();
416 if (now - lastTrim > 30 * 1000) {
417 max = trimToFit(); // In case data dribbles in slowly
418 lastTrim = now;
419 }
420
421 read = input.read(buffer);
422 if (read <= 0) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700423 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700424 output.close(); // Get a final size measurement
425 output = null;
426 } else {
427 output.flush(); // So the size measurement is pseudo-reasonable
428 }
429
430 long len = temp.length();
431 if (len > max) {
Joe Onorato99598ee2019-02-11 15:55:13 +0000432 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > "
433 + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700434 temp.delete();
435 temp = null; // Pass temp = null to createEntry() to leave a tombstone
436 break;
437 }
438 } while (read > 0);
439
Hakan Stillb2475362010-12-07 14:05:55 +0100440 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700441 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100442
Craig Mautner26caf7a2012-03-04 17:17:59 -0800443 // Call sendBroadcast after returning from this call to avoid deadlock. In particular
444 // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
445 // lock in ActivityManagerService. ActivityManagerService has been caught holding that
446 // very lock while waiting for the WindowManagerService lock.
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700447 if (mLowPriorityTags != null && mLowPriorityTags.contains(tag)) {
448 // Rate limit low priority Dropbox entries
449 mHandler.maybeDeferBroadcast(tag, time);
450 } else {
451 mHandler.sendBroadcast(tag, time);
452 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700453 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800454 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700455 } finally {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700456 IoUtils.closeQuietly(output);
457 IoUtils.closeQuietly(input);
Dan Egnor95240272009-10-27 18:23:39 -0700458 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700459 if (temp != null) temp.delete();
460 }
461 }
462
463 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700464 final long token = Binder.clearCallingIdentity();
465 try {
466 return !"disabled".equals(Settings.Global.getString(
467 mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
468 } finally {
469 Binder.restoreCallingIdentity(token);
470 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700471 }
472
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -0600473 private boolean checkPermission(int callingUid, String callingPackage) {
Joe Onorato8e566f32019-10-23 17:35:08 -0700474 // If callers have this permission, then we don't need to check
475 // USAGE_STATS, because they are part of the system and have agreed to
476 // check USAGE_STATS before passing the data along.
477 if (getContext().checkCallingPermission(android.Manifest.permission.PEEK_DROPBOX_DATA)
478 == PackageManager.PERMISSION_GRANTED) {
479 return true;
480 }
481
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -0600482 // Callers always need this permission
483 getContext().enforceCallingOrSelfPermission(
484 android.Manifest.permission.READ_LOGS, TAG);
485
486 // Callers also need the ability to read usage statistics
487 switch (getContext().getSystemService(AppOpsManager.class)
488 .noteOp(AppOpsManager.OP_GET_USAGE_STATS, callingUid, callingPackage)) {
489 case AppOpsManager.MODE_ALLOWED:
490 return true;
491 case AppOpsManager.MODE_DEFAULT:
492 getContext().enforceCallingOrSelfPermission(
493 android.Manifest.permission.PACKAGE_USAGE_STATS, TAG);
494 return true;
495 default:
496 return false;
497 }
498 }
499
500 public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis,
501 String callingPackage) {
502 if (!checkPermission(Binder.getCallingUid(), callingPackage)) {
503 return null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700504 }
505
506 try {
507 init();
508 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800509 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700510 return null;
511 }
512
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700513 FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
514 if (list == null) return null;
515
516 for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700517 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800518 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
519 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700520 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700521 final File file = entry.getFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700522 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800523 return new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700524 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700525 } catch (IOException e) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700526 Slog.wtf(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700527 // Continue to next file
528 }
529 }
530
531 return null;
532 }
533
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700534 private synchronized void setLowPriorityRateLimit(long period) {
535 mLowPriorityRateLimitPeriod = period;
536 }
537
538 private synchronized void addLowPriorityTag(String tag) {
539 mLowPriorityTags.add(tag);
540 }
541
542 private synchronized void removeLowPriorityTag(String tag) {
543 mLowPriorityTags.remove(tag);
544 }
545
546 private synchronized void restoreDefaults() {
547 getLowPriorityResourceConfigs();
548 }
549
Dan Egnor4410ec82009-09-11 16:40:01 -0700550 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -0600551 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700552
553 try {
554 init();
555 } catch (IOException e) {
556 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800557 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700558 return;
559 }
560
Dan Egnor3d40df32009-11-17 13:36:31 -0800561 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
562
Dan Egnor5ec249a2009-11-25 13:16:47 -0800563 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700564 boolean doPrint = false, doFile = false;
zhouwenjie6a72b392019-10-25 19:22:40 -0700565 boolean dumpProto = false;
Dan Egnor4410ec82009-09-11 16:40:01 -0700566 ArrayList<String> searchArgs = new ArrayList<String>();
567 for (int i = 0; args != null && i < args.length; i++) {
568 if (args[i].equals("-p") || args[i].equals("--print")) {
569 doPrint = true;
570 } else if (args[i].equals("-f") || args[i].equals("--file")) {
571 doFile = true;
zhouwenjie6a72b392019-10-25 19:22:40 -0700572 } else if (args[i].equals("--proto")) {
573 dumpProto = true;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700574 } else if (args[i].equals("-h") || args[i].equals("--help")) {
575 pw.println("Dropbox (dropbox) dump options:");
576 pw.println(" [-h|--help] [-p|--print] [-f|--file] [timestamp]");
577 pw.println(" -h|--help: print this help");
578 pw.println(" -p|--print: print full contents of each entry");
579 pw.println(" -f|--file: print path of each entry's file");
zhouwenjie6a72b392019-10-25 19:22:40 -0700580 pw.println(" --proto: dump data to proto");
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700581 pw.println(" [timestamp] optionally filters to only those entries.");
582 return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700583 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800584 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700585 } else {
586 searchArgs.add(args[i]);
587 }
588 }
589
zhouwenjie6a72b392019-10-25 19:22:40 -0700590 if (dumpProto) {
591 dumpProtoLocked(fd, searchArgs);
592 return;
593 }
594
Dan Egnor5ec249a2009-11-25 13:16:47 -0800595 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Makoto Onuki0e623be2017-08-22 10:36:12 -0700596 out.append("Max entries: ").append(mMaxFiles).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700597
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700598 out.append("Low priority rate limit period: ");
599 out.append(mLowPriorityRateLimitPeriod).append(" ms\n");
600 out.append("Low priority tags: ").append(mLowPriorityTags).append("\n");
601
Dan Egnor4410ec82009-09-11 16:40:01 -0700602 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800603 out.append("Searching for:");
604 for (String a : searchArgs) out.append(" ").append(a);
605 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700606 }
607
zhouwenjie6a72b392019-10-25 19:22:40 -0700608 int numFound = 0;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800609 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700610 for (EntryFile entry : mAllFiles.contents) {
zhouwenjie6a72b392019-10-25 19:22:40 -0700611 if (!matchEntry(entry, searchArgs)) continue;
Dan Egnor4410ec82009-09-11 16:40:01 -0700612
613 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800614 if (doPrint) out.append("========================================\n");
zhouwenjie6a72b392019-10-25 19:22:40 -0700615
616 String date = TimeMigrationUtils.formatMillisWithFixedFormat(entry.timestampMillis);
Dan Egnor5ec249a2009-11-25 13:16:47 -0800617 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Makoto Onukiff94e032017-08-08 14:58:19 -0700618
619 final File file = entry.getFile(mDropBoxDir);
620 if (file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800621 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700622 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800623 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800624 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700625 continue;
626 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800627 out.append(" (");
628 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
629 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
Makoto Onukiff94e032017-08-08 14:58:19 -0700630 out.append(", ").append(file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700631 }
632
Dan Egnorf18a01c2009-11-12 11:32:50 -0800633 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800634 if (!doPrint) out.append(" ");
Makoto Onukiff94e032017-08-08 14:58:19 -0700635 out.append(file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700636 }
637
Dan Egnorf18a01c2009-11-12 11:32:50 -0800638 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
639 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800640 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700641 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800642 dbe = new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700643 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700644
645 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800646 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700647 char[] buf = new char[4096];
648 boolean newline = false;
649 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800650 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700651 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800652 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700653 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800654
655 // Flush periodically when printing to avoid out-of-memory.
656 if (out.length() > 65536) {
657 pw.write(out.toString());
658 out.setLength(0);
659 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700660 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800661 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700662 } else {
663 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800664 out.append(" ");
665 if (text == null) {
666 out.append("[null]");
667 } else {
668 boolean truncated = (text.length() == 70);
669 out.append(text.trim().replace('\n', '/'));
670 if (truncated) out.append(" ...");
671 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800672 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700673 }
674 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800675 out.append("*** ").append(e.toString()).append("\n");
Makoto Onukiff94e032017-08-08 14:58:19 -0700676 Slog.e(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700677 } finally {
678 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800679 if (isr != null) {
680 try {
681 isr.close();
682 } catch (IOException unused) {
683 }
684 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700685 }
686 }
687
Dan Egnor5ec249a2009-11-25 13:16:47 -0800688 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700689 }
690
Dan Egnor5ec249a2009-11-25 13:16:47 -0800691 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700692
693 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800694 if (!doPrint) out.append("\n");
695 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700696 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800697
698 pw.write(out.toString());
699 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700700 }
701
zhouwenjie6a72b392019-10-25 19:22:40 -0700702 private boolean matchEntry(EntryFile entry, ArrayList<String> searchArgs) {
703 String date = TimeMigrationUtils.formatMillisWithFixedFormat(entry.timestampMillis);
704 boolean match = true;
705 int numArgs = searchArgs.size();
706 for (int i = 0; i < numArgs && match; i++) {
707 String arg = searchArgs.get(i);
708 match = (date.contains(arg) || arg.equals(entry.tag));
709 }
710 return match;
711 }
712
713 private void dumpProtoLocked(FileDescriptor fd, ArrayList<String> searchArgs) {
714 final ProtoOutputStream proto = new ProtoOutputStream(fd);
715
716 for (EntryFile entry : mAllFiles.contents) {
717 if (!matchEntry(entry, searchArgs)) continue;
718
719 final File file = entry.getFile(mDropBoxDir);
720 if ((file == null) || ((entry.flags & DropBoxManager.IS_EMPTY) != 0)) {
721 continue;
722 }
723
724 final long bToken = proto.start(DropBoxManagerServiceDumpProto.ENTRIES);
725 proto.write(DropBoxManagerServiceDumpProto.Entry.TIME_MS, entry.timestampMillis);
726 try (
727 DropBoxManager.Entry dbe = new DropBoxManager.Entry(
728 entry.tag, entry.timestampMillis, file, entry.flags);
729 InputStream is = dbe.getInputStream();
730 ) {
731 if (is != null) {
732 byte[] buf = new byte[PROTO_MAX_DATA_BYTES];
733 int readBytes = 0;
734 int n = 0;
735 while (n >= 0 && (readBytes += n) < PROTO_MAX_DATA_BYTES) {
736 n = is.read(buf, readBytes, PROTO_MAX_DATA_BYTES - readBytes);
737 }
738 proto.write(DropBoxManagerServiceDumpProto.Entry.DATA,
739 Arrays.copyOf(buf, readBytes));
740 }
741 } catch (IOException e) {
742 Slog.e(TAG, "Can't read: " + file, e);
743 }
744
745 proto.end(bToken);
746 }
747
748 proto.flush();
749 }
750
Dan Egnor4410ec82009-09-11 16:40:01 -0700751 ///////////////////////////////////////////////////////////////////////////
752
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700753 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700754 private static final class FileList implements Comparable<FileList> {
755 public int blocks = 0;
756 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
757
758 /** Sorts bigger FileList instances before smaller ones. */
759 public final int compareTo(FileList o) {
760 if (blocks != o.blocks) return o.blocks - blocks;
761 if (this == o) return 0;
762 if (hashCode() < o.hashCode()) return -1;
763 if (hashCode() > o.hashCode()) return 1;
764 return 0;
765 }
766 }
767
Makoto Onukiff94e032017-08-08 14:58:19 -0700768 /**
769 * Metadata describing an on-disk log file.
770 *
771 * Note its instances do no have knowledge on what directory they're stored, just to save
772 * 4/8 bytes per instance. Instead, {@link #getFile} takes a directory so it can build a
773 * fullpath.
774 */
775 @VisibleForTesting
776 static final class EntryFile implements Comparable<EntryFile> {
Dan Egnor4410ec82009-09-11 16:40:01 -0700777 public final String tag;
778 public final long timestampMillis;
779 public final int flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700780 public final int blocks;
781
782 /** Sorts earlier EntryFile instances before later ones. */
783 public final int compareTo(EntryFile o) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700784 int comp = Long.compare(timestampMillis, o.timestampMillis);
785 if (comp != 0) return comp;
786
787 comp = ObjectUtils.compare(tag, o.tag);
788 if (comp != 0) return comp;
789
790 comp = Integer.compare(flags, o.flags);
791 if (comp != 0) return comp;
792
793 return Integer.compare(hashCode(), o.hashCode());
Dan Egnor4410ec82009-09-11 16:40:01 -0700794 }
795
796 /**
797 * Moves an existing temporary file to a new log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700798 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700799 * @param temp file to rename
800 * @param dir to store file in
801 * @param tag to use for new log file name
802 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700803 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700804 * @param blockSize to use for space accounting
805 * @throws IOException if the file can't be moved
806 */
807 public EntryFile(File temp, File dir, String tag,long timestampMillis,
808 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800809 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700810
Makoto Onukiff94e032017-08-08 14:58:19 -0700811 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700812 this.timestampMillis = timestampMillis;
813 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700814
Makoto Onukiff94e032017-08-08 14:58:19 -0700815 final File file = this.getFile(dir);
816 if (!temp.renameTo(file)) {
817 throw new IOException("Can't rename " + temp + " to " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700818 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700819 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700820 }
821
822 /**
823 * Creates a zero-length tombstone for a file whose contents were lost.
Makoto Onukiff94e032017-08-08 14:58:19 -0700824 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700825 * @param dir to store file in
826 * @param tag to use for new log file name
827 * @param timestampMillis of log entry
828 * @throws IOException if the file can't be created.
829 */
830 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
Makoto Onukiff94e032017-08-08 14:58:19 -0700831 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700832 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800833 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700834 this.blocks = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700835 new FileOutputStream(getFile(dir)).close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700836 }
837
838 /**
839 * Extracts metadata from an existing on-disk log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700840 *
841 * Note when a filename is not recognizable, it will create an instance that
842 * {@link #hasFile()} would return false on, and also remove the file.
843 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700844 * @param file name of existing log file
845 * @param blockSize to use for space accounting
846 */
847 public EntryFile(File file, int blockSize) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700848
849 boolean parseFailure = false;
Dan Egnor4410ec82009-09-11 16:40:01 -0700850
851 String name = file.getName();
Dan Egnor4410ec82009-09-11 16:40:01 -0700852 int flags = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700853 String tag = null;
854 long millis = 0;
855
856 final int at = name.lastIndexOf('@');
857 if (at < 0) {
858 parseFailure = true;
Dan Egnor4410ec82009-09-11 16:40:01 -0700859 } else {
Makoto Onukiff94e032017-08-08 14:58:19 -0700860 tag = Uri.decode(name.substring(0, at));
861 if (name.endsWith(".gz")) {
862 flags |= DropBoxManager.IS_GZIPPED;
863 name = name.substring(0, name.length() - 3);
864 }
865 if (name.endsWith(".lost")) {
866 flags |= DropBoxManager.IS_EMPTY;
867 name = name.substring(at + 1, name.length() - 5);
868 } else if (name.endsWith(".txt")) {
869 flags |= DropBoxManager.IS_TEXT;
870 name = name.substring(at + 1, name.length() - 4);
871 } else if (name.endsWith(".dat")) {
872 name = name.substring(at + 1, name.length() - 4);
873 } else {
874 parseFailure = true;
875 }
876 if (!parseFailure) {
877 try {
878 millis = Long.parseLong(name);
879 } catch (NumberFormatException e) {
880 parseFailure = true;
881 }
882 }
883 }
884 if (parseFailure) {
885 Slog.wtf(TAG, "Invalid filename: " + file);
886
887 // Remove the file and return an empty instance.
888 file.delete();
889 this.tag = null;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800890 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700891 this.timestampMillis = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700892 this.blocks = 0;
Dan Egnor4410ec82009-09-11 16:40:01 -0700893 return;
894 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700895
Makoto Onukiff94e032017-08-08 14:58:19 -0700896 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
897 this.tag = TextUtils.safeIntern(tag);
898 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700899 this.timestampMillis = millis;
900 }
901
902 /**
903 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700904 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700905 */
906 public EntryFile(long millis) {
907 this.tag = null;
908 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800909 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700910 this.blocks = 0;
911 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700912
913 /**
914 * @return whether an entry actually has a backing file, or it's an empty "tombstone"
915 * entry.
916 */
917 public boolean hasFile() {
918 return tag != null;
919 }
920
921 /** @return File extension for the flags. */
922 private String getExtension() {
923 if ((flags & DropBoxManager.IS_EMPTY) != 0) {
924 return ".lost";
925 }
926 return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
927 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
928 }
929
930 /**
931 * @return filename for this entry without the pathname.
932 */
933 public String getFilename() {
934 return hasFile() ? Uri.encode(tag) + "@" + timestampMillis + getExtension() : null;
935 }
936
937 /**
938 * Get a full-path {@link File} representing this entry.
939 * @param dir Parent directly. The caller needs to pass it because {@link EntryFile}s don't
940 * know in which directory they're stored.
941 */
942 public File getFile(File dir) {
943 return hasFile() ? new File(dir, getFilename()) : null;
944 }
945
946 /**
947 * If an entry has a backing file, remove it.
948 */
949 public void deleteFile(File dir) {
950 if (hasFile()) {
951 getFile(dir).delete();
952 }
953 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700954 }
955
956 ///////////////////////////////////////////////////////////////////////////
957
958 /** If never run before, scans disk contents to build in-memory tracking data. */
959 private synchronized void init() throws IOException {
960 if (mStatFs == null) {
961 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
962 throw new IOException("Can't mkdir: " + mDropBoxDir);
963 }
964 try {
965 mStatFs = new StatFs(mDropBoxDir.getPath());
966 mBlockSize = mStatFs.getBlockSize();
967 } catch (IllegalArgumentException e) { // StatFs throws this on error
968 throw new IOException("Can't statfs: " + mDropBoxDir);
969 }
970 }
971
972 if (mAllFiles == null) {
973 File[] files = mDropBoxDir.listFiles();
974 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
975
976 mAllFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700977 mFilesByTag = new ArrayMap<>();
Dan Egnor4410ec82009-09-11 16:40:01 -0700978
979 // Scan pre-existing files.
980 for (File file : files) {
981 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800982 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700983 file.delete();
984 continue;
985 }
986
987 EntryFile entry = new EntryFile(file, mBlockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700988
Makoto Onukiff94e032017-08-08 14:58:19 -0700989 if (entry.hasFile()) {
990 // Enroll only when the filename is valid. Otherwise the above constructor
991 // has removed the file already.
992 enrollEntry(entry);
993 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700994 }
995 }
996 }
997
998 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
999 private synchronized void enrollEntry(EntryFile entry) {
1000 mAllFiles.contents.add(entry);
1001 mAllFiles.blocks += entry.blocks;
1002
1003 // mFilesByTag is used for trimming, so don't list empty files.
1004 // (Zero-length/lost files are trimmed by date from mAllFiles.)
1005
Makoto Onukiff94e032017-08-08 14:58:19 -07001006 if (entry.hasFile() && entry.blocks > 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -07001007 FileList tagFiles = mFilesByTag.get(entry.tag);
1008 if (tagFiles == null) {
1009 tagFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -07001010 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
Dan Egnor4410ec82009-09-11 16:40:01 -07001011 }
1012 tagFiles.contents.add(entry);
1013 tagFiles.blocks += entry.blocks;
1014 }
1015 }
1016
1017 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +01001018 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -07001019 long t = System.currentTimeMillis();
1020
1021 // Require each entry to have a unique timestamp; if there are entries
1022 // >10sec in the future (due to clock skew), drag them back to avoid
1023 // keeping them around forever.
1024
1025 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
1026 EntryFile[] future = null;
1027 if (!tail.isEmpty()) {
1028 future = tail.toArray(new EntryFile[tail.size()]);
1029 tail.clear(); // Remove from mAllFiles
1030 }
1031
1032 if (!mAllFiles.contents.isEmpty()) {
1033 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
1034 }
1035
1036 if (future != null) {
1037 for (EntryFile late : future) {
1038 mAllFiles.blocks -= late.blocks;
1039 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -08001040 if (tagFiles != null && tagFiles.contents.remove(late)) {
1041 tagFiles.blocks -= late.blocks;
1042 }
Dan Egnorf18a01c2009-11-12 11:32:50 -08001043 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Makoto Onukiff94e032017-08-08 14:58:19 -07001044 enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
1045 late.tag, t++, late.flags, mBlockSize));
Dan Egnor4410ec82009-09-11 16:40:01 -07001046 } else {
1047 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
1048 }
1049 }
1050 }
1051
1052 if (temp == null) {
1053 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
1054 } else {
1055 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
1056 }
Hakan Stillb2475362010-12-07 14:05:55 +01001057 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -07001058 }
1059
1060 /**
1061 * Trims the files on disk to make sure they aren't using too much space.
1062 * @return the overall quota for storage (in bytes)
1063 */
songjinshic5e249b2016-07-27 20:36:46 +08001064 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -07001065 // Expunge aged items (including tombstones marking deleted data).
1066
Jeff Sharkey625239a2012-09-26 22:03:49 -07001067 int ageSeconds = Settings.Global.getInt(mContentResolver,
1068 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Makoto Onuki0e623be2017-08-22 10:36:12 -07001069 mMaxFiles = Settings.Global.getInt(mContentResolver,
1070 Settings.Global.DROPBOX_MAX_FILES,
1071 (ActivityManager.isLowRamDeviceStatic()
1072 ? DEFAULT_MAX_FILES_LOWRAM : DEFAULT_MAX_FILES));
Dan Egnor4410ec82009-09-11 16:40:01 -07001073 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
1074 while (!mAllFiles.contents.isEmpty()) {
1075 EntryFile entry = mAllFiles.contents.first();
Makoto Onuki0e623be2017-08-22 10:36:12 -07001076 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < mMaxFiles) {
1077 break;
1078 }
Dan Egnor4410ec82009-09-11 16:40:01 -07001079
1080 FileList tag = mFilesByTag.get(entry.tag);
1081 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
1082 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
Makoto Onukiff94e032017-08-08 14:58:19 -07001083 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -07001084 }
1085
1086 // Compute overall quota (a fraction of available free space) in blocks.
1087 // The quota changes dynamically based on the amount of free space;
1088 // that way when lots of data is available we can use it, but we'll get
1089 // out of the way if storage starts getting tight.
1090
1091 long uptimeMillis = SystemClock.uptimeMillis();
1092 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07001093 int quotaPercent = Settings.Global.getInt(mContentResolver,
1094 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
1095 int reservePercent = Settings.Global.getInt(mContentResolver,
1096 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
1097 int quotaKb = Settings.Global.getInt(mContentResolver,
1098 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -07001099
songjinshic5e249b2016-07-27 20:36:46 +08001100 String dirPath = mDropBoxDir.getPath();
1101 try {
1102 mStatFs.restat(dirPath);
1103 } catch (IllegalArgumentException e) { // restat throws this on error
1104 throw new IOException("Can't restat: " + mDropBoxDir);
1105 }
Dmytro Chystiakovcbb50002019-04-28 17:06:36 -07001106 long available = mStatFs.getAvailableBlocksLong();
1107 long nonreserved = available - mStatFs.getBlockCountLong() * reservePercent / 100;
1108 long maxAvailableLong = nonreserved * quotaPercent / 100;
1109 int maxAvailable = Math.toIntExact(Math.max(0,
1110 Math.min(maxAvailableLong, Integer.MAX_VALUE)));
Dan Egnor4410ec82009-09-11 16:40:01 -07001111 int maximum = quotaKb * 1024 / mBlockSize;
Dmytro Chystiakovcbb50002019-04-28 17:06:36 -07001112 mCachedQuotaBlocks = Math.min(maximum, maxAvailable);
Dan Egnor4410ec82009-09-11 16:40:01 -07001113 mCachedQuotaUptimeMillis = uptimeMillis;
1114 }
1115
1116 // If we're using too much space, delete old items to make room.
1117 //
1118 // We trim each tag independently (this is why we keep per-tag lists).
1119 // Space is "fairly" shared between tags -- they are all squeezed
1120 // equally until enough space is reclaimed.
1121 //
1122 // A single circular buffer (a la logcat) would be simpler, but this
1123 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
1124 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -07001125 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -07001126 //
1127 // Deleted files are replaced with zero-length tombstones to mark what
1128 // was lost. Tombstones are expunged by age (see above).
1129
1130 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -07001131 // Find a fair share amount of space to limit each tag
1132 int unsqueezed = mAllFiles.blocks, squeezed = 0;
1133 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
1134 for (FileList tag : tags) {
1135 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
1136 break;
1137 }
1138 unsqueezed -= tag.blocks;
1139 squeezed++;
1140 }
1141 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
1142
1143 // Remove old items from each tag until it meets the per-tag quota.
1144 for (FileList tag : tags) {
1145 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
1146 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
1147 EntryFile entry = tag.contents.first();
1148 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
1149 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
1150
1151 try {
Makoto Onukiff94e032017-08-08 14:58:19 -07001152 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -07001153 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
1154 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001155 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -07001156 }
1157 }
1158 }
1159 }
1160
1161 return mCachedQuotaBlocks * mBlockSize;
1162 }
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -07001163
1164 private void getLowPriorityResourceConfigs() {
1165 mLowPriorityRateLimitPeriod = Resources.getSystem().getInteger(
1166 R.integer.config_dropboxLowPriorityBroadcastRateLimitPeriod);
1167
1168 final String[] lowPrioritytags = Resources.getSystem().getStringArray(
1169 R.array.config_dropboxLowPriorityTags);
1170 final int size = lowPrioritytags.length;
1171 if (size == 0) {
1172 mLowPriorityTags = null;
1173 return;
1174 }
1175 mLowPriorityTags = new ArraySet(size);
1176 for (int i = 0; i < size; i++) {
1177 mLowPriorityTags.add(lowPrioritytags[i]);
1178 }
1179 }
Dan Egnor4410ec82009-09-11 16:40:01 -07001180}