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 android.os;
18
19import android.util.Log;
20
21import com.android.internal.os.IDropBoxManagerService;
22
23import java.io.ByteArrayInputStream;
24import java.io.Closeable;
25import java.io.File;
26import java.io.FileInputStream;
27import java.io.IOException;
28import java.io.InputStream;
29import java.util.zip.GZIPInputStream;
30
31/**
32 * Enqueues chunks of data (from various sources -- application crashes, kernel
33 * log records, etc.).  The queue is size bounded and will drop old data if the
34 * enqueued data exceeds the maximum size.  You can think of this as a
35 * persistent, system-wide, blob-oriented "logcat".
36 *
37 * <p>You can obtain an instance of this class by calling
38 * {@link android.content.Context#getSystemService}
39 * with {@link android.content.Context#DROPBOX_SERVICE}.
40 *
41 * <p>DropBoxManager entries are not sent anywhere directly, but other system
42 * services and debugging tools may scan and upload entries for processing.
43 */
44public class DropBoxManager {
45    private static final String TAG = "DropBoxManager";
46    private final IDropBoxManagerService mService;
47
48    /** Flag value: Entry's content was deleted to save space. */
49    public static final int IS_EMPTY = 1;
50
51    /** Flag value: Content is human-readable UTF-8 text (can be combined with IS_GZIPPED). */
52    public static final int IS_TEXT = 2;
53
54    /** Flag value: Content can be decompressed with {@link java.util.zip.GZIPOutputStream}. */
55    public static final int IS_GZIPPED = 4;
56
57    /** Flag value for serialization only: Value is a byte array, not a file descriptor */
58    private static final int HAS_BYTE_ARRAY = 8;
59
60    /**
61     * A single entry retrieved from the drop box.
62     * This may include a reference to a stream, so you must call
63     * {@link #close()} when you are done using it.
64     */
65    public static class Entry implements Parcelable, Closeable {
66        private final String mTag;
67        private final long mTimeMillis;
68
69        private final byte[] mData;
70        private final ParcelFileDescriptor mFileDescriptor;
71        private final int mFlags;
72
73        /** Create a new empty Entry with no contents. */
74        public Entry(String tag, long millis) {
75            if (tag == null) throw new NullPointerException("tag == null");
76
77            mTag = tag;
78            mTimeMillis = millis;
79            mData = null;
80            mFileDescriptor = null;
81            mFlags = IS_EMPTY;
82        }
83
84        /** Create a new Entry with plain text contents. */
85        public Entry(String tag, long millis, String text) {
86            if (tag == null) throw new NullPointerException("tag == null");
87            if (text == null) throw new NullPointerException("text == null");
88
89            mTag = tag;
90            mTimeMillis = millis;
91            mData = text.getBytes();
92            mFileDescriptor = null;
93            mFlags = IS_TEXT;
94        }
95
96        /**
97         * Create a new Entry with byte array contents.
98         * The data array must not be modified after creating this entry.
99         */
100        public Entry(String tag, long millis, byte[] data, int flags) {
101            if (tag == null) throw new NullPointerException("tag == null");
102            if (((flags & IS_EMPTY) != 0) != (data == null)) {
103                throw new IllegalArgumentException("Bad flags: " + flags);
104            }
105
106            mTag = tag;
107            mTimeMillis = millis;
108            mData = data;
109            mFileDescriptor = null;
110            mFlags = flags;
111        }
112
113        /**
114         * Create a new Entry with streaming data contents.
115         * Takes ownership of the ParcelFileDescriptor.
116         */
117        public Entry(String tag, long millis, ParcelFileDescriptor data, int flags) {
118            if (tag == null) throw new NullPointerException("tag == null");
119            if (((flags & IS_EMPTY) != 0) != (data == null)) {
120                throw new IllegalArgumentException("Bad flags: " + flags);
121            }
122
123            mTag = tag;
124            mTimeMillis = millis;
125            mData = null;
126            mFileDescriptor = data;
127            mFlags = flags;
128        }
129
130        /**
131         * Create a new Entry with the contents read from a file.
132         * The file will be read when the entry's contents are requested.
133         */
134        public Entry(String tag, long millis, File data, int flags) throws IOException {
135            if (tag == null) throw new NullPointerException("tag == null");
136            if ((flags & IS_EMPTY) != 0) throw new IllegalArgumentException("Bad flags: " + flags);
137
138            mTag = tag;
139            mTimeMillis = millis;
140            mData = null;
141            mFileDescriptor = ParcelFileDescriptor.open(data, ParcelFileDescriptor.MODE_READ_ONLY);
142            mFlags = flags;
143        }
144
145        /** Close the input stream associated with this entry. */
146        public void close() {
147            try { if (mFileDescriptor != null) mFileDescriptor.close(); } catch (IOException e) { }
148        }
149
150        /** @return the tag originally attached to the entry. */
151        public String getTag() { return mTag; }
152
153        /** @return time when the entry was originally created. */
154        public long getTimeMillis() { return mTimeMillis; }
155
156        /** @return flags describing the content returned by {@link #getInputStream()}. */
157        public int getFlags() { return mFlags & ~IS_GZIPPED; }  // getInputStream() decompresses.
158
159        /**
160         * @param maxBytes of string to return (will truncate at this length).
161         * @return the uncompressed text contents of the entry, null if the entry is not text.
162         */
163        public String getText(int maxBytes) {
164            if ((mFlags & IS_TEXT) == 0) return null;
165            if (mData != null) return new String(mData, 0, Math.min(maxBytes, mData.length));
166
167            InputStream is = null;
168            try {
169                is = getInputStream();
170                if (is == null) return null;
171                byte[] buf = new byte[maxBytes];
172                return new String(buf, 0, Math.max(0, is.read(buf)));
173            } catch (IOException e) {
174                return null;
175            } finally {
176                try { if (is != null) is.close(); } catch (IOException e) {}
177            }
178        }
179
180        /** @return the uncompressed contents of the entry, or null if the contents were lost */
181        public InputStream getInputStream() throws IOException {
182            InputStream is;
183            if (mData != null) {
184                is = new ByteArrayInputStream(mData);
185            } else if (mFileDescriptor != null) {
186                is = new ParcelFileDescriptor.AutoCloseInputStream(mFileDescriptor);
187            } else {
188                return null;
189            }
190            return (mFlags & IS_GZIPPED) != 0 ? new GZIPInputStream(is) : is;
191        }
192
193        public static final Parcelable.Creator<Entry> CREATOR = new Parcelable.Creator() {
194            public Entry[] newArray(int size) { return new Entry[size]; }
195            public Entry createFromParcel(Parcel in) {
196                String tag = in.readString();
197                long millis = in.readLong();
198                int flags = in.readInt();
199                if ((flags & HAS_BYTE_ARRAY) != 0) {
200                    return new Entry(tag, millis, in.createByteArray(), flags & ~HAS_BYTE_ARRAY);
201                } else {
202                    return new Entry(tag, millis, in.readFileDescriptor(), flags);
203                }
204            }
205        };
206
207        public int describeContents() {
208            return mFileDescriptor != null ? Parcelable.CONTENTS_FILE_DESCRIPTOR : 0;
209        }
210
211        public void writeToParcel(Parcel out, int flags) {
212            out.writeString(mTag);
213            out.writeLong(mTimeMillis);
214            if (mFileDescriptor != null) {
215                out.writeInt(mFlags & ~HAS_BYTE_ARRAY);  // Clear bit just to be safe
216                mFileDescriptor.writeToParcel(out, flags);
217            } else {
218                out.writeInt(mFlags | HAS_BYTE_ARRAY);
219                out.writeByteArray(mData);
220            }
221        }
222    }
223
224    /** {@hide} */
225    public DropBoxManager(IDropBoxManagerService service) { mService = service; }
226
227    /**
228     * Create a dummy instance for testing.  All methods will fail unless
229     * overridden with an appropriate mock implementation.  To obtain a
230     * functional instance, use {@link android.content.Context#getSystemService}.
231     */
232    protected DropBoxManager() { mService = null; }
233
234    /**
235     * Stores human-readable text.  The data may be discarded eventually (or even
236     * immediately) if space is limited, or ignored entirely if the tag has been
237     * blocked (see {@link #isTagEnabled}).
238     *
239     * @param tag describing the type of entry being stored
240     * @param data value to store
241     */
242    public void addText(String tag, String data) {
243        try { mService.add(new Entry(tag, 0, data)); } catch (RemoteException e) {}
244    }
245
246    /**
247     * Stores binary data, which may be ignored or discarded as with {@link #addText}.
248     *
249     * @param tag describing the type of entry being stored
250     * @param data value to store
251     * @param flags describing the data
252     */
253    public void addData(String tag, byte[] data, int flags) {
254        if (data == null) throw new NullPointerException("data == null");
255        try { mService.add(new Entry(tag, 0, data, flags)); } catch (RemoteException e) {}
256    }
257
258    /**
259     * Stores the contents of a file, which may be ignored or discarded as with
260     * {@link #addText}.
261     *
262     * @param tag describing the type of entry being stored
263     * @param file to read from
264     * @param flags describing the data
265     * @throws IOException if the file can't be opened
266     */
267    public void addFile(String tag, File file, int flags) throws IOException {
268        if (file == null) throw new NullPointerException("file == null");
269        Entry entry = new Entry(tag, 0, file, flags);
270        try {
271            mService.add(entry);
272        } catch (RemoteException e) {
273            // ignore
274        } finally {
275            entry.close();
276        }
277    }
278
279    /**
280     * Checks any blacklists (set in system settings) to see whether a certain
281     * tag is allowed.  Entries with disabled tags will be dropped immediately,
282     * so you can save the work of actually constructing and sending the data.
283     *
284     * @param tag that would be used in {@link #addText} or {@link #addFile}
285     * @return whether events with that tag would be accepted
286     */
287    public boolean isTagEnabled(String tag) {
288        try { return mService.isTagEnabled(tag); } catch (RemoteException e) { return false; }
289    }
290
291    /**
292     * Gets the next entry from the drop box <em>after</em> the specified time.
293     * Requires <code>android.permission.READ_LOGS</code>.  You must always call
294     * {@link Entry#close()} on the return value!
295     *
296     * @param tag of entry to look for, null for all tags
297     * @param msec time of the last entry seen
298     * @return the next entry, or null if there are no more entries
299     */
300    public Entry getNextEntry(String tag, long msec) {
301        try { return mService.getNextEntry(tag, msec); } catch (RemoteException e) { return null; }
302    }
303
304    // TODO: It may be useful to have some sort of notification mechanism
305    // when data is added to the dropbox, for demand-driven readers --
306    // for now readers need to poll the dropbox to find new data.
307}
308