1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.nfc;
import com.android.nfc3.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.charset.Charsets;
import java.util.Arrays;
import java.util.UUID;
public class BluetoothDropbox extends BroadcastReceiver {
private static final String TAG = "btdropbox";
private static final boolean DBG = true;
public static final String MIME_TYPE = "vnd.android.com/oob.ndef";
private static final String SERVICE_NAME = "BtDropbox";
private static final String PREF = "BluetoothDropboxPrefs";
private static final String PREF_BLUETOOTH_ADDRESS = "bluetooth_address";
private static final UUID SERVICE_UUID = UUID.randomUUID();
private static final byte PROTOCOL_VERSION = 0x017;
private static final int ACCESS_WINDOW_MS = 45*1000;
private static final int BLUETOOTH_STARTUP_DELAY_MS = 7000;
private static final int BLUETOOTH_CHANNEL = 13;
private static final int NOTIFICATION_INBOUND_ME_PROFILE = 1;
private static final int NOTIFICATION_OUTBOUND_ME_PROFILE = 2;
final Context mContext;
final BluetoothAdapter mBluetoothAdapter;
final SharedPreferences mPrefs;
// these fields protected by BluetoothDropbox.this
String mLastAccessAddress;
long mLastAccessTime;
DropboxAcceptThread mAcceptThread;
int mBluetoothState;
int mBluetoothCount;
boolean mBluetoothTransient;
NotificationManager mNotificationManager;
String mBluetoothAddress;
public BluetoothDropbox(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Log.e(TAG, "Cannot start btdropbox, bluetooth not available");
throw new RuntimeException("Cannot start btdropbox, bluetooth not available");
}
mBluetoothCount = 0;
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
context.registerReceiver(this, filter);
mBluetoothState = mBluetoothAdapter.getState();
mPrefs = context.getSharedPreferences(PREF, Context.MODE_PRIVATE);
mBluetoothAddress = mPrefs.getString(PREF_BLUETOOTH_ADDRESS, null);
if (mBluetoothAddress == null && mBluetoothState == BluetoothAdapter.STATE_ON) {
mBluetoothAddress = mBluetoothAdapter.getAddress();
mPrefs.edit().putString(PREF_BLUETOOTH_ADDRESS, mBluetoothAddress).apply();
}
mNotificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
}
public void start() {
boolean needAddress = false;
synchronized (this) {
needAddress = mBluetoothAddress == null;
}
if (needAddress) {
// cycle Bluetooth to pick up mBluetoothAddress
requestBluetooth();
mHandler.sendMessageDelayed(mHandler.obtainMessage(), 1000);
}
}
public synchronized void startListening() {
if (DBG) Log.d(TAG, "Starting btdropbox service");
if (mAcceptThread != null) {
if (DBG) Log.d(TAG, "btdropbox already started");
return;
}
mAcceptThread = new DropboxAcceptThread(SERVICE_NAME, SERVICE_UUID);
mAcceptThread.start();
}
public void stop() { }
public synchronized void stopListening() {
if (mAcceptThread != null) {
if (DBG) Log.d(TAG, "Stopping btdropbox service");
mAcceptThread.cancel();
mAcceptThread = null;
}
}
/**
* Grants exclusive access to this dropbox to a remote device, for
* ACCESS_WINDOW_MS milliseconds.
*/
public void grantAccess(NdefMessage sender) {
requestBluetooth();
mHandler.sendMessageDelayed(mHandler.obtainMessage(), ACCESS_WINDOW_MS);
if (sender == null || sender.getRecords().length == 0) {
return;
}
NdefRecord firstRecord = sender.getRecords()[0];
if (firstRecord.getTnf() != NdefRecord.TNF_MIME_MEDIA ||
!Arrays.equals(firstRecord.getType(), MIME_TYPE.getBytes())) {
return;
}
Uri senderUri = Uri.parse(new String(firstRecord.getPayload()));
if (DBG) Log.d(TAG, "Granting dropbox access to " + senderUri.getAuthority());
synchronized (this) {
mLastAccessAddress = senderUri.getAuthority();
mLastAccessTime = System.currentTimeMillis();
}
}
/**
* Returns an ndef message with the information required to connect
* to this dropbox.
*/
public synchronized NdefMessage getDropboxAddressNdef() {
// if (mAcceptThread == null || mAcceptThread.mServerSocket == null) return null;
if (mBluetoothAddress == null) {
Log.w(TAG, "No bluetooth address");
return null;
}
byte[] payload = ("btdb://" + mBluetoothAddress + "/" + SERVICE_UUID
+ "?channel=" + BLUETOOTH_CHANNEL).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, MIME_TYPE.getBytes(),
new byte[0], payload);
return new NdefMessage(new NdefRecord[] { record });
}
/** Enable Bluetooth, ref-counted, blocking */
void requestBluetooth() {
synchronized (this) {
if (mBluetoothCount == 0) {
if (mBluetoothState != BluetoothAdapter.STATE_ON) {
mBluetoothTransient = true;
mBluetoothAdapter.enable();
} else {
mBluetoothTransient = false;
}
}
mBluetoothCount++;
if (DBG) Log.d(TAG, "requestBluetooth(), count=" + mBluetoothCount);
}
// TODO: don't poll
for (int i=0; i<60; i++) {
synchronized (this) {
if (mBluetoothState == BluetoothAdapter.STATE_ON) {
break;
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
}
}
/** Disable Bluetooth, ref-counted, NOT blocking*/
void releaseBluetooth() {
synchronized (this) {
if (mBluetoothCount <= 0) {
Log.w(TAG, "Unbalanced releaseBluetooth()");
return;
}
mBluetoothCount--;
if (DBG) Log.d(TAG, "releaseBluetooth(), count=" + mBluetoothCount);
if (mBluetoothCount == 0 && mBluetoothTransient) {
mBluetoothAdapter.disable();
}
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(intent.getAction())) {
synchronized (this) {
mBluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.STATE_OFF);
switch (mBluetoothState) {
case BluetoothAdapter.STATE_OFF:
case BluetoothAdapter.STATE_TURNING_OFF:
stopListening();
break;
case BluetoothAdapter.STATE_ON:
if (mBluetoothAddress == null) {
mBluetoothAddress = mBluetoothAdapter.getAddress();
mPrefs.edit().putString(PREF_BLUETOOTH_ADDRESS, mBluetoothAddress).apply();
if (DBG) Log.d(TAG, "Got BT address " + mBluetoothAddress);
}
startListening();
break;
default:
}
}
}
}
public void sendContent(NdefMessage target, NdefMessage content) throws IOException {
new DropboxSendThread(target, content).start();
}
public void handleOutboundMeProfile(NdefMessage target, NdefMessage profile) throws IOException {
Intent intent = new Intent();
intent.setClass(mContext, BluetoothMeProfileReceiver.class);
intent.putExtra(BluetoothMeProfileReceiver.EXTRA_TARGET, target);
intent.putExtra(BluetoothMeProfileReceiver.EXTRA_PROFILE, profile);
PendingIntent pi = PendingIntent.getBroadcast(mContext, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(mContext)
.setContentTitle(mContext.getString(R.string.outbound_me_profile_title))
.setContentText(mContext.getString(R.string.outbound_me_profile_text))
.setContentIntent(pi)
.setSmallIcon(R.drawable.ic_tab_selected_contacts)
.setAutoCancel(true)
.getNotification();
mNotificationManager.notify(NOTIFICATION_OUTBOUND_ME_PROFILE, notification);
}
private class DropboxReceiveThread extends Thread {
private final BluetoothSocket mmSocket;
public DropboxReceiveThread(BluetoothSocket socket) {
mmSocket = socket;
}
@Override
public void run() {
setName("DropboxReceiveThread");
try {
if (DBG) Log.d(TAG, "Receiver reading content");
InputStream in = mmSocket.getInputStream();
byte version = (byte)in.read();
if (version != PROTOCOL_VERSION) {
throw new IOException("Invalid protocol version " + version);
}
byte[] lengthBytes = new byte[4];
int r = in.read(lengthBytes);
if (r < lengthBytes.length) {
throw new IOException("Error reading data length");
}
ByteBuffer buffer = ByteBuffer.wrap(lengthBytes);
int length = buffer.getInt();
byte[] ndefBytes = new byte[length];
int total = 0;
while (total < length) {
int read = in.read(ndefBytes, total, length - total);
if (read == -1) {
throw new IOException("End of stream while reading data");
}
total += read;
}
NdefMessage ndef;
try {
ndef = new NdefMessage(ndefBytes);
} catch (FormatException e) {
throw new IOException("Error reading ndef", e);
}
if (DBG) Log.d(TAG, "Received ndef " + new String(ndef.getRecords()[0].getType()));
handleInboundMeProfile(ndef);
} catch (IOException e) {
Log.e(TAG, "Failed to receive data", e);
}
}
}
boolean handleInboundMeProfile(NdefMessage msg) {
NdefRecord records[] = msg.getRecords();
if (records == null || records.length < 1) {
Log.d(TAG, "invalid me profile");
return false;
}
NdefRecord vcard = records[0];
if (vcard.getTnf() != NdefRecord.TNF_MIME_MEDIA) {
Log.d(TAG, "invalid TNF for me profile: " + vcard.getTnf());
return false;
}
String type = new String(vcard.getType(), Charsets.US_ASCII);
if (!"text/x-vCard".equalsIgnoreCase(type)) {
Log.d(TAG, "invalid me profile MIME type: " + type);
return false;
}
Intent intent = new Intent(NfcAdapter.ACTION_NDEF_DISCOVERED);
intent.setType("text/x-vCard");
intent.putExtra(NfcAdapter.EXTRA_NDEF_MESSAGES, new NdefMessage[] { msg });
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pi = PendingIntent.getActivity(mContext, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(mContext)
.setContentTitle(mContext.getString(R.string.inbound_me_profile_title))
.setContentText(mContext.getString(R.string.inbound_me_profile_text))
.setContentIntent(pi)
.setSmallIcon(R.drawable.ic_tab_selected_contacts)
.setAutoCancel(true)
.getNotification();
mNotificationManager.notify(NOTIFICATION_INBOUND_ME_PROFILE, notification);
return true;
}
private class DropboxSendThread extends Thread {
private final NdefMessage mmTarget;
private final NdefMessage mmOutboundNdef;
public DropboxSendThread(NdefMessage target, NdefMessage outboundNdef) {
mmTarget = target;
mmOutboundNdef = outboundNdef;
}
@Override
public void run() {
setName("DropboxSendThread");
long t1 = System.currentTimeMillis();
BluetoothDevice device;
BluetoothSocket socket;
Uri dbUri = Uri.parse(new String(mmTarget.getRecords()[0].getPayload()));
Log.d(TAG, "Opening outbound dropbox connection for " + dbUri);
requestBluetooth();
synchronized (BluetoothDropbox.this) {
device = mBluetoothAdapter.getRemoteDevice(dbUri.getAuthority());
}
String channel = dbUri.getQueryParameter("channel");
int chan = Integer.parseInt(channel);
long delta = BLUETOOTH_STARTUP_DELAY_MS - (System.currentTimeMillis() - t1);
if (delta > 0) {
try {
Log.d(TAG, "Waiting " + delta + " ms");
Thread.sleep(BLUETOOTH_STARTUP_DELAY_MS);
} catch (InterruptedException e) { }
}
try {
socket = device.createInsecureRfcommSocket(chan);
} catch (IOException e) {
Log.w(TAG, "Could not create outbound socket to " + device + " on channel " + chan);
releaseBluetooth();
return;
}
if (DBG) Log.d(TAG, "Sending content to dropbox");
OutputStream out;
try {
socket.connect();
if (DBG) Log.d(TAG, "Dropbox client connected");
out = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "failed to connect to bluetooth socket", e);
try {
socket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() socket during connection failure", e2);
}
releaseBluetooth();
return;
}
try {
if (DBG) Log.d(TAG, "Sending ndef content " + mmOutboundNdef);
byte[] outboundBytes = mmOutboundNdef.toByteArray();
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(outboundBytes.length);
out.write(PROTOCOL_VERSION);
out.write(buffer.array());
out.write(outboundBytes);
out.close();
if (DBG) Log.d(TAG, "Done sending, closing socket.");
} catch (IOException e) {
Log.e(TAG, "Failed to send data", e);
}
releaseBluetooth();
}
}
private class DropboxAcceptThread extends Thread {
final BluetoothServerSocket mServerSocket;
boolean mRunning;
DropboxAcceptThread(String serviceName, UUID serviceUuid) {
BluetoothServerSocket tmp = null;
try {
tmp = mBluetoothAdapter.listenUsingInsecureRfcommOn(BLUETOOTH_CHANNEL);
} catch (IOException e) {
Log.e(TAG, "listen() failed", e);
}
mServerSocket = tmp;
}
@Override
public void run() {
setName("DropboxAcceptThread");
BluetoothSocket socket = null;
mRunning = true;
while (mRunning) {
try {
if (DBG) Log.d(TAG, "Dropbox server waiting...");
socket = mServerSocket.accept();
if (DBG) Log.d(TAG, "Dropbox server connected!");
} catch (IOException e) {
continue;
}
if (socket == null) {
continue;
}
synchronized (this) {
try {
String senderAddress = socket.getRemoteDevice().getAddress();
if (mLastAccessAddress == null ||
!mLastAccessAddress.equals(senderAddress)) {
if (DBG) Log.w(TAG, "Invalid access to dropbox.");
return;
}
if (mLastAccessTime + ACCESS_WINDOW_MS < System.currentTimeMillis()) {
if (DBG) Log.w(TAG, "Client waited to long to send to dropbox.");
return;
}
} finally {
mLastAccessAddress = null;
}
}
new DropboxReceiveThread(socket).start();
}
}
public void cancel() {
try {
mRunning = false;
mServerSocket.close();
} catch (IOException e) { }
}
}
private final Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
releaseBluetooth();
}
};
}
|