1 /*
2 * SysDB - src/frontend/sock.c
3 * Copyright (C) 2013 Sebastian 'tokkee' Harl <sh@tokkee.org>
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
17 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
18 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
19 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
20 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
28 #include "sysdb.h"
29 #include "core/error.h"
30 #include "core/object.h"
31 #include "frontend/sock.h"
33 #include "utils/channel.h"
34 #include "utils/llist.h"
35 #include "utils/strbuf.h"
37 #include <assert.h>
38 #include <errno.h>
40 #include <arpa/inet.h>
42 #include <stdio.h>
43 #include <stdlib.h>
44 #include <string.h>
46 #include <unistd.h>
48 #include <fcntl.h>
50 #include <sys/time.h>
51 #include <sys/types.h>
52 #include <sys/select.h>
53 #include <sys/socket.h>
54 #include <sys/un.h>
56 #include <pthread.h>
58 /* name of connection objects */
59 #define CONN_FD_PREFIX "conn#"
60 #define CONN_FD_PLACEHOLDER "XXXXXXX"
62 /*
63 * private data types
64 */
66 typedef struct {
67 sdb_object_t super;
69 /* connection and client information */
70 int fd;
71 struct sockaddr_storage client_addr;
72 socklen_t client_addr_len;
74 /* read buffer */
75 sdb_strbuf_t *buf;
77 /* state information for the currently executed command */
78 uint32_t cmd;
79 uint32_t cmd_len;
80 } connection_obj_t;
81 #define CONN(obj) ((connection_obj_t *)(obj))
83 typedef struct {
84 char *address;
85 int type;
87 int sock_fd;
88 } listener_t;
90 typedef struct {
91 int type;
92 const char *prefix;
94 int (*opener)(listener_t *);
95 } fe_listener_impl_t;
97 struct sdb_fe_socket {
98 listener_t *listeners;
99 size_t listeners_num;
101 sdb_llist_t *open_connections;
103 /* channel used for communication between main
104 * and connection handler threads */
105 sdb_channel_t *chan;
106 };
108 /*
109 * connection management functions
110 */
112 static int
113 open_unix_sock(listener_t *listener)
114 {
115 struct sockaddr_un sa;
116 int status;
118 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
119 if (listener->sock_fd < 0) {
120 char buf[1024];
121 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
122 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
123 return -1;
124 }
126 memset(&sa, 0, sizeof(sa));
127 sa.sun_family = AF_UNIX;
128 strncpy(sa.sun_path, listener->address + strlen("unix:"),
129 sizeof(sa.sun_path));
131 status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
132 if (status) {
133 char buf[1024];
134 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
135 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
136 return -1;
137 }
138 return 0;
139 } /* open_unix_sock */
141 /*
142 * private variables
143 */
145 /* the enum has to be sorted the same as the implementations array
146 * to ensure that the type may be used as index into the array */
147 enum {
148 LISTENER_UNIXSOCK = 0,
149 };
150 static fe_listener_impl_t listener_impls[] = {
151 { LISTENER_UNIXSOCK, "unix", open_unix_sock },
152 };
154 /*
155 * private helper functions
156 */
158 static int
159 get_type(const char *address)
160 {
161 char *sep;
162 size_t len;
163 size_t i;
165 sep = strchr(address, (int)':');
166 if (! sep)
167 return -1;
169 assert(sep > address);
170 len = (size_t)(sep - address);
172 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
173 fe_listener_impl_t *impl = listener_impls + i;
175 if (!strncmp(address, impl->prefix, len)) {
176 assert(impl->type == (int)i);
177 return impl->type;
178 }
179 }
180 return -1;
181 } /* get_type */
183 static void
184 listener_destroy(listener_t *listener)
185 {
186 if (! listener)
187 return;
189 if (listener->sock_fd >= 0)
190 close(listener->sock_fd);
191 listener->sock_fd = -1;
193 if (listener->address)
194 free(listener->address);
195 } /* listener_destroy */
197 static listener_t *
198 listener_create(sdb_fe_socket_t *sock, const char *address)
199 {
200 listener_t *listener;
201 int type;
203 type = get_type(address);
204 if (type < 0) {
205 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
206 "in listen address '%s'", address);
207 return NULL;
208 }
210 listener = realloc(sock->listeners,
211 sock->listeners_num * sizeof(*sock->listeners));
212 if (! listener) {
213 char buf[1024];
214 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
215 sdb_strerror(errno, buf, sizeof(buf)));
216 return NULL;
217 }
219 sock->listeners = listener;
220 listener = sock->listeners + sock->listeners_num;
222 listener->sock_fd = -1;
223 listener->address = strdup(address);
224 if (! listener->address) {
225 char buf[1024];
226 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
227 sdb_strerror(errno, buf, sizeof(buf)));
228 listener_destroy(listener);
229 return NULL;
230 }
231 listener->type = type;
233 if (listener_impls[type].opener(listener)) {
234 /* prints error */
235 listener_destroy(listener);
236 return NULL;
237 }
239 ++sock->listeners_num;
240 return listener;
241 } /* listener_create */
243 static int
244 listener_listen(listener_t *listener)
245 {
246 assert(listener);
248 /* try to reopen */
249 if (listener->sock_fd < 0)
250 if (listener_impls[listener->type].opener(listener))
251 return -1;
252 assert(listener->sock_fd >= 0);
254 if (listen(listener->sock_fd, /* backlog = */ 32)) {
255 char buf[1024];
256 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
257 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
258 return -1;
259 }
260 return 0;
261 } /* listener_listen */
263 static void
264 listener_close(listener_t *listener)
265 {
266 assert(listener);
268 if (listener->sock_fd < 0)
269 return;
271 close(listener->sock_fd);
272 listener->sock_fd = -1;
273 } /* listener_close */
275 static void
276 socket_close(sdb_fe_socket_t *sock)
277 {
278 size_t i;
280 assert(sock);
281 for (i = 0; i < sock->listeners_num; ++i)
282 listener_close(sock->listeners + i);
283 } /* socket_close */
285 /*
286 * private data types
287 */
289 static int
290 connection_init(sdb_object_t *obj, va_list ap)
291 {
292 connection_obj_t *conn;
293 int sock_fd;
294 int sock_fl;
296 assert(obj);
297 conn = CONN(obj);
299 sock_fd = va_arg(ap, int);
301 CONN(obj)->buf = sdb_strbuf_create(/* size = */ 128);
302 if (! CONN(obj)->buf) {
303 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
304 "for a new remote connection");
305 return -1;
306 }
308 conn->client_addr_len = sizeof(conn->client_addr);
309 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
310 &conn->client_addr_len);
312 if (conn->fd < 0) {
313 char buf[1024];
314 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
315 "connection: %s", sdb_strerror(errno,
316 buf, sizeof(buf)));
317 return -1;
318 }
320 if (conn->client_addr.ss_family != AF_UNIX) {
321 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
322 "unexpected family type %d", conn->client_addr.ss_family);
323 return -1;
324 }
326 sock_fl = fcntl(conn->fd, F_GETFL);
327 if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
328 char buf[1024];
329 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
330 "to non-blocking mode: %s", conn->fd,
331 sdb_strerror(errno, buf, sizeof(buf)));
332 return -1;
333 }
335 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
336 conn->fd);
338 /* update the object name */
339 snprintf(obj->name + strlen(CONN_FD_PREFIX),
340 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
341 return 0;
342 } /* connection_init */
344 static void
345 connection_destroy(sdb_object_t *obj)
346 {
347 connection_obj_t *conn;
349 assert(obj);
350 conn = CONN(obj);
352 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection on fd=%i", conn->fd);
353 close(conn->fd);
354 conn->fd = -1;
356 sdb_strbuf_destroy(CONN(obj)->buf);
357 } /* connection_destroy */
359 static sdb_type_t connection_type = {
360 /* size = */ sizeof(connection_obj_t),
361 /* init = */ connection_init,
362 /* destroy = */ connection_destroy,
363 };
365 /*
366 * connection handler functions
367 */
369 static uint32_t
370 connection_get_int32(connection_obj_t *conn, size_t offset)
371 {
372 const char *data;
373 uint32_t n;
375 assert(conn && (sdb_strbuf_len(conn->buf) >= offset + sizeof(uint32_t)));
377 data = sdb_strbuf_string(conn->buf);
378 memcpy(&n, data + offset, sizeof(n));
379 n = ntohl(n);
380 return n;
381 } /* connection_get_int32 */
383 static int
384 command_handle(connection_obj_t *conn)
385 {
386 assert(conn && conn->cmd && conn->cmd_len);
387 /* XXX */
388 sdb_strbuf_skip(conn->buf, conn->cmd_len);
389 return 0;
390 } /* command_handle */
392 /* initialize the connection state information */
393 static int
394 command_init(connection_obj_t *conn)
395 {
396 assert(conn && (! conn->cmd) && (! conn->cmd_len));
398 conn->cmd = connection_get_int32(conn, 0);
399 conn->cmd_len = connection_get_int32(conn, sizeof(uint32_t));
400 sdb_strbuf_skip(conn->buf, 2 * sizeof(uint32_t));
401 return 0;
402 } /* command_init */
404 /* returns negative value on error, 0 on EOF, number of octets else */
405 static ssize_t
406 connection_read(connection_obj_t *conn)
407 {
408 ssize_t n = 0;
410 while (42) {
411 ssize_t status;
413 errno = 0;
414 status = sdb_strbuf_read(conn->buf, conn->fd, 1024);
415 if (status < 0) {
416 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
417 return n;
418 return (int)status;
419 }
420 else if (! status) /* EOF */
421 return n;
423 n += status;
424 }
426 return n;
427 } /* connection_read */
429 static void *
430 connection_handler(void *data)
431 {
432 sdb_fe_socket_t *sock = data;
434 assert(sock);
436 while (42) {
437 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
438 connection_obj_t *conn;
439 int status;
441 errno = 0;
442 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
443 /* write */ NULL, NULL, &timeout);
444 if (status) {
445 char buf[1024];
447 if (errno == ETIMEDOUT)
448 continue;
449 if (errno == EBADF) /* channel shut down */
450 break;
452 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
453 sdb_strerror(errno, buf, sizeof(buf)));
454 continue;
455 }
457 status = (int)connection_read(conn);
458 if (status <= 0) {
459 /* error or EOF -> close connection */
460 sdb_object_deref(SDB_OBJ(conn));
461 continue;
462 }
464 if (conn->cmd_len && (sdb_strbuf_len(conn->buf) >= conn->cmd_len))
465 command_handle(conn);
466 else if (sdb_strbuf_len(conn->buf) >= 2 * sizeof(int32_t))
467 command_init(conn);
469 /* return the connection to the main loop */
470 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
471 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
472 "connection %s to list of open connections",
473 SDB_OBJ(conn)->name);
474 }
476 /* pass ownership back to list; or destroy in case of an error */
477 sdb_object_deref(SDB_OBJ(conn));
478 }
479 return NULL;
480 } /* connection_handler */
482 static int
483 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
484 {
485 sdb_object_t *obj;
487 /* the placeholder will be replaced with the accepted file
488 * descriptor when initializing the object */
489 obj = sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
490 connection_type, listener->sock_fd);
491 if (! obj)
492 return -1;
494 if (sdb_llist_append(sock->open_connections, obj)) {
495 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
496 "connection %s to list of open connections",
497 obj->name);
498 sdb_object_deref(obj);
499 return -1;
500 }
502 /* hand ownership over to the list */
503 sdb_object_deref(obj);
504 return 0;
505 } /* connection_accept */
507 static int
508 socket_handle_incoming(sdb_fe_socket_t *sock,
509 fd_set *ready, fd_set *exceptions)
510 {
511 sdb_llist_iter_t *iter;
512 size_t i;
514 for (i = 0; i < sock->listeners_num; ++i) {
515 listener_t *listener = sock->listeners + i;
516 if (FD_ISSET(listener->sock_fd, ready))
517 if (connection_accept(sock, listener))
518 continue;
519 }
521 iter = sdb_llist_get_iter(sock->open_connections);
522 if (! iter) {
523 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
524 "for open connections");
525 return -1;
526 }
528 while (sdb_llist_iter_has_next(iter)) {
529 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
531 if (FD_ISSET(CONN(obj)->fd, exceptions))
532 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
533 CONN(obj)->fd);
535 if (FD_ISSET(CONN(obj)->fd, ready)) {
536 sdb_llist_iter_remove_current(iter);
537 sdb_channel_write(sock->chan, &obj);
538 }
539 }
540 sdb_llist_iter_destroy(iter);
541 return 0;
542 } /* socket_handle_incoming */
544 /*
545 * public API
546 */
548 sdb_fe_socket_t *
549 sdb_fe_sock_create(void)
550 {
551 sdb_fe_socket_t *sock;
553 sock = calloc(1, sizeof(*sock));
554 if (! sock)
555 return NULL;
557 sock->open_connections = sdb_llist_create();
558 if (! sock->open_connections) {
559 sdb_fe_sock_destroy(sock);
560 return NULL;
561 }
562 return sock;
563 } /* sdb_fe_sock_create */
565 void
566 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
567 {
568 size_t i;
570 if (! sock)
571 return;
573 for (i = 0; i < sock->listeners_num; ++i) {
574 listener_destroy(sock->listeners + i);
575 }
576 if (sock->listeners)
577 free(sock->listeners);
578 sock->listeners = NULL;
580 sdb_llist_destroy(sock->open_connections);
581 sock->open_connections = NULL;
582 free(sock);
583 } /* sdb_fe_sock_destroy */
585 int
586 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
587 {
588 listener_t *listener;
590 if ((! sock) || (! address))
591 return -1;
593 listener = listener_create(sock, address);
594 if (! listener)
595 return -1;
596 return 0;
597 } /* sdb_fe_sock_add_listener */
599 int
600 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
601 {
602 fd_set sockets;
603 int max_listen_fd = 0;
604 size_t i;
606 /* XXX: make the number of threads configurable */
607 pthread_t handler_threads[5];
609 if ((! sock) || (! sock->listeners_num) || (! loop) || sock->chan)
610 return -1;
612 FD_ZERO(&sockets);
613 for (i = 0; i < sock->listeners_num; ++i) {
614 listener_t *listener = sock->listeners + i;
616 if (listener_listen(listener)) {
617 socket_close(sock);
618 return -1;
619 }
621 FD_SET(listener->sock_fd, &sockets);
622 if (listener->sock_fd > max_listen_fd)
623 max_listen_fd = listener->sock_fd;
624 }
626 sock->chan = sdb_channel_create(1024, sizeof(connection_obj_t *));
627 if (! sock->chan) {
628 socket_close(sock);
629 return -1;
630 }
632 memset(&handler_threads, 0, sizeof(handler_threads));
633 /* XXX: error handling */
634 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
635 pthread_create(&handler_threads[i], /* attr = */ NULL,
636 connection_handler, /* arg = */ sock);
638 while (loop->do_loop) {
639 struct timeval timeout = { 1, 0 }; /* one second */
640 sdb_llist_iter_t *iter;
642 int max_fd = max_listen_fd;
643 fd_set ready;
644 fd_set exceptions;
645 int n;
647 FD_ZERO(&ready);
648 FD_ZERO(&exceptions);
650 ready = sockets;
652 iter = sdb_llist_get_iter(sock->open_connections);
653 if (! iter) {
654 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
655 "for open connections");
656 break;
657 }
659 while (sdb_llist_iter_has_next(iter)) {
660 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
661 FD_SET(CONN(obj)->fd, &ready);
662 FD_SET(CONN(obj)->fd, &exceptions);
664 if (CONN(obj)->fd > max_fd)
665 max_fd = CONN(obj)->fd;
666 }
667 sdb_llist_iter_destroy(iter);
669 errno = 0;
670 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
671 if (n < 0) {
672 char buf[1024];
674 if (errno == EINTR)
675 continue;
677 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
678 sdb_strerror(errno, buf, sizeof(buf)));
679 break;
680 }
681 else if (! n)
682 continue;
684 /* handle new and open connections */
685 if (socket_handle_incoming(sock, &ready, &exceptions))
686 break;
687 }
689 socket_close(sock);
691 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
692 "to terminate");
693 if (! sdb_channel_shutdown(sock->chan))
694 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
695 pthread_join(handler_threads[i], NULL);
696 /* else: we tried our best; let the operating system clean up */
698 sdb_channel_destroy(sock->chan);
699 sock->chan = NULL;
700 return 0;
701 } /* sdb_fe_sock_listen_and_server */
703 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */