summaryrefslogtreecommitdiff
path: root/core/java/android/os/image/DynamicSystemClient.java
blob: ada708bda34ca53a81ea5cf61201f9d0d6673d09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*
 * Copyright (C) 2019 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package android.os.image;

import android.annotation.BytesLong;
import android.annotation.CallbackExecutor;
import android.annotation.IntDef;
import android.annotation.NonNull;
import android.annotation.Nullable;
import android.annotation.RequiresPermission;
import android.annotation.SystemApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.ParcelableException;
import android.os.RemoteException;
import android.util.Slog;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executor;

/**
 * <p>This class contains methods and constants used to start a {@code DynamicSystem} installation,
 * and a listener for status updates.</p>
 *
 * <p>{@code DynamicSystem} allows users to run certified system images in a non destructive manner
 * without needing to prior OEM unlock. It creates a temporary system partition to install the new
 * system image, and a temporary data partition for the newly installed system to run with.</p>
 *
 * After the installation is completed, the device will be running in the new system on next the
 * reboot. Then, when the user reboots the device again, it will leave {@code DynamicSystem} and go
 * back to the original system. While running in {@code DynamicSystem}, persistent storage for
 * factory reset protection (FRP) remains unchanged. Since the user is running the new system with
 * a temporarily created data partition, their original user data are kept unchanged.</p>
 *
 * <p>With {@link #setOnStatusChangedListener}, API users can register an
 * {@link #OnStatusChangedListener} to get status updates and their causes when the installation is
 * started, stopped, or cancelled. It also sends progress updates during the installation. With
 * {@link #start}, API users can start an installation with the {@link Uri} to a unsparsed and
 * gzipped system image. The {@link Uri} can be a web URL or a content Uri to a local path.</p>
 *
 * @hide
 */
@SystemApi
public class DynamicSystemClient {
    private static final String TAG = "DynamicSystemClient";

