summaryrefslogtreecommitdiffstats
path: root/tests/AndroidTests/src/com/android/unit_tests/AsecTests.java
blob: 9a750472b91399da3084f1b9dc8eb0ad366f0c2a (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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
/*
 * Copyright (C) 2006 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 com.android.unit_tests;

import com.android.unit_tests.PackageManagerTests.StorageListener;

import android.os.storage.IMountService.Stub;

import android.net.Uri;
import android.os.FileUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.test.AndroidTestCase;
import android.test.suitebuilder.annotation.Suppress;
import android.util.DisplayMetrics;
import android.util.Log;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.storage.IMountService;
import android.os.storage.IMountShutdownObserver;
import android.os.storage.StorageEventListener;
import android.os.storage.StorageManager;
import android.os.storage.StorageResultCode;
import android.os.RemoteException;
import android.os.ServiceManager;
import android.os.StatFs;
import android.provider.Settings;
import junit.framework.Assert;

public class AsecTests extends AndroidTestCase {
    private static final boolean localLOGV = true;
    public static final String TAG="AsecTests";

    void failStr(String errMsg) {
        Log.w(TAG, "errMsg="+errMsg);
    }

    void failStr(Exception e) {
        Log.w(TAG, "e.getMessage="+e.getMessage());
        Log.w(TAG, "e="+e);
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        if (localLOGV) Log.i(TAG, "Cleaning out old test containers");
        cleanupContainers();
    }

    @Override
    protected void tearDown() throws Exception {
        super.tearDown();
        if (localLOGV) Log.i(TAG, "Cleaning out old test containers");
        cleanupContainers();
    }

    private void cleanupContainers() throws RemoteException {
        IMountService ms = getMs();
        String[] containers = ms.getSecureContainerList();

        for (int i = 0; i < containers.length; i++) {
            if (containers[i].startsWith("com.android.unittests.AsecTests.")) {
                ms.destroySecureContainer(containers[i], true);
            }
        }
    }

    private boolean containerExists(String localId) throws RemoteException {
        IMountService ms = getMs();
        String[] containers = ms.getSecureContainerList();
        String fullId = "com.android.unittests.AsecTests." + localId;

        for (int i = 0; i < containers.length; i++) {
            if (containers[i].equals(fullId)) {
                return true;
            }
        }
        return false;
    }

    private int createContainer(String localId, int size, String key) throws RemoteException {
        Assert.assertTrue(isMediaMounted());
        String fullId = "com.android.unittests.AsecTests." + localId;

        IMountService ms = getMs();
        return ms.createSecureContainer(fullId, size, "fat", key, android.os.Process.myUid());
    }

    private int mountContainer(String localId, String key) throws RemoteException {
        Assert.assertTrue(isMediaMounted());
        String fullId = "com.android.unittests.AsecTests." + localId;

        IMountService ms = getMs();
        return ms.mountSecureContainer(fullId, key, android.os.Process.myUid());
    }

    private int renameContainer(String localId1, String localId2) throws RemoteException {
        Assert.assertTrue(isMediaMounted());
        String fullId1 = "com.android.unittests.AsecTests." + localId1;
        String fullId2 = "com.android.unittests.AsecTests." + localId2;

        IMountService ms = getMs();
        return ms.renameSecureContainer(fullId1, fullId2);
    }

    private int unmountContainer(String localId, boolean force) throws RemoteException {
        Assert.assertTrue(isMediaMounted());
        String fullId = "com.android.unittests.AsecTests." + localId;

        IMountService ms = getMs();
        return ms.unmountSecureContainer(fullId, force);
    }

    private int destroyContainer(String localId, boolean force) throws RemoteException {
        Assert.assertTrue(isMediaMounted());
        String fullId = "com.android.unittests.AsecTests." + localId;

        IMountService ms = getMs();
        return ms.destroySecureContainer(fullId, force);
    }

    private boolean isContainerMounted(String localId) throws RemoteException {
        Assert.assertTrue(isMediaMounted());
        String fullId = "com.android.unittests.AsecTests." + localId;

        IMountService ms = getMs();
        return ms.isSecureContainerMounted(fullId);
    }

    private IMountService getMs() {
        IBinder service = ServiceManager.getService("mount");
        if (service != null) {
            return IMountService.Stub.asInterface(service);
        } else {
            Log.e(TAG, "Can't get mount service");
        }
        return null;
    }

    private boolean isMediaMounted() {
        try {
        String mPath = Environment.getExternalStorageDirectory().toString();
        String state = getMs().getVolumeState(mPath);
        return Environment.MEDIA_MOUNTED.equals(state);
        } catch (RemoteException e) {
            failStr(e);
            return false;
        }
    }

    public void testCreateContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testCreateContainer", 4, "none"));
            Assert.assertEquals(true, containerExists("testCreateContainer"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testCreateMinSizeContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testCreateContainer", 1, "none"));
            Assert.assertEquals(true, containerExists("testCreateContainer"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testCreateZeroSizeContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationFailedInternalError,
                    createContainer("testCreateZeroContainer", 0, "none"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testCreateDuplicateContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testCreateDupContainer", 4, "none"));

            Assert.assertEquals(StorageResultCode.OperationFailedInternalError,
                    createContainer("testCreateDupContainer", 4, "none"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testDestroyContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testDestroyContainer", 4, "none"));
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    destroyContainer("testDestroyContainer", false));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testMountContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testMountContainer", 4, "none"));

            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    unmountContainer("testMountContainer", false));

            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    mountContainer("testMountContainer", "none"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testMountBadKey() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testMountBadKey", 4, "00000000000000000000000000000000"));

            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    unmountContainer("testMountBadKey", false));

            Assert.assertEquals(StorageResultCode.OperationFailedInternalError,
                    mountContainer("testMountContainer", "000000000000000000000000000000001"));

            Assert.assertEquals(StorageResultCode.OperationFailedInternalError,
                    mountContainer("testMountContainer", "none"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testNonExistPath() {
        IMountService ms = getMs();
        try {
            String path = ms.getSecureContainerPath("jparks.broke.it");
            failStr(path);
        } catch (IllegalArgumentException e) {
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testUnmountBusyContainer() {
        IMountService ms = getMs();
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testUnmountBusyContainer", 4, "none"));

            String path = ms.getSecureContainerPath("com.android.unittests.AsecTests.testUnmountBusyContainer");

            File f = new File(path, "reference");
            FileOutputStream fos = new FileOutputStream(f);

            Assert.assertEquals(StorageResultCode.OperationFailedStorageBusy,
                    unmountContainer("testUnmountBusyContainer", false));

            fos.close();
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    unmountContainer("testUnmountBusyContainer", false));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testDestroyBusyContainer() {
        IMountService ms = getMs();
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testDestroyBusyContainer", 4, "none"));

            String path = ms.getSecureContainerPath("com.android.unittests.AsecTests.testDestroyBusyContainer");

            File f = new File(path, "reference");
            FileOutputStream fos = new FileOutputStream(f);

            Assert.assertEquals(StorageResultCode.OperationFailedStorageBusy,
                    destroyContainer("testDestroyBusyContainer", false));

            fos.close();
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    destroyContainer("testDestroyBusyContainer", false));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testRenameContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testRenameContainer.1", 4, "none"));

            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    unmountContainer("testRenameContainer.1", false));

            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    renameContainer("testRenameContainer.1", "testRenameContainer.2"));

            Assert.assertEquals(false, containerExists("testRenameContainer.1"));
            Assert.assertEquals(true, containerExists("testRenameContainer.2"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testRenameSrcMountedContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testRenameContainer.1", 4, "none"));

            Assert.assertEquals(StorageResultCode.OperationFailedStorageMounted,
                    renameContainer("testRenameContainer.1", "testRenameContainer.2"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testRenameDstMountedContainer() {
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testRenameContainer.1", 4, "none"));

            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    unmountContainer("testRenameContainer.1", false));

            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testRenameContainer.2", 4, "none"));

            Assert.assertEquals(StorageResultCode.OperationFailedStorageMounted,
                    renameContainer("testRenameContainer.1", "testRenameContainer.2"));
        } catch (Exception e) {
            failStr(e);
        }
    }

    public void testContainerSize() {
        IMountService ms = getMs();
        try {
            Assert.assertEquals(StorageResultCode.OperationSucceeded,
                    createContainer("testContainerSize", 1, "none"));
            String path = ms.getSecureContainerPath("com.android.unittests.AsecTests.testUnmountBusyContainer");

            byte[] buf = new byte[4096];
            File f = new File(path, "reference");
            FileOutputStream fos = new FileOutputStream(f);
            for (int i = 0; i < (1024 * 1024); i+= buf.length) {
                fos.write(buf);
            }
            fos.close();
        } catch (Exception e) {
            failStr(e);
        }
    }

    /*------------ Tests for unmounting volume ---*/
    public final long MAX_WAIT_TIME=120*1000;
    public final long WAIT_TIME_INCR=20*1000;
    boolean getMediaState() {
        try {
        String mPath = Environment.getExternalStorageDirectory().toString();
        String state = getMs().getVolumeState(mPath);
        return Environment.MEDIA_MOUNTED.equals(state);
        } catch (RemoteException e) {
            return false;
        }
    }

    boolean mountMedia() {
        if (getMediaState()) {
            return true;
        }
        try {
        String mPath = Environment.getExternalStorageDirectory().toString();
        int ret = getMs().mountVolume(mPath);
        return ret == StorageResultCode.OperationSucceeded;
        } catch (RemoteException e) {
            return false;
        }
    }

    class StorageListener extends StorageEventListener {
        String oldState;
        String newState;
        String path;
        private boolean doneFlag = false;

        public void action() {
            synchronized (this) {
                doneFlag = true;
                notifyAll();
            }
        }

        public boolean isDone() {
            return doneFlag;
        }

        @Override
        public void onStorageStateChanged(String path, String oldState, String newState) {
            if (localLOGV) Log.i(TAG, "Storage state changed from " + oldState + " to " + newState);
            this.oldState = oldState;
            this.newState = newState;
            this.path = path;
            action();
        }
    }

    private boolean unmountMedia() {
        if (!getMediaState()) {
            return true;
        }
        String path = Environment.getExternalStorageDirectory().toString();
        StorageListener observer = new StorageListener();
        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        sm.registerListener(observer);
        try {
            // Wait on observer
            synchronized(observer) {
                getMs().unmountVolume(path, false);
                long waitTime = 0;
                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
                    observer.wait(WAIT_TIME_INCR);
                    waitTime += WAIT_TIME_INCR;
                }
                if(!observer.isDone()) {
                    throw new Exception("Timed out waiting for packageInstalled callback");
                }
                return true;
            }
        } catch (Exception e) {
            return false;
        } finally {
            sm.unregisterListener(observer);
        }
    }
    public void testUnmount() {
        boolean oldStatus = getMediaState();
        Log.i(TAG, "oldStatus="+oldStatus);
        try {
            // Mount media firsts
            if (!getMediaState()) {
                mountMedia();
            }
            assertTrue(unmountMedia());
        } finally {
            // Restore old status
            boolean currStatus = getMediaState();
            if (oldStatus != currStatus) {
                if (oldStatus) {
                    // Mount media
                    mountMedia();
                } else {
                    unmountMedia();
                }
            }
        }
    }

    class MultipleStorageLis extends StorageListener {
        int count = 0;
        public void onStorageStateChanged(String path, String oldState, String newState) {
            count++;
            super.action();
        }
    }
    /*
     * This test invokes unmount multiple time and expects the call back
     * to be invoked just once.
     */
    public void testUnmountMultiple() {
        boolean oldStatus = getMediaState();
        StorageManager sm = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
        MultipleStorageLis observer = new MultipleStorageLis();
        try {
            // Mount media firsts
            if (!getMediaState()) {
                mountMedia();
            }
            String path = Environment.getExternalStorageDirectory().toString();
            sm.registerListener(observer);
            // Wait on observer
            synchronized(observer) {
                for (int i = 0; i < 5; i++) {
                    getMs().unmountVolume(path, false);
                }
                long waitTime = 0;
                while((!observer.isDone()) && (waitTime < MAX_WAIT_TIME) ) {
                    observer.wait(WAIT_TIME_INCR);
                    waitTime += WAIT_TIME_INCR;
                }
                if(!observer.isDone()) {
                    failStr("Timed out waiting for packageInstalled callback");
                }
            }
            assertEquals(observer.count, 1);
        } catch (Exception e) {
            failStr(e);
        } finally {
            sm.unregisterListener(observer);
            // Restore old status
            boolean currStatus = getMediaState();
            if (oldStatus != currStatus) {
                if (oldStatus) {
                    // Mount media
                    mountMedia();
                } else {
                    unmountMedia();
                }
            }
        }
    }
    
    class ShutdownObserver extends  IMountShutdownObserver.Stub{
        private boolean doneFlag = false;
        int statusCode;

        public void action() {
            synchronized (this) {
                doneFlag = true;
                notifyAll();
            }
        }

        public boolean isDone() {
            return doneFlag;
        }
        public void onShutDownComplete(int statusCode) throws RemoteException {
            this.statusCode = statusCode;
            action();
        }
        
    }

    boolean invokeShutdown() {
        IMountService ms = getMs();
        ShutdownObserver observer = new ShutdownObserver();
        synchronized (observer) {
            try {
                ms.shutdown(observer);
                return true;
            } catch (RemoteException e) {
                failStr(e);
            }
        }
        return false;
    }

    public void testShutdown() {
        boolean oldStatus = getMediaState();
        try {
            // Mount media firsts
            if (!getMediaState()) {
                mountMedia();
            }
            assertTrue(invokeShutdown());
        } finally {
            // Restore old status
            boolean currStatus = getMediaState();
            if (oldStatus != currStatus) {
                if (oldStatus) {
                    // Mount media
                    mountMedia();
                } else {
                    unmountMedia();
                }
            }
        }
    }

    /*
     * This test invokes unmount multiple time and expects the call back
     * to be invoked just once.
     */
    public void testShutdownMultiple() {
        boolean oldStatus = getMediaState();
        try {
            // Mount media firsts
            if (!getMediaState()) {
                mountMedia();
            }
            IMountService ms = getMs();
            ShutdownObserver observer = new ShutdownObserver();
            synchronized (observer) {
                try {
                    ms.shutdown(observer);
                    for (int i = 0; i < 4; i++) {
                        ms.shutdown(null);
                    }
                } catch (RemoteException e) {
                    failStr(e);
                }
            }
        } finally {
            // Restore old status
            boolean currStatus = getMediaState();
            if (oldStatus != currStatus) {
                if (oldStatus) {
                    // Mount media
                    mountMedia();
                } else {
                    unmountMedia();
                }
            }
        }
    }

}