xref: /btstack/platform/daemon/src/socket_connection.c (revision 2c455dad9a589f886e28f6a5d10bb735305e4f1b)
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     btstack_run_loop_enable_data_source_callbacks(&conn->ds, DATA_SOURCE_CALLBACK_READ);
176 
177     // prepare state machine and
178     socket_connection_init_statemachine(conn);
179 
180     // add this socket to the run_loop
181     btstack_run_loop_add_data_source( &conn->ds );
182 
183     // and the connection list
184     btstack_linked_list_add( &connections, &conn->linked_connection.item);
185 
186     return conn;
187 }
188 
189 void static socket_connection_emit_connection_opened(connection_t *connection){
190     uint8_t event[1];
191     event[0] = DAEMON_EVENT_CONNECTION_OPENED;
192     (*socket_connection_packet_callback)(connection, DAEMON_EVENT_PACKET, 0, (uint8_t *) &event, 1);
193 }
194 
195 void static socket_connection_emit_connection_closed(connection_t *connection){
196     uint8_t event[1];
197     event[0] = DAEMON_EVENT_CONNECTION_CLOSED;
198     (*socket_connection_packet_callback)(connection, DAEMON_EVENT_PACKET, 0, (uint8_t *) &event, 1);
199 }
200 
201 void socket_connection_hci_process(btstack_data_source_t *ds, btstack_data_source_callback_type_t callback_type) {
202     connection_t *conn = (connection_t *) ds;
203     int fd = btstack_run_loop_get_data_source_fd(ds);
204     int bytes_read = read(fd, &conn->buffer[conn->bytes_read], conn->bytes_to_read);
205     if (bytes_read <= 0){
206         // connection broken (no particular channel, no date yet)
207         socket_connection_emit_connection_closed(conn);
208 
209         // free connection
210         socket_connection_free_connection(conn);
211 
212         return;
213     }
214     conn->bytes_read += bytes_read;
215     conn->bytes_to_read -= bytes_read;
216     if (conn->bytes_to_read > 0) return;
217 
218     int dispatch = 0;
219     switch (conn->state){
220         case SOCKET_W4_HEADER:
221             conn->state = SOCKET_W4_DATA;
222             conn->bytes_to_read = little_endian_read_16( conn->buffer, 4);
223             if (conn->bytes_to_read == 0){
224                 dispatch = 1;
225             }
226             break;
227         case SOCKET_W4_DATA:
228             dispatch = 1;
229             break;
230         default:
231             break;
232     }
233 
234     if (dispatch){
235         // dispatch packet !!! connection, type, channel, data, size
236         int dispatch_err = (*socket_connection_packet_callback)(conn, little_endian_read_16( conn->buffer, 0), little_endian_read_16( conn->buffer, 2),
237                                                             &conn->buffer[sizeof(packet_header_t)], little_endian_read_16( conn->buffer, 4));
238 
239         // reset state machine
240         socket_connection_init_statemachine(conn);
241 
242         // "park" if dispatch failed
243         if (dispatch_err) {
244             log_info("socket_connection_hci_process dispatch failed -> park connection");
245             btstack_run_loop_remove_data_source(ds);
246             btstack_linked_list_add_tail(&parked, (btstack_linked_item_t *) ds);
247         }
248     }
249 }
250 
251 /**
252  * try to dispatch packet for all "parked" connections.
253  * if dispatch is successful, a connection is added again to run loop
254  * pre: connections get parked iff packet was dispatched but could not be sent
255  */
256 void socket_connection_retry_parked(void){
257     // log_info("socket_connection_hci_process retry parked");
258     btstack_linked_item_t *it = (btstack_linked_item_t *) &parked;
259     while (it->next) {
260         connection_t * conn = (connection_t *) it->next;
261 
262         // dispatch packet !!! connection, type, channel, data, size
263         uint16_t packet_type = little_endian_read_16( conn->buffer, 0);
264         uint16_t channel     = little_endian_read_16( conn->buffer, 2);
265         uint16_t length      = little_endian_read_16( conn->buffer, 4);
266         log_info("socket_connection_hci_process retry parked %p (type %u, channel %04x, length %u", conn, packet_type, channel, length);
267         int dispatch_err = (*socket_connection_packet_callback)(conn, packet_type, channel, &conn->buffer[sizeof(packet_header_t)], length);
268         // "un-park" if successful
269         if (!dispatch_err) {
270             log_info("socket_connection_hci_process dispatch succeeded -> un-park connection %p", conn);
271             it->next = it->next->next;
272             btstack_run_loop_add_data_source( (btstack_data_source_t *) conn);
273         } else {
274             it = it->next;
275         }
276     }
277 }
278 
279 int  socket_connection_has_parked_connections(void){
280     return parked != NULL;
281 }
282 
283 static void socket_connection_accept(btstack_data_source_t *socket_ds, btstack_data_source_callback_type_t callback_type) {
284     struct sockaddr_storage ss;
285     socklen_t slen = sizeof(ss);
286     int socket_fd = btstack_run_loop_get_data_source_fd(socket_ds);
287 
288 	/* New connection coming in! */
289 	int fd = accept(socket_fd, (struct sockaddr *)&ss, &slen);
290 	if (fd < 0) {
291 		perror("accept");
292         return;
293 	}
294 
295     // no sigpipe
296     socket_connection_set_no_sigpipe(fd);
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 #if defined(HAVE_SO_NOSIGPIPE) || defined (_WIN32)
519     // BSD Variants like Darwin and iOS
520     write(conn->ds.fd, header, 6);
521     write(conn->ds.fd, packet, size);
522 #else
523     // Linux
524     send(conn->ds.fd, header,    6, MSG_NOSIGNAL);
525     send(conn->ds.fd, packet, size, MSG_NOSIGNAL);
526 #endif
527 }
528 
529 /**
530  * send HCI packet to all connections
531  */
532 void socket_connection_send_packet_all(uint16_t type, uint16_t channel, uint8_t *packet, uint16_t size){
533     btstack_linked_item_t *next;
534     btstack_linked_item_t *it;
535     for (it = (btstack_linked_item_t *) connections; it ; it = next){
536         next = it->next; // cache pointer to next connection_t to allow for removal
537         linked_connection_t * linked_connection = (linked_connection_t *) it;
538         socket_connection_send_packet( linked_connection->connection, type, channel, packet, size);
539     }
540 }
541 
542 /**
543  * create socket connection to BTdaemon
544  */
545 connection_t * socket_connection_open_tcp(const char *address, uint16_t port){
546     // TCP
547     struct protoent* tcp = getprotobyname("tcp");
548 
549     int btsocket = socket(PF_INET, SOCK_STREAM, tcp->p_proto);
550 	if(btsocket == -1){
551 		return NULL;
552 	}
553     // localhost
554 	struct sockaddr_in btdaemon_address;
555 	btdaemon_address.sin_family = AF_INET;
556 	btdaemon_address.sin_port = htons(port);
557 	struct hostent* localhost = gethostbyname(address);
558 	if(!localhost){
559 		return NULL;
560 	}
561     // connect
562 	char* addr = localhost->h_addr_list[0];
563 	memcpy(&btdaemon_address.sin_addr.s_addr, addr, sizeof (struct in_addr));
564 	if(connect(btsocket, (struct sockaddr*)&btdaemon_address, sizeof (btdaemon_address)) == -1){
565 		return NULL;
566 	}
567 
568     return socket_connection_register_new_connection(btsocket);
569 }
570 
571 
572 /**
573  * close socket connection to BTdaemon
574  */
575 int socket_connection_close_tcp(connection_t * connection){
576     if (!connection) return -1;
577 #ifdef _WIN32
578     shutdown(connection->ds.fd, SD_BOTH);
579 #else
580     shutdown(connection->ds.fd, SHUT_RDWR);
581 #endif
582     socket_connection_free_connection(connection);
583     return 0;
584 }
585 
586 
587 /**
588  * create socket connection to BTdaemon
589  */
590 connection_t * socket_connection_open_unix(void){
591 
592     int btsocket = socket(AF_UNIX, SOCK_STREAM, 0);
593 	if(btsocket == -1){
594 		return NULL;
595 	}
596 
597     struct sockaddr_un server;
598     memset(&server, 0, sizeof(server));
599     server.sun_family = AF_UNIX;
600     strcpy(server.sun_path, BTSTACK_UNIX);
601     if (connect(btsocket, (struct sockaddr *)&server, sizeof (server)) == -1){
602         return NULL;
603     };
604 
605     return socket_connection_register_new_connection(btsocket);
606 }
607 
608 
609 /**
610  * close socket connection to BTdaemon
611  */
612 int socket_connection_close_unix(connection_t * connection){
613     if (!connection) return -1;
614 #ifdef _WIN32
615     shutdown(connection->ds.fd, SD_BOTH);
616 #else
617     shutdown(connection->ds.fd, SHUT_RDWR);
618 #endif
619     socket_connection_free_connection(connection);
620     return 0;
621 }
622 
623