blob: aeb3e7fd94de52b0d6fc53a713baac147b7eb13f [file] [log] [blame]
Dan Egnor4410ec82009-09-11 16:40:01 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Makoto Onuki0e623be2017-08-22 10:36:12 -070019import android.app.ActivityManager;
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -060020import android.app.AppOpsManager;
Dan Egnor4410ec82009-09-11 16:40:01 -070021import android.content.BroadcastReceiver;
22import android.content.ContentResolver;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070026import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080027import android.database.ContentObserver;
Dan Egnor4410ec82009-09-11 16:40:01 -070028import android.net.Uri;
Jeff Sharkey911d7f42013-09-05 18:11:45 -070029import android.os.Binder;
Dan Egnor3d40df32009-11-17 13:36:31 -080030import android.os.Debug;
Dan Egnorf18a01c2009-11-12 11:32:50 -080031import android.os.DropBoxManager;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -070032import android.os.FileUtils;
Doug Zongker43866e02010-01-07 12:09:54 -080033import android.os.Handler;
Makoto Onukiff94e032017-08-08 14:58:19 -070034import android.os.Looper;
Craig Mautner26caf7a2012-03-04 17:17:59 -080035import android.os.Message;
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070036import android.os.ResultReceiver;
37import android.os.ShellCallback;
38import android.os.ShellCommand;
Dan Egnor4410ec82009-09-11 16:40:01 -070039import android.os.StatFs;
40import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070041import android.os.UserHandle;
Dan Egnor4410ec82009-09-11 16:40:01 -070042import android.provider.Settings;
Makoto Onukiff94e032017-08-08 14:58:19 -070043import android.text.TextUtils;
Neil Fuller9aa7b742019-06-17 11:40:35 +010044import android.text.format.TimeMigrationUtils;
Makoto Onukiff94e032017-08-08 14:58:19 -070045import android.util.ArrayMap;
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070046import android.util.ArraySet;
Joe Onorato8a9b2202010-02-26 18:56:32 -080047import android.util.Slog;
Dan Egnor4410ec82009-09-11 16:40:01 -070048
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -070049import com.android.internal.R;
50import com.android.internal.annotations.GuardedBy;
Makoto Onukiff94e032017-08-08 14:58:19 -070051import com.android.internal.annotations.VisibleForTesting;
Dan Egnorf18a01c2009-11-12 11:32:50 -080052import com.android.internal.os.IDropBoxManagerService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060053import com.android.internal.util.DumpUtils;
Makoto Onukiff94e032017-08-08 14:58:19 -070054import com.android.internal.util.ObjectUtils;
Dan Egnor95240272009-10-27 18:23:39 -070055
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -060056import libcore.io.IoUtils;
57
Brad Fitzpatrick89647b12010-09-22 17:49:16 -070058import java.io.BufferedOutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070059import java.io.File;
60import java.io.FileDescriptor;
Dan Egnor4410ec82009-09-11 16:40:01 -070061import java.io.FileOutputStream;
62import java.io.IOException;
Dan Egnor95240272009-10-27 18:23:39 -070063import java.io.InputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070064import java.io.InputStreamReader;
65import java.io.OutputStream;
Dan Egnor4410ec82009-09-11 16:40:01 -070066import java.io.PrintWriter;
Dan Egnor4410ec82009-09-11 16:40:01 -070067import java.util.ArrayList;
Dan Egnor4410ec82009-09-11 16:40:01 -070068import java.util.SortedSet;
69import java.util.TreeSet;
70import java.util.zip.GZIPOutputStream;
71
72/**
Dan Egnorf18a01c2009-11-12 11:32:50 -080073 * Implementation of {@link IDropBoxManagerService} using the filesystem.
74 * Clients use {@link DropBoxManager} to access this service.
Dan Egnor4410ec82009-09-11 16:40:01 -070075 */
Tim Kilbourn0935f3c2015-05-28 11:48:43 -070076public final class DropBoxManagerService extends SystemService {
Dan Egnorf18a01c2009-11-12 11:32:50 -080077 private static final String TAG = "DropBoxManagerService";
Dan Egnor4410ec82009-09-11 16:40:01 -070078 private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070079 private static final int DEFAULT_MAX_FILES = 1000;
Makoto Onuki0e623be2017-08-22 10:36:12 -070080 private static final int DEFAULT_MAX_FILES_LOWRAM = 300;
Dan Egnor3a8b0c12010-03-24 17:48:20 -070081 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;
Dan Egnor4410ec82009-09-11 16:40:01 -070084 private static final int QUOTA_RESCAN_MILLIS = 5000;
85
Dan Egnor3d40df32009-11-17 13:36:31 -080086 private static final boolean PROFILE_DUMP = false;
87
Dan Egnor4410ec82009-09-11 16:40:01 -070088 // 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
Dan Egnor4410ec82009-09-11 16:40:01 -070094 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;
Makoto Onukiff94e032017-08-08 14:58:19 -0700100 private ArrayMap<String, FileList> mFilesByTag = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700101
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700102 private long mLowPriorityRateLimitPeriod = 0;
103 private ArraySet<String> mLowPriorityTags = null;
104
Dan Egnor4410ec82009-09-11 16:40:01 -0700105 // 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
Brad Fitzpatrick34165c62011-01-17 18:14:18 -0800112 private volatile boolean mBooted = false;
113
Craig Mautner26caf7a2012-03-04 17:17:59 -0800114 // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700115 private final DropBoxManagerBroadcastHandler mHandler;
Craig Mautner26caf7a2012-03-04 17:17:59 -0800116
Makoto Onuki0e623be2017-08-22 10:36:12 -0700117 private int mMaxFiles = -1; // -1 means uninitialized.
118
Dan Egnor4410ec82009-09-11 16:40:01 -0700119 /** 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) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700123 // For ACTION_DEVICE_STORAGE_LOW:
Dan Egnor4410ec82009-09-11 16:40:01 -0700124 mCachedQuotaUptimeMillis = 0; // Force a re-check of quota size
Dan Egnor3a8b0c12010-03-24 17:48:20 -0700125
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();
Dan Egnor4410ec82009-09-11 16:40:01 -0700139 }
140 };
141
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700142 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
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -0600154 public DropBoxManager.Entry getNextEntry(String tag, long millis, String callingPackage) {
155 return DropBoxManagerService.this.getNextEntry(tag, millis, callingPackage);
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700156 }
157
158 @Override
159 public void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
160 DropBoxManagerService.this.dump(fd, pw, args);
161 }
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700162
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 }
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700169 };
170
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700171 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
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700298 /**
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) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700305 this(context, new File("/data/system/dropbox"), FgThread.get().getLooper());
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700306 }
307
Dan Egnor4410ec82009-09-11 16:40:01 -0700308 /**
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 */
Makoto Onukiff94e032017-08-08 14:58:19 -0700315 @VisibleForTesting
316 public DropBoxManagerService(final Context context, File path, Looper looper) {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700317 super(context);
Dan Egnor4410ec82009-09-11 16:40:01 -0700318 mDropBoxDir = path;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700319 mContentResolver = getContext().getContentResolver();
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700320 mHandler = new DropBoxManagerBroadcastHandler(looper);
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700321 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700322
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700323 @Override
324 public void onStart() {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700325 publishBinderService(Context.DROPBOX_SERVICE, mStub);
Craig Mautner26caf7a2012-03-04 17:17:59 -0800326
Dan Egnor4410ec82009-09-11 16:40:01 -0700327 // 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
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700331 @Override
332 public void onBootPhase(int phase) {
333 switch (phase) {
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600334 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 });
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700347
348 getLowPriorityResourceConfigs();
Jeff Sharkeyd79d2032016-08-23 13:39:07 -0600349 break;
350
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700351 case PHASE_BOOT_COMPLETED:
352 mBooted = true;
353 break;
354 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700355 }
356
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700357 /** Retrieves the binder stub -- for test instances */
358 public IDropBoxManagerService getServiceStub() {
359 return mStub;
360 }
361
Dan Egnorf18a01c2009-11-12 11:32:50 -0800362 public void add(DropBoxManager.Entry entry) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700363 File temp = null;
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700364 InputStream input = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700365 OutputStream output = null;
Dan Egnor95240272009-10-27 18:23:39 -0700366 final String tag = entry.getTag();
Dan Egnor4410ec82009-09-11 16:40:01 -0700367 try {
Dan Egnor95240272009-10-27 18:23:39 -0700368 int flags = entry.getFlags();
Joe Onorato99598ee2019-02-11 15:55:13 +0000369 Slog.i(TAG, "add tag=" + tag + " isTagEnabled=" + isTagEnabled(tag)
370 + " flags=0x" + Integer.toHexString(flags));
Dan Egnorf18a01c2009-11-12 11:32:50 -0800371 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700372
373 init();
374 if (!isTagEnabled(tag)) return;
375 long max = trimToFit();
376 long lastTrim = System.currentTimeMillis();
377
378 byte[] buffer = new byte[mBlockSize];
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700379 input = entry.getInputStream();
Dan Egnor4410ec82009-09-11 16:40:01 -0700380
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");
Brad Fitzpatrick89647b12010-09-22 17:49:16 -0700395 int bufferSize = mBlockSize;
396 if (bufferSize > 4096) bufferSize = 4096;
397 if (bufferSize < 512) bufferSize = 512;
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700398 FileOutputStream foutput = new FileOutputStream(temp);
399 output = new BufferedOutputStream(foutput, bufferSize);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800400 if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700401 output = new GZIPOutputStream(output);
Dan Egnorf18a01c2009-11-12 11:32:50 -0800402 flags = flags | DropBoxManager.IS_GZIPPED;
Dan Egnor4410ec82009-09-11 16:40:01 -0700403 }
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) {
Dianne Hackborn8bdf5932010-10-15 12:54:40 -0700416 FileUtils.sync(foutput);
Dan Egnor4410ec82009-09-11 16:40:01 -0700417 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) {
Joe Onorato99598ee2019-02-11 15:55:13 +0000425 Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > "
426 + max + " bytes)");
Dan Egnor4410ec82009-09-11 16:40:01 -0700427 temp.delete();
428 temp = null; // Pass temp = null to createEntry() to leave a tombstone
429 break;
430 }
431 } while (read > 0);
432
Hakan Stillb2475362010-12-07 14:05:55 +0100433 long time = createEntry(temp, tag, flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700434 temp = null;
Hakan Stillb2475362010-12-07 14:05:55 +0100435
Craig Mautner26caf7a2012-03-04 17:17:59 -0800436 // 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.
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700440 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 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700446 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800447 Slog.e(TAG, "Can't write: " + tag, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700448 } finally {
Tim Kilbourn0935f3c2015-05-28 11:48:43 -0700449 IoUtils.closeQuietly(output);
450 IoUtils.closeQuietly(input);
Dan Egnor95240272009-10-27 18:23:39 -0700451 entry.close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700452 if (temp != null) temp.delete();
453 }
454 }
455
456 public boolean isTagEnabled(String tag) {
Jeff Sharkey911d7f42013-09-05 18:11:45 -0700457 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 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700464 }
465
Jeff Sharkeyc36c3b92018-04-19 15:22:45 -0600466 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;
Dan Egnor4410ec82009-09-11 16:40:01 -0700489 }
490
491 try {
492 init();
493 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800494 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700495 return null;
496 }
497
Dan Egnorb3b06fc2009-10-20 13:05:17 -0700498 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))) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700502 if (entry.tag == null) continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800503 if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
504 return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
Dan Egnor95240272009-10-27 18:23:39 -0700505 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700506 final File file = entry.getFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -0700507 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800508 return new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700509 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700510 } catch (IOException e) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700511 Slog.wtf(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700512 // Continue to next file
513 }
514 }
515
516 return null;
517 }
518
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700519 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
Dan Egnor4410ec82009-09-11 16:40:01 -0700535 public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -0600536 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Dan Egnor4410ec82009-09-11 16:40:01 -0700537
538 try {
539 init();
540 } catch (IOException e) {
541 pw.println("Can't initialize: " + e);
Joe Onorato8a9b2202010-02-26 18:56:32 -0800542 Slog.e(TAG, "Can't init", e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700543 return;
544 }
545
Dan Egnor3d40df32009-11-17 13:36:31 -0800546 if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
547
Dan Egnor5ec249a2009-11-25 13:16:47 -0800548 StringBuilder out = new StringBuilder();
Dan Egnor4410ec82009-09-11 16:40:01 -0700549 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;
Dianne Hackborn83b40f62017-04-26 13:59:47 -0700556 } 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;
Dan Egnor4410ec82009-09-11 16:40:01 -0700564 } else if (args[i].startsWith("-")) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800565 out.append("Unknown argument: ").append(args[i]).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700566 } else {
567 searchArgs.add(args[i]);
568 }
569 }
570
Dan Egnor5ec249a2009-11-25 13:16:47 -0800571 out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
Makoto Onuki0e623be2017-08-22 10:36:12 -0700572 out.append("Max entries: ").append(mMaxFiles).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700573
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -0700574 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
Dan Egnor4410ec82009-09-11 16:40:01 -0700578 if (!searchArgs.isEmpty()) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800579 out.append("Searching for:");
580 for (String a : searchArgs) out.append(" ").append(a);
581 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700582 }
583
Dan Egnor3d40df32009-11-17 13:36:31 -0800584 int numFound = 0, numArgs = searchArgs.size();
Dan Egnor5ec249a2009-11-25 13:16:47 -0800585 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700586 for (EntryFile entry : mAllFiles.contents) {
Neil Fuller9aa7b742019-06-17 11:40:35 +0100587 String date = TimeMigrationUtils.formatMillisWithFixedFormat(entry.timestampMillis);
Dan Egnor4410ec82009-09-11 16:40:01 -0700588 boolean match = true;
Dan Egnor3d40df32009-11-17 13:36:31 -0800589 for (int i = 0; i < numArgs && match; i++) {
590 String arg = searchArgs.get(i);
591 match = (date.contains(arg) || arg.equals(entry.tag));
592 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700593 if (!match) continue;
594
595 numFound++;
Dan Egnor42471dd2010-01-07 17:25:22 -0800596 if (doPrint) out.append("========================================\n");
Dan Egnor5ec249a2009-11-25 13:16:47 -0800597 out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
Makoto Onukiff94e032017-08-08 14:58:19 -0700598
599 final File file = entry.getFile(mDropBoxDir);
600 if (file == null) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800601 out.append(" (no file)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700602 continue;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800603 } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800604 out.append(" (contents lost)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700605 continue;
606 } else {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800607 out.append(" (");
608 if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
609 out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
Makoto Onukiff94e032017-08-08 14:58:19 -0700610 out.append(", ").append(file.length()).append(" bytes)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700611 }
612
Dan Egnorf18a01c2009-11-12 11:32:50 -0800613 if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800614 if (!doPrint) out.append(" ");
Makoto Onukiff94e032017-08-08 14:58:19 -0700615 out.append(file.getPath()).append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700616 }
617
Dan Egnorf18a01c2009-11-12 11:32:50 -0800618 if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
619 DropBoxManager.Entry dbe = null;
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800620 InputStreamReader isr = null;
Dan Egnor4410ec82009-09-11 16:40:01 -0700621 try {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800622 dbe = new DropBoxManager.Entry(
Makoto Onukiff94e032017-08-08 14:58:19 -0700623 entry.tag, entry.timestampMillis, file, entry.flags);
Dan Egnor4410ec82009-09-11 16:40:01 -0700624
625 if (doPrint) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800626 isr = new InputStreamReader(dbe.getInputStream());
Dan Egnor4410ec82009-09-11 16:40:01 -0700627 char[] buf = new char[4096];
628 boolean newline = false;
629 for (;;) {
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800630 int n = isr.read(buf);
Dan Egnor4410ec82009-09-11 16:40:01 -0700631 if (n <= 0) break;
Dan Egnor5ec249a2009-11-25 13:16:47 -0800632 out.append(buf, 0, n);
Dan Egnor4410ec82009-09-11 16:40:01 -0700633 newline = (buf[n - 1] == '\n');
Dan Egnor42471dd2010-01-07 17:25:22 -0800634
635 // Flush periodically when printing to avoid out-of-memory.
636 if (out.length() > 65536) {
637 pw.write(out.toString());
638 out.setLength(0);
639 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700640 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800641 if (!newline) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700642 } else {
643 String text = dbe.getText(70);
Jeff Sharkey22510ef2014-11-13 12:28:46 -0800644 out.append(" ");
645 if (text == null) {
646 out.append("[null]");
647 } else {
648 boolean truncated = (text.length() == 70);
649 out.append(text.trim().replace('\n', '/'));
650 if (truncated) out.append(" ...");
651 }
Dan Egnor5ec249a2009-11-25 13:16:47 -0800652 out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700653 }
654 } catch (IOException e) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800655 out.append("*** ").append(e.toString()).append("\n");
Makoto Onukiff94e032017-08-08 14:58:19 -0700656 Slog.e(TAG, "Can't read: " + file, e);
Dan Egnor4410ec82009-09-11 16:40:01 -0700657 } finally {
658 if (dbe != null) dbe.close();
Brad Fitzpatrick0c822402010-11-23 09:17:56 -0800659 if (isr != null) {
660 try {
661 isr.close();
662 } catch (IOException unused) {
663 }
664 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700665 }
666 }
667
Dan Egnor5ec249a2009-11-25 13:16:47 -0800668 if (doPrint) out.append("\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700669 }
670
Dan Egnor5ec249a2009-11-25 13:16:47 -0800671 if (numFound == 0) out.append("(No entries found.)\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700672
673 if (args == null || args.length == 0) {
Dan Egnor5ec249a2009-11-25 13:16:47 -0800674 if (!doPrint) out.append("\n");
675 out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
Dan Egnor4410ec82009-09-11 16:40:01 -0700676 }
Dan Egnor3d40df32009-11-17 13:36:31 -0800677
678 pw.write(out.toString());
679 if (PROFILE_DUMP) Debug.stopMethodTracing();
Dan Egnor4410ec82009-09-11 16:40:01 -0700680 }
681
682 ///////////////////////////////////////////////////////////////////////////
683
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700684 /** Chronologically sorted list of {@link EntryFile} */
Dan Egnor4410ec82009-09-11 16:40:01 -0700685 private static final class FileList implements Comparable<FileList> {
686 public int blocks = 0;
687 public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
688
689 /** Sorts bigger FileList instances before smaller ones. */
690 public final int compareTo(FileList o) {
691 if (blocks != o.blocks) return o.blocks - blocks;
692 if (this == o) return 0;
693 if (hashCode() < o.hashCode()) return -1;
694 if (hashCode() > o.hashCode()) return 1;
695 return 0;
696 }
697 }
698
Makoto Onukiff94e032017-08-08 14:58:19 -0700699 /**
700 * Metadata describing an on-disk log file.
701 *
702 * Note its instances do no have knowledge on what directory they're stored, just to save
703 * 4/8 bytes per instance. Instead, {@link #getFile} takes a directory so it can build a
704 * fullpath.
705 */
706 @VisibleForTesting
707 static final class EntryFile implements Comparable<EntryFile> {
Dan Egnor4410ec82009-09-11 16:40:01 -0700708 public final String tag;
709 public final long timestampMillis;
710 public final int flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700711 public final int blocks;
712
713 /** Sorts earlier EntryFile instances before later ones. */
714 public final int compareTo(EntryFile o) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700715 int comp = Long.compare(timestampMillis, o.timestampMillis);
716 if (comp != 0) return comp;
717
718 comp = ObjectUtils.compare(tag, o.tag);
719 if (comp != 0) return comp;
720
721 comp = Integer.compare(flags, o.flags);
722 if (comp != 0) return comp;
723
724 return Integer.compare(hashCode(), o.hashCode());
Dan Egnor4410ec82009-09-11 16:40:01 -0700725 }
726
727 /**
728 * Moves an existing temporary file to a new log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700729 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700730 * @param temp file to rename
731 * @param dir to store file in
732 * @param tag to use for new log file name
733 * @param timestampMillis of log entry
Dan Egnor95240272009-10-27 18:23:39 -0700734 * @param flags for the entry data
Dan Egnor4410ec82009-09-11 16:40:01 -0700735 * @param blockSize to use for space accounting
736 * @throws IOException if the file can't be moved
737 */
738 public EntryFile(File temp, File dir, String tag,long timestampMillis,
739 int flags, int blockSize) throws IOException {
Dan Egnorf18a01c2009-11-12 11:32:50 -0800740 if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
Dan Egnor4410ec82009-09-11 16:40:01 -0700741
Makoto Onukiff94e032017-08-08 14:58:19 -0700742 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700743 this.timestampMillis = timestampMillis;
744 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700745
Makoto Onukiff94e032017-08-08 14:58:19 -0700746 final File file = this.getFile(dir);
747 if (!temp.renameTo(file)) {
748 throw new IOException("Can't rename " + temp + " to " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700749 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700750 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700751 }
752
753 /**
754 * Creates a zero-length tombstone for a file whose contents were lost.
Makoto Onukiff94e032017-08-08 14:58:19 -0700755 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700756 * @param dir to store file in
757 * @param tag to use for new log file name
758 * @param timestampMillis of log entry
759 * @throws IOException if the file can't be created.
760 */
761 public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
Makoto Onukiff94e032017-08-08 14:58:19 -0700762 this.tag = TextUtils.safeIntern(tag);
Dan Egnor4410ec82009-09-11 16:40:01 -0700763 this.timestampMillis = timestampMillis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800764 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700765 this.blocks = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700766 new FileOutputStream(getFile(dir)).close();
Dan Egnor4410ec82009-09-11 16:40:01 -0700767 }
768
769 /**
770 * Extracts metadata from an existing on-disk log filename.
Makoto Onukiff94e032017-08-08 14:58:19 -0700771 *
772 * Note when a filename is not recognizable, it will create an instance that
773 * {@link #hasFile()} would return false on, and also remove the file.
774 *
Dan Egnor4410ec82009-09-11 16:40:01 -0700775 * @param file name of existing log file
776 * @param blockSize to use for space accounting
777 */
778 public EntryFile(File file, int blockSize) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700779
780 boolean parseFailure = false;
Dan Egnor4410ec82009-09-11 16:40:01 -0700781
782 String name = file.getName();
Dan Egnor4410ec82009-09-11 16:40:01 -0700783 int flags = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700784 String tag = null;
785 long millis = 0;
786
787 final int at = name.lastIndexOf('@');
788 if (at < 0) {
789 parseFailure = true;
Dan Egnor4410ec82009-09-11 16:40:01 -0700790 } else {
Makoto Onukiff94e032017-08-08 14:58:19 -0700791 tag = Uri.decode(name.substring(0, at));
792 if (name.endsWith(".gz")) {
793 flags |= DropBoxManager.IS_GZIPPED;
794 name = name.substring(0, name.length() - 3);
795 }
796 if (name.endsWith(".lost")) {
797 flags |= DropBoxManager.IS_EMPTY;
798 name = name.substring(at + 1, name.length() - 5);
799 } else if (name.endsWith(".txt")) {
800 flags |= DropBoxManager.IS_TEXT;
801 name = name.substring(at + 1, name.length() - 4);
802 } else if (name.endsWith(".dat")) {
803 name = name.substring(at + 1, name.length() - 4);
804 } else {
805 parseFailure = true;
806 }
807 if (!parseFailure) {
808 try {
809 millis = Long.parseLong(name);
810 } catch (NumberFormatException e) {
811 parseFailure = true;
812 }
813 }
814 }
815 if (parseFailure) {
816 Slog.wtf(TAG, "Invalid filename: " + file);
817
818 // Remove the file and return an empty instance.
819 file.delete();
820 this.tag = null;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800821 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700822 this.timestampMillis = 0;
Makoto Onukiff94e032017-08-08 14:58:19 -0700823 this.blocks = 0;
Dan Egnor4410ec82009-09-11 16:40:01 -0700824 return;
825 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700826
Makoto Onukiff94e032017-08-08 14:58:19 -0700827 this.blocks = (int) ((file.length() + blockSize - 1) / blockSize);
828 this.tag = TextUtils.safeIntern(tag);
829 this.flags = flags;
Dan Egnor4410ec82009-09-11 16:40:01 -0700830 this.timestampMillis = millis;
831 }
832
833 /**
834 * Creates a EntryFile object with only a timestamp for comparison purposes.
Xiaohui Chene4de5a02015-09-22 15:33:31 -0700835 * @param millis to compare with.
Dan Egnor4410ec82009-09-11 16:40:01 -0700836 */
837 public EntryFile(long millis) {
838 this.tag = null;
839 this.timestampMillis = millis;
Dan Egnorf18a01c2009-11-12 11:32:50 -0800840 this.flags = DropBoxManager.IS_EMPTY;
Dan Egnor4410ec82009-09-11 16:40:01 -0700841 this.blocks = 0;
842 }
Makoto Onukiff94e032017-08-08 14:58:19 -0700843
844 /**
845 * @return whether an entry actually has a backing file, or it's an empty "tombstone"
846 * entry.
847 */
848 public boolean hasFile() {
849 return tag != null;
850 }
851
852 /** @return File extension for the flags. */
853 private String getExtension() {
854 if ((flags & DropBoxManager.IS_EMPTY) != 0) {
855 return ".lost";
856 }
857 return ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
858 ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : "");
859 }
860
861 /**
862 * @return filename for this entry without the pathname.
863 */
864 public String getFilename() {
865 return hasFile() ? Uri.encode(tag) + "@" + timestampMillis + getExtension() : null;
866 }
867
868 /**
869 * Get a full-path {@link File} representing this entry.
870 * @param dir Parent directly. The caller needs to pass it because {@link EntryFile}s don't
871 * know in which directory they're stored.
872 */
873 public File getFile(File dir) {
874 return hasFile() ? new File(dir, getFilename()) : null;
875 }
876
877 /**
878 * If an entry has a backing file, remove it.
879 */
880 public void deleteFile(File dir) {
881 if (hasFile()) {
882 getFile(dir).delete();
883 }
884 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700885 }
886
887 ///////////////////////////////////////////////////////////////////////////
888
889 /** If never run before, scans disk contents to build in-memory tracking data. */
890 private synchronized void init() throws IOException {
891 if (mStatFs == null) {
892 if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
893 throw new IOException("Can't mkdir: " + mDropBoxDir);
894 }
895 try {
896 mStatFs = new StatFs(mDropBoxDir.getPath());
897 mBlockSize = mStatFs.getBlockSize();
898 } catch (IllegalArgumentException e) { // StatFs throws this on error
899 throw new IOException("Can't statfs: " + mDropBoxDir);
900 }
901 }
902
903 if (mAllFiles == null) {
904 File[] files = mDropBoxDir.listFiles();
905 if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
906
907 mAllFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700908 mFilesByTag = new ArrayMap<>();
Dan Egnor4410ec82009-09-11 16:40:01 -0700909
910 // Scan pre-existing files.
911 for (File file : files) {
912 if (file.getName().endsWith(".tmp")) {
Joe Onorato8a9b2202010-02-26 18:56:32 -0800913 Slog.i(TAG, "Cleaning temp file: " + file);
Dan Egnor4410ec82009-09-11 16:40:01 -0700914 file.delete();
915 continue;
916 }
917
918 EntryFile entry = new EntryFile(file, mBlockSize);
Dan Egnor4410ec82009-09-11 16:40:01 -0700919
Makoto Onukiff94e032017-08-08 14:58:19 -0700920 if (entry.hasFile()) {
921 // Enroll only when the filename is valid. Otherwise the above constructor
922 // has removed the file already.
923 enrollEntry(entry);
924 }
Dan Egnor4410ec82009-09-11 16:40:01 -0700925 }
926 }
927 }
928
929 /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
930 private synchronized void enrollEntry(EntryFile entry) {
931 mAllFiles.contents.add(entry);
932 mAllFiles.blocks += entry.blocks;
933
934 // mFilesByTag is used for trimming, so don't list empty files.
935 // (Zero-length/lost files are trimmed by date from mAllFiles.)
936
Makoto Onukiff94e032017-08-08 14:58:19 -0700937 if (entry.hasFile() && entry.blocks > 0) {
Dan Egnor4410ec82009-09-11 16:40:01 -0700938 FileList tagFiles = mFilesByTag.get(entry.tag);
939 if (tagFiles == null) {
940 tagFiles = new FileList();
Makoto Onukiff94e032017-08-08 14:58:19 -0700941 mFilesByTag.put(TextUtils.safeIntern(entry.tag), tagFiles);
Dan Egnor4410ec82009-09-11 16:40:01 -0700942 }
943 tagFiles.contents.add(entry);
944 tagFiles.blocks += entry.blocks;
945 }
946 }
947
948 /** Moves a temporary file to a final log filename and enrolls it. */
Hakan Stillb2475362010-12-07 14:05:55 +0100949 private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700950 long t = System.currentTimeMillis();
951
952 // Require each entry to have a unique timestamp; if there are entries
953 // >10sec in the future (due to clock skew), drag them back to avoid
954 // keeping them around forever.
955
956 SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
957 EntryFile[] future = null;
958 if (!tail.isEmpty()) {
959 future = tail.toArray(new EntryFile[tail.size()]);
960 tail.clear(); // Remove from mAllFiles
961 }
962
963 if (!mAllFiles.contents.isEmpty()) {
964 t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
965 }
966
967 if (future != null) {
968 for (EntryFile late : future) {
969 mAllFiles.blocks -= late.blocks;
970 FileList tagFiles = mFilesByTag.get(late.tag);
Dan Egnorf283e362010-03-10 16:49:55 -0800971 if (tagFiles != null && tagFiles.contents.remove(late)) {
972 tagFiles.blocks -= late.blocks;
973 }
Dan Egnorf18a01c2009-11-12 11:32:50 -0800974 if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
Makoto Onukiff94e032017-08-08 14:58:19 -0700975 enrollEntry(new EntryFile(late.getFile(mDropBoxDir), mDropBoxDir,
976 late.tag, t++, late.flags, mBlockSize));
Dan Egnor4410ec82009-09-11 16:40:01 -0700977 } else {
978 enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
979 }
980 }
981 }
982
983 if (temp == null) {
984 enrollEntry(new EntryFile(mDropBoxDir, tag, t));
985 } else {
986 enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
987 }
Hakan Stillb2475362010-12-07 14:05:55 +0100988 return t;
Dan Egnor4410ec82009-09-11 16:40:01 -0700989 }
990
991 /**
992 * Trims the files on disk to make sure they aren't using too much space.
993 * @return the overall quota for storage (in bytes)
994 */
songjinshic5e249b2016-07-27 20:36:46 +0800995 private synchronized long trimToFit() throws IOException {
Dan Egnor4410ec82009-09-11 16:40:01 -0700996 // Expunge aged items (including tombstones marking deleted data).
997
Jeff Sharkey625239a2012-09-26 22:03:49 -0700998 int ageSeconds = Settings.Global.getInt(mContentResolver,
999 Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
Makoto Onuki0e623be2017-08-22 10:36:12 -07001000 mMaxFiles = Settings.Global.getInt(mContentResolver,
1001 Settings.Global.DROPBOX_MAX_FILES,
1002 (ActivityManager.isLowRamDeviceStatic()
1003 ? DEFAULT_MAX_FILES_LOWRAM : DEFAULT_MAX_FILES));
Dan Egnor4410ec82009-09-11 16:40:01 -07001004 long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
1005 while (!mAllFiles.contents.isEmpty()) {
1006 EntryFile entry = mAllFiles.contents.first();
Makoto Onuki0e623be2017-08-22 10:36:12 -07001007 if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < mMaxFiles) {
1008 break;
1009 }
Dan Egnor4410ec82009-09-11 16:40:01 -07001010
1011 FileList tag = mFilesByTag.get(entry.tag);
1012 if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
1013 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
Makoto Onukiff94e032017-08-08 14:58:19 -07001014 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -07001015 }
1016
1017 // Compute overall quota (a fraction of available free space) in blocks.
1018 // The quota changes dynamically based on the amount of free space;
1019 // that way when lots of data is available we can use it, but we'll get
1020 // out of the way if storage starts getting tight.
1021
1022 long uptimeMillis = SystemClock.uptimeMillis();
1023 if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
Jeff Sharkey625239a2012-09-26 22:03:49 -07001024 int quotaPercent = Settings.Global.getInt(mContentResolver,
1025 Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
1026 int reservePercent = Settings.Global.getInt(mContentResolver,
1027 Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
1028 int quotaKb = Settings.Global.getInt(mContentResolver,
1029 Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
Dan Egnor4410ec82009-09-11 16:40:01 -07001030
songjinshic5e249b2016-07-27 20:36:46 +08001031 String dirPath = mDropBoxDir.getPath();
1032 try {
1033 mStatFs.restat(dirPath);
1034 } catch (IllegalArgumentException e) { // restat throws this on error
1035 throw new IOException("Can't restat: " + mDropBoxDir);
1036 }
Dmytro Chystiakovcbb50002019-04-28 17:06:36 -07001037 long available = mStatFs.getAvailableBlocksLong();
1038 long nonreserved = available - mStatFs.getBlockCountLong() * reservePercent / 100;
1039 long maxAvailableLong = nonreserved * quotaPercent / 100;
1040 int maxAvailable = Math.toIntExact(Math.max(0,
1041 Math.min(maxAvailableLong, Integer.MAX_VALUE)));
Dan Egnor4410ec82009-09-11 16:40:01 -07001042 int maximum = quotaKb * 1024 / mBlockSize;
Dmytro Chystiakovcbb50002019-04-28 17:06:36 -07001043 mCachedQuotaBlocks = Math.min(maximum, maxAvailable);
Dan Egnor4410ec82009-09-11 16:40:01 -07001044 mCachedQuotaUptimeMillis = uptimeMillis;
1045 }
1046
1047 // If we're using too much space, delete old items to make room.
1048 //
1049 // We trim each tag independently (this is why we keep per-tag lists).
1050 // Space is "fairly" shared between tags -- they are all squeezed
1051 // equally until enough space is reclaimed.
1052 //
1053 // A single circular buffer (a la logcat) would be simpler, but this
1054 // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
1055 // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
Dan Egnor3a8b0c12010-03-24 17:48:20 -07001056 // well-behaved data streams (event statistics, profile data, etc).
Dan Egnor4410ec82009-09-11 16:40:01 -07001057 //
1058 // Deleted files are replaced with zero-length tombstones to mark what
1059 // was lost. Tombstones are expunged by age (see above).
1060
1061 if (mAllFiles.blocks > mCachedQuotaBlocks) {
Dan Egnor4410ec82009-09-11 16:40:01 -07001062 // Find a fair share amount of space to limit each tag
1063 int unsqueezed = mAllFiles.blocks, squeezed = 0;
1064 TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
1065 for (FileList tag : tags) {
1066 if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
1067 break;
1068 }
1069 unsqueezed -= tag.blocks;
1070 squeezed++;
1071 }
1072 int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
1073
1074 // Remove old items from each tag until it meets the per-tag quota.
1075 for (FileList tag : tags) {
1076 if (mAllFiles.blocks < mCachedQuotaBlocks) break;
1077 while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
1078 EntryFile entry = tag.contents.first();
1079 if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
1080 if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
1081
1082 try {
Makoto Onukiff94e032017-08-08 14:58:19 -07001083 entry.deleteFile(mDropBoxDir);
Dan Egnor4410ec82009-09-11 16:40:01 -07001084 enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
1085 } catch (IOException e) {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001086 Slog.e(TAG, "Can't write tombstone file", e);
Dan Egnor4410ec82009-09-11 16:40:01 -07001087 }
1088 }
1089 }
1090 }
1091
1092 return mCachedQuotaBlocks * mBlockSize;
1093 }
Michael Wachenschwanzfd6523e2019-03-20 23:16:20 -07001094
1095 private void getLowPriorityResourceConfigs() {
1096 mLowPriorityRateLimitPeriod = Resources.getSystem().getInteger(
1097 R.integer.config_dropboxLowPriorityBroadcastRateLimitPeriod);
1098
1099 final String[] lowPrioritytags = Resources.getSystem().getStringArray(
1100 R.array.config_dropboxLowPriorityTags);
1101 final int size = lowPrioritytags.length;
1102 if (size == 0) {
1103 mLowPriorityTags = null;
1104 return;
1105 }
1106 mLowPriorityTags = new ArraySet(size);
1107 for (int i = 0; i < size; i++) {
1108 mLowPriorityTags.add(lowPrioritytags[i]);
1109 }
1110 }
Dan Egnor4410ec82009-09-11 16:40:01 -07001111}