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