1/*
2 * Copyright (C) 2014 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 android.bluetooth.client.pbap;
18
19import android.os.Handler;
20import android.util.Log;
21
22import javax.obex.Authenticator;
23import javax.obex.PasswordAuthentication;
24
25class BluetoothPbapObexAuthenticator implements Authenticator {
26
27    private final static String TAG = "BluetoothPbapObexAuthenticator";
28
29    private String mSessionKey;
30
31    private boolean mReplied;
32
33    private final Handler mCallback;
34
35    public BluetoothPbapObexAuthenticator(Handler callback) {
36        mCallback = callback;
37    }
38
39    public synchronized void setReply(String key) {
40        Log.d(TAG, "setReply key=" + key);
41
42        mSessionKey = key;
43        mReplied = true;
44
45        notify();
46    }
47
48    @Override
49    public PasswordAuthentication onAuthenticationChallenge(String description,
50            boolean isUserIdRequired, boolean isFullAccess) {
51        PasswordAuthentication pa = null;
52
53        mReplied = false;
54
55        Log.d(TAG, "onAuthenticationChallenge: sending request");
56        mCallback.obtainMessage(BluetoothPbapObexSession.OBEX_SESSION_AUTHENTICATION_REQUEST)
57                .sendToTarget();
58
59        synchronized (this) {
60            while (!mReplied) {
61                try {
62                    Log.v(TAG, "onAuthenticationChallenge: waiting for response");
63                    this.wait();
64                } catch (InterruptedException e) {
65                    Log.e(TAG, "Interrupted while waiting for challenge response");
66                }
67            }
68        }
69
70        if (mSessionKey != null && mSessionKey.length() != 0) {
71            Log.v(TAG, "onAuthenticationChallenge: mSessionKey=" + mSessionKey);
72            pa = new PasswordAuthentication(null, mSessionKey.getBytes());
73        } else {
74            Log.v(TAG, "onAuthenticationChallenge: mSessionKey is empty, timeout/cancel occured");
75        }
76
77        return pa;
78    }
79
80    @Override
81    public byte[] onAuthenticationResponse(byte[] userName) {
82        /* required only in case PCE challenges PSE which we don't do now */
83        return null;
84    }
85
86}
87