    /** @hide */
    @IntDef(prefix = { "STATUS_" }, value = {
            STATUS_UNKNOWN,
            STATUS_NOT_STARTED,
            STATUS_IN_PROGRESS,
            STATUS_READY,
            STATUS_IN_USE,
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface InstallationStatus {}

    /** @hide */
    @IntDef(prefix = { "CAUSE_" }, value = {
            CAUSE_NOT_SPECIFIED,
            CAUSE_INSTALL_COMPLETED,
            CAUSE_INSTALL_CANCELLED,
            CAUSE_ERROR_IO,
            CAUSE_ERROR_INVALID_URL,
            CAUSE_ERROR_IPC,
            CAUSE_ERROR_EXCEPTION,
    })
    @Retention(RetentionPolicy.SOURCE)
    public @interface StatusChangedCause {}

    /** Listener for installation status updates. */
    public interface OnStatusChangedListener {
        /**
         * This callback is called when installation status is changed, and when the
         * client is {@link #bind} to {@code DynamicSystem} installation service.
         *
         * @param status status code, also defined in {@code DynamicSystemClient}.
         * @param cause cause code, also defined in {@code DynamicSystemClient}.
         * @param progress number of bytes installed.
         * @param detail additional detail about the error if available, otherwise null.
         */
        void onStatusChanged(@InstallationStatus int status, @StatusChangedCause int cause,
                @BytesLong long progress, @Nullable Throwable detail);
    }

    /*
     * Status codes
     */
    /** We are bound to installation service, but failed to get its status */
    public static final int STATUS_UNKNOWN = 0;

    /** Installation is not started yet. */
    public static final int STATUS_NOT_STARTED = 1;

    /** Installation is in progress. */
    public static final int STATUS_IN_PROGRESS = 2;

    /** Installation is finished but the user has not launched it. */
    public static final int STATUS_READY = 3;

    /** Device is running in {@code DynamicSystem}. */
    public static final int STATUS_IN_USE = 4;

    /*
     * Causes
     */
    /** Cause is not specified. This means the status is not changed. */
    public static final int CAUSE_NOT_SPECIFIED = 0;

    /** Status changed because installation is completed. */
    public static final int CAUSE_INSTALL_COMPLETED = 1;

    /** Status changed because installation is cancelled. */
    public static final int CAUSE_INSTALL_CANCELLED = 2;

    /** Installation failed due to {@code IOException}. */
    public static final int CAUSE_ERROR_IO = 3;

    /** Installation failed because the image URL source is not supported. */
    public static final int CAUSE_ERROR_INVALID_URL = 4;

    /** Installation failed due to IPC error. */
    public static final int CAUSE_ERROR_IPC = 5;

    /** Installation failed due to unhandled exception. */
    public static final int CAUSE_ERROR_EXCEPTION = 6;

    /*
     * IPC Messages
     */
    /**
     * Message to register listener.
     * @hide
     */
    public static final int MSG_REGISTER_LISTENER = 1;

    /**
     * Message to unregister listener.
     * @hide
     */
    public static final int MSG_UNREGISTER_LISTENER = 2;

    /**
     * Message for status updates.
     * @hide
     */
    public static final int MSG_POST_STATUS = 3;

    /*
     * Messages keys
     */
    /**
     * Message key, for progress updates.
     * @hide
     */
    public static final String KEY_INSTALLED_SIZE = "KEY_INSTALLED_SIZE";

    /**
     * Message key, used when the service is sending exception detail to the client.
     * @hide
     */
    public static final String KEY_EXCEPTION_DETAIL = "KEY_EXCEPTION_DETAIL";

    /*
     * Intent Actions
     */
    /**
     * Intent action: start installation.
     * @hide
     */
    public static final String ACTION_START_INSTALL =
            "android.os.image.action.START_INSTALL";

    /**
     * Intent action: notify user if we are currently running in {@code DynamicSystem}.
     * @hide
     */
    public static final String ACTION_NOTIFY_IF_IN_USE =
            "android.os.image.action.NOTIFY_IF_IN_USE";

    /**
     * Intent action: hide notifications about the status of {@code DynamicSystem}.
     * @hide
     */
    public static final String ACTION_HIDE_NOTIFICATION =
            "android.os.image.action.HIDE_NOTIFICATION";

    /**
     * Intent action: notify the service to post a status update when keyguard is dismissed.
     * @hide
     */
    public static final String ACTION_NOTIFY_KEYGUARD_DISMISSED =
            "android.os.image.action.NOTIFY_KEYGUARD_DISMISSED";

    /*
     * Intent Keys
     */
    /**
     * Intent key: Size of the system image, in bytes.
     * @hide
     */
    public static final String KEY_SYSTEM_SIZE = "KEY_SYSTEM_SIZE";

    /**
     * Intent key: Number of bytes to reserve for userdata.
     * @hide
     */
    public static final String KEY_USERDATA_SIZE = "KEY_USERDATA_SIZE";

    /**
     * Intent key: Whether to enable DynamicSystem immediately after installation is done.
     *             Note this will reboot the device automatically.
     * @hide
     */
    public static final String KEY_ENABLE_WHEN_COMPLETED = "KEY_ENABLE_WHEN_COMPLETED";

    /**
     * Intent key: Whether to leave DynamicSystem on device reboot.
     *             False indicates a sticky mode where device stays in DynamicSystem across reboots.
     * @hide
     */
    public static final String KEY_ONE_SHOT = "KEY_ONE_SHOT";

    /**
     * Intent key: Whether to use default strings when showing the dialog that prompts
     *             user for device credentials.
     *             False indicates using the custom strings provided by {@code DynamicSystem}.
     * @hide
     */
    public static final String KEY_KEYGUARD_USE_DEFAULT_STRINGS =
            "KEY_KEYGUARD_USE_DEFAULT_STRINGS";

    private static class IncomingHandler extends Handler {
        private final WeakReference<DynamicSystemClient> mWeakClient;

        IncomingHandler(DynamicSystemClient service) {
            super(Looper.getMainLooper());
            mWeakClient = new WeakReference<>(service);
        }

        @Override
        public void handleMessage(Message msg) {
            DynamicSystemClient service = mWeakClient.get();

            if (service != null) {
                service.handleMessage(msg);
            }
        }
    }

    private class DynSystemServiceConnection implements ServiceConnection {
        public void onServiceConnected(ComponentName className, IBinder service) {
            Slog.v(TAG, "onServiceConnected: " + className);

            mService = new Messenger(service);

            try {
                Message msg = Message.obtain(null, MSG_REGISTER_LISTENER);
                msg.replyTo = mMessenger;

                mService.send(msg);
            } catch (RemoteException e) {
                Slog.e(TAG, "Unable to get status from installation service");
                notifyOnStatusChangedListener(STATUS_UNKNOWN, CAUSE_ERROR_IPC, 0, e);
            }
        }

        public void onServiceDisconnected(ComponentName className) {
            Slog.v(TAG, "onServiceDisconnected: " + className);
            mService = null;
        }
    }

    private final Context mContext;
    private final DynSystemServiceConnection mConnection;
    private final Messenger mMessenger;

    private boolean mBound;
    private Executor mExecutor;
    private OnStatusChangedListener mListener;
    private Messenger mService;

    /**
     * Create a new {@code DynamicSystem} client.
     *
     * @param context a {@link Context} will be used to bind the installation service.
     *
     * @hide
     */
    @SystemApi
    public DynamicSystemClient(@NonNull Context context) {
        mContext = context;
        mConnection = new DynSystemServiceConnection();
        mMessenger = new Messenger(new IncomingHandler(this));
    }

    /**
     * This method register a listener for status change. The listener is called using
     * the executor.
     */
    public void setOnStatusChangedListener(
            @NonNull @CallbackExecutor Executor executor,
            @NonNull OnStatusChangedListener listener) {
        mListener = listener;
        mExecutor = executor;
    }

    /**
     * This method register a listener for status change. The listener is called in main
     * thread.
     */
    public void setOnStatusChangedListener(
            @NonNull OnStatusChangedListener listener) {
        mListener = listener;
        mExecutor = null;
    }

    private void notifyOnStatusChangedListener(
            int status, int cause, long progress, Throwable detail) {
        if (mListener != null) {
            if (mExecutor != null) {
                mExecutor.execute(
                        () -> {
                            mListener.onStatusChanged(status, cause, progress, detail);
                        });
            } else {
                mListener.onStatusChanged(status, cause, progress, detail);
            }
        }
    }

    /**
     * Bind to {@code DynamicSystem} installation service. Binding to the installation service
     * allows it to send status updates to {@link #OnStatusChangedListener}. It is recommanded
     * to bind before calling {@link #start} and get status updates.
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.INSTALL_DYNAMIC_SYSTEM)
    @SystemApi
    public void bind() {
        Intent intent = new Intent();
        intent.setClassName("com.android.dynsystem",
                "com.android.dynsystem.DynamicSystemInstallationService");

        mContext.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

        mBound = true;
    }

    /**
     * Unbind from {@code DynamicSystem} installation service. Unbinding from the installation
     * service stops it from sending following status updates.
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.INSTALL_DYNAMIC_SYSTEM)
    @SystemApi
    public void unbind() {
        if (!mBound) {
            return;
        }

        if (mService != null) {
            try {
                Message msg = Message.obtain(null, MSG_UNREGISTER_LISTENER);
                msg.replyTo = mMessenger;
                mService.send(msg);
            } catch (RemoteException e) {
                Slog.e(TAG, "Unable to unregister from installation service");
            }
        }

        // Detach our existing connection.
        mContext.unbindService(mConnection);

        mBound = false;
    }

    /**
     * Start installing {@code DynamicSystem} from URL with default userdata size.
     *
     * Calling this function will first start an Activity to confirm device credential, using
     * {@link KeyguardManager}. If it's confirmed, the installation service will be started.
     *
     * This function doesn't require prior calling {@link #bind}.
     *
     * @param systemUrl a network Uri, a file Uri or a content Uri pointing to a system image file.
     * @param systemSize size of system image.
     * @hide
     */
    @RequiresPermission(android.Manifest.permission.INSTALL_DYNAMIC_SYSTEM)
    @SystemApi
    public void start(@NonNull Uri systemUrl, @BytesLong long systemSize) {
        start(systemUrl, systemSize, 0 /* Use the default userdata size */);
    }

    /**
     * Start installing {@code DynamicSystem} from URL.
     *
     * Calling this function will first start an Activity to confirm device credential, using
     * {@link KeyguardManager}. If it's confirmed, the installation service will be started.
     *
     * This function doesn't require prior calling {@link #bind}.
     *
     * @param systemUrl a network Uri, a file Uri or a content Uri pointing to a system image file.
     * @param systemSize size of system image.
     * @param userdataSize bytes reserved for userdata.
     */
    @RequiresPermission(android.Manifest.permission.INSTALL_DYNAMIC_SYSTEM)
    public void start(@NonNull Uri systemUrl, @BytesLong long systemSize,
            @BytesLong long userdataSize) {
        Intent intent = new Intent();

        intent.setClassName("com.android.dynsystem",
                "com.android.dynsystem.VerificationActivity");

        intent.setData(systemUrl);
        intent.setAction(ACTION_START_INSTALL);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        intent.putExtra(KEY_SYSTEM_SIZE, systemSize);
        intent.putExtra(KEY_USERDATA_SIZE, userdataSize);

        mContext.startActivity(intent);
    }

    private void handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_POST_STATUS:
                int status = msg.arg1;
                int cause = msg.arg2;
                // obj is non-null
                Bundle bundle = (Bundle) msg.obj;
                long progress = bundle.getLong(KEY_INSTALLED_SIZE);
                ParcelableException t = (ParcelableException) bundle.getSerializable(
                        KEY_EXCEPTION_DETAIL, android.os.ParcelableException.class);

                Throwable detail = t == null ? null : t.getCause();

                notifyOnStatusChangedListener(status, cause, progress, detail);
                break;
            default:
                // do nothing

        }
    }
}