Code

socket frontend: Let handler read from open connection.
[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);
185         if (listener->address)
186                 free(listener->address);
187 } /* listener_destroy */
189 static listener_t *
190 listener_create(sdb_fe_socket_t *sock, const char *address)
192         listener_t *listener;
193         int type;
195         type = get_type(address);
196         if (type < 0) {
197                 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
198                                 "in listen address '%s'", address);
199                 return NULL;
200         }
202         listener = realloc(sock->listeners,
203                         sock->listeners_num * sizeof(*sock->listeners));
204         if (! listener) {
205                 char buf[1024];
206                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
207                                 sdb_strerror(errno, buf, sizeof(buf)));
208                 return NULL;
209         }
211         sock->listeners = listener;
212         listener = sock->listeners + sock->listeners_num;
214         listener->sock_fd = -1;
215         listener->address = strdup(address);
216         if (! listener->address) {
217                 char buf[1024];
218                 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
219                                 sdb_strerror(errno, buf, sizeof(buf)));
220                 listener_destroy(listener);
221                 return NULL;
222         }
223         listener->type = type;
225         if (listener_impls[type].opener(listener)) {
226                 /* prints error */
227                 listener_destroy(listener);
228                 return NULL;
229         }
231         ++sock->listeners_num;
232         return listener;
233 } /* listener_create */
235 /*
236  * private data types
237  */
239 static int
240 connection_init(sdb_object_t *obj, va_list ap)
242         connection_t *conn;
243         int sock_fd;
244         int sock_fl;
246         assert(obj);
247         conn = &CONN(obj)->conn;
249         sock_fd = va_arg(ap, int);
251         conn->client_addr_len = sizeof(conn->client_addr);
252         conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
253                         &conn->client_addr_len);
255         if (conn->fd < 0) {
256                 char buf[1024];
257                 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
258                                 "connection: %s", sdb_strerror(errno,
259                                         buf, sizeof(buf)));
260                 return -1;
261         }
263         if (conn->client_addr.ss_family != AF_UNIX) {
264                 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
265                                 "unexpected family type %d", conn->client_addr.ss_family);
266                 return -1;
267         }
269         sock_fl = fcntl(conn->fd, F_GETFL);
270         if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
271                 char buf[1024];
272                 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
273                                 "to non-blocking mode: %s", conn->fd,
274                                 sdb_strerror(errno, buf, sizeof(buf)));
275                 return -1;
276         }
278         sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
279                         conn->fd);
281         /* update the object name */
282         snprintf(obj->name + strlen(CONN_FD_PREFIX),
283                         strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
284         return 0;
285 } /* connection_init */
287 static void
288 connection_destroy(sdb_object_t *obj)
290         connection_t *conn;
292         assert(obj);
293         conn = &CONN(obj)->conn;
295         sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection on fd=%i", conn->fd);
296         close(conn->fd);
297         conn->fd = -1;
298 } /* connection_destroy */
300 static sdb_type_t connection_type = {
301         /* size = */ sizeof(connection_obj_t),
302         /* init = */ connection_init,
303         /* destroy = */ connection_destroy,
304 };
306 /*
307  * connection handler functions
308  */
310 /* returns negative value on error, 0 on EOF, number of packets else */
311 static int
312 connection_read(int fd)
314         int n = 0;
316         while (42) {
317                 int32_t cmd;
318                 ssize_t status;
320                 errno = 0;
321                 status = read(fd, &cmd, sizeof(cmd));
322                 if (status < 0) {
323                         if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
324                                 return n + 1;
325                         return (int)status;
326                 }
327                 else if (! status) /* EOF */
328                         return 0;
330                 /* XXX */
331                 sdb_log(SDB_LOG_DEBUG, "frontend: read command %i from fd=%i",
332                                 cmd, fd);
333                 ++n;
334         }
336         return n + 1;
337 } /* connection_read */
339 static void *
340 connection_handler(void *data)
342         sdb_fe_socket_t *sock = data;
344         assert(sock);
346         while (42) {
347                 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
348                 connection_obj_t *conn;
349                 int status;
351                 errno = 0;
352                 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
353                                 /* write */ NULL, NULL, &timeout);
354                 if (status) {
355                         char buf[1024];
357                         if (errno == ETIMEDOUT)
358                                 continue;
359                         if (errno == EBADF) /* channel shut down */
360                                 break;
362                         sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
363                                         sdb_strerror(errno, buf, sizeof(buf)));
364                         continue;
365                 }
367                 status = connection_read(conn->conn.fd);
368                 if (status <= 0) {
369                         /* error or EOF → close connection */
370                         sdb_object_deref(SDB_OBJ(conn));
371                 }
372                 else {
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         }
383         return NULL;
384 } /* connection_handler */
386 static int
387 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
389         sdb_object_t *obj;
391         /* the placeholder will be replaced with the accepted file
392          * descriptor when initializing the object */
393         obj = sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
394                         connection_type, listener->sock_fd);
395         if (! obj)
396                 return -1;
398         if (sdb_llist_append(sock->open_connections, obj)) {
399                 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
400                                 "connection %s to list of open connections",
401                                 obj->name);
402                 sdb_object_deref(obj);
403                 return -1;
404         }
406         /* hand ownership over to the list */
407         sdb_object_deref(obj);
408         return 0;
409 } /* connection_accept */
411 /*
412  * public API
413  */
415 sdb_fe_socket_t *
416 sdb_fe_sock_create(void)
418         sdb_fe_socket_t *sock;
420         sock = calloc(1, sizeof(*sock));
421         if (! sock)
422                 return NULL;
424         sock->open_connections = sdb_llist_create();
425         if (! sock->open_connections) {
426                 sdb_fe_sock_destroy(sock);
427                 return NULL;
428         }
429         return sock;
430 } /* sdb_fe_sock_create */
432 void
433 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
435         size_t i;
437         if (! sock)
438                 return;
440         for (i = 0; i < sock->listeners_num; ++i) {
441                 listener_destroy(sock->listeners + i);
442         }
443         if (sock->listeners)
444                 free(sock->listeners);
445         sock->listeners = NULL;
447         sdb_llist_destroy(sock->open_connections);
448         sock->open_connections = NULL;
449         free(sock);
450 } /* sdb_fe_sock_destroy */
452 int
453 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
455         listener_t *listener;
457         if ((! sock) || (! address))
458                 return -1;
460         listener = listener_create(sock, address);
461         if (! listener)
462                 return -1;
463         return 0;
464 } /* sdb_fe_sock_add_listener */
466 int
467 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
469         fd_set sockets;
470         int max_listen_fd = 0;
471         size_t i;
473         /* XXX: make the number of threads configurable */
474         pthread_t handler_threads[5];
476         if ((! sock) || (! sock->listeners_num) || (! loop))
477                 return -1;
479         FD_ZERO(&sockets);
481         for (i = 0; i < sock->listeners_num; ++i) {
482                 listener_t *listener = sock->listeners + i;
484                 if (listen(listener->sock_fd, /* backlog = */ 32)) {
485                         char buf[1024];
486                         sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
487                                         listener->address, sdb_strerror(errno, buf, sizeof(buf)));
488                         return -1;
489                 }
491                 FD_SET(listener->sock_fd, &sockets);
492                 if (listener->sock_fd > max_listen_fd)
493                         max_listen_fd = listener->sock_fd;
494         }
496         sock->chan = sdb_channel_create(1024, sizeof(connection_obj_t *));
497         if (! sock->chan)
498                 return -1;
500         memset(&handler_threads, 0, sizeof(handler_threads));
501         /* XXX: error handling */
502         for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
503                 pthread_create(&handler_threads[i], /* attr = */ NULL,
504                                 connection_handler, /* arg = */ sock);
506         while (loop->do_loop) {
507                 fd_set ready;
508                 fd_set exceptions;
509                 int max_fd;
510                 int n;
512                 struct timeval timeout = { 1, 0 }; /* one second */
513                 sdb_llist_iter_t *iter;
515                 FD_ZERO(&ready);
516                 FD_ZERO(&exceptions);
518                 ready = sockets;
520                 max_fd = max_listen_fd;
522                 iter = sdb_llist_get_iter(sock->open_connections);
523                 if (! iter) {
524                         sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
525                                         "for open connections");
526                         return -1;
527                 }
529                 while (sdb_llist_iter_has_next(iter)) {
530                         sdb_object_t *obj = sdb_llist_iter_get_next(iter);
531                         FD_SET(CONN(obj)->conn.fd, &ready);
532                         FD_SET(CONN(obj)->conn.fd, &exceptions);
534                         if (CONN(obj)->conn.fd > max_fd)
535                                 max_fd = CONN(obj)->conn.fd;
536                 }
537                 sdb_llist_iter_destroy(iter);
539                 errno = 0;
540                 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
541                 if (n < 0) {
542                         char buf[1024];
544                         if (errno == EINTR)
545                                 continue;
547                         sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
548                                         sdb_strerror(errno, buf, sizeof(buf)));
549                         return -1;
550                 }
552                 if (! n)
553                         continue;
555                 for (i = 0; i < sock->listeners_num; ++i) {
556                         listener_t *listener = sock->listeners + i;
557                         if (FD_ISSET(listener->sock_fd, &ready))
558                                 if (connection_accept(sock, listener))
559                                         continue;
560                 }
562                 iter = sdb_llist_get_iter(sock->open_connections);
563                 if (! iter) {
564                         sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
565                                         "for open connections");
566                         return -1;
567                 }
569                 while (sdb_llist_iter_has_next(iter)) {
570                         sdb_object_t *obj = sdb_llist_iter_get_next(iter);
572                         if (FD_ISSET(CONN(obj)->conn.fd, &exceptions))
573                                 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
574                                                 CONN(obj)->conn.fd);
576                         if (FD_ISSET(CONN(obj)->conn.fd, &ready)) {
577                                 sdb_llist_iter_remove_current(iter);
578                                 sdb_channel_write(sock->chan, &obj);
579                         }
580                 }
581                 sdb_llist_iter_destroy(iter);
582         }
584         sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
585                         "to terminate");
586         if (! sdb_channel_shutdown(sock->chan))
587                 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
588                         pthread_join(handler_threads[i], NULL);
589         /* else: we tried our best; let the operating system clean up */
590         return 0;
591 } /* sdb_fe_sock_listen_and_server */
593 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */