summaryrefslogtreecommitdiffstats
path: root/src/com/android/browser/CrashLogExceptionHandler.java
blob: dc42d5961720982f2ec9f7d25dc2e0da3747da78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
 * Copyright (c) 2014, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above
 *       copyright notice, this list of conditions and the following
 *       disclaimer in the documentation and/or other materials provided
 *       with the distribution.
 *     * Neither the name of The Linux Foundation nor the names of its
 *       contributors may be used to endorse or promote products derived
 *       from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.android.browser;

import android.app.Activity;
import android.app.ActivityManager;
import android.content.Context;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.SystemClock;
import android.net.http.AndroidHttpClient;
import android.util.Log;
import android.os.FileObserver;
import android.os.Handler;

import org.codeaurora.swe.BrowserCommandLine;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.entity.AbstractHttpEntity;
import org.apache.http.entity.ByteArrayEntity;


import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.Integer;
import java.lang.StringBuilder;
import java.lang.System;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Calendar;
import java.util.zip.GZIPOutputStream;

public class CrashLogExceptionHandler implements Thread.UncaughtExceptionHandler {

    private static final String CRASH_LOG_FILE = "crash.log";
    private static final String CRASH_LOG_MAX_FILE_SIZE_CMD = "crash-log-max-file-size";
    private static final String CRASH_REPORT_DIR = "Crash Reports";

    private final static String LOGTAG = "CrashLog";

    private Context mAppContext = null;

    private UncaughtExceptionHandler mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();

    private String mLogServer = new String();

    private boolean mOverrideHandler = false;

    private int mMaxLogFileSize = 1024 * 1024;
    // To avoid increasing startup time an upload delay is used
    private static final int UPLOAD_DELAY = 3000;

    private static FileObserver crashObserver;

    private final Handler mCrashReportHandler = new Handler();

    public CrashLogExceptionHandler(Context ctx) {
        mAppContext = ctx;
        if (BrowserCommandLine.hasSwitch(BrowserSwitches.CRASH_LOG_SERVER_CMD)) {
            initNativeReporter(ctx);
            mLogServer = BrowserCommandLine.getSwitchValue(BrowserSwitches.CRASH_LOG_SERVER_CMD);
            if (mLogServer != null) {
                uploadPastCrashLog();
                mOverrideHandler = true;
            }
        }

        try {
            int size = Integer.parseInt(
                                BrowserCommandLine.getSwitchValue(CRASH_LOG_MAX_FILE_SIZE_CMD,
                                Integer.toString(mMaxLogFileSize)));
            mMaxLogFileSize = size;
        } catch (NumberFormatException nfe) {
            Log.e(LOGTAG,"Max log file size is not configured properly. Using default: "
                  + mMaxLogFileSize);
        }

    }

