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