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 #if HAVE_CONFIG_H
29 # include "config.h"
30 #endif /* HAVE_CONFIG_H */
32 #include "sysdb.h"
33 #include "core/object.h"
34 #include "frontend/connection-private.h"
35 #include "frontend/sock.h"
37 #include "utils/channel.h"
38 #include "utils/error.h"
39 #include "utils/llist.h"
40 #include "utils/os.h"
41 #include "utils/strbuf.h"
43 #include <assert.h>
44 #include <errno.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
50 #include <unistd.h>
52 #include <sys/time.h>
53 #include <sys/types.h>
54 #include <sys/select.h>
55 #include <sys/socket.h>
56 #include <sys/un.h>
58 #include <libgen.h>
60 #include <pthread.h>
62 /*
63 * private data types
64 */
66 typedef struct {
67 char *address;
68 int type;
70 int sock_fd;
71 } listener_t;
73 typedef struct {
74 int type;
75 const char *prefix;
77 int (*opener)(listener_t *);
78 void (*closer)(listener_t *);
79 } fe_listener_impl_t;
81 struct sdb_fe_socket {
82 listener_t *listeners;
83 size_t listeners_num;
85 sdb_llist_t *open_connections;
87 /* channel used for communication between main
88 * and connection handler threads */
89 sdb_channel_t *chan;
90 };
92 /*
93 * connection management functions
94 */
96 static int
97 open_unix_sock(listener_t *listener)
98 {
99 const char *addr;
100 char *base_dir;
101 struct sockaddr_un sa;
102 int status;
104 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
105 if (listener->sock_fd < 0) {
106 char buf[1024];
107 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
108 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
109 return -1;
110 }
112 if (*listener->address == '/')
113 addr = listener->address;
114 else
115 addr = listener->address + strlen("unix:");
117 memset(&sa, 0, sizeof(sa));
118 sa.sun_family = AF_UNIX;
119 strncpy(sa.sun_path, addr, sizeof(sa.sun_path));
121 base_dir = strdup(addr);
122 if (! base_dir) {
123 char errbuf[1024];
124 sdb_log(SDB_LOG_ERR, "frontend: strdup failed: %s",
125 sdb_strerror(errno, errbuf, sizeof(errbuf)));
126 return -1;
127 }
128 base_dir = dirname(base_dir);
130 /* ensure that the directory exists */
131 if (sdb_mkdir_all(base_dir, 0777)) {
132 char errbuf[1024];
133 sdb_log(SDB_LOG_ERR, "frontend: Failed to create directory '%s': %s",
134 base_dir, sdb_strerror(errno, errbuf, sizeof(errbuf)));
135 free(base_dir);
136 return -1;
137 }
138 free(base_dir);
140 if (unlink(addr) && (errno != ENOENT)) {
141 char errbuf[1024];
142 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
143 "socket %s: %s", listener->address + strlen("unix:"),
144 sdb_strerror(errno, errbuf, sizeof(errbuf)));
145 }
147 status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
148 if (status) {
149 char buf[1024];
150 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
151 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
152 return -1;
153 }
154 return 0;
155 } /* open_unix_sock */
157 static void
158 close_unix_sock(listener_t *listener)
159 {
160 const char *addr;
161 assert(listener);
163 if (! listener->address)
164 return;
166 if (*listener->address == '/')
167 addr = listener->address;
168 else
169 addr = listener->address + strlen("unix:");
171 if (listener->sock_fd >= 0)
172 close(listener->sock_fd);
173 listener->sock_fd = -1;
175 unlink(addr);
176 } /* close_unix_sock */
178 /*
179 * private variables
180 */
182 /* the enum has to be sorted the same as the implementations array
183 * to ensure that the type may be used as index into the array */
184 enum {
185 LISTENER_UNIXSOCK = 0, /* this is the default */
186 };
187 static fe_listener_impl_t listener_impls[] = {
188 { LISTENER_UNIXSOCK, "unix", open_unix_sock, close_unix_sock },
189 };
191 /*
192 * private helper functions
193 */
195 static int
196 listener_listen(listener_t *listener)
197 {
198 assert(listener);
200 /* try to reopen */
201 if (listener->sock_fd < 0)
202 if (listener_impls[listener->type].opener(listener))
203 return -1;
204 assert(listener->sock_fd >= 0);
206 if (listen(listener->sock_fd, /* backlog = */ 32)) {
207 char buf[1024];
208 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
209 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
210 return -1;
211 }
212 return 0;
213 } /* listener_listen */
215 static void
216 listener_close(listener_t *listener)
217 {
218 assert(listener);
220 if (listener_impls[listener->type].closer)
221 listener_impls[listener->type].closer(listener);
223 if (listener->sock_fd >= 0)
224 close(listener->sock_fd);
225 listener->sock_fd = -1;
226 } /* listener_close */
228 static int
229 get_type(const char *address)
230 {
231 char *sep;
232 size_t len;
233 size_t i;
235 sep = strchr(address, (int)':');
236 if (! sep)
237 return listener_impls[0].type;
239 assert(sep > address);
240 len = (size_t)(sep - address);
242 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
243 fe_listener_impl_t *impl = listener_impls + i;
245 if (!strncmp(address, impl->prefix, len)) {
246 assert(impl->type == (int)i);
247 return impl->type;
248 }
249 }
250 return -1;
251 } /* get_type */
253 static void
254 listener_destroy(listener_t *listener)
255 {
256 if (! listener)
257 return;
259 listener_close(listener);
261 if (listener->address)
262 free(listener->address);
263 listener->address = NULL;
264 } /* listener_destroy */
266 static listener_t *
267 listener_create(sdb_fe_socket_t *sock, const char *address)
268 {
269 listener_t *listener;
270 int type;
272 type = get_type(address);
273 if (type < 0) {
274 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
275 "in listen address '%s'", address);
276 return NULL;
277 }
279 listener = realloc(sock->listeners,
280 (sock->listeners_num + 1) * sizeof(*sock->listeners));
281 if (! listener) {
282 char buf[1024];
283 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
284 sdb_strerror(errno, buf, sizeof(buf)));
285 return NULL;
286 }
288 sock->listeners = listener;
289 listener = sock->listeners + sock->listeners_num;
291 listener->sock_fd = -1;
292 listener->address = strdup(address);
293 if (! listener->address) {
294 char buf[1024];
295 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
296 sdb_strerror(errno, buf, sizeof(buf)));
297 listener_destroy(listener);
298 return NULL;
299 }
300 listener->type = type;
302 if (listener_impls[type].opener(listener)) {
303 /* prints error */
304 listener_destroy(listener);
305 return NULL;
306 }
308 ++sock->listeners_num;
309 return listener;
310 } /* listener_create */
312 static void
313 socket_clear(sdb_fe_socket_t *sock)
314 {
315 size_t i;
317 assert(sock);
318 for (i = 0; i < sock->listeners_num; ++i)
319 listener_destroy(sock->listeners + i);
320 if (sock->listeners)
321 free(sock->listeners);
322 sock->listeners = NULL;
323 sock->listeners_num = 0;
324 } /* socket_clear */
326 static void
327 socket_close(sdb_fe_socket_t *sock)
328 {
329 size_t i;
331 assert(sock);
332 for (i = 0; i < sock->listeners_num; ++i)
333 listener_close(sock->listeners + i);
334 } /* socket_close */
336 /*
337 * connection handler functions
338 */
340 static void *
341 connection_handler(void *data)
342 {
343 sdb_fe_socket_t *sock = data;
345 assert(sock);
347 while (42) {
348 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
349 sdb_conn_t *conn;
350 int status;
352 errno = 0;
353 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
354 /* write */ NULL, NULL, &timeout);
355 if (status) {
356 char buf[1024];
358 if (errno == ETIMEDOUT)
359 continue;
360 if (errno == EBADF) /* channel shut down */
361 break;
363 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
364 sdb_strerror(errno, buf, sizeof(buf)));
365 continue;
366 }
368 status = (int)sdb_connection_read(conn);
369 if (status <= 0) {
370 /* error or EOF -> close connection */
371 sdb_object_deref(SDB_OBJ(conn));
372 continue;
373 }
375 /* return the connection to the main loop */
376 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
377 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
378 "connection %s to list of open connections",
379 SDB_OBJ(conn)->name);
380 }
382 /* pass ownership back to list; or destroy in case of an error */
383 sdb_object_deref(SDB_OBJ(conn));
384 }
385 return NULL;
386 } /* connection_handler */
388 static int
389 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
390 {
391 sdb_object_t *obj;
392 int status;
394 obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
395 if (! obj)
396 return -1;
398 status = sdb_llist_append(sock->open_connections, obj);
399 if (status)
400 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
401 "connection %s to list of open connections",
402 obj->name);
404 /* hand ownership over to the list; or destroy in case of an error */
405 sdb_object_deref(obj);
406 return status;
407 } /* connection_accept */
409 static int
410 socket_handle_incoming(sdb_fe_socket_t *sock,
411 fd_set *ready, fd_set *exceptions)
412 {
413 sdb_llist_iter_t *iter;
414 size_t i;
416 for (i = 0; i < sock->listeners_num; ++i) {
417 listener_t *listener = sock->listeners + i;
418 if (FD_ISSET(listener->sock_fd, ready))
419 if (connection_accept(sock, listener))
420 continue;
421 }
423 iter = sdb_llist_get_iter(sock->open_connections);
424 if (! iter) {
425 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
426 "for open connections");
427 return -1;
428 }
430 while (sdb_llist_iter_has_next(iter)) {
431 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
433 if (FD_ISSET(CONN(obj)->fd, exceptions)) {
434 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
435 CONN(obj)->fd);
436 /* close the connection */
437 sdb_llist_iter_remove_current(iter);
438 sdb_object_deref(obj);
439 continue;
440 }
442 if (FD_ISSET(CONN(obj)->fd, ready)) {
443 sdb_llist_iter_remove_current(iter);
444 sdb_channel_write(sock->chan, &obj);
445 }
446 }
447 sdb_llist_iter_destroy(iter);
448 return 0;
449 } /* socket_handle_incoming */
451 /*
452 * public API
453 */
455 sdb_fe_socket_t *
456 sdb_fe_sock_create(void)
457 {
458 sdb_fe_socket_t *sock;
460 sock = calloc(1, sizeof(*sock));
461 if (! sock)
462 return NULL;
464 sock->open_connections = sdb_llist_create();
465 if (! sock->open_connections) {
466 sdb_fe_sock_destroy(sock);
467 return NULL;
468 }
469 return sock;
470 } /* sdb_fe_sock_create */
472 void
473 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
474 {
475 if (! sock)
476 return;
478 socket_clear(sock);
480 sdb_llist_destroy(sock->open_connections);
481 sock->open_connections = NULL;
482 free(sock);
483 } /* sdb_fe_sock_destroy */
485 int
486 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
487 {
488 listener_t *listener;
490 if ((! sock) || (! address))
491 return -1;
493 listener = listener_create(sock, address);
494 if (! listener)
495 return -1;
496 return 0;
497 } /* sdb_fe_sock_add_listener */
499 void
500 sdb_fe_sock_clear_listeners(sdb_fe_socket_t *sock)
501 {
502 if (! sock)
503 return;
505 socket_clear(sock);
506 } /* sdb_fe_sock_clear_listeners */
508 int
509 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
510 {
511 fd_set sockets;
512 int max_listen_fd = 0;
513 size_t i;
515 pthread_t handler_threads[loop->num_threads];
516 size_t num_threads;
518 if ((! sock) || (! sock->listeners_num) || sock->chan
519 || (! loop) || (loop->num_threads <= 0))
520 return -1;
522 if (! loop->do_loop)
523 return 0;
525 FD_ZERO(&sockets);
526 for (i = 0; i < sock->listeners_num; ++i) {
527 listener_t *listener = sock->listeners + i;
529 if (listener_listen(listener)) {
530 socket_close(sock);
531 return -1;
532 }
534 FD_SET(listener->sock_fd, &sockets);
535 if (listener->sock_fd > max_listen_fd)
536 max_listen_fd = listener->sock_fd;
537 }
539 sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
540 if (! sock->chan) {
541 socket_close(sock);
542 return -1;
543 }
545 sdb_log(SDB_LOG_INFO, "frontend: Starting %d connection "
546 "handler thread%s managing %d listener%s",
547 loop->num_threads, loop->num_threads == 1 ? "" : "s",
548 sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
550 num_threads = loop->num_threads;
551 memset(&handler_threads, 0, sizeof(handler_threads));
552 for (i = 0; i < num_threads; ++i) {
553 errno = 0;
554 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
555 connection_handler, /* arg = */ sock)) {
556 char errbuf[1024];
557 sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
558 "connection handler thread: %s",
559 sdb_strerror(errno, errbuf, sizeof(errbuf)));
560 num_threads = i;
561 break;
562 }
563 }
565 while (loop->do_loop && num_threads) {
566 struct timeval timeout = { 1, 0 }; /* one second */
567 sdb_llist_iter_t *iter;
569 int max_fd = max_listen_fd;
570 fd_set ready;
571 fd_set exceptions;
572 int n;
574 FD_ZERO(&ready);
575 FD_ZERO(&exceptions);
577 ready = sockets;
579 iter = sdb_llist_get_iter(sock->open_connections);
580 if (! iter) {
581 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
582 "for open connections");
583 break;
584 }
586 while (sdb_llist_iter_has_next(iter)) {
587 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
589 if (CONN(obj)->fd < 0) {
590 sdb_llist_iter_remove_current(iter);
591 sdb_object_deref(obj);
592 continue;
593 }
595 FD_SET(CONN(obj)->fd, &ready);
596 FD_SET(CONN(obj)->fd, &exceptions);
598 if (CONN(obj)->fd > max_fd)
599 max_fd = CONN(obj)->fd;
600 }
601 sdb_llist_iter_destroy(iter);
603 errno = 0;
604 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
605 if (n < 0) {
606 char buf[1024];
608 if (errno == EINTR)
609 continue;
611 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
612 sdb_strerror(errno, buf, sizeof(buf)));
613 break;
614 }
615 else if (! n)
616 continue;
618 /* handle new and open connections */
619 if (socket_handle_incoming(sock, &ready, &exceptions))
620 break;
621 }
623 socket_close(sock);
625 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
626 "to terminate");
627 if (! sdb_channel_shutdown(sock->chan))
628 for (i = 0; i < num_threads; ++i)
629 pthread_join(handler_threads[i], NULL);
630 /* else: we tried our best; let the operating system clean up */
632 sdb_channel_destroy(sock->chan);
633 sock->chan = NULL;
635 if (! num_threads)
636 return -1;
637 return 0;
638 } /* sdb_fe_sock_listen_and_server */
640 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */