1/*
2 * Copyright (C) 2006 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.am;
18
19import android.app.AppOpsManager;
20import android.app.BroadcastOptions;
21import android.content.IIntentReceiver;
22import android.content.ComponentName;
23import android.content.Intent;
24import android.content.pm.ActivityInfo;
25import android.content.pm.ResolveInfo;
26import android.os.Binder;
27import android.os.Bundle;
28import android.os.IBinder;
29import android.os.SystemClock;
30import android.os.UserHandle;
31import android.util.PrintWriterPrinter;
32import android.util.TimeUtils;
33
34import java.io.PrintWriter;
35import java.text.SimpleDateFormat;
36import java.util.Arrays;
37import java.util.Date;
38import java.util.List;
39import java.util.Set;
40
41/**
42 * An active intent broadcast.
43 */
44final class BroadcastRecord extends Binder {
45    final Intent intent;    // the original intent that generated us
46    final ComponentName targetComp; // original component name set on the intent
47    final ProcessRecord callerApp; // process that sent this
48    final String callerPackage; // who sent this
49    final int callingPid;   // the pid of who sent this
50    final int callingUid;   // the uid of who sent this
51    final boolean callerInstantApp; // caller is an Instant App?
52    final boolean ordered;  // serialize the send to receivers?
53    final boolean sticky;   // originated from existing sticky data?
54    final boolean initialSticky; // initial broadcast from register to sticky?
55    final int userId;       // user id this broadcast was for
56    final String resolvedType; // the resolved data type
57    final String[] requiredPermissions; // permissions the caller has required
58    final int appOp;        // an app op that is associated with this broadcast
59    final BroadcastOptions options; // BroadcastOptions supplied by caller
60    final List receivers;   // contains BroadcastFilter and ResolveInfo
61    final int[] delivery;   // delivery state of each receiver
62    IIntentReceiver resultTo; // who receives final result if non-null
63    long enqueueClockTime;  // the clock time the broadcast was enqueued
64    long dispatchTime;      // when dispatch started on this set of receivers
65    long dispatchClockTime; // the clock time the dispatch started
66    long receiverTime;      // when current receiver started for timeouts.
67    long finishTime;        // when we finished the broadcast.
68    int resultCode;         // current result code value.
69    String resultData;      // current result data value.
70    Bundle resultExtras;    // current result extra data values.
71    boolean resultAbort;    // current result abortBroadcast value.
72    int nextReceiver;       // next receiver to be executed.
73    IBinder receiver;       // who is currently running, null if none.
74    int state;
75    int anrCount;           // has this broadcast record hit any ANRs?
76    int manifestCount;      // number of manifest receivers dispatched.
77    int manifestSkipCount;  // number of manifest receivers skipped.
78    BroadcastQueue queue;   // the outbound queue handling this broadcast
79
80    static final int IDLE = 0;
81    static final int APP_RECEIVE = 1;
82    static final int CALL_IN_RECEIVE = 2;
83    static final int CALL_DONE_RECEIVE = 3;
84    static final int WAITING_SERVICES = 4;
85
86    static final int DELIVERY_PENDING = 0;
87    static final int DELIVERY_DELIVERED = 1;
88    static final int DELIVERY_SKIPPED = 2;
89    static final int DELIVERY_TIMEOUT = 3;
90
91    // The following are set when we are calling a receiver (one that
92    // was found in our list of registered receivers).
93    BroadcastFilter curFilter;
94
95    // The following are set only when we are launching a receiver (one
96    // that was found by querying the package manager).
97    ProcessRecord curApp;       // hosting application of current receiver.
98    ComponentName curComponent; // the receiver class that is currently running.
99    ActivityInfo curReceiver;   // info about the receiver that is currently running.
100
101    void dump(PrintWriter pw, String prefix, SimpleDateFormat sdf) {
102        final long now = SystemClock.uptimeMillis();
103
104        pw.print(prefix); pw.print(this); pw.print(" to user "); pw.println(userId);
105        pw.print(prefix); pw.println(intent.toInsecureString());
106        if (targetComp != null && targetComp != intent.getComponent()) {
107            pw.print(prefix); pw.print("  targetComp: "); pw.println(targetComp.toShortString());
108        }
109        Bundle bundle = intent.getExtras();
110        if (bundle != null) {
111            pw.print(prefix); pw.print("  extras: "); pw.println(bundle.toString());
112        }
113        pw.print(prefix); pw.print("caller="); pw.print(callerPackage); pw.print(" ");
114                pw.print(callerApp != null ? callerApp.toShortString() : "null");
115                pw.print(" pid="); pw.print(callingPid);
116                pw.print(" uid="); pw.println(callingUid);
117        if ((requiredPermissions != null && requiredPermissions.length > 0)
118                || appOp != AppOpsManager.OP_NONE) {
119            pw.print(prefix); pw.print("requiredPermissions=");
120            pw.print(Arrays.toString(requiredPermissions));
121            pw.print("  appOp="); pw.println(appOp);
122        }
123        if (options != null) {
124            pw.print(prefix); pw.print("options="); pw.println(options.toBundle());
125        }
126        pw.print(prefix); pw.print("enqueueClockTime=");
127                pw.print(sdf.format(new Date(enqueueClockTime)));
128                pw.print(" dispatchClockTime=");
129                pw.println(sdf.format(new Date(dispatchClockTime)));
130        pw.print(prefix); pw.print("dispatchTime=");
131                TimeUtils.formatDuration(dispatchTime, now, pw);
132                pw.print(" (");
133                TimeUtils.formatDuration(dispatchClockTime-enqueueClockTime, pw);
134                pw.print(" since enq)");
135        if (finishTime != 0) {
136            pw.print(" finishTime="); TimeUtils.formatDuration(finishTime, now, pw);
137            pw.print(" (");
138            TimeUtils.formatDuration(finishTime-dispatchTime, pw);
139            pw.print(" since disp)");
140        } else {
141            pw.print(" receiverTime="); TimeUtils.formatDuration(receiverTime, now, pw);
142        }
143        pw.println("");
144        if (anrCount != 0) {
145            pw.print(prefix); pw.print("anrCount="); pw.println(anrCount);
146        }
147        if (resultTo != null || resultCode != -1 || resultData != null) {
148            pw.print(prefix); pw.print("resultTo="); pw.print(resultTo);
149                    pw.print(" resultCode="); pw.print(resultCode);
150                    pw.print(" resultData="); pw.println(resultData);
151        }
152        if (resultExtras != null) {
153            pw.print(prefix); pw.print("resultExtras="); pw.println(resultExtras);
154        }
155        if (resultAbort || ordered || sticky || initialSticky) {
156            pw.print(prefix); pw.print("resultAbort="); pw.print(resultAbort);
157                    pw.print(" ordered="); pw.print(ordered);
158                    pw.print(" sticky="); pw.print(sticky);
159                    pw.print(" initialSticky="); pw.println(initialSticky);
160        }
161        if (nextReceiver != 0 || receiver != null) {
162            pw.print(prefix); pw.print("nextReceiver="); pw.print(nextReceiver);
163                    pw.print(" receiver="); pw.println(receiver);
164        }
165        if (curFilter != null) {
166            pw.print(prefix); pw.print("curFilter="); pw.println(curFilter);
167        }
168        if (curReceiver != null) {
169            pw.print(prefix); pw.print("curReceiver="); pw.println(curReceiver);
170        }
171        if (curApp != null) {
172            pw.print(prefix); pw.print("curApp="); pw.println(curApp);
173            pw.print(prefix); pw.print("curComponent=");
174                    pw.println((curComponent != null ? curComponent.toShortString() : "--"));
175            if (curReceiver != null && curReceiver.applicationInfo != null) {
176                pw.print(prefix); pw.print("curSourceDir=");
177                        pw.println(curReceiver.applicationInfo.sourceDir);
178            }
179        }
180        if (state != IDLE) {
181            String stateStr = " (?)";
182            switch (state) {
183                case APP_RECEIVE:       stateStr=" (APP_RECEIVE)"; break;
184                case CALL_IN_RECEIVE:   stateStr=" (CALL_IN_RECEIVE)"; break;
185                case CALL_DONE_RECEIVE: stateStr=" (CALL_DONE_RECEIVE)"; break;
186                case WAITING_SERVICES:  stateStr=" (WAITING_SERVICES)"; break;
187            }
188            pw.print(prefix); pw.print("state="); pw.print(state); pw.println(stateStr);
189        }
190        final int N = receivers != null ? receivers.size() : 0;
191        String p2 = prefix + "  ";
192        PrintWriterPrinter printer = new PrintWriterPrinter(pw);
193        for (int i = 0; i < N; i++) {
194            Object o = receivers.get(i);
195            pw.print(prefix);
196            switch (delivery[i]) {
197                case DELIVERY_PENDING:   pw.print("Pending"); break;
198                case DELIVERY_DELIVERED: pw.print("Deliver"); break;
199                case DELIVERY_SKIPPED:   pw.print("Skipped"); break;
200                case DELIVERY_TIMEOUT:   pw.print("Timeout"); break;
201                default:                 pw.print("???????"); break;
202            }
203            pw.print(" #"); pw.print(i); pw.print(": ");
204            if (o instanceof BroadcastFilter) {
205                pw.println(o);
206                ((BroadcastFilter) o).dumpBrief(pw, p2);
207            } else if (o instanceof ResolveInfo) {
208                pw.println("(manifest)");
209                ((ResolveInfo) o).dump(printer, p2, 0);
210            } else {
211                pw.println(o);
212            }
213        }
214    }
215
216    BroadcastRecord(BroadcastQueue _queue,
217            Intent _intent, ProcessRecord _callerApp, String _callerPackage,
218            int _callingPid, int _callingUid, boolean _callerInstantApp, String _resolvedType,
219            String[] _requiredPermissions, int _appOp, BroadcastOptions _options, List _receivers,
220            IIntentReceiver _resultTo, int _resultCode, String _resultData, Bundle _resultExtras,
221            boolean _serialized, boolean _sticky, boolean _initialSticky, int _userId) {
222        if (_intent == null) {
223            throw new NullPointerException("Can't construct with a null intent");
224        }
225        queue = _queue;
226        intent = _intent;
227        targetComp = _intent.getComponent();
228        callerApp = _callerApp;
229        callerPackage = _callerPackage;
230        callingPid = _callingPid;
231        callingUid = _callingUid;
232        callerInstantApp = _callerInstantApp;
233        resolvedType = _resolvedType;
234        requiredPermissions = _requiredPermissions;
235        appOp = _appOp;
236        options = _options;
237        receivers = _receivers;
238        delivery = new int[_receivers != null ? _receivers.size() : 0];
239        resultTo = _resultTo;
240        resultCode = _resultCode;
241        resultData = _resultData;
242        resultExtras = _resultExtras;
243        ordered = _serialized;
244        sticky = _sticky;
245        initialSticky = _initialSticky;
246        userId = _userId;
247        nextReceiver = 0;
248        state = IDLE;
249    }
250
251    /**
252     * Copy constructor which takes a different intent.
253     * Only used by {@link #maybeStripForHistory}.
254     */
255    private BroadcastRecord(BroadcastRecord from, Intent newIntent) {
256        intent = newIntent;
257        targetComp = newIntent.getComponent();
258
259        callerApp = from.callerApp;
260        callerPackage = from.callerPackage;
261        callingPid = from.callingPid;
262        callingUid = from.callingUid;
263        callerInstantApp = from.callerInstantApp;
264        ordered = from.ordered;
265        sticky = from.sticky;
266        initialSticky = from.initialSticky;
267        userId = from.userId;
268        resolvedType = from.resolvedType;
269        requiredPermissions = from.requiredPermissions;
270        appOp = from.appOp;
271        options = from.options;
272        receivers = from.receivers;
273        delivery = from.delivery;
274        resultTo = from.resultTo;
275        enqueueClockTime = from.enqueueClockTime;
276        dispatchTime = from.dispatchTime;
277        dispatchClockTime = from.dispatchClockTime;
278        receiverTime = from.receiverTime;
279        finishTime = from.finishTime;
280        resultCode = from.resultCode;
281        resultData = from.resultData;
282        resultExtras = from.resultExtras;
283        resultAbort = from.resultAbort;
284        nextReceiver = from.nextReceiver;
285        receiver = from.receiver;
286        state = from.state;
287        anrCount = from.anrCount;
288        manifestCount = from.manifestCount;
289        manifestSkipCount = from.manifestSkipCount;
290        queue = from.queue;
291    }
292
293    public BroadcastRecord maybeStripForHistory() {
294        if (!intent.canStripForHistory()) {
295            return this;
296        }
297        return new BroadcastRecord(this, intent.maybeStripForHistory());
298    }
299
300    boolean cleanupDisabledPackageReceiversLocked(
301            String packageName, Set<String> filterByClasses, int userId, boolean doit) {
302        if ((userId != UserHandle.USER_ALL && this.userId != userId) || receivers == null) {
303            return false;
304        }
305
306        boolean didSomething = false;
307        Object o;
308        for (int i = receivers.size() - 1; i >= 0; i--) {
309            o = receivers.get(i);
310            if (!(o instanceof ResolveInfo)) {
311                continue;
312            }
313            ActivityInfo info = ((ResolveInfo)o).activityInfo;
314
315            final boolean sameComponent = packageName == null
316                    || (info.applicationInfo.packageName.equals(packageName)
317                    && (filterByClasses == null || filterByClasses.contains(info.name)));
318            if (sameComponent) {
319                if (!doit) {
320                    return true;
321                }
322                didSomething = true;
323                receivers.remove(i);
324                if (i < nextReceiver) {
325                    nextReceiver--;
326                }
327            }
328        }
329        nextReceiver = Math.min(nextReceiver, receivers.size());
330
331        return didSomething;
332    }
333
334    public String toString() {
335        return "BroadcastRecord{"
336            + Integer.toHexString(System.identityHashCode(this))
337            + " u" + userId + " " + intent.getAction() + "}";
338    }
339}
340