Code

frontend: Be more robust in case of failed connections.
[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/strbuf.h"
42 #include <assert.h>
43 #include <errno.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
49 #include <unistd.h>
51 #include <sys/time.h>
52 #include <sys/types.h>
53 #include <sys/select.h>
54 #include <sys/socket.h>
55 #include <sys/un.h>
57 #include <pthread.h>
59 /*
60  * private data types
61  */
63 typedef struct {
64         char *address;
65         int   type;
67         int sock_fd;
68 } listener_t;
70 typedef struct {
71         int type;
72         const char *prefix;
74         int (*opener)(listener_t *);
75         void (*closer)(listener_t *);
76 } fe_listener_impl_t;
78 struct sdb_fe_socket {
79         listener_t *listeners;
80         size_t listeners_num;
82         sdb_llist_t *open_connections;
84         /* channel used for communication between main
85          * and connection handler threads */
86         sdb_channel_t *chan;
87 };
89 /*
90  * connection management functions
91  */
93 static int
94 open_unix_sock(listener_t *listener)
95 {
96         struct sockaddr_un sa;
97         int status;
99         listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
100         if (listener->sock_fd < 0) {
101                 char buf[1024];
102                 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
103                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
104                 return -1;
105         }
107         memset(&sa, 0, sizeof(sa));
108         sa.sun_family = AF_UNIX;
109         strncpy(sa.sun_path, listener->address + strlen("unix:"),
110                         sizeof(sa.sun_path));
112         if (unlink(listener->address + strlen("unix:")) && (errno != ENOENT)) {
113                 char errbuf[1024];
114                 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
115                                 "socket %s: %s", listener->address + strlen("unix:"),
116                                 sdb_strerror(errno, errbuf, sizeof(errbuf)));
117         }
119         status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
120         if (status) {
121                 char buf[1024];
122                 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
123                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
124                 return -1;
125         }
126         return 0;
127 } /* open_unix_sock */
129 static void
130 close_unix_sock(listener_t *listener)
132         assert(listener);
133         if (! listener->address)
134                 return;
136         if (listener->sock_fd >= 0)
137                 close(listener->sock_fd);
138         listener->sock_fd = -1;
140         unlink(listener->address + strlen("unix:"));
141 } /* close_unix_sock */
143 /*
144  * private variables
145  */
147 /* the enum has to be sorted the same as the implementations array
148  * to ensure that the type may be used as index into the array */
149 enum {
150         LISTENER_UNIXSOCK = 0,
151 };
152 static fe_listener_impl_t listener_impls[] = {
153         { LISTENER_UNIXSOCK, "unix", open_unix_sock, close_unix_sock },
154 };
156 /*
157  * private helper functions
158  */
160 static int
161 listener_listen(listener_t *listener)
163         assert(listener);
165         /* try to reopen */
166         if (listener->sock_fd < 0)
167                 if (listener_impls[listener->type].opener(listener))
168                         return -1;
169         assert(listener->sock_fd >= 0);
171         if (listen(listener->sock_fd, /* backlog = */ 32)) {
172                 char buf[1024];
173                 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
174                                 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
175                 return -1;
176         }
177         return 0;
178 } /* listener_listen */
180 static void
181 listener_close(listener_t *listener)
183         assert(listener);
185         if (listener_impls[listener->type].closer)
186                 listener_impls[listener->type].closer(listener);
188         if (listener->sock_fd >= 0)
189                 close(listener->sock_fd);
190         listener->sock_fd = -1;
191 } /* listener_close */
193 static int
194 get_type(const char *address)
196         char *sep;
197         size_t len;
198         size_t i;
200         sep = strchr(address, (int)':');
201         if (! sep)
202                 return -1;
204         assert(sep > address);
205         len = (size_t)(sep - address);
207         for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
208                 fe_listener_impl_t *impl = listener_impls + i;
210                 if (!strncmp(address, impl->prefix, len)) {
211                         assert(impl->type == (int)i);
212                         return impl->type;
213                 }
214         }
215         return -1;
216 } /* get_type */
218 static void
219 listener_destroy(listener_t *listener)
221         if (! listener)
222                 return;
224         listener_close(listener);
226         if (listener->address)
227                 free(listener->address);
228         listener->address = NULL;
229 } /* listener_destroy */
231 static listener_t *
232 listener_create(sdb_fe_socket_t *sock, const char *address)
234         listener_t *listener;
235         int type;
237         type = get_type(address);
238         if (type < 0) {
239                 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
240                                 "in listen address '%s'", address);
241                 return NULL;
242         }
244         listener = realloc(sock->listeners,
245                         (sock->listeners_num + 1) * sizeof(*sock->listeners));
246         if (! listener) {
247                 char buf[1024];
248                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
249                                 sdb_strerror(errno, buf, sizeof(buf)));
250                 return NULL;
251         }
253         sock->listeners = listener;
254         listener = sock->listeners + sock->listeners_num;
256         listener->sock_fd = -1;
257         listener->address = strdup(address);
258         if (! listener->address) {
259                 char buf[1024];
260                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
261                                 sdb_strerror(errno, buf, sizeof(buf)));
262                 listener_destroy(listener);
263                 return NULL;
264         }
265         listener->type = type;
267         if (listener_impls[type].opener(listener)) {
268                 /* prints error */
269                 listener_destroy(listener);
270                 return NULL;
271         }
273         ++sock->listeners_num;
274         return listener;
275 } /* listener_create */
277 static void
278 socket_close(sdb_fe_socket_t *sock)
280         size_t i;
282         assert(sock);
283         for (i = 0; i < sock->listeners_num; ++i)
284                 listener_close(sock->listeners + i);
285 } /* socket_close */
287 /*
288  * connection handler functions
289  */
291 static void *
292 connection_handler(void *data)
294         sdb_fe_socket_t *sock = data;
296         assert(sock);
298         while (42) {
299                 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
300                 sdb_conn_t *conn;
301                 int status;
303                 errno = 0;
304                 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
305                                 /* write */ NULL, NULL, &timeout);
306                 if (status) {
307                         char buf[1024];
309                         if (errno == ETIMEDOUT)
310                                 continue;
311                         if (errno == EBADF) /* channel shut down */
312                                 break;
314                         sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
315                                         sdb_strerror(errno, buf, sizeof(buf)));
316                         continue;
317                 }
319                 status = (int)sdb_connection_read(conn);
320                 if (status <= 0) {
321                         /* error or EOF -> close connection */
322                         sdb_object_deref(SDB_OBJ(conn));
323                         continue;
324                 }
326                 /* return the connection to the main loop */
327                 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
328                         sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
329                                         "connection %s to list of open connections",
330                                         SDB_OBJ(conn)->name);
331                 }
333                 /* pass ownership back to list; or destroy in case of an error */
334                 sdb_object_deref(SDB_OBJ(conn));
335         }
336         return NULL;
337 } /* connection_handler */
339 static int
340 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
342         sdb_object_t *obj;
343         int status;
345         obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
346         if (! obj)
347                 return -1;
349         status = sdb_llist_append(sock->open_connections, obj);
350         if (status)
351                 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
352                                 "connection %s to list of open connections",
353                                 obj->name);
355         /* hand ownership over to the list; or destroy in case of an error */
356         sdb_object_deref(obj);
357         return status;
358 } /* connection_accept */
360 static int
361 socket_handle_incoming(sdb_fe_socket_t *sock,
362                 fd_set *ready, fd_set *exceptions)
364         sdb_llist_iter_t *iter;
365         size_t i;
367         for (i = 0; i < sock->listeners_num; ++i) {
368                 listener_t *listener = sock->listeners + i;
369                 if (FD_ISSET(listener->sock_fd, ready))
370                         if (connection_accept(sock, listener))
371                                 continue;
372         }
374         iter = sdb_llist_get_iter(sock->open_connections);
375         if (! iter) {
376                 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
377                                 "for open connections");
378                 return -1;
379         }
381         while (sdb_llist_iter_has_next(iter)) {
382                 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
384                 if (FD_ISSET(CONN(obj)->fd, exceptions)) {
385                         sdb_log(SDB_LOG_INFO, "Exception on fd %d",
386                                         CONN(obj)->fd);
387                         /* close the connection */
388                         sdb_llist_iter_remove_current(iter);
389                         sdb_object_deref(obj);
390                         continue;
391                 }
393                 if (FD_ISSET(CONN(obj)->fd, ready)) {
394                         sdb_llist_iter_remove_current(iter);
395                         sdb_channel_write(sock->chan, &obj);
396                 }
397         }
398         sdb_llist_iter_destroy(iter);
399         return 0;
400 } /* socket_handle_incoming */
402 /*
403  * public API
404  */
406 sdb_fe_socket_t *
407 sdb_fe_sock_create(void)
409         sdb_fe_socket_t *sock;
411         sock = calloc(1, sizeof(*sock));
412         if (! sock)
413                 return NULL;
415         sock->open_connections = sdb_llist_create();
416         if (! sock->open_connections) {
417                 sdb_fe_sock_destroy(sock);
418                 return NULL;
419         }
420         return sock;
421 } /* sdb_fe_sock_create */
423 void
424 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
426         size_t i;
428         if (! sock)
429                 return;
431         for (i = 0; i < sock->listeners_num; ++i) {
432                 listener_destroy(sock->listeners + i);
433         }
434         if (sock->listeners)
435                 free(sock->listeners);
436         sock->listeners = NULL;
438         sdb_llist_destroy(sock->open_connections);
439         sock->open_connections = NULL;
440         free(sock);
441 } /* sdb_fe_sock_destroy */
443 int
444 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
446         listener_t *listener;
448         if ((! sock) || (! address))
449                 return -1;
451         listener = listener_create(sock, address);
452         if (! listener)
453                 return -1;
454         return 0;
455 } /* sdb_fe_sock_add_listener */
457 int
458 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
460         fd_set sockets;
461         int max_listen_fd = 0;
462         size_t i;
464         pthread_t handler_threads[loop->num_threads];
465         size_t num_threads;
467         if ((! sock) || (! sock->listeners_num) || sock->chan
468                         || (! loop) || (loop->num_threads <= 0))
469                 return -1;
471         if (! loop->do_loop)
472                 return 0;
474         FD_ZERO(&sockets);
475         for (i = 0; i < sock->listeners_num; ++i) {
476                 listener_t *listener = sock->listeners + i;
478                 if (listener_listen(listener)) {
479                         socket_close(sock);
480                         return -1;
481                 }
483                 FD_SET(listener->sock_fd, &sockets);
484                 if (listener->sock_fd > max_listen_fd)
485                         max_listen_fd = listener->sock_fd;
486         }
488         sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
489         if (! sock->chan) {
490                 socket_close(sock);
491                 return -1;
492         }
494         sdb_log(SDB_LOG_INFO, "frontend: Starting %d connection "
495                         "handler thread%s managing %d listener%s",
496                         loop->num_threads, loop->num_threads == 1 ? "" : "s",
497                         sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
499         num_threads = loop->num_threads;
500         memset(&handler_threads, 0, sizeof(handler_threads));
501         for (i = 0; i < num_threads; ++i) {
502                 errno = 0;
503                 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
504                                         connection_handler, /* arg = */ sock)) {
505                         char errbuf[1024];
506                         sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
507                                         "connection handler thread: %s",
508                                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
509                         num_threads = i;
510                         break;
511                 }
512         }
514         while (loop->do_loop && num_threads) {
515                 struct timeval timeout = { 1, 0 }; /* one second */
516                 sdb_llist_iter_t *iter;
518                 int max_fd = max_listen_fd;
519                 fd_set ready;
520                 fd_set exceptions;
521                 int n;
523                 FD_ZERO(&ready);
524                 FD_ZERO(&exceptions);
526                 ready = sockets;
528                 iter = sdb_llist_get_iter(sock->open_connections);
529                 if (! iter) {
530                         sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
531                                         "for open connections");
532                         break;
533                 }
535                 while (sdb_llist_iter_has_next(iter)) {
536                         sdb_object_t *obj = sdb_llist_iter_get_next(iter);
538                         if (CONN(obj)->fd < 0) {
539                                 sdb_llist_iter_remove_current(iter);
540                                 sdb_object_deref(obj);
541                                 continue;
542                         }
544                         FD_SET(CONN(obj)->fd, &ready);
545                         FD_SET(CONN(obj)->fd, &exceptions);
547                         if (CONN(obj)->fd > max_fd)
548                                 max_fd = CONN(obj)->fd;
549                 }
550                 sdb_llist_iter_destroy(iter);
552                 errno = 0;
553                 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
554                 if (n < 0) {
555                         char buf[1024];
557                         if (errno == EINTR)
558                                 continue;
560                         sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
561                                         sdb_strerror(errno, buf, sizeof(buf)));
562                         break;
563                 }
564                 else if (! n)
565                         continue;
567                 /* handle new and open connections */
568                 if (socket_handle_incoming(sock, &ready, &exceptions))
569                         break;
570         }
572         socket_close(sock);
574         sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
575                         "to terminate");
576         if (! sdb_channel_shutdown(sock->chan))
577                 for (i = 0; i < num_threads; ++i)
578                         pthread_join(handler_threads[i], NULL);
579         /* else: we tried our best; let the operating system clean up */
581         sdb_channel_destroy(sock->chan);
582         sock->chan = NULL;
584         if (! num_threads)
585                 return -1;
586         return 0;
587 } /* sdb_fe_sock_listen_and_server */
589 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */