1 /*
2  * Copyright (C) 2013 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 
17 package com.android.server;
18 
19 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT;
20 
21 import android.annotation.IntDef;
22 import android.annotation.NonNull;
23 import android.annotation.Nullable;
24 import android.annotation.SystemApi;
25 import android.annotation.SystemApi.Client;
26 import android.annotation.UserIdInt;
27 import android.app.ActivityThread;
28 import android.content.Context;
29 import android.content.pm.UserInfo;
30 import android.os.IBinder;
31 import android.os.ServiceManager;
32 import android.os.UserHandle;
33 import android.os.UserManager;
34 
35 import com.android.server.pm.UserManagerService;
36 
37 import java.io.PrintWriter;
38 import java.lang.annotation.Retention;
39 import java.lang.annotation.RetentionPolicy;
40 import java.util.ArrayList;
41 import java.util.List;
42 
43 /**
44  * The base class for services running in the system process. Override and implement
45  * the lifecycle event callback methods as needed.
46  * <p>
47  * The lifecycle of a SystemService:
48  * </p><ul>
49  * <li>The constructor is called and provided with the system {@link Context}
50  * to initialize the system service.
51  * <li>{@link #onStart()} is called to get the service running.  The service should
52  * publish its binder interface at this point using
53  * {@link #publishBinderService(String, IBinder)}.  It may also publish additional
54  * local interfaces that other services within the system server may use to access
55  * privileged internal functions.
56  * <li>Then {@link #onBootPhase(int)} is called as many times as there are boot phases
57  * until {@link #PHASE_BOOT_COMPLETED} is sent, which is the last boot phase. Each phase
58  * is an opportunity to do special work, like acquiring optional service dependencies,
59  * waiting to see if SafeMode is enabled, or registering with a service that gets
60  * started after this one.
61  * </ul><p>
62  * NOTE: All lifecycle methods are called from the system server's main looper thread.
63  * </p>
64  *
65  * {@hide}
66  */
67 @SystemApi(client = Client.SYSTEM_SERVER)
68 public abstract class SystemService {
69 
70     /** @hide */
71     protected static final boolean DEBUG_USER = false;
72 
73     /*
74      * The earliest boot phase the system send to system services on boot.
75      */
76     public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100;
77 
78     /**
79      * After receiving this boot phase, services can obtain lock settings data.
80      */
81     public static final int PHASE_LOCK_SETTINGS_READY = 480;
82 
83     /**
84      * After receiving this boot phase, services can safely call into core system services
85      * such as the PowerManager or PackageManager.
86      */
87     public static final int PHASE_SYSTEM_SERVICES_READY = 500;
88 
89     /**
90      * After receiving this boot phase, services can safely call into device specific services.
91      */
92     public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;
93 
94     /**
95      * After receiving this boot phase, services can broadcast Intents.
96      */
97     public static final int PHASE_ACTIVITY_MANAGER_READY = 550;
98 
99     /**
100      * After receiving this boot phase, services can start/bind to third party apps.
101      * Apps will be able to make Binder calls into services at this point.
102      */
103     public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;
104 
105     /**
106      * After receiving this boot phase, services can allow user interaction with the device.
107      * This phase occurs when boot has completed and the home application has started.
108      * System services may prefer to listen to this phase rather than registering a
109      * broadcast receiver for {@link android.content.Intent#ACTION_LOCKED_BOOT_COMPLETED}
110      * to reduce overall latency.
111      */
112     public static final int PHASE_BOOT_COMPLETED = 1000;
113 
114     /** @hide */
115     @IntDef(flag = true, prefix = { "PHASE_" }, value = {
116             PHASE_WAIT_FOR_DEFAULT_DISPLAY,
117             PHASE_LOCK_SETTINGS_READY,
118             PHASE_SYSTEM_SERVICES_READY,
119             PHASE_DEVICE_SPECIFIC_SERVICES_READY,
120             PHASE_ACTIVITY_MANAGER_READY,
121             PHASE_THIRD_PARTY_APPS_CAN_START,
122             PHASE_BOOT_COMPLETED
123     })
124     @Retention(RetentionPolicy.SOURCE)
125     public @interface BootPhase {}
126 
127     private final Context mContext;
128 
129     /**
130      * Class representing user in question in the lifecycle callbacks.
131      * @hide
132      */
133     @SystemApi(client = Client.SYSTEM_SERVER)
134     public static final class TargetUser {
135         @NonNull
136         private final UserInfo mUserInfo;
137 
138         /** @hide */
TargetUser(@onNull UserInfo userInfo)139         public TargetUser(@NonNull UserInfo userInfo) {
140             mUserInfo = userInfo;
141         }
142 
143         /**
144          * @return The information about the user. <b>NOTE: </b> this is a "live" object
145          * referenced by {@link UserManagerService} and hence should not be modified.
146          *
147          * @hide
148          */
149         @NonNull
getUserInfo()150         public UserInfo getUserInfo() {
151             return mUserInfo;
152         }
153 
154         /**
155          * @return the target {@link UserHandle}.
156          */
157         @NonNull
getUserHandle()158         public UserHandle getUserHandle() {
159             return mUserInfo.getUserHandle();
160         }
161 
162         /**
163          * @return the integer user id
164          *
165          * @hide
166          */
getUserIdentifier()167         public int getUserIdentifier() {
168             return mUserInfo.id;
169         }
170 
171         @Override
toString()172         public String toString() {
173             return Integer.toString(getUserIdentifier());
174         }
175     }
176 
177     /**
178      * Initializes the system service.
179      * <p>
180      * Subclasses must define a single argument constructor that accepts the context
181      * and passes it to super.
182      * </p>
183      *
184      * @param context The system server context.
185      */
SystemService(@onNull Context context)186     public SystemService(@NonNull Context context) {
187         mContext = context;
188     }
189 
190     /**
191      * Gets the system context.
192      */
193     @NonNull
getContext()194     public final Context getContext() {
195         return mContext;
196     }
197 
198     /**
199      * Get the system UI context. This context is to be used for displaying UI. It is themable,
200      * which means resources can be overridden at runtime. Do not use to retrieve properties that
201      * configure the behavior of the device that is not UX related.
202      *
203      * @hide
204      */
getUiContext()205     public final Context getUiContext() {
206         // This has already been set up by the time any SystemServices are created.
207         return ActivityThread.currentActivityThread().getSystemUiContext();
208     }
209 
210     /**
211      * Returns true if the system is running in safe mode.
212      * TODO: we should define in which phase this becomes valid
213      *
214      * @hide
215      */
isSafeMode()216     public final boolean isSafeMode() {
217         return getManager().isSafeMode();
218     }
219 
220     /**
221      * Called when the system service should publish a binder service using
222      * {@link #publishBinderService(String, IBinder).}
223      */
onStart()224     public abstract void onStart();
225 
226     /**
227      * Called on each phase of the boot process. Phases before the service's start phase
228      * (as defined in the @Service annotation) are never received.
229      *
230      * @param phase The current boot phase.
231      */
onBootPhase(@ootPhase int phase)232     public void onBootPhase(@BootPhase int phase) {}
233 
234     /**
235      * Checks if the service should be available for the given user.
236      *
237      * <p>By default returns {@code true}, but subclasses should extend for optimization, if they
238      * don't support some types (like headless system user).
239      */
isUserSupported(@onNull TargetUser user)240     public boolean isUserSupported(@NonNull TargetUser user) {
241         return true;
242     }
243 
244     /**
245      * Helper method used to dump which users are {@link #onUserStarting(TargetUser) supported}.
246      *
247      * @hide
248      */
dumpSupportedUsers(@onNull PrintWriter pw, @NonNull String prefix)249     protected void dumpSupportedUsers(@NonNull PrintWriter pw, @NonNull String prefix) {
250         final List<UserInfo> allUsers = UserManager.get(mContext).getUsers();
251         final List<Integer> supportedUsers = new ArrayList<>(allUsers.size());
252         for (UserInfo user : allUsers) {
253             supportedUsers.add(user.id);
254         }
255         if (allUsers.isEmpty()) {
256             pw.print(prefix); pw.println("No supported users");
257         } else {
258             final int size = supportedUsers.size();
259             pw.print(prefix); pw.print(size); pw.print(" supported user");
260             if (size > 1) pw.print("s");
261             pw.print(": "); pw.println(supportedUsers);
262         }
263     }
264 
265     /**
266      * @deprecated subclasses should extend {@link #onUserStarting(TargetUser)} instead
267      * (which by default calls this method).
268      *
269      * @hide
270      */
271     @Deprecated
onStartUser(@serIdInt int userId)272     public void onStartUser(@UserIdInt int userId) {}
273 
274     /**
275      * @deprecated subclasses should extend {@link #onUserStarting(TargetUser)} instead
276      * (which by default calls this method).
277      *
278      * @hide
279      */
280     @Deprecated
onStartUser(@onNull UserInfo userInfo)281     public void onStartUser(@NonNull UserInfo userInfo) {
282         onStartUser(userInfo.id);
283     }
284 
285     /**
286      * Called when a new user is starting, for system services to initialize any per-user
287      * state they maintain for running users.
288      *
289      * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports}
290      * this user.
291      *
292      * @param user target user
293      */
onUserStarting(@onNull TargetUser user)294     public void onUserStarting(@NonNull TargetUser user) {
295         onStartUser(user.getUserInfo());
296     }
297 
298     /**
299      * @deprecated subclasses should extend {@link #onUserUnlocking(TargetUser)} instead (which by
300      * default calls this method).
301      *
302      * @hide
303      */
304     @Deprecated
onUnlockUser(@serIdInt int userId)305     public void onUnlockUser(@UserIdInt int userId) {}
306 
307     /**
308      * @deprecated subclasses should extend {@link #onUserUnlocking(TargetUser)} instead (which by
309      * default calls this method).
310      *
311      * @hide
312      */
313     @Deprecated
onUnlockUser(@onNull UserInfo userInfo)314     public void onUnlockUser(@NonNull UserInfo userInfo) {
315         onUnlockUser(userInfo.id);
316     }
317 
318     /**
319      * Called when an existing user is in the process of being unlocked. This
320      * means the credential-encrypted storage for that user is now available,
321      * and encryption-aware component filtering is no longer in effect.
322      * <p>
323      * While dispatching this event to services, the user is in the
324      * {@code STATE_RUNNING_UNLOCKING} state, and once dispatching is finished
325      * the user will transition into the {@code STATE_RUNNING_UNLOCKED} state.
326      * Code written inside system services should use
327      * {@link UserManager#isUserUnlockingOrUnlocked(int)} to handle both of
328      * these states, or use {@link #onUserUnlocked(TargetUser)} instead.
329      * <p>
330      * This method is only called when the service {@link #isUserSupported(TargetUser) supports}
331      * this user.
332      *
333      * @param user target user
334      */
onUserUnlocking(@onNull TargetUser user)335     public void onUserUnlocking(@NonNull TargetUser user) {
336         onUnlockUser(user.getUserInfo());
337     }
338 
339     /**
340      * Called after an existing user is unlocked.
341      *
342      * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports}
343      * this user.
344      *
345      * @param user target user
346      */
onUserUnlocked(@onNull TargetUser user)347     public void onUserUnlocked(@NonNull TargetUser user) {
348     }
349 
350     /**
351      * @deprecated subclasses should extend {@link #onUserSwitching(TargetUser, TargetUser)} instead
352      * (which by default calls this method).
353      *
354      * @hide
355      */
356     @Deprecated
onSwitchUser(@serIdInt int toUserId)357     public void onSwitchUser(@UserIdInt int toUserId) {}
358 
359     /**
360      * @deprecated subclasses should extend {@link #onUserSwitching(TargetUser, TargetUser)} instead
361      * (which by default calls this method).
362      *
363      * @hide
364      */
365     @Deprecated
onSwitchUser(@ullable UserInfo from, @NonNull UserInfo to)366     public void onSwitchUser(@Nullable UserInfo from, @NonNull UserInfo to) {
367         onSwitchUser(to.id);
368     }
369 
370     /**
371      * Called when switching to a different foreground user, for system services that have
372      * special behavior for whichever user is currently in the foreground.  This is called
373      * before any application processes are aware of the new user.
374      *
375      * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports}
376      * either of the users ({@code from} or {@code to}).
377      *
378      * <b>NOTE: </b> both {@code from} and {@code to} are "live" objects
379      * referenced by {@link UserManagerService} and hence should not be modified.
380      *
381      * @param from the user switching from
382      * @param to the user switching to
383      */
onUserSwitching(@ullable TargetUser from, @NonNull TargetUser to)384     public void onUserSwitching(@Nullable TargetUser from, @NonNull TargetUser to) {
385         onSwitchUser((from == null ? null : from.getUserInfo()), to.getUserInfo());
386     }
387 
388     /**
389      * @deprecated subclasses should extend {@link #onUserStopping(TargetUser)} instead
390      * (which by default calls this method).
391      *
392      * @hide
393      */
394     @Deprecated
onStopUser(@serIdInt int userId)395     public void onStopUser(@UserIdInt int userId) {}
396 
397     /**
398      * @deprecated subclasses should extend {@link #onUserStopping(TargetUser)} instead
399      * (which by default calls this method).
400      *
401      * @hide
402      */
403     @Deprecated
onStopUser(@onNull UserInfo user)404     public void onStopUser(@NonNull UserInfo user) {
405         onStopUser(user.id);
406 
407     }
408 
409     /**
410      * Called when an existing user is stopping, for system services to finalize any per-user
411      * state they maintain for running users.  This is called prior to sending the SHUTDOWN
412      * broadcast to the user; it is a good place to stop making use of any resources of that
413      * user (such as binding to a service running in the user).
414      *
415      * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports}
416      * this user.
417      *
418      * <p>NOTE: This is the last callback where the callee may access the target user's CE storage.
419      *
420      * @param user target user
421      */
onUserStopping(@onNull TargetUser user)422     public void onUserStopping(@NonNull TargetUser user) {
423         onStopUser(user.getUserInfo());
424     }
425 
426     /**
427      * @deprecated subclasses should extend {@link #onUserStopped(TargetUser)} instead (which by
428      * default calls this method).
429      *
430      * @hide
431      */
432     @Deprecated
onCleanupUser(@serIdInt int userId)433     public void onCleanupUser(@UserIdInt int userId) {}
434 
435     /**
436      * @deprecated subclasses should extend {@link #onUserStopped(TargetUser)} instead (which by
437      * default calls this method).
438      *
439      * @hide
440      */
441     @Deprecated
onCleanupUser(@onNull UserInfo user)442     public void onCleanupUser(@NonNull UserInfo user) {
443         onCleanupUser(user.id);
444     }
445 
446     /**
447      * Called after an existing user is stopped.
448      *
449      * <p>This is called after all application process teardown of the user is complete.
450      *
451      * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports}
452      * this user.
453      *
454      * @param user target user
455      */
onUserStopped(@onNull TargetUser user)456     public void onUserStopped(@NonNull TargetUser user) {
457         onCleanupUser(user.getUserInfo());
458     }
459 
460     /**
461      * Publish the service so it is accessible to other services and apps.
462      *
463      * @param name the name of the new service
464      * @param service the service object
465      */
publishBinderService(@onNull String name, @NonNull IBinder service)466     protected final void publishBinderService(@NonNull String name, @NonNull IBinder service) {
467         publishBinderService(name, service, false);
468     }
469 
470     /**
471      * Publish the service so it is accessible to other services and apps.
472      *
473      * @param name the name of the new service
474      * @param service the service object
475      * @param allowIsolated set to true to allow isolated sandboxed processes
476      * to access this service
477      */
publishBinderService(@onNull String name, @NonNull IBinder service, boolean allowIsolated)478     protected final void publishBinderService(@NonNull String name, @NonNull IBinder service,
479             boolean allowIsolated) {
480         publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);
481     }
482 
483     /**
484      * Publish the service so it is accessible to other services and apps.
485      *
486      * @param name the name of the new service
487      * @param service the service object
488      * @param allowIsolated set to true to allow isolated sandboxed processes
489      * to access this service
490      * @param dumpPriority supported dump priority levels as a bitmask
491      *
492      * @hide
493      */
publishBinderService(String name, IBinder service, boolean allowIsolated, int dumpPriority)494     protected final void publishBinderService(String name, IBinder service,
495             boolean allowIsolated, int dumpPriority) {
496         ServiceManager.addService(name, service, allowIsolated, dumpPriority);
497     }
498 
499     /**
500      * Get a binder service by its name.
501      *
502      * @hide
503      */
getBinderService(String name)504     protected final IBinder getBinderService(String name) {
505         return ServiceManager.getService(name);
506     }
507 
508     /**
509      * Publish the service so it is only accessible to the system process.
510      *
511      * @hide
512      */
publishLocalService(Class<T> type, T service)513     protected final <T> void publishLocalService(Class<T> type, T service) {
514         LocalServices.addService(type, service);
515     }
516 
517     /**
518      * Get a local service by interface.
519      *
520      * @hide
521      */
getLocalService(Class<T> type)522     protected final <T> T getLocalService(Class<T> type) {
523         return LocalServices.getService(type);
524     }
525 
getManager()526     private SystemServiceManager getManager() {
527         return LocalServices.getService(SystemServiceManager.class);
528     }
529 }
530