BootReceiver.java revision dea847c2ace8894a595cf9bd87764ce2ca9698ab
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.Context;
21import android.content.Intent;
22import android.content.SharedPreferences;
23import android.content.pm.IPackageManager;
24import android.os.Build;
25import android.os.DropBoxManager;
26import android.os.FileObserver;
27import android.os.FileUtils;
28import android.os.RecoverySystem;
29import android.os.RemoteException;
30import android.os.ServiceManager;
31import android.os.SystemProperties;
32import android.provider.Downloads;
33import android.util.Slog;
34
35import java.io.File;
36import java.io.IOException;
37
38/**
39 * Performs a number of miscellaneous, non-system-critical actions
40 * after the system has finished booting.
41 */
42public class BootReceiver extends BroadcastReceiver {
43    private static final String TAG = "BootReceiver";
44
45    // Maximum size of a logged event (files get truncated if they're longer).
46    // Give userdebug builds a larger max to capture extra debug, esp. for last_kmsg.
47    private static final int LOG_SIZE =
48        SystemProperties.getInt("ro.debuggable", 0) == 1 ? 98304 : 65536;
49
50    private static final File TOMBSTONE_DIR = new File("/data/tombstones");
51
52    // The pre-froyo package and class of the system updater, which
53    // ran in the system process.  We need to remove its packages here
54    // in order to clean up after a pre-froyo-to-froyo update.
55    private static final String OLD_UPDATER_PACKAGE =
56        "com.google.android.systemupdater";
57    private static final String OLD_UPDATER_CLASS =
58        "com.google.android.systemupdater.SystemUpdateReceiver";
59
60    // Keep a reference to the observer so the finalizer doesn't disable it.
61    private static FileObserver sTombstoneObserver = null;
62
63    @Override
64    public void onReceive(final Context context, Intent intent) {
65        // Log boot events in the background to avoid blocking the main thread with I/O
66        new Thread() {
67            @Override
68            public void run() {
69                try {
70                    logBootEvents(context);
71                } catch (Exception e) {
72                    Slog.e(TAG, "Can't log boot events", e);
73                }
74                try {
75                    boolean onlyCore = false;
76                    try {
77                        onlyCore = IPackageManager.Stub.asInterface(ServiceManager.getService(
78                                "package")).isOnlyCoreApps();
79                    } catch (RemoteException e) {
80                    }
81                    if (!onlyCore) {
82                        removeOldUpdatePackages(context);
83                    }
84                } catch (Exception e) {
85                    Slog.e(TAG, "Can't remove old update packages", e);
86                }
87
88            }
89        }.start();
90    }
91
92    private void removeOldUpdatePackages(Context context) {
93        Downloads.removeAllDownloadsByPackage(context, OLD_UPDATER_PACKAGE, OLD_UPDATER_CLASS);
94    }
95
96    private void logBootEvents(Context ctx) throws IOException {
97        final DropBoxManager db = (DropBoxManager) ctx.getSystemService(Context.DROPBOX_SERVICE);
98        final SharedPreferences prefs = ctx.getSharedPreferences("log_files", Context.MODE_PRIVATE);
99        final String headers = new StringBuilder(512)
100            .append("Build: ").append(Build.FINGERPRINT).append("\n")
101            .append("Hardware: ").append(Build.BOARD).append("\n")
102            .append("Revision: ")
103            .append(SystemProperties.get("ro.revision", "")).append("\n")
104            .append("Bootloader: ").append(Build.BOOTLOADER).append("\n")
105            .append("Radio: ").append(Build.RADIO).append("\n")
106            .append("Kernel: ")
107            .append(FileUtils.readTextFile(new File("/proc/version"), 1024, "...\n"))
108            .append("\n").toString();
109        final String bootReason = SystemProperties.get("ro.boot.bootreason", null);
110
111        String recovery = RecoverySystem.handleAftermath();
112        if (recovery != null && db != null) {
113            db.addText("SYSTEM_RECOVERY_LOG", headers + recovery);
114        }
115
116        String lastKmsgFooter = "";
117        if (bootReason != null) {
118            lastKmsgFooter = new StringBuilder(512)
119                .append("\n")
120                .append("Boot info:\n")
121                .append("Last boot reason: ").append(bootReason).append("\n")
122                .toString();
123        }
124
125        if (SystemProperties.getLong("ro.runtime.firstboot", 0) == 0) {
126            if ("encrypted".equals(SystemProperties.get("ro.crypto.state"))
127                && "trigger_restart_min_framework".equals(SystemProperties.get("vold.decrypt"))){
128                // Encrypted, first boot to get PIN/pattern/password so data is tmpfs
129                // Don't set ro.runtime.firstboot so that we will do this again
130                // when data is properly mounted
131            } else {
132                String now = Long.toString(System.currentTimeMillis());
133                SystemProperties.set("ro.runtime.firstboot", now);
134            }
135            if (db != null) db.addText("SYSTEM_BOOT", headers);
136
137            // Negative sizes mean to take the *tail* of the file (see FileUtils.readTextFile())
138            addFileWithFootersToDropBox(db, prefs, headers, lastKmsgFooter,
139                    "/proc/last_kmsg", -LOG_SIZE, "SYSTEM_LAST_KMSG");
140            addFileWithFootersToDropBox(db, prefs, headers, lastKmsgFooter,
141                    "/sys/fs/pstore/console-ramoops", -LOG_SIZE,
142                    "SYSTEM_LAST_KMSG");
143            addFileToDropBox(db, prefs, headers, "/cache/recovery/log",
144                    -LOG_SIZE, "SYSTEM_RECOVERY_LOG");
145            addFileToDropBox(db, prefs, headers, "/data/dontpanic/apanic_console",
146                    -LOG_SIZE, "APANIC_CONSOLE");
147            addFileToDropBox(db, prefs, headers, "/data/dontpanic/apanic_threads",
148                    -LOG_SIZE, "APANIC_THREADS");
149            addAuditErrorsToDropBox(db, prefs, headers, -LOG_SIZE, "SYSTEM_AUDIT");
150            addFsckErrorsToDropBox(db, prefs, headers, -LOG_SIZE, "SYSTEM_FSCK");
151        } else {
152            if (db != null) db.addText("SYSTEM_RESTART", headers);
153        }
154
155        // Scan existing tombstones (in case any new ones appeared)
156        File[] tombstoneFiles = TOMBSTONE_DIR.listFiles();
157        for (int i = 0; tombstoneFiles != null && i < tombstoneFiles.length; i++) {
158            if (tombstoneFiles[i].isFile()) {
159                addFileToDropBox(db, prefs, headers, tombstoneFiles[i].getPath(),
160                        LOG_SIZE, "SYSTEM_TOMBSTONE");
161            }
162        }
163
164        // Start watching for new tombstone files; will record them as they occur.
165        // This gets registered with the singleton file observer thread.
166        sTombstoneObserver = new FileObserver(TOMBSTONE_DIR.getPath(), FileObserver.CLOSE_WRITE) {
167            @Override
168            public void onEvent(int event, String path) {
169                try {
170                    File file = new File(TOMBSTONE_DIR, path);
171                    if (file.isFile()) {
172                        addFileToDropBox(db, prefs, headers, file.getPath(), LOG_SIZE, "SYSTEM_TOMBSTONE");
173                    }
174                } catch (IOException e) {
175                    Slog.e(TAG, "Can't log tombstone", e);
176                }
177            }
178        };
179
180        sTombstoneObserver.startWatching();
181    }
182
183    private static void addFileToDropBox(
184            DropBoxManager db, SharedPreferences prefs,
185            String headers, String filename, int maxSize, String tag) throws IOException {
186        addFileWithFootersToDropBox(db, prefs, headers, "", filename, maxSize,
187                tag);
188    }
189
190    private static void addFileWithFootersToDropBox(
191            DropBoxManager db, SharedPreferences prefs,
192            String headers, String footers, String filename, int maxSize,
193            String tag) throws IOException {
194        if (db == null || !db.isTagEnabled(tag)) return;  // Logging disabled
195
196        File file = new File(filename);
197        long fileTime = file.lastModified();
198        if (fileTime <= 0) return;  // File does not exist
199
200        if (prefs != null) {
201            long lastTime = prefs.getLong(filename, 0);
202            if (lastTime == fileTime) return;  // Already logged this particular file
203            // TODO: move all these SharedPreferences Editor commits
204            // outside this function to the end of logBootEvents
205            prefs.edit().putLong(filename, fileTime).apply();
206        }
207
208        Slog.i(TAG, "Copying " + filename + " to DropBox (" + tag + ")");
209        db.addText(tag, headers + FileUtils.readTextFile(file, maxSize, "[[TRUNCATED]]\n") + footers);
210    }
211
212    private static void addAuditErrorsToDropBox(DropBoxManager db,  SharedPreferences prefs,
213            String headers, int maxSize, String tag) throws IOException {
214        if (db == null || !db.isTagEnabled(tag)) return;  // Logging disabled
215        Slog.i(TAG, "Copying audit failures to DropBox");
216
217        File file = new File("/proc/last_kmsg");
218        long fileTime = file.lastModified();
219        if (fileTime <= 0) {
220            file = new File("/sys/fs/pstore/console-ramoops");
221            fileTime = file.lastModified();
222        }
223
224        if (fileTime <= 0) return;  // File does not exist
225
226        if (prefs != null) {
227            long lastTime = prefs.getLong(tag, 0);
228            if (lastTime == fileTime) return;  // Already logged this particular file
229            // TODO: move all these SharedPreferences Editor commits
230            // outside this function to the end of logBootEvents
231            prefs.edit().putLong(tag, fileTime).apply();
232        }
233
234        String log = FileUtils.readTextFile(file, maxSize, "[[TRUNCATED]]\n");
235        StringBuilder sb = new StringBuilder();
236        for (String line : log.split("\n")) {
237            if (line.contains("audit")) {
238                sb.append(line + "\n");
239            }
240        }
241        Slog.i(TAG, "Copied " + sb.toString().length() + " worth of audits to DropBox");
242        db.addText(tag, headers + sb.toString());
243    }
244
245    private static void addFsckErrorsToDropBox(DropBoxManager db,  SharedPreferences prefs,
246            String headers, int maxSize, String tag) throws IOException {
247        boolean upload_needed = false;
248        if (db == null || !db.isTagEnabled(tag)) return;  // Logging disabled
249        Slog.i(TAG, "Checking for fsck errors");
250
251        File file = new File("/dev/fscklogs/log");
252        long fileTime = file.lastModified();
253        if (fileTime <= 0) return;  // File does not exist
254
255        String log = FileUtils.readTextFile(file, maxSize, "[[TRUNCATED]]\n");
256        StringBuilder sb = new StringBuilder();
257        for (String line : log.split("\n")) {
258            if (line.contains("FILE SYSTEM WAS MODIFIED")) {
259                upload_needed = true;
260                break;
261            }
262        }
263
264        if (upload_needed) {
265            addFileToDropBox(db, prefs, headers, "/dev/fscklogs/log", maxSize, tag);
266        }
267
268        // Remove the file so we don't re-upload if the runtime restarts.
269        file.delete();
270    }
271}
272