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)
107 {
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)
153 {
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)
178 {
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)
192 {
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)
238 {
239 assert(listener);
241 if (listen(listener->sock_fd, /* backlog = */ 32)) {
242 char buf[1024];
243 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
244 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
245 return -1;
246 }
247 return 0;
248 } /* listener_listen */
250 static void
251 listener_close(listener_t *listener)
252 {
253 assert(listener);
255 if (listener->sock_fd < 0)
256 return;
258 close(listener->sock_fd);
259 listener->sock_fd = -1;
260 } /* listener_close */
262 /*
263 * private data types
264 */
266 static int
267 connection_init(sdb_object_t *obj, va_list ap)
268 {
269 connection_t *conn;
270 int sock_fd;
271 int sock_fl;
273 assert(obj);
274 conn = &CONN(obj)->conn;
276 sock_fd = va_arg(ap, int);
278 conn->client_addr_len = sizeof(conn->client_addr);
279 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
280 &conn->client_addr_len);
282 if (conn->fd < 0) {
283 char buf[1024];
284 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
285 "connection: %s", sdb_strerror(errno,
286 buf, sizeof(buf)));
287 return -1;
288 }
290 if (conn->client_addr.ss_family != AF_UNIX) {
291 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
292 "unexpected family type %d", conn->client_addr.ss_family);
293 return -1;
294 }
296 sock_fl = fcntl(conn->fd, F_GETFL);
297 if (fcntl(conn->fd, F_SETFL, sock_fl | O_NONBLOCK)) {
298 char buf[1024];
299 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
300 "to non-blocking mode: %s", conn->fd,
301 sdb_strerror(errno, buf, sizeof(buf)));
302 return -1;
303 }
305 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
306 conn->fd);
308 /* update the object name */
309 snprintf(obj->name + strlen(CONN_FD_PREFIX),
310 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
311 return 0;
312 } /* connection_init */
314 static void
315 connection_destroy(sdb_object_t *obj)
316 {
317 connection_t *conn;
319 assert(obj);
320 conn = &CONN(obj)->conn;
322 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection on fd=%i", conn->fd);
323 close(conn->fd);
324 conn->fd = -1;
325 } /* connection_destroy */
327 static sdb_type_t connection_type = {
328 /* size = */ sizeof(connection_obj_t),
329 /* init = */ connection_init,
330 /* destroy = */ connection_destroy,
331 };
333 /*
334 * connection handler functions
335 */
337 /* returns negative value on error, 0 on EOF, number of packets else */
338 static int
339 connection_read(int fd)
340 {
341 int n = 0;
343 while (42) {
344 int32_t cmd;
345 ssize_t status;
347 errno = 0;
348 status = read(fd, &cmd, sizeof(cmd));
349 if (status < 0) {
350 if ((errno == EAGAIN) || (errno == EWOULDBLOCK))
351 return n + 1;
352 return (int)status;
353 }
354 else if (! status) /* EOF */
355 return 0;
357 /* XXX */
358 sdb_log(SDB_LOG_DEBUG, "frontend: read command %i from fd=%i",
359 cmd, fd);
360 ++n;
361 }
363 return n + 1;
364 } /* connection_read */
366 static void *
367 connection_handler(void *data)
368 {
369 sdb_fe_socket_t *sock = data;
371 assert(sock);
373 while (42) {
374 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
375 connection_obj_t *conn;
376 int status;
378 errno = 0;
379 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
380 /* write */ NULL, NULL, &timeout);
381 if (status) {
382 char buf[1024];
384 if (errno == ETIMEDOUT)
385 continue;
386 if (errno == EBADF) /* channel shut down */
387 break;
389 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
390 sdb_strerror(errno, buf, sizeof(buf)));
391 continue;
392 }
394 status = connection_read(conn->conn.fd);
395 if (status <= 0) {
396 /* error or EOF -> close connection */
397 sdb_object_deref(SDB_OBJ(conn));
398 }
399 else {
400 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
401 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
402 "connection %s to list of open connections",
403 SDB_OBJ(conn)->name);
404 }
406 /* pass ownership back to list; or destroy in case of an error */
407 sdb_object_deref(SDB_OBJ(conn));
408 }
409 }
410 return NULL;
411 } /* connection_handler */
413 static int
414 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
415 {
416 sdb_object_t *obj;
418 /* the placeholder will be replaced with the accepted file
419 * descriptor when initializing the object */
420 obj = sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
421 connection_type, listener->sock_fd);
422 if (! obj)
423 return -1;
425 if (sdb_llist_append(sock->open_connections, obj)) {
426 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
427 "connection %s to list of open connections",
428 obj->name);
429 sdb_object_deref(obj);
430 return -1;
431 }
433 /* hand ownership over to the list */
434 sdb_object_deref(obj);
435 return 0;
436 } /* connection_accept */
438 /*
439 * public API
440 */
442 sdb_fe_socket_t *
443 sdb_fe_sock_create(void)
444 {
445 sdb_fe_socket_t *sock;
447 sock = calloc(1, sizeof(*sock));
448 if (! sock)
449 return NULL;
451 sock->open_connections = sdb_llist_create();
452 if (! sock->open_connections) {
453 sdb_fe_sock_destroy(sock);
454 return NULL;
455 }
456 return sock;
457 } /* sdb_fe_sock_create */
459 void
460 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
461 {
462 size_t i;
464 if (! sock)
465 return;
467 for (i = 0; i < sock->listeners_num; ++i) {
468 listener_destroy(sock->listeners + i);
469 }
470 if (sock->listeners)
471 free(sock->listeners);
472 sock->listeners = NULL;
474 sdb_llist_destroy(sock->open_connections);
475 sock->open_connections = NULL;
476 free(sock);
477 } /* sdb_fe_sock_destroy */
479 int
480 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
481 {
482 listener_t *listener;
484 if ((! sock) || (! address))
485 return -1;
487 listener = listener_create(sock, address);
488 if (! listener)
489 return -1;
490 return 0;
491 } /* sdb_fe_sock_add_listener */
493 int
494 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
495 {
496 fd_set sockets;
497 int max_listen_fd = 0;
498 size_t i;
500 /* XXX: make the number of threads configurable */
501 pthread_t handler_threads[5];
503 if ((! sock) || (! sock->listeners_num) || (! loop))
504 return -1;
506 if (sock->chan)
507 return -1;
509 FD_ZERO(&sockets);
511 for (i = 0; i < sock->listeners_num; ++i) {
512 listener_t *listener = sock->listeners + i;
514 if (listener_listen(listener))
515 return -1;
517 FD_SET(listener->sock_fd, &sockets);
518 if (listener->sock_fd > max_listen_fd)
519 max_listen_fd = listener->sock_fd;
520 }
522 sock->chan = sdb_channel_create(1024, sizeof(connection_obj_t *));
523 if (! sock->chan)
524 return -1;
526 memset(&handler_threads, 0, sizeof(handler_threads));
527 /* XXX: error handling */
528 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
529 pthread_create(&handler_threads[i], /* attr = */ NULL,
530 connection_handler, /* arg = */ sock);
532 while (loop->do_loop) {
533 fd_set ready;
534 fd_set exceptions;
535 int max_fd;
536 int n;
538 struct timeval timeout = { 1, 0 }; /* one second */
539 sdb_llist_iter_t *iter;
541 FD_ZERO(&ready);
542 FD_ZERO(&exceptions);
544 ready = sockets;
546 max_fd = max_listen_fd;
548 iter = sdb_llist_get_iter(sock->open_connections);
549 if (! iter) {
550 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
551 "for open connections");
552 break;
553 }
555 while (sdb_llist_iter_has_next(iter)) {
556 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
557 FD_SET(CONN(obj)->conn.fd, &ready);
558 FD_SET(CONN(obj)->conn.fd, &exceptions);
560 if (CONN(obj)->conn.fd > max_fd)
561 max_fd = CONN(obj)->conn.fd;
562 }
563 sdb_llist_iter_destroy(iter);
565 errno = 0;
566 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
567 if (n < 0) {
568 char buf[1024];
570 if (errno == EINTR)
571 continue;
573 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
574 sdb_strerror(errno, buf, sizeof(buf)));
575 break;
576 }
578 if (! n)
579 continue;
581 for (i = 0; i < sock->listeners_num; ++i) {
582 listener_t *listener = sock->listeners + i;
583 if (FD_ISSET(listener->sock_fd, &ready))
584 if (connection_accept(sock, listener))
585 continue;
586 }
588 iter = sdb_llist_get_iter(sock->open_connections);
589 if (! iter) {
590 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
591 "for open connections");
592 break;
593 }
595 while (sdb_llist_iter_has_next(iter)) {
596 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
598 if (FD_ISSET(CONN(obj)->conn.fd, &exceptions))
599 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
600 CONN(obj)->conn.fd);
602 if (FD_ISSET(CONN(obj)->conn.fd, &ready)) {
603 sdb_llist_iter_remove_current(iter);
604 sdb_channel_write(sock->chan, &obj);
605 }
606 }
607 sdb_llist_iter_destroy(iter);
608 }
610 for (i = 0; i < sock->listeners_num; ++i)
611 listener_close(sock->listeners + i);
613 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
614 "to terminate");
615 if (! sdb_channel_shutdown(sock->chan))
616 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
617 pthread_join(handler_threads[i], NULL);
618 /* else: we tried our best; let the operating system clean up */
620 sdb_channel_destroy(sock->chan);
621 sock->chan = NULL;
622 return 0;
623 } /* sdb_fe_sock_listen_and_server */
625 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */