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 /* 39 * SocketServer.c 40 * 41 * Handles multiple connections to a single socket without blocking 42 * 43 * Created by Matthias Ringwald on 6/6/09. 44 * 45 */ 46 47 #include "socket_connection.h" 48 49 #include "hci.h" 50 #include "btstack_debug.h" 51 52 #include "btstack_config.h" 53 54 #include "btstack.h" 55 #include "btstack_client.h" 56 57 #include <errno.h> 58 #include <fcntl.h> 59 #include <stdio.h> 60 #include <stdint.h> 61 #include <string.h> 62 #include <unistd.h> 63 64 #include <sys/stat.h> 65 66 #ifndef _WIN32 67 #include <arpa/inet.h> 68 #include <netdb.h> 69 #include <sys/socket.h> 70 #include <sys/un.h> 71 #endif 72 73 #ifdef _WIN32 74 #include "Winsock2.h" 75 // define missing types 76 typedef int32_t socklen_t; 77 // 78 #define UNIX_PATH_MAX 108 79 struct sockaddr_un { 80 uint16_t sun_family; 81 char sun_path[UNIX_PATH_MAX]; 82 }; 83 // 84 #define S_IRWXG 0 85 #define S_IRWXO 0 86 #endif 87 88 #ifdef USE_LAUNCHD 89 #include "../port/ios/3rdparty/launch.h" 90 #endif 91 92 #define MAX_PENDING_CONNECTIONS 10 93 94 /** prototypes */ 95 static void socket_connection_hci_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type); 96 static int socket_connection_dummy_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length); 97 98 /** globals */ 99 100 /** packet header used over socket connections, in front of the HCI packet */ 101 typedef struct packet_header { 102 uint16_t type; 103 uint16_t channel; 104 uint16_t length; 105 uint8_t data[0]; 106 } packet_header_t; // 6 107 108 typedef enum { 109 SOCKET_W4_HEADER, 110 SOCKET_W4_DATA 111 } SOCKET_STATE; 112 113 typedef struct linked_connection { 114 btstack_linked_item_t item; 115 connection_t * connection; 116 } linked_connection_t; 117 118 struct connection { 119 btstack_data_source_t ds; // used for run loop 120 linked_connection_t linked_connection; // used for connection list 121 SOCKET_STATE state; 122 uint16_t bytes_read; 123 uint16_t bytes_to_read; 124 uint8_t buffer[6+HCI_ACL_BUFFER_SIZE]; // packet_header(6) + max packet: 3-DH5 = header(6) + payload (1021) 125 }; 126 127 /** list of socket connections */ 128 static btstack_linked_list_t connections = NULL; 129 static btstack_linked_list_t parked = NULL; 130 131 132 /** client packet handler */ 133 134 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; 135 136 static int socket_connection_dummy_handler(connection_t *connection, uint16_t packet_type, uint16_t channel, uint8_t *data, uint16_t length){ 137 return 0; 138 } 139 140 void socket_connection_set_no_sigpipe(int fd){ 141 #ifdef HAVE_SO_NOSIGPIPE 142 int set = 1; 143 setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int)); 144 #endif 145 } 146 147 void socket_connection_free_connection(connection_t *conn){ 148 // remove from run_loop 149 btstack_run_loop_remove_data_source(&conn->ds); 150 151 // and from connection list 152 btstack_linked_list_remove(&connections, &conn->linked_connection.item); 153 154 // destroy 155 free(conn); 156 } 157 158 void socket_connection_init_statemachine(connection_t *connection){ 159 // wait for next packet 160 connection->state = SOCKET_W4_HEADER; 161 connection->bytes_read = 0; 162 connection->bytes_to_read = sizeof(packet_header_t); 163 } 164 165 connection_t * socket_connection_register_new_connection(int fd){ 166 // create connection objec 167 connection_t * conn = malloc( sizeof(connection_t)); 168 if (conn == NULL) return 0; 169 170 // store reference from linked item to base object 171 conn->linked_connection.connection = conn; 172 173 btstack_run_loop_set_data_source_handler(&conn->ds, &socket_connection_hci_process); 174 btstack_run_loop_set_data_source_fd(&conn->ds, fd); 175 176 // prepare state machine and 177 socket_connection_init_statemachine(conn); 178 179 // add this socket to the run_loop 180 btstack_run_loop_add_data_source( &conn->ds ); 181 182 // and the connection list 183 btstack_linked_list_add( &connections, &conn->linked_connection.item); 184 185 return conn; 186 } 187 188 void static socket_connection_emit_connection_opened(connection_t *connection){ 189 uint8_t event[1]; 190 event[0] = DAEMON_EVENT_CONNECTION_OPENED; 191 (*socket_connection_packet_callback)(connection, DAEMON_EVENT_PACKET, 0, (uint8_t *) &event, 1); 192 } 193 194 void static socket_connection_emit_connection_closed(connection_t *connection){ 195 uint8_t event[1]; 196 event[0] = DAEMON_EVENT_CONNECTION_CLOSED; 197 (*socket_connection_packet_callback)(connection, DAEMON_EVENT_PACKET, 0, (uint8_t *) &event, 1); 198 } 199 200 void socket_connection_hci_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) { 201 connection_t *conn = (connection_t *) ds; 202 int fd = btstack_run_loop_get_data_source_fd(ds); 203 int bytes_read = read(fd, &conn->buffer[conn->bytes_read], conn->bytes_to_read); 204 if (bytes_read <= 0){ 205 // connection broken (no particular channel, no date yet) 206 socket_connection_emit_connection_closed(conn); 207 208 // free connection 209 socket_connection_free_connection(conn); 210 211 return; 212 } 213 conn->bytes_read += bytes_read; 214 conn->bytes_to_read -= bytes_read; 215 if (conn->bytes_to_read > 0) return; 216 217 int dispatch = 0; 218 switch (conn->state){ 219 case SOCKET_W4_HEADER: 220 conn->state = SOCKET_W4_DATA; 221 conn->bytes_to_read = little_endian_read_16( conn->buffer, 4); 222 if (conn->bytes_to_read == 0){ 223 dispatch = 1; 224 } 225 break; 226 case SOCKET_W4_DATA: 227 dispatch = 1; 228 break; 229 default: 230 break; 231 } 232 233 if (dispatch){ 234 // dispatch packet !!! connection, type, channel, data, size 235 int dispatch_err = (*socket_connection_packet_callback)(conn, little_endian_read_16( conn->buffer, 0), little_endian_read_16( conn->buffer, 2), 236 &conn->buffer[sizeof(packet_header_t)], little_endian_read_16( conn->buffer, 4)); 237 238 // reset state machine 239 socket_connection_init_statemachine(conn); 240 241 // "park" if dispatch failed 242 if (dispatch_err) { 243 log_info("socket_connection_hci_process dispatch failed -> park connection"); 244 btstack_run_loop_remove_data_source(ds); 245 btstack_linked_list_add_tail(&parked, (btstack_linked_item_t *) ds); 246 } 247 } 248 } 249 250 /** 251 * try to dispatch packet for all "parked" connections. 252 * if dispatch is successful, a connection is added again to run loop 253 * pre: connections get parked iff packet was dispatched but could not be sent 254 */ 255 void socket_connection_retry_parked(void){ 256 // log_info("socket_connection_hci_process retry parked"); 257 btstack_linked_item_t *it = (btstack_linked_item_t *) &parked; 258 while (it->next) { 259 connection_t * conn = (connection_t *) it->next; 260 261 // dispatch packet !!! connection, type, channel, data, size 262 uint16_t packet_type = little_endian_read_16( conn->buffer, 0); 263 uint16_t channel = little_endian_read_16( conn->buffer, 2); 264 uint16_t length = little_endian_read_16( conn->buffer, 4); 265 log_info("socket_connection_hci_process retry parked %p (type %u, channel %04x, length %u", conn, packet_type, channel, length); 266 int dispatch_err = (*socket_connection_packet_callback)(conn, packet_type, channel, &conn->buffer[sizeof(packet_header_t)], length); 267 // "un-park" if successful 268 if (!dispatch_err) { 269 log_info("socket_connection_hci_process dispatch succeeded -> un-park connection %p", conn); 270 it->next = it->next->next; 271 btstack_run_loop_add_data_source( (btstack_data_source_t *) conn); 272 } else { 273 it = it->next; 274 } 275 } 276 } 277 278 int socket_connection_has_parked_connections(void){ 279 return parked != NULL; 280 } 281 282 static void socket_connection_accept(btstack_data_source_t *socket_ds, btstack_data_source_callback_type_t callback_type) { 283 struct sockaddr_storage ss; 284 socklen_t slen = sizeof(ss); 285 int socket_fd = btstack_run_loop_get_data_source_fd(socket_ds); 286 287 /* New connection coming in! */ 288 int fd = accept(socket_fd, (struct sockaddr *)&ss, &slen); 289 if (fd < 0) { 290 perror("accept"); 291 return; 292 } 293 294 // no sigpipe 295 socket_connection_set_no_sigpipe(fd); 296 297 log_info("socket_connection_accept new connection %u", fd); 298 299 connection_t * connection = socket_connection_register_new_connection(fd); 300 socket_connection_emit_connection_opened(connection); 301 } 302 303 /** 304 * create socket data_source for tcp socket 305 * 306 * @return data_source object. If null, check errno 307 */ 308 int socket_connection_create_tcp(int port){ 309 310 // create btstack_data_source_t 311 btstack_data_source_t *ds = malloc( sizeof(btstack_data_source_t)); 312 if (ds == NULL) return -1; 313 memset(ds, 0, sizeof(btstack_data_source_t)); 314 btstack_run_loop_set_data_source_handler(ds, &socket_connection_accept); 315 316 // create tcp socket 317 if ((ds->fd = socket (PF_INET, SOCK_STREAM, 0)) < 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(ds->fd, SOL_SOCKET, SO_REUSEADDR, (void*) &y, sizeof(int)); 332 333 if (bind ( ds->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 (ds->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_add_data_source(ds); 346 347 log_info ("Server up and running ..."); 348 return 0; 349 } 350 351 #ifdef USE_LAUNCHD 352 353 /* 354 * Register listening sockets with our run loop 355 */ 356 void socket_connection_launchd_register_fd_array(launch_data_t listening_fd_array){ 357 int i; 358 for (i = 0; i < launch_data_array_get_count(listening_fd_array); i++) { 359 // get fd 360 launch_data_t tempi = launch_data_array_get_index (listening_fd_array, i); 361 int listening_fd = launch_data_get_fd(tempi); 362 launch_data_free (tempi); 363 log_info("file descriptor = %u", listening_fd); 364 365 // create btstack_data_source_t for fd 366 btstack_data_source_t *ds = malloc( sizeof(btstack_data_source_t)); 367 if (ds == NULL) return; 368 memset(ds, 0, sizeof(btstack_data_source_t)); 369 btstack_run_loop_set_data_source_handler(ds, &socket_connection_accept); 370 btstack_run_loop_set_data_source_fd(ds, listening_fd); 371 btstack_run_loop_add_data_source(ds); 372 } 373 } 374 375 /** 376 * create socket data_source for socket specified by launchd configuration 377 */ 378 int socket_connection_create_launchd(void){ 379 380 launch_data_t sockets_dict, checkin_response; 381 launch_data_t checkin_request; 382 launch_data_t listening_fd_array; 383 384 /* 385 * Register ourselves with launchd. 386 * 387 */ 388 if ((checkin_request = launch_data_new_string(LAUNCH_KEY_CHECKIN)) == NULL) { 389 log_error( "launch_data_new_string(\"" LAUNCH_KEY_CHECKIN "\") Unable to create string."); 390 return -1; 391 } 392 393 if ((checkin_response = launch_msg(checkin_request)) == NULL) { 394 log_error( "launch_msg(\"" LAUNCH_KEY_CHECKIN "\") IPC failure: %u", errno); 395 return -1; 396 } 397 398 if (LAUNCH_DATA_ERRNO == launch_data_get_type(checkin_response)) { 399 errno = launch_data_get_errno(checkin_response); 400 log_error( "Check-in failed: %u", errno); 401 return -1; 402 } 403 404 launch_data_t the_label = launch_data_dict_lookup(checkin_response, LAUNCH_JOBKEY_LABEL); 405 if (NULL == the_label) { 406 log_error( "No label found"); 407 return -1; 408 } 409 410 /* 411 * Retrieve the dictionary of Socket entries in the config file 412 */ 413 sockets_dict = launch_data_dict_lookup(checkin_response, LAUNCH_JOBKEY_SOCKETS); 414 if (NULL == sockets_dict) { 415 log_error("No sockets found to answer requests on!"); 416 return -1; 417 } 418 419 // if (launch_data_dict_get_count(sockets_dict) > 1) { 420 // log_error("Some sockets will be ignored!"); 421 // } 422 423 /* 424 * Get the dictionary value from the key "Listeners" 425 */ 426 listening_fd_array = launch_data_dict_lookup(sockets_dict, "Listeners"); 427 if (listening_fd_array) { 428 // log_error("Listeners..."); 429 socket_connection_launchd_register_fd_array( listening_fd_array ); 430 } 431 432 /* 433 * Get the dictionary value from the key "Listeners" 434 */ 435 listening_fd_array = launch_data_dict_lookup(sockets_dict, "Listeners2"); 436 if (listening_fd_array) { 437 // log_error("Listeners2..."); 438 socket_connection_launchd_register_fd_array( listening_fd_array ); 439 } 440 441 // although used in Apple examples, it creates a malloc warning 442 // launch_data_free(checkin_response); 443 return 0; 444 } 445 #endif 446 447 /** 448 * create socket data_source for unix domain socket 449 */ 450 int socket_connection_create_unix(char *path){ 451 452 // create btstack_data_source_t 453 btstack_data_source_t *ds = malloc( sizeof(btstack_data_source_t)); 454 if (ds == NULL) return -1; 455 memset(ds, 0, sizeof(btstack_data_source_t)); 456 btstack_run_loop_set_data_source_handler(ds, &socket_connection_accept); 457 458 // create unix socket 459 int fd = socket (AF_UNIX, SOCK_STREAM, 0); 460 if (fd < 0) { 461 log_error( "Error creating socket ...(%s)", strerror(errno)); 462 free(ds); 463 return -1; 464 } 465 btstack_run_loop_set_data_source_fd(ds, fd); 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_add_data_source(ds); 495 496 log_info ("Server up and running ..."); 497 return 0; 498 } 499 500 /** 501 * set packet handler for all auto-accepted connections 502 */ 503 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) ){ 504 socket_connection_packet_callback = packet_callback; 505 } 506 507 /** 508 * send HCI packet to single connection 509 */ 510 void socket_connection_send_packet(connection_t *conn, uint16_t type, uint16_t channel, uint8_t *packet, uint16_t size){ 511 uint8_t header[sizeof(packet_header_t)]; 512 little_endian_store_16(header, 0, type); 513 little_endian_store_16(header, 2, channel); 514 little_endian_store_16(header, 4, size); 515 #if defined(HAVE_SO_NOSIGPIPE) || defined (_WIN32) 516 // BSD Variants like Darwin and iOS 517 write(conn->ds.fd, header, 6); 518 write(conn->ds.fd, packet, size); 519 #else 520 // Linux 521 send(conn->ds.fd, header, 6, MSG_NOSIGNAL); 522 send(conn->ds.fd, packet, size, MSG_NOSIGNAL); 523 #endif 524 } 525 526 /** 527 * send HCI packet to all connections 528 */ 529 void socket_connection_send_packet_all(uint16_t type, uint16_t channel, uint8_t *packet, uint16_t size){ 530 btstack_linked_item_t *next; 531 btstack_linked_item_t *it; 532 for (it = (btstack_linked_item_t *) connections; it ; it = next){ 533 next = it->next; // cache pointer to next connection_t to allow for removal 534 linked_connection_t * linked_connection = (linked_connection_t *) it; 535 socket_connection_send_packet( linked_connection->connection, type, channel, packet, size); 536 } 537 } 538 539 /** 540 * create socket connection to BTdaemon 541 */ 542 connection_t * socket_connection_open_tcp(const char *address, uint16_t port){ 543 // TCP 544 struct protoent* tcp = getprotobyname("tcp"); 545 546 int btsocket = socket(PF_INET, SOCK_STREAM, tcp->p_proto); 547 if(btsocket == -1){ 548 return NULL; 549 } 550 // localhost 551 struct sockaddr_in btdaemon_address; 552 btdaemon_address.sin_family = AF_INET; 553 btdaemon_address.sin_port = htons(port); 554 struct hostent* localhost = gethostbyname(address); 555 if(!localhost){ 556 return NULL; 557 } 558 // connect 559 char* addr = localhost->h_addr_list[0]; 560 memcpy(&btdaemon_address.sin_addr.s_addr, addr, sizeof (struct in_addr)); 561 if(connect(btsocket, (struct sockaddr*)&btdaemon_address, sizeof (btdaemon_address)) == -1){ 562 return NULL; 563 } 564 565 return socket_connection_register_new_connection(btsocket); 566 } 567 568 569 /** 570 * close socket connection to BTdaemon 571 */ 572 int socket_connection_close_tcp(connection_t * connection){ 573 if (!connection) return -1; 574 #ifdef _WIN32 575 shutdown(connection->ds.fd, SD_BOTH); 576 #else 577 shutdown(connection->ds.fd, SHUT_RDWR); 578 #endif 579 socket_connection_free_connection(connection); 580 return 0; 581 } 582 583 584 /** 585 * create socket connection to BTdaemon 586 */ 587 connection_t * socket_connection_open_unix(void){ 588 589 int btsocket = socket(AF_UNIX, SOCK_STREAM, 0); 590 if(btsocket == -1){ 591 return NULL; 592 } 593 594 struct sockaddr_un server; 595 memset(&server, 0, sizeof(server)); 596 server.sun_family = AF_UNIX; 597 strcpy(server.sun_path, BTSTACK_UNIX); 598 if (connect(btsocket, (struct sockaddr *)&server, sizeof (server)) == -1){ 599 return NULL; 600 }; 601 602 return socket_connection_register_new_connection(btsocket); 603 } 604 605 606 /** 607 * close socket connection to BTdaemon 608 */ 609 int socket_connection_close_unix(connection_t * connection){ 610 if (!connection) return -1; 611 #ifdef _WIN32 612 shutdown(connection->ds.fd, SD_BOTH); 613 #else 614 shutdown(connection->ds.fd, SHUT_RDWR); 615 #endif 616 socket_connection_free_connection(connection); 617 return 0; 618 } 619 620