Home | History | Annotate | Download | only in server
      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.Time;
     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
    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
    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 
    230         DropBoxManagerBroadcastHandler(Looper looper) {
    231             super(looper);
    232         }
    233 
    234         @Override
    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 
    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 
    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          */
    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          */
    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      */
    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
    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
    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
    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 */
    358     public IDropBoxManagerService getServiceStub() {
    359         return mStub;
    360     }
    361 
    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 
    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 
    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 
    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 
    519     private synchronized void setLowPriorityRateLimit(long period) {
    520         mLowPriorityRateLimitPeriod = period;
    521     }
    522 
    523     private synchronized void addLowPriorityTag(String tag) {
    524         mLowPriorityTags.add(tag);
    525     }
    526 
    527     private synchronized void removeLowPriorityTag(String tag) {
    528         mLowPriorityTags.remove(tag);
    529     }
    530 
    531     private synchronized void restoreDefaults() {
    532         getLowPriorityResourceConfigs();
    533     }
    534 
    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         Time time = new Time();
    586         out.append("\n");
    587         for (EntryFile entry : mAllFiles.contents) {
    588             time.set(entry.timestampMillis);
    589             String date = time.format("%Y-%m-%d %H:%M:%S");
    590             boolean match = true;
    591             for (int i = 0; i < numArgs && match; i++) {
    592                 String arg = searchArgs.get(i);
    593                 match = (date.contains(arg) || arg.equals(entry.tag));
    594             }
    595             if (!match) continue;
    596 
    597             numFound++;
    598             if (doPrint) out.append("========================================\n");
    599             out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
    600 
    601             final File file = entry.getFile(mDropBoxDir);
    602             if (file == null) {
    603                 out.append(" (no file)\n");
    604                 continue;
    605             } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
    606                 out.append(" (contents lost)\n");
    607                 continue;
    608             } else {
    609                 out.append(" (");
    610                 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
    611                 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
    612                 out.append(", ").append(file.length()).append(" bytes)\n");
    613             }
    614 
    615             if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
    616                 if (!doPrint) out.append("    ");
    617                 out.append(file.getPath()).append("\n");
    618             }
    619 
    620             if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
    621                 DropBoxManager.Entry dbe = null;
    622                 InputStreamReader isr = null;
    623                 try {
    624                     dbe = new DropBoxManager.Entry(
    625                              entry.tag, entry.timestampMillis, file, entry.flags);
    626 
    627                     if (doPrint) {
    628                         isr = new InputStreamReader(dbe.getInputStream());
    629                         char[] buf = new char[4096];
    630                         boolean newline = false;
    631                         for (;;) {
    632                             int n = isr.read(buf);
    633                             if (n <= 0) break;
    634                             out.append(buf, 0, n);
    635                             newline = (buf[n - 1] == '\n');
    636 
    637                             // Flush periodically when printing to avoid out-of-memory.
    638                             if (out.length() > 65536) {
    639                                 pw.write(out.toString());
    640                                 out.setLength(0);
    641                             }
    642                         }
    643                         if (!newline) out.append("\n");
    644                     } else {
    645                         String text = dbe.getText(70);
    646                         out.append("    ");
    647                         if (text == null) {
    648                             out.append("[null]");
    649                         } else {
    650                             boolean truncated = (text.length() == 70);
    651                             out.append(text.trim().replace('\n', '/'));
    652                             if (truncated) out.append(" ...");
    653                         }
    654                         out.append("\n");
    655                     }
    656                 } catch (IOException e) {
    657                     out.append("*** ").append(e.toString()).append("\n");
    658                     Slog.e(TAG, "Can't read: " + file, e);
    659                 } finally {
    660                     if (dbe != null) dbe.close();
    661                     if (isr != null) {
    662                         try {
    663                             isr.close();
    664                         } catch (IOException unused) {
    665                         }
    666                     }
    667                 }
    668             }
    669 
    670             if (doPrint) out.append("\n");
    671         }
    672 
    673         if (numFound == 0) out.append("(No entries found.)\n");
    674 
    675         if (args == null || args.length == 0) {
    676             if (!doPrint) out.append("\n");
    677             out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
    678         }
    679 
    680         pw.write(out.toString());
    681         if (PROFILE_DUMP) Debug.stopMethodTracing();
    682     }
    683 
    684     ///////////////////////////////////////////////////////////////////////////
    685 
    686     /** Chronologically sorted list of {@link EntryFile} */
    687     private static final class FileList implements Comparable<FileList> {
    688         public int blocks = 0;
    689         public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
    690 
    691         /** Sorts bigger FileList instances before smaller ones. */
    692         public final int compareTo(FileList o) {
    693             if (blocks != o.blocks) return o.blocks - blocks;
    694             if (this == o) return 0;
    695             if (hashCode() < o.hashCode()) return -1;
    696             if (hashCode() > o.hashCode()) return 1;
    697             return 0;
    698         }
    699     }
    700 
    701     /**
    702      * Metadata describing an on-disk log file.
    703      *
    704      * Note its instances do no have knowledge on what directory they're stored, just to save
    705      * 4/8 bytes per instance.  Instead, {@link #getFile} takes a directory so it can build a
    706      * fullpath.
    707      */
    708     @VisibleForTesting
    709     static final class EntryFile implements Comparable<EntryFile> {
    710         public final String tag;
    711         public final long timestampMillis;
    712         public final int flags;
    713         public final int blocks;
    714 
    715         /** Sorts earlier EntryFile instances before later ones. */
    716         public final int compareTo(EntryFile o) {
    717             int comp = Long.compare(timestampMillis, o.timestampMillis);
    718             if (comp != 0) return comp;
    719 
    720             comp = ObjectUtils.compare(tag, o.tag);
    721             if (comp != 0) return comp;
    722 
    723             comp = Integer.compare(flags, o.flags);
    724             if (comp != 0) return comp;
    725 
    726             return Integer.compare(hashCode(), o.hashCode());
    727         }
    728 
    729         /**
    730          * Moves an existing temporary file to a new log filename.
    731          *
    732          * @param temp file to rename
    733          * @param dir to store file in
    734          * @param tag to use for new log file name
    735          * @param timestampMillis of log entry
    736          * @param flags for the entry data
    737          * @param blockSize to use for space accounting
    738          * @throws IOException if the file can't be moved
    739          */
    740         public EntryFile(File temp, File dir, String tag,long timestampMillis,
    741                          int flags, int blockSize) throws IOException {
    742             if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
    743 
    744             this.tag = TextUtils.safeIntern(tag);
    745             this.timestampMillis = timestampMillis;
    746             this.flags = flags;
    747 
    748             final File file = this.getFile(dir);
    749             if (!temp.renameTo(file)) {
    750                 throw new IOException("Can't rename " + temp + " to " + file);
    751             }
    752             this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
    753         }
    754 
    755         /**
    756          * Creates a zero-length tombstone for a file whose contents were lost.
    757          *
    758          * @param dir to store file in
    759          * @param tag to use for new log file name
    760          * @param timestampMillis of log entry
    761          * @throws IOException if the file can't be created.
    762          */
    763         public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
    764             this.tag = TextUtils.safeIntern(tag);
    765             this.timestampMillis = timestampMillis;
    766             this.flags = DropBoxManager.IS_EMPTY;
    767             this.blocks = 0;
    768             new FileOutputStream(getFile(dir)).close();
    769         }
    770 
    771         /**
    772          * Extracts metadata from an existing on-disk log filename.
    773          *
    774          * Note when a filename is not recognizable, it will create an instance that
    775          * {@link #hasFile()} would return false on, and also remove the file.
    776          *
    777          * @param file name of existing log file
    778          * @param blockSize to use for space accounting
    779          */
    780         public EntryFile(File file, int blockSize) {
    781 
    782             boolean parseFailure = false;
    783 
    784             String name = file.getName();
    785             int flags = 0;
    786             String tag = null;
    787             long millis = 0;
    788 
    789             final int at = name.lastIndexOf('@');
    790             if (at < 0) {
    791                 parseFailure = true;
    792             } else {
    793                 tag = Uri.decode(name.substring(0, at));
    794                 if (name.endsWith(".gz")) {
    795                     flags |= DropBoxManager.IS_GZIPPED;
    796                     name = name.substring(0, name.length() - 3);
    797                 }
    798                 if (name.endsWith(".lost")) {
    799                     flags |= DropBoxManager.IS_EMPTY;
    800                     name = name.substring(at + 1, name.length() - 5);
    801                 } else if (name.endsWith(".txt")) {
    802                     flags |= DropBoxManager.IS_TEXT;
    803                     name = name.substring(at + 1, name.length() - 4);
    804                 } else if (name.endsWith(".dat")) {
    805                     name = name.substring(at + 1, name.length() - 4);
    806                 } else {
    807                     parseFailure = true;
    808                 }
    809                 if (!parseFailure) {
    810                     try {
    811                         millis = Long.parseLong(name);
    812                     } catch (NumberFormatException e) {
    813                         parseFailure = true;
    814                     }
    815                 }
    816             }
    817             if (parseFailure) {
    818                 Slog.wtf(TAG, "Invalid filename: " + file);
    819 
    820                 // Remove the file and return an empty instance.
    821                 file.delete();
    822                 this.tag = null;
    823                 this.flags = DropBoxManager.IS_EMPTY;
    824                 this.timestampMillis = 0;
    825                 this.blocks = 0;
    826                 return;
    827             }
    828 
    829             this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
    830             this.tag = TextUtils.safeIntern(tag);
    831             this.flags = flags;
    832             this.timestampMillis = millis;
    833         }
    834 
    835         /**
    836          * Creates a EntryFile object with only a timestamp for comparison purposes.
    837          * @param millis to compare with.
    838          */
    839         public EntryFile(long millis) {
    840             this.tag = null;
    841             this.timestampMillis = millis;
    842             this.flags = DropBoxManager.IS_EMPTY;
    843             this.blocks = 0;
    844         }
    845 
    846         /**
    847          * @return whether an entry actually has a backing file, or it's an empty "tombstone"
    848          * entry.
    849          */
    850         public boolean hasFile() {
    851             return tag != null;
    852         }
    853 
    854         /** @return File extension for the flags. */
    855         private String getExtension() {
    856             if ((flags &  DropBoxManager.IS_EMPTY) != 0) {
    857                 return ".lost";
    858             }
    859             return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
    860                     ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
    861         }
    862 
    863         /**
    864          * @return filename for this entry without the pathname.
    865          */
    866         public String getFilename() {
    867             return hasFile() ? Uri.encode(tag) + "@" + timestampMillis + getExtension() : null;
    868         }
    869 
    870         /**
    871          * Get a full-path {@link File} representing this entry.
    872          * @param dir Parent directly.  The caller needs to pass it because {@link EntryFile}s don't
    873          *            know in which directory they're stored.
    874          */
    875         public File getFile(File dir) {
    876             return hasFile() ? new File(dir, getFilename()) : null;
    877         }
    878 
    879         /**
    880          * If an entry has a backing file, remove it.
    881          */
    882         public void deleteFile(File dir) {
    883             if (hasFile()) {
    884                 getFile(dir).delete();
    885             }
    886         }
    887     }
    888 
    889     ///////////////////////////////////////////////////////////////////////////
    890 
    891     /** If never run before, scans disk contents to build in-memory tracking data. */
    892     private synchronized void init() throws IOException {
    893         if (mStatFs == null) {
    894             if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
    895                 throw new IOException("Can't mkdir: " + mDropBoxDir);
    896             }
    897             try {
    898                 mStatFs = new StatFs(mDropBoxDir.getPath());
    899                 mBlockSize = mStatFs.getBlockSize();
    900             } catch (IllegalArgumentException e) {  // StatFs throws this on error
    901                 throw new IOException("Can't statfs: " + mDropBoxDir);
    902             }
    903         }
    904 
    905         if (mAllFiles == null) {
    906             File[] files = mDropBoxDir.listFiles();
    907             if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
    908 
    909             mAllFiles = new FileList();
    910             mFilesByTag = new ArrayMap<>();
    911 
    912             // Scan pre-existing files.
    913             for (File file : files) {
    914                 if (file.getName().endsWith(".tmp")) {
    915                     Slog.i(TAG, "Cleaning temp file: " + file);
    916                     file.delete();
    917                     continue;
    918                 }
    919 
    920                 EntryFile entry = new EntryFile(file, mBlockSize);
    921 
    922                 if (entry.hasFile()) {
    923                     // Enroll only when the filename is valid.  Otherwise the above constructor
    924                     // has removed the file already.
    925                     enrollEntry(entry);
    926                 }
    927             }
    928         }
    929     }
    930 
    931     /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
    932     private synchronized void enrollEntry(EntryFile entry) {
    933         mAllFiles.contents.add(entry);
    934         mAllFiles.blocks += entry.blocks;
    935 
    936         // mFilesByTag is used for trimming, so don't list empty files.
    937         // (Zero-length/lost files are trimmed by date from mAllFiles.)
    938 
    939         if (entry.hasFile() && entry.blocks > 0) {
    940             FileList tagFiles = mFilesByTag.get(entry.tag);
    941             if (tagFiles == null) {
    942                 tagFiles = new FileList();
    943                 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
    944             }
    945             tagFiles.contents.add(entry);
    946             tagFiles.blocks += entry.blocks;
    947         }
    948     }
    949 
    950     /** Moves a temporary file to a final log filename and enrolls it. */
    951     private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
    952         long t = System.currentTimeMillis();
    953 
    954         // Require each entry to have a unique timestamp; if there are entries
    955         // >10sec in the future (due to clock skew), drag them back to avoid
    956         // keeping them around forever.
    957 
    958         SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
    959         EntryFile[] future = null;
    960         if (!tail.isEmpty()) {
    961             future = tail.toArray(new EntryFile[tail.size()]);
    962             tail.clear();  // Remove from mAllFiles
    963         }
    964 
    965         if (!mAllFiles.contents.isEmpty()) {
    966             t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
    967         }
    968 
    969         if (future != null) {
    970             for (EntryFile late : future) {
    971                 mAllFiles.blocks -= late.blocks;
    972                 FileList tagFiles = mFilesByTag.get(late.tag);
    973                 if (tagFiles != null && tagFiles.contents.remove(late)) {
    974                     tagFiles.blocks -= late.blocks;
    975                 }
    976                 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
    977                     enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
    978                             late.tag, t++, late.flags, mBlockSize));
    979                 } else {
    980                     enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
    981                 }
    982             }
    983         }
    984 
    985         if (temp == null) {
    986             enrollEntry(new EntryFile(mDropBoxDir, tag, t));
    987         } else {
    988             enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
    989         }
    990         return t;
    991     }
    992 
    993     /**
    994      * Trims the files on disk to make sure they aren't using too much space.
    995      * @return the overall quota for storage (in bytes)
    996      */
    997     private synchronized long trimToFit() throws IOException {
    998         // Expunge aged items (including tombstones marking deleted data).
    999 
   1000         int ageSeconds = Settings.Global.getInt(mContentResolver,
   1001                 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
   1002         mMaxFiles = Settings.Global.getInt(mContentResolver,
   1003                 Settings.Global.DROPBOX_MAX_FILES,
   1004                 (ActivityManager.isLowRamDeviceStatic()
   1005                         ?  DEFAULT_MAX_FILES_LOWRAM : DEFAULT_MAX_FILES));
   1006         long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
   1007         while (!mAllFiles.contents.isEmpty()) {
   1008             EntryFile entry = mAllFiles.contents.first();
   1009             if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < mMaxFiles) {
   1010                 break;
   1011             }
   1012 
   1013             FileList tag = mFilesByTag.get(entry.tag);
   1014             if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
   1015             if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
   1016             entry.deleteFile(mDropBoxDir);
   1017         }
   1018 
   1019         // Compute overall quota (a fraction of available free space) in blocks.
   1020         // The quota changes dynamically based on the amount of free space;
   1021         // that way when lots of data is available we can use it, but we'll get
   1022         // out of the way if storage starts getting tight.
   1023 
   1024         long uptimeMillis = SystemClock.uptimeMillis();
   1025         if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
   1026             int quotaPercent = Settings.Global.getInt(mContentResolver,
   1027                     Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
   1028             int reservePercent = Settings.Global.getInt(mContentResolver,
   1029                     Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
   1030             int quotaKb = Settings.Global.getInt(mContentResolver,
   1031                     Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
   1032 
   1033             String dirPath = mDropBoxDir.getPath();
   1034             try {
   1035                 mStatFs.restat(dirPath);
   1036             } catch (IllegalArgumentException e) {  // restat throws this on error
   1037                 throw new IOException("Can't restat: " + mDropBoxDir);
   1038             }
   1039             int available = mStatFs.getAvailableBlocks();
   1040             int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
   1041             int maximum = quotaKb * 1024 / mBlockSize;
   1042             mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
   1043             mCachedQuotaUptimeMillis = uptimeMillis;
   1044         }
   1045 
   1046         // If we're using too much space, delete old items to make room.
   1047         //
   1048         // We trim each tag independently (this is why we keep per-tag lists).
   1049         // Space is "fairly" shared between tags -- they are all squeezed
   1050         // equally until enough space is reclaimed.
   1051         //
   1052         // A single circular buffer (a la logcat) would be simpler, but this
   1053         // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
   1054         // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
   1055         // well-behaved data streams (event statistics, profile data, etc).
   1056         //
   1057         // Deleted files are replaced with zero-length tombstones to mark what
   1058         // was lost.  Tombstones are expunged by age (see above).
   1059 
   1060         if (mAllFiles.blocks > mCachedQuotaBlocks) {
   1061             // Find a fair share amount of space to limit each tag
   1062             int unsqueezed = mAllFiles.blocks, squeezed = 0;
   1063             TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
   1064             for (FileList tag : tags) {
   1065                 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
   1066                     break;
   1067                 }
   1068                 unsqueezed -= tag.blocks;
   1069                 squeezed++;
   1070             }
   1071             int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
   1072 
   1073             // Remove old items from each tag until it meets the per-tag quota.
   1074             for (FileList tag : tags) {
   1075                 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
   1076                 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
   1077                     EntryFile entry = tag.contents.first();
   1078                     if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
   1079                     if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
   1080 
   1081                     try {
   1082                         entry.deleteFile(mDropBoxDir);
   1083                         enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
   1084                     } catch (IOException e) {
   1085                         Slog.e(TAG, "Can't write tombstone file", e);
   1086                     }
   1087                 }
   1088             }
   1089         }
   1090 
   1091         return mCachedQuotaBlocks * mBlockSize;
   1092     }
   1093 
   1094     private void getLowPriorityResourceConfigs() {
   1095         mLowPriorityRateLimitPeriod = Resources.getSystem().getInteger(
   1096                 R.integer.config_dropboxLowPriorityBroadcastRateLimitPeriod);
   1097 
   1098         final String[] lowPrioritytags = Resources.getSystem().getStringArray(
   1099                 R.array.config_dropboxLowPriorityTags);
   1100         final int size = lowPrioritytags.length;
   1101         if (size == 0) {
   1102             mLowPriorityTags = null;
   1103             return;
   1104         }
   1105         mLowPriorityTags = new ArraySet(size);
   1106         for (int i = 0; i < size; i++) {
   1107             mLowPriorityTags.add(lowPrioritytags[i]);
   1108         }
   1109     }
   1110 }
   1111