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 com.android.internal.app.ProcessStats;
20import com.android.internal.os.BatteryStatsImpl;
21import com.android.server.LocalServices;
22import com.android.server.notification.NotificationManagerInternal;
23
24import android.app.INotificationManager;
25import android.app.Notification;
26import android.app.NotificationManager;
27import android.app.PendingIntent;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
31import android.content.pm.ApplicationInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.ServiceInfo;
34import android.net.Uri;
35import android.os.Binder;
36import android.os.IBinder;
37import android.os.RemoteException;
38import android.os.SystemClock;
39import android.os.UserHandle;
40import android.provider.Settings;
41import android.util.ArrayMap;
42import android.util.Slog;
43import android.util.TimeUtils;
44
45import java.io.PrintWriter;
46import java.util.ArrayList;
47import java.util.List;
48import java.util.Objects;
49
50/**
51 * A running application service.
52 */
53final class ServiceRecord extends Binder {
54    // Maximum number of delivery attempts before giving up.
55    static final int MAX_DELIVERY_COUNT = 3;
56
57    // Maximum number of times it can fail during execution before giving up.
58    static final int MAX_DONE_EXECUTING_COUNT = 6;
59
60    final ActivityManagerService ams;
61    final BatteryStatsImpl.Uid.Pkg.Serv stats;
62    final ComponentName name; // service component.
63    final String shortName; // name.flattenToShortString().
64    final Intent.FilterComparison intent;
65                            // original intent used to find service.
66    final ServiceInfo serviceInfo;
67                            // all information about the service.
68    final ApplicationInfo appInfo;
69                            // information about service's app.
70    final int userId;       // user that this service is running as
71    final String packageName; // the package implementing intent's component
72    final String processName; // process where this component wants to run
73    final String permission;// permission needed to access service
74    final boolean exported; // from ServiceInfo.exported
75    final Runnable restarter; // used to schedule retries of starting the service
76    final long createTime;  // when this service was created
77    final ArrayMap<Intent.FilterComparison, IntentBindRecord> bindings
78            = new ArrayMap<Intent.FilterComparison, IntentBindRecord>();
79                            // All active bindings to the service.
80    final ArrayMap<IBinder, ArrayList<ConnectionRecord>> connections
81            = new ArrayMap<IBinder, ArrayList<ConnectionRecord>>();
82                            // IBinder -> ConnectionRecord of all bound clients
83
84    ProcessRecord app;      // where this service is running or null.
85    ProcessRecord isolatedProc; // keep track of isolated process, if requested
86    ProcessStats.ServiceState tracker; // tracking service execution, may be null
87    ProcessStats.ServiceState restartTracker; // tracking service restart
88    boolean delayed;        // are we waiting to start this service in the background?
89    boolean isForeground;   // is service currently in foreground mode?
90    int foregroundId;       // Notification ID of last foreground req.
91    Notification foregroundNoti; // Notification record of foreground state.
92    long lastActivity;      // last time there was some activity on the service.
93    long startingBgTimeout;  // time at which we scheduled this for a delayed start.
94    boolean startRequested; // someone explicitly called start?
95    boolean delayedStop;    // service has been stopped but is in a delayed start?
96    boolean stopIfKilled;   // last onStart() said to stop if service killed?
97    boolean callStart;      // last onStart() has asked to alway be called on restart.
98    int executeNesting;     // number of outstanding operations keeping foreground.
99    boolean executeFg;      // should we be executing in the foreground?
100    long executingStart;    // start time of last execute request.
101    boolean createdFromFg;  // was this service last created due to a foreground process call?
102    int crashCount;         // number of times proc has crashed with service running
103    int totalRestartCount;  // number of times we have had to restart.
104    int restartCount;       // number of restarts performed in a row.
105    long restartDelay;      // delay until next restart attempt.
106    long restartTime;       // time of last restart.
107    long nextRestartTime;   // time when restartDelay will expire.
108
109    String stringName;      // caching of toString
110
111    private int lastStartId;    // identifier of most recent start request.
112
113    static class StartItem {
114        final ServiceRecord sr;
115        final boolean taskRemoved;
116        final int id;
117        final Intent intent;
118        final ActivityManagerService.NeededUriGrants neededGrants;
119        long deliveredTime;
120        int deliveryCount;
121        int doneExecutingCount;
122        UriPermissionOwner uriPermissions;
123
124        String stringName;      // caching of toString
125
126        StartItem(ServiceRecord _sr, boolean _taskRemoved, int _id, Intent _intent,
127                ActivityManagerService.NeededUriGrants _neededGrants) {
128            sr = _sr;
129            taskRemoved = _taskRemoved;
130            id = _id;
131            intent = _intent;
132            neededGrants = _neededGrants;
133        }
134
135        UriPermissionOwner getUriPermissionsLocked() {
136            if (uriPermissions == null) {
137                uriPermissions = new UriPermissionOwner(sr.ams, this);
138            }
139            return uriPermissions;
140        }
141
142        void removeUriPermissionsLocked() {
143            if (uriPermissions != null) {
144                uriPermissions.removeUriPermissionsLocked();
145                uriPermissions = null;
146            }
147        }
148
149        public String toString() {
150            if (stringName != null) {
151                return stringName;
152            }
153            StringBuilder sb = new StringBuilder(128);
154            sb.append("ServiceRecord{")
155                .append(Integer.toHexString(System.identityHashCode(sr)))
156                .append(' ').append(sr.shortName)
157                .append(" StartItem ")
158                .append(Integer.toHexString(System.identityHashCode(this)))
159                .append(" id=").append(id).append('}');
160            return stringName = sb.toString();
161        }
162    }
163
164    final ArrayList<StartItem> deliveredStarts = new ArrayList<StartItem>();
165                            // start() arguments which been delivered.
166    final ArrayList<StartItem> pendingStarts = new ArrayList<StartItem>();
167                            // start() arguments that haven't yet been delivered.
168
169    void dumpStartList(PrintWriter pw, String prefix, List<StartItem> list, long now) {
170        final int N = list.size();
171        for (int i=0; i<N; i++) {
172            StartItem si = list.get(i);
173            pw.print(prefix); pw.print("#"); pw.print(i);
174                    pw.print(" id="); pw.print(si.id);
175                    if (now != 0) {
176                        pw.print(" dur=");
177                        TimeUtils.formatDuration(si.deliveredTime, now, pw);
178                    }
179                    if (si.deliveryCount != 0) {
180                        pw.print(" dc="); pw.print(si.deliveryCount);
181                    }
182                    if (si.doneExecutingCount != 0) {
183                        pw.print(" dxc="); pw.print(si.doneExecutingCount);
184                    }
185                    pw.println("");
186            pw.print(prefix); pw.print("  intent=");
187                    if (si.intent != null) pw.println(si.intent.toString());
188                    else pw.println("null");
189            if (si.neededGrants != null) {
190                pw.print(prefix); pw.print("  neededGrants=");
191                        pw.println(si.neededGrants);
192            }
193            if (si.uriPermissions != null) {
194                si.uriPermissions.dump(pw, prefix);
195            }
196        }
197    }
198
199    void dump(PrintWriter pw, String prefix) {
200        pw.print(prefix); pw.print("intent={");
201                pw.print(intent.getIntent().toShortString(false, true, false, true));
202                pw.println('}');
203        pw.print(prefix); pw.print("packageName="); pw.println(packageName);
204        pw.print(prefix); pw.print("processName="); pw.println(processName);
205        if (permission != null) {
206            pw.print(prefix); pw.print("permission="); pw.println(permission);
207        }
208        long now = SystemClock.uptimeMillis();
209        long nowReal = SystemClock.elapsedRealtime();
210        if (appInfo != null) {
211            pw.print(prefix); pw.print("baseDir="); pw.println(appInfo.sourceDir);
212            if (!Objects.equals(appInfo.sourceDir, appInfo.publicSourceDir)) {
213                pw.print(prefix); pw.print("resDir="); pw.println(appInfo.publicSourceDir);
214            }
215            pw.print(prefix); pw.print("dataDir="); pw.println(appInfo.dataDir);
216        }
217        pw.print(prefix); pw.print("app="); pw.println(app);
218        if (isolatedProc != null) {
219            pw.print(prefix); pw.print("isolatedProc="); pw.println(isolatedProc);
220        }
221        if (delayed) {
222            pw.print(prefix); pw.print("delayed="); pw.println(delayed);
223        }
224        if (isForeground || foregroundId != 0) {
225            pw.print(prefix); pw.print("isForeground="); pw.print(isForeground);
226                    pw.print(" foregroundId="); pw.print(foregroundId);
227                    pw.print(" foregroundNoti="); pw.println(foregroundNoti);
228        }
229        pw.print(prefix); pw.print("createTime=");
230                TimeUtils.formatDuration(createTime, nowReal, pw);
231                pw.print(" startingBgTimeout=");
232                TimeUtils.formatDuration(startingBgTimeout, now, pw);
233                pw.println();
234        pw.print(prefix); pw.print("lastActivity=");
235                TimeUtils.formatDuration(lastActivity, now, pw);
236                pw.print(" restartTime=");
237                TimeUtils.formatDuration(restartTime, now, pw);
238                pw.print(" createdFromFg="); pw.println(createdFromFg);
239        if (startRequested || delayedStop || lastStartId != 0) {
240            pw.print(prefix); pw.print("startRequested="); pw.print(startRequested);
241                    pw.print(" delayedStop="); pw.print(delayedStop);
242                    pw.print(" stopIfKilled="); pw.print(stopIfKilled);
243                    pw.print(" callStart="); pw.print(callStart);
244                    pw.print(" lastStartId="); pw.println(lastStartId);
245        }
246        if (executeNesting != 0) {
247            pw.print(prefix); pw.print("executeNesting="); pw.print(executeNesting);
248                    pw.print(" executeFg="); pw.print(executeFg);
249                    pw.print(" executingStart=");
250                    TimeUtils.formatDuration(executingStart, now, pw);
251                    pw.println();
252        }
253        if (crashCount != 0 || restartCount != 0
254                || restartDelay != 0 || nextRestartTime != 0) {
255            pw.print(prefix); pw.print("restartCount="); pw.print(restartCount);
256                    pw.print(" restartDelay=");
257                    TimeUtils.formatDuration(restartDelay, now, pw);
258                    pw.print(" nextRestartTime=");
259                    TimeUtils.formatDuration(nextRestartTime, now, pw);
260                    pw.print(" crashCount="); pw.println(crashCount);
261        }
262        if (deliveredStarts.size() > 0) {
263            pw.print(prefix); pw.println("Delivered Starts:");
264            dumpStartList(pw, prefix, deliveredStarts, now);
265        }
266        if (pendingStarts.size() > 0) {
267            pw.print(prefix); pw.println("Pending Starts:");
268            dumpStartList(pw, prefix, pendingStarts, 0);
269        }
270        if (bindings.size() > 0) {
271            pw.print(prefix); pw.println("Bindings:");
272            for (int i=0; i<bindings.size(); i++) {
273                IntentBindRecord b = bindings.valueAt(i);
274                pw.print(prefix); pw.print("* IntentBindRecord{");
275                        pw.print(Integer.toHexString(System.identityHashCode(b)));
276                        if ((b.collectFlags()&Context.BIND_AUTO_CREATE) != 0) {
277                            pw.append(" CREATE");
278                        }
279                        pw.println("}:");
280                b.dumpInService(pw, prefix + "  ");
281            }
282        }
283        if (connections.size() > 0) {
284            pw.print(prefix); pw.println("All Connections:");
285            for (int conni=0; conni<connections.size(); conni++) {
286                ArrayList<ConnectionRecord> c = connections.valueAt(conni);
287                for (int i=0; i<c.size(); i++) {
288                    pw.print(prefix); pw.print("  "); pw.println(c.get(i));
289                }
290            }
291        }
292    }
293
294    ServiceRecord(ActivityManagerService ams,
295            BatteryStatsImpl.Uid.Pkg.Serv servStats, ComponentName name,
296            Intent.FilterComparison intent, ServiceInfo sInfo, boolean callerIsFg,
297            Runnable restarter) {
298        this.ams = ams;
299        this.stats = servStats;
300        this.name = name;
301        shortName = name.flattenToShortString();
302        this.intent = intent;
303        serviceInfo = sInfo;
304        appInfo = sInfo.applicationInfo;
305        packageName = sInfo.applicationInfo.packageName;
306        processName = sInfo.processName;
307        permission = sInfo.permission;
308        exported = sInfo.exported;
309        this.restarter = restarter;
310        createTime = SystemClock.elapsedRealtime();
311        lastActivity = SystemClock.uptimeMillis();
312        userId = UserHandle.getUserId(appInfo.uid);
313        createdFromFg = callerIsFg;
314    }
315
316    public ProcessStats.ServiceState getTracker() {
317        if (tracker != null) {
318            return tracker;
319        }
320        if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
321            tracker = ams.mProcessStats.getServiceStateLocked(serviceInfo.packageName,
322                    serviceInfo.applicationInfo.uid, serviceInfo.applicationInfo.versionCode,
323                    serviceInfo.processName, serviceInfo.name);
324            tracker.applyNewOwner(this);
325        }
326        return tracker;
327    }
328
329    public void forceClearTracker() {
330        if (tracker != null) {
331            tracker.clearCurrentOwner(this, true);
332            tracker = null;
333        }
334    }
335
336    public void makeRestarting(int memFactor, long now) {
337        if (restartTracker == null) {
338            if ((serviceInfo.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) == 0) {
339                restartTracker = ams.mProcessStats.getServiceStateLocked(serviceInfo.packageName,
340                        serviceInfo.applicationInfo.uid, serviceInfo.applicationInfo.versionCode,
341                        serviceInfo.processName, serviceInfo.name);
342            }
343            if (restartTracker == null) {
344                return;
345            }
346        }
347        restartTracker.setRestarting(true, memFactor, now);
348    }
349
350    public AppBindRecord retrieveAppBindingLocked(Intent intent,
351            ProcessRecord app) {
352        Intent.FilterComparison filter = new Intent.FilterComparison(intent);
353        IntentBindRecord i = bindings.get(filter);
354        if (i == null) {
355            i = new IntentBindRecord(this, filter);
356            bindings.put(filter, i);
357        }
358        AppBindRecord a = i.apps.get(app);
359        if (a != null) {
360            return a;
361        }
362        a = new AppBindRecord(this, i, app);
363        i.apps.put(app, a);
364        return a;
365    }
366
367    public boolean hasAutoCreateConnections() {
368        // XXX should probably keep a count of the number of auto-create
369        // connections directly in the service.
370        for (int conni=connections.size()-1; conni>=0; conni--) {
371            ArrayList<ConnectionRecord> cr = connections.valueAt(conni);
372            for (int i=0; i<cr.size(); i++) {
373                if ((cr.get(i).flags&Context.BIND_AUTO_CREATE) != 0) {
374                    return true;
375                }
376            }
377        }
378        return false;
379    }
380
381    public void resetRestartCounter() {
382        restartCount = 0;
383        restartDelay = 0;
384        restartTime = 0;
385    }
386
387    public StartItem findDeliveredStart(int id, boolean remove) {
388        final int N = deliveredStarts.size();
389        for (int i=0; i<N; i++) {
390            StartItem si = deliveredStarts.get(i);
391            if (si.id == id) {
392                if (remove) deliveredStarts.remove(i);
393                return si;
394            }
395        }
396
397        return null;
398    }
399
400    public int getLastStartId() {
401        return lastStartId;
402    }
403
404    public int makeNextStartId() {
405        lastStartId++;
406        if (lastStartId < 1) {
407            lastStartId = 1;
408        }
409        return lastStartId;
410    }
411
412    public void postNotification() {
413        final int appUid = appInfo.uid;
414        final int appPid = app.pid;
415        if (foregroundId != 0 && foregroundNoti != null) {
416            // Do asynchronous communication with notification manager to
417            // avoid deadlocks.
418            final String localPackageName = packageName;
419            final int localForegroundId = foregroundId;
420            final Notification localForegroundNoti = foregroundNoti;
421            ams.mHandler.post(new Runnable() {
422                public void run() {
423                    NotificationManagerInternal nm = LocalServices.getService(
424                            NotificationManagerInternal.class);
425                    if (nm == null) {
426                        return;
427                    }
428                    try {
429                        if (localForegroundNoti.icon == 0) {
430                            // It is not correct for the caller to supply a notification
431                            // icon, but this used to be able to slip through, so for
432                            // those dirty apps give it the app's icon.
433                            localForegroundNoti.icon = appInfo.icon;
434
435                            // Do not allow apps to present a sneaky invisible content view either.
436                            localForegroundNoti.contentView = null;
437                            localForegroundNoti.bigContentView = null;
438                            CharSequence appName = appInfo.loadLabel(
439                                    ams.mContext.getPackageManager());
440                            if (appName == null) {
441                                appName = appInfo.packageName;
442                            }
443                            Context ctx = null;
444                            try {
445                                ctx = ams.mContext.createPackageContext(
446                                        appInfo.packageName, 0);
447                                Intent runningIntent = new Intent(
448                                        Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
449                                runningIntent.setData(Uri.fromParts("package",
450                                        appInfo.packageName, null));
451                                PendingIntent pi = PendingIntent.getActivity(ams.mContext, 0,
452                                        runningIntent, PendingIntent.FLAG_UPDATE_CURRENT);
453                                localForegroundNoti.color = ams.mContext.getResources().getColor(
454                                        com.android.internal
455                                                .R.color.system_notification_accent_color);
456                                localForegroundNoti.setLatestEventInfo(ctx,
457                                        ams.mContext.getString(
458                                                com.android.internal.R.string
459                                                        .app_running_notification_title,
460                                                appName),
461                                        ams.mContext.getString(
462                                                com.android.internal.R.string
463                                                        .app_running_notification_text,
464                                                appName),
465                                        pi);
466                            } catch (PackageManager.NameNotFoundException e) {
467                                localForegroundNoti.icon = 0;
468                            }
469                        }
470                        if (localForegroundNoti.icon == 0) {
471                            // Notifications whose icon is 0 are defined to not show
472                            // a notification, silently ignoring it.  We don't want to
473                            // just ignore it, we want to prevent the service from
474                            // being foreground.
475                            throw new RuntimeException("icon must be non-zero");
476                        }
477                        int[] outId = new int[1];
478                        nm.enqueueNotification(localPackageName, localPackageName,
479                                appUid, appPid, null, localForegroundId, localForegroundNoti,
480                                outId, userId);
481                    } catch (RuntimeException e) {
482                        Slog.w(ActivityManagerService.TAG,
483                                "Error showing notification for service", e);
484                        // If it gave us a garbage notification, it doesn't
485                        // get to be foreground.
486                        ams.setServiceForeground(name, ServiceRecord.this,
487                                0, null, true);
488                        ams.crashApplication(appUid, appPid, localPackageName,
489                                "Bad notification for startForeground: " + e);
490                    }
491                }
492            });
493        }
494    }
495
496    public void cancelNotification() {
497        if (foregroundId != 0) {
498            // Do asynchronous communication with notification manager to
499            // avoid deadlocks.
500            final String localPackageName = packageName;
501            final int localForegroundId = foregroundId;
502            ams.mHandler.post(new Runnable() {
503                public void run() {
504                    INotificationManager inm = NotificationManager.getService();
505                    if (inm == null) {
506                        return;
507                    }
508                    try {
509                        inm.cancelNotificationWithTag(localPackageName, null,
510                                localForegroundId, userId);
511                    } catch (RuntimeException e) {
512                        Slog.w(ActivityManagerService.TAG,
513                                "Error canceling notification for service", e);
514                    } catch (RemoteException e) {
515                    }
516                }
517            });
518        }
519    }
520
521    public void stripForegroundServiceFlagFromNotification() {
522        if (foregroundId == 0) {
523            return;
524        }
525
526        final int localForegroundId = foregroundId;
527        final int localUserId = userId;
528        final String localPackageName = packageName;
529
530        // Do asynchronous communication with notification manager to
531        // avoid deadlocks.
532        ams.mHandler.post(new Runnable() {
533            @Override
534            public void run() {
535                NotificationManagerInternal nmi = LocalServices.getService(
536                        NotificationManagerInternal.class);
537                if (nmi == null) {
538                    return;
539                }
540                nmi.removeForegroundServiceFlagFromNotification(localPackageName, localForegroundId,
541                        localUserId);
542            }
543        });
544    }
545
546    public void clearDeliveredStartsLocked() {
547        for (int i=deliveredStarts.size()-1; i>=0; i--) {
548            deliveredStarts.get(i).removeUriPermissionsLocked();
549        }
550        deliveredStarts.clear();
551    }
552
553    public String toString() {
554        if (stringName != null) {
555            return stringName;
556        }
557        StringBuilder sb = new StringBuilder(128);
558        sb.append("ServiceRecord{")
559            .append(Integer.toHexString(System.identityHashCode(this)))
560            .append(" u").append(userId)
561            .append(' ').append(shortName).append('}');
562        return stringName = sb.toString();
563    }
564}
565