1 /*
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 
17 package com.android.server;
18 
19 import android.app.ActivityManager;
20 import android.app.AppOpsManager;
21 import android.content.BroadcastReceiver;
22 import android.content.ContentResolver;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.IntentFilter;
26 import android.content.pm.PackageManager;
27 import android.content.res.Resources;
28 import android.database.ContentObserver;
29 import android.net.Uri;
30 import android.os.Binder;
31 import android.os.Debug;
32 import android.os.DropBoxManager;
33 import android.os.FileUtils;
34 import android.os.Handler;
35 import android.os.Looper;
36 import android.os.Message;
37 import android.os.ResultReceiver;
38 import android.os.ShellCallback;
39 import android.os.ShellCommand;
40 import android.os.StatFs;
41 import android.os.SystemClock;
42 import android.os.UserHandle;
43 import android.provider.Settings;
44 import android.service.dropbox.DropBoxManagerServiceDumpProto;
45 import android.text.TextUtils;
46 import android.text.format.TimeMigrationUtils;
47 import android.util.ArrayMap;
48 import android.util.ArraySet;
49 import android.util.Slog;
50 import android.util.proto.ProtoOutputStream;
51 
52 import com.android.internal.R;
53 import com.android.internal.annotations.GuardedBy;
54 import com.android.internal.annotations.VisibleForTesting;
55 import com.android.internal.os.IDropBoxManagerService;
56 import com.android.internal.util.DumpUtils;
57 import com.android.internal.util.ObjectUtils;
58 
59 import libcore.io.IoUtils;
60 
61 import java.io.BufferedOutputStream;
62 import java.io.File;
63 import java.io.FileDescriptor;
64 import java.io.FileOutputStream;
65 import java.io.IOException;
66 import java.io.InputStream;
67 import java.io.InputStreamReader;
68 import java.io.OutputStream;
69 import java.io.PrintWriter;
70 import java.util.ArrayList;
71 import java.util.Arrays;
72 import java.util.SortedSet;
73 import java.util.TreeSet;
74 import java.util.zip.GZIPOutputStream;
75 
76 /**
77  * Implementation of {@link IDropBoxManagerService} using the filesystem.
78  * Clients use {@link DropBoxManager} to access this service.
79  */
80 public final class DropBoxManagerService extends SystemService {
81     private static final String TAG = "DropBoxManagerService";
82     private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
83     private static final int DEFAULT_MAX_FILES = 1000;
84     private static final int DEFAULT_MAX_FILES_LOWRAM = 300;
85     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;
88     private static final int QUOTA_RESCAN_MILLIS = 5000;
89 
90     private static final boolean PROFILE_DUMP = false;
91 
92     // Max number of bytes of a dropbox entry to write into protobuf.
93     private static final int PROTO_MAX_DATA_BYTES = 256 * 1024;
94 
95     // 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 
101     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;
107     private ArrayMap<String, FileList> mFilesByTag = null;
108 
109     private long mLowPriorityRateLimitPeriod = 0;
110     private ArraySet<String> mLowPriorityTags = null;
111 
112     // 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 
119     private volatile boolean mBooted = false;
120 
121     // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
122     private final DropBoxManagerBroadcastHandler mHandler;
123 
124     private int mMaxFiles = -1; // -1 means uninitialized.
125 
126     /** 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) {
130             // For ACTION_DEVICE_STORAGE_LOW:
131             mCachedQuotaUptimeMillis = 0;  // Force a re-check of quota size
132 
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();
146         }
147     };
148 
149     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
161         public DropBoxManager.Entry getNextEntry(String tag, long millis, String callingPackage) {
162             return DropBoxManagerService.this.getNextEntry(tag, millis, callingPackage);
163         }
164 
165         @Override
166         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
167             DropBoxManagerService.this.dump(fd, pw, args);
168         }
169 
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         }
176     };
177 
178     private class ShellCmd extends ShellCommand {
179         @Override
onCommand(String cmd)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
onHelp()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 
DropBoxManagerBroadcastHandler(Looper looper)237         DropBoxManagerBroadcastHandler(Looper looper) {
238             super(looper);
239         }
240 
241         @Override
handleMessage(Message msg)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 
prepareAndSendBroadcast(Intent intent)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 
createIntent(String tag, long time)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          */
sendBroadcast(String tag, long time)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          */
maybeDeferBroadcast(String tag, long time)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 
305     /**
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      */
DropBoxManagerService(final Context context)311     public DropBoxManagerService(final Context context) {
312         this(context, new File("/data/system/dropbox"), FgThread.get().getLooper());
313     }
314 
315     /**
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      */
322     @VisibleForTesting
DropBoxManagerService(final Context context, File path, Looper looper)323     public DropBoxManagerService(final Context context, File path, Looper looper) {
324         super(context);
325         mDropBoxDir = path;
326         mContentResolver = getContext().getContentResolver();
327         mHandler = new DropBoxManagerBroadcastHandler(looper);
328     }
329 
330     @Override
onStart()331     public void onStart() {
332         publishBinderService(Context.DROPBOX_SERVICE, mStub);
333 
334         // 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 
338     @Override
onBootPhase(int phase)339     public void onBootPhase(int phase) {
340         switch (phase) {
341             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                     });
354 
355                 getLowPriorityResourceConfigs();
356                 break;
357 
358             case PHASE_BOOT_COMPLETED:
359                 mBooted = true;
360                 break;
361         }
362     }
363 
364     /** Retrieves the binder stub -- for test instances */
getServiceStub()365     public IDropBoxManagerService getServiceStub() {
366         return mStub;
367     }
368 
add(DropBoxManager.Entry entry)369     public void add(DropBoxManager.Entry entry) {
370         File temp = null;
371         InputStream input = null;
372         OutputStream output = null;
373         final String tag = entry.getTag();
374         try {
375             int flags = entry.getFlags();
376             Slog.i(TAG, "add tag=" + tag + " isTagEnabled=" + isTagEnabled(tag)
377                     + " flags=0x" + Integer.toHexString(flags));
378             if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
379 
380             init();
381             if (!isTagEnabled(tag)) return;
382             long max = trimToFit();
383             long lastTrim = System.currentTimeMillis();
384 
385             byte[] buffer = new byte[mBlockSize];
386             input = entry.getInputStream();
387 
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");
402             int bufferSize = mBlockSize;
403             if (bufferSize > 4096) bufferSize = 4096;
404             if (bufferSize < 512) bufferSize = 512;
405             FileOutputStream foutput = new FileOutputStream(temp);
406             output = new BufferedOutputStream(foutput, bufferSize);
407             if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
408                 output = new GZIPOutputStream(output);
409                 flags = flags | DropBoxManager.IS_GZIPPED;
410             }
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) {
423                     FileUtils.sync(foutput);
424                     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) {
432                     Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > "
433                             + max + " bytes)");
434                     temp.delete();
435                     temp = null;  // Pass temp = null to createEntry() to leave a tombstone
436                     break;
437                 }
438             } while (read > 0);
439 
440             long time = createEntry(temp, tag, flags);
441             temp = null;
442 
443             // 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.
447             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             }
453         } catch (IOException e) {
454             Slog.e(TAG, "Can't write: " + tag, e);
455         } finally {
456             IoUtils.closeQuietly(output);
457             IoUtils.closeQuietly(input);
458             entry.close();
459             if (temp != null) temp.delete();
460         }
461     }
462 
isTagEnabled(String tag)463     public boolean isTagEnabled(String tag) {
464         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         }
471     }
472 
checkPermission(int callingUid, String callingPackage)473     private boolean checkPermission(int callingUid, String callingPackage) {
474         // 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 
482         // 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 
getNextEntry(String tag, long millis, String callingPackage)500     public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis,
501             String callingPackage) {
502         if (!checkPermission(Binder.getCallingUid(), callingPackage)) {
503             return null;
504         }
505 
506         try {
507             init();
508         } catch (IOException e) {
509             Slog.e(TAG, "Can't init", e);
510             return null;
511         }
512 
513         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))) {
517             if (entry.tag == null) continue;
518             if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
519                 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
520             }
521             final File file = entry.getFile(mDropBoxDir);
522             try {
523                 return new DropBoxManager.Entry(
524                         entry.tag, entry.timestampMillis, file, entry.flags);
525             } catch (IOException e) {
526                 Slog.wtf(TAG, "Can't read: " + file, e);
527                 // Continue to next file
528             }
529         }
530 
531         return null;
532     }
533 
setLowPriorityRateLimit(long period)534     private synchronized void setLowPriorityRateLimit(long period) {
535         mLowPriorityRateLimitPeriod = period;
536     }
537 
addLowPriorityTag(String tag)538     private synchronized void addLowPriorityTag(String tag) {
539         mLowPriorityTags.add(tag);
540     }
541 
removeLowPriorityTag(String tag)542     private synchronized void removeLowPriorityTag(String tag) {
543         mLowPriorityTags.remove(tag);
544     }
545 
restoreDefaults()546     private synchronized void restoreDefaults() {
547         getLowPriorityResourceConfigs();
548     }
549 
dump(FileDescriptor fd, PrintWriter pw, String[] args)550     public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
551         if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
552 
553         try {
554             init();
555         } catch (IOException e) {
556             pw.println("Can't initialize: " + e);
557             Slog.e(TAG, "Can't init", e);
558             return;
559         }
560 
561         if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
562 
563         StringBuilder out = new StringBuilder();
564         boolean doPrint = false, doFile = false;
565         boolean dumpProto = false;
566         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;
572             } else if (args[i].equals("--proto")) {
573                 dumpProto = true;
574             } 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");
580                 pw.println("    --proto: dump data to proto");
581                 pw.println("  [timestamp] optionally filters to only those entries.");
582                 return;
583             } else if (args[i].startsWith("-")) {
584                 out.append("Unknown argument: ").append(args[i]).append("\n");
585             } else {
586                 searchArgs.add(args[i]);
587             }
588         }
589 
590         if (dumpProto) {
591             dumpProtoLocked(fd, searchArgs);
592             return;
593         }
594 
595         out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
596         out.append("Max entries: ").append(mMaxFiles).append("\n");
597 
598         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 
602         if (!searchArgs.isEmpty()) {
603             out.append("Searching for:");
604             for (String a : searchArgs) out.append(" ").append(a);
605             out.append("\n");
606         }
607 
608         int numFound = 0;
609         out.append("\n");
610         for (EntryFile entry : mAllFiles.contents) {
611             if (!matchEntry(entry, searchArgs)) continue;
612 
613             numFound++;
614             if (doPrint) out.append("========================================\n");
615 
616             String date = TimeMigrationUtils.formatMillisWithFixedFormat(entry.timestampMillis);
617             out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
618 
619             final File file = entry.getFile(mDropBoxDir);
620             if (file == null) {
621                 out.append(" (no file)\n");
622                 continue;
623             } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
624                 out.append(" (contents lost)\n");
625                 continue;
626             } else {
627                 out.append(" (");
628                 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
629                 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
630                 out.append(", ").append(file.length()).append(" bytes)\n");
631             }
632 
633             if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
634                 if (!doPrint) out.append("    ");
635                 out.append(file.getPath()).append("\n");
636             }
637 
638             if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
639                 DropBoxManager.Entry dbe = null;
640                 InputStreamReader isr = null;
641                 try {
642                     dbe = new DropBoxManager.Entry(
643                              entry.tag, entry.timestampMillis, file, entry.flags);
644 
645                     if (doPrint) {
646                         isr = new InputStreamReader(dbe.getInputStream());
647                         char[] buf = new char[4096];
648                         boolean newline = false;
649                         for (;;) {
650                             int n = isr.read(buf);
651                             if (n <= 0) break;
652                             out.append(buf, 0, n);
653                             newline = (buf[n - 1] == '\n');
654 
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                             }
660                         }
661                         if (!newline) out.append("\n");
662                     } else {
663                         String text = dbe.getText(70);
664                         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                         }
672                         out.append("\n");
673                     }
674                 } catch (IOException e) {
675                     out.append("*** ").append(e.toString()).append("\n");
676                     Slog.e(TAG, "Can't read: " + file, e);
677                 } finally {
678                     if (dbe != null) dbe.close();
679                     if (isr != null) {
680                         try {
681                             isr.close();
682                         } catch (IOException unused) {
683                         }
684                     }
685                 }
686             }
687 
688             if (doPrint) out.append("\n");
689         }
690 
691         if (numFound == 0) out.append("(No entries found.)\n");
692 
693         if (args == null || args.length == 0) {
694             if (!doPrint) out.append("\n");
695             out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
696         }
697 
698         pw.write(out.toString());
699         if (PROFILE_DUMP) Debug.stopMethodTracing();
700     }
701 
matchEntry(EntryFile entry, ArrayList<String> searchArgs)702     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 
dumpProtoLocked(FileDescriptor fd, ArrayList<String> searchArgs)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 
751     ///////////////////////////////////////////////////////////////////////////
752 
753     /** Chronologically sorted list of {@link EntryFile} */
754     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. */
compareTo(FileList o)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 
768     /**
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> {
777         public final String tag;
778         public final long timestampMillis;
779         public final int flags;
780         public final int blocks;
781 
782         /** Sorts earlier EntryFile instances before later ones. */
compareTo(EntryFile o)783         public final int compareTo(EntryFile o) {
784             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());
794         }
795 
796         /**
797          * Moves an existing temporary file to a new log filename.
798          *
799          * @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
803          * @param flags for the entry data
804          * @param blockSize to use for space accounting
805          * @throws IOException if the file can't be moved
806          */
EntryFile(File temp, File dir, String tag,long timestampMillis, int flags, int blockSize)807         public EntryFile(File temp, File dir, String tag,long timestampMillis,
808                          int flags, int blockSize) throws IOException {
809             if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
810 
811             this.tag = TextUtils.safeIntern(tag);
812             this.timestampMillis = timestampMillis;
813             this.flags = flags;
814 
815             final File file = this.getFile(dir);
816             if (!temp.renameTo(file)) {
817                 throw new IOException("Can't rename " + temp + " to " + file);
818             }
819             this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
820         }
821 
822         /**
823          * Creates a zero-length tombstone for a file whose contents were lost.
824          *
825          * @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          */
EntryFile(File dir, String tag, long timestampMillis)830         public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
831             this.tag = TextUtils.safeIntern(tag);
832             this.timestampMillis = timestampMillis;
833             this.flags = DropBoxManager.IS_EMPTY;
834             this.blocks = 0;
835             new FileOutputStream(getFile(dir)).close();
836         }
837 
838         /**
839          * Extracts metadata from an existing on-disk log filename.
840          *
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          *
844          * @param file name of existing log file
845          * @param blockSize to use for space accounting
846          */
EntryFile(File file, int blockSize)847         public EntryFile(File file, int blockSize) {
848 
849             boolean parseFailure = false;
850 
851             String name = file.getName();
852             int flags = 0;
853             String tag = null;
854             long millis = 0;
855 
856             final int at = name.lastIndexOf('@');
857             if (at < 0) {
858                 parseFailure = true;
859             } else {
860                 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;
890                 this.flags = DropBoxManager.IS_EMPTY;
891                 this.timestampMillis = 0;
892                 this.blocks = 0;
893                 return;
894             }
895 
896             this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
897             this.tag = TextUtils.safeIntern(tag);
898             this.flags = flags;
899             this.timestampMillis = millis;
900         }
901 
902         /**
903          * Creates a EntryFile object with only a timestamp for comparison purposes.
904          * @param millis to compare with.
905          */
EntryFile(long millis)906         public EntryFile(long millis) {
907             this.tag = null;
908             this.timestampMillis = millis;
909             this.flags = DropBoxManager.IS_EMPTY;
910             this.blocks = 0;
911         }
912 
913         /**
914          * @return whether an entry actually has a backing file, or it's an empty "tombstone"
915          * entry.
916          */
hasFile()917         public boolean hasFile() {
918             return tag != null;
919         }
920 
921         /** @return File extension for the flags. */
getExtension()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          */
getFilename()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          */
getFile(File dir)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          */
deleteFile(File dir)949         public void deleteFile(File dir) {
950             if (hasFile()) {
951                 getFile(dir).delete();
952             }
953         }
954     }
955 
956     ///////////////////////////////////////////////////////////////////////////
957 
958     /** If never run before, scans disk contents to build in-memory tracking data. */
init()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();
977             mFilesByTag = new ArrayMap<>();
978 
979             // Scan pre-existing files.
980             for (File file : files) {
981                 if (file.getName().endsWith(".tmp")) {
982                     Slog.i(TAG, "Cleaning temp file: " + file);
983                     file.delete();
984                     continue;
985                 }
986 
987                 EntryFile entry = new EntryFile(file, mBlockSize);
988 
989                 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                 }
994             }
995         }
996     }
997 
998     /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
enrollEntry(EntryFile entry)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 
1006         if (entry.hasFile() && entry.blocks > 0) {
1007             FileList tagFiles = mFilesByTag.get(entry.tag);
1008             if (tagFiles == null) {
1009                 tagFiles = new FileList();
1010                 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
1011             }
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. */
createEntry(File temp, String tag, int flags)1018     private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
1019         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);
1040                 if (tagFiles != null && tagFiles.contents.remove(late)) {
1041                     tagFiles.blocks -= late.blocks;
1042                 }
1043                 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
1044                     enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
1045                             late.tag, t++, late.flags, mBlockSize));
1046                 } 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         }
1057         return t;
1058     }
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      */
trimToFit()1064     private synchronized long trimToFit() throws IOException {
1065         // Expunge aged items (including tombstones marking deleted data).
1066 
1067         int ageSeconds = Settings.Global.getInt(mContentResolver,
1068                 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
1069         mMaxFiles = Settings.Global.getInt(mContentResolver,
1070                 Settings.Global.DROPBOX_MAX_FILES,
1071                 (ActivityManager.isLowRamDeviceStatic()
1072                         ?  DEFAULT_MAX_FILES_LOWRAM : DEFAULT_MAX_FILES));
1073         long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
1074         while (!mAllFiles.contents.isEmpty()) {
1075             EntryFile entry = mAllFiles.contents.first();
1076             if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < mMaxFiles) {
1077                 break;
1078             }
1079 
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;
1083             entry.deleteFile(mDropBoxDir);
1084         }
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) {
1093             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);
1099 
1100             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             }
1106             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)));
1111             int maximum = quotaKb * 1024 / mBlockSize;
1112             mCachedQuotaBlocks = Math.min(maximum, maxAvailable);
1113             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,
1125         // well-behaved data streams (event statistics, profile data, etc).
1126         //
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) {
1131             // 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 {
1152                         entry.deleteFile(mDropBoxDir);
1153                         enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
1154                     } catch (IOException e) {
1155                         Slog.e(TAG, "Can't write tombstone file", e);
1156                     }
1157                 }
1158             }
1159         }
1160 
1161         return mCachedQuotaBlocks * mBlockSize;
1162     }
1163 
getLowPriorityResourceConfigs()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     }
1180 }
1181