1 /* 2 * Copyright (C) 2014 BlueKitchen GmbH 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions 6 * are met: 7 * 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 3. Neither the name of the copyright holders nor the names of 14 * contributors may be used to endorse or promote products derived 15 * from this software without specific prior written permission. 16 * 4. Any redistribution, use, or modification is done solely for 17 * personal benefit and not for any commercial purpose or for 18 * monetary gain. 19 * 20 * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS 24 * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 25 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS 27 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF 30 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 31 * SUCH DAMAGE. 32 * 33 * Please inquire about commercial licensing options at 34 * [email protected] 35 * 36 */ 37 38 #define __BTSTACK_FILE__ "socket_connection.c" 39 40 /* 41 * SocketServer.c 42 * 43 * Handles multiple connections to a single socket without blocking 44 * 45 * Created by Matthias Ringwald on 6/6/09. 46 * 47 */ 48 49 #include "socket_connection.h" 50 51 #include "hci.h" 52 #include "btstack_debug.h" 53 54 #include "btstack_config.h" 55 56 #include "btstack.h" 57 #include "btstack_client.h" 58 59 #include <errno.h> 60 #include <fcntl.h> 61 #include <signal.h> 62 #include <stdint.h> 63 #include <stdio.h> 64 #include <string.h> 65 #include <unistd.h> 66 67 #include <sys/stat.h> 68 69 #ifndef _WIN32 70 #include <arpa/inet.h> 71 #include <netdb.h> 72 #include <sys/socket.h> 73 #include <sys/un.h> 74 #endif 75 76 #ifdef _WIN32 77 #include "Winsock2.h" 78 // define missing types 79 typedef int32_t socklen_t; 80 // 81 #define UNIX_PATH_MAX 108 82 struct sockaddr_un { 83 uint16_t sun_family; 84 char sun_path[UNIX_PATH_MAX]; 85 }; 86 // 87 #define S_IRWXG 0 88 #define S_IRWXO 0 89 #endif 90 91 #ifdef USE_LAUNCHD 92 #include "../port/ios/3rdparty/launch.h" 93 #endif 94 95 #define MAX_PENDING_CONNECTIONS 10 96 97 /** prototypes */ 98 static void socket_connection_hci_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type); 99 static int socket_connection_dummy_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length); 100 101 /** globals */ 102 103 /** packet header used over socket connections, in front of the HCI packet */ 104 typedef struct packet_header { 105 uint16_t type; 106 uint16_t channel; 107 uint16_t length; 108 uint8_t data[0]; 109 } packet_header_t; // 6 110 111 typedef enum { 112 SOCKET_W4_HEADER, 113 SOCKET_W4_DATA 114 } SOCKET_STATE; 115 116 typedef struct linked_connection { 117 btstack_linked_item_t item; 118 connection_t * connection; 119 } linked_connection_t; 120 121 struct connection { 122 btstack_data_source_t ds; // used for run loop 123 linked_connection_t linked_connection; // used for connection list 124 SOCKET_STATE state; 125 uint16_t bytes_read; 126 uint16_t bytes_to_read; 127 uint8_t buffer[6+HCI_ACL_BUFFER_SIZE]; // packet_header(6) + max packet: 3-DH5 = header(6) + payload (1021) 128 }; 129 130 /** list of socket connections */ 131 static btstack_linked_list_t connections = NULL; 132 static btstack_linked_list_t parked = NULL; 133 134 135 /** client packet handler */ 136 137 static int (*socket_connection_packet_callback)(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length) = socket_connection_dummy_handler; 138 139 static int socket_connection_dummy_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){ 140 UNUSED(connection); 141 UNUSED(packet_type); 142 UNUSED(channel); 143 UNUSED(data); 144 UNUSED(length); 145 return 0; 146 } 147 148 static void socket_connection_free_connection(connection_t *conn){ 149 // remove from run_loop 150 btstack_run_loop_remove_data_source(&conn->ds); 151 152 // and from connection list 153 btstack_linked_list_remove(&connections, &conn->linked_connection.item); 154 155 // destroy 156 free(conn); 157 } 158 159 static void socket_connection_init_statemachine(connection_t *connection){ 160 // wait for next packet 161 connection->state = SOCKET_W4_HEADER; 162 connection->bytes_read = 0; 163 connection->bytes_to_read = sizeof(packet_header_t); 164 } 165 166 static connection_t * socket_connection_register_new_connection(int fd){ 167 // create connection objec 168 connection_t * conn = malloc( sizeof(connection_t)); 169 if (conn == NULL) return 0; 170 171 // store reference from linked item to base object 172 conn->linked_connection.connection = conn; 173 174 btstack_run_loop_set_data_source_handler(&conn->ds, &socket_connection_hci_process); 175 btstack_run_loop_set_data_source_fd(&conn->ds, fd); 176 btstack_run_loop_enable_data_source_callbacks(&conn->ds, DATA_SOURCE_CALLBACK_READ); 177 178 // prepare state machine and 179 socket_connection_init_statemachine(conn); 180 181 // add this socket to the run_loop 182 btstack_run_loop_add_data_source( &conn->ds ); 183 184 // and the connection list 185 btstack_linked_list_add( &connections, &conn->linked_connection.item); 186 187 return conn; 188 } 189 190 void static socket_connection_emit_connection_opened(connection_t *connection){ 191 uint8_t event[1]; 192 event[0] = DAEMON_EVENT_CONNECTION_OPENED; 193 (*socket_connection_packet_callback)(connection, DAEMON_EVENT_PACKET, 0, (uint8_t *) &event, 1); 194 } 195 196 void static socket_connection_emit_connection_closed(connection_t *connection){ 197 uint8_t event[1]; 198 event[0] = DAEMON_EVENT_CONNECTION_CLOSED; 199 (*socket_connection_packet_callback)(connection, DAEMON_EVENT_PACKET, 0, (uint8_t *) &event, 1); 200 } 201 202 void socket_connection_hci_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) { 203 UNUSED(callback_type); 204 connection_t *conn = (connection_t *) ds; 205 int fd = btstack_run_loop_get_data_source_fd(ds); 206 int bytes_read = read(fd, &conn->buffer[conn->bytes_read], conn->bytes_to_read); 207 if (bytes_read <= 0){ 208 // connection broken (no particular channel, no date yet) 209 socket_connection_emit_connection_closed(conn); 210 211 // free connection 212 socket_connection_free_connection(conn); 213 214 return; 215 } 216 conn->bytes_read += bytes_read; 217 conn->bytes_to_read -= bytes_read; 218 if (conn->bytes_to_read > 0) return; 219 220 int dispatch = 0; 221 switch (conn->state){ 222 case SOCKET_W4_HEADER: 223 conn->state = SOCKET_W4_DATA; 224 conn->bytes_to_read = little_endian_read_16( conn->buffer, 4); 225 if (conn->bytes_to_read == 0){ 226 dispatch = 1; 227 } 228 break; 229 case SOCKET_W4_DATA: 230 dispatch = 1; 231 break; 232 default: 233 break; 234 } 235 236 if (dispatch){ 237 // dispatch packet !!! connection, type, channel, data, size 238 int dispatch_err = (*socket_connection_packet_callback)(conn, little_endian_read_16( conn->buffer, 0), little_endian_read_16( conn->buffer, 2), 239 &conn->buffer[sizeof(packet_header_t)], little_endian_read_16( conn->buffer, 4)); 240 241 // reset state machine 242 socket_connection_init_statemachine(conn); 243 244 // "park" if dispatch failed 245 if (dispatch_err) { 246 log_info("socket_connection_hci_process dispatch failed -> park connection"); 247 btstack_run_loop_remove_data_source(ds); 248 btstack_linked_list_add_tail(&parked, (btstack_linked_item_t *) ds); 249 } 250 } 251 } 252 253 /** 254 * try to dispatch packet for all "parked" connections. 255 * if dispatch is successful, a connection is added again to run loop 256 * pre: connections get parked iff packet was dispatched but could not be sent 257 */ 258 void socket_connection_retry_parked(void){ 259 // log_info("socket_connection_hci_process retry parked"); 260 btstack_linked_item_t *it = (btstack_linked_item_t *) &parked; 261 while (it->next) { 262 connection_t * conn = (connection_t *) it->next; 263 264 // dispatch packet !!! connection, type, channel, data, size 265 uint16_t packet_type = little_endian_read_16( conn->buffer, 0); 266 uint16_t channel = little_endian_read_16( conn->buffer, 2); 267 uint16_t length = little_endian_read_16( conn->buffer, 4); 268 log_info("socket_connection_hci_process retry parked %p (type %u, channel %04x, length %u", conn, packet_type, channel, length); 269 int dispatch_err = (*socket_connection_packet_callback)(conn, packet_type, channel, &conn->buffer[sizeof(packet_header_t)], length); 270 // "un-park" if successful 271 if (!dispatch_err) { 272 log_info("socket_connection_hci_process dispatch succeeded -> un-park connection %p", conn); 273 it->next = it->next->next; 274 btstack_run_loop_add_data_source( (btstack_data_source_t *) conn); 275 } else { 276 it = it->next; 277 } 278 } 279 } 280 281 int socket_connection_has_parked_connections(void){ 282 return parked != NULL; 283 } 284 285 static void socket_connection_accept(btstack_data_source_t *socket_ds, btstack_data_source_callback_type_t callback_type) { 286 UNUSED(callback_type); 287 struct sockaddr_storage ss; 288 socklen_t slen = sizeof(ss); 289 int socket_fd = btstack_run_loop_get_data_source_fd(socket_ds); 290 291 /* New connection coming in! */ 292 int fd = accept(socket_fd, (struct sockaddr *)&ss, &slen); 293 if (fd < 0) { 294 perror("accept"); 295 return; 296 } 297 298 log_info("socket_connection_accept new connection %u", fd); 299 300 connection_t * connection = socket_connection_register_new_connection(fd); 301 socket_connection_emit_connection_opened(connection); 302 } 303 304 /** 305 * create socket data_source for tcp socket 306 * 307 * @return data_source object. If null, check errno 308 */ 309 int socket_connection_create_tcp(int port){ 310 311 // create btstack_data_source_t 312 btstack_data_source_t *ds = calloc(sizeof(btstack_data_source_t), 1); 313 if (ds == NULL) return -1; 314 315 // create tcp socket 316 int fd = socket (PF_INET, SOCK_STREAM, 0); 317 if (fd < 0) { 318 log_error("Error creating socket ...(%s)", strerror(errno)); 319 free(ds); 320 return -1; 321 } 322 323 log_info ("Socket created for port %u", port); 324 325 struct sockaddr_in addr; 326 addr.sin_family = AF_INET; 327 addr.sin_port = htons (port); 328 memset (&addr.sin_addr, 0, sizeof (addr.sin_addr)); 329 330 const int y = 1; 331 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*) &y, sizeof(int)); 332 333 if (bind ( fd, (struct sockaddr *) &addr, sizeof (addr) ) ) { 334 log_error("Error on bind() ...(%s)", strerror(errno)); 335 free(ds); 336 return -1; 337 } 338 339 if (listen (fd, MAX_PENDING_CONNECTIONS)) { 340 log_error("Error on listen() ...(%s)", strerror(errno)); 341 free(ds); 342 return -1; 343 } 344 345 btstack_run_loop_set_data_source_fd(ds, fd); 346 btstack_run_loop_set_data_source_handler(ds, &socket_connection_accept); 347 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ); 348 btstack_run_loop_add_data_source(ds); 349 350 log_info ("Server up and running ..."); 351 return 0; 352 } 353 354 #ifdef USE_LAUNCHD 355 356 /* 357 * Register listening sockets with our run loop 358 */ 359 void socket_connection_launchd_register_fd_array(launch_data_t listening_fd_array){ 360 int i; 361 for (i = 0; i < launch_data_array_get_count(listening_fd_array); i++) { 362 // get fd 363 launch_data_t tempi = launch_data_array_get_index (listening_fd_array, i); 364 int listening_fd = launch_data_get_fd(tempi); 365 launch_data_free (tempi); 366 log_info("file descriptor = %u", listening_fd); 367 368 // create btstack_data_source_t for fd 369 btstack_data_source_t *ds = calloc(sizeof(btstack_data_source_t), 1); 370 if (ds == NULL) return; 371 btstack_run_loop_set_data_source_fd(ds, listening_fd); 372 btstack_run_loop_set_data_source_handler(ds, &socket_connection_accept); 373 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ); 374 btstack_run_loop_add_data_source(ds); 375 } 376 } 377 378 /** 379 * create socket data_source for socket specified by launchd configuration 380 */ 381 int socket_connection_create_launchd(void){ 382 383 launch_data_t sockets_dict, checkin_response; 384 launch_data_t checkin_request; 385 launch_data_t listening_fd_array; 386 387 /* 388 * Register ourselves with launchd. 389 * 390 */ 391 if ((checkin_request = launch_data_new_string(LAUNCH_KEY_CHECKIN)) == NULL) { 392 log_error( "launch_data_new_string(\"" LAUNCH_KEY_CHECKIN "\") Unable to create string."); 393 return -1; 394 } 395 396 if ((checkin_response = launch_msg(checkin_request)) == NULL) { 397 log_error( "launch_msg(\"" LAUNCH_KEY_CHECKIN "\") IPC failure: %u", errno); 398 return -1; 399 } 400 401 if (LAUNCH_DATA_ERRNO == launch_data_get_type(checkin_response)) { 402 errno = launch_data_get_errno(checkin_response); 403 log_error( "Check-in failed: %u", errno); 404 return -1; 405 } 406 407 launch_data_t the_label = launch_data_dict_lookup(checkin_response, LAUNCH_JOBKEY_LABEL); 408 if (NULL == the_label) { 409 log_error( "No label found"); 410 return -1; 411 } 412 413 /* 414 * Retrieve the dictionary of Socket entries in the config file 415 */ 416 sockets_dict = launch_data_dict_lookup(checkin_response, LAUNCH_JOBKEY_SOCKETS); 417 if (NULL == sockets_dict) { 418 log_error("No sockets found to answer requests on!"); 419 return -1; 420 } 421 422 // if (launch_data_dict_get_count(sockets_dict) > 1) { 423 // log_error("Some sockets will be ignored!"); 424 // } 425 426 /* 427 * Get the dictionary value from the key "Listeners" 428 */ 429 listening_fd_array = launch_data_dict_lookup(sockets_dict, "Listeners"); 430 if (listening_fd_array) { 431 // log_error("Listeners..."); 432 socket_connection_launchd_register_fd_array( listening_fd_array ); 433 } 434 435 /* 436 * Get the dictionary value from the key "Listeners" 437 */ 438 listening_fd_array = launch_data_dict_lookup(sockets_dict, "Listeners2"); 439 if (listening_fd_array) { 440 // log_error("Listeners2..."); 441 socket_connection_launchd_register_fd_array( listening_fd_array ); 442 } 443 444 // although used in Apple examples, it creates a malloc warning 445 // launch_data_free(checkin_response); 446 return 0; 447 } 448 #endif 449 450 /** 451 * create socket data_source for unix domain socket 452 */ 453 int socket_connection_create_unix(char *path){ 454 455 // create btstack_data_source_t 456 btstack_data_source_t *ds = calloc(sizeof(btstack_data_source_t), 1); 457 if (ds == NULL) return -1; 458 459 // create unix socket 460 int fd = socket (AF_UNIX, SOCK_STREAM, 0); 461 if (fd < 0) { 462 log_error( "Error creating socket ...(%s)", strerror(errno)); 463 free(ds); 464 return -1; 465 } 466 log_info ("Socket created at %s", path); 467 468 struct sockaddr_un addr; 469 memset(&addr, 0, sizeof(addr)); 470 addr.sun_family = AF_UNIX; 471 strcpy(addr.sun_path, path); 472 unlink(path); 473 474 const int y = 1; 475 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (void*) &y, sizeof(int)); 476 477 if (bind (fd, (struct sockaddr *) &addr, sizeof (addr) ) ) { 478 log_error( "Error on bind() ...(%s)", strerror(errno)); 479 free(ds); 480 return -1; 481 } 482 483 // http://blog.henning.makholm.net/2008/06/unix-domain-socket-woes.html 484 // make socket accept from all clients 485 chmod(path, S_IRWXU | S_IRWXG | S_IRWXO); 486 // 487 488 if (listen(fd, MAX_PENDING_CONNECTIONS)) { 489 log_error( "Error on listen() ...(%s)", strerror(errno)); 490 free(ds); 491 return -1; 492 } 493 494 btstack_run_loop_set_data_source_fd(ds, fd); 495 btstack_run_loop_set_data_source_handler(ds, &socket_connection_accept); 496 btstack_run_loop_enable_data_source_callbacks(ds, DATA_SOURCE_CALLBACK_READ); 497 btstack_run_loop_add_data_source(ds); 498 499 log_info ("Server up and running ..."); 500 return 0; 501 } 502 503 /** 504 * set packet handler for all auto-accepted connections 505 */ 506 void socket_connection_register_packet_callback( int (*packet_callback)(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length) ){ 507 socket_connection_packet_callback = packet_callback; 508 } 509 510 /** 511 * send HCI packet to single connection 512 */ 513 void socket_connection_send_packet(connection_t *conn, uint16_t type, uint16_t channel, uint8_t *packet, uint16_t size){ 514 uint8_t header[sizeof(packet_header_t)]; 515 little_endian_store_16(header, 0, type); 516 little_endian_store_16(header, 2, channel); 517 little_endian_store_16(header, 4, size); 518 write(conn->ds.fd, header, 6); 519 write(conn->ds.fd, packet, size); 520 } 521 522 /** 523 * send HCI packet to all connections 524 */ 525 void socket_connection_send_packet_all(uint16_t type, uint16_t channel, uint8_t *packet, uint16_t size){ 526 btstack_linked_item_t *next; 527 btstack_linked_item_t *it; 528 for (it = (btstack_linked_item_t *) connections; it ; it = next){ 529 next = it->next; // cache pointer to next connection_t to allow for removal 530 linked_connection_t * linked_connection = (linked_connection_t *) it; 531 socket_connection_send_packet( linked_connection->connection, type, channel, packet, size); 532 } 533 } 534 535 /** 536 * create socket connection to BTdaemon 537 */ 538 connection_t * socket_connection_open_tcp(const char *address, uint16_t port){ 539 // TCP 540 struct protoent* tcp = getprotobyname("tcp"); 541 542 int btsocket = socket(PF_INET, SOCK_STREAM, tcp->p_proto); 543 if(btsocket == -1){ 544 return NULL; 545 } 546 // localhost 547 struct sockaddr_in btdaemon_address; 548 btdaemon_address.sin_family = AF_INET; 549 btdaemon_address.sin_port = htons(port); 550 struct hostent* localhost = gethostbyname(address); 551 if(!localhost){ 552 return NULL; 553 } 554 // connect 555 char* addr = localhost->h_addr_list[0]; 556 memcpy(&btdaemon_address.sin_addr.s_addr, addr, sizeof (struct in_addr)); 557 if(connect(btsocket, (struct sockaddr*)&btdaemon_address, sizeof (btdaemon_address)) == -1){ 558 return NULL; 559 } 560 561 return socket_connection_register_new_connection(btsocket); 562 } 563 564 565 /** 566 * close socket connection to BTdaemon 567 */ 568 int socket_connection_close_tcp(connection_t * connection){ 569 if (!connection) return -1; 570 #ifdef _WIN32 571 shutdown(connection->ds.fd, SD_BOTH); 572 #else 573 shutdown(connection->ds.fd, SHUT_RDWR); 574 #endif 575 socket_connection_free_connection(connection); 576 return 0; 577 } 578 579 580 /** 581 * create socket connection to BTdaemon 582 */ 583 connection_t * socket_connection_open_unix(void){ 584 585 int btsocket = socket(AF_UNIX, SOCK_STREAM, 0); 586 if(btsocket == -1){ 587 return NULL; 588 } 589 590 struct sockaddr_un server; 591 memset(&server, 0, sizeof(server)); 592 server.sun_family = AF_UNIX; 593 strcpy(server.sun_path, BTSTACK_UNIX); 594 if (connect(btsocket, (struct sockaddr *)&server, sizeof (server)) == -1){ 595 return NULL; 596 }; 597 598 return socket_connection_register_new_connection(btsocket); 599 } 600 601 602 /** 603 * close socket connection to BTdaemon 604 */ 605 int socket_connection_close_unix(connection_t * connection){ 606 if (!connection) return -1; 607 #ifdef _WIN32 608 shutdown(connection->ds.fd, SD_BOTH); 609 #else 610 shutdown(connection->ds.fd, SHUT_RDWR); 611 #endif 612 socket_connection_free_connection(connection); 613 return 0; 614 } 615 616 /** 617 * Init socket connection module 618 */ 619 void socket_connection_init(void){ 620 // just ignore broken sockets - NO_SO_SIGPIPE 621 #ifndef _WIN32 622 sig_t result = signal(SIGPIPE, SIG_IGN); 623 if (result){ 624 log_error("socket_connection_init: failed to ignore SIGPIPE, error: %s", strerror(errno)); 625 } 626 #endif 627 } 628 629 630