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 const char *addr;
97 struct sockaddr_un sa;
98 int status;
100 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
101 if (listener->sock_fd < 0) {
102 char buf[1024];
103 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
104 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
105 return -1;
106 }
108 if (*listener->address == '/')
109 addr = listener->address;
110 else
111 addr = listener->address + strlen("unix:");
113 memset(&sa, 0, sizeof(sa));
114 sa.sun_family = AF_UNIX;
115 strncpy(sa.sun_path, addr, sizeof(sa.sun_path));
117 if (unlink(addr) && (errno != ENOENT)) {
118 char errbuf[1024];
119 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
120 "socket %s: %s", listener->address + strlen("unix:"),
121 sdb_strerror(errno, errbuf, sizeof(errbuf)));
122 }
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 static void
135 close_unix_sock(listener_t *listener)
136 {
137 const char *addr;
138 assert(listener);
140 if (! listener->address)
141 return;
143 if (*listener->address == '/')
144 addr = listener->address;
145 else
146 addr = listener->address + strlen("unix:");
148 if (listener->sock_fd >= 0)
149 close(listener->sock_fd);
150 listener->sock_fd = -1;
152 unlink(addr);
153 } /* close_unix_sock */
155 /*
156 * private variables
157 */
159 /* the enum has to be sorted the same as the implementations array
160 * to ensure that the type may be used as index into the array */
161 enum {
162 LISTENER_UNIXSOCK = 0, /* this is the default */
163 };
164 static fe_listener_impl_t listener_impls[] = {
165 { LISTENER_UNIXSOCK, "unix", open_unix_sock, close_unix_sock },
166 };
168 /*
169 * private helper functions
170 */
172 static int
173 listener_listen(listener_t *listener)
174 {
175 assert(listener);
177 /* try to reopen */
178 if (listener->sock_fd < 0)
179 if (listener_impls[listener->type].opener(listener))
180 return -1;
181 assert(listener->sock_fd >= 0);
183 if (listen(listener->sock_fd, /* backlog = */ 32)) {
184 char buf[1024];
185 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
186 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
187 return -1;
188 }
189 return 0;
190 } /* listener_listen */
192 static void
193 listener_close(listener_t *listener)
194 {
195 assert(listener);
197 if (listener_impls[listener->type].closer)
198 listener_impls[listener->type].closer(listener);
200 if (listener->sock_fd >= 0)
201 close(listener->sock_fd);
202 listener->sock_fd = -1;
203 } /* listener_close */
205 static int
206 get_type(const char *address)
207 {
208 char *sep;
209 size_t len;
210 size_t i;
212 sep = strchr(address, (int)':');
213 if (! sep)
214 return listener_impls[0].type;
216 assert(sep > address);
217 len = (size_t)(sep - address);
219 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
220 fe_listener_impl_t *impl = listener_impls + i;
222 if (!strncmp(address, impl->prefix, len)) {
223 assert(impl->type == (int)i);
224 return impl->type;
225 }
226 }
227 return -1;
228 } /* get_type */
230 static void
231 listener_destroy(listener_t *listener)
232 {
233 if (! listener)
234 return;
236 listener_close(listener);
238 if (listener->address)
239 free(listener->address);
240 listener->address = NULL;
241 } /* listener_destroy */
243 static listener_t *
244 listener_create(sdb_fe_socket_t *sock, const char *address)
245 {
246 listener_t *listener;
247 int type;
249 type = get_type(address);
250 if (type < 0) {
251 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
252 "in listen address '%s'", address);
253 return NULL;
254 }
256 listener = realloc(sock->listeners,
257 (sock->listeners_num + 1) * sizeof(*sock->listeners));
258 if (! listener) {
259 char buf[1024];
260 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
261 sdb_strerror(errno, buf, sizeof(buf)));
262 return NULL;
263 }
265 sock->listeners = listener;
266 listener = sock->listeners + sock->listeners_num;
268 listener->sock_fd = -1;
269 listener->address = strdup(address);
270 if (! listener->address) {
271 char buf[1024];
272 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
273 sdb_strerror(errno, buf, sizeof(buf)));
274 listener_destroy(listener);
275 return NULL;
276 }
277 listener->type = type;
279 if (listener_impls[type].opener(listener)) {
280 /* prints error */
281 listener_destroy(listener);
282 return NULL;
283 }
285 ++sock->listeners_num;
286 return listener;
287 } /* listener_create */
289 static void
290 socket_clear(sdb_fe_socket_t *sock)
291 {
292 size_t i;
294 assert(sock);
295 for (i = 0; i < sock->listeners_num; ++i)
296 listener_destroy(sock->listeners + i);
297 if (sock->listeners)
298 free(sock->listeners);
299 sock->listeners = NULL;
300 sock->listeners_num = 0;
301 } /* socket_clear */
303 static void
304 socket_close(sdb_fe_socket_t *sock)
305 {
306 size_t i;
308 assert(sock);
309 for (i = 0; i < sock->listeners_num; ++i)
310 listener_close(sock->listeners + i);
311 } /* socket_close */
313 /*
314 * connection handler functions
315 */
317 static void *
318 connection_handler(void *data)
319 {
320 sdb_fe_socket_t *sock = data;
322 assert(sock);
324 while (42) {
325 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
326 sdb_conn_t *conn;
327 int status;
329 errno = 0;
330 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
331 /* write */ NULL, NULL, &timeout);
332 if (status) {
333 char buf[1024];
335 if (errno == ETIMEDOUT)
336 continue;
337 if (errno == EBADF) /* channel shut down */
338 break;
340 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
341 sdb_strerror(errno, buf, sizeof(buf)));
342 continue;
343 }
345 status = (int)sdb_connection_read(conn);
346 if (status <= 0) {
347 /* error or EOF -> close connection */
348 sdb_object_deref(SDB_OBJ(conn));
349 continue;
350 }
352 /* return the connection to the main loop */
353 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
354 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
355 "connection %s to list of open connections",
356 SDB_OBJ(conn)->name);
357 }
359 /* pass ownership back to list; or destroy in case of an error */
360 sdb_object_deref(SDB_OBJ(conn));
361 }
362 return NULL;
363 } /* connection_handler */
365 static int
366 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
367 {
368 sdb_object_t *obj;
369 int status;
371 obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
372 if (! obj)
373 return -1;
375 status = sdb_llist_append(sock->open_connections, obj);
376 if (status)
377 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
378 "connection %s to list of open connections",
379 obj->name);
381 /* hand ownership over to the list; or destroy in case of an error */
382 sdb_object_deref(obj);
383 return status;
384 } /* connection_accept */
386 static int
387 socket_handle_incoming(sdb_fe_socket_t *sock,
388 fd_set *ready, fd_set *exceptions)
389 {
390 sdb_llist_iter_t *iter;
391 size_t i;
393 for (i = 0; i < sock->listeners_num; ++i) {
394 listener_t *listener = sock->listeners + i;
395 if (FD_ISSET(listener->sock_fd, ready))
396 if (connection_accept(sock, listener))
397 continue;
398 }
400 iter = sdb_llist_get_iter(sock->open_connections);
401 if (! iter) {
402 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
403 "for open connections");
404 return -1;
405 }
407 while (sdb_llist_iter_has_next(iter)) {
408 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
410 if (FD_ISSET(CONN(obj)->fd, exceptions)) {
411 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
412 CONN(obj)->fd);
413 /* close the connection */
414 sdb_llist_iter_remove_current(iter);
415 sdb_object_deref(obj);
416 continue;
417 }
419 if (FD_ISSET(CONN(obj)->fd, ready)) {
420 sdb_llist_iter_remove_current(iter);
421 sdb_channel_write(sock->chan, &obj);
422 }
423 }
424 sdb_llist_iter_destroy(iter);
425 return 0;
426 } /* socket_handle_incoming */
428 /*
429 * public API
430 */
432 sdb_fe_socket_t *
433 sdb_fe_sock_create(void)
434 {
435 sdb_fe_socket_t *sock;
437 sock = calloc(1, sizeof(*sock));
438 if (! sock)
439 return NULL;
441 sock->open_connections = sdb_llist_create();
442 if (! sock->open_connections) {
443 sdb_fe_sock_destroy(sock);
444 return NULL;
445 }
446 return sock;
447 } /* sdb_fe_sock_create */
449 void
450 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
451 {
452 if (! sock)
453 return;
455 socket_clear(sock);
457 sdb_llist_destroy(sock->open_connections);
458 sock->open_connections = NULL;
459 free(sock);
460 } /* sdb_fe_sock_destroy */
462 int
463 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
464 {
465 listener_t *listener;
467 if ((! sock) || (! address))
468 return -1;
470 listener = listener_create(sock, address);
471 if (! listener)
472 return -1;
473 return 0;
474 } /* sdb_fe_sock_add_listener */
476 void
477 sdb_fe_sock_clear_listeners(sdb_fe_socket_t *sock)
478 {
479 if (! sock)
480 return;
482 socket_clear(sock);
483 } /* sdb_fe_sock_clear_listeners */
485 int
486 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
487 {
488 fd_set sockets;
489 int max_listen_fd = 0;
490 size_t i;
492 pthread_t handler_threads[loop->num_threads];
493 size_t num_threads;
495 if ((! sock) || (! sock->listeners_num) || sock->chan
496 || (! loop) || (loop->num_threads <= 0))
497 return -1;
499 if (! loop->do_loop)
500 return 0;
502 FD_ZERO(&sockets);
503 for (i = 0; i < sock->listeners_num; ++i) {
504 listener_t *listener = sock->listeners + i;
506 if (listener_listen(listener)) {
507 socket_close(sock);
508 return -1;
509 }
511 FD_SET(listener->sock_fd, &sockets);
512 if (listener->sock_fd > max_listen_fd)
513 max_listen_fd = listener->sock_fd;
514 }
516 sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
517 if (! sock->chan) {
518 socket_close(sock);
519 return -1;
520 }
522 sdb_log(SDB_LOG_INFO, "frontend: Starting %d connection "
523 "handler thread%s managing %d listener%s",
524 loop->num_threads, loop->num_threads == 1 ? "" : "s",
525 sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
527 num_threads = loop->num_threads;
528 memset(&handler_threads, 0, sizeof(handler_threads));
529 for (i = 0; i < num_threads; ++i) {
530 errno = 0;
531 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
532 connection_handler, /* arg = */ sock)) {
533 char errbuf[1024];
534 sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
535 "connection handler thread: %s",
536 sdb_strerror(errno, errbuf, sizeof(errbuf)));
537 num_threads = i;
538 break;
539 }
540 }
542 while (loop->do_loop && num_threads) {
543 struct timeval timeout = { 1, 0 }; /* one second */
544 sdb_llist_iter_t *iter;
546 int max_fd = max_listen_fd;
547 fd_set ready;
548 fd_set exceptions;
549 int n;
551 FD_ZERO(&ready);
552 FD_ZERO(&exceptions);
554 ready = sockets;
556 iter = sdb_llist_get_iter(sock->open_connections);
557 if (! iter) {
558 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
559 "for open connections");
560 break;
561 }
563 while (sdb_llist_iter_has_next(iter)) {
564 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
566 if (CONN(obj)->fd < 0) {
567 sdb_llist_iter_remove_current(iter);
568 sdb_object_deref(obj);
569 continue;
570 }
572 FD_SET(CONN(obj)->fd, &ready);
573 FD_SET(CONN(obj)->fd, &exceptions);
575 if (CONN(obj)->fd > max_fd)
576 max_fd = CONN(obj)->fd;
577 }
578 sdb_llist_iter_destroy(iter);
580 errno = 0;
581 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
582 if (n < 0) {
583 char buf[1024];
585 if (errno == EINTR)
586 continue;
588 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
589 sdb_strerror(errno, buf, sizeof(buf)));
590 break;
591 }
592 else if (! n)
593 continue;
595 /* handle new and open connections */
596 if (socket_handle_incoming(sock, &ready, &exceptions))
597 break;
598 }
600 socket_close(sock);
602 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
603 "to terminate");
604 if (! sdb_channel_shutdown(sock->chan))
605 for (i = 0; i < num_threads; ++i)
606 pthread_join(handler_threads[i], NULL);
607 /* else: we tried our best; let the operating system clean up */
609 sdb_channel_destroy(sock->chan);
610 sock->chan = NULL;
612 if (! num_threads)
613 return -1;
614 return 0;
615 } /* sdb_fe_sock_listen_and_server */
617 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */