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