Code

Include config.h in source files.
[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);
388                 if (FD_ISSET(CONN(obj)->fd, ready)) {
389                         sdb_llist_iter_remove_current(iter);
390                         sdb_channel_write(sock->chan, &obj);
391                 }
392         }
393         sdb_llist_iter_destroy(iter);
394         return 0;
395 } /* socket_handle_incoming */
397 /*
398  * public API
399  */
401 sdb_fe_socket_t *
402 sdb_fe_sock_create(void)
404         sdb_fe_socket_t *sock;
406         sock = calloc(1, sizeof(*sock));
407         if (! sock)
408                 return NULL;
410         sock->open_connections = sdb_llist_create();
411         if (! sock->open_connections) {
412                 sdb_fe_sock_destroy(sock);
413                 return NULL;
414         }
415         return sock;
416 } /* sdb_fe_sock_create */
418 void
419 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
421         size_t i;
423         if (! sock)
424                 return;
426         for (i = 0; i < sock->listeners_num; ++i) {
427                 listener_destroy(sock->listeners + i);
428         }
429         if (sock->listeners)
430                 free(sock->listeners);
431         sock->listeners = NULL;
433         sdb_llist_destroy(sock->open_connections);
434         sock->open_connections = NULL;
435         free(sock);
436 } /* sdb_fe_sock_destroy */
438 int
439 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
441         listener_t *listener;
443         if ((! sock) || (! address))
444                 return -1;
446         listener = listener_create(sock, address);
447         if (! listener)
448                 return -1;
449         return 0;
450 } /* sdb_fe_sock_add_listener */
452 int
453 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
455         fd_set sockets;
456         int max_listen_fd = 0;
457         size_t i;
459         pthread_t handler_threads[loop->num_threads];
460         size_t num_threads;
462         if ((! sock) || (! sock->listeners_num) || sock->chan
463                         || (! loop) || (loop->num_threads <= 0))
464                 return -1;
466         if (! loop->do_loop)
467                 return 0;
469         FD_ZERO(&sockets);
470         for (i = 0; i < sock->listeners_num; ++i) {
471                 listener_t *listener = sock->listeners + i;
473                 if (listener_listen(listener)) {
474                         socket_close(sock);
475                         return -1;
476                 }
478                 FD_SET(listener->sock_fd, &sockets);
479                 if (listener->sock_fd > max_listen_fd)
480                         max_listen_fd = listener->sock_fd;
481         }
483         sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
484         if (! sock->chan) {
485                 socket_close(sock);
486                 return -1;
487         }
489         sdb_log(SDB_LOG_INFO, "frontend: Starting %d connection "
490                         "handler thread%s managing %d listener%s",
491                         loop->num_threads, loop->num_threads == 1 ? "" : "s",
492                         sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
494         num_threads = loop->num_threads;
495         memset(&handler_threads, 0, sizeof(handler_threads));
496         for (i = 0; i < num_threads; ++i) {
497                 errno = 0;
498                 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
499                                         connection_handler, /* arg = */ sock)) {
500                         char errbuf[1024];
501                         sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
502                                         "connection handler thread: %s",
503                                         sdb_strerror(errno, errbuf, sizeof(errbuf)));
504                         num_threads = i;
505                         break;
506                 }
507         }
509         while (loop->do_loop && num_threads) {
510                 struct timeval timeout = { 1, 0 }; /* one second */
511                 sdb_llist_iter_t *iter;
513                 int max_fd = max_listen_fd;
514                 fd_set ready;
515                 fd_set exceptions;
516                 int n;
518                 FD_ZERO(&ready);
519                 FD_ZERO(&exceptions);
521                 ready = sockets;
523                 iter = sdb_llist_get_iter(sock->open_connections);
524                 if (! iter) {
525                         sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
526                                         "for open connections");
527                         break;
528                 }
530                 while (sdb_llist_iter_has_next(iter)) {
531                         sdb_object_t *obj = sdb_llist_iter_get_next(iter);
532                         FD_SET(CONN(obj)->fd, &ready);
533                         FD_SET(CONN(obj)->fd, &exceptions);
535                         if (CONN(obj)->fd > max_fd)
536                                 max_fd = CONN(obj)->fd;
537                 }
538                 sdb_llist_iter_destroy(iter);
540                 errno = 0;
541                 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
542                 if (n < 0) {
543                         char buf[1024];
545                         if (errno == EINTR)
546                                 continue;
548                         sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
549                                         sdb_strerror(errno, buf, sizeof(buf)));
550                         break;
551                 }
552                 else if (! n)
553                         continue;
555                 /* handle new and open connections */
556                 if (socket_handle_incoming(sock, &ready, &exceptions))
557                         break;
558         }
560         socket_close(sock);
562         sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
563                         "to terminate");
564         if (! sdb_channel_shutdown(sock->chan))
565                 for (i = 0; i < num_threads; ++i)
566                         pthread_join(handler_threads[i], NULL);
567         /* else: we tried our best; let the operating system clean up */
569         sdb_channel_destroy(sock->chan);
570         sock->chan = NULL;
572         if (! num_threads)
573                 return -1;
574         return 0;
575 } /* sdb_fe_sock_listen_and_server */
577 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */