Code

frontend/sock: Simplified internal address handling.
[sysdb.git] / src / frontend / sock.c
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_unixsock(listener_t *listener)
99 {
100         char *addr_copy;
101         char *base_dir;
102         struct sockaddr_un sa;
103         int status;
105         listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
106         if (listener->sock_fd < 0) {
107                 char buf[1024];
108                 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
109                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
110                 return -1;
111         }
113         memset(&sa, 0, sizeof(sa));
114         sa.sun_family = AF_UNIX;
115         strncpy(sa.sun_path, listener->address, sizeof(sa.sun_path));
117         addr_copy = strdup(listener->address);
118         if (! addr_copy) {
119                 char errbuf[1024];
120                 sdb_log(SDB_LOG_ERR, "frontend: strdup failed: %s",
121                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
122                 return -1;
123         }
124         base_dir = dirname(addr_copy);
126         /* ensure that the directory exists */
127         if (sdb_mkdir_all(base_dir, 0777)) {
128                 char errbuf[1024];
129                 sdb_log(SDB_LOG_ERR, "frontend: Failed to create directory '%s': %s",
130                                 base_dir, sdb_strerror(errno, errbuf, sizeof(errbuf)));
131                 free(addr_copy);
132                 return -1;
133         }
134         free(addr_copy);
136         if (unlink(listener->address) && (errno != ENOENT)) {
137                 char errbuf[1024];
138                 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
139                                 "socket %s: %s", listener->address,
140                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
141         }
143         status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
144         if (status) {
145                 char buf[1024];
146                 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
147                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
148                 return -1;
149         }
150         return 0;
151 } /* open_unixsock */
153 static void
154 close_unixsock(listener_t *listener)
156         assert(listener);
158         if (! listener->address)
159                 return;
161         if (listener->sock_fd >= 0)
162                 close(listener->sock_fd);
163         listener->sock_fd = -1;
165         unlink(listener->address);
166 } /* close_unixsock */
168 /*
169  * private variables
170  */
172 /* the enum has to be sorted the same as the implementations array
173  * to ensure that the type may be used as index into the array */
174 enum {
175         LISTENER_UNIXSOCK = 0, /* this is the default */
176 };
177 static fe_listener_impl_t listener_impls[] = {
178         { LISTENER_UNIXSOCK, "unix", open_unixsock, close_unixsock },
179 };
181 /*
182  * private helper functions
183  */
185 static int
186 listener_listen(listener_t *listener)
188         assert(listener);
190         /* try to reopen */
191         if (listener->sock_fd < 0)
192                 if (listener_impls[listener->type].open(listener))
193                         return -1;
194         assert(listener->sock_fd >= 0);
196         if (listen(listener->sock_fd, /* backlog = */ 32)) {
197                 char buf[1024];
198                 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
199                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
200                 return -1;
201         }
202         return 0;
203 } /* listener_listen */
205 static void
206 listener_close(listener_t *listener)
208         assert(listener);
210         if (listener_impls[listener->type].close)
211                 listener_impls[listener->type].close(listener);
213         if (listener->sock_fd >= 0)
214                 close(listener->sock_fd);
215         listener->sock_fd = -1;
216 } /* listener_close */
218 static int
219 get_type(const char *address)
221         char *sep;
222         size_t len;
223         size_t i;
225         sep = strchr(address, (int)':');
226         if (! sep)
227                 return listener_impls[0].type;
229         assert(sep > address);
230         len = (size_t)(sep - address);
232         for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
233                 fe_listener_impl_t *impl = listener_impls + i;
235                 if (!strncmp(address, impl->prefix, len)) {
236                         assert(impl->type == (int)i);
237                         return impl->type;
238                 }
239         }
240         return -1;
241 } /* get_type */
243 static void
244 listener_destroy(listener_t *listener)
246         if (! listener)
247                 return;
249         listener_close(listener);
251         if (listener->address)
252                 free(listener->address);
253         listener->address = NULL;
254 } /* listener_destroy */
256 static listener_t *
257 listener_create(sdb_fe_socket_t *sock, const char *address)
259         listener_t *listener;
260         size_t len;
261         int type;
263         type = get_type(address);
264         if (type < 0) {
265                 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
266                                 "in listen address '%s'", address);
267                 return NULL;
268         }
270         listener = realloc(sock->listeners,
271                         (sock->listeners_num + 1) * sizeof(*sock->listeners));
272         if (! listener) {
273                 char buf[1024];
274                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
275                                 sdb_strerror(errno, buf, sizeof(buf)));
276                 return NULL;
277         }
279         sock->listeners = listener;
280         listener = sock->listeners + sock->listeners_num;
282         len = strlen(listener_impls[type].prefix);
283         if ((! strncmp(address, listener_impls[type].prefix, len))
284                         && (address[len] == ':'))
285                 address += strlen(listener_impls[type].prefix) + 1;
287         listener->sock_fd = -1;
288         listener->address = strdup(address);
289         if (! listener->address) {
290                 char buf[1024];
291                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
292                                 sdb_strerror(errno, buf, sizeof(buf)));
293                 listener_destroy(listener);
294                 return NULL;
295         }
296         listener->type = type;
297         listener->accept = NULL;
299         if (listener_impls[type].open(listener)) {
300                 /* prints error */
301                 listener_destroy(listener);
302                 return NULL;
303         }
305         ++sock->listeners_num;
306         return listener;
307 } /* listener_create */
309 static void
310 socket_clear(sdb_fe_socket_t *sock)
312         size_t i;
314         assert(sock);
315         for (i = 0; i < sock->listeners_num; ++i)
316                 listener_destroy(sock->listeners + i);
317         if (sock->listeners)
318                 free(sock->listeners);
319         sock->listeners = NULL;
320         sock->listeners_num = 0;
321 } /* socket_clear */
323 static void
324 socket_close(sdb_fe_socket_t *sock)
326         size_t i;
328         assert(sock);
329         for (i = 0; i < sock->listeners_num; ++i)
330                 listener_close(sock->listeners + i);
331 } /* socket_close */
333 /*
334  * connection handler functions
335  */
337 static void *
338 connection_handler(void *data)
340         sdb_fe_socket_t *sock = data;
342         assert(sock);
344         while (42) {
345                 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
346                 sdb_conn_t *conn;
347                 int status;
349                 errno = 0;
350                 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
351                                 /* write */ NULL, NULL, &timeout);
352                 if (status) {
353                         char buf[1024];
355                         if (errno == ETIMEDOUT)
356                                 continue;
357                         if (errno == EBADF) /* channel shut down */
358                                 break;
360                         sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
361                                         sdb_strerror(errno, buf, sizeof(buf)));
362                         continue;
363                 }
365                 status = (int)sdb_connection_handle(conn);
366                 if (status <= 0) {
367                         /* error or EOF -> close connection */
368                         sdb_object_deref(SDB_OBJ(conn));
369                         continue;
370                 }
372                 /* return the connection to the main loop */
373                 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
374                         sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
375                                         "connection %s to list of open connections",
376                                         SDB_OBJ(conn)->name);
377                 }
379                 /* pass ownership back to list; or destroy in case of an error */
380                 sdb_object_deref(SDB_OBJ(conn));
381         }
382         return NULL;
383 } /* connection_handler */
385 static int
386 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
388         sdb_object_t *obj;
389         int status;
391         obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
392         if (! obj)
393                 return -1;
395         if (listener->accept && listener->accept(CONN(obj))) {
396                 /* accept() is expected to log an error */
397                 sdb_object_deref(obj);
398                 return -1;
399         }
401         status = sdb_llist_append(sock->open_connections, obj);
402         if (status)
403                 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
404                                 "connection %s to list of open connections",
405                                 obj->name);
407         /* hand ownership over to the list; or destroy in case of an error */
408         sdb_object_deref(obj);
409         return status;
410 } /* connection_accept */
412 static int
413 socket_handle_incoming(sdb_fe_socket_t *sock,
414                 fd_set *ready, fd_set *exceptions)
416         sdb_llist_iter_t *iter;
417         size_t i;
419         for (i = 0; i < sock->listeners_num; ++i) {
420                 listener_t *listener = sock->listeners + i;
421                 if (FD_ISSET(listener->sock_fd, ready))
422                         if (connection_accept(sock, listener))
423                                 continue;
424         }
426         iter = sdb_llist_get_iter(sock->open_connections);
427         if (! iter) {
428                 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
429                                 "for open connections");
430                 return -1;
431         }
433         while (sdb_llist_iter_has_next(iter)) {
434                 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
436                 if (FD_ISSET(CONN(obj)->fd, exceptions)) {
437                         sdb_log(SDB_LOG_INFO, "Exception on fd %d",
438                                         CONN(obj)->fd);
439                         /* close the connection */
440                         sdb_llist_iter_remove_current(iter);
441                         sdb_object_deref(obj);
442                         continue;
443                 }
445                 if (FD_ISSET(CONN(obj)->fd, ready)) {
446                         sdb_llist_iter_remove_current(iter);
447                         sdb_channel_write(sock->chan, &obj);
448                 }
449         }
450         sdb_llist_iter_destroy(iter);
451         return 0;
452 } /* socket_handle_incoming */
454 /*
455  * public API
456  */
458 sdb_fe_socket_t *
459 sdb_fe_sock_create(void)
461         sdb_fe_socket_t *sock;
463         sock = calloc(1, sizeof(*sock));
464         if (! sock)
465                 return NULL;
467         sock->open_connections = sdb_llist_create();
468         if (! sock->open_connections) {
469                 sdb_fe_sock_destroy(sock);
470                 return NULL;
471         }
472         return sock;
473 } /* sdb_fe_sock_create */
475 void
476 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
478         if (! sock)
479                 return;
481         socket_clear(sock);
483         sdb_llist_destroy(sock->open_connections);
484         sock->open_connections = NULL;
485         free(sock);
486 } /* sdb_fe_sock_destroy */
488 int
489 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
491         listener_t *listener;
493         if ((! sock) || (! address))
494                 return -1;
496         listener = listener_create(sock, address);
497         if (! listener)
498                 return -1;
499         return 0;
500 } /* sdb_fe_sock_add_listener */
502 void
503 sdb_fe_sock_clear_listeners(sdb_fe_socket_t *sock)
505         if (! sock)
506                 return;
508         socket_clear(sock);
509 } /* sdb_fe_sock_clear_listeners */
511 int
512 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
514         fd_set sockets;
515         int max_listen_fd = 0;
516         size_t i;
518         pthread_t handler_threads[loop->num_threads];
519         size_t num_threads;
521         if ((! sock) || (! sock->listeners_num) || sock->chan
522                         || (! loop) || (loop->num_threads <= 0))
523                 return -1;
525         if (! loop->do_loop)
526                 return 0;
528         FD_ZERO(&sockets);
529         for (i = 0; i < sock->listeners_num; ++i) {
530                 listener_t *listener = sock->listeners + i;
532                 if (listener_listen(listener)) {
533                         socket_close(sock);
534                         return -1;
535                 }
537                 FD_SET(listener->sock_fd, &sockets);
538                 if (listener->sock_fd > max_listen_fd)
539                         max_listen_fd = listener->sock_fd;
540         }
542         sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
543         if (! sock->chan) {
544                 socket_close(sock);
545                 return -1;
546         }
548         sdb_log(SDB_LOG_INFO, "frontend: Starting %zu connection "
549                         "handler thread%s managing %zu listener%s",
550                         loop->num_threads, loop->num_threads == 1 ? "" : "s",
551                         sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
553         num_threads = loop->num_threads;
554         memset(&handler_threads, 0, sizeof(handler_threads));
555         for (i = 0; i < num_threads; ++i) {
556                 errno = 0;
557                 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
558                                         connection_handler, /* arg = */ sock)) {
559                         char errbuf[1024];
560                         sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
561                                         "connection handler thread: %s",
562                                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
563                         num_threads = i;
564                         break;
565                 }
566         }
568         while (loop->do_loop && num_threads) {
569                 struct timeval timeout = { 1, 0 }; /* one second */
570                 sdb_llist_iter_t *iter;
572                 int max_fd = max_listen_fd;
573                 fd_set ready;
574                 fd_set exceptions;
575                 int n;
577                 FD_ZERO(&ready);
578                 FD_ZERO(&exceptions);
580                 ready = sockets;
582                 iter = sdb_llist_get_iter(sock->open_connections);
583                 if (! iter) {
584                         sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
585                                         "for open connections");
586                         break;
587                 }
589                 while (sdb_llist_iter_has_next(iter)) {
590                         sdb_object_t *obj = sdb_llist_iter_get_next(iter);
592                         if (CONN(obj)->fd < 0) {
593                                 sdb_llist_iter_remove_current(iter);
594                                 sdb_object_deref(obj);
595                                 continue;
596                         }
598                         FD_SET(CONN(obj)->fd, &ready);
599                         FD_SET(CONN(obj)->fd, &exceptions);
601                         if (CONN(obj)->fd > max_fd)
602                                 max_fd = CONN(obj)->fd;
603                 }
604                 sdb_llist_iter_destroy(iter);
606                 errno = 0;
607                 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
608                 if (n < 0) {
609                         char buf[1024];
611                         if (errno == EINTR)
612                                 continue;
614                         sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
615                                         sdb_strerror(errno, buf, sizeof(buf)));
616                         break;
617                 }
618                 else if (! n)
619                         continue;
621                 /* handle new and open connections */
622                 if (socket_handle_incoming(sock, &ready, &exceptions))
623                         break;
624         }
626         socket_close(sock);
628         sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
629                         "to terminate");
630         if (! sdb_channel_shutdown(sock->chan))
631                 for (i = 0; i < num_threads; ++i)
632                         pthread_join(handler_threads[i], NULL);
633         /* else: we tried our best; let the operating system clean up */
635         sdb_channel_destroy(sock->chan);
636         sock->chan = NULL;
638         if (! num_threads)
639                 return -1;
640         return 0;
641 } /* sdb_fe_sock_listen_and_server */
643 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */