Home | History | Annotate | Download | only in settings
      1 /*
      2  * Copyright (C) 2011 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.settings;
     18 
     19 import android.app.Activity;
     20 import android.app.StatusBarManager;
     21 import android.content.ComponentName;
     22 import android.content.Context;
     23 import android.content.Intent;
     24 import android.content.pm.ActivityInfo;
     25 import android.content.pm.PackageManager;
     26 import android.content.res.Resources.NotFoundException;
     27 import android.media.AudioManager;
     28 import android.os.AsyncTask;
     29 import android.os.Bundle;
     30 import android.os.Handler;
     31 import android.os.IBinder;
     32 import android.os.Message;
     33 import android.os.PowerManager;
     34 import android.os.RemoteException;
     35 import android.os.ServiceManager;
     36 import android.os.SystemProperties;
     37 import android.os.UserHandle;
     38 import android.os.storage.IMountService;
     39 import android.os.storage.StorageManager;
     40 import android.provider.Settings;
     41 import android.telecom.TelecomManager;
     42 import android.telephony.TelephonyManager;
     43 import android.text.Editable;
     44 import android.text.TextUtils;
     45 import android.text.TextWatcher;
     46 import android.text.format.DateUtils;
     47 import android.util.Log;
     48 import android.view.KeyEvent;
     49 import android.view.MotionEvent;
     50 import android.view.View;
     51 import android.view.View.OnClickListener;
     52 import android.view.View.OnKeyListener;
     53 import android.view.View.OnTouchListener;
     54 import android.view.WindowManager;
     55 import android.view.inputmethod.EditorInfo;
     56 import android.view.inputmethod.InputMethodInfo;
     57 import android.view.inputmethod.InputMethodManager;
     58 import android.view.inputmethod.InputMethodSubtype;
     59 import android.widget.Button;
     60 import android.widget.EditText;
     61 import android.widget.ProgressBar;
     62 import android.widget.TextView;
     63 
     64 import com.android.internal.telephony.PhoneConstants;
     65 import com.android.internal.widget.LockPatternUtils;
     66 import com.android.internal.widget.LockPatternView;
     67 import com.android.internal.widget.LockPatternView.Cell;
     68 import com.android.internal.widget.LockPatternView.DisplayMode;
     69 
     70 import java.util.List;
     71 
     72 /**
     73  * Settings screens to show the UI flows for encrypting/decrypting the device.
     74  *
     75  * This may be started via adb for debugging the UI layout, without having to go through
     76  * encryption flows everytime. It should be noted that starting the activity in this manner
     77  * is only useful for verifying UI-correctness - the behavior will not be identical.
     78  * <pre>
     79  * $ adb shell pm enable com.android.settings/.CryptKeeper
     80  * $ adb shell am start \
     81  *     -e "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW" "progress" \
     82  *     -n com.android.settings/.CryptKeeper
     83  * </pre>
     84  */
     85 public class CryptKeeper extends Activity implements TextView.OnEditorActionListener,
     86         OnKeyListener, OnTouchListener, TextWatcher {
     87     private static final String TAG = "CryptKeeper";
     88 
     89     private static final String DECRYPT_STATE = "trigger_restart_framework";
     90 
     91     /** Message sent to us to indicate encryption update progress. */
     92     private static final int MESSAGE_UPDATE_PROGRESS = 1;
     93     /** Message sent to us to indicate alerting the user that we are waiting for password entry */
     94     private static final int MESSAGE_NOTIFY = 2;
     95 
     96     // Constants used to control policy.
     97     private static final int MAX_FAILED_ATTEMPTS = 30;
     98     private static final int COOL_DOWN_ATTEMPTS = 10;
     99 
    100     // Intent action for launching the Emergency Dialer activity.
    101     static final String ACTION_EMERGENCY_DIAL = "com.android.phone.EmergencyDialer.DIAL";
    102 
    103     // Debug Intent extras so that this Activity may be started via adb for debugging UI layouts
    104     private static final String EXTRA_FORCE_VIEW =
    105             "com.android.settings.CryptKeeper.DEBUG_FORCE_VIEW";
    106     private static final String FORCE_VIEW_PROGRESS = "progress";
    107     private static final String FORCE_VIEW_ERROR = "error";
    108     private static final String FORCE_VIEW_PASSWORD = "password";
    109 
    110     private static final String STATE_COOLDOWN = "cooldown";
    111 
    112     /** When encryption is detected, this flag indicates whether or not we've checked for errors. */
    113     private boolean mValidationComplete;
    114     private boolean mValidationRequested;
    115     /** A flag to indicate that the volume is in a bad state (e.g. partially encrypted). */
    116     private boolean mEncryptionGoneBad;
    117     /** If gone bad, should we show encryption failed (false) or corrupt (true)*/
    118     private boolean mCorrupt;
    119     /** A flag to indicate when the back event should be ignored */
    120     /** When set, blocks unlocking. Set every COOL_DOWN_ATTEMPTS attempts, only cleared
    121         by power cycling phone. */
    122     private boolean mCooldown = false;
    123 
    124     PowerManager.WakeLock mWakeLock;
    125     private EditText mPasswordEntry;
    126     private LockPatternView mLockPatternView;
    127     /** Number of calls to {@link #notifyUser()} to ignore before notifying. */
    128     private int mNotificationCountdown = 0;
    129     /** Number of calls to {@link #notifyUser()} before we release the wakelock */
    130     private int mReleaseWakeLockCountdown = 0;
    131     private int mStatusString = R.string.enter_password;
    132 
    133     // how long we wait to clear a wrong pattern
    134     private static final int WRONG_PATTERN_CLEAR_TIMEOUT_MS = 1500;
    135 
    136     // how long we wait to clear a right pattern
    137     private static final int RIGHT_PATTERN_CLEAR_TIMEOUT_MS = 500;
    138 
    139     // When the user enters a short pin/password, run this to show an error,
    140     // but don't count it against attempts.
    141     private final Runnable mFakeUnlockAttemptRunnable = new Runnable() {
    142         @Override
    143         public void run() {
    144             handleBadAttempt(1 /* failedAttempt */);
    145         }
    146     };
    147 
    148     // TODO: this should be tuned to match minimum decryption timeout
    149     private static final int FAKE_ATTEMPT_DELAY = 1000;
    150 
    151     private final Runnable mClearPatternRunnable = new Runnable() {
    152         @Override
    153         public void run() {
    154             mLockPatternView.clearPattern();
    155         }
    156     };
    157 
    158     /**
    159      * Used to propagate state through configuration changes (e.g. screen rotation)
    160      */
    161     private static class NonConfigurationInstanceState {
    162         final PowerManager.WakeLock wakelock;
    163 
    164         NonConfigurationInstanceState(PowerManager.WakeLock _wakelock) {
    165             wakelock = _wakelock;
    166         }
    167     }
    168 
    169     private class DecryptTask extends AsyncTask<String, Void, Integer> {
    170         private void hide(int id) {
    171             View view = findViewById(id);
    172             if (view != null) {
    173                 view.setVisibility(View.GONE);
    174             }
    175         }
    176 
    177         @Override
    178         protected void onPreExecute() {
    179             super.onPreExecute();
    180             beginAttempt();
    181         }
    182 
    183         @Override
    184         protected Integer doInBackground(String... params) {
    185             final IMountService service = getMountService();
    186             try {
    187                 return service.decryptStorage(params[0]);
    188             } catch (Exception e) {
    189                 Log.e(TAG, "Error while decrypting...", e);
    190                 return -1;
    191             }
    192         }
    193 
    194         @Override
    195         protected void onPostExecute(Integer failedAttempts) {
    196             if (failedAttempts == 0) {
    197                 // The password was entered successfully. Simply do nothing
    198                 // and wait for the service restart to switch to surfacefligner
    199                 if (mLockPatternView != null) {
    200                     mLockPatternView.removeCallbacks(mClearPatternRunnable);
    201                     mLockPatternView.postDelayed(mClearPatternRunnable, RIGHT_PATTERN_CLEAR_TIMEOUT_MS);
    202                 }
    203                 final TextView status = (TextView) findViewById(R.id.status);
    204                 status.setText(R.string.starting_android);
    205                 hide(R.id.passwordEntry);
    206                 hide(R.id.switch_ime_button);
    207                 hide(R.id.lockPattern);
    208                 hide(R.id.owner_info);
    209                 hide(R.id.emergencyCallButton);
    210             } else if (failedAttempts == MAX_FAILED_ATTEMPTS) {
    211                 // Factory reset the device.
    212                 Intent intent = new Intent(Intent.ACTION_MASTER_CLEAR);
    213                 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    214                 intent.putExtra(Intent.EXTRA_REASON, "CryptKeeper.MAX_FAILED_ATTEMPTS");
    215                 sendBroadcast(intent);
    216             } else if (failedAttempts == -1) {
    217                 // Right password, but decryption failed. Tell user bad news ...
    218                 setContentView(R.layout.crypt_keeper_progress);
    219                 showFactoryReset(true);
    220                 return;
    221             } else {
    222                 handleBadAttempt(failedAttempts);
    223             }
    224         }
    225     }
    226 
    227     private void beginAttempt() {
    228         final TextView status = (TextView) findViewById(R.id.status);
    229         status.setText(R.string.checking_decryption);
    230     }
    231 
    232     private void handleBadAttempt(Integer failedAttempts) {
    233         // Wrong entry. Handle pattern case.
    234         if (mLockPatternView != null) {
    235             mLockPatternView.setDisplayMode(DisplayMode.Wrong);
    236             mLockPatternView.removeCallbacks(mClearPatternRunnable);
    237             mLockPatternView.postDelayed(mClearPatternRunnable, WRONG_PATTERN_CLEAR_TIMEOUT_MS);
    238         }
    239         if ((failedAttempts % COOL_DOWN_ATTEMPTS) == 0) {
    240             mCooldown = true;
    241             // No need to setBackFunctionality(false) - it's already done
    242             // at this point.
    243             cooldown();
    244         } else {
    245             final TextView status = (TextView) findViewById(R.id.status);
    246 
    247             int remainingAttempts = MAX_FAILED_ATTEMPTS - failedAttempts;
    248             if (remainingAttempts < COOL_DOWN_ATTEMPTS) {
    249                 CharSequence warningTemplate = getText(R.string.crypt_keeper_warn_wipe);
    250                 CharSequence warning = TextUtils.expandTemplate(warningTemplate,
    251                         Integer.toString(remainingAttempts));
    252                 status.setText(warning);
    253             } else {
    254                 int passwordType = StorageManager.CRYPT_TYPE_PASSWORD;
    255                 try {
    256                     final IMountService service = getMountService();
    257                     passwordType = service.getPasswordType();
    258                 } catch (Exception e) {
    259                     Log.e(TAG, "Error calling mount service " + e);
    260                 }
    261 
    262                 if (passwordType == StorageManager.CRYPT_TYPE_PIN) {
    263                     status.setText(R.string.cryptkeeper_wrong_pin);
    264                 } else if (passwordType == StorageManager.CRYPT_TYPE_PATTERN) {
    265                     status.setText(R.string.cryptkeeper_wrong_pattern);
    266                 } else {
    267                     status.setText(R.string.cryptkeeper_wrong_password);
    268                 }
    269             }
    270 
    271             if (mLockPatternView != null) {
    272                 mLockPatternView.setDisplayMode(DisplayMode.Wrong);
    273                 mLockPatternView.setEnabled(true);
    274             }
    275 
    276             // Reenable the password entry
    277             if (mPasswordEntry != null) {
    278                 mPasswordEntry.setEnabled(true);
    279                 final InputMethodManager imm = (InputMethodManager) getSystemService(
    280                         Context.INPUT_METHOD_SERVICE);
    281                 imm.showSoftInput(mPasswordEntry, 0);
    282                 setBackFunctionality(true);
    283             }
    284         }
    285     }
    286 
    287     private class ValidationTask extends AsyncTask<Void, Void, Boolean> {
    288         int state;
    289 
    290         @Override
    291         protected Boolean doInBackground(Void... params) {
    292             final IMountService service = getMountService();
    293             try {
    294                 Log.d(TAG, "Validating encryption state.");
    295                 state = service.getEncryptionState();
    296                 if (state == IMountService.ENCRYPTION_STATE_NONE) {
    297                     Log.w(TAG, "Unexpectedly in CryptKeeper even though there is no encryption.");
    298                     return true; // Unexpected, but fine, I guess...
    299                 }
    300                 return state == IMountService.ENCRYPTION_STATE_OK;
    301             } catch (RemoteException e) {
    302                 Log.w(TAG, "Unable to get encryption state properly");
    303                 return true;
    304             }
    305         }
    306 
    307         @Override
    308         protected void onPostExecute(Boolean result) {
    309             mValidationComplete = true;
    310             if (Boolean.FALSE.equals(result)) {
    311                 Log.w(TAG, "Incomplete, or corrupted encryption detected. Prompting user to wipe.");
    312                 mEncryptionGoneBad = true;
    313                 mCorrupt = state == IMountService.ENCRYPTION_STATE_ERROR_CORRUPT;
    314             } else {
    315                 Log.d(TAG, "Encryption state validated. Proceeding to configure UI");
    316             }
    317             setupUi();
    318         }
    319     }
    320 
    321     private final Handler mHandler = new Handler() {
    322         @Override
    323         public void handleMessage(Message msg) {
    324             switch (msg.what) {
    325             case MESSAGE_UPDATE_PROGRESS:
    326                 updateProgress();
    327                 break;
    328 
    329             case MESSAGE_NOTIFY:
    330                 notifyUser();
    331                 break;
    332             }
    333         }
    334     };
    335 
    336     private AudioManager mAudioManager;
    337     /** The status bar where back/home/recent buttons are shown. */
    338     private StatusBarManager mStatusBar;
    339 
    340     /** All the widgets to disable in the status bar */
    341     final private static int sWidgetsToDisable = StatusBarManager.DISABLE_EXPAND
    342             | StatusBarManager.DISABLE_NOTIFICATION_ICONS
    343             | StatusBarManager.DISABLE_NOTIFICATION_ALERTS
    344             | StatusBarManager.DISABLE_HOME
    345             | StatusBarManager.DISABLE_SEARCH
    346             | StatusBarManager.DISABLE_RECENT;
    347 
    348     protected static final int MIN_LENGTH_BEFORE_REPORT = LockPatternUtils.MIN_LOCK_PATTERN_SIZE;
    349 
    350     /** @return whether or not this Activity was started for debugging the UI only. */
    351     private boolean isDebugView() {
    352         return getIntent().hasExtra(EXTRA_FORCE_VIEW);
    353     }
    354 
    355     /** @return whether or not this Activity was started for debugging the specific UI view only. */
    356     private boolean isDebugView(String viewType /* non-nullable */) {
    357         return viewType.equals(getIntent().getStringExtra(EXTRA_FORCE_VIEW));
    358     }
    359 
    360     /**
    361      * Notify the user that we are awaiting input. Currently this sends an audio alert.
    362      */
    363     private void notifyUser() {
    364         if (mNotificationCountdown > 0) {
    365             --mNotificationCountdown;
    366         } else if (mAudioManager != null) {
    367             try {
    368                 // Play the standard keypress sound at full volume. This should be available on
    369                 // every device. We cannot play a ringtone here because media services aren't
    370                 // available yet. A DTMF-style tone is too soft to be noticed, and might not exist
    371                 // on tablet devices. The idea is to alert the user that something is needed: this
    372                 // does not have to be pleasing.
    373                 mAudioManager.playSoundEffect(AudioManager.FX_KEYPRESS_STANDARD, 100);
    374             } catch (Exception e) {
    375                 Log.w(TAG, "notifyUser: Exception while playing sound: " + e);
    376             }
    377         }
    378         // Notify the user again in 5 seconds.
    379         mHandler.removeMessages(MESSAGE_NOTIFY);
    380         mHandler.sendEmptyMessageDelayed(MESSAGE_NOTIFY, 5 * 1000);
    381 
    382         if (mWakeLock.isHeld()) {
    383             if (mReleaseWakeLockCountdown > 0) {
    384                 --mReleaseWakeLockCountdown;
    385             } else {
    386                 mWakeLock.release();
    387             }
    388         }
    389     }
    390 
    391     /**
    392      * Ignore back events from this activity always - there's nowhere to go back
    393      * to
    394      */
    395     @Override
    396     public void onBackPressed() {
    397     }
    398 
    399     @Override
    400     public void onCreate(Bundle savedInstanceState) {
    401         super.onCreate(savedInstanceState);
    402 
    403         // If we are not encrypted or encrypting, get out quickly.
    404         final String state = SystemProperties.get("vold.decrypt");
    405         if (!isDebugView() && ("".equals(state) || DECRYPT_STATE.equals(state))) {
    406             disableCryptKeeperComponent(this);
    407             // Typically CryptKeeper is launched as the home app.  We didn't
    408             // want to be running, so need to finish this activity.  We can count
    409             // on the activity manager re-launching the new home app upon finishing
    410             // this one, since this will leave the activity stack empty.
    411             // NOTE: This is really grungy.  I think it would be better for the
    412             // activity manager to explicitly launch the crypt keeper instead of
    413             // home in the situation where we need to decrypt the device
    414             finish();
    415             return;
    416         }
    417 
    418         try {
    419             if (getResources().getBoolean(R.bool.crypt_keeper_allow_rotation)) {
    420                 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
    421             }
    422         } catch (NotFoundException e) {
    423         }
    424 
    425         // Disable the status bar, but do NOT disable back because the user needs a way to go
    426         // from keyboard settings and back to the password screen.
    427         mStatusBar = (StatusBarManager) getSystemService(Context.STATUS_BAR_SERVICE);
    428         mStatusBar.disable(sWidgetsToDisable);
    429 
    430         if (savedInstanceState != null) {
    431             mCooldown = savedInstanceState.getBoolean(STATE_COOLDOWN);
    432         }
    433 
    434         setAirplaneModeIfNecessary();
    435         mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    436         // Check for (and recover) retained instance data
    437         final Object lastInstance = getLastNonConfigurationInstance();
    438         if (lastInstance instanceof NonConfigurationInstanceState) {
    439             NonConfigurationInstanceState retained = (NonConfigurationInstanceState) lastInstance;
    440             mWakeLock = retained.wakelock;
    441             Log.d(TAG, "Restoring wakelock from NonConfigurationInstanceState");
    442         }
    443     }
    444 
    445     @Override
    446     public void  onSaveInstanceState(Bundle savedInstanceState) {
    447         savedInstanceState.putBoolean(STATE_COOLDOWN, mCooldown);
    448     }
    449 
    450     /**
    451      * Note, we defer the state check and screen setup to onStart() because this will be
    452      * re-run if the user clicks the power button (sleeping/waking the screen), and this is
    453      * especially important if we were to lose the wakelock for any reason.
    454      */
    455     @Override
    456     public void onStart() {
    457         super.onStart();
    458         setupUi();
    459     }
    460 
    461     /**
    462      * Initializes the UI based on the current state of encryption.
    463      * This is idempotent - calling repeatedly will simply re-initialize the UI.
    464      */
    465     private void setupUi() {
    466         if (mEncryptionGoneBad || isDebugView(FORCE_VIEW_ERROR)) {
    467             setContentView(R.layout.crypt_keeper_progress);
    468             showFactoryReset(mCorrupt);
    469             return;
    470         }
    471 
    472         final String progress = SystemProperties.get("vold.encrypt_progress");
    473         if (!"".equals(progress) || isDebugView(FORCE_VIEW_PROGRESS)) {
    474             setContentView(R.layout.crypt_keeper_progress);
    475             encryptionProgressInit();
    476         } else if (mValidationComplete || isDebugView(FORCE_VIEW_PASSWORD)) {
    477             new AsyncTask<Void, Void, Void>() {
    478                 int passwordType = StorageManager.CRYPT_TYPE_PASSWORD;
    479                 String owner_info;
    480                 boolean pattern_visible;
    481                 boolean password_visible;
    482 
    483                 @Override
    484                 public Void doInBackground(Void... v) {
    485                     try {
    486                         final IMountService service = getMountService();
    487                         passwordType = service.getPasswordType();
    488                         owner_info = service.getField(StorageManager.OWNER_INFO_KEY);
    489                         pattern_visible = !("0".equals(service.getField(StorageManager.PATTERN_VISIBLE_KEY)));
    490                         password_visible = !("0".equals(service.getField(StorageManager.PASSWORD_VISIBLE_KEY)));
    491                     } catch (Exception e) {
    492                         Log.e(TAG, "Error calling mount service " + e);
    493                     }
    494 
    495                     return null;
    496                 }
    497 
    498                 @Override
    499                 public void onPostExecute(java.lang.Void v) {
    500                     Settings.System.putInt(getContentResolver(), Settings.System.TEXT_SHOW_PASSWORD,
    501                                   password_visible ? 1 : 0);
    502 
    503                     if (passwordType == StorageManager.CRYPT_TYPE_PIN) {
    504                         setContentView(R.layout.crypt_keeper_pin_entry);
    505                         mStatusString = R.string.enter_pin;
    506                     } else if (passwordType == StorageManager.CRYPT_TYPE_PATTERN) {
    507                         setContentView(R.layout.crypt_keeper_pattern_entry);
    508                         setBackFunctionality(false);
    509                         mStatusString = R.string.enter_pattern;
    510                     } else {
    511                         setContentView(R.layout.crypt_keeper_password_entry);
    512                         mStatusString = R.string.enter_password;
    513                     }
    514                     final TextView status = (TextView) findViewById(R.id.status);
    515                     status.setText(mStatusString);
    516 
    517                     final TextView ownerInfo = (TextView) findViewById(R.id.owner_info);
    518                     ownerInfo.setText(owner_info);
    519                     ownerInfo.setSelected(true); // Required for marquee'ing to work
    520 
    521                     passwordEntryInit();
    522 
    523                     findViewById(android.R.id.content).setSystemUiVisibility(View.STATUS_BAR_DISABLE_BACK);
    524 
    525                     if (mLockPatternView != null) {
    526                         mLockPatternView.setInStealthMode(!pattern_visible);
    527                     }
    528                     if (mCooldown) {
    529                         // in case we are cooling down and coming back from emergency dialler
    530                         setBackFunctionality(false);
    531                         cooldown();
    532                     }
    533 
    534                 }
    535             }.execute();
    536         } else if (!mValidationRequested) {
    537             // We're supposed to be encrypted, but no validation has been done.
    538             new ValidationTask().execute((Void[]) null);
    539             mValidationRequested = true;
    540         }
    541     }
    542 
    543     @Override
    544     public void onStop() {
    545         super.onStop();
    546         mHandler.removeMessages(MESSAGE_UPDATE_PROGRESS);
    547         mHandler.removeMessages(MESSAGE_NOTIFY);
    548     }
    549 
    550     /**
    551      * Reconfiguring, so propagate the wakelock to the next instance.  This runs between onStop()
    552      * and onDestroy() and only if we are changing configuration (e.g. rotation).  Also clears
    553      * mWakeLock so the subsequent call to onDestroy does not release it.
    554      */
    555     @Override
    556     public Object onRetainNonConfigurationInstance() {
    557         NonConfigurationInstanceState state = new NonConfigurationInstanceState(mWakeLock);
    558         Log.d(TAG, "Handing wakelock off to NonConfigurationInstanceState");
    559         mWakeLock = null;
    560         return state;
    561     }
    562 
    563     @Override
    564     public void onDestroy() {
    565         super.onDestroy();
    566 
    567         if (mWakeLock != null) {
    568             Log.d(TAG, "Releasing and destroying wakelock");
    569             mWakeLock.release();
    570             mWakeLock = null;
    571         }
    572     }
    573 
    574     /**
    575      * Start encrypting the device.
    576      */
    577     private void encryptionProgressInit() {
    578         // Accquire a partial wakelock to prevent the device from sleeping. Note
    579         // we never release this wakelock as we will be restarted after the device
    580         // is encrypted.
    581         Log.d(TAG, "Encryption progress screen initializing.");
    582         if (mWakeLock == null) {
    583             Log.d(TAG, "Acquiring wakelock.");
    584             PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    585             mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
    586             mWakeLock.acquire();
    587         }
    588 
    589         ((ProgressBar) findViewById(R.id.progress_bar)).setIndeterminate(true);
    590         // Ignore all back presses from now, both hard and soft keys.
    591         setBackFunctionality(false);
    592         // Start the first run of progress manually. This method sets up messages to occur at
    593         // repeated intervals.
    594         updateProgress();
    595     }
    596 
    597     /**
    598      * Show factory reset screen allowing the user to reset their phone when
    599      * there is nothing else we can do
    600      * @param corrupt true if userdata is corrupt, false if encryption failed
    601      *        partway through
    602      */
    603     private void showFactoryReset(final boolean corrupt) {
    604         // Hide the encryption-bot to make room for the "factory reset" button
    605         findViewById(R.id.encroid).setVisibility(View.GONE);
    606 
    607         // Show the reset button, failure text, and a divider
    608         final Button button = (Button) findViewById(R.id.factory_reset);
    609         button.setVisibility(View.VISIBLE);
    610         button.setOnClickListener(new OnClickListener() {
    611                 @Override
    612             public void onClick(View v) {
    613                 // Factory reset the device.
    614                 Intent intent = new Intent(Intent.ACTION_MASTER_CLEAR);
    615                 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
    616                 intent.putExtra(Intent.EXTRA_REASON,
    617                         "CryptKeeper.showFactoryReset() corrupt=" + corrupt);
    618                 sendBroadcast(intent);
    619             }
    620         });
    621 
    622         // Alert the user of the failure.
    623         if (corrupt) {
    624             ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_data_corrupt_title);
    625             ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_data_corrupt_summary);
    626         } else {
    627             ((TextView) findViewById(R.id.title)).setText(R.string.crypt_keeper_failed_title);
    628             ((TextView) findViewById(R.id.status)).setText(R.string.crypt_keeper_failed_summary);
    629         }
    630 
    631         final View view = findViewById(R.id.bottom_divider);
    632         // TODO(viki): Why would the bottom divider be missing in certain layouts? Investigate.
    633         if (view != null) {
    634             view.setVisibility(View.VISIBLE);
    635         }
    636     }
    637 
    638     private void updateProgress() {
    639         final String state = SystemProperties.get("vold.encrypt_progress");
    640 
    641         if ("error_partially_encrypted".equals(state)) {
    642             showFactoryReset(false);
    643             return;
    644         }
    645 
    646         // Get status as percentage first
    647         CharSequence status = getText(R.string.crypt_keeper_setup_description);
    648         int percent = 0;
    649         try {
    650             // Force a 50% progress state when debugging the view.
    651             percent = isDebugView() ? 50 : Integer.parseInt(state);
    652         } catch (Exception e) {
    653             Log.w(TAG, "Error parsing progress: " + e.toString());
    654         }
    655         String progress = Integer.toString(percent);
    656 
    657         // Now try to get status as time remaining and replace as appropriate
    658         Log.v(TAG, "Encryption progress: " + progress);
    659         try {
    660             final String timeProperty = SystemProperties.get("vold.encrypt_time_remaining");
    661             int time = Integer.parseInt(timeProperty);
    662             if (time >= 0) {
    663                 // Round up to multiple of 10 - this way display is less jerky
    664                 time = (time + 9) / 10 * 10;
    665                 progress = DateUtils.formatElapsedTime(time);
    666                 status = getText(R.string.crypt_keeper_setup_time_remaining);
    667             }
    668         } catch (Exception e) {
    669             // Will happen if no time etc - show percentage
    670         }
    671 
    672         final TextView tv = (TextView) findViewById(R.id.status);
    673         if (tv != null) {
    674             tv.setText(TextUtils.expandTemplate(status, progress));
    675         }
    676 
    677         // Check the progress every 1 seconds
    678         mHandler.removeMessages(MESSAGE_UPDATE_PROGRESS);
    679         mHandler.sendEmptyMessageDelayed(MESSAGE_UPDATE_PROGRESS, 1000);
    680     }
    681 
    682     /** Insist on a power cycle to force the user to waste time between retries.
    683      *
    684      * Call setBackFunctionality(false) before calling this. */
    685     private void cooldown() {
    686         // Disable the password entry.
    687         if (mPasswordEntry != null) {
    688             mPasswordEntry.setEnabled(false);
    689         }
    690         if (mLockPatternView != null) {
    691             mLockPatternView.setEnabled(false);
    692         }
    693 
    694         final TextView status = (TextView) findViewById(R.id.status);
    695         status.setText(R.string.crypt_keeper_force_power_cycle);
    696     }
    697 
    698     /**
    699      * Sets the back status: enabled or disabled according to the parameter.
    700      * @param isEnabled true if back is enabled, false otherwise.
    701      */
    702     private final void setBackFunctionality(boolean isEnabled) {
    703         if (isEnabled) {
    704             mStatusBar.disable(sWidgetsToDisable);
    705         } else {
    706             mStatusBar.disable(sWidgetsToDisable | StatusBarManager.DISABLE_BACK);
    707         }
    708     }
    709 
    710     private void fakeUnlockAttempt(View postingView) {
    711         beginAttempt();
    712         postingView.postDelayed(mFakeUnlockAttemptRunnable, FAKE_ATTEMPT_DELAY);
    713     }
    714 
    715     protected LockPatternView.OnPatternListener mChooseNewLockPatternListener =
    716         new LockPatternView.OnPatternListener() {
    717 
    718         @Override
    719         public void onPatternStart() {
    720             mLockPatternView.removeCallbacks(mClearPatternRunnable);
    721         }
    722 
    723         @Override
    724         public void onPatternCleared() {
    725         }
    726 
    727         @Override
    728         public void onPatternDetected(List<LockPatternView.Cell> pattern) {
    729             mLockPatternView.setEnabled(false);
    730             if (pattern.size() >= MIN_LENGTH_BEFORE_REPORT) {
    731                 new DecryptTask().execute(LockPatternUtils.patternToString(pattern));
    732             } else {
    733                 // Allow user to make as many of these as they want.
    734                 fakeUnlockAttempt(mLockPatternView);
    735             }
    736         }
    737 
    738         @Override
    739         public void onPatternCellAdded(List<Cell> pattern) {
    740         }
    741      };
    742 
    743      private void passwordEntryInit() {
    744         // Password/pin case
    745         mPasswordEntry = (EditText) findViewById(R.id.passwordEntry);
    746         if (mPasswordEntry != null){
    747             mPasswordEntry.setOnEditorActionListener(this);
    748             mPasswordEntry.requestFocus();
    749             // Become quiet when the user interacts with the Edit text screen.
    750             mPasswordEntry.setOnKeyListener(this);
    751             mPasswordEntry.setOnTouchListener(this);
    752             mPasswordEntry.addTextChangedListener(this);
    753         }
    754 
    755         // Pattern case
    756         mLockPatternView = (LockPatternView) findViewById(R.id.lockPattern);
    757         if (mLockPatternView != null) {
    758             mLockPatternView.setOnPatternListener(mChooseNewLockPatternListener);
    759         }
    760 
    761         // Disable the Emergency call button if the device has no voice telephone capability
    762         if (!getTelephonyManager().isVoiceCapable()) {
    763             final View emergencyCall = findViewById(R.id.emergencyCallButton);
    764             if (emergencyCall != null) {
    765                 Log.d(TAG, "Removing the emergency Call button");
    766                 emergencyCall.setVisibility(View.GONE);
    767             }
    768         }
    769 
    770         final View imeSwitcher = findViewById(R.id.switch_ime_button);
    771         final InputMethodManager imm = (InputMethodManager) getSystemService(
    772                 Context.INPUT_METHOD_SERVICE);
    773         if (imeSwitcher != null && hasMultipleEnabledIMEsOrSubtypes(imm, false)) {
    774             imeSwitcher.setVisibility(View.VISIBLE);
    775             imeSwitcher.setOnClickListener(new OnClickListener() {
    776                     @Override
    777                 public void onClick(View v) {
    778                     imm.showInputMethodPicker(false /* showAuxiliarySubtypes */);
    779                 }
    780             });
    781         }
    782 
    783         // We want to keep the screen on while waiting for input. In minimal boot mode, the device
    784         // is completely non-functional, and we want the user to notice the device and enter a
    785         // password.
    786         if (mWakeLock == null) {
    787             Log.d(TAG, "Acquiring wakelock.");
    788             final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    789             if (pm != null) {
    790                 mWakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, TAG);
    791                 mWakeLock.acquire();
    792                 // Keep awake for 10 minutes - if the user hasn't been alerted by then
    793                 // best not to just drain their battery
    794                 mReleaseWakeLockCountdown = 96; // 96 * 5 secs per click + 120 secs before we show this = 600
    795             }
    796         }
    797 
    798         // Asynchronously throw up the IME, since there are issues with requesting it to be shown
    799         // immediately.
    800         if (mLockPatternView == null && !mCooldown) {
    801             getWindow().setSoftInputMode(
    802                                 WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
    803             mHandler.postDelayed(new Runnable() {
    804                 @Override public void run() {
    805                     imm.showSoftInputUnchecked(0, null);
    806                 }
    807             }, 0);
    808         }
    809 
    810         updateEmergencyCallButtonState();
    811         // Notify the user in 120 seconds that we are waiting for him to enter the password.
    812         mHandler.removeMessages(MESSAGE_NOTIFY);
    813         mHandler.sendEmptyMessageDelayed(MESSAGE_NOTIFY, 120 * 1000);
    814 
    815         // Dismiss secure & non-secure keyguards while this screen is showing.
    816         getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
    817                 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
    818     }
    819 
    820     /**
    821      * Method adapted from com.android.inputmethod.latin.Utils
    822      *
    823      * @param imm The input method manager
    824      * @param shouldIncludeAuxiliarySubtypes
    825      * @return true if we have multiple IMEs to choose from
    826      */
    827     private boolean hasMultipleEnabledIMEsOrSubtypes(InputMethodManager imm,
    828             final boolean shouldIncludeAuxiliarySubtypes) {
    829         final List<InputMethodInfo> enabledImis = imm.getEnabledInputMethodList();
    830 
    831         // Number of the filtered IMEs
    832         int filteredImisCount = 0;
    833 
    834         for (InputMethodInfo imi : enabledImis) {
    835             // We can return true immediately after we find two or more filtered IMEs.
    836             if (filteredImisCount > 1) return true;
    837             final List<InputMethodSubtype> subtypes =
    838                     imm.getEnabledInputMethodSubtypeList(imi, true);
    839             // IMEs that have no subtypes should be counted.
    840             if (subtypes.isEmpty()) {
    841                 ++filteredImisCount;
    842                 continue;
    843             }
    844 
    845             int auxCount = 0;
    846             for (InputMethodSubtype subtype : subtypes) {
    847                 if (subtype.isAuxiliary()) {
    848                     ++auxCount;
    849                 }
    850             }
    851             final int nonAuxCount = subtypes.size() - auxCount;
    852 
    853             // IMEs that have one or more non-auxiliary subtypes should be counted.
    854             // If shouldIncludeAuxiliarySubtypes is true, IMEs that have two or more auxiliary
    855             // subtypes should be counted as well.
    856             if (nonAuxCount > 0 || (shouldIncludeAuxiliarySubtypes && auxCount > 1)) {
    857                 ++filteredImisCount;
    858                 continue;
    859             }
    860         }
    861 
    862         return filteredImisCount > 1
    863         // imm.getEnabledInputMethodSubtypeList(null, false) will return the current IME's enabled
    864         // input method subtype (The current IME should be LatinIME.)
    865                 || imm.getEnabledInputMethodSubtypeList(null, false).size() > 1;
    866     }
    867 
    868     private IMountService getMountService() {
    869         final IBinder service = ServiceManager.getService("mount");
    870         if (service != null) {
    871             return IMountService.Stub.asInterface(service);
    872         }
    873         return null;
    874     }
    875 
    876     @Override
    877     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    878         if (actionId == EditorInfo.IME_NULL || actionId == EditorInfo.IME_ACTION_DONE) {
    879             // Get the password
    880             final String password = v.getText().toString();
    881 
    882             if (TextUtils.isEmpty(password)) {
    883                 return true;
    884             }
    885 
    886             // Now that we have the password clear the password field.
    887             v.setText(null);
    888 
    889             // Disable the password entry and back keypress while checking the password. These
    890             // we either be re-enabled if the password was wrong or after the cooldown period.
    891             mPasswordEntry.setEnabled(false);
    892             setBackFunctionality(false);
    893 
    894             if (password.length() >= LockPatternUtils.MIN_LOCK_PATTERN_SIZE) {
    895                 new DecryptTask().execute(password);
    896             } else {
    897                 // Allow user to make as many of these as they want.
    898                 fakeUnlockAttempt(mPasswordEntry);
    899             }
    900 
    901             return true;
    902         }
    903         return false;
    904     }
    905 
    906     /**
    907      * Set airplane mode on the device if it isn't an LTE device.
    908      * Full story: In minimal boot mode, we cannot save any state. In particular, we cannot save
    909      * any incoming SMS's. So SMSs that are received here will be silently dropped to the floor.
    910      * That is bad. Also, we cannot receive any telephone calls in this state. So to avoid
    911      * both these problems, we turn the radio off. However, on certain networks turning on and
    912      * off the radio takes a long time. In such cases, we are better off leaving the radio
    913      * running so the latency of an E911 call is short.
    914      * The behavior after this is:
    915      * 1. Emergency dialing: the emergency dialer has logic to force the device out of
    916      *    airplane mode and restart the radio.
    917      * 2. Full boot: we read the persistent settings from the previous boot and restore the
    918      *    radio to whatever it was before it restarted. This also happens when rebooting a
    919      *    phone that has no encryption.
    920      */
    921     private final void setAirplaneModeIfNecessary() {
    922         final boolean isLteDevice =
    923                 getTelephonyManager().getLteOnCdmaMode() == PhoneConstants.LTE_ON_CDMA_TRUE;
    924         if (!isLteDevice) {
    925             Log.d(TAG, "Going into airplane mode.");
    926             Settings.Global.putInt(getContentResolver(), Settings.Global.AIRPLANE_MODE_ON, 1);
    927             final Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
    928             intent.putExtra("state", true);
    929             sendBroadcastAsUser(intent, UserHandle.ALL);
    930         }
    931     }
    932 
    933     /**
    934      * Code to update the state of, and handle clicks from, the "Emergency call" button.
    935      *
    936      * This code is mostly duplicated from the corresponding code in
    937      * LockPatternUtils and LockPatternKeyguardView under frameworks/base.
    938      */
    939     private void updateEmergencyCallButtonState() {
    940         final Button emergencyCall = (Button) findViewById(R.id.emergencyCallButton);
    941         // The button isn't present at all in some configurations.
    942         if (emergencyCall == null)
    943             return;
    944 
    945         if (isEmergencyCallCapable()) {
    946             emergencyCall.setVisibility(View.VISIBLE);
    947             emergencyCall.setOnClickListener(new View.OnClickListener() {
    948                     @Override
    949 
    950                     public void onClick(View v) {
    951                         takeEmergencyCallAction();
    952                     }
    953                 });
    954         } else {
    955             emergencyCall.setVisibility(View.GONE);
    956             return;
    957         }
    958 
    959         int textId;
    960         if (getTelecomManager().isInCall()) {
    961             // Show "return to call"
    962             textId = R.string.cryptkeeper_return_to_call;
    963         } else {
    964             textId = R.string.cryptkeeper_emergency_call;
    965         }
    966         emergencyCall.setText(textId);
    967     }
    968 
    969     private boolean isEmergencyCallCapable() {
    970         return getResources().getBoolean(com.android.internal.R.bool.config_voice_capable);
    971     }
    972 
    973     private void takeEmergencyCallAction() {
    974         TelecomManager telecomManager = getTelecomManager();
    975         if (telecomManager.isInCall()) {
    976             telecomManager.showInCallScreen(false /* showDialpad */);
    977         } else {
    978             launchEmergencyDialer();
    979         }
    980     }
    981 
    982 
    983     private void launchEmergencyDialer() {
    984         final Intent intent = new Intent(ACTION_EMERGENCY_DIAL);
    985         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
    986                         | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
    987         setBackFunctionality(true);
    988         startActivity(intent);
    989     }
    990 
    991     private TelephonyManager getTelephonyManager() {
    992         return (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    993     }
    994 
    995     private TelecomManager getTelecomManager() {
    996         return (TelecomManager) getSystemService(Context.TELECOM_SERVICE);
    997     }
    998 
    999     /**
   1000      * Listen to key events so we can disable sounds when we get a keyinput in EditText.
   1001      */
   1002     private void delayAudioNotification() {
   1003         mNotificationCountdown = 20;
   1004     }
   1005 
   1006     @Override
   1007     public boolean onKey(View v, int keyCode, KeyEvent event) {
   1008         delayAudioNotification();
   1009         return false;
   1010     }
   1011 
   1012     @Override
   1013     public boolean onTouch(View v, MotionEvent event) {
   1014         delayAudioNotification();
   1015         return false;
   1016     }
   1017 
   1018     @Override
   1019     public void beforeTextChanged(CharSequence s, int start, int count, int after) {
   1020         return;
   1021     }
   1022 
   1023     @Override
   1024     public void onTextChanged(CharSequence s, int start, int before, int count) {
   1025         delayAudioNotification();
   1026     }
   1027 
   1028     @Override
   1029     public void afterTextChanged(Editable s) {
   1030         return;
   1031     }
   1032 
   1033     private static void disableCryptKeeperComponent(Context context) {
   1034         PackageManager pm = context.getPackageManager();
   1035         ComponentName name = new ComponentName(context, CryptKeeper.class);
   1036         Log.d(TAG, "Disabling component " + name);
   1037         pm.setComponentEnabledSetting(name, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
   1038                 PackageManager.DONT_KILL_APP);
   1039     }
   1040 }
   1041