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.res.Resources;
27 import android.database.ContentObserver;
28 import android.net.Uri;
29 import android.os.Binder;
30 import android.os.Debug;
31 import android.os.DropBoxManager;
32 import android.os.FileUtils;
33 import android.os.Handler;
34 import android.os.Looper;
35 import android.os.Message;
36 import android.os.ResultReceiver;
37 import android.os.ShellCallback;
38 import android.os.ShellCommand;
39 import android.os.StatFs;
40 import android.os.SystemClock;
41 import android.os.UserHandle;
42 import android.provider.Settings;
43 import android.text.TextUtils;
44 import android.text.format.TimeMigrationUtils;
45 import android.util.ArrayMap;
46 import android.util.ArraySet;
47 import android.util.Slog;
48 
49 import com.android.internal.R;
50 import com.android.internal.annotations.GuardedBy;
51 import com.android.internal.annotations.VisibleForTesting;
52 import com.android.internal.os.IDropBoxManagerService;
53 import com.android.internal.util.DumpUtils;
54 import com.android.internal.util.ObjectUtils;
55 
56 import libcore.io.IoUtils;
57 
58 import java.io.BufferedOutputStream;
59 import java.io.File;
60 import java.io.FileDescriptor;
61 import java.io.FileOutputStream;
62 import java.io.IOException;
63 import java.io.InputStream;
64 import java.io.InputStreamReader;
65 import java.io.OutputStream;
66 import java.io.PrintWriter;
67 import java.util.ArrayList;
68 import java.util.SortedSet;
69 import java.util.TreeSet;
70 import java.util.zip.GZIPOutputStream;
71 
72 /**
73  * Implementation of {@link IDropBoxManagerService} using the filesystem.
74  * Clients use {@link DropBoxManager} to access this service.
75  */
76 public final class DropBoxManagerService extends SystemService {
77     private static final String TAG = "DropBoxManagerService";
78     private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
79     private static final int DEFAULT_MAX_FILES = 1000;
80     private static final int DEFAULT_MAX_FILES_LOWRAM = 300;
81     private static final int DEFAULT_QUOTA_KB = 5 * 1024;
82     private static final int DEFAULT_QUOTA_PERCENT = 10;
83     private static final int DEFAULT_RESERVE_PERCENT = 10;
84     private static final int QUOTA_RESCAN_MILLIS = 5000;
85 
86     private static final boolean PROFILE_DUMP = false;
87 
88     // TODO: This implementation currently uses one file per entry, which is
89     // inefficient for smallish entries -- consider using a single queue file
90     // per tag (or even globally) instead.
91 
92     // The cached context and derived objects
93 
94     private final ContentResolver mContentResolver;
95     private final File mDropBoxDir;
96 
97     // Accounting of all currently written log files (set in init()).
98 
99     private FileList mAllFiles = null;
100     private ArrayMap<String, FileList> mFilesByTag = null;
101 
102     private long mLowPriorityRateLimitPeriod = 0;
103     private ArraySet<String> mLowPriorityTags = null;
104 
105     // Various bits of disk information
106 
107     private StatFs mStatFs = null;
108     private int mBlockSize = 0;
109     private int mCachedQuotaBlocks = 0;  // Space we can use: computed from free space, etc.
110     private long mCachedQuotaUptimeMillis = 0;
111 
112     private volatile boolean mBooted = false;
113 
114     // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
115     private final DropBoxManagerBroadcastHandler mHandler;
116 
117     private int mMaxFiles = -1; // -1 means uninitialized.
118 
119     /** Receives events that might indicate a need to clean up files. */
120     private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
121         @Override
122         public void onReceive(Context context, Intent intent) {
123             // For ACTION_DEVICE_STORAGE_LOW:
124             mCachedQuotaUptimeMillis = 0;  // Force a re-check of quota size
125 
126             // Run the initialization in the background (not this main thread).
127             // The init() and trimToFit() methods are synchronized, so they still
128             // block other users -- but at least the onReceive() call can finish.
129             new Thread() {
130                 public void run() {
131                     try {
132                         init();
133                         trimToFit();
134                     } catch (IOException e) {
135                         Slog.e(TAG, "Can't init", e);
136                     }
137                 }
138             }.start();
139         }
140     };
141 
142     private final IDropBoxManagerService.Stub mStub = new IDropBoxManagerService.Stub() {
143         @Override
144         public void add(DropBoxManager.Entry entry) {
145             DropBoxManagerService.this.add(entry);
146         }
147 
148         @Override
149         public boolean isTagEnabled(String tag) {
150             return DropBoxManagerService.this.isTagEnabled(tag);
151         }
152 
153         @Override
154         public DropBoxManager.Entry getNextEntry(String tag, long millis, String callingPackage) {
155             return DropBoxManagerService.this.getNextEntry(tag, millis, callingPackage);
156         }
157 
158         @Override
159         public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
160             DropBoxManagerService.this.dump(fd, pw, args);
161         }
162 
163         @Override
164         public void onShellCommand(FileDescriptor in, FileDescriptor out,
165                                    FileDescriptor err, String[] args, ShellCallback callback,
166                                    ResultReceiver resultReceiver) {
167             (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
168         }
169     };
170 
171     private class ShellCmd extends ShellCommand {
172         @Override
onCommand(String cmd)173         public int onCommand(String cmd) {
174             if (cmd == null) {
175                 return handleDefaultCommands(cmd);
176             }
177             final PrintWriter pw = getOutPrintWriter();
178             try {
179                 switch (cmd) {
180                     case "set-rate-limit":
181                         final long period = Long.parseLong(getNextArgRequired());
182                         DropBoxManagerService.this.setLowPriorityRateLimit(period);
183                         break;
184                     case "add-low-priority":
185                         final String addedTag = getNextArgRequired();
186                         DropBoxManagerService.this.addLowPriorityTag(addedTag);
187                         break;
188                     case "remove-low-priority":
189                         final String removeTag = getNextArgRequired();
190                         DropBoxManagerService.this.removeLowPriorityTag(removeTag);
191                         break;
192                     case "restore-defaults":
193                         DropBoxManagerService.this.restoreDefaults();
194                         break;
195                     default:
196                         return handleDefaultCommands(cmd);
197                 }
198             } catch (Exception e) {
199                 pw.println(e);
200             }
201             return 0;
202         }
203 
204         @Override
onHelp()205         public void onHelp() {
206             PrintWriter pw = getOutPrintWriter();
207             pw.println("Dropbox manager service commands:");
208             pw.println("  help");
209             pw.println("    Print this help text.");
210             pw.println("  set-rate-limit PERIOD");
211             pw.println("    Sets low priority broadcast rate limit period to PERIOD ms");
212             pw.println("  add-low-priority TAG");
213             pw.println("    Add TAG to dropbox low priority list");
214             pw.println("  remove-low-priority TAG");
215             pw.println("    Remove TAG from dropbox low priority list");
216             pw.println("  restore-defaults");
217             pw.println("    restore dropbox settings to defaults");
218         }
219     }
220 
221     private class DropBoxManagerBroadcastHandler extends Handler {
222         private final Object mLock = new Object();
223 
224         static final int MSG_SEND_BROADCAST = 1;
225         static final int MSG_SEND_DEFERRED_BROADCAST = 2;
226 
227         @GuardedBy("mLock")
228         private final ArrayMap<String, Intent> mDeferredMap = new ArrayMap();
229 
DropBoxManagerBroadcastHandler(Looper looper)230         DropBoxManagerBroadcastHandler(Looper looper) {
231             super(looper);
232         }
233 
234         @Override
handleMessage(Message msg)235         public void handleMessage(Message msg) {
236             switch (msg.what) {
237                 case MSG_SEND_BROADCAST:
238                     prepareAndSendBroadcast((Intent) msg.obj);
239                     break;
240                 case MSG_SEND_DEFERRED_BROADCAST:
241                     Intent deferredIntent;
242                     synchronized (mLock) {
243                         deferredIntent = mDeferredMap.remove((String) msg.obj);
244                     }
245                     if (deferredIntent != null) {
246                         prepareAndSendBroadcast(deferredIntent);
247                     }
248                     break;
249             }
250         }
251 
prepareAndSendBroadcast(Intent intent)252         private void prepareAndSendBroadcast(Intent intent) {
253             if (!DropBoxManagerService.this.mBooted) {
254                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
255             }
256             getContext().sendBroadcastAsUser(intent, UserHandle.SYSTEM,
257                     android.Manifest.permission.READ_LOGS);
258         }
259 
createIntent(String tag, long time)260         private Intent createIntent(String tag, long time) {
261             final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
262             dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
263             dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
264             return dropboxIntent;
265         }
266 
267         /**
268          * Schedule a dropbox broadcast to be sent asynchronously.
269          */
sendBroadcast(String tag, long time)270         public void sendBroadcast(String tag, long time) {
271             sendMessage(obtainMessage(MSG_SEND_BROADCAST, createIntent(tag, time)));
272         }
273 
274         /**
275          * Possibly schedule a delayed dropbox broadcast. The broadcast will only be scheduled if
276          * no broadcast is currently scheduled. Otherwise updated the scheduled broadcast with the
277          * new intent information, effectively dropping the previous broadcast.
278          */
maybeDeferBroadcast(String tag, long time)279         public void maybeDeferBroadcast(String tag, long time) {
280             synchronized (mLock) {
281                 final Intent intent = mDeferredMap.get(tag);
282                 if (intent == null) {
283                     // Schedule new delayed broadcast.
284                     mDeferredMap.put(tag, createIntent(tag, time));
285                     sendMessageDelayed(obtainMessage(MSG_SEND_DEFERRED_BROADCAST, tag),
286                             mLowPriorityRateLimitPeriod);
287                 } else {
288                     // Broadcast is already scheduled. Update intent with new data.
289                     intent.putExtra(DropBoxManager.EXTRA_TIME, time);
290                     final int dropped = intent.getIntExtra(DropBoxManager.EXTRA_DROPPED_COUNT, 0);
291                     intent.putExtra(DropBoxManager.EXTRA_DROPPED_COUNT, dropped + 1);
292                     return;
293                 }
294             }
295         }
296     }
297 
298     /**
299      * Creates an instance of managed drop box storage using the default dropbox
300      * directory.
301      *
302      * @param context to use for receiving free space & gservices intents
303      */
DropBoxManagerService(final Context context)304     public DropBoxManagerService(final Context context) {
305         this(context, new File("/data/system/dropbox"), FgThread.get().getLooper());
306     }
307 
308     /**
309      * Creates an instance of managed drop box storage.  Normally there is one of these
310      * run by the system, but others can be created for testing and other purposes.
311      *
312      * @param context to use for receiving free space & gservices intents
313      * @param path to store drop box entries in
314      */
315     @VisibleForTesting
DropBoxManagerService(final Context context, File path, Looper looper)316     public DropBoxManagerService(final Context context, File path, Looper looper) {
317         super(context);
318         mDropBoxDir = path;
319         mContentResolver = getContext().getContentResolver();
320         mHandler = new DropBoxManagerBroadcastHandler(looper);
321     }
322 
323     @Override
onStart()324     public void onStart() {
325         publishBinderService(Context.DROPBOX_SERVICE, mStub);
326 
327         // The real work gets done lazily in init() -- that way service creation always
328         // succeeds, and things like disk problems cause individual method failures.
329     }
330 
331     @Override
onBootPhase(int phase)332     public void onBootPhase(int phase) {
333         switch (phase) {
334             case PHASE_SYSTEM_SERVICES_READY:
335                 IntentFilter filter = new IntentFilter();
336                 filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
337                 getContext().registerReceiver(mReceiver, filter);
338 
339                 mContentResolver.registerContentObserver(
340                     Settings.Global.CONTENT_URI, true,
341                     new ContentObserver(new Handler()) {
342                         @Override
343                         public void onChange(boolean selfChange) {
344                             mReceiver.onReceive(getContext(), (Intent) null);
345                         }
346                     });
347 
348                 getLowPriorityResourceConfigs();
349                 break;
350 
351             case PHASE_BOOT_COMPLETED:
352                 mBooted = true;
353                 break;
354         }
355     }
356 
357     /** Retrieves the binder stub -- for test instances */
getServiceStub()358     public IDropBoxManagerService getServiceStub() {
359         return mStub;
360     }
361 
add(DropBoxManager.Entry entry)362     public void add(DropBoxManager.Entry entry) {
363         File temp = null;
364         InputStream input = null;
365         OutputStream output = null;
366         final String tag = entry.getTag();
367         try {
368             int flags = entry.getFlags();
369             Slog.i(TAG, "add tag=" + tag + " isTagEnabled=" + isTagEnabled(tag)
370                     + " flags=0x" + Integer.toHexString(flags));
371             if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
372 
373             init();
374             if (!isTagEnabled(tag)) return;
375             long max = trimToFit();
376             long lastTrim = System.currentTimeMillis();
377 
378             byte[] buffer = new byte[mBlockSize];
379             input = entry.getInputStream();
380 
381             // First, accumulate up to one block worth of data in memory before
382             // deciding whether to compress the data or not.
383 
384             int read = 0;
385             while (read < buffer.length) {
386                 int n = input.read(buffer, read, buffer.length - read);
387                 if (n <= 0) break;
388                 read += n;
389             }
390 
391             // If we have at least one block, compress it -- otherwise, just write
392             // the data in uncompressed form.
393 
394             temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
395             int bufferSize = mBlockSize;
396             if (bufferSize > 4096) bufferSize = 4096;
397             if (bufferSize < 512) bufferSize = 512;
398             FileOutputStream foutput = new FileOutputStream(temp);
399             output = new BufferedOutputStream(foutput, bufferSize);
400             if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
401                 output = new GZIPOutputStream(output);
402                 flags = flags | DropBoxManager.IS_GZIPPED;
403             }
404 
405             do {
406                 output.write(buffer, 0, read);
407 
408                 long now = System.currentTimeMillis();
409                 if (now - lastTrim > 30 * 1000) {
410                     max = trimToFit();  // In case data dribbles in slowly
411                     lastTrim = now;
412                 }
413 
414                 read = input.read(buffer);
415                 if (read <= 0) {
416                     FileUtils.sync(foutput);
417                     output.close();  // Get a final size measurement
418                     output = null;
419                 } else {
420                     output.flush();  // So the size measurement is pseudo-reasonable
421                 }
422 
423                 long len = temp.length();
424                 if (len > max) {
425                     Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > "
426                             + max + " bytes)");
427                     temp.delete();
428                     temp = null;  // Pass temp = null to createEntry() to leave a tombstone
429                     break;
430                 }
431             } while (read > 0);
432 
433             long time = createEntry(temp, tag, flags);
434             temp = null;
435 
436             // Call sendBroadcast after returning from this call to avoid deadlock. In particular
437             // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
438             // lock in ActivityManagerService. ActivityManagerService has been caught holding that
439             // very lock while waiting for the WindowManagerService lock.
440             if (mLowPriorityTags != null && mLowPriorityTags.contains(tag)) {
441                 // Rate limit low priority Dropbox entries
442                 mHandler.maybeDeferBroadcast(tag, time);
443             } else {
444                 mHandler.sendBroadcast(tag, time);
445             }
446         } catch (IOException e) {
447             Slog.e(TAG, "Can't write: " + tag, e);
448         } finally {
449             IoUtils.closeQuietly(output);
450             IoUtils.closeQuietly(input);
451             entry.close();
452             if (temp != null) temp.delete();
453         }
454     }
455 
isTagEnabled(String tag)456     public boolean isTagEnabled(String tag) {
457         final long token = Binder.clearCallingIdentity();
458         try {
459             return !"disabled".equals(Settings.Global.getString(
460                     mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
461         } finally {
462             Binder.restoreCallingIdentity(token);
463         }
464     }
465 
checkPermission(int callingUid, String callingPackage)466     private boolean checkPermission(int callingUid, String callingPackage) {
467         // Callers always need this permission
468         getContext().enforceCallingOrSelfPermission(
469                 android.Manifest.permission.READ_LOGS, TAG);
470 
471         // Callers also need the ability to read usage statistics
472         switch (getContext().getSystemService(AppOpsManager.class)
473                 .noteOp(AppOpsManager.OP_GET_USAGE_STATS, callingUid, callingPackage)) {
474             case AppOpsManager.MODE_ALLOWED:
475                 return true;
476             case AppOpsManager.MODE_DEFAULT:
477                 getContext().enforceCallingOrSelfPermission(
478                         android.Manifest.permission.PACKAGE_USAGE_STATS, TAG);
479                 return true;
480             default:
481                 return false;
482         }
483     }
484 
getNextEntry(String tag, long millis, String callingPackage)485     public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis,
486             String callingPackage) {
487         if (!checkPermission(Binder.getCallingUid(), callingPackage)) {
488             return null;
489         }
490 
491         try {
492             init();
493         } catch (IOException e) {
494             Slog.e(TAG, "Can't init", e);
495             return null;
496         }
497 
498         FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
499         if (list == null) return null;
500 
501         for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
502             if (entry.tag == null) continue;
503             if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
504                 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
505             }
506             final File file = entry.getFile(mDropBoxDir);
507             try {
508                 return new DropBoxManager.Entry(
509                         entry.tag, entry.timestampMillis, file, entry.flags);
510             } catch (IOException e) {
511                 Slog.wtf(TAG, "Can't read: " + file, e);
512                 // Continue to next file
513             }
514         }
515 
516         return null;
517     }
518 
setLowPriorityRateLimit(long period)519     private synchronized void setLowPriorityRateLimit(long period) {
520         mLowPriorityRateLimitPeriod = period;
521     }
522 
addLowPriorityTag(String tag)523     private synchronized void addLowPriorityTag(String tag) {
524         mLowPriorityTags.add(tag);
525     }
526 
removeLowPriorityTag(String tag)527     private synchronized void removeLowPriorityTag(String tag) {
528         mLowPriorityTags.remove(tag);
529     }
530 
restoreDefaults()531     private synchronized void restoreDefaults() {
532         getLowPriorityResourceConfigs();
533     }
534 
dump(FileDescriptor fd, PrintWriter pw, String[] args)535     public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
536         if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
537 
538         try {
539             init();
540         } catch (IOException e) {
541             pw.println("Can't initialize: " + e);
542             Slog.e(TAG, "Can't init", e);
543             return;
544         }
545 
546         if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
547 
548         StringBuilder out = new StringBuilder();
549         boolean doPrint = false, doFile = false;
550         ArrayList<String> searchArgs = new ArrayList<String>();
551         for (int i = 0; args != null && i < args.length; i++) {
552             if (args[i].equals("-p") || args[i].equals("--print")) {
553                 doPrint = true;
554             } else if (args[i].equals("-f") || args[i].equals("--file")) {
555                 doFile = true;
556             } else if (args[i].equals("-h") || args[i].equals("--help")) {
557                 pw.println("Dropbox (dropbox) dump options:");
558                 pw.println("  [-h|--help] [-p|--print] [-f|--file] [timestamp]");
559                 pw.println("    -h|--help: print this help");
560                 pw.println("    -p|--print: print full contents of each entry");
561                 pw.println("    -f|--file: print path of each entry's file");
562                 pw.println("  [timestamp] optionally filters to only those entries.");
563                 return;
564             } else if (args[i].startsWith("-")) {
565                 out.append("Unknown argument: ").append(args[i]).append("\n");
566             } else {
567                 searchArgs.add(args[i]);
568             }
569         }
570 
571         out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
572         out.append("Max entries: ").append(mMaxFiles).append("\n");
573 
574         out.append("Low priority rate limit period: ");
575         out.append(mLowPriorityRateLimitPeriod).append(" ms\n");
576         out.append("Low priority tags: ").append(mLowPriorityTags).append("\n");
577 
578         if (!searchArgs.isEmpty()) {
579             out.append("Searching for:");
580             for (String a : searchArgs) out.append(" ").append(a);
581             out.append("\n");
582         }
583 
584         int numFound = 0, numArgs = searchArgs.size();
585         out.append("\n");
586         for (EntryFile entry : mAllFiles.contents) {
587             String date = TimeMigrationUtils.formatMillisWithFixedFormat(entry.timestampMillis);
588             boolean match = true;
589             for (int i = 0; i < numArgs && match; i++) {
590                 String arg = searchArgs.get(i);
591                 match = (date.contains(arg) || arg.equals(entry.tag));
592             }
593             if (!match) continue;
594 
595             numFound++;
596             if (doPrint) out.append("========================================\n");
597             out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
598 
599             final File file = entry.getFile(mDropBoxDir);
600             if (file == null) {
601                 out.append(" (no file)\n");
602                 continue;
603             } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
604                 out.append(" (contents lost)\n");
605                 continue;
606             } else {
607                 out.append(" (");
608                 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
609                 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
610                 out.append(", ").append(file.length()).append(" bytes)\n");
611             }
612 
613             if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
614                 if (!doPrint) out.append("    ");
615                 out.append(file.getPath()).append("\n");
616             }
617 
618             if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
619                 DropBoxManager.Entry dbe = null;
620                 InputStreamReader isr = null;
621                 try {
622                     dbe = new DropBoxManager.Entry(
623                              entry.tag, entry.timestampMillis, file, entry.flags);
624 
625                     if (doPrint) {
626                         isr = new InputStreamReader(dbe.getInputStream());
627                         char[] buf = new char[4096];
628                         boolean newline = false;
629                         for (;;) {
630                             int n = isr.read(buf);
631                             if (n <= 0) break;
632                             out.append(buf, 0, n);
633                             newline = (buf[n - 1] == '\n');
634 
635                             // Flush periodically when printing to avoid out-of-memory.
636                             if (out.length() > 65536) {
637                                 pw.write(out.toString());
638                                 out.setLength(0);
639                             }
640                         }
641                         if (!newline) out.append("\n");
642                     } else {
643                         String text = dbe.getText(70);
644                         out.append("    ");
645                         if (text == null) {
646                             out.append("[null]");
647                         } else {
648                             boolean truncated = (text.length() == 70);
649                             out.append(text.trim().replace('\n', '/'));
650                             if (truncated) out.append(" ...");
651                         }
652                         out.append("\n");
653                     }
654                 } catch (IOException e) {
655                     out.append("*** ").append(e.toString()).append("\n");
656                     Slog.e(TAG, "Can't read: " + file, e);
657                 } finally {
658                     if (dbe != null) dbe.close();
659                     if (isr != null) {
660                         try {
661                             isr.close();
662                         } catch (IOException unused) {
663                         }
664                     }
665                 }
666             }
667 
668             if (doPrint) out.append("\n");
669         }
670 
671         if (numFound == 0) out.append("(No entries found.)\n");
672 
673         if (args == null || args.length == 0) {
674             if (!doPrint) out.append("\n");
675             out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
676         }
677 
678         pw.write(out.toString());
679         if (PROFILE_DUMP) Debug.stopMethodTracing();
680     }
681 
682     ///////////////////////////////////////////////////////////////////////////
683 
684     /** Chronologically sorted list of {@link EntryFile} */
685     private static final class FileList implements Comparable<FileList> {
686         public int blocks = 0;
687         public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
688 
689         /** Sorts bigger FileList instances before smaller ones. */
compareTo(FileList o)690         public final int compareTo(FileList o) {
691             if (blocks != o.blocks) return o.blocks - blocks;
692             if (this == o) return 0;
693             if (hashCode() < o.hashCode()) return -1;
694             if (hashCode() > o.hashCode()) return 1;
695             return 0;
696         }
697     }
698 
699     /**
700      * Metadata describing an on-disk log file.
701      *
702      * Note its instances do no have knowledge on what directory they're stored, just to save
703      * 4/8 bytes per instance.  Instead, {@link #getFile} takes a directory so it can build a
704      * fullpath.
705      */
706     @VisibleForTesting
707     static final class EntryFile implements Comparable<EntryFile> {
708         public final String tag;
709         public final long timestampMillis;
710         public final int flags;
711         public final int blocks;
712 
713         /** Sorts earlier EntryFile instances before later ones. */
compareTo(EntryFile o)714         public final int compareTo(EntryFile o) {
715             int comp = Long.compare(timestampMillis, o.timestampMillis);
716             if (comp != 0) return comp;
717 
718             comp = ObjectUtils.compare(tag, o.tag);
719             if (comp != 0) return comp;
720 
721             comp = Integer.compare(flags, o.flags);
722             if (comp != 0) return comp;
723 
724             return Integer.compare(hashCode(), o.hashCode());
725         }
726 
727         /**
728          * Moves an existing temporary file to a new log filename.
729          *
730          * @param temp file to rename
731          * @param dir to store file in
732          * @param tag to use for new log file name
733          * @param timestampMillis of log entry
734          * @param flags for the entry data
735          * @param blockSize to use for space accounting
736          * @throws IOException if the file can't be moved
737          */
EntryFile(File temp, File dir, String tag,long timestampMillis, int flags, int blockSize)738         public EntryFile(File temp, File dir, String tag,long timestampMillis,
739                          int flags, int blockSize) throws IOException {
740             if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
741 
742             this.tag = TextUtils.safeIntern(tag);
743             this.timestampMillis = timestampMillis;
744             this.flags = flags;
745 
746             final File file = this.getFile(dir);
747             if (!temp.renameTo(file)) {
748                 throw new IOException("Can't rename " + temp + " to " + file);
749             }
750             this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
751         }
752 
753         /**
754          * Creates a zero-length tombstone for a file whose contents were lost.
755          *
756          * @param dir to store file in
757          * @param tag to use for new log file name
758          * @param timestampMillis of log entry
759          * @throws IOException if the file can't be created.
760          */
EntryFile(File dir, String tag, long timestampMillis)761         public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
762             this.tag = TextUtils.safeIntern(tag);
763             this.timestampMillis = timestampMillis;
764             this.flags = DropBoxManager.IS_EMPTY;
765             this.blocks = 0;
766             new FileOutputStream(getFile(dir)).close();
767         }
768 
769         /**
770          * Extracts metadata from an existing on-disk log filename.
771          *
772          * Note when a filename is not recognizable, it will create an instance that
773          * {@link #hasFile()} would return false on, and also remove the file.
774          *
775          * @param file name of existing log file
776          * @param blockSize to use for space accounting
777          */
EntryFile(File file, int blockSize)778         public EntryFile(File file, int blockSize) {
779 
780             boolean parseFailure = false;
781 
782             String name = file.getName();
783             int flags = 0;
784             String tag = null;
785             long millis = 0;
786 
787             final int at = name.lastIndexOf('@');
788             if (at < 0) {
789                 parseFailure = true;
790             } else {
791                 tag = Uri.decode(name.substring(0, at));
792                 if (name.endsWith(".gz")) {
793                     flags |= DropBoxManager.IS_GZIPPED;
794                     name = name.substring(0, name.length() - 3);
795                 }
796                 if (name.endsWith(".lost")) {
797                     flags |= DropBoxManager.IS_EMPTY;
798                     name = name.substring(at + 1, name.length() - 5);
799                 } else if (name.endsWith(".txt")) {
800                     flags |= DropBoxManager.IS_TEXT;
801                     name = name.substring(at + 1, name.length() - 4);
802                 } else if (name.endsWith(".dat")) {
803                     name = name.substring(at + 1, name.length() - 4);
804                 } else {
805                     parseFailure = true;
806                 }
807                 if (!parseFailure) {
808                     try {
809                         millis = Long.parseLong(name);
810                     } catch (NumberFormatException e) {
811                         parseFailure = true;
812                     }
813                 }
814             }
815             if (parseFailure) {
816                 Slog.wtf(TAG, "Invalid filename: " + file);
817 
818                 // Remove the file and return an empty instance.
819                 file.delete();
820                 this.tag = null;
821                 this.flags = DropBoxManager.IS_EMPTY;
822                 this.timestampMillis = 0;
823                 this.blocks = 0;
824                 return;
825             }
826 
827             this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
828             this.tag = TextUtils.safeIntern(tag);
829             this.flags = flags;
830             this.timestampMillis = millis;
831         }
832 
833         /**
834          * Creates a EntryFile object with only a timestamp for comparison purposes.
835          * @param millis to compare with.
836          */
EntryFile(long millis)837         public EntryFile(long millis) {
838             this.tag = null;
839             this.timestampMillis = millis;
840             this.flags = DropBoxManager.IS_EMPTY;
841             this.blocks = 0;
842         }
843 
844         /**
845          * @return whether an entry actually has a backing file, or it's an empty "tombstone"
846          * entry.
847          */
hasFile()848         public boolean hasFile() {
849             return tag != null;
850         }
851 
852         /** @return File extension for the flags. */
getExtension()853         private String getExtension() {
854             if ((flags &  DropBoxManager.IS_EMPTY) != 0) {
855                 return ".lost";
856             }
857             return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
858                     ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
859         }
860 
861         /**
862          * @return filename for this entry without the pathname.
863          */
getFilename()864         public String getFilename() {
865             return hasFile() ? Uri.encode(tag) + "@" + timestampMillis + getExtension() : null;
866         }
867 
868         /**
869          * Get a full-path {@link File} representing this entry.
870          * @param dir Parent directly.  The caller needs to pass it because {@link EntryFile}s don't
871          *            know in which directory they're stored.
872          */
getFile(File dir)873         public File getFile(File dir) {
874             return hasFile() ? new File(dir, getFilename()) : null;
875         }
876 
877         /**
878          * If an entry has a backing file, remove it.
879          */
deleteFile(File dir)880         public void deleteFile(File dir) {
881             if (hasFile()) {
882                 getFile(dir).delete();
883             }
884         }
885     }
886 
887     ///////////////////////////////////////////////////////////////////////////
888 
889     /** If never run before, scans disk contents to build in-memory tracking data. */
init()890     private synchronized void init() throws IOException {
891         if (mStatFs == null) {
892             if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
893                 throw new IOException("Can't mkdir: " + mDropBoxDir);
894             }
895             try {
896                 mStatFs = new StatFs(mDropBoxDir.getPath());
897                 mBlockSize = mStatFs.getBlockSize();
898             } catch (IllegalArgumentException e) {  // StatFs throws this on error
899                 throw new IOException("Can't statfs: " + mDropBoxDir);
900             }
901         }
902 
903         if (mAllFiles == null) {
904             File[] files = mDropBoxDir.listFiles();
905             if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
906 
907             mAllFiles = new FileList();
908             mFilesByTag = new ArrayMap<>();
909 
910             // Scan pre-existing files.
911             for (File file : files) {
912                 if (file.getName().endsWith(".tmp")) {
913                     Slog.i(TAG, "Cleaning temp file: " + file);
914                     file.delete();
915                     continue;
916                 }
917 
918                 EntryFile entry = new EntryFile(file, mBlockSize);
919 
920                 if (entry.hasFile()) {
921                     // Enroll only when the filename is valid.  Otherwise the above constructor
922                     // has removed the file already.
923                     enrollEntry(entry);
924                 }
925             }
926         }
927     }
928 
929     /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
enrollEntry(EntryFile entry)930     private synchronized void enrollEntry(EntryFile entry) {
931         mAllFiles.contents.add(entry);
932         mAllFiles.blocks += entry.blocks;
933 
934         // mFilesByTag is used for trimming, so don't list empty files.
935         // (Zero-length/lost files are trimmed by date from mAllFiles.)
936 
937         if (entry.hasFile() && entry.blocks > 0) {
938             FileList tagFiles = mFilesByTag.get(entry.tag);
939             if (tagFiles == null) {
940                 tagFiles = new FileList();
941                 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
942             }
943             tagFiles.contents.add(entry);
944             tagFiles.blocks += entry.blocks;
945         }
946     }
947 
948     /** Moves a temporary file to a final log filename and enrolls it. */
createEntry(File temp, String tag, int flags)949     private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
950         long t = System.currentTimeMillis();
951 
952         // Require each entry to have a unique timestamp; if there are entries
953         // >10sec in the future (due to clock skew), drag them back to avoid
954         // keeping them around forever.
955 
956         SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
957         EntryFile[] future = null;
958         if (!tail.isEmpty()) {
959             future = tail.toArray(new EntryFile[tail.size()]);
960             tail.clear();  // Remove from mAllFiles
961         }
962 
963         if (!mAllFiles.contents.isEmpty()) {
964             t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
965         }
966 
967         if (future != null) {
968             for (EntryFile late : future) {
969                 mAllFiles.blocks -= late.blocks;
970                 FileList tagFiles = mFilesByTag.get(late.tag);
971                 if (tagFiles != null && tagFiles.contents.remove(late)) {
972                     tagFiles.blocks -= late.blocks;
973                 }
974                 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
975                     enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
976                             late.tag, t++, late.flags, mBlockSize));
977                 } else {
978                     enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
979                 }
980             }
981         }
982 
983         if (temp == null) {
984             enrollEntry(new EntryFile(mDropBoxDir, tag, t));
985         } else {
986             enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
987         }
988         return t;
989     }
990 
991     /**
992      * Trims the files on disk to make sure they aren't using too much space.
993      * @return the overall quota for storage (in bytes)
994      */
trimToFit()995     private synchronized long trimToFit() throws IOException {
996         // Expunge aged items (including tombstones marking deleted data).
997 
998         int ageSeconds = Settings.Global.getInt(mContentResolver,
999                 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
1000         mMaxFiles = Settings.Global.getInt(mContentResolver,
1001                 Settings.Global.DROPBOX_MAX_FILES,
1002                 (ActivityManager.isLowRamDeviceStatic()
1003                         ?  DEFAULT_MAX_FILES_LOWRAM : DEFAULT_MAX_FILES));
1004         long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
1005         while (!mAllFiles.contents.isEmpty()) {
1006             EntryFile entry = mAllFiles.contents.first();
1007             if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < mMaxFiles) {
1008                 break;
1009             }
1010 
1011             FileList tag = mFilesByTag.get(entry.tag);
1012             if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
1013             if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
1014             entry.deleteFile(mDropBoxDir);
1015         }
1016 
1017         // Compute overall quota (a fraction of available free space) in blocks.
1018         // The quota changes dynamically based on the amount of free space;
1019         // that way when lots of data is available we can use it, but we'll get
1020         // out of the way if storage starts getting tight.
1021 
1022         long uptimeMillis = SystemClock.uptimeMillis();
1023         if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
1024             int quotaPercent = Settings.Global.getInt(mContentResolver,
1025                     Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
1026             int reservePercent = Settings.Global.getInt(mContentResolver,
1027                     Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
1028             int quotaKb = Settings.Global.getInt(mContentResolver,
1029                     Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
1030 
1031             String dirPath = mDropBoxDir.getPath();
1032             try {
1033                 mStatFs.restat(dirPath);
1034             } catch (IllegalArgumentException e) {  // restat throws this on error
1035                 throw new IOException("Can't restat: " + mDropBoxDir);
1036             }
1037             long available = mStatFs.getAvailableBlocksLong();
1038             long nonreserved = available - mStatFs.getBlockCountLong() * reservePercent / 100;
1039             long maxAvailableLong = nonreserved * quotaPercent / 100;
1040             int maxAvailable = Math.toIntExact(Math.max(0,
1041                     Math.min(maxAvailableLong, Integer.MAX_VALUE)));
1042             int maximum = quotaKb * 1024 / mBlockSize;
1043             mCachedQuotaBlocks = Math.min(maximum, maxAvailable);
1044             mCachedQuotaUptimeMillis = uptimeMillis;
1045         }
1046 
1047         // If we're using too much space, delete old items to make room.
1048         //
1049         // We trim each tag independently (this is why we keep per-tag lists).
1050         // Space is "fairly" shared between tags -- they are all squeezed
1051         // equally until enough space is reclaimed.
1052         //
1053         // A single circular buffer (a la logcat) would be simpler, but this
1054         // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
1055         // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
1056         // well-behaved data streams (event statistics, profile data, etc).
1057         //
1058         // Deleted files are replaced with zero-length tombstones to mark what
1059         // was lost.  Tombstones are expunged by age (see above).
1060 
1061         if (mAllFiles.blocks > mCachedQuotaBlocks) {
1062             // Find a fair share amount of space to limit each tag
1063             int unsqueezed = mAllFiles.blocks, squeezed = 0;
1064             TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
1065             for (FileList tag : tags) {
1066                 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
1067                     break;
1068                 }
1069                 unsqueezed -= tag.blocks;
1070                 squeezed++;
1071             }
1072             int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
1073 
1074             // Remove old items from each tag until it meets the per-tag quota.
1075             for (FileList tag : tags) {
1076                 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
1077                 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
1078                     EntryFile entry = tag.contents.first();
1079                     if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
1080                     if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
1081 
1082                     try {
1083                         entry.deleteFile(mDropBoxDir);
1084                         enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
1085                     } catch (IOException e) {
1086                         Slog.e(TAG, "Can't write tombstone file", e);
1087                     }
1088                 }
1089             }
1090         }
1091 
1092         return mCachedQuotaBlocks * mBlockSize;
1093     }
1094 
getLowPriorityResourceConfigs()1095     private void getLowPriorityResourceConfigs() {
1096         mLowPriorityRateLimitPeriod = Resources.getSystem().getInteger(
1097                 R.integer.config_dropboxLowPriorityBroadcastRateLimitPeriod);
1098 
1099         final String[] lowPrioritytags = Resources.getSystem().getStringArray(
1100                 R.array.config_dropboxLowPriorityTags);
1101         final int size = lowPrioritytags.length;
1102         if (size == 0) {
1103             mLowPriorityTags = null;
1104             return;
1105         }
1106         mLowPriorityTags = new ArraySet(size);
1107         for (int i = 0; i < size; i++) {
1108             mLowPriorityTags.add(lowPrioritytags[i]);
1109         }
1110     }
1111 }
1112