Code

socket frontend: Try to reopen a connection if it has been closed.
[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 #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"
36 #include <assert.h>
38 #include <errno.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
44 #include <unistd.h>
46 #include <fcntl.h>
48 #include <sys/time.h>
49 #include <sys/types.h>
50 #include <sys/select.h>
51 #include <sys/socket.h>
52 #include <sys/un.h>
54 #include <pthread.h>
56 /* name of connection objects */
57 #define CONN_FD_PREFIX "conn#"
58 #define CONN_FD_PLACEHOLDER "XXXXXXX"
60 /*
61  * private data types
62  */
64 typedef struct {
65         int fd;
66         struct sockaddr_storage client_addr;
67         socklen_t client_addr_len;
68 } connection_t;
70 typedef struct {
71         sdb_object_t super;
72         connection_t conn;
73 } connection_obj_t;
74 #define CONN(obj) ((connection_obj_t *)(obj))
76 typedef struct {
77         char *address;
78         int   type;
80         int sock_fd;
81 } listener_t;
83 typedef struct {
84         int type;
85         const char *prefix;
87         int (*opener)(listener_t *);
88 } fe_listener_impl_t;
90 struct sdb_fe_socket {
91         listener_t *listeners;
92         size_t listeners_num;
94         sdb_llist_t *open_connections;
96         /* channel used for communication between main
97          * and connection handler threads */
98         sdb_channel_t *chan;
99 };
101 /*
102  * connection management functions
103  */
105 static int
106 open_unix_sock(listener_t *listener)
108         struct sockaddr_un sa;
109         int status;
111         listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
112         if (listener->sock_fd < 0) {
113                 char buf[1024];
114                 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
115                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
116                 return -1;
117         }
119         memset(&sa, 0, sizeof(sa));
120         sa.sun_family = AF_UNIX;
121         strncpy(sa.sun_path, listener->address + strlen("unix:"),
122                         sizeof(sa.sun_path));
124         status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
125         if (status) {
126                 char buf[1024];
127                 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
128                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
129                 return -1;
130         }
131         return 0;
132 } /* open_unix_sock */
134 /*
135  * private variables
136  */
138 /* the enum has to be sorted the same as the implementations array
139  * to ensure that the type may be used as index into the array */
140 enum {
141         LISTENER_UNIXSOCK = 0,
142 };
143 static fe_listener_impl_t listener_impls[] = {
144         { LISTENER_UNIXSOCK, "unix", open_unix_sock },
145 };
147 /*
148  * private helper functions
149  */
151 static int
152 get_type(const char *address)
154         char *sep;
155         size_t len;
156         size_t i;
158         sep = strchr(address, (int)':');
159         if (! sep)
160                 return -1;
162         assert(sep > address);
163         len = (size_t)(sep - address);
165         for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
166                 fe_listener_impl_t *impl = listener_impls + i;
168                 if (!strncmp(address, impl->prefix, len)) {
169                         assert(impl->type == (int)i);
170                         return impl->type;
171                 }
172         }
173         return -1;
174 } /* get_type */
176 static void
177 listener_destroy(listener_t *listener)
179         if (! listener)
180                 return;
182         if (listener->sock_fd >= 0)
183                 close(listener->sock_fd);
184         listener->sock_fd = -1;
186         if (listener->address)
187                 free(listener->address);
188 } /* listener_destroy */
190 static listener_t *
191 listener_create(sdb_fe_socket_t *sock, const char *address)
193         listener_t *listener;
194         int type;
196         type = get_type(address);
197         if (type < 0) {
198                 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
199                                 "in listen address '%s'", address);
200                 return NULL;
201         }
203         listener = realloc(sock->listeners,
204                         sock->listeners_num * sizeof(*sock->listeners));
205         if (! listener) {
206                 char buf[1024];
207                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
208                                 sdb_strerror(errno, buf, sizeof(buf)));
209                 return NULL;
210         }
212         sock->listeners = listener;
213         listener = sock->listeners + sock->listeners_num;
215         listener->sock_fd = -1;
216         listener->address = strdup(address);
217         if (! listener->address) {
218                 char buf[1024];
219                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
220                                 sdb_strerror(errno, buf, sizeof(buf)));
221                 listener_destroy(listener);
222                 return NULL;
223         }
224         listener->type = type;
226         if (listener_impls[type].opener(listener)) {
227                 /* prints error */
228                 listener_destroy(listener);
229                 return NULL;
230         }
232         ++sock->listeners_num;
233         return listener;
234 } /* listener_create */
236 static int
237 listener_listen(listener_t *listener)
239         assert(listener);
241         /* try to reopen */
242         if (listener->sock_fd < 0)
243                 if (listener_impls[listener->type].opener(listener))
244                         return -1;
245         assert(listener->sock_fd >= 0);
247         if (listen(listener->sock_fd, /* backlog = */ 32)) {
248                 char buf[1024];
249                 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
250                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
251                 return -1;
252         }
253         return 0;
254 } /* listener_listen */
256 static void
257 listener_close(listener_t *listener)
259         assert(listener);
261         if (listener->sock_fd < 0)
262                 return;
264         close(listener->sock_fd);
265         listener->sock_fd = -1;
266 } /* listener_close */
268 static void
269 socket_close(sdb_fe_socket_t *sock)
271         size_t i;
273         assert(sock);
274         for (i = 0; i < sock->listeners_num; ++i)
275                 listener_close(sock->listeners + i);
276 } /* socket_close */
278 /*
279  * private data types
280  */
282 static int
283 connection_init(sdb_object_t *obj, va_list ap)
285         connection_t *conn;
286         int sock_fd;
287         int sock_fl;
289         assert(obj);
290         conn = &CONN(obj)->conn;
292         sock_fd = va_arg(ap, int);
294         conn->client_addr_len = sizeof(conn->client_addr);
295         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
296                         &conn->client_addr_len);
298         if (conn->fd < 0) {
299                 char buf[1024];
300                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
301                                 "connection: %s", sdb_strerror(errno,
302                                         buf, sizeof(buf)));
303                 return -1;
304         }
306         if (conn->client_addr.ss_family != AF_UNIX) {
307                 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
308                                 "unexpected family type %d", conn->client_addr.ss_family);
309                 return -1;
310         }
312         sock_fl = fcntl(conn->fd, F_GETFL);
313         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
314                 char buf[1024];
315                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
316                                 "to non-blocking mode: %s", conn->fd,
317                                 sdb_strerror(errno, buf, sizeof(buf)));
318                 return -1;
319         }
321         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
322                         conn->fd);
324         /* update the object name */
325         snprintf(obj->name + strlen(CONN_FD_PREFIX),
326                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
327         return 0;
328 } /* connection_init */
330 static void
331 connection_destroy(sdb_object_t *obj)
333         connection_t *conn;
335         assert(obj);
336         conn = &CONN(obj)->conn;
338         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection on fd=%i", conn->fd);
339         close(conn->fd);
340         conn->fd = -1;
341 } /* connection_destroy */
343 static sdb_type_t connection_type = {
344         /* size = */ sizeof(connection_obj_t),
345         /* init = */ connection_init,
346         /* destroy = */ connection_destroy,
347 };
349 /*
350  * connection handler functions
351  */
353 /* returns negative value on error, 0 on EOF, number of packets else */
354 static int
355 connection_read(int fd)
357         int n = 0;
359         while (42) {
360                 int32_t cmd;
361                 ssize_t status;
363                 errno = 0;
364                 status = read(fd, &cmd, sizeof(cmd));
365                 if (status < 0) {
366                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
367                                 return n + 1;
368                         return (int)status;
369                 }
370                 else if (! status) /* EOF */
371                         return 0;
373                 /* XXX */
374                 sdb_log(SDB_LOG_DEBUG, "frontend: read command %i from fd=%i",
375                                 cmd, fd);
376                 ++n;
377         }
379         return n + 1;
380 } /* connection_read */
382 static void *
383 connection_handler(void *data)
385         sdb_fe_socket_t *sock = data;
387         assert(sock);
389         while (42) {
390                 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
391                 connection_obj_t *conn;
392                 int status;
394                 errno = 0;
395                 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
396                                 /* write */ NULL, NULL, &timeout);
397                 if (status) {
398                         char buf[1024];
400                         if (errno == ETIMEDOUT)
401                                 continue;
402                         if (errno == EBADF) /* channel shut down */
403                                 break;
405                         sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
406                                         sdb_strerror(errno, buf, sizeof(buf)));
407                         continue;
408                 }
410                 status = connection_read(conn->conn.fd);
411                 if (status <= 0) {
412                         /* error or EOF -> close connection */
413                         sdb_object_deref(SDB_OBJ(conn));
414                 }
415                 else {
416                         if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
417                                 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
418                                                 "connection %s to list of open connections",
419                                                 SDB_OBJ(conn)->name);
420                         }
422                         /* pass ownership back to list; or destroy in case of an error */
423                         sdb_object_deref(SDB_OBJ(conn));
424                 }
425         }
426         return NULL;
427 } /* connection_handler */
429 static int
430 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
432         sdb_object_t *obj;
434         /* the placeholder will be replaced with the accepted file
435          * descriptor when initializing the object */
436         obj = sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
437                         connection_type, listener->sock_fd);
438         if (! obj)
439                 return -1;
441         if (sdb_llist_append(sock->open_connections, obj)) {
442                 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
443                                 "connection %s to list of open connections",
444                                 obj->name);
445                 sdb_object_deref(obj);
446                 return -1;
447         }
449         /* hand ownership over to the list */
450         sdb_object_deref(obj);
451         return 0;
452 } /* connection_accept */
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         size_t i;
480         if (! sock)
481                 return;
483         for (i = 0; i < sock->listeners_num; ++i) {
484                 listener_destroy(sock->listeners + i);
485         }
486         if (sock->listeners)
487                 free(sock->listeners);
488         sock->listeners = NULL;
490         sdb_llist_destroy(sock->open_connections);
491         sock->open_connections = NULL;
492         free(sock);
493 } /* sdb_fe_sock_destroy */
495 int
496 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
498         listener_t *listener;
500         if ((! sock) || (! address))
501                 return -1;
503         listener = listener_create(sock, address);
504         if (! listener)
505                 return -1;
506         return 0;
507 } /* sdb_fe_sock_add_listener */
509 int
510 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
512         fd_set sockets;
513         int max_listen_fd = 0;
514         size_t i;
516         /* XXX: make the number of threads configurable */
517         pthread_t handler_threads[5];
519         if ((! sock) || (! sock->listeners_num) || (! loop) || sock->chan)
520                 return -1;
522         FD_ZERO(&sockets);
523         for (i = 0; i < sock->listeners_num; ++i) {
524                 listener_t *listener = sock->listeners + i;
526                 if (listener_listen(listener)) {
527                         socket_close(sock);
528                         return -1;
529                 }
531                 FD_SET(listener->sock_fd, &sockets);
532                 if (listener->sock_fd > max_listen_fd)
533                         max_listen_fd = listener->sock_fd;
534         }
536         sock->chan = sdb_channel_create(1024, sizeof(connection_obj_t *));
537         if (! sock->chan) {
538                 socket_close(sock);
539                 return -1;
540         }
542         memset(&handler_threads, 0, sizeof(handler_threads));
543         /* XXX: error handling */
544         for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
545                 pthread_create(&handler_threads[i], /* attr = */ NULL,
546                                 connection_handler, /* arg = */ sock);
548         while (loop->do_loop) {
549                 fd_set ready;
550                 fd_set exceptions;
551                 int max_fd;
552                 int n;
554                 struct timeval timeout = { 1, 0 }; /* one second */
555                 sdb_llist_iter_t *iter;
557                 FD_ZERO(&ready);
558                 FD_ZERO(&exceptions);
560                 ready = sockets;
562                 max_fd = max_listen_fd;
564                 iter = sdb_llist_get_iter(sock->open_connections);
565                 if (! iter) {
566                         sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
567                                         "for open connections");
568                         break;
569                 }
571                 while (sdb_llist_iter_has_next(iter)) {
572                         sdb_object_t *obj = sdb_llist_iter_get_next(iter);
573                         FD_SET(CONN(obj)->conn.fd, &ready);
574                         FD_SET(CONN(obj)->conn.fd, &exceptions);
576                         if (CONN(obj)->conn.fd > max_fd)
577                                 max_fd = CONN(obj)->conn.fd;
578                 }
579                 sdb_llist_iter_destroy(iter);
581                 errno = 0;
582                 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
583                 if (n < 0) {
584                         char buf[1024];
586                         if (errno == EINTR)
587                                 continue;
589                         sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
590                                         sdb_strerror(errno, buf, sizeof(buf)));
591                         break;
592                 }
594                 if (! n)
595                         continue;
597                 for (i = 0; i < sock->listeners_num; ++i) {
598                         listener_t *listener = sock->listeners + i;
599                         if (FD_ISSET(listener->sock_fd, &ready))
600                                 if (connection_accept(sock, listener))
601                                         continue;
602                 }
604                 iter = sdb_llist_get_iter(sock->open_connections);
605                 if (! iter) {
606                         sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
607                                         "for open connections");
608                         break;
609                 }
611                 while (sdb_llist_iter_has_next(iter)) {
612                         sdb_object_t *obj = sdb_llist_iter_get_next(iter);
614                         if (FD_ISSET(CONN(obj)->conn.fd, &exceptions))
615                                 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
616                                                 CONN(obj)->conn.fd);
618                         if (FD_ISSET(CONN(obj)->conn.fd, &ready)) {
619                                 sdb_llist_iter_remove_current(iter);
620                                 sdb_channel_write(sock->chan, &obj);
621                         }
622                 }
623                 sdb_llist_iter_destroy(iter);
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 < SDB_STATIC_ARRAY_LEN(handler_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;
637         return 0;
638 } /* sdb_fe_sock_listen_and_server */
640 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */