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
17package com.android.server;
18
19import android.content.BroadcastReceiver;
20import android.content.ContentResolver;
21import android.content.Context;
22import android.content.Intent;
23import android.content.IntentFilter;
24import android.content.pm.PackageManager;
25import android.database.ContentObserver;
26import android.net.Uri;
27import android.os.Debug;
28import android.os.DropBoxManager;
29import android.os.FileUtils;
30import android.os.Handler;
31import android.os.Message;
32import android.os.StatFs;
33import android.os.SystemClock;
34import android.os.UserHandle;
35import android.provider.Settings;
36import android.text.format.Time;
37import android.util.Slog;
38
39import com.android.internal.os.IDropBoxManagerService;
40
41import java.io.BufferedOutputStream;
42import java.io.File;
43import java.io.FileDescriptor;
44import java.io.FileOutputStream;
45import java.io.IOException;
46import java.io.InputStream;
47import java.io.InputStreamReader;
48import java.io.OutputStream;
49import java.io.PrintWriter;
50import java.util.ArrayList;
51import java.util.HashMap;
52import java.util.SortedSet;
53import java.util.TreeSet;
54import java.util.zip.GZIPOutputStream;
55
56/**
57 * Implementation of {@link IDropBoxManagerService} using the filesystem.
58 * Clients use {@link DropBoxManager} to access this service.
59 */
60public final class DropBoxManagerService extends IDropBoxManagerService.Stub {
61    private static final String TAG = "DropBoxManagerService";
62    private static final int DEFAULT_AGE_SECONDS = 3 * 86400;
63    private static final int DEFAULT_MAX_FILES = 1000;
64    private static final int DEFAULT_QUOTA_KB = 5 * 1024;
65    private static final int DEFAULT_QUOTA_PERCENT = 10;
66    private static final int DEFAULT_RESERVE_PERCENT = 10;
67    private static final int QUOTA_RESCAN_MILLIS = 5000;
68
69    // mHandler 'what' value.
70    private static final int MSG_SEND_BROADCAST = 1;
71
72    private static final boolean PROFILE_DUMP = false;
73
74    // TODO: This implementation currently uses one file per entry, which is
75    // inefficient for smallish entries -- consider using a single queue file
76    // per tag (or even globally) instead.
77
78    // The cached context and derived objects
79
80    private final Context mContext;
81    private final ContentResolver mContentResolver;
82    private final File mDropBoxDir;
83
84    // Accounting of all currently written log files (set in init()).
85
86    private FileList mAllFiles = null;
87    private HashMap<String, FileList> mFilesByTag = null;
88
89    // Various bits of disk information
90
91    private StatFs mStatFs = null;
92    private int mBlockSize = 0;
93    private int mCachedQuotaBlocks = 0;  // Space we can use: computed from free space, etc.
94    private long mCachedQuotaUptimeMillis = 0;
95
96    private volatile boolean mBooted = false;
97
98    // Provide a way to perform sendBroadcast asynchronously to avoid deadlocks.
99    private final Handler mHandler;
100
101    /** Receives events that might indicate a need to clean up files. */
102    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
103        @Override
104        public void onReceive(Context context, Intent intent) {
105            if (intent != null && Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
106                mBooted = true;
107                return;
108            }
109
110            // Else, for ACTION_DEVICE_STORAGE_LOW:
111            mCachedQuotaUptimeMillis = 0;  // Force a re-check of quota size
112
113            // Run the initialization in the background (not this main thread).
114            // The init() and trimToFit() methods are synchronized, so they still
115            // block other users -- but at least the onReceive() call can finish.
116            new Thread() {
117                public void run() {
118                    try {
119                        init();
120                        trimToFit();
121                    } catch (IOException e) {
122                        Slog.e(TAG, "Can't init", e);
123                    }
124                }
125            }.start();
126        }
127    };
128
129    /**
130     * Creates an instance of managed drop box storage.  Normally there is one of these
131     * run by the system, but others can be created for testing and other purposes.
132     *
133     * @param context to use for receiving free space & gservices intents
134     * @param path to store drop box entries in
135     */
136    public DropBoxManagerService(final Context context, File path) {
137        mDropBoxDir = path;
138
139        // Set up intent receivers
140        mContext = context;
141        mContentResolver = context.getContentResolver();
142
143        IntentFilter filter = new IntentFilter();
144        filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
145        filter.addAction(Intent.ACTION_BOOT_COMPLETED);
146        context.registerReceiver(mReceiver, filter);
147
148        mContentResolver.registerContentObserver(
149            Settings.Global.CONTENT_URI, true,
150            new ContentObserver(new Handler()) {
151                @Override
152                public void onChange(boolean selfChange) {
153                    mReceiver.onReceive(context, (Intent) null);
154                }
155            });
156
157        mHandler = new Handler() {
158            @Override
159            public void handleMessage(Message msg) {
160                if (msg.what == MSG_SEND_BROADCAST) {
161                    mContext.sendBroadcastAsUser((Intent)msg.obj, UserHandle.OWNER,
162                            android.Manifest.permission.READ_LOGS);
163                }
164            }
165        };
166
167        // The real work gets done lazily in init() -- that way service creation always
168        // succeeds, and things like disk problems cause individual method failures.
169    }
170
171    /** Unregisters broadcast receivers and any other hooks -- for test instances */
172    public void stop() {
173        mContext.unregisterReceiver(mReceiver);
174    }
175
176    @Override
177    public void add(DropBoxManager.Entry entry) {
178        File temp = null;
179        OutputStream output = null;
180        final String tag = entry.getTag();
181        try {
182            int flags = entry.getFlags();
183            if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
184
185            init();
186            if (!isTagEnabled(tag)) return;
187            long max = trimToFit();
188            long lastTrim = System.currentTimeMillis();
189
190            byte[] buffer = new byte[mBlockSize];
191            InputStream input = entry.getInputStream();
192
193            // First, accumulate up to one block worth of data in memory before
194            // deciding whether to compress the data or not.
195
196            int read = 0;
197            while (read < buffer.length) {
198                int n = input.read(buffer, read, buffer.length - read);
199                if (n <= 0) break;
200                read += n;
201            }
202
203            // If we have at least one block, compress it -- otherwise, just write
204            // the data in uncompressed form.
205
206            temp = new File(mDropBoxDir, "drop" + Thread.currentThread().getId() + ".tmp");
207            int bufferSize = mBlockSize;
208            if (bufferSize > 4096) bufferSize = 4096;
209            if (bufferSize < 512) bufferSize = 512;
210            FileOutputStream foutput = new FileOutputStream(temp);
211            output = new BufferedOutputStream(foutput, bufferSize);
212            if (read == buffer.length && ((flags & DropBoxManager.IS_GZIPPED) == 0)) {
213                output = new GZIPOutputStream(output);
214                flags = flags | DropBoxManager.IS_GZIPPED;
215            }
216
217            do {
218                output.write(buffer, 0, read);
219
220                long now = System.currentTimeMillis();
221                if (now - lastTrim > 30 * 1000) {
222                    max = trimToFit();  // In case data dribbles in slowly
223                    lastTrim = now;
224                }
225
226                read = input.read(buffer);
227                if (read <= 0) {
228                    FileUtils.sync(foutput);
229                    output.close();  // Get a final size measurement
230                    output = null;
231                } else {
232                    output.flush();  // So the size measurement is pseudo-reasonable
233                }
234
235                long len = temp.length();
236                if (len > max) {
237                    Slog.w(TAG, "Dropping: " + tag + " (" + temp.length() + " > " + max + " bytes)");
238                    temp.delete();
239                    temp = null;  // Pass temp = null to createEntry() to leave a tombstone
240                    break;
241                }
242            } while (read > 0);
243
244            long time = createEntry(temp, tag, flags);
245            temp = null;
246
247            final Intent dropboxIntent = new Intent(DropBoxManager.ACTION_DROPBOX_ENTRY_ADDED);
248            dropboxIntent.putExtra(DropBoxManager.EXTRA_TAG, tag);
249            dropboxIntent.putExtra(DropBoxManager.EXTRA_TIME, time);
250            if (!mBooted) {
251                dropboxIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
252            }
253            // Call sendBroadcast after returning from this call to avoid deadlock. In particular
254            // the caller may be holding the WindowManagerService lock but sendBroadcast requires a
255            // lock in ActivityManagerService. ActivityManagerService has been caught holding that
256            // very lock while waiting for the WindowManagerService lock.
257            mHandler.sendMessage(mHandler.obtainMessage(MSG_SEND_BROADCAST, dropboxIntent));
258        } catch (IOException e) {
259            Slog.e(TAG, "Can't write: " + tag, e);
260        } finally {
261            try { if (output != null) output.close(); } catch (IOException e) {}
262            entry.close();
263            if (temp != null) temp.delete();
264        }
265    }
266
267    public boolean isTagEnabled(String tag) {
268        return !"disabled".equals(Settings.Global.getString(
269                mContentResolver, Settings.Global.DROPBOX_TAG_PREFIX + tag));
270    }
271
272    public synchronized DropBoxManager.Entry getNextEntry(String tag, long millis) {
273        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.READ_LOGS)
274                != PackageManager.PERMISSION_GRANTED) {
275            throw new SecurityException("READ_LOGS permission required");
276        }
277
278        try {
279            init();
280        } catch (IOException e) {
281            Slog.e(TAG, "Can't init", e);
282            return null;
283        }
284
285        FileList list = tag == null ? mAllFiles : mFilesByTag.get(tag);
286        if (list == null) return null;
287
288        for (EntryFile entry : list.contents.tailSet(new EntryFile(millis + 1))) {
289            if (entry.tag == null) continue;
290            if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
291                return new DropBoxManager.Entry(entry.tag, entry.timestampMillis);
292            }
293            try {
294                return new DropBoxManager.Entry(
295                        entry.tag, entry.timestampMillis, entry.file, entry.flags);
296            } catch (IOException e) {
297                Slog.e(TAG, "Can't read: " + entry.file, e);
298                // Continue to next file
299            }
300        }
301
302        return null;
303    }
304
305    public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
306        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
307                != PackageManager.PERMISSION_GRANTED) {
308            pw.println("Permission Denial: Can't dump DropBoxManagerService");
309            return;
310        }
311
312        try {
313            init();
314        } catch (IOException e) {
315            pw.println("Can't initialize: " + e);
316            Slog.e(TAG, "Can't init", e);
317            return;
318        }
319
320        if (PROFILE_DUMP) Debug.startMethodTracing("/data/trace/dropbox.dump");
321
322        StringBuilder out = new StringBuilder();
323        boolean doPrint = false, doFile = false;
324        ArrayList<String> searchArgs = new ArrayList<String>();
325        for (int i = 0; args != null && i < args.length; i++) {
326            if (args[i].equals("-p") || args[i].equals("--print")) {
327                doPrint = true;
328            } else if (args[i].equals("-f") || args[i].equals("--file")) {
329                doFile = true;
330            } else if (args[i].startsWith("-")) {
331                out.append("Unknown argument: ").append(args[i]).append("\n");
332            } else {
333                searchArgs.add(args[i]);
334            }
335        }
336
337        out.append("Drop box contents: ").append(mAllFiles.contents.size()).append(" entries\n");
338
339        if (!searchArgs.isEmpty()) {
340            out.append("Searching for:");
341            for (String a : searchArgs) out.append(" ").append(a);
342            out.append("\n");
343        }
344
345        int numFound = 0, numArgs = searchArgs.size();
346        Time time = new Time();
347        out.append("\n");
348        for (EntryFile entry : mAllFiles.contents) {
349            time.set(entry.timestampMillis);
350            String date = time.format("%Y-%m-%d %H:%M:%S");
351            boolean match = true;
352            for (int i = 0; i < numArgs && match; i++) {
353                String arg = searchArgs.get(i);
354                match = (date.contains(arg) || arg.equals(entry.tag));
355            }
356            if (!match) continue;
357
358            numFound++;
359            if (doPrint) out.append("========================================\n");
360            out.append(date).append(" ").append(entry.tag == null ? "(no tag)" : entry.tag);
361            if (entry.file == null) {
362                out.append(" (no file)\n");
363                continue;
364            } else if ((entry.flags & DropBoxManager.IS_EMPTY) != 0) {
365                out.append(" (contents lost)\n");
366                continue;
367            } else {
368                out.append(" (");
369                if ((entry.flags & DropBoxManager.IS_GZIPPED) != 0) out.append("compressed ");
370                out.append((entry.flags & DropBoxManager.IS_TEXT) != 0 ? "text" : "data");
371                out.append(", ").append(entry.file.length()).append(" bytes)\n");
372            }
373
374            if (doFile || (doPrint && (entry.flags & DropBoxManager.IS_TEXT) == 0)) {
375                if (!doPrint) out.append("    ");
376                out.append(entry.file.getPath()).append("\n");
377            }
378
379            if ((entry.flags & DropBoxManager.IS_TEXT) != 0 && (doPrint || !doFile)) {
380                DropBoxManager.Entry dbe = null;
381                InputStreamReader isr = null;
382                try {
383                    dbe = new DropBoxManager.Entry(
384                             entry.tag, entry.timestampMillis, entry.file, entry.flags);
385
386                    if (doPrint) {
387                        isr = new InputStreamReader(dbe.getInputStream());
388                        char[] buf = new char[4096];
389                        boolean newline = false;
390                        for (;;) {
391                            int n = isr.read(buf);
392                            if (n <= 0) break;
393                            out.append(buf, 0, n);
394                            newline = (buf[n - 1] == '\n');
395
396                            // Flush periodically when printing to avoid out-of-memory.
397                            if (out.length() > 65536) {
398                                pw.write(out.toString());
399                                out.setLength(0);
400                            }
401                        }
402                        if (!newline) out.append("\n");
403                    } else {
404                        String text = dbe.getText(70);
405                        boolean truncated = (text.length() == 70);
406                        out.append("    ").append(text.trim().replace('\n', '/'));
407                        if (truncated) out.append(" ...");
408                        out.append("\n");
409                    }
410                } catch (IOException e) {
411                    out.append("*** ").append(e.toString()).append("\n");
412                    Slog.e(TAG, "Can't read: " + entry.file, e);
413                } finally {
414                    if (dbe != null) dbe.close();
415                    if (isr != null) {
416                        try {
417                            isr.close();
418                        } catch (IOException unused) {
419                        }
420                    }
421                }
422            }
423
424            if (doPrint) out.append("\n");
425        }
426
427        if (numFound == 0) out.append("(No entries found.)\n");
428
429        if (args == null || args.length == 0) {
430            if (!doPrint) out.append("\n");
431            out.append("Usage: dumpsys dropbox [--print|--file] [YYYY-mm-dd] [HH:MM:SS] [tag]\n");
432        }
433
434        pw.write(out.toString());
435        if (PROFILE_DUMP) Debug.stopMethodTracing();
436    }
437
438    ///////////////////////////////////////////////////////////////////////////
439
440    /** Chronologically sorted list of {@link #EntryFile} */
441    private static final class FileList implements Comparable<FileList> {
442        public int blocks = 0;
443        public final TreeSet<EntryFile> contents = new TreeSet<EntryFile>();
444
445        /** Sorts bigger FileList instances before smaller ones. */
446        public final int compareTo(FileList o) {
447            if (blocks != o.blocks) return o.blocks - blocks;
448            if (this == o) return 0;
449            if (hashCode() < o.hashCode()) return -1;
450            if (hashCode() > o.hashCode()) return 1;
451            return 0;
452        }
453    }
454
455    /** Metadata describing an on-disk log file. */
456    private static final class EntryFile implements Comparable<EntryFile> {
457        public final String tag;
458        public final long timestampMillis;
459        public final int flags;
460        public final File file;
461        public final int blocks;
462
463        /** Sorts earlier EntryFile instances before later ones. */
464        public final int compareTo(EntryFile o) {
465            if (timestampMillis < o.timestampMillis) return -1;
466            if (timestampMillis > o.timestampMillis) return 1;
467            if (file != null && o.file != null) return file.compareTo(o.file);
468            if (o.file != null) return -1;
469            if (file != null) return 1;
470            if (this == o) return 0;
471            if (hashCode() < o.hashCode()) return -1;
472            if (hashCode() > o.hashCode()) return 1;
473            return 0;
474        }
475
476        /**
477         * Moves an existing temporary file to a new log filename.
478         * @param temp file to rename
479         * @param dir to store file in
480         * @param tag to use for new log file name
481         * @param timestampMillis of log entry
482         * @param flags for the entry data
483         * @param blockSize to use for space accounting
484         * @throws IOException if the file can't be moved
485         */
486        public EntryFile(File temp, File dir, String tag,long timestampMillis,
487                         int flags, int blockSize) throws IOException {
488            if ((flags & DropBoxManager.IS_EMPTY) != 0) throw new IllegalArgumentException();
489
490            this.tag = tag;
491            this.timestampMillis = timestampMillis;
492            this.flags = flags;
493            this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis +
494                    ((flags & DropBoxManager.IS_TEXT) != 0 ? ".txt" : ".dat") +
495                    ((flags & DropBoxManager.IS_GZIPPED) != 0 ? ".gz" : ""));
496
497            if (!temp.renameTo(this.file)) {
498                throw new IOException("Can't rename " + temp + " to " + this.file);
499            }
500            this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
501        }
502
503        /**
504         * Creates a zero-length tombstone for a file whose contents were lost.
505         * @param dir to store file in
506         * @param tag to use for new log file name
507         * @param timestampMillis of log entry
508         * @throws IOException if the file can't be created.
509         */
510        public EntryFile(File dir, String tag, long timestampMillis) throws IOException {
511            this.tag = tag;
512            this.timestampMillis = timestampMillis;
513            this.flags = DropBoxManager.IS_EMPTY;
514            this.file = new File(dir, Uri.encode(tag) + "@" + timestampMillis + ".lost");
515            this.blocks = 0;
516            new FileOutputStream(this.file).close();
517        }
518
519        /**
520         * Extracts metadata from an existing on-disk log filename.
521         * @param file name of existing log file
522         * @param blockSize to use for space accounting
523         */
524        public EntryFile(File file, int blockSize) {
525            this.file = file;
526            this.blocks = (int) ((this.file.length() + blockSize - 1) / blockSize);
527
528            String name = file.getName();
529            int at = name.lastIndexOf('@');
530            if (at < 0) {
531                this.tag = null;
532                this.timestampMillis = 0;
533                this.flags = DropBoxManager.IS_EMPTY;
534                return;
535            }
536
537            int flags = 0;
538            this.tag = Uri.decode(name.substring(0, at));
539            if (name.endsWith(".gz")) {
540                flags |= DropBoxManager.IS_GZIPPED;
541                name = name.substring(0, name.length() - 3);
542            }
543            if (name.endsWith(".lost")) {
544                flags |= DropBoxManager.IS_EMPTY;
545                name = name.substring(at + 1, name.length() - 5);
546            } else if (name.endsWith(".txt")) {
547                flags |= DropBoxManager.IS_TEXT;
548                name = name.substring(at + 1, name.length() - 4);
549            } else if (name.endsWith(".dat")) {
550                name = name.substring(at + 1, name.length() - 4);
551            } else {
552                this.flags = DropBoxManager.IS_EMPTY;
553                this.timestampMillis = 0;
554                return;
555            }
556            this.flags = flags;
557
558            long millis;
559            try { millis = Long.valueOf(name); } catch (NumberFormatException e) { millis = 0; }
560            this.timestampMillis = millis;
561        }
562
563        /**
564         * Creates a EntryFile object with only a timestamp for comparison purposes.
565         * @param timestampMillis to compare with.
566         */
567        public EntryFile(long millis) {
568            this.tag = null;
569            this.timestampMillis = millis;
570            this.flags = DropBoxManager.IS_EMPTY;
571            this.file = null;
572            this.blocks = 0;
573        }
574    }
575
576    ///////////////////////////////////////////////////////////////////////////
577
578    /** If never run before, scans disk contents to build in-memory tracking data. */
579    private synchronized void init() throws IOException {
580        if (mStatFs == null) {
581            if (!mDropBoxDir.isDirectory() && !mDropBoxDir.mkdirs()) {
582                throw new IOException("Can't mkdir: " + mDropBoxDir);
583            }
584            try {
585                mStatFs = new StatFs(mDropBoxDir.getPath());
586                mBlockSize = mStatFs.getBlockSize();
587            } catch (IllegalArgumentException e) {  // StatFs throws this on error
588                throw new IOException("Can't statfs: " + mDropBoxDir);
589            }
590        }
591
592        if (mAllFiles == null) {
593            File[] files = mDropBoxDir.listFiles();
594            if (files == null) throw new IOException("Can't list files: " + mDropBoxDir);
595
596            mAllFiles = new FileList();
597            mFilesByTag = new HashMap<String, FileList>();
598
599            // Scan pre-existing files.
600            for (File file : files) {
601                if (file.getName().endsWith(".tmp")) {
602                    Slog.i(TAG, "Cleaning temp file: " + file);
603                    file.delete();
604                    continue;
605                }
606
607                EntryFile entry = new EntryFile(file, mBlockSize);
608                if (entry.tag == null) {
609                    Slog.w(TAG, "Unrecognized file: " + file);
610                    continue;
611                } else if (entry.timestampMillis == 0) {
612                    Slog.w(TAG, "Invalid filename: " + file);
613                    file.delete();
614                    continue;
615                }
616
617                enrollEntry(entry);
618            }
619        }
620    }
621
622    /** Adds a disk log file to in-memory tracking for accounting and enumeration. */
623    private synchronized void enrollEntry(EntryFile entry) {
624        mAllFiles.contents.add(entry);
625        mAllFiles.blocks += entry.blocks;
626
627        // mFilesByTag is used for trimming, so don't list empty files.
628        // (Zero-length/lost files are trimmed by date from mAllFiles.)
629
630        if (entry.tag != null && entry.file != null && entry.blocks > 0) {
631            FileList tagFiles = mFilesByTag.get(entry.tag);
632            if (tagFiles == null) {
633                tagFiles = new FileList();
634                mFilesByTag.put(entry.tag, tagFiles);
635            }
636            tagFiles.contents.add(entry);
637            tagFiles.blocks += entry.blocks;
638        }
639    }
640
641    /** Moves a temporary file to a final log filename and enrolls it. */
642    private synchronized long createEntry(File temp, String tag, int flags) throws IOException {
643        long t = System.currentTimeMillis();
644
645        // Require each entry to have a unique timestamp; if there are entries
646        // >10sec in the future (due to clock skew), drag them back to avoid
647        // keeping them around forever.
648
649        SortedSet<EntryFile> tail = mAllFiles.contents.tailSet(new EntryFile(t + 10000));
650        EntryFile[] future = null;
651        if (!tail.isEmpty()) {
652            future = tail.toArray(new EntryFile[tail.size()]);
653            tail.clear();  // Remove from mAllFiles
654        }
655
656        if (!mAllFiles.contents.isEmpty()) {
657            t = Math.max(t, mAllFiles.contents.last().timestampMillis + 1);
658        }
659
660        if (future != null) {
661            for (EntryFile late : future) {
662                mAllFiles.blocks -= late.blocks;
663                FileList tagFiles = mFilesByTag.get(late.tag);
664                if (tagFiles != null && tagFiles.contents.remove(late)) {
665                    tagFiles.blocks -= late.blocks;
666                }
667                if ((late.flags & DropBoxManager.IS_EMPTY) == 0) {
668                    enrollEntry(new EntryFile(
669                            late.file, mDropBoxDir, late.tag, t++, late.flags, mBlockSize));
670                } else {
671                    enrollEntry(new EntryFile(mDropBoxDir, late.tag, t++));
672                }
673            }
674        }
675
676        if (temp == null) {
677            enrollEntry(new EntryFile(mDropBoxDir, tag, t));
678        } else {
679            enrollEntry(new EntryFile(temp, mDropBoxDir, tag, t, flags, mBlockSize));
680        }
681        return t;
682    }
683
684    /**
685     * Trims the files on disk to make sure they aren't using too much space.
686     * @return the overall quota for storage (in bytes)
687     */
688    private synchronized long trimToFit() {
689        // Expunge aged items (including tombstones marking deleted data).
690
691        int ageSeconds = Settings.Global.getInt(mContentResolver,
692                Settings.Global.DROPBOX_AGE_SECONDS, DEFAULT_AGE_SECONDS);
693        int maxFiles = Settings.Global.getInt(mContentResolver,
694                Settings.Global.DROPBOX_MAX_FILES, DEFAULT_MAX_FILES);
695        long cutoffMillis = System.currentTimeMillis() - ageSeconds * 1000;
696        while (!mAllFiles.contents.isEmpty()) {
697            EntryFile entry = mAllFiles.contents.first();
698            if (entry.timestampMillis > cutoffMillis && mAllFiles.contents.size() < maxFiles) break;
699
700            FileList tag = mFilesByTag.get(entry.tag);
701            if (tag != null && tag.contents.remove(entry)) tag.blocks -= entry.blocks;
702            if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
703            if (entry.file != null) entry.file.delete();
704        }
705
706        // Compute overall quota (a fraction of available free space) in blocks.
707        // The quota changes dynamically based on the amount of free space;
708        // that way when lots of data is available we can use it, but we'll get
709        // out of the way if storage starts getting tight.
710
711        long uptimeMillis = SystemClock.uptimeMillis();
712        if (uptimeMillis > mCachedQuotaUptimeMillis + QUOTA_RESCAN_MILLIS) {
713            int quotaPercent = Settings.Global.getInt(mContentResolver,
714                    Settings.Global.DROPBOX_QUOTA_PERCENT, DEFAULT_QUOTA_PERCENT);
715            int reservePercent = Settings.Global.getInt(mContentResolver,
716                    Settings.Global.DROPBOX_RESERVE_PERCENT, DEFAULT_RESERVE_PERCENT);
717            int quotaKb = Settings.Global.getInt(mContentResolver,
718                    Settings.Global.DROPBOX_QUOTA_KB, DEFAULT_QUOTA_KB);
719
720            mStatFs.restat(mDropBoxDir.getPath());
721            int available = mStatFs.getAvailableBlocks();
722            int nonreserved = available - mStatFs.getBlockCount() * reservePercent / 100;
723            int maximum = quotaKb * 1024 / mBlockSize;
724            mCachedQuotaBlocks = Math.min(maximum, Math.max(0, nonreserved * quotaPercent / 100));
725            mCachedQuotaUptimeMillis = uptimeMillis;
726        }
727
728        // If we're using too much space, delete old items to make room.
729        //
730        // We trim each tag independently (this is why we keep per-tag lists).
731        // Space is "fairly" shared between tags -- they are all squeezed
732        // equally until enough space is reclaimed.
733        //
734        // A single circular buffer (a la logcat) would be simpler, but this
735        // way we can handle fat/bursty data (like 1MB+ bugreports, 300KB+
736        // kernel crash dumps, and 100KB+ ANR reports) without swamping small,
737        // well-behaved data streams (event statistics, profile data, etc).
738        //
739        // Deleted files are replaced with zero-length tombstones to mark what
740        // was lost.  Tombstones are expunged by age (see above).
741
742        if (mAllFiles.blocks > mCachedQuotaBlocks) {
743            // Find a fair share amount of space to limit each tag
744            int unsqueezed = mAllFiles.blocks, squeezed = 0;
745            TreeSet<FileList> tags = new TreeSet<FileList>(mFilesByTag.values());
746            for (FileList tag : tags) {
747                if (squeezed > 0 && tag.blocks <= (mCachedQuotaBlocks - unsqueezed) / squeezed) {
748                    break;
749                }
750                unsqueezed -= tag.blocks;
751                squeezed++;
752            }
753            int tagQuota = (mCachedQuotaBlocks - unsqueezed) / squeezed;
754
755            // Remove old items from each tag until it meets the per-tag quota.
756            for (FileList tag : tags) {
757                if (mAllFiles.blocks < mCachedQuotaBlocks) break;
758                while (tag.blocks > tagQuota && !tag.contents.isEmpty()) {
759                    EntryFile entry = tag.contents.first();
760                    if (tag.contents.remove(entry)) tag.blocks -= entry.blocks;
761                    if (mAllFiles.contents.remove(entry)) mAllFiles.blocks -= entry.blocks;
762
763                    try {
764                        if (entry.file != null) entry.file.delete();
765                        enrollEntry(new EntryFile(mDropBoxDir, entry.tag, entry.timestampMillis));
766                    } catch (IOException e) {
767                        Slog.e(TAG, "Can't write tombstone file", e);
768                    }
769                }
770            }
771        }
772
773        return mCachedQuotaBlocks * mBlockSize;
774    }
775}
776