My favorites | Sign in
Project Home Downloads Wiki Issues Source
Checkout   Browse   Changes    
 
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
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
/**
* BlueCove - Java library for Bluetooth
* Copyright 2004 Intel Corporation
* Copyright (C) 2006-2008 Vlad Skarzhevskyy
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*
* @version $Id$
*/

#include "common.h"
#include "commonObjects.h"

#ifndef CPP_FILE
#define CPP_FILE "intelbth.cpp"
#endif

#include "com_intel_bluetooth_BluetoothStackMicrosoft.h"

#ifdef _WIN32_WCE
#include <winsock2.h>
#include <bthapi.h>
#include <bt_api.h>
#include <bthutil.h>
#include <bt_sdp.h>
#else // _WIN32_WCE
#include <winsock2.h>
#include <ws2bth.h>
#include <bluetoothapis.h>
#endif // #else // _WIN32_WCE


static BOOL started;
static int dllWSAStartupError = 0;
static HANDLE hDeviceLookup;
static CRITICAL_SECTION csLookup;

static BOOL restoreBtMode = false;
#ifdef _WIN32_WCE
static DWORD initialBtMode;
static BTH_LOCAL_VERSION localBluetoothDeviceInfo;
#else
static BOOL initialBtIsDiscoverable;
#endif

BOOL microsoftBluetoothStackPresent;

void dllCleanup();

void throwIOExceptionWSAGetLastError(JNIEnv *env, const char *msg);

BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
switch(ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
{
WSADATA data;
if (WSAStartup(MAKEWORD(2, 2), &data) != 0) {
dllWSAStartupError = WSAGetLastError();
started = FALSE;
} else {
started = TRUE;
}
hDeviceLookup = NULL;
//debug(("InitializeCriticalSection"));
InitializeCriticalSection(&csLookup);
return started;
}
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
dllCleanup();
break;
}
return TRUE;
}

JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
return JNI_VERSION_1_2;
}

JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved) {
dllCleanup();
}


void dllCleanup() {
if (started) {
if (restoreBtMode) {
#ifdef _BTWINSOCKLIB
#ifdef _WIN32_WCE
BthSetMode(initialBtMode);
#else
BluetoothEnableDiscovery(NULL, initialBtIsDiscoverable);
#endif // _WIN32_WCE
#endif // _BTWINSOCKLIB
restoreBtMode = false;
}
WSACleanup();
}
DeleteCriticalSection(&csLookup);
}

void throwIOExceptionWSAGetLastError(JNIEnv *env, const char *msg) {
throwIOExceptionWinErrorMessage(env, msg, WSAGetLastError());
}

JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_isNativeCodeLoaded
(JNIEnv *env, jobject peer) {
return JNI_TRUE;
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getLibraryVersion
(JNIEnv *, jobject) {
return blueCoveVersion();
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_detectBluetoothStack
(JNIEnv *env, jobject) {
return detectBluetoothStack(env);
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_enableNativeDebug
(JNIEnv *env, jobject, jclass loggerClass, jboolean on) {
enableNativeDebug(env, loggerClass, on);
}

//See same function for VC6 isMicrosoftBluetoothStackPresentVC6 in WIDCOMMStack.cpp
BOOL isMicrosoftBluetoothStackPresent(JNIEnv *env) {
SOCKET s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);
if (s == INVALID_SOCKET) {
int last_error = WSAGetLastError();
debug(("socket error [%d] %S", last_error, getWinErrorMessage(last_error)));
return FALSE;
}
SOCKADDR_BTH btAddr;
memset(&btAddr, 0, sizeof(SOCKADDR_BTH));
btAddr.addressFamily = AF_BTH;
#ifdef _WIN32_WCE
btAddr.port = 0;
#else
btAddr.port = BT_PORT_ANY;
#endif
if (bind(s, (SOCKADDR *)&btAddr, sizeof(SOCKADDR_BTH))) {
int last_error = WSAGetLastError();
debug(("bind error [%d] %S", last_error, getWinErrorMessage(last_error)));
closesocket(s);
return FALSE;
}

int size = sizeof(SOCKADDR_BTH);
if (getsockname(s, (sockaddr*)&btAddr, &size)) {
int last_error = WSAGetLastError();
debug(("getsockname error [%d] %S", last_error, getWinErrorMessage(last_error)));
closesocket(s);
return FALSE;
}
closesocket(s);
//return TRUE;
microsoftBluetoothStackPresent = (btAddr.btAddr != 0);
return microsoftBluetoothStackPresent;
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_initializationStatus(JNIEnv *env, jclass peerClass) {
if (!microsoftBluetoothStackPresent) {
if (!isMicrosoftBluetoothStackPresent(env)) {
throwBluetoothStateException(env, "BluetoothStack not detected");
}
}
#ifdef _BTWINSOCKLIB
if (started) {
#ifdef _WIN32_WCE
// Use the BthGetMode function to retrieve the current mode of operation of the Bluetooth radio.
int rc = BthGetMode(&initialBtMode);
if (rc == ERROR_SUCCESS) {
if (initialBtMode == BTH_POWER_OFF) {
rc = BthSetMode(BTH_CONNECTABLE);
if (rc == ERROR_SUCCESS) {
restoreBtMode = true;
return 1;
} else {
throwIOExceptionWinErrorMessage(env, "set Bluetooth mode error ", rc);
}
} else {
return 1;
}
} else {
throwIOExceptionWinErrorMessage(env, "Bluetooth radio error ", rc);
}
started = false;
dllWSAStartupError = rc;
return 0;
#else
if (BluetoothIsDiscoverable(NULL)) {
initialBtIsDiscoverable = true;
}
return 1;
#endif
}
throwIOExceptionWinErrorMessage(env, "Initialization error ", dllWSAStartupError);
return 0;
#else
return 0;
#endif // _BTWINSOCKLIB
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_uninitialize
(JNIEnv *, jobject) {

}

JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_isWindowsCE
(JNIEnv *, jobject) {
#ifdef _WIN32_WCE
return JNI_TRUE;
#else
return JNI_FALSE;
#endif // _WIN32_WCE
}

#ifdef _BTWINSOCKLIB

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_runDeviceInquiryImpl
(JNIEnv *env, jobject peer, jobject inquiryRunnable, jobject inquiryThread, jint accessCode, jint duration, jobject listener) {

debug(("runDeviceInquiry, duration=%i", duration));

DeviceInquiryCallback callback;
if (!callback.builDeviceInquiryCallbacks(env, inquiryRunnable, inquiryThread)) {
return INQUIRY_ERROR;
}

// build device query

#ifndef _WIN32_WCE
BTH_QUERY_DEVICE query;
query.LAP = accessCode;
#else
BTHNS_INQUIRYBLOB query;
query.LAP = accessCode;
query.num_responses = 10;
#endif
query.length = (unsigned char)duration;

// build BLOB pointing to device query

BLOB blob;

blob.cbSize = sizeof(query);
blob.pBlobData = (BYTE *)&query;

// build query

WSAQUERYSET queryset;

memset(&queryset, 0, sizeof(WSAQUERYSET));
queryset.dwSize = sizeof(WSAQUERYSET);
queryset.dwNameSpace = NS_BTH;

// TODO Test this.
//queryset.lpBlob = &blob;

#ifndef _WIN32_WCE
queryset.lpBlob = &blob;
#endif

// begin query

EnterCriticalSection(&csLookup);

if (hDeviceLookup != NULL) {
LeaveCriticalSection(&csLookup);
throwBluetoothStateException(env, cINQUIRY_RUNNING);
return INQUIRY_ERROR;
}

// WSALookupServiceBegin Do not return for 10 seconds.
if (!callback.callDeviceInquiryStartedCallback(env)) {
LeaveCriticalSection(&csLookup);
return INQUIRY_ERROR;
}

#ifdef _WIN32_WCE
if (WSALookupServiceBegin(&queryset, LUP_CONTAINERS, &hDeviceLookup)) {
#else
if (WSALookupServiceBegin(&queryset, LUP_FLUSHCACHE|LUP_CONTAINERS, &hDeviceLookup)) {
#endif
int last_error = WSAGetLastError();

LeaveCriticalSection(&csLookup);
//throwBluetoothStateExceptionWinErrorMessage(env, "Can't start Lookup", last_error);
debug(("WSALookupServiceBegin error [%d] %S", last_error, getWinErrorMessage(last_error)));
return INQUIRY_ERROR;
}

LeaveCriticalSection(&csLookup);


// fetch results
jint result = -1;

int bufSize = 0x2000;
void* buf = malloc(bufSize);
if (buf == NULL) {
result = INQUIRY_ERROR;
}

while (result == -1) {
memset(buf, 0, bufSize);

LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
pwsaResults->dwSize = sizeof(WSAQUERYSET);
pwsaResults->dwNameSpace = NS_BTH;

DWORD size = bufSize;

EnterCriticalSection(&csLookup);

if (hDeviceLookup == NULL) {
LeaveCriticalSection(&csLookup);
result = INQUIRY_TERMINATED;
debug(("doInquiry, INQUIRY_TERMINATED"));
break;
}
debug(("doInquiry, WSALookupServiceNext"));
if (WSALookupServiceNext(hDeviceLookup, LUP_RETURN_NAME|LUP_RETURN_ADDR|LUP_RETURN_BLOB, &size, pwsaResults)) {
int last_error = WSAGetLastError();
switch(last_error) {
case WSAENOMORE:
case WSA_E_NO_MORE:
result = INQUIRY_COMPLETED;
break;
default:
debug(("Device lookup error [%d] %S", last_error, getWinErrorMessage(last_error)));
result = INQUIRY_ERROR;
}
WSALookupServiceEnd(hDeviceLookup);
hDeviceLookup = NULL;
LeaveCriticalSection(&csLookup);
debug(("doInquiry, exits"));
break;
}

LeaveCriticalSection(&csLookup);

debug(("doInquiry, has next Service"));

#ifdef _WIN32_WCE
BthInquiryResult *p_inqRes = (BthInquiryResult *)pwsaResults->lpBlob->pBlobData;

#else
BTH_DEVICE_INFO *p_inqRes = (BTH_DEVICE_INFO *)pwsaResults->lpBlob->pBlobData;
#endif

// get device name
WCHAR name[256];
BOOL bHaveName = pwsaResults->lpszServiceInstanceName && *(pwsaResults->lpszServiceInstanceName);
StringCchPrintf(name, sizeof(name),L"%s",bHaveName ? pwsaResults->lpszServiceInstanceName : L"");
debug(("ServiceInstanceName [%S]", name));
jstring deviceName = env->NewString((jchar*)name, (jsize)wcslen(name));

jboolean paired = JNI_FALSE;

#ifdef _WIN32_WCE
int deviceClass = p_inqRes->cod;
bt_addr deviceAddr;
#else
int deviceClass = p_inqRes->classOfDevice;
if (p_inqRes->flags & BDIF_PAIRED) {
paired = JNI_TRUE;
}
BTH_ADDR deviceAddr;
#endif
deviceAddr = ((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr;

// notify listener
debug(("doInquiry, notify listener"));
if (!callback.callDeviceDiscovered(env, listener, deviceAddr, deviceClass, deviceName, paired)) {
debug(("doInquiry, ExceptionOccurred"));
result = INQUIRY_ERROR;
break;
}
debug(("doInquiry, listener returns"));
}

if (buf != NULL) {
free(buf);
}

if (hDeviceLookup != NULL) {
WSALookupServiceEnd(hDeviceLookup);
hDeviceLookup = NULL;
}

return result;
}

JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_cancelInquiry(JNIEnv *env, jobject peer) {
debug(("cancelInquiry"));
EnterCriticalSection(&csLookup);

if (hDeviceLookup == NULL) {
LeaveCriticalSection(&csLookup);
return JNI_FALSE;
}

debug(("cancelInquiry WSALookupServiceEnd"));

WSALookupServiceEnd(hDeviceLookup);

hDeviceLookup = NULL;

LeaveCriticalSection(&csLookup);

return JNI_TRUE;
}


JNIEXPORT jintArray JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_runSearchServicesImpl
(JNIEnv *env, jobject peer, jobjectArray uuidSet, jlong address) {
debug(("runSearchServices"));

// check if we can handle the number of UUIDs supplied
if ((uuidSet != NULL) && (env->GetArrayLength(uuidSet) > MAX_UUIDS_IN_QUERY)) {
return NULL;
}

#ifndef _WIN32_WCE
// generate a Bluetooth address string (WSAAddressToString doesn't work on WinCE)

WCHAR addressString[20];

swprintf_s(addressString, _T("(%02x:%02x:%02x:%02x:%02x:%02x)"), (int)(address>>40&0xff), (int)(address>>32&0xff), (int)(address>>24&0xff), (int)(address>>16&0xff), (int)(address>>8&0xff), (int)(address&0xff));

// build service query

BTH_QUERY_SERVICE queryservice;

#else
BTHNS_RESTRICTIONBLOB queryservice;
#endif

memset(&queryservice, 0, sizeof(queryservice));

queryservice.type = SDP_SERVICE_SEARCH_REQUEST;

GUID guid;

jclass clsUUID = NULL;

for(int i = 0; (uuidSet != NULL) && (i < env->GetArrayLength(uuidSet)); i++) {
if (clsUUID == NULL) {
clsUUID = env->FindClass("javax/bluetooth/UUID");
if (clsUUID == NULL) {
env->FatalError("Can't create UUID Class");
return NULL;
}
}

jbyteArray uuidValue = (jbyteArray)env->GetObjectField(env->GetObjectArrayElement(uuidSet, i), env->GetFieldID(clsUUID, "uuidValue", "[B"));

// pin array

jbyte *bytes = env->GetByteArrayElements(uuidValue, 0);

// build UUID

convertUUIDBytesToGUID(bytes, &guid);

//UUID is full 128 bits

queryservice.uuids[i].uuidType = SDP_ST_UUID128;

memcpy(&queryservice.uuids[i].u.uuid128, &guid, sizeof(guid));

// unpin array

env->ReleaseByteArrayElements(uuidValue, bytes, 0);
}
if (clsUUID != NULL) {
env->DeleteLocalRef(clsUUID);
}

// build BLOB pointing to service query

BLOB blob;

blob.cbSize = sizeof(queryservice);
blob.pBlobData = (BYTE *)&queryservice;

// build query

WSAQUERYSET queryset;

memset(&queryset, 0, sizeof(WSAQUERYSET));

queryset.dwSize = sizeof(WSAQUERYSET);
queryset.dwNameSpace = NS_BTH;
queryset.lpBlob = &blob;

#ifdef _WIN32_WCE

// Build address

SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BT;
sa.btAddr = address;
CSADDR_INFO csai;
memset (&csai, 0, sizeof(csai));
csai.RemoteAddr.lpSockaddr = (sockaddr *)&sa;
csai.RemoteAddr.iSockaddrLength = sizeof(sa);
queryset.lpcsaBuffer = &csai;
#else
queryset.lpszContext = addressString;
#endif

HANDLE hLookupSearchServices;

// begin query

#ifdef _WIN32_WCE
if (WSALookupServiceBegin(&queryset, 0, &hLookupSearchServices)) {
int last_error = WSAGetLastError();
debug(("WSALookupServiceBegin error [%i] %S", last_error, getWinErrorMessage(last_error)));
return NULL;
}
#else
if (WSALookupServiceBegin(&queryset, LUP_FLUSHCACHE, &hLookupSearchServices)) {
int last_error = WSAGetLastError();
debug(("WSALookupServiceBegin error [%i] %S", last_error, getWinErrorMessage(last_error)));
// [10108] No such service is known. The service cannot be found in the specified name space. -> SERVICE_SEARCH_DEVICE_NOT_REACHABLE
if (10108 == last_error) {
throwException(env, "com/intel/bluetooth/SearchServicesDeviceNotReachableException", "");
}
return NULL;
}
#endif

// fetch results
jintArray result = NULL;

int bufSize = 0x2000;
void* buf = malloc(bufSize);
if (buf == NULL) {
WSALookupServiceEnd(hLookupSearchServices);
return NULL;
}
memset(buf, 0, bufSize);

LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
pwsaResults->dwSize = sizeof(WSAQUERYSET);
pwsaResults->dwNameSpace = NS_BTH;
pwsaResults->lpBlob = NULL;

DWORD size = bufSize;

#ifdef _WIN32_WCE
if (WSALookupServiceNext(hLookupSearchServices, 0, &size, pwsaResults)) {
#else
if (WSALookupServiceNext(hLookupSearchServices, LUP_RETURN_BLOB, &size, pwsaResults)) {
#endif
int last_error = WSAGetLastError();
switch(last_error) {
case WSANO_DATA:
result = env->NewIntArray(0);
break;
default:
debug(("WSALookupServiceNext error [%i] %S", last_error, getWinErrorMessage(last_error)));
result = NULL;
}
} else {
// construct int array to hold handles
result = env->NewIntArray(pwsaResults->lpBlob->cbSize/sizeof(ULONG));
jint *ints = env->GetIntArrayElements(result, 0);
memcpy(ints, pwsaResults->lpBlob->pBlobData, pwsaResults->lpBlob->cbSize);
env->ReleaseIntArrayElements(result, ints, 0);
}
WSALookupServiceEnd(hLookupSearchServices);
free(buf);
return result;
}

JNIEXPORT jbyteArray JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getServiceAttributes(JNIEnv *env, jobject peer, jintArray attrIDs, jlong address, jint handle)
{
debug(("getServiceAttributes"));
#ifdef _WIN32_WCE
BTHNS_RESTRICTIONBLOB *queryservice = (BTHNS_RESTRICTIONBLOB *)malloc(sizeof(BTHNS_RESTRICTIONBLOB)+sizeof(SdpAttributeRange)*(1));
queryservice->type = SDP_SERVICE_ATTRIBUTE_REQUEST;

queryservice->serviceHandle = handle;
queryservice->numRange = 1;

// set attribute ranges
jint *ints = env->GetIntArrayElements(attrIDs, 0);

queryservice->pRange[0].minAttribute = (USHORT)ints[0];
queryservice->pRange[0].maxAttribute = (USHORT)ints[env->GetArrayLength(attrIDs)-1];

env->ReleaseIntArrayElements(attrIDs, ints, 0);
#else
// generate a Bluetooth address string (WSAAddressToString doesn't work on WinCE)

WCHAR addressString[20];

swprintf_s(addressString, _T("(%02x:%02x:%02x:%02x:%02x:%02x)"), (int)(address>>40&0xff), (int)(address>>32&0xff), (int)(address>>24&0xff), (int)(address>>16&0xff), (int)(address>>8&0xff), (int)(address&0xff));

// build attribute query

BTH_QUERY_SERVICE *queryservice = (BTH_QUERY_SERVICE *)malloc(sizeof(BTH_QUERY_SERVICE)+sizeof(SdpAttributeRange)*(env->GetArrayLength(attrIDs)-1));
memset(queryservice, 0, sizeof(BTH_QUERY_SERVICE)-sizeof(SdpAttributeRange));

queryservice->type = SDP_SERVICE_ATTRIBUTE_REQUEST;
queryservice->serviceHandle = handle;
queryservice->numRange = env->GetArrayLength(attrIDs);

// set attribute ranges

jint *ints = env->GetIntArrayElements(attrIDs, 0);

for(int i = 0; i < env->GetArrayLength(attrIDs); i++) {
queryservice->pRange[i].minAttribute = (USHORT)ints[i];
queryservice->pRange[i].maxAttribute = (USHORT)ints[i];
}

env->ReleaseIntArrayElements(attrIDs, ints, 0);
#endif

// build BLOB pointing to attribute query

BLOB blob;

#ifdef _WIN32_WCE
blob.cbSize = sizeof(BTHNS_RESTRICTIONBLOB);
#else
blob.cbSize = sizeof(BTH_QUERY_SERVICE);
#endif
blob.pBlobData = (BYTE *)queryservice;

// build query

WSAQUERYSET queryset;

memset(&queryset, 0, sizeof(WSAQUERYSET));

queryset.dwSize = sizeof(WSAQUERYSET);
queryset.dwNameSpace = NS_BTH;
#ifdef _WIN32_WCE

// Build address

SOCKADDR_BTH sa;
memset (&sa, 0, sizeof(sa));
sa.addressFamily = AF_BT;
sa.btAddr = address;
CSADDR_INFO csai;
memset (&csai, 0, sizeof(csai));
csai.RemoteAddr.lpSockaddr = (sockaddr *)&sa;
csai.RemoteAddr.iSockaddrLength = sizeof(sa);
queryset.lpcsaBuffer = &csai;
#else
queryset.lpszContext = addressString;
#endif
queryset.lpBlob = &blob;

HANDLE hLookupServiceAttributes;

// begin query

#ifdef _WIN32_WCE
if (WSALookupServiceBegin(&queryset, 0, &hLookupServiceAttributes)) {
#else
if (WSALookupServiceBegin(&queryset, LUP_FLUSHCACHE, &hLookupServiceAttributes)) {
#endif
free(queryservice);
throwIOExceptionWSAGetLastError(env, "Failed to begin attribute query");
return NULL;
}

free(queryservice);

// fetch results
int bufSize = 0x2000;
void* buf = malloc(bufSize);
if (buf == NULL) {
WSALookupServiceEnd(hLookupServiceAttributes);
return NULL;
}
memset(buf, 0, bufSize);

LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf;
pwsaResults->dwSize = sizeof(WSAQUERYSET);
pwsaResults->dwNameSpace = NS_BTH;
pwsaResults->lpBlob = NULL;

DWORD size = bufSize;

jbyteArray result = NULL;
#ifdef _WIN32_WCE
if (WSALookupServiceNext(hLookupServiceAttributes, 0, &size, pwsaResults)) {
#else
if (WSALookupServiceNext(hLookupServiceAttributes, LUP_RETURN_BLOB, &size, pwsaResults)) {
#endif
throwIOExceptionWSAGetLastError(env, "Failed to perform attribute query");
result = NULL;
} else {
// construct byte array to hold blob
result = env->NewByteArray(pwsaResults->lpBlob->cbSize);

jbyte *bytes = env->GetByteArrayElements(result, 0);

memcpy(bytes, pwsaResults->lpBlob->pBlobData, pwsaResults->lpBlob->cbSize);

env->ReleaseByteArrayElements(result, bytes, 0);
}
WSALookupServiceEnd(hLookupServiceAttributes);
free(buf);
return result;
}

JNIEXPORT jlong JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_registerService(JNIEnv *env, jobject peer, jbyteArray record, jint classOfDevice) {
debug(("registerService"));
int length = env->GetArrayLength(record);

HANDLE handle = NULL;

// build service set

ULONG version = BTH_SDP_VERSION;

#ifdef _WIN32_WCE
BTHNS_SETBLOB *setservice = (BTHNS_SETBLOB*)malloc(sizeof(BTHNS_SETBLOB)+length-1);
memset(setservice, 0, sizeof(BTHNS_SETBLOB)-1);
setservice->pRecordHandle = (ULONG*)&handle;
#else
BTH_SET_SERVICE *setservice = (BTH_SET_SERVICE *)malloc(sizeof(BTH_SET_SERVICE)+length-1);
memset(setservice, 0, sizeof(BTH_SET_SERVICE)-1);
setservice->pRecordHandle = &handle;
setservice->fCodService = GET_COD_SERVICE(classOfDevice);
#endif

setservice->pSdpVersion = &version;
setservice->ulRecordLength = length;

jbyte *bytes = env->GetByteArrayElements(record, 0);

memcpy(setservice->pRecord, bytes, length);

env->ReleaseByteArrayElements(record, bytes, 0);

// build BLOB pointing to service set

BLOB blob;

#ifdef _WIN32_WCE
blob.cbSize = sizeof(BTHNS_SETBLOB);
#else
blob.cbSize = sizeof(BTH_SET_SERVICE);
#endif
blob.pBlobData = (BYTE *)setservice;

// build set

WSAQUERYSET queryset;

memset(&queryset, 0, sizeof(WSAQUERYSET));

queryset.dwSize = sizeof(WSAQUERYSET);
queryset.dwNameSpace = NS_BTH;
queryset.lpBlob = &blob;

// perform set

if (WSASetService(&queryset, RNRSERVICE_REGISTER, 0)) {
throwExceptionWinErrorMessage(env, cServiceRegistrationException, "Failed to register service", WSAGetLastError());
free(setservice);
return 0;
}
free(setservice);
return (jlong)handle;
}


JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_unregisterService(JNIEnv *env, jobject peer, jlong handle) {
debug(("unregisterService"));
// build service set

ULONG version = BTH_SDP_VERSION;

#ifdef _WIN32_WCE
BTHNS_SETBLOB setservice;
memset(&setservice, 0, sizeof(BTHNS_SETBLOB));
setservice.pRecordHandle = (ULONG *)&handle;
#else
BTH_SET_SERVICE setservice;
memset(&setservice, 0, sizeof(BTH_SET_SERVICE));
setservice.pRecordHandle = (HANDLE *)&handle;
#endif

setservice.pSdpVersion = &version;

// build BLOB pointing to service set

BLOB blob;
#ifdef _WIN32_WCE
blob.cbSize = sizeof(BTHNS_SETBLOB);
#else
blob.cbSize = sizeof(BTH_SET_SERVICE);
#endif
blob.pBlobData = (BYTE *)&setservice;

// build set

WSAQUERYSET queryset;

memset(&queryset, 0, sizeof(WSAQUERYSET));

queryset.dwSize = sizeof(WSAQUERYSET);
queryset.dwNameSpace = NS_BTH;
queryset.lpBlob = &blob;

// perform set

if (WSASetService(&queryset, RNRSERVICE_DELETE, 0)) {
throwServiceRegistrationException(env, "Failed to unregister service");
}
}

JNIEXPORT jlong JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_socket(JNIEnv *env, jobject peer, jboolean authenticate, jboolean encrypt) {
debug(("socket"));
// create socket

SOCKET s = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);

if (s == INVALID_SOCKET) {
throwIOExceptionWinGetLastError(env, "Failed to create socket");
return 0;
}

// set socket options

if (authenticate) {
ULONG ul = TRUE;

if (setsockopt(s, SOL_RFCOMM, SO_BTH_AUTHENTICATE, (char *)&ul, sizeof(ULONG))) {
closesocket(s);
throwIOExceptionWinGetLastError(env, "Failed to set authentication option");
return 0;
}
}

if (encrypt) {
#ifdef _WIN32_WCE
int ul = TRUE;
#else
ULONG ul = TRUE;
#endif
if (setsockopt(s, SOL_RFCOMM, SO_BTH_ENCRYPT, (char *)&ul, sizeof(ul))) {
closesocket(s);
throwIOExceptionWinGetLastError(env, "Failed to set encryption option");
return 0;
}
}
debug(("socket[%u] opened", (int)s));
return s;
}

/* This does not work: [10042] An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call. */
/*
JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getSecurityOptImpl(JNIEnv * env, jobject peer, jlong socket) {
ULONG authenticatedVal = FALSE;
int optLen = sizeof(ULONG);
if (getsockopt((SOCKET)socket, SOL_RFCOMM, SO_BTH_AUTHENTICATE, (char*)&authenticatedVal, &optLen) == SOCKET_ERROR) {
throwIOExceptionWinGetLastError(env, "Failed to get authenticate option");
return NOAUTHENTICATE_NOENCRYPT;
}
ULONG encryptedVal = FALSE;
optLen = sizeof(ULONG);
if (getsockopt((SOCKET)socket, SOL_RFCOMM, SO_BTH_ENCRYPT, (char*)&encryptedVal, &optLen) == SOCKET_ERROR) {
throwIOExceptionWinGetLastError(env, "Failed to get encryption option");
return NOAUTHENTICATE_NOENCRYPT;
}
if (!authenticatedVal) {
return NOAUTHENTICATE_NOENCRYPT;
}

if (encryptedVal) {
return AUTHENTICATE_ENCRYPT;
} else {
return AUTHENTICATE_NOENCRYPT;
}
}
*/

JNIEXPORT jlong JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getsockaddress(JNIEnv *env, jobject peer, jlong socket) {
debug(("socket[%u] getsockaddress", (int)socket));
// get socket name
SOCKADDR_BTH addr;
int size = sizeof(SOCKADDR_BTH);
if (getsockname((SOCKET)socket, (sockaddr *)&addr, &size)) {
throwIOExceptionWSAGetLastError(env, "Failed to get socket name");
return 0;
}
return addr.btAddr;
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getsockchannel(JNIEnv *env, jobject peer, jlong socket) {
debug(("socket[%u] getsockchannel", (int)socket));
// get socket name

SOCKADDR_BTH addr;

int size = sizeof(SOCKADDR_BTH);

if (getsockname((SOCKET)socket, (sockaddr *)&addr, &size)) {
throwIOExceptionWSAGetLastError(env, "Failed to get socket name");
return 0;
}
return addr.port;
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_connect(JNIEnv *env, jobject peer, jlong socket, jlong address, jint channel, jint retryUnreachable) {
debug(("socket[%u] connect", (int)socket));

SOCKADDR_BTH addr;

memset(&addr, 0, sizeof(SOCKADDR_BTH));

addr.addressFamily = AF_BTH;
addr.btAddr = address;
addr.port = channel;

int retyCount = 0;
connectRety:
if (connect((SOCKET)socket, (sockaddr *)&addr, sizeof(SOCKADDR_BTH))) {
retyCount ++;
int last_error = WSAGetLastError();
//10051 - A socket operation was attempted to an unreachable network. / Error other than time-out at L2CAP or Bluetooth radio level.
if (last_error == WSAENETUNREACH) {
if ((retyCount < retryUnreachable) && (retryUnreachable > 0)) {
if (isCurrentThreadInterrupted(env, peer, "connect")) {
return;
}
debug(("connectRety %i", retyCount));
goto connectRety;
}
}
if (last_error == WSAEACCES) {
throwBluetoothConnectionException(env, BT_CONNECTION_ERROR_SECURITY_BLOCK, "Connecting application requested authentication, but authentication failed [10013] .");
} else if (last_error == WSAETIMEDOUT) {
throwBluetoothConnectionException(env, BT_CONNECTION_ERROR_TIMEOUT, "Connection timeout; [%lu] %S", last_error, getWinErrorMessage(last_error));
} else {
throwBluetoothConnectionException(env, BT_CONNECTION_ERROR_FAILED_NOINFO, "Failed to connect; [%lu] %S", last_error, getWinErrorMessage(last_error));
}
}
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_bind(JNIEnv *env, jobject peer, jlong socket) {
// bind socket
debug(("socket[%u] bind", (int)socket));

SOCKADDR_BTH addr;
memset(&addr, 0, sizeof(addr));
addr.addressFamily = AF_BTH;
#ifdef _WIN32_WCE
addr.port = 0;
#else
addr.port = BT_PORT_ANY;
#endif
if (bind((SOCKET)socket, (SOCKADDR *)&addr, sizeof(addr))) {
closesocket((SOCKET)socket);
throwIOExceptionWSAGetLastError(env, "Failed to bind socket");
return;
}
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_listen(JNIEnv *env, jobject peer, jlong socket) {
debug(("socket[%u] listen", (int)socket));
if (listen((SOCKET)socket, 10)) {
throwIOExceptionWSAGetLastError(env, "Failed to listen socket");
}
}

JNIEXPORT jlong JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_accept(JNIEnv *env, jobject peer, jlong socket) {
debug(("socket[%u] accept", (int)socket));
SOCKADDR_BTH addr;

int size = sizeof(SOCKADDR_BTH);

SOCKET s = accept((SOCKET)socket, (sockaddr *)&addr, &size);

if (s == INVALID_SOCKET) {
throwIOException(env, "Failed to listen socket");
return 0;
}

debug(("connection accepted"));

return s;
}

/*
*
* Use to determine the amount of data pending in the network's input buffer that can be read from socket.
* returns the amount of data that can be read in a single call to the recv function, which may not be the same as
* the total amount of data queued on the socket.
*/
JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_recvAvailable(JNIEnv *env, jobject peer, jlong socket) {
unsigned long arg = 0;
if (ioctlsocket((SOCKET)socket, FIONREAD, &arg) != 0) {
throwIOExceptionWSAGetLastError(env, "Failed to read available");
return 0;
}
return (jint)arg;
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_recv__J(JNIEnv *env, jobject peer, jlong socket) {
debug(("socket[%u] recv()", (int)socket));
// Use non blocking functions to see if we have one byte
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 500 * 1000; //microseconds
while (TRUE) {
fd_set readfds;
fd_set exceptfds;
FD_ZERO(&readfds);
FD_SET((SOCKET)socket, &readfds);
FD_ZERO(&exceptfds);
FD_SET((SOCKET)socket, &exceptfds);
int ready_count = select(FD_SETSIZE, &readfds, NULL, &exceptfds, &timeout);
if (ready_count == SOCKET_ERROR) {
throwIOExceptionWSAGetLastError(env, "Failed to read(int)/select");
return -1;
} else if (ready_count > 0) {
break;
} else if (isCurrentThreadInterrupted(env, peer, "read")) {
return -1;
}
}
// Read the data when available
unsigned char c;
int rc = recv((SOCKET)socket, (char *)&c, 1, 0);
if (rc == SOCKET_ERROR) {
throwIOExceptionWSAGetLastError(env, "Failed to read(int)");
return 0;
} else if (rc == 0) {
debug(("Connection closed"));
// See InputStream.read();
return -1;
}
return (int)c;
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_recv__J_3BII(JNIEnv *env, jobject peer, jlong socket, jbyteArray b, jint off, jint len) {
debug(("socket[%u] recv (byte[],int,int=%i)", (int)socket, len));
// Use non blocking functions to see if we have one byte
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 500 * 1000; //microseconds
while (TRUE) {
fd_set readfds;
fd_set exceptfds;
FD_ZERO(&readfds);
FD_SET((SOCKET)socket, &readfds);
FD_ZERO(&exceptfds);
FD_SET((SOCKET)socket, &exceptfds);
int ready_count = select(FD_SETSIZE, &readfds, NULL, &exceptfds, &timeout);
if (ready_count == SOCKET_ERROR) {
throwIOExceptionWSAGetLastError(env, "Failed to read(byte[])/select");
return -1;
} else if (ready_count > 0) {
break;
} else if (isCurrentThreadInterrupted(env, peer, "read")) {
return -1;
}
}
// Read the data when available
jbyte *bytes = env->GetByteArrayElements(b, 0);
int done = 0;
while(done < len) {
int count = recv((SOCKET)socket, (char *)(bytes + off + done), len - done, 0);
if (count == SOCKET_ERROR) {
throwIOExceptionWSAGetLastError(env, "Failed to read(byte[])");
done = -1;
break;
} else if (count == 0) {
debug(("Connection closed"));
if (done == 0) {
// See InputStream.read();
done = -1;
break;
} else {
break;
}
}
done += count;
if (done != 0) {
if (isCurrentThreadInterrupted(env, peer, "read")) {
done = -1;
break;
}
unsigned long available = 0;
if (ioctlsocket((SOCKET)socket, FIONREAD, &available) != 0) {
// error;
break;
} else if (available == 0) {
break;
}
}
}
env->ReleaseByteArrayElements(b, bytes, 0);
return done;
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_send__JI(JNIEnv *env, jobject peer, jlong socket, jint b) {
debug(("socket[%u] send(int)", (int)socket));
char c = (char)b;
if (send((SOCKET)socket, &c, 1, 0) != 1) {
throwIOExceptionWSAGetLastError(env, "Failed to write");
}
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_send__J_3BII(JNIEnv *env, jobject peer, jlong socket, jbyteArray b, jint off, jint len) {
debug(("socket[%u] send(byte[],int,int=%i)", (int)socket, len));
jbyte *bytes = env->GetByteArrayElements(b, 0);
int done = 0;
while (done < len) {
int count = send((SOCKET)socket, (char *)(bytes + off + done), len - done, 0);
if (count <= 0) {
throwIOExceptionWSAGetLastError(env, "Failed to write");
break;
}
done += count;
if ((done < len) && (isCurrentThreadInterrupted(env, peer, "write"))) {
break;
}
}
env->ReleaseByteArrayElements(b, bytes, 0);
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_close(JNIEnv *env, jobject peer, jlong socket) {
debug(("socket[%u] close", (int)socket));
if (shutdown((SOCKET)socket, SD_BOTH) != 0) {
int last_error = WSAGetLastError();
if (last_error != WSAENOTCONN) {
debug(("shutdown error [%i] %S", last_error, getWinErrorMessage(last_error)));
}
}
if (closesocket((SOCKET)socket)) {
throwIOExceptionWSAGetLastError(env, "Failed to close socket");
}
}

JNIEXPORT jstring JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getpeername(JNIEnv *env, jobject peer, jlong addr) {
#ifdef _WIN32_WCE
/*
* For the moment just return an empty string on Windows Mobile
* The next device scan will return a name anyway...
* To be modified later
*/
return env->NewStringUTF((char*)"");
#else

debug(("getpeername"));


WSAQUERYSET querySet;
memset(&querySet, 0, sizeof(WSAQUERYSET));
querySet.dwSize = sizeof(WSAQUERYSET);
querySet.dwNameSpace = NS_BTH;

DWORD flagsBegin = LUP_FLUSHCACHE | LUP_CONTAINERS;
DWORD flagsNext = LUP_RETURN_NAME | LUP_RETURN_ADDR | LUP_CONTAINERS;

EnterCriticalSection(&csLookup);

if (hDeviceLookup != NULL) {
LeaveCriticalSection(&csLookup);
throwIOException(env, cINQUIRY_RUNNING);
return NULL;
}

HANDLE hLookupPeerName = NULL;

if (WSALookupServiceBegin(&querySet, flagsBegin, &hLookupPeerName)) {
LeaveCriticalSection(&csLookup);
throwIOExceptionWSAGetLastError(env, "Name Lookup error");
return NULL;
}

LeaveCriticalSection(&csLookup);
DWORD bufSize = 0x2000;
void* buf = malloc(bufSize);
if (buf == NULL) {
return NULL;
}

jstring result = NULL;
BOOL error = FALSE;
while (!error) {
memset(buf, 0, bufSize);
WSAQUERYSET *pwsaResults = (WSAQUERYSET*)buf;
pwsaResults->dwSize = sizeof(WSAQUERYSET);
pwsaResults->dwNameSpace = NS_BTH;

DWORD bufferLength = bufSize;

EnterCriticalSection(&csLookup);
if (WSALookupServiceNext(hLookupPeerName, flagsNext, &bufferLength, pwsaResults)) {
int err = WSAGetLastError();
LeaveCriticalSection(&csLookup);
switch(err) {
case WSAENOMORE:
case WSA_E_NO_MORE:
break;
default:
throwIOExceptionWinErrorMessage(env, "Service Lookup error", err);
error = TRUE;
break;
}
break;
}

LeaveCriticalSection(&csLookup);

if (((SOCKADDR_BTH *)((CSADDR_INFO *)pwsaResults->lpcsaBuffer)->RemoteAddr.lpSockaddr)->btAddr == addr) {
WCHAR *name = pwsaResults->lpszServiceInstanceName;
debug(("return %s", name));
result = env->NewString((jchar*)name, (jsize)wcslen(name));
break;
}
}
free(buf);
if (hLookupPeerName != NULL) {
WSALookupServiceEnd(hLookupPeerName);
}

if ((result == NULL) && (!error)) {
debug(("return empty"));
result = env->NewStringUTF((char*)"");
}
return result;
#endif
}


JNIEXPORT jlong JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getpeeraddress(JNIEnv *env, jobject peer, jlong socket) {
debug(("socket[%u] getpeeraddress", (int)socket));
SOCKADDR_BTH addr;
int size = sizeof(addr);
if (getpeername((SOCKET) socket, (sockaddr*)&addr, &size)) {
throwIOExceptionWSAGetLastError(env, "peername error");
return 0;
}
return addr.btAddr;
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_storesockopt(JNIEnv * env, jobject peer, jlong socket) {
#ifndef _WIN32_WCE
int optVal;
int optLen = sizeof(int);
if (getsockopt((SOCKET)socket, SOL_SOCKET, SO_RCVBUF, (char*)&optVal, &optLen) != SOCKET_ERROR) {
debug(("receive buffer %i", optVal));
}
if (getsockopt((SOCKET)socket, SOL_SOCKET, SO_SNDBUF, (char*)&optVal, &optLen) != SOCKET_ERROR) {
debug(("send buffer %i", optVal));
}
#else
int optVal;
int optLen = sizeof(int);
if (getsockopt(socket, SOL_RFCOMM, SO_BTH_GET_RECV_BUFFER, (char*)&optVal, &optLen) != SOCKET_ERROR) {
debug(("receive buffer %i", optVal));
}
if (getsockopt(socket, SOL_RFCOMM, SO_BTH_GET_SEND_BUFFER, (char*)&optVal, &optLen) != SOCKET_ERROR) {
debug(("send buffer %i", optVal));
}
optLen = sizeof(BTH_LOCAL_VERSION);
if (getsockopt(socket, SOL_RFCOMM, SO_BTH_GET_SEND_BUFFER, (char*)&localBluetoothDeviceInfo, &optLen) != SOCKET_ERROR) {
//
}
#endif
}

// Unsupported for _WIN32_WCE for the moment...
#ifndef _WIN32_WCE
BOOL getBluetoothGetRadioInfo(jlong address, BLUETOOTH_RADIO_INFO* info) {
HANDLE hRadio;
BLUETOOTH_FIND_RADIO_PARAMS btfrp = { sizeof(btfrp) };
HBLUETOOTH_RADIO_FIND hFind = BluetoothFindFirstRadio( &btfrp, &hRadio );
if ( NULL != hFind ) {
do {
BLUETOOTH_RADIO_INFO radioInfo;
radioInfo.dwSize = sizeof(radioInfo);
if (ERROR_SUCCESS == BluetoothGetRadioInfo(hRadio, &radioInfo)) {
if (radioInfo.address.ullLong == address) {
BluetoothFindRadioClose(hFind);
memcpy(info, &radioInfo, sizeof(BLUETOOTH_RADIO_INFO));
return TRUE;
}
}
} while( BluetoothFindNextRadio( hFind, &hRadio ) );
BluetoothFindRadioClose( hFind );
}
return FALSE;
}
#endif

JNIEXPORT jstring JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getradioname(JNIEnv *env, jobject peer, jlong address) {
debug(("getradioname"));
// Unsupported for _WIN32_WCE for the moment...
#ifndef _WIN32_WCE
BLUETOOTH_RADIO_INFO radioInfo;
if (getBluetoothGetRadioInfo(address, &radioInfo)) {
return env->NewString((jchar*)radioInfo.szName, (jsize) wcslen(radioInfo.szName));
}
#endif
return NULL;
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getDeviceVersion(JNIEnv *env, jobject peer, jlong address) {
#ifndef _WIN32_WCE
BLUETOOTH_RADIO_INFO radioInfo;
if (getBluetoothGetRadioInfo(address, &radioInfo)) {
return radioInfo.lmpSubversion;
}
return -1;
#else
return localBluetoothDeviceInfo.lmp_subversion;
#endif
}

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getDeviceManufacturer(JNIEnv *env, jobject peer, jlong address) {
#ifndef _WIN32_WCE
BLUETOOTH_RADIO_INFO radioInfo;
if (getBluetoothGetRadioInfo(address, &radioInfo)) {
return radioInfo.manufacturer;
}
return -1;
#else
return localBluetoothDeviceInfo.manufacturer;
#endif
}

#define MAJOR_COMPUTER 0x0100
#define MAJOR_PHONE 0x0200
#define COMPUTER_MINOR_HANDHELD 0x10
#define PHONE_MINOR_SMARTPHONE 0x0c

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getDeviceClass(JNIEnv *env, jobject peer, jlong address) {
#ifndef _WIN32_WCE
if (address == 0) {
return MAJOR_COMPUTER;
}
BLUETOOTH_RADIO_INFO radioInfo;
if (getBluetoothGetRadioInfo(address, &radioInfo)) {
return radioInfo.ulClassofDevice;
} else {
debug(("e.can't find RadioInfo"));
}
return MAJOR_COMPUTER;
#else
OSVERSIONINFO osvi;
TCHAR szPlatform[MAX_PATH];

BOOL rb;

osvi.dwOSVersionInfoSize = sizeof(osvi);
rb = GetVersionEx(&osvi);
if (rb == FALSE) {
return MAJOR_COMPUTER;
}
switch (osvi.dwPlatformId) {
// A Windows CE platform.
case VER_PLATFORM_WIN32_CE:
// Get platform string.
rb = SystemParametersInfo(SPI_GETPLATFORMTYPE, MAX_PATH, szPlatform, 0);
if (rb == FALSE) // SystemParametersInfo failed.
{
return MAJOR_COMPUTER & COMPUTER_MINOR_HANDHELD;
}
debug(("PLATFORMTYPE %S", szPlatform));
if (0 == lstrcmpi(szPlatform, TEXT("Smartphone"))) {
return MAJOR_PHONE | PHONE_MINOR_SMARTPHONE;
}
if (0 == lstrcmpi(szPlatform, TEXT("PocketPC"))) {
return MAJOR_COMPUTER | COMPUTER_MINOR_HANDHELD;
}
}
return MAJOR_COMPUTER;
#endif
}

#define BTH_MODE_POWER_OFF 1
#define BTH_MODE_CONNECTABLE 2
#define BTH_MODE_DISCOVERABLE 3

JNIEXPORT jint JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_getBluetoothRadioMode(JNIEnv *env, jobject peer) {
#ifndef _WIN32_WCE
if (BluetoothIsDiscoverable(NULL)) {
return BTH_MODE_DISCOVERABLE;
}
if (BluetoothIsConnectable(NULL)) {
return BTH_MODE_CONNECTABLE;
}
#else
DWORD dwMode;
int rc = BthGetMode(&dwMode);
if (rc == ERROR_SUCCESS) {
switch(dwMode) {
case BTH_DISCOVERABLE:
return BTH_MODE_DISCOVERABLE;
case BTH_CONNECTABLE:
return BTH_MODE_CONNECTABLE;
case BTH_POWER_OFF:
return BTH_MODE_POWER_OFF;
}
} else {
throwBluetoothStateExceptionWinErrorMessage(env, "Bluetooth mode error ", rc);
}
#endif
return 0;
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_setDiscoverable(JNIEnv *env, jobject peer, jboolean on) {
#ifndef _WIN32_WCE
BOOL enabled = FALSE;
if (on) {
if (!BluetoothEnableIncomingConnections(NULL, TRUE)) {
throwBluetoothStateException(env, "Enable Incoming Connections error");
}
enabled = TRUE;
}
if (BluetoothEnableDiscovery(NULL, enabled)) {
restoreBtMode = (initialBtIsDiscoverable != enabled);
} else {
throwBluetoothStateException(env, "Change Bluetooth Discovery mode error");
}
#else
DWORD dwMode = BTH_CONNECTABLE;
if (on) {
dwMode = BTH_DISCOVERABLE;
}
int rc = BthSetMode(dwMode);
if (rc == ERROR_SUCCESS) {
restoreBtMode = (initialBtMode != dwMode);
} else {
throwBluetoothStateExceptionWinErrorMessage(env, "Set Bluetooth mode error ", rc);
}
#endif
}

#ifndef _WIN32_WCE
BOOL getBluetoothDeviceInfo(jlong address, BLUETOOTH_DEVICE_INFO* pbtdi, BOOL issueInquiry) {
BLUETOOTH_DEVICE_SEARCH_PARAMS btsp;
memset(&btsp, 0, sizeof(btsp));
btsp.dwSize = sizeof(btsp);
btsp.fIssueInquiry = issueInquiry;
btsp.fReturnAuthenticated = true;
btsp.fReturnConnected = true;
btsp.fReturnRemembered = true;
btsp.fReturnUnknown = true;
if (issueInquiry) {
btsp.cTimeoutMultiplier = 10;
}

memset(pbtdi, 0, sizeof(BLUETOOTH_DEVICE_INFO));
pbtdi->dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
HBLUETOOTH_DEVICE_FIND hFind = BluetoothFindFirstDevice(&btsp, pbtdi);
if (NULL != hFind) {
do {
if (pbtdi->Address.ullLong == address) {
BluetoothFindDeviceClose(hFind);
return TRUE;
}
ndebug(("found device %i", pbtdi->Address.ullLong));
memset(pbtdi, 0, sizeof(BLUETOOTH_DEVICE_INFO));
pbtdi->dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
} while (BluetoothFindNextDevice(hFind, pbtdi));
BluetoothFindDeviceClose(hFind);
}
return FALSE;
}
#endif

JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_authenticateRemoteDeviceImpl
(JNIEnv *env, jobject, jlong address, jstring passkey) {
#ifdef _WIN32_WCE
return JNI_FALSE;
#else
#define MAX_PIN_CODE_LEN 256
WCHAR szPasskey[MAX_PIN_CODE_LEN + 1];
PWCHAR pszPasskey;
ULONG ulPasskeyLength;

BLUETOOTH_DEVICE_INFO btdi;
if (!getBluetoothDeviceInfo(address, &btdi, false)) {
debug(("device not found; Issue Inquiry"));
if (!getBluetoothDeviceInfo(address, &btdi, true)) {
debug(("device not found"));
return JNI_FALSE;
}
}

if (passkey != NULL) {
const jchar *cpasskey = env->GetStringChars(passkey, JNI_FALSE);
jsize size = env->GetStringLength(passkey);
int i = 0;
for(; (i < MAX_PIN_CODE_LEN) && (i < size); i ++) {
szPasskey[i] = cpasskey[i];
}
szPasskey[i] = '\0';
ulPasskeyLength = i;
env->ReleaseStringChars(passkey, cpasskey);
pszPasskey = szPasskey;
debug(("authenticate using pin [%S] %i", szPasskey, ulPasskeyLength));
} else {
pszPasskey = NULL;
ulPasskeyLength = 0;
debug(("authenticate using user interface"));
}

// ReAuthenticate, Keep devices Authenticated in DB if function fails, suggested by Eric Schreiber
btdi.fAuthenticated = false;

DWORD rc = BluetoothAuthenticateDevice(NULL, NULL, &btdi, pszPasskey, ulPasskeyLength);
if (ERROR_SUCCESS != rc) {
debug(("authenticate error [%i] %S", rc, getWinErrorMessage(rc)));
return JNI_FALSE;
} else {
return JNI_TRUE;
}
#endif
}

JNIEXPORT void JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_removeAuthenticationWithRemoteDeviceImpl
(JNIEnv *env, jobject, jlong address) {
#ifndef _WIN32_WCE
BLUETOOTH_ADDRESS btAddr;
btAddr.ullLong = address;
DWORD rc = BluetoothRemoveDevice(&btAddr);
if (ERROR_NOT_FOUND == rc) {
throwIOException(env, "device was not found");
} else if (ERROR_SUCCESS != rc) {
throwIOException(env, "not a remembered device");
}
#endif
}

JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_isRemoteDeviceTrustedImpl
(JNIEnv *env, jobject, jlong address) {
#ifndef _WIN32_WCE
BLUETOOTH_DEVICE_INFO btdi;
if (!getBluetoothDeviceInfo(address, &btdi, false)) {
debug(("device not found"));
return JNI_FALSE;
}
if (btdi.fAuthenticated && btdi.fRemembered) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
#else
return JNI_FALSE;
#endif
}

/*
* Class: com_intel_bluetooth_BluetoothStackMicrosoft
* Method: isRemoteDeviceAuthenticatedImpl
* Signature: (J)Z
*/
JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_isRemoteDeviceAuthenticatedImpl
(JNIEnv *env, jobject, jlong address) {
#ifndef _WIN32_WCE
BLUETOOTH_DEVICE_INFO btdi;
if (!getBluetoothDeviceInfo(address, &btdi, false)) {
debug(("device not found"));
return JNI_FALSE;
}
if (btdi.fAuthenticated && btdi.fConnected) {
return JNI_TRUE;
} else {
return JNI_FALSE;
}
#else
return JNI_FALSE;
#endif
}

JNIEXPORT jboolean JNICALL Java_com_intel_bluetooth_BluetoothStackMicrosoft_retrieveDevicesImpl
(JNIEnv *env, jobject peer, jint option, jobject retrieveDevicesCallback) {
#ifndef _WIN32_WCE
RetrieveDevicesCallback callback;
if (!callback.builCallback(env, peer, retrieveDevicesCallback)) {
return JNI_FALSE;
}

jboolean result = JNI_FALSE;
BLUETOOTH_DEVICE_SEARCH_PARAMS btsp;
memset(&btsp, 0, sizeof(btsp));
btsp.dwSize = sizeof(btsp);
btsp.fIssueInquiry = false;

switch (option) {
case RETRIEVEDEVICES_OPTION_PREKNOWN:
btsp.fReturnRemembered = true;
break;
case RETRIEVEDEVICES_OPTION_CACHED:
btsp.fReturnAuthenticated = true;
btsp.fReturnConnected = true;
btsp.fReturnRemembered = true;
btsp.fReturnUnknown = true;
break;
}
BLUETOOTH_DEVICE_INFO btdi;
memset(&btdi, 0, sizeof(BLUETOOTH_DEVICE_INFO));
btdi.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
HBLUETOOTH_DEVICE_FIND hFind = BluetoothFindFirstDevice(&btsp, &btdi);
if (NULL != hFind) {
result = JNI_TRUE;
do {
debug(("deviceFoundCallback, notify listener; %i", btdi.Address.ullLong));
jlong deviceAddr = btdi.Address.ullLong;
jint deviceClass = btdi.ulClassofDevice;
jstring deviceName = env->NewString((jchar*)btdi.szName, (jsize)wcslen(btdi.szName));
jboolean paired = (btdi.fAuthenticated && btdi.fRemembered)?JNI_TRUE:JNI_FALSE;
if (!callback.callDeviceFoundCallback(env, deviceAddr, deviceClass, deviceName, paired)) {
result = JNI_FALSE;
break;
}
memset(&btdi, 0, sizeof(BLUETOOTH_DEVICE_INFO));
btdi.dwSize = sizeof(BLUETOOTH_DEVICE_INFO);
} while (BluetoothFindNextDevice(hFind, &btdi));
BluetoothFindDeviceClose(hFind);
}
return result;
#else
return JNI_FALSE;
#endif

}

#endif // _BTWINSOCKLIB

Change log

r3065 by skarzhevskyy on Nov 29, 2010   Diff
issues #120; Apply changes suggested by
Sven Köhler for mingw64 toolchain
Go to: 
Project members, sign in to write a code review

Older revisions

r3064 by skarzhevskyy on Nov 28, 2010   Diff
issues #120; Apply changes suggested
by Sven Köhler for mingw64 toolchain
r2821 by skarzhevskyy on Mar 1, 2009   Diff
review calls for
isCurrentThreadInterrupted
r2638 by skarzhevskyy on Dec 22, 2008   Diff
proper java code for InquiryRunnable
and SearchServicesRunnable
All revisions of this file

File info

Size: 49690 bytes, 1659 lines

File properties

svn:mime-type
text/plain
svn:eol-style
CRLF
svn:keywords
Date Author Id Revision
Powered by Google Project Hosting