bluetooth.c (14120B)
1 /* 2 * libdivecomputer 3 * 4 * Copyright (C) 2013 Jef Driesen 5 * 6 * This library is free software; you can redistribute it and/or 7 * modify it under the terms of the GNU Lesser General Public 8 * License as published by the Free Software Foundation; either 9 * version 2.1 of the License, or (at your option) any later version. 10 * 11 * This library is distributed in the hope that it will be useful, 12 * but WITHOUT ANY WARRANTY; without even the implied warranty of 13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 14 * Lesser General Public License for more details. 15 * 16 * You should have received a copy of the GNU Lesser General Public 17 * License along with this library; if not, write to the Free Software 18 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, 19 * MA 02110-1301 USA 20 */ 21 22 #ifdef HAVE_CONFIG_H 23 #include "config.h" 24 #endif 25 26 #include <stdlib.h> // malloc, free 27 28 #include "socket.h" 29 30 #ifdef _WIN32 31 #ifdef HAVE_WS2BTH_H 32 #define BLUETOOTH 33 #include <initguid.h> 34 #include <ws2bth.h> 35 #endif 36 #else 37 #ifdef HAVE_BLUEZ 38 #define BLUETOOTH 39 #include <bluetooth/bluetooth.h> 40 #include <bluetooth/rfcomm.h> 41 #include <bluetooth/hci.h> 42 #include <bluetooth/hci_lib.h> 43 #include <bluetooth/sdp.h> 44 #include <bluetooth/sdp_lib.h> 45 #endif 46 #endif 47 48 #include <libdivecomputer/bluetooth.h> 49 50 #include "common-private.h" 51 #include "context-private.h" 52 #include "iostream-private.h" 53 #include "iterator-private.h" 54 #include "platform.h" 55 #include "array.h" 56 57 #ifdef _WIN32 58 #define DC_ADDRESS_FORMAT "%012I64X" 59 #else 60 #define DC_ADDRESS_FORMAT "%012llX" 61 #endif 62 63 #define MAX_DEVICES 255 64 #define MAX_PERIODS 8 65 66 #define ISINSTANCE(device) dc_iostream_isinstance((device), &dc_bluetooth_vtable) 67 68 struct dc_bluetooth_device_t { 69 dc_bluetooth_address_t address; 70 char name[248]; 71 }; 72 73 #ifdef BLUETOOTH 74 static dc_status_t dc_bluetooth_iterator_next (dc_iterator_t *iterator, void *item); 75 static dc_status_t dc_bluetooth_iterator_free (dc_iterator_t *iterator); 76 77 typedef struct dc_bluetooth_iterator_t { 78 dc_iterator_t base; 79 dc_descriptor_t *descriptor; 80 #ifdef _WIN32 81 HANDLE hLookup; 82 #else 83 int fd; 84 inquiry_info *devices; 85 size_t count; 86 size_t current; 87 #endif 88 } dc_bluetooth_iterator_t; 89 90 static const dc_iterator_vtable_t dc_bluetooth_iterator_vtable = { 91 sizeof(dc_bluetooth_iterator_t), 92 dc_bluetooth_iterator_next, 93 dc_bluetooth_iterator_free, 94 }; 95 96 static const dc_iostream_vtable_t dc_bluetooth_vtable = { 97 sizeof(dc_socket_t), 98 dc_socket_set_timeout, /* set_timeout */ 99 NULL, /* set_break */ 100 NULL, /* set_dtr */ 101 NULL, /* set_rts */ 102 NULL, /* get_lines */ 103 dc_socket_get_available, /* get_available */ 104 NULL, /* configure */ 105 dc_socket_poll, /* poll */ 106 dc_socket_read, /* read */ 107 dc_socket_write, /* write */ 108 dc_socket_ioctl, /* ioctl */ 109 NULL, /* flush */ 110 NULL, /* purge */ 111 dc_socket_sleep, /* sleep */ 112 dc_socket_close, /* close */ 113 }; 114 115 #ifdef HAVE_BLUEZ 116 static dc_bluetooth_address_t 117 dc_address_get (const bdaddr_t *ba) 118 { 119 dc_bluetooth_address_t address = 0; 120 121 size_t shift = 0; 122 for (size_t i = 0; i < C_ARRAY_SIZE(ba->b); ++i) { 123 address |= (dc_bluetooth_address_t) ba->b[i] << shift; 124 shift += 8; 125 } 126 127 return address; 128 } 129 130 static void 131 dc_address_set (bdaddr_t *ba, dc_bluetooth_address_t address) 132 { 133 size_t shift = 0; 134 for (size_t i = 0; i < C_ARRAY_SIZE(ba->b); ++i) { 135 ba->b[i] = (address >> shift) & 0xFF; 136 shift += 8; 137 } 138 } 139 140 static dc_status_t 141 dc_bluetooth_sdp (uint8_t *port, dc_context_t *context, const bdaddr_t *ba) 142 { 143 dc_status_t status = DC_STATUS_SUCCESS; 144 sdp_session_t *session = NULL; 145 sdp_list_t *search = NULL, *attrid = NULL; 146 sdp_list_t *records = NULL; 147 uint8_t channel = 0; 148 149 // Connect to the SDP server on the remote device. 150 session = sdp_connect (BDADDR_ANY, ba, SDP_RETRY_IF_BUSY); 151 if (session == NULL) { 152 s_errcode_t errcode = S_ERRNO; 153 SYSERROR (context, errcode); 154 status = dc_socket_syserror(errcode); 155 goto error; 156 } 157 158 // Specify the UUID of the serial port service with all attributes. 159 uuid_t uuid = {0}; 160 uint32_t range = 0x0000FFFF; 161 sdp_uuid16_create (&uuid, SERIAL_PORT_SVCLASS_ID); 162 search = sdp_list_append (NULL, &uuid); 163 attrid = sdp_list_append (NULL, &range); 164 if (search == NULL || attrid == NULL) { 165 s_errcode_t errcode = S_ERRNO; 166 SYSERROR (context, errcode); 167 status = dc_socket_syserror(errcode); 168 goto error; 169 } 170 171 // Get a list of the service records with their attributes. 172 if (sdp_service_search_attr_req (session, search, SDP_ATTR_REQ_RANGE, attrid, &records) != 0) { 173 s_errcode_t errcode = S_ERRNO; 174 SYSERROR (context, errcode); 175 status = dc_socket_syserror(errcode); 176 goto error; 177 } 178 179 // Go through each of the service records. 180 for (sdp_list_t *r = records; r; r = r->next ) { 181 sdp_record_t *record = (sdp_record_t *) r->data; 182 183 // Get a list of the protocol sequences. 184 sdp_list_t *protos = NULL; 185 if (sdp_get_access_protos (record, &protos) != 0 ) { 186 s_errcode_t errcode = S_ERRNO; 187 SYSERROR (context, errcode); 188 status = dc_socket_syserror(errcode); 189 goto error; 190 } 191 192 // Get the rfcomm port number. 193 int ch = sdp_get_proto_port (protos, RFCOMM_UUID); 194 195 sdp_list_foreach (protos, (sdp_list_func_t) sdp_list_free, NULL); 196 sdp_list_free (protos, NULL); 197 198 if (ch > 0) { 199 channel = ch; 200 break; 201 } 202 } 203 204 if (channel == 0) { 205 ERROR (context, "No serial port service found!"); 206 status = DC_STATUS_IO; 207 goto error; 208 } 209 210 INFO (context, "SDP: channel=%u", channel); 211 212 *port = channel; 213 214 error: 215 sdp_list_free (records, (sdp_free_func_t) sdp_record_free); 216 sdp_list_free (attrid, NULL); 217 sdp_list_free (search, NULL); 218 sdp_close (session); 219 220 return status; 221 } 222 #endif 223 #endif 224 225 char * 226 dc_bluetooth_addr2str(dc_bluetooth_address_t address, char *str, size_t size) 227 { 228 if (str == NULL || size < DC_BLUETOOTH_SIZE) 229 return NULL; 230 231 int n = dc_platform_snprintf(str, size, "%02X:%02X:%02X:%02X:%02X:%02X", 232 (unsigned char)((address >> 40) & 0xFF), 233 (unsigned char)((address >> 32) & 0xFF), 234 (unsigned char)((address >> 24) & 0xFF), 235 (unsigned char)((address >> 16) & 0xFF), 236 (unsigned char)((address >> 8) & 0xFF), 237 (unsigned char)((address >> 0) & 0xFF)); 238 if (n < 0 || (size_t) n >= size) 239 return NULL; 240 241 return str; 242 } 243 244 dc_bluetooth_address_t 245 dc_bluetooth_str2addr(const char *str) 246 { 247 dc_bluetooth_address_t address = 0; 248 249 if (str == NULL) 250 return 0; 251 252 unsigned char c = 0; 253 while ((c = *str++) != '\0') { 254 if (c == ':') { 255 continue; 256 } else if (c >= '0' && c <= '9') { 257 c -= '0'; 258 } else if (c >= 'A' && c <= 'F') { 259 c -= 'A' - 10; 260 } else if (c >= 'a' && c <= 'f') { 261 c -= 'a' - 10; 262 } else { 263 return 0; /* Invalid character! */ 264 } 265 266 address <<= 4; 267 address |= c; 268 } 269 270 return address; 271 } 272 273 dc_bluetooth_address_t 274 dc_bluetooth_device_get_address (dc_bluetooth_device_t *device) 275 { 276 if (device == NULL) 277 return 0; 278 279 return device->address; 280 } 281 282 const char * 283 dc_bluetooth_device_get_name (dc_bluetooth_device_t *device) 284 { 285 if (device == NULL || device->name[0] == '\0') 286 return NULL; 287 288 return device->name; 289 } 290 291 void 292 dc_bluetooth_device_free (dc_bluetooth_device_t *device) 293 { 294 free (device); 295 } 296 297 dc_status_t 298 dc_bluetooth_iterator_new (dc_iterator_t **out, dc_context_t *context, dc_descriptor_t *descriptor) 299 { 300 #ifdef BLUETOOTH 301 dc_status_t status = DC_STATUS_SUCCESS; 302 dc_bluetooth_iterator_t *iterator = NULL; 303 304 if (out == NULL) 305 return DC_STATUS_INVALIDARGS; 306 307 iterator = (dc_bluetooth_iterator_t *) dc_iterator_allocate (context, &dc_bluetooth_iterator_vtable); 308 if (iterator == NULL) { 309 SYSERROR (context, S_ENOMEM); 310 return DC_STATUS_NOMEMORY; 311 } 312 313 // Initialize the socket library. 314 status = dc_socket_init (context); 315 if (status != DC_STATUS_SUCCESS) { 316 goto error_free; 317 } 318 319 #ifdef _WIN32 320 WSAQUERYSET wsaq; 321 memset(&wsaq, 0, sizeof (wsaq)); 322 wsaq.dwSize = sizeof (wsaq); 323 wsaq.dwNameSpace = NS_BTH; 324 wsaq.lpcsaBuffer = NULL; 325 326 HANDLE hLookup = NULL; 327 if (WSALookupServiceBegin(&wsaq, LUP_CONTAINERS | LUP_FLUSHCACHE, &hLookup) != 0) { 328 s_errcode_t errcode = S_ERRNO; 329 if (errcode == WSASERVICE_NOT_FOUND) { 330 // No remote bluetooth devices found. 331 hLookup = NULL; 332 } else { 333 SYSERROR (context, errcode); 334 status = dc_socket_syserror(errcode); 335 goto error_socket_exit; 336 } 337 } 338 339 iterator->hLookup = hLookup; 340 #else 341 // Get the resource number for the first available bluetooth adapter. 342 int dev = hci_get_route (NULL); 343 if (dev < 0) { 344 s_errcode_t errcode = S_ERRNO; 345 SYSERROR (context, errcode); 346 status = dc_socket_syserror(errcode); 347 goto error_socket_exit; 348 } 349 350 // Open a socket to the bluetooth adapter. 351 int fd = hci_open_dev (dev); 352 if (fd < 0) { 353 s_errcode_t errcode = S_ERRNO; 354 SYSERROR (context, errcode); 355 status = dc_socket_syserror(errcode); 356 goto error_socket_exit; 357 } 358 359 // Perform the bluetooth device discovery. The inquiry lasts for at 360 // most MAX_PERIODS * 1.28 seconds, and at most MAX_DEVICES devices 361 // will be returned. 362 inquiry_info *devices = NULL; 363 int ndevices = hci_inquiry (dev, MAX_PERIODS, MAX_DEVICES, NULL, &devices, IREQ_CACHE_FLUSH); 364 if (ndevices < 0) { 365 s_errcode_t errcode = S_ERRNO; 366 SYSERROR (context, errcode); 367 status = dc_socket_syserror(errcode); 368 goto error_close; 369 } 370 371 iterator->fd = fd; 372 iterator->devices = devices; 373 iterator->count = ndevices; 374 iterator->current = 0; 375 #endif 376 iterator->descriptor = descriptor; 377 378 *out = (dc_iterator_t *) iterator; 379 380 return DC_STATUS_SUCCESS; 381 382 #ifndef _WIN32 383 error_close: 384 hci_close_dev(fd); 385 #endif 386 error_socket_exit: 387 dc_socket_exit (context); 388 error_free: 389 dc_iterator_deallocate ((dc_iterator_t *) iterator); 390 return status; 391 #else 392 return DC_STATUS_UNSUPPORTED; 393 #endif 394 } 395 396 #ifdef BLUETOOTH 397 static dc_status_t 398 dc_bluetooth_iterator_next (dc_iterator_t *abstract, void *out) 399 { 400 dc_bluetooth_iterator_t *iterator = (dc_bluetooth_iterator_t *) abstract; 401 dc_bluetooth_device_t *device = NULL; 402 403 #ifdef _WIN32 404 if (iterator->hLookup == NULL) { 405 return DC_STATUS_DONE; 406 } 407 408 unsigned char buf[4096]; 409 LPWSAQUERYSET pwsaResults = (LPWSAQUERYSET) buf; 410 memset(pwsaResults, 0, sizeof(WSAQUERYSET)); 411 pwsaResults->dwSize = sizeof(WSAQUERYSET); 412 pwsaResults->dwNameSpace = NS_BTH; 413 pwsaResults->lpBlob = NULL; 414 415 while (1) { 416 DWORD dwSize = sizeof(buf); 417 if (WSALookupServiceNext (iterator->hLookup, LUP_RETURN_NAME | LUP_RETURN_ADDR, &dwSize, pwsaResults) != 0) { 418 s_errcode_t errcode = S_ERRNO; 419 if (errcode == WSA_E_NO_MORE || errcode == WSAENOMORE) { 420 break; // No more results. 421 } 422 SYSERROR (abstract->context, errcode); 423 return dc_socket_syserror(errcode); 424 } 425 426 if (pwsaResults->dwNumberOfCsAddrs == 0 || 427 pwsaResults->lpcsaBuffer == NULL || 428 pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr == NULL) { 429 ERROR (abstract->context, "Invalid results returned"); 430 return DC_STATUS_IO; 431 } 432 433 SOCKADDR_BTH *sa = (SOCKADDR_BTH *) pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr; 434 dc_bluetooth_address_t address = sa->btAddr; 435 const char *name = (char *) pwsaResults->lpszServiceInstanceName; 436 #else 437 while (iterator->current < iterator->count) { 438 inquiry_info *dev = &iterator->devices[iterator->current++]; 439 440 dc_bluetooth_address_t address = dc_address_get (&dev->bdaddr); 441 442 // Get the user friendly name. 443 char buf[HCI_MAX_NAME_LENGTH], *name = buf; 444 int rc = hci_read_remote_name (iterator->fd, &dev->bdaddr, sizeof(buf), buf, 0); 445 if (rc < 0) { 446 name = NULL; 447 } 448 449 // Null terminate the string. 450 buf[sizeof(buf) - 1] = '\0'; 451 #endif 452 453 INFO (abstract->context, "Discover: address=" DC_ADDRESS_FORMAT ", name=%s", 454 address, name ? name : ""); 455 456 if (!dc_descriptor_filter (iterator->descriptor, DC_TRANSPORT_BLUETOOTH, name)) { 457 continue; 458 } 459 460 device = (dc_bluetooth_device_t *) malloc (sizeof(dc_bluetooth_device_t)); 461 if (device == NULL) { 462 SYSERROR (abstract->context, S_ENOMEM); 463 return DC_STATUS_NOMEMORY; 464 } 465 466 device->address = address; 467 if (name) { 468 strncpy(device->name, name, sizeof(device->name) - 1); 469 device->name[sizeof(device->name) - 1] = '\0'; 470 } else { 471 memset(device->name, 0, sizeof(device->name)); 472 } 473 474 *(dc_bluetooth_device_t **) out = device; 475 476 return DC_STATUS_SUCCESS; 477 } 478 479 return DC_STATUS_DONE; 480 } 481 482 static dc_status_t 483 dc_bluetooth_iterator_free (dc_iterator_t *abstract) 484 { 485 dc_bluetooth_iterator_t *iterator = (dc_bluetooth_iterator_t *) abstract; 486 487 #ifdef _WIN32 488 if (iterator->hLookup) { 489 WSALookupServiceEnd (iterator->hLookup); 490 } 491 #else 492 bt_free(iterator->devices); 493 hci_close_dev(iterator->fd); 494 #endif 495 dc_socket_exit (abstract->context); 496 497 return DC_STATUS_SUCCESS; 498 } 499 #endif 500 501 dc_status_t 502 dc_bluetooth_open (dc_iostream_t **out, dc_context_t *context, dc_bluetooth_address_t address, unsigned int port) 503 { 504 #ifdef BLUETOOTH 505 dc_status_t status = DC_STATUS_SUCCESS; 506 dc_socket_t *device = NULL; 507 508 if (out == NULL) 509 return DC_STATUS_INVALIDARGS; 510 511 INFO (context, "Open: address=" DC_ADDRESS_FORMAT ", port=%u", address, port); 512 513 // Allocate memory. 514 device = (dc_socket_t *) dc_iostream_allocate (context, &dc_bluetooth_vtable, DC_TRANSPORT_BLUETOOTH); 515 if (device == NULL) { 516 SYSERROR (context, S_ENOMEM); 517 return DC_STATUS_NOMEMORY; 518 } 519 520 // Open the socket. 521 #ifdef _WIN32 522 status = dc_socket_open (&device->base, AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); 523 #else 524 status = dc_socket_open (&device->base, AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM); 525 #endif 526 if (status != DC_STATUS_SUCCESS) { 527 goto error_free; 528 } 529 530 #ifdef _WIN32 531 SOCKADDR_BTH sa; 532 sa.addressFamily = AF_BTH; 533 sa.btAddr = address; 534 sa.port = port; 535 if (port == 0) { 536 sa.serviceClassId = SerialPortServiceClass_UUID; 537 } else { 538 memset(&sa.serviceClassId, 0, sizeof(sa.serviceClassId)); 539 } 540 #else 541 struct sockaddr_rc sa; 542 sa.rc_family = AF_BLUETOOTH; 543 dc_address_set (&sa.rc_bdaddr, address); 544 if (port == 0) { 545 status = dc_bluetooth_sdp (&sa.rc_channel, context, &sa.rc_bdaddr); 546 if (status != DC_STATUS_SUCCESS) { 547 goto error_close; 548 } 549 } else { 550 sa.rc_channel = port; 551 } 552 #endif 553 554 status = dc_socket_connect (&device->base, (struct sockaddr *) &sa, sizeof (sa)); 555 if (status != DC_STATUS_SUCCESS) { 556 goto error_close; 557 } 558 559 *out = (dc_iostream_t *) device; 560 561 return DC_STATUS_SUCCESS; 562 563 error_close: 564 dc_socket_close (&device->base); 565 error_free: 566 dc_iostream_deallocate ((dc_iostream_t *) device); 567 return status; 568 #else 569 return DC_STATUS_UNSUPPORTED; 570 #endif 571 }