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 int (*accept)(sdb_conn_t *);
72 } listener_t;
74 typedef struct {
75 int type;
76 const char *prefix;
78 int (*open)(listener_t *);
79 void (*close)(listener_t *);
80 } fe_listener_impl_t;
82 struct sdb_fe_socket {
83 listener_t *listeners;
84 size_t listeners_num;
86 sdb_llist_t *open_connections;
88 /* channel used for communication between main
89 * and connection handler threads */
90 sdb_channel_t *chan;
91 };
93 /*
94 * connection management functions
95 */
97 static int
98 open_unix_sock(listener_t *listener)
99 {
100 const char *addr;
101 char *addr_copy;
102 char *base_dir;
103 struct sockaddr_un sa;
104 int status;
106 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
107 if (listener->sock_fd < 0) {
108 char buf[1024];
109 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
110 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
111 return -1;
112 }
114 if (*listener->address == '/')
115 addr = listener->address;
116 else
117 addr = listener->address + strlen("unix:");
119 memset(&sa, 0, sizeof(sa));
120 sa.sun_family = AF_UNIX;
121 strncpy(sa.sun_path, addr, sizeof(sa.sun_path));
123 addr_copy = strdup(addr);
124 if (! addr_copy) {
125 char errbuf[1024];
126 sdb_log(SDB_LOG_ERR, "frontend: strdup failed: %s",
127 sdb_strerror(errno, errbuf, sizeof(errbuf)));
128 return -1;
129 }
130 base_dir = dirname(addr_copy);
132 /* ensure that the directory exists */
133 if (sdb_mkdir_all(base_dir, 0777)) {
134 char errbuf[1024];
135 sdb_log(SDB_LOG_ERR, "frontend: Failed to create directory '%s': %s",
136 base_dir, sdb_strerror(errno, errbuf, sizeof(errbuf)));
137 free(addr_copy);
138 return -1;
139 }
140 free(addr_copy);
142 if (unlink(addr) && (errno != ENOENT)) {
143 char errbuf[1024];
144 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
145 "socket %s: %s", listener->address + strlen("unix:"),
146 sdb_strerror(errno, errbuf, sizeof(errbuf)));
147 }
149 status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
150 if (status) {
151 char buf[1024];
152 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
153 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
154 return -1;
155 }
156 return 0;
157 } /* open_unix_sock */
159 static void
160 close_unix_sock(listener_t *listener)
161 {
162 const char *addr;
163 assert(listener);
165 if (! listener->address)
166 return;
168 if (*listener->address == '/')
169 addr = listener->address;
170 else
171 addr = listener->address + strlen("unix:");
173 if (listener->sock_fd >= 0)
174 close(listener->sock_fd);
175 listener->sock_fd = -1;
177 unlink(addr);
178 } /* close_unix_sock */
180 /*
181 * private variables
182 */
184 /* the enum has to be sorted the same as the implementations array
185 * to ensure that the type may be used as index into the array */
186 enum {
187 LISTENER_UNIXSOCK = 0, /* this is the default */
188 };
189 static fe_listener_impl_t listener_impls[] = {
190 { LISTENER_UNIXSOCK, "unix", open_unix_sock, close_unix_sock },
191 };
193 /*
194 * private helper functions
195 */
197 static int
198 listener_listen(listener_t *listener)
199 {
200 assert(listener);
202 /* try to reopen */
203 if (listener->sock_fd < 0)
204 if (listener_impls[listener->type].open(listener))
205 return -1;
206 assert(listener->sock_fd >= 0);
208 if (listen(listener->sock_fd, /* backlog = */ 32)) {
209 char buf[1024];
210 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
211 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
212 return -1;
213 }
214 return 0;
215 } /* listener_listen */
217 static void
218 listener_close(listener_t *listener)
219 {
220 assert(listener);
222 if (listener_impls[listener->type].close)
223 listener_impls[listener->type].close(listener);
225 if (listener->sock_fd >= 0)
226 close(listener->sock_fd);
227 listener->sock_fd = -1;
228 } /* listener_close */
230 static int
231 get_type(const char *address)
232 {
233 char *sep;
234 size_t len;
235 size_t i;
237 sep = strchr(address, (int)':');
238 if (! sep)
239 return listener_impls[0].type;
241 assert(sep > address);
242 len = (size_t)(sep - address);
244 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
245 fe_listener_impl_t *impl = listener_impls + i;
247 if (!strncmp(address, impl->prefix, len)) {
248 assert(impl->type == (int)i);
249 return impl->type;
250 }
251 }
252 return -1;
253 } /* get_type */
255 static void
256 listener_destroy(listener_t *listener)
257 {
258 if (! listener)
259 return;
261 listener_close(listener);
263 if (listener->address)
264 free(listener->address);
265 listener->address = NULL;
266 } /* listener_destroy */
268 static listener_t *
269 listener_create(sdb_fe_socket_t *sock, const char *address)
270 {
271 listener_t *listener;
272 int type;
274 type = get_type(address);
275 if (type < 0) {
276 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
277 "in listen address '%s'", address);
278 return NULL;
279 }
281 listener = realloc(sock->listeners,
282 (sock->listeners_num + 1) * sizeof(*sock->listeners));
283 if (! listener) {
284 char buf[1024];
285 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
286 sdb_strerror(errno, buf, sizeof(buf)));
287 return NULL;
288 }
290 sock->listeners = listener;
291 listener = sock->listeners + sock->listeners_num;
293 listener->sock_fd = -1;
294 listener->address = strdup(address);
295 if (! listener->address) {
296 char buf[1024];
297 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
298 sdb_strerror(errno, buf, sizeof(buf)));
299 listener_destroy(listener);
300 return NULL;
301 }
302 listener->type = type;
303 listener->accept = NULL;
305 if (listener_impls[type].open(listener)) {
306 /* prints error */
307 listener_destroy(listener);
308 return NULL;
309 }
311 ++sock->listeners_num;
312 return listener;
313 } /* listener_create */
315 static void
316 socket_clear(sdb_fe_socket_t *sock)
317 {
318 size_t i;
320 assert(sock);
321 for (i = 0; i < sock->listeners_num; ++i)
322 listener_destroy(sock->listeners + i);
323 if (sock->listeners)
324 free(sock->listeners);
325 sock->listeners = NULL;
326 sock->listeners_num = 0;
327 } /* socket_clear */
329 static void
330 socket_close(sdb_fe_socket_t *sock)
331 {
332 size_t i;
334 assert(sock);
335 for (i = 0; i < sock->listeners_num; ++i)
336 listener_close(sock->listeners + i);
337 } /* socket_close */
339 /*
340 * connection handler functions
341 */
343 static void *
344 connection_handler(void *data)
345 {
346 sdb_fe_socket_t *sock = data;
348 assert(sock);
350 while (42) {
351 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
352 sdb_conn_t *conn;
353 int status;
355 errno = 0;
356 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
357 /* write */ NULL, NULL, &timeout);
358 if (status) {
359 char buf[1024];
361 if (errno == ETIMEDOUT)
362 continue;
363 if (errno == EBADF) /* channel shut down */
364 break;
366 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
367 sdb_strerror(errno, buf, sizeof(buf)));
368 continue;
369 }
371 status = (int)sdb_connection_handle(conn);
372 if (status <= 0) {
373 /* error or EOF -> close connection */
374 sdb_object_deref(SDB_OBJ(conn));
375 continue;
376 }
378 /* return the connection to the main loop */
379 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
380 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
381 "connection %s to list of open connections",
382 SDB_OBJ(conn)->name);
383 }
385 /* pass ownership back to list; or destroy in case of an error */
386 sdb_object_deref(SDB_OBJ(conn));
387 }
388 return NULL;
389 } /* connection_handler */
391 static int
392 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
393 {
394 sdb_object_t *obj;
395 int status;
397 obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
398 if (! obj)
399 return -1;
401 if (listener->accept && listener->accept(CONN(obj))) {
402 /* accept() is expected to log an error */
403 sdb_object_deref(obj);
404 return -1;
405 }
407 status = sdb_llist_append(sock->open_connections, obj);
408 if (status)
409 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
410 "connection %s to list of open connections",
411 obj->name);
413 /* hand ownership over to the list; or destroy in case of an error */
414 sdb_object_deref(obj);
415 return status;
416 } /* connection_accept */
418 static int
419 socket_handle_incoming(sdb_fe_socket_t *sock,
420 fd_set *ready, fd_set *exceptions)
421 {
422 sdb_llist_iter_t *iter;
423 size_t i;
425 for (i = 0; i < sock->listeners_num; ++i) {
426 listener_t *listener = sock->listeners + i;
427 if (FD_ISSET(listener->sock_fd, ready))
428 if (connection_accept(sock, listener))
429 continue;
430 }
432 iter = sdb_llist_get_iter(sock->open_connections);
433 if (! iter) {
434 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
435 "for open connections");
436 return -1;
437 }
439 while (sdb_llist_iter_has_next(iter)) {
440 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
442 if (FD_ISSET(CONN(obj)->fd, exceptions)) {
443 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
444 CONN(obj)->fd);
445 /* close the connection */
446 sdb_llist_iter_remove_current(iter);
447 sdb_object_deref(obj);
448 continue;
449 }
451 if (FD_ISSET(CONN(obj)->fd, ready)) {
452 sdb_llist_iter_remove_current(iter);
453 sdb_channel_write(sock->chan, &obj);
454 }
455 }
456 sdb_llist_iter_destroy(iter);
457 return 0;
458 } /* socket_handle_incoming */
460 /*
461 * public API
462 */
464 sdb_fe_socket_t *
465 sdb_fe_sock_create(void)
466 {
467 sdb_fe_socket_t *sock;
469 sock = calloc(1, sizeof(*sock));
470 if (! sock)
471 return NULL;
473 sock->open_connections = sdb_llist_create();
474 if (! sock->open_connections) {
475 sdb_fe_sock_destroy(sock);
476 return NULL;
477 }
478 return sock;
479 } /* sdb_fe_sock_create */
481 void
482 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
483 {
484 if (! sock)
485 return;
487 socket_clear(sock);
489 sdb_llist_destroy(sock->open_connections);
490 sock->open_connections = NULL;
491 free(sock);
492 } /* sdb_fe_sock_destroy */
494 int
495 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
496 {
497 listener_t *listener;
499 if ((! sock) || (! address))
500 return -1;
502 listener = listener_create(sock, address);
503 if (! listener)
504 return -1;
505 return 0;
506 } /* sdb_fe_sock_add_listener */
508 void
509 sdb_fe_sock_clear_listeners(sdb_fe_socket_t *sock)
510 {
511 if (! sock)
512 return;
514 socket_clear(sock);
515 } /* sdb_fe_sock_clear_listeners */
517 int
518 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
519 {
520 fd_set sockets;
521 int max_listen_fd = 0;
522 size_t i;
524 pthread_t handler_threads[loop->num_threads];
525 size_t num_threads;
527 if ((! sock) || (! sock->listeners_num) || sock->chan
528 || (! loop) || (loop->num_threads <= 0))
529 return -1;
531 if (! loop->do_loop)
532 return 0;
534 FD_ZERO(&sockets);
535 for (i = 0; i < sock->listeners_num; ++i) {
536 listener_t *listener = sock->listeners + i;
538 if (listener_listen(listener)) {
539 socket_close(sock);
540 return -1;
541 }
543 FD_SET(listener->sock_fd, &sockets);
544 if (listener->sock_fd > max_listen_fd)
545 max_listen_fd = listener->sock_fd;
546 }
548 sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
549 if (! sock->chan) {
550 socket_close(sock);
551 return -1;
552 }
554 sdb_log(SDB_LOG_INFO, "frontend: Starting %zu connection "
555 "handler thread%s managing %zu listener%s",
556 loop->num_threads, loop->num_threads == 1 ? "" : "s",
557 sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
559 num_threads = loop->num_threads;
560 memset(&handler_threads, 0, sizeof(handler_threads));
561 for (i = 0; i < num_threads; ++i) {
562 errno = 0;
563 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
564 connection_handler, /* arg = */ sock)) {
565 char errbuf[1024];
566 sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
567 "connection handler thread: %s",
568 sdb_strerror(errno, errbuf, sizeof(errbuf)));
569 num_threads = i;
570 break;
571 }
572 }
574 while (loop->do_loop && num_threads) {
575 struct timeval timeout = { 1, 0 }; /* one second */
576 sdb_llist_iter_t *iter;
578 int max_fd = max_listen_fd;
579 fd_set ready;
580 fd_set exceptions;
581 int n;
583 FD_ZERO(&ready);
584 FD_ZERO(&exceptions);
586 ready = sockets;
588 iter = sdb_llist_get_iter(sock->open_connections);
589 if (! iter) {
590 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
591 "for open connections");
592 break;
593 }
595 while (sdb_llist_iter_has_next(iter)) {
596 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
598 if (CONN(obj)->fd < 0) {
599 sdb_llist_iter_remove_current(iter);
600 sdb_object_deref(obj);
601 continue;
602 }
604 FD_SET(CONN(obj)->fd, &ready);
605 FD_SET(CONN(obj)->fd, &exceptions);
607 if (CONN(obj)->fd > max_fd)
608 max_fd = CONN(obj)->fd;
609 }
610 sdb_llist_iter_destroy(iter);
612 errno = 0;
613 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
614 if (n < 0) {
615 char buf[1024];
617 if (errno == EINTR)
618 continue;
620 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
621 sdb_strerror(errno, buf, sizeof(buf)));
622 break;
623 }
624 else if (! n)
625 continue;
627 /* handle new and open connections */
628 if (socket_handle_incoming(sock, &ready, &exceptions))
629 break;
630 }
632 socket_close(sock);
634 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
635 "to terminate");
636 if (! sdb_channel_shutdown(sock->chan))
637 for (i = 0; i < num_threads; ++i)
638 pthread_join(handler_threads[i], NULL);
639 /* else: we tried our best; let the operating system clean up */
641 sdb_channel_destroy(sock->chan);
642 sock->chan = NULL;
644 if (! num_threads)
645 return -1;
646 return 0;
647 } /* sdb_fe_sock_listen_and_server */
649 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */