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