    private void initNativeReporter(Context ctx){
        final File crashReports = new File(ctx.getCacheDir(),CRASH_REPORT_DIR);
        // On fresh installs, make the directory before registering an observer
        if (!crashReports.isDirectory()) {
            crashReports.mkdir();
        }
        // Implement FileObserver for crashReports that don't bring the system down
        crashObserver = new FileObserver(crashReports.getAbsolutePath()) {
            @Override
            public void onEvent(int event, String path){
                if ((event == FileObserver.CREATE) || (event == FileObserver.MOVED_TO)){
                    Log.w(LOGTAG, "A crash report was generated");
                    checkNativeCrash(crashReports);
                }
            }
        };
        // Native Crash reporting if commandline is set
        mCrashReportHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                checkNativeCrash(crashReports);
            }
        }, UPLOAD_DELAY);
        // start watching the crash reports folder
        crashObserver.startWatching();
    }

    private void saveCrashLog(String crashLog) {
        // Check if log file exists and it's current size
        try {
            File file = new File(mAppContext.getFilesDir(), CRASH_LOG_FILE);
            if (file.exists()) {
                if (file.length() > mMaxLogFileSize) {
                    Log.e(LOGTAG,"CRASH Log file size(" + file.length()
                          + ") exceeded max log file size("
                          + mMaxLogFileSize + ")");
                    return;
                }
            }
        } catch (NullPointerException npe) {
            Log.e(LOGTAG,"Exception while checking file size: " + npe);
        }

        FileOutputStream crashLogFile = null;
        try {
            crashLogFile = mAppContext.openFileOutput(CRASH_LOG_FILE, Context.MODE_APPEND);
            crashLogFile.write(crashLog.getBytes());
        } catch(IOException ioe) {
            Log.e(LOGTAG,"Exception while writing file: " + ioe);
        } finally {
            if (crashLogFile != null) {
                try {
                    crashLogFile.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private void uploadPastCrashLog() {
        FileInputStream crashLogFile = null;
        BufferedReader reader = null;
        try {
            crashLogFile = mAppContext.openFileInput(CRASH_LOG_FILE);

            reader = new BufferedReader(new InputStreamReader(crashLogFile));
            StringBuilder crashLog = new StringBuilder();
            String line = reader.readLine();
            if (line != null) {
                crashLog.append(line);
            }

            // Typically there's only one line (JSON string) in the crash
            // log file. This loop would not be executed.
            while ((line = reader.readLine()) != null) {
                crashLog.append("\n").append(line);
            }

            uploadCrashLog(crashLog.toString(), UPLOAD_DELAY);
        } catch(FileNotFoundException fnfe) {
            Log.v(LOGTAG,"No previous crash found");
        } catch(IOException ioe) {
            Log.e(LOGTAG,"Exception while reading crash file: " + ioe);
        } finally {
            if (crashLogFile != null) {
                try {
                    crashLogFile.close();
                } catch (IOException ignore) {
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException ignore) {
                }
            }
        }
    }

    private void uploadCrashLog(String data, int after) {
        final String crashLog = data;
        final int waitFor = after;
        new Thread(new Runnable() {
                public void run(){
                    try {
                        SystemClock.sleep(waitFor);
                        AndroidHttpClient httpClient = AndroidHttpClient.newInstance("Android");;
                        HttpPost httpPost = new HttpPost(mLogServer);
                        HttpEntity se = new StringEntity(crashLog);
                        httpPost.setEntity(se);
                        HttpResponse response = httpClient.execute(httpPost);

                        File crashLogFile = new File(mAppContext.getFilesDir(),
                                                     CRASH_LOG_FILE);
                        if (crashLogFile != null) {
                            crashLogFile.delete();
                        } else {
                            Log.e(LOGTAG,"crash log file could not be opened for deletion");
                        }
                    } catch (ClientProtocolException pe) {
                        Log.e(LOGTAG,"Exception while sending http post: " + pe);
                    } catch (IOException ioe1) {
                        Log.e(LOGTAG,"Exception while sending http post: " + ioe1);
                    }
                }
            }).start();
    }

    public void uncaughtException(Thread t, Throwable e) {
        if (!mOverrideHandler) {
            mDefaultHandler.uncaughtException(t, e);
            return;
        }

        String crashLog = new String();

        try {
            Calendar calendar = Calendar.getInstance();
            JSONObject jsonBackTraceObj = new JSONObject();
            String date = calendar.getTime().toString();
            String aboutSWE = mAppContext.getResources().getString(R.string.about_text);
            String sweVer = findValueFromAboutText(aboutSWE, "Version: ");
            String sweHash = findValueFromAboutText(aboutSWE, "Hash: ");
            String sweBuildDate = findValueFromAboutText(aboutSWE, "Built: ");

            jsonBackTraceObj.put("date", date);
            jsonBackTraceObj.put("android-model", android.os.Build.MODEL);
            jsonBackTraceObj.put("android-device", android.os.Build.DEVICE);
            jsonBackTraceObj.put("android-ver", android.os.Build.VERSION.RELEASE);
            jsonBackTraceObj.put("browser-ver", sweVer);
            jsonBackTraceObj.put("browser-hash", sweHash);
            jsonBackTraceObj.put("browser-build-date", sweBuildDate);
            jsonBackTraceObj.put("thread", t.toString());
            jsonBackTraceObj.put("format", "crashmon-1");
            jsonBackTraceObj.put("monkey-test", ActivityManager.isUserAMonkey());

            JSONArray jsonStackArray = new JSONArray();

            Throwable throwable = e;
            String stackTag = "Exception thrown while running";
            while (throwable != null) {
                JSONObject jsonStackObj = new JSONObject();
                StackTraceElement[] arr = throwable.getStackTrace();
                JSONArray jsonStack = new JSONArray(arr);

                jsonStackObj.put("cause", throwable.getCause());
                jsonStackObj.put("message", throwable.getMessage());
                jsonStackObj.put(stackTag, jsonStack);

                jsonStackArray.put(jsonStackObj);

                stackTag = "stack";
                throwable = throwable.getCause();
            }
            jsonBackTraceObj.put("exceptions", jsonStackArray);

            JSONObject jsonMainObj = new JSONObject();
            jsonMainObj.put("backtraces", jsonBackTraceObj);

            Log.e(LOGTAG, "Exception: " + jsonMainObj.toString(4));
            crashLog = jsonMainObj.toString();

        } catch (JSONException je) {
            Log.e(LOGTAG, "Failed in JSON encoding: " + je);
        }

        saveCrashLog(crashLog);

        uploadCrashLog(crashLog, 0);

        mDefaultHandler.uncaughtException(t, e);
    }

    private String findValueFromAboutText(String aboutText, String aboutKey) {
        int start = aboutText.indexOf(aboutKey);
        int end = aboutText.indexOf("\n", start);
        String value = "";

        if (start != -1 && end != -1) {
            start += aboutKey.length();
            value = aboutText.substring(start, end);
        }
        return value;
    }

    private void checkNativeCrash(final File crashReportsDir) {
        // Search cache/Crash Reports/ for any crashes
        if (crashReportsDir.exists()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (File f : crashReportsDir.listFiles()) {
                        uploadNativeCrashReport(f);
                    }
                }
            }).start();
        }
    }

    private void uploadNativeCrashReport(final File report) {
        Log.w(LOGTAG, "Preparing Crash Report for upload " + report.getName());
        // get server url from commandline
        String server = BrowserCommandLine.getSwitchValue(BrowserSwitches.CRASH_LOG_SERVER_CMD);
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(server);

            // Compress the data
            ByteArrayOutputStream arrayStream = new ByteArrayOutputStream();
            OutputStream gzipData = new GZIPOutputStream(arrayStream);
            InputStream inputStream = new FileInputStream(report);
            long length = report.length();
            byte[] data = new byte[(int)length];

            // Read in the bytes
            int offset = 0;
            int numRead = 0;
            while (offset < data.length
                   && (numRead=inputStream.read(data, offset, data.length-offset)) >= 0) {
                offset += numRead;
            }
            gzipData.write(data);
            gzipData.close();

            AbstractHttpEntity entity = new ByteArrayEntity(arrayStream.toByteArray());

            // Send the report as a compressed Binary
            entity.setContentType("binary/octet-stream");
            entity.setContentEncoding("gzip");
            entity.setChunked(false);
            httpPost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpPost);
            int status = response.getStatusLine().getStatusCode();
            if (status == 200)
                report.delete();
            else Log.w(LOGTAG, "Upload Failure. Will try again next time- " + status);

        } catch (Exception e) {
            Log.w(LOGTAG, "Crash Report failed to upload, will try again next time " + e);
        }
    }

}