1/*
2 * Copyright (C) 2012 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.internal.policy.impl.keyguard;
18
19import com.android.internal.policy.IFaceLockCallback;
20import com.android.internal.policy.IFaceLockInterface;
21import com.android.internal.widget.LockPatternUtils;
22
23import android.app.admin.DevicePolicyManager;
24import android.content.ComponentName;
25import android.content.Context;
26import android.content.Intent;
27import android.content.ServiceConnection;
28import android.os.Handler;
29import android.os.IBinder;
30import android.os.Looper;
31import android.os.Message;
32import android.os.PowerManager;
33import android.os.RemoteException;
34import android.util.Log;
35import android.view.View;
36
37public class FaceUnlock implements BiometricSensorUnlock, Handler.Callback {
38
39    private static final boolean DEBUG = false;
40    private static final String TAG = "FULLockscreen";
41
42    private final Context mContext;
43    private final LockPatternUtils mLockPatternUtils;
44
45    // TODO: is mServiceRunning needed or can we just use mIsRunning or check if mService is null?
46    private boolean mServiceRunning = false;
47    // TODO: now that the code has been restructure to do almost all operations from a handler, this
48    // lock may no longer be necessary.
49    private final Object mServiceRunningLock = new Object();
50    private IFaceLockInterface mService;
51    private boolean mBoundToService = false;
52    private View mFaceUnlockView;
53
54    private Handler mHandler;
55    private final int MSG_SERVICE_CONNECTED = 0;
56    private final int MSG_SERVICE_DISCONNECTED = 1;
57    private final int MSG_UNLOCK = 2;
58    private final int MSG_CANCEL = 3;
59    private final int MSG_REPORT_FAILED_ATTEMPT = 4;
60    private final int MSG_POKE_WAKELOCK = 5;
61
62    // TODO: This was added for the purpose of adhering to what the biometric interface expects
63    // the isRunning() function to return.  However, it is probably not necessary to have both
64    // mRunning and mServiceRunning.  I'd just rather wait to change that logic.
65    private volatile boolean mIsRunning = false;
66
67    // So the user has a consistent amount of time when brought to the backup method from Face
68    // Unlock
69    private final int BACKUP_LOCK_TIMEOUT = 5000;
70
71    KeyguardSecurityCallback mKeyguardScreenCallback;
72
73    /**
74     * Stores some of the structures that Face Unlock will need to access and creates the handler
75     * will be used to execute messages on the UI thread.
76     */
77    public FaceUnlock(Context context) {
78        mContext = context;
79        mLockPatternUtils = new LockPatternUtils(context);
80        mHandler = new Handler(this);
81    }
82
83    public void setKeyguardCallback(KeyguardSecurityCallback keyguardScreenCallback) {
84        mKeyguardScreenCallback = keyguardScreenCallback;
85    }
86
87    /**
88     * Stores and displays the view that Face Unlock is allowed to draw within.
89     * TODO: since the layout object will eventually be shared by multiple biometric unlock
90     * methods, we will have to add our other views (background, cancel button) here.
91     */
92    public void initializeView(View biometricUnlockView) {
93        Log.d(TAG, "initializeView()");
94        mFaceUnlockView = biometricUnlockView;
95    }
96
97    /**
98     * Indicates whether Face Unlock is currently running.
99     */
100    public boolean isRunning() {
101        return mIsRunning;
102    }
103
104    /**
105     * Dismisses face unlock and goes to the backup lock
106     */
107    public void stopAndShowBackup() {
108        if (DEBUG) Log.d(TAG, "stopAndShowBackup()");
109        mHandler.sendEmptyMessage(MSG_CANCEL);
110    }
111
112    /**
113     * Binds to the Face Unlock service.  Face Unlock will be started when the bind completes.  The
114     * Face Unlock view is displayed to hide the backup lock while the service is starting up.
115     * Called on the UI thread.
116     */
117    public boolean start() {
118        if (DEBUG) Log.d(TAG, "start()");
119        if (mHandler.getLooper() != Looper.myLooper()) {
120            Log.e(TAG, "start() called off of the UI thread");
121        }
122
123        if (mIsRunning) {
124            Log.w(TAG, "start() called when already running");
125        }
126
127        if (!mBoundToService) {
128            Log.d(TAG, "Binding to Face Unlock service for user="
129                    + mLockPatternUtils.getCurrentUser());
130            mContext.bindService(new Intent(IFaceLockInterface.class.getName()),
131                    mConnection,
132                    Context.BIND_AUTO_CREATE,
133                    mLockPatternUtils.getCurrentUser());
134            mBoundToService = true;
135        } else {
136            Log.w(TAG, "Attempt to bind to Face Unlock when already bound");
137        }
138
139        mIsRunning = true;
140        return true;
141    }
142
143    /**
144     * Stops Face Unlock and unbinds from the service.  Called on the UI thread.
145     */
146    public boolean stop() {
147        if (DEBUG) Log.d(TAG, "stop()");
148        if (mHandler.getLooper() != Looper.myLooper()) {
149            Log.e(TAG, "stop() called from non-UI thread");
150        }
151
152        // Clearing any old service connected messages.
153        mHandler.removeMessages(MSG_SERVICE_CONNECTED);
154
155        boolean mWasRunning = mIsRunning;
156
157        stopUi();
158
159        if (mBoundToService) {
160            if (mService != null) {
161                try {
162                    mService.unregisterCallback(mFaceUnlockCallback);
163                } catch (RemoteException e) {
164                    // Not much we can do
165                }
166            }
167            Log.d(TAG, "Unbinding from Face Unlock service");
168            mContext.unbindService(mConnection);
169            mBoundToService = false;
170        } else {
171            // This is usually not an error when this happens.  Sometimes we will tell it to
172            // unbind multiple times because it's called from both onWindowFocusChanged and
173            // onDetachedFromWindow.
174            if (DEBUG) Log.d(TAG, "Attempt to unbind from Face Unlock when not bound");
175        }
176        mIsRunning = false;
177        return mWasRunning;
178    }
179
180    /**
181     * Frees up resources used by Face Unlock and stops it if it is still running.
182     */
183    public void cleanUp() {
184        if (DEBUG) Log.d(TAG, "cleanUp()");
185        if (mService != null) {
186            try {
187                mService.unregisterCallback(mFaceUnlockCallback);
188            } catch (RemoteException e) {
189                // Not much we can do
190            }
191            stopUi();
192            mService = null;
193        }
194    }
195
196    /**
197     * Returns the Device Policy Manager quality for Face Unlock, which is BIOMETRIC_WEAK.
198     */
199    public int getQuality() {
200        return DevicePolicyManager.PASSWORD_QUALITY_BIOMETRIC_WEAK;
201    }
202
203    /**
204     * Handles messages such that everything happens on the UI thread in a deterministic order.
205     * Calls from the Face Unlock service come from binder threads.  Calls from lockscreen typically
206     * come from the UI thread.  This makes sure there are no race conditions between those calls.
207     */
208    public boolean handleMessage(Message msg) {
209        switch (msg.what) {
210            case MSG_SERVICE_CONNECTED:
211                handleServiceConnected();
212                break;
213            case MSG_SERVICE_DISCONNECTED:
214                handleServiceDisconnected();
215                break;
216            case MSG_UNLOCK:
217                handleUnlock();
218                break;
219            case MSG_CANCEL:
220                handleCancel();
221                break;
222            case MSG_REPORT_FAILED_ATTEMPT:
223                handleReportFailedAttempt();
224                break;
225            case MSG_POKE_WAKELOCK:
226                handlePokeWakelock(msg.arg1);
227                break;
228            default:
229                Log.e(TAG, "Unhandled message");
230                return false;
231        }
232        return true;
233    }
234
235    /**
236     * Tells the service to start its UI via an AIDL interface.  Called when the
237     * onServiceConnected() callback is received.
238     */
239    void handleServiceConnected() {
240        Log.d(TAG, "handleServiceConnected()");
241
242        // It is possible that an unbind has occurred in the time between the bind and when this
243        // function is reached.  If an unbind has already occurred, proceeding on to call startUi()
244        // can result in a fatal error.  Note that the onServiceConnected() callback is
245        // asynchronous, so this possibility would still exist if we executed this directly in
246        // onServiceConnected() rather than using a handler.
247        if (!mBoundToService) {
248            Log.d(TAG, "Dropping startUi() in handleServiceConnected() because no longer bound");
249            return;
250        }
251
252        try {
253            mService.registerCallback(mFaceUnlockCallback);
254        } catch (RemoteException e) {
255            Log.e(TAG, "Caught exception connecting to Face Unlock: " + e.toString());
256            mService = null;
257            mBoundToService = false;
258            mIsRunning = false;
259            return;
260        }
261
262        if (mFaceUnlockView != null) {
263            IBinder windowToken = mFaceUnlockView.getWindowToken();
264            if (windowToken != null) {
265                // When switching between portrait and landscape view while Face Unlock is running,
266                // the screen will eventually go dark unless we poke the wakelock when Face Unlock
267                // is restarted.
268                mKeyguardScreenCallback.userActivity(0);
269
270                int[] position;
271                position = new int[2];
272                mFaceUnlockView.getLocationInWindow(position);
273                startUi(windowToken, position[0], position[1], mFaceUnlockView.getWidth(),
274                        mFaceUnlockView.getHeight());
275            } else {
276                Log.e(TAG, "windowToken is null in handleServiceConnected()");
277            }
278        }
279    }
280
281    /**
282     * Called when the onServiceDisconnected() callback is received.  This should not happen during
283     * normal operation.  It indicates an error has occurred.
284     */
285    void handleServiceDisconnected() {
286        Log.e(TAG, "handleServiceDisconnected()");
287        // TODO: this lock may no longer be needed now that everything is being called from a
288        // handler
289        synchronized (mServiceRunningLock) {
290            mService = null;
291            mServiceRunning = false;
292        }
293        mBoundToService = false;
294        mIsRunning = false;
295    }
296
297    /**
298     * Stops the Face Unlock service and tells the device to grant access to the user.
299     */
300    void handleUnlock() {
301        if (DEBUG) Log.d(TAG, "handleUnlock()");
302        stop();
303        mKeyguardScreenCallback.reportSuccessfulUnlockAttempt();
304        mKeyguardScreenCallback.dismiss(true);
305    }
306
307    /**
308     * Stops the Face Unlock service and goes to the backup lock.
309     */
310    void handleCancel() {
311        if (DEBUG) Log.d(TAG, "handleCancel()");
312        // We are going to the backup method, so we don't want to see Face Unlock again until the
313        // next time the user visits keyguard.
314        KeyguardUpdateMonitor.getInstance(mContext).setAlternateUnlockEnabled(false);
315
316        mKeyguardScreenCallback.showBackupSecurity();
317        stop();
318        mKeyguardScreenCallback.userActivity(BACKUP_LOCK_TIMEOUT);
319    }
320
321    /**
322     * Increments the number of failed Face Unlock attempts.
323     */
324    void handleReportFailedAttempt() {
325        if (DEBUG) Log.d(TAG, "handleReportFailedAttempt()");
326        // We are going to the backup method, so we don't want to see Face Unlock again until the
327        // next time the user visits keyguard.
328        KeyguardUpdateMonitor.getInstance(mContext).setAlternateUnlockEnabled(false);
329
330        mKeyguardScreenCallback.reportFailedUnlockAttempt();
331    }
332
333    /**
334     * If the screen is on, pokes the wakelock to keep the screen alive and active for a specific
335     * amount of time.
336     */
337    void handlePokeWakelock(int millis) {
338      PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
339      if (powerManager.isScreenOn()) {
340        mKeyguardScreenCallback.userActivity(millis);
341      }
342    }
343
344    /**
345     * Implements service connection methods.
346     */
347    private ServiceConnection mConnection = new ServiceConnection() {
348        /**
349         * Called when the Face Unlock service connects after calling bind().
350         */
351        public void onServiceConnected(ComponentName className, IBinder iservice) {
352            Log.d(TAG, "Connected to Face Unlock service");
353            mService = IFaceLockInterface.Stub.asInterface(iservice);
354            mHandler.sendEmptyMessage(MSG_SERVICE_CONNECTED);
355        }
356
357        /**
358         * Called if the Face Unlock service unexpectedly disconnects.  This indicates an error.
359         */
360        public void onServiceDisconnected(ComponentName className) {
361            Log.e(TAG, "Unexpected disconnect from Face Unlock service");
362            mHandler.sendEmptyMessage(MSG_SERVICE_DISCONNECTED);
363        }
364    };
365
366    /**
367     * Tells the Face Unlock service to start displaying its UI and start processing.
368     */
369    private void startUi(IBinder windowToken, int x, int y, int w, int h) {
370        if (DEBUG) Log.d(TAG, "startUi()");
371        synchronized (mServiceRunningLock) {
372            if (!mServiceRunning) {
373                Log.d(TAG, "Starting Face Unlock");
374                try {
375                    mService.startUi(windowToken, x, y, w, h,
376                            mLockPatternUtils.isBiometricWeakLivelinessEnabled());
377                } catch (RemoteException e) {
378                    Log.e(TAG, "Caught exception starting Face Unlock: " + e.toString());
379                    return;
380                }
381                mServiceRunning = true;
382            } else {
383                Log.w(TAG, "startUi() attempted while running");
384            }
385        }
386    }
387
388    /**
389     * Tells the Face Unlock service to stop displaying its UI and stop processing.
390     */
391    private void stopUi() {
392        if (DEBUG) Log.d(TAG, "stopUi()");
393        // Note that attempting to stop Face Unlock when it's not running is not an issue.
394        // Face Unlock can return, which stops it and then we try to stop it when the
395        // screen is turned off.  That's why we check.
396        synchronized (mServiceRunningLock) {
397            if (mServiceRunning) {
398                Log.d(TAG, "Stopping Face Unlock");
399                try {
400                    mService.stopUi();
401                } catch (RemoteException e) {
402                    Log.e(TAG, "Caught exception stopping Face Unlock: " + e.toString());
403                }
404                mServiceRunning = false;
405            } else {
406                // This is usually not an error when this happens.  Sometimes we will tell it to
407                // stop multiple times because it's called from both onWindowFocusChanged and
408                // onDetachedFromWindow.
409                if (DEBUG) Log.d(TAG, "stopUi() attempted while not running");
410            }
411        }
412    }
413
414    /**
415     * Implements the AIDL biometric unlock service callback interface.
416     */
417    private final IFaceLockCallback mFaceUnlockCallback = new IFaceLockCallback.Stub() {
418        /**
419         * Called when Face Unlock wants to grant access to the user.
420         */
421        public void unlock() {
422            if (DEBUG) Log.d(TAG, "unlock()");
423            mHandler.sendEmptyMessage(MSG_UNLOCK);
424        }
425
426        /**
427         * Called when Face Unlock wants to go to the backup.
428         */
429        public void cancel() {
430            if (DEBUG) Log.d(TAG, "cancel()");
431            mHandler.sendEmptyMessage(MSG_CANCEL);
432        }
433
434        /**
435         * Called when Face Unlock wants to increment the number of failed attempts.
436         */
437        public void reportFailedAttempt() {
438            if (DEBUG) Log.d(TAG, "reportFailedAttempt()");
439            mHandler.sendEmptyMessage(MSG_REPORT_FAILED_ATTEMPT);
440        }
441
442        /**
443         * Called when Face Unlock wants to keep the screen alive and active for a specific amount
444         * of time.
445         */
446        public void pokeWakelock(int millis) {
447            if (DEBUG) Log.d(TAG, "pokeWakelock() for " + millis + "ms");
448            Message message = mHandler.obtainMessage(MSG_POKE_WAKELOCK, millis, -1);
449            mHandler.sendMessage(message);
450        }
451
452    };
453}
454