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 int socket_connection_hci_process(struct btstack_data_source *ds); 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 conn->ds.fd = fd; 174 conn->ds.process = socket_connection_hci_process; 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 int socket_connection_hci_process(struct btstack_data_source *ds) { 201 connection_t *conn = (connection_t *) ds; 202 203 int bytes_read = read(ds->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 0; 212 } 213 conn->bytes_read += bytes_read; 214 conn->bytes_to_read -= bytes_read; 215 if (conn->bytes_to_read > 0) { 216 return 0; 217 } 218 219 int dispatch = 0; 220 switch (conn->state){ 221 case SOCKET_W4_HEADER: 222 conn->state = SOCKET_W4_DATA; 223 conn->bytes_to_read = little_endian_read_16( conn->buffer, 4); 224 if (conn->bytes_to_read == 0){ 225 dispatch = 1; 226 } 227 break; 228 case SOCKET_W4_DATA: 229 dispatch = 1; 230 break; 231 default: 232 break; 233 } 234 235 if (dispatch){ 236 // dispatch packet !!! connection, type, channel, data, size 237 int dispatch_err = (*socket_connection_packet_callback)(conn, little_endian_read_16( conn->buffer, 0), little_endian_read_16( conn->buffer, 2), 238 &conn->buffer[sizeof(packet_header_t)], little_endian_read_16( conn->buffer, 4)); 239 240 // reset state machine 241 socket_connection_init_statemachine(conn); 242 243 // "park" if dispatch failed 244 if (dispatch_err) { 245 log_info("socket_connection_hci_process dispatch failed -> park connection"); 246 btstack_run_loop_remove_data_source(ds); 247 btstack_linked_list_add_tail(&parked, (btstack_linked_item_t *) ds); 248 } 249 } 250 return 0; 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 int socket_connection_accept(struct btstack_data_source *socket_ds) { 286 struct sockaddr_storage ss; 287 socklen_t slen = sizeof(ss); 288 289 /* New connection coming in! */ 290 int fd = accept(socket_ds->fd, (struct sockaddr *)&ss, &slen); 291 if (fd < 0) { 292 perror("accept"); 293 return 0; 294 } 295 296 // no sigpipe 297 socket_connection_set_no_sigpipe(fd); 298 299 log_info("socket_connection_accept new connection %u", fd); 300 301 connection_t * connection = socket_connection_register_new_connection(fd); 302 socket_connection_emit_connection_opened(connection); 303 304 return 0; 305 } 306 307 /** 308 * create socket data_source for tcp socket 309 * 310 * @return data_source object. If null, check errno 311 */ 312 int socket_connection_create_tcp(int port){ 313 314 // create btstack_data_source_t 315 btstack_data_source_t *ds = malloc( sizeof(btstack_data_source_t)); 316 if (ds == NULL) return -1; 317 ds->fd = 0; 318 ds->process = socket_connection_accept; 319 320 // create tcp socket 321 if ((ds->fd = socket (PF_INET, SOCK_STREAM, 0)) < 0) { 322 log_error("Error creating socket ...(%s)", strerror(errno)); 323 free(ds); 324 return -1; 325 } 326 327 log_info ("Socket created for port %u", port); 328 329 struct sockaddr_in addr; 330 addr.sin_family = AF_INET; 331 addr.sin_port = htons (port); 332 memset (&addr.sin_addr, 0, sizeof (addr.sin_addr)); 333 334 const int y = 1; 335 setsockopt(ds->fd, SOL_SOCKET, SO_REUSEADDR, (void*) &y, sizeof(int)); 336 337 if (bind ( ds->fd, (struct sockaddr *) &addr, sizeof (addr) ) ) { 338 log_error("Error on bind() ...(%s)", strerror(errno)); 339 free(ds); 340 return -1; 341 } 342 343 if (listen (ds->fd, MAX_PENDING_CONNECTIONS)) { 344 log_error("Error on listen() ...(%s)", strerror(errno)); 345 free(ds); 346 return -1; 347 } 348 349 btstack_run_loop_add_data_source(ds); 350 351 log_info ("Server up and running ..."); 352 return 0; 353 } 354 355 #ifdef USE_LAUNCHD 356 357 /* 358 * Register listening sockets with our run loop 359 */ 360 void socket_connection_launchd_register_fd_array(launch_data_t listening_fd_array){ 361 int i; 362 for (i = 0; i < launch_data_array_get_count(listening_fd_array); i++) { 363 // get fd 364 launch_data_t tempi = launch_data_array_get_index (listening_fd_array, i); 365 int listening_fd = launch_data_get_fd(tempi); 366 launch_data_free (tempi); 367 log_info("file descriptor = %u", listening_fd); 368 369 // create btstack_data_source_t for fd 370 btstack_data_source_t *ds = malloc( sizeof(btstack_data_source_t)); 371 if (ds == NULL) return; 372 ds->process = socket_connection_accept; 373 ds->fd = listening_fd; 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 = malloc( sizeof(btstack_data_source_t)); 457 if (ds == NULL) return -1; 458 ds->fd = 0; 459 ds->process = socket_connection_accept; 460 461 // create unix socket 462 if ((ds->fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0) { 463 log_error( "Error creating socket ...(%s)", strerror(errno)); 464 free(ds); 465 return -1; 466 } 467 468 log_info ("Socket created at %s", path); 469 470 struct sockaddr_un addr; 471 memset(&addr, 0, sizeof(addr)); 472 addr.sun_family = AF_UNIX; 473 strcpy(addr.sun_path, path); 474 unlink(path); 475 476 const int y = 1; 477 setsockopt(ds->fd, SOL_SOCKET, SO_REUSEADDR, (void*) &y, sizeof(int)); 478 479 if (bind ( ds->fd, (struct sockaddr *) &addr, sizeof (addr) ) ) { 480 log_error( "Error on bind() ...(%s)", strerror(errno)); 481 free(ds); 482 return -1; 483 } 484 485 // http://blog.henning.makholm.net/2008/06/unix-domain-socket-woes.html 486 // make socket accept from all clients 487 chmod(path, S_IRWXU | S_IRWXG | S_IRWXO); 488 // 489 490 if (listen (ds->fd, MAX_PENDING_CONNECTIONS)) { 491 log_error( "Error on listen() ...(%s)", strerror(errno)); 492 free(ds); 493 return -1; 494 } 495 496 btstack_run_loop_add_data_source(ds); 497 498 log_info ("Server up and running ..."); 499 return 0; 500 } 501 502 /** 503 * set packet handler for all auto-accepted connections 504 */ 505 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) ){ 506 socket_connection_packet_callback = packet_callback; 507 } 508 509 /** 510 * send HCI packet to single connection 511 */ 512 void socket_connection_send_packet(connection_t *conn, uint16_t type, uint16_t channel, uint8_t *packet, uint16_t size){ 513 uint8_t header[sizeof(packet_header_t)]; 514 little_endian_store_16(header, 0, type); 515 little_endian_store_16(header, 2, channel); 516 little_endian_store_16(header, 4, size); 517 #if defined(HAVE_SO_NOSIGPIPE) || defined (_WIN32) 518 // BSD Variants like Darwin and iOS 519 write(conn->ds.fd, header, 6); 520 write(conn->ds.fd, packet, size); 521 #else 522 // Linux 523 send(conn->ds.fd, header, 6, MSG_NOSIGNAL); 524 send(conn->ds.fd, packet, size, MSG_NOSIGNAL); 525 #endif 526 } 527 528 /** 529 * send HCI packet to all connections 530 */ 531 void socket_connection_send_packet_all(uint16_t type, uint16_t channel, uint8_t *packet, uint16_t size){ 532 btstack_linked_item_t *next; 533 btstack_linked_item_t *it; 534 for (it = (btstack_linked_item_t *) connections; it ; it = next){ 535 next = it->next; // cache pointer to next connection_t to allow for removal 536 linked_connection_t * linked_connection = (linked_connection_t *) it; 537 socket_connection_send_packet( linked_connection->connection, type, channel, packet, size); 538 } 539 } 540 541 /** 542 * create socket connection to BTdaemon 543 */ 544 connection_t * socket_connection_open_tcp(const char *address, uint16_t port){ 545 // TCP 546 struct protoent* tcp = getprotobyname("tcp"); 547 548 int btsocket = socket(PF_INET, SOCK_STREAM, tcp->p_proto); 549 if(btsocket == -1){ 550 return NULL; 551 } 552 // localhost 553 struct sockaddr_in btdaemon_address; 554 btdaemon_address.sin_family = AF_INET; 555 btdaemon_address.sin_port = htons(port); 556 struct hostent* localhost = gethostbyname(address); 557 if(!localhost){ 558 return NULL; 559 } 560 // connect 561 char* addr = localhost->h_addr_list[0]; 562 memcpy(&btdaemon_address.sin_addr.s_addr, addr, sizeof (struct in_addr)); 563 if(connect(btsocket, (struct sockaddr*)&btdaemon_address, sizeof (btdaemon_address)) == -1){ 564 return NULL; 565 } 566 567 return socket_connection_register_new_connection(btsocket); 568 } 569 570 571 /** 572 * close socket connection to BTdaemon 573 */ 574 int socket_connection_close_tcp(connection_t * connection){ 575 if (!connection) return -1; 576 #ifdef _WIN32 577 shutdown(connection->ds.fd, SD_BOTH); 578 #else 579 shutdown(connection->ds.fd, SHUT_RDWR); 580 #endif 581 socket_connection_free_connection(connection); 582 return 0; 583 } 584 585 586 /** 587 * create socket connection to BTdaemon 588 */ 589 connection_t * socket_connection_open_unix(void){ 590 591 int btsocket = socket(AF_UNIX, SOCK_STREAM, 0); 592 if(btsocket == -1){ 593 return NULL; 594 } 595 596 struct sockaddr_un server; 597 memset(&server, 0, sizeof(server)); 598 server.sun_family = AF_UNIX; 599 strcpy(server.sun_path, BTSTACK_UNIX); 600 if (connect(btsocket, (struct sockaddr *)&server, sizeof (server)) == -1){ 601 return NULL; 602 }; 603 604 return socket_connection_register_new_connection(btsocket); 605 } 606 607 608 /** 609 * close socket connection to BTdaemon 610 */ 611 int socket_connection_close_unix(connection_t * connection){ 612 if (!connection) return -1; 613 #ifdef _WIN32 614 shutdown(connection->ds.fd, SD_BOTH); 615 #else 616 shutdown(connection->ds.fd, SHUT_RDWR); 617 #endif 618 socket_connection_free_connection(connection); 619 return 0; 620 } 621 622