1 #include <opensrf/socket_bundle.h>
3 struct socket_node_struct {
4 int endpoint; /* SERVER_SOCKET or CLIENT_SOCKET */
5 int addr_type; /* INET or UNIX */
7 int parent_id; /* if we're a new client for a server socket,
8 this points to the server socket we spawned from */
9 struct socket_node_struct* next;
12 /* buffer used to read from the sockets */
15 static socket_node* _socket_add_node(socket_manager* mgr,
16 int endpoint, int addr_type, int sock_fd, int parent_id );
17 static socket_node* socket_find_node(socket_manager* mgr, int sock_fd);
18 static void socket_remove_node(socket_manager*, int sock_fd);
19 static int _socket_send(int sock_fd, const char* data, int flags);
20 static int _socket_route_data(socket_manager* mgr, int num_active, fd_set* read_set);
21 static int _socket_route_data_id( socket_manager* mgr, int sock_id);
22 static int _socket_handle_new_client(socket_manager* mgr, socket_node* node);
23 static int _socket_handle_client_data(socket_manager* mgr, socket_node* node);
26 /* --------------------------------------------------------------------
28 -------------------------------------------------------------------- */
31 void printme(void* blob, socket_manager* mgr,
32 int sock_fd, char* data, int parent_id) {
34 fprintf(stderr, "Got data from socket %d with parent %d => %s",
35 sock_fd, parent_id, data );
37 socket_send(sock_fd, data);
40 socket_disconnect(mgr, sock_fd);
41 _socket_print_list(mgr);
45 int main(int argc, char* argv[]) {
46 socket_manager manager;
47 memset(&manager, 0, sizeof(socket_manager));
52 manager.data_received = &printme;
53 socket_open_tcp_server(&manager, port);
56 socket_wait_all(&manager, -1);
61 /* -------------------------------------------------------------------- */
65 @brief Create a new socket_node and add it to a socket_manager's list.
66 @param mgr Pointer to the socket_manager.
67 @param endpoint SERVER_SOCKET or CLIENT_SOCKET, denoting how the socket is to be used.
68 @param addr_type address type: INET or UNIX.
69 @param sock_fd sock_fd for the new socket_node.
70 @param parent_id parent_id for the new node.
71 @return Pointer to the new socket_node.
73 If @a parent_id is negative, the new socket_node receives a parent_id of 0.
75 static socket_node* _socket_add_node(socket_manager* mgr,
76 int endpoint, int addr_type, int sock_fd, int parent_id ) {
78 if(mgr == NULL) return NULL;
79 osrfLogInternal( OSRF_LOG_MARK, "Adding socket node with fd %d", sock_fd);
80 socket_node* new_node = safe_malloc(sizeof(socket_node));
82 new_node->endpoint = endpoint;
83 new_node->addr_type = addr_type;
84 new_node->sock_fd = sock_fd;
85 new_node->next = NULL;
86 new_node->parent_id = 0;
88 new_node->parent_id = parent_id;
90 new_node->next = mgr->socket;
91 mgr->socket = new_node;
96 @brief Create an TCP INET listener socket and add it to a socket_manager's list.
97 @param mgr Pointer to the socket manager that will own the socket.
98 @param port The port number to bind to.
99 @param listen_ip The IP address to bind to; or, NULL for INADDR_ANY.
100 @return The socket fd if successful; otherwise -1.
102 Calls: socket(), bind(), and listen().
104 int socket_open_tcp_server(socket_manager* mgr, int port, const char* listen_ip) {
107 osrfLogWarning( OSRF_LOG_MARK, "socket_open_tcp_server(): NULL mgr");
112 struct sockaddr_in server_addr;
114 server_addr.sin_family = AF_INET;
116 if(listen_ip != NULL) {
118 if( inet_aton( listen_ip, &addr ) )
119 server_addr.sin_addr.s_addr = addr.s_addr;
121 osrfLogError( OSRF_LOG_MARK, "Listener address is invalid: %s", listen_ip );
125 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
128 server_addr.sin_port = htons(port);
131 sock_fd = socket(AF_INET, SOCK_STREAM, 0);
133 osrfLogWarning( OSRF_LOG_MARK, "socket_open_tcp_server(): Unable to create TCP socket: %s",
139 if(bind( sock_fd, (struct sockaddr*) &server_addr, sizeof(server_addr)) < 0) {
140 osrfLogWarning( OSRF_LOG_MARK, "socket_open_tcp_server(): cannot bind to port %d: %s",
141 port, strerror( errno ) );
147 if(listen(sock_fd, 20) == -1) {
148 osrfLogWarning( OSRF_LOG_MARK, "socket_open_tcp_server(): listen() returned error: %s",
154 _socket_add_node(mgr, SERVER_SOCKET, INET, sock_fd, 0);
159 @brief Create a UNIX domain listener socket and add it to the socket_manager's list.
160 @param mgr Pointer to the socket_manager that will own the socket.
161 @param path Name of the socket within the file system.
162 @return The socket fd if successful; otherwise -1.
164 Calls: socket(), bind(), listen().
166 int socket_open_unix_server(socket_manager* mgr, const char* path) {
167 if(mgr == NULL || path == NULL) return -1;
169 osrfLogDebug( OSRF_LOG_MARK, "opening unix socket at %s", path);
171 struct sockaddr_un server_addr;
173 if(strlen(path) > sizeof(server_addr.sun_path) - 1)
175 osrfLogWarning( OSRF_LOG_MARK, "socket_open_unix_server(): path too long: %s",
181 sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
183 osrfLogWarning( OSRF_LOG_MARK, "socket_open_unix_server(): socket() failed: %s",
188 server_addr.sun_family = AF_UNIX;
189 strcpy(server_addr.sun_path, path);
192 if( bind(sock_fd, (struct sockaddr*) &server_addr,
193 sizeof(struct sockaddr_un)) < 0) {
194 osrfLogWarning( OSRF_LOG_MARK,
195 "socket_open_unix_server(): cannot bind to unix port %s: %s",
196 path, strerror( errno ) );
202 if(listen(sock_fd, 20) == -1) {
203 osrfLogWarning( OSRF_LOG_MARK, "socket_open_unix_server(): listen() returned error: %s",
209 osrfLogDebug( OSRF_LOG_MARK, "unix socket successfully opened");
213 /* causing problems with router for some reason ... */
214 //osrfLogDebug( OSRF_LOG_MARK, "Setting SO_REUSEADDR");
215 //setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &i, sizeof(i));
217 //osrfLogDebug( OSRF_LOG_MARK, "Setting TCP_NODELAY");
218 setsockopt(sock_fd, IPPROTO_TCP, TCP_NODELAY, &i, sizeof(i));
220 _socket_add_node(mgr, SERVER_SOCKET, UNIX, sock_fd, 0);
226 @brief Create a UDP socket for a server, and add it to a socket_manager's list.
227 @param mgr Pointer to the socket_manager that will own the socket.
228 @param port The port number to bind to.
229 @param listen_ip The IP address to bind to, or NULL for INADDR_ANY.
230 @return The socket fd if successful; otherwise -1.
232 Calls: socket(), bind().
234 int socket_open_udp_server(
235 socket_manager* mgr, int port, const char* listen_ip ) {
238 struct sockaddr_in server_addr;
240 server_addr.sin_family = AF_INET;
241 server_addr.sin_port = htons(port);
244 if( inet_aton( listen_ip, &addr ) )
245 server_addr.sin_addr.s_addr = addr.s_addr;
247 osrfLogError( OSRF_LOG_MARK, "UDP listener address is invalid: %s", listen_ip );
251 server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
254 if( (sockfd = socket( AF_INET, SOCK_DGRAM, 0 )) < 0 ) {
255 osrfLogWarning( OSRF_LOG_MARK, "Unable to create UDP socket: %s", strerror( errno ) );
260 if( (bind (sockfd, (struct sockaddr *) &server_addr,sizeof(server_addr))) ) {
261 osrfLogWarning( OSRF_LOG_MARK, "Unable to bind to UDP port %d: %s",
262 port, strerror( errno ) );
267 _socket_add_node(mgr, SERVER_SOCKET, INET, sockfd, 0);
273 @brief Create a client TCP socket, connect with it, and add it to a socket_manager's list.
274 @param mgr Pointer to the socket_manager that will own the socket.
275 @param port What port number to connect to.
276 @param dest_addr Host name or IP address of the server to which we are connecting.
277 @return The socket fd if successful; otherwise -1.
279 Calls: gethostbyname(), socket(), connect().
281 int socket_open_tcp_client(socket_manager* mgr, int port, const char* dest_addr) {
283 struct sockaddr_in remoteAddr;
284 struct hostent *hptr;
287 // ------------------------------------------------------------------
289 // ------------------------------------------------------------------
291 if( (hptr = gethostbyname( dest_addr ) ) == NULL ) {
292 osrfLogWarning( OSRF_LOG_MARK, "socket_open_tcp_client(): Unknown Host => %s: %s",
293 dest_addr, strerror( errno ) );
297 // ------------------------------------------------------------------
299 // ------------------------------------------------------------------
301 if( (sock_fd = socket( AF_INET, SOCK_STREAM, 0 )) < 0 ) {
302 osrfLogWarning( OSRF_LOG_MARK, "socket_open_tcp_client(): Cannot create TCP socket: %s",
308 //osrfLogDebug( OSRF_LOG_MARK, "Setting TCP_NODELAY");
309 setsockopt(sock_fd, IPPROTO_TCP, TCP_NODELAY, &i, sizeof(i));
311 // ------------------------------------------------------------------
312 // Construct server info struct
313 // ------------------------------------------------------------------
314 memset( &remoteAddr, 0, sizeof(remoteAddr));
315 remoteAddr.sin_family = AF_INET;
316 remoteAddr.sin_port = htons( port );
317 memcpy( (char*) &remoteAddr.sin_addr.s_addr,
318 hptr->h_addr_list[0], hptr->h_length );
320 // ------------------------------------------------------------------
322 // ------------------------------------------------------------------
324 if( connect( sock_fd, (struct sockaddr*) &remoteAddr, sizeof( struct sockaddr_in ) ) < 0 ) {
325 osrfLogWarning( OSRF_LOG_MARK, "socket_open_tcp_client(): Cannot connect to server %s: %s",
326 dest_addr, strerror(errno) );
331 _socket_add_node(mgr, CLIENT_SOCKET, INET, sock_fd, -1 );
338 @brief Create a client UDP socket and add it to a socket_manager's list.
339 @param mgr Pointer to the socket_manager that will own the socket.
340 @return The socket fd if successful; otherwise -1.
344 int socket_open_udp_client( socket_manager* mgr ) {
349 if( (sockfd = socket(AF_INET,SOCK_DGRAM,0)) < 0 ) {
350 osrfLogWarning( OSRF_LOG_MARK,
351 "socket_open_udp_client(): Unable to create UDP socket: %s", strerror( errno ) );
355 _socket_add_node(mgr, CLIENT_SOCKET, INET, sockfd, -1 );
362 @brief Create a UNIX domain client socket, connect with it, add it to the socket_manager's list
363 @param mgr Pointer to the socket_manager that will own the socket.
364 @param sock_path Name of the socket within the file system.
365 @return The socket fd if successful; otherwise -1.
367 Calls: socket(), connect().
369 int socket_open_unix_client(socket_manager* mgr, const char* sock_path) {
372 struct sockaddr_un usock;
374 if(strlen(sock_path) > sizeof(usock.sun_path) - 1)
376 osrfLogWarning( OSRF_LOG_MARK, "socket_open_unix_client(): path too long: %s",
382 if( (sock_fd = socket( AF_UNIX, SOCK_STREAM, 0 )) < 0 ) {
383 osrfLogWarning( OSRF_LOG_MARK, "socket_open_unix_client(): Cannot create UNIX socket: %s", strerror( errno ) );
387 usock.sun_family = AF_UNIX;
388 strcpy( usock.sun_path, sock_path );
390 len = sizeof( usock.sun_family ) + strlen( usock.sun_path );
393 if( connect( sock_fd, (struct sockaddr *) &usock, len ) < 0 ) {
394 osrfLogWarning( OSRF_LOG_MARK, "Error connecting to unix socket: %s",
400 _socket_add_node(mgr, CLIENT_SOCKET, UNIX, sock_fd, -1 );
406 /* returns the socket_node with the given sock_fd */
407 static socket_node* socket_find_node(socket_manager* mgr, int sock_fd) {
408 if(mgr == NULL) return NULL;
409 socket_node* node = mgr->socket;
411 if(node->sock_fd == sock_fd)
418 /* removes the node with the given sock_fd from the list and frees it */
419 static void socket_remove_node(socket_manager* mgr, int sock_fd) {
421 if(mgr == NULL) return;
423 osrfLogDebug( OSRF_LOG_MARK, "removing socket %d", sock_fd);
425 socket_node* head = mgr->socket;
426 socket_node* tail = head;
427 if(head == NULL) return;
429 /* if removing the first node in the list */
430 if(head->sock_fd == sock_fd) {
431 mgr->socket = head->next;
438 /* if removing any other node */
440 if(head->sock_fd == sock_fd) {
441 tail->next = head->next;
451 void _socket_print_list(socket_manager* mgr) {
452 if(mgr == NULL) return;
453 socket_node* node = mgr->socket;
454 osrfLogDebug( OSRF_LOG_MARK, "socket_node list: [");
456 osrfLogDebug( OSRF_LOG_MARK, "sock_fd: %d | parent_id: %d",
457 node->sock_fd, node->parent_id);
460 osrfLogDebug( OSRF_LOG_MARK, "]");
463 /* sends the given data to the given socket */
464 int socket_send(int sock_fd, const char* data) {
465 return _socket_send( sock_fd, data, 0);
469 static int _socket_send(int sock_fd, const char* data, int flags) {
471 signal(SIGPIPE, SIG_IGN); /* in case a unix socket was closed */
474 size_t r = send( sock_fd, data, strlen(data), flags );
475 int local_errno = errno;
478 osrfLogWarning( OSRF_LOG_MARK, "_socket_send(): Error sending data with return %d", r );
479 osrfLogWarning( OSRF_LOG_MARK, "Last Sys Error: %s", strerror(local_errno));
487 /* sends the given data to the given socket.
488 * sets the send flag MSG_DONTWAIT which will allow the
489 * process to continue even if the socket buffer is full
490 * returns 0 on success, -1 otherwise */
491 //int socket_send_nowait( int sock_fd, const char* data) {
492 // return _socket_send( sock_fd, data, MSG_DONTWAIT);
497 * Waits at most usecs microseconds for the send buffer of the given
498 * socket to accept new data. This does not guarantee that the
499 * socket will accept all the data we want to give it.
501 int socket_send_timeout( int sock_fd, const char* data, int usecs ) {
504 FD_ZERO( &write_set );
505 FD_SET( sock_fd, &write_set );
508 int secs = (int) usecs / mil;
509 usecs = usecs - (secs * mil);
516 int ret = select( sock_fd + 1, NULL, &write_set, NULL, &tv);
517 if( ret > 0 ) return _socket_send( sock_fd, data, 0);
519 osrfLogError(OSRF_LOG_MARK, "socket_send_timeout(): "
520 "timed out on send for socket %d after %d secs, %d usecs: %s",
521 sock_fd, secs, usecs, strerror( errno ) );
527 /* disconnects the node with the given sock_fd and removes
528 it from the socket set */
529 void socket_disconnect(socket_manager* mgr, int sock_fd) {
530 osrfLogInternal( OSRF_LOG_MARK, "Closing socket %d", sock_fd);
532 socket_remove_node(mgr, sock_fd);
536 /* we assume that if select() fails, the socket is no longer valid */
537 int socket_connected(int sock_fd) {
539 FD_ZERO( &read_set );
540 FD_SET( sock_fd, &read_set );
541 if( select( sock_fd + 1, &read_set, NULL, NULL, NULL) == -1 )
547 /* this only waits on the server socket and does not handle the actual
548 data coming in from the client..... XXX */
549 int socket_wait(socket_manager* mgr, int timeout, int sock_fd) {
553 FD_ZERO( &read_set );
554 FD_SET( sock_fd, &read_set );
563 // If timeout is -1, we block indefinitely
564 if( (retval = select( sock_fd + 1, &read_set, NULL, NULL, NULL)) == -1 ) {
565 osrfLogDebug( OSRF_LOG_MARK, "Call to select() interrupted: Sys Error: %s", strerror(errno));
569 } else if( timeout > 0 ) { /* timeout of 0 means don't block */
571 if( (retval = select( sock_fd + 1, &read_set, NULL, NULL, &tv)) == -1 ) {
572 osrfLogDebug( OSRF_LOG_MARK, "Call to select() interrupted: Sys Error: %s", strerror(errno));
577 osrfLogInternal( OSRF_LOG_MARK, "%d active sockets after select()", retval);
578 return _socket_route_data_id(mgr, sock_fd);
582 int socket_wait_all(socket_manager* mgr, int timeout) {
585 osrfLogWarning( OSRF_LOG_MARK, "socket_wait_all(): null mgr" );
591 FD_ZERO( &read_set );
593 socket_node* node = mgr->socket;
596 osrfLogInternal( OSRF_LOG_MARK, "Adding socket fd %d to select set",node->sock_fd);
597 FD_SET( node->sock_fd, &read_set );
598 if(node->sock_fd > max_fd) max_fd = node->sock_fd;
610 // If timeout is -1, there is no timeout passed to the call to select
611 if( (retval = select( max_fd, &read_set, NULL, NULL, NULL)) == -1 ) {
612 osrfLogWarning( OSRF_LOG_MARK, "select() call aborted: %s", strerror(errno));
616 } else if( timeout != 0 ) { /* timeout of 0 means don't block */
618 if( (retval = select( max_fd, &read_set, NULL, NULL, &tv)) == -1 ) {
619 osrfLogWarning( OSRF_LOG_MARK, "select() call aborted: %s", strerror(errno));
624 osrfLogDebug( OSRF_LOG_MARK, "%d active sockets after select()", retval);
625 return _socket_route_data(mgr, retval, &read_set);
628 /* iterates over the sockets in the set and handles active sockets.
629 new sockets connecting to server sockets cause the creation
630 of a new socket node.
631 Any new data read is is passed off to the data_received callback
633 /* determines if we're receiving a new client or data
634 on an existing client */
635 static int _socket_route_data(
636 socket_manager* mgr, int num_active, fd_set* read_set) {
638 if(!(mgr && read_set)) return -1;
640 int last_failed_id = -1;
643 /* come back here if someone yanks a socket_node from beneath us */
646 socket_node* node = mgr->socket;
650 while(node && (handled < num_active)) {
652 int sock_fd = node->sock_fd;
654 if(last_failed_id != -1) {
655 /* in case it was not removed by our overlords */
656 osrfLogInternal( OSRF_LOG_MARK, "Attempting to remove last_failed_id of %d", last_failed_id);
657 socket_remove_node( mgr, last_failed_id );
663 /* does this socket have data? */
664 if( FD_ISSET( sock_fd, read_set ) ) {
666 osrfLogInternal( OSRF_LOG_MARK, "Socket %d active", sock_fd);
668 FD_CLR(sock_fd, read_set);
670 if(node->endpoint == SERVER_SOCKET)
671 _socket_handle_new_client(mgr, node);
674 status = _socket_handle_client_data(mgr, node);
676 /* someone may have yanked a socket_node out from under
677 us...start over with the first socket */
679 last_failed_id = sock_fd;
680 osrfLogInternal( OSRF_LOG_MARK, "Backtracking back to start of loop because "
681 "of -1 return code from _socket_handle_client_data()");
685 if(status == -1) break;
690 if(status == 0) break;
691 if(status == -1) status = 0;
698 /* routes data from a single known socket */
699 static int _socket_route_data_id( socket_manager* mgr, int sock_id) {
700 socket_node* node = socket_find_node(mgr, sock_id);
704 if(node->endpoint == SERVER_SOCKET)
705 _socket_handle_new_client(mgr, node);
707 if(node->endpoint == CLIENT_SOCKET )
708 status = _socket_handle_client_data(mgr, node);
711 socket_remove_node(mgr, sock_id);
721 static int _socket_handle_new_client(socket_manager* mgr, socket_node* node) {
722 if(mgr == NULL || node == NULL) return -1;
726 new_sock_fd = accept(node->sock_fd, NULL, NULL);
727 if(new_sock_fd < 0) {
728 osrfLogWarning( OSRF_LOG_MARK, "_socket_handle_new_client(): accept() failed: %s",
733 if(node->addr_type == INET) {
734 _socket_add_node(mgr, CLIENT_SOCKET, INET, new_sock_fd, node->sock_fd);
735 osrfLogDebug( OSRF_LOG_MARK, "Adding new INET client for %d", node->sock_fd);
737 } else if(node->addr_type == UNIX) {
738 _socket_add_node(mgr, CLIENT_SOCKET, UNIX, new_sock_fd, node->sock_fd);
739 osrfLogDebug( OSRF_LOG_MARK, "Adding new UNIX client for %d", node->sock_fd);
746 static int _socket_handle_client_data(socket_manager* mgr, socket_node* node) {
747 if(mgr == NULL || node == NULL) return -1;
751 int sock_fd = node->sock_fd;
753 osrf_clearbuf(buf, sizeof(buf));
754 set_fl(sock_fd, O_NONBLOCK);
756 osrfLogInternal( OSRF_LOG_MARK, "%ld : Received data at %f\n", (long) getpid(), get_timestamp_millis());
758 while( (read_bytes = recv(sock_fd, buf, RBUFSIZE-1, 0) ) > 0 ) {
759 buf[read_bytes] = '\0';
760 osrfLogInternal( OSRF_LOG_MARK, "Socket %d Read %d bytes and data: %s", sock_fd, read_bytes, buf);
761 if(mgr->data_received)
762 mgr->data_received(mgr->blob, mgr, sock_fd, buf, node->parent_id);
764 osrf_clearbuf(buf, sizeof(buf));
766 int local_errno = errno; /* capture errno as set by recv() */
768 if(socket_find_node(mgr, sock_fd)) { /* someone may have closed this socket */
769 clr_fl(sock_fd, O_NONBLOCK);
771 if(local_errno != EAGAIN)
772 osrfLogWarning(OSRF_LOG_MARK, " * Error reading socket with error %s", strerror(local_errno));
775 } else { return -1; } /* inform the caller that this node has been tampered with */
777 if(read_bytes == 0) { /* socket closed by client */
778 if(mgr->on_socket_closed) {
779 mgr->on_socket_closed(mgr->blob, sock_fd);
789 void socket_manager_free(socket_manager* mgr) {
790 if(mgr == NULL) return;
793 tmp = mgr->socket->next;
794 socket_disconnect(mgr, mgr->socket->sock_fd);