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/object.h"
30 #include "frontend/connection-private.h"
31 #include "frontend/sock.h"
33 #include "utils/channel.h"
34 #include "utils/error.h"
35 #include "utils/llist.h"
36 #include "utils/strbuf.h"
38 #include <assert.h>
39 #include <errno.h>
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
45 #include <unistd.h>
47 #include <sys/time.h>
48 #include <sys/types.h>
49 #include <sys/select.h>
50 #include <sys/socket.h>
51 #include <sys/un.h>
53 #include <pthread.h>
55 /*
56 * private data types
57 */
59 typedef struct {
60 char *address;
61 int type;
63 int sock_fd;
64 } listener_t;
66 typedef struct {
67 int type;
68 const char *prefix;
70 int (*opener)(listener_t *);
71 void (*closer)(listener_t *);
72 } fe_listener_impl_t;
74 struct sdb_fe_socket {
75 listener_t *listeners;
76 size_t listeners_num;
78 sdb_llist_t *open_connections;
80 /* channel used for communication between main
81 * and connection handler threads */
82 sdb_channel_t *chan;
83 };
85 /*
86 * connection management functions
87 */
89 static int
90 open_unix_sock(listener_t *listener)
91 {
92 struct sockaddr_un sa;
93 int status;
95 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
96 if (listener->sock_fd < 0) {
97 char buf[1024];
98 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
99 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
100 return -1;
101 }
103 memset(&sa, 0, sizeof(sa));
104 sa.sun_family = AF_UNIX;
105 strncpy(sa.sun_path, listener->address + strlen("unix:"),
106 sizeof(sa.sun_path));
108 if (unlink(listener->address + strlen("unix:")) && (errno != ENOENT)) {
109 char errbuf[1024];
110 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
111 "socket %s: %s", listener->address + strlen("unix:"),
112 sdb_strerror(errno, errbuf, sizeof(errbuf)));
113 }
115 status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
116 if (status) {
117 char buf[1024];
118 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
119 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
120 return -1;
121 }
122 return 0;
123 } /* open_unix_sock */
125 static void
126 close_unix_sock(listener_t *listener)
127 {
128 assert(listener);
129 if (! listener->address)
130 return;
132 if (listener->sock_fd >= 0)
133 close(listener->sock_fd);
134 listener->sock_fd = -1;
136 unlink(listener->address + strlen("unix:"));
137 } /* close_unix_sock */
139 /*
140 * private variables
141 */
143 /* the enum has to be sorted the same as the implementations array
144 * to ensure that the type may be used as index into the array */
145 enum {
146 LISTENER_UNIXSOCK = 0,
147 };
148 static fe_listener_impl_t listener_impls[] = {
149 { LISTENER_UNIXSOCK, "unix", open_unix_sock, close_unix_sock },
150 };
152 /*
153 * private helper functions
154 */
156 static int
157 listener_listen(listener_t *listener)
158 {
159 assert(listener);
161 /* try to reopen */
162 if (listener->sock_fd < 0)
163 if (listener_impls[listener->type].opener(listener))
164 return -1;
165 assert(listener->sock_fd >= 0);
167 if (listen(listener->sock_fd, /* backlog = */ 32)) {
168 char buf[1024];
169 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
170 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
171 return -1;
172 }
173 return 0;
174 } /* listener_listen */
176 static void
177 listener_close(listener_t *listener)
178 {
179 assert(listener);
181 if (listener_impls[listener->type].closer)
182 listener_impls[listener->type].closer(listener);
184 if (listener->sock_fd >= 0)
185 close(listener->sock_fd);
186 listener->sock_fd = -1;
187 } /* listener_close */
189 static int
190 get_type(const char *address)
191 {
192 char *sep;
193 size_t len;
194 size_t i;
196 sep = strchr(address, (int)':');
197 if (! sep)
198 return -1;
200 assert(sep > address);
201 len = (size_t)(sep - address);
203 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
204 fe_listener_impl_t *impl = listener_impls + i;
206 if (!strncmp(address, impl->prefix, len)) {
207 assert(impl->type == (int)i);
208 return impl->type;
209 }
210 }
211 return -1;
212 } /* get_type */
214 static void
215 listener_destroy(listener_t *listener)
216 {
217 if (! listener)
218 return;
220 listener_close(listener);
222 if (listener->address)
223 free(listener->address);
224 listener->address = NULL;
225 } /* listener_destroy */
227 static listener_t *
228 listener_create(sdb_fe_socket_t *sock, const char *address)
229 {
230 listener_t *listener;
231 int type;
233 type = get_type(address);
234 if (type < 0) {
235 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
236 "in listen address '%s'", address);
237 return NULL;
238 }
240 listener = realloc(sock->listeners,
241 sock->listeners_num * sizeof(*sock->listeners));
242 if (! listener) {
243 char buf[1024];
244 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
245 sdb_strerror(errno, buf, sizeof(buf)));
246 return NULL;
247 }
249 sock->listeners = listener;
250 listener = sock->listeners + sock->listeners_num;
252 listener->sock_fd = -1;
253 listener->address = strdup(address);
254 if (! listener->address) {
255 char buf[1024];
256 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
257 sdb_strerror(errno, buf, sizeof(buf)));
258 listener_destroy(listener);
259 return NULL;
260 }
261 listener->type = type;
263 if (listener_impls[type].opener(listener)) {
264 /* prints error */
265 listener_destroy(listener);
266 return NULL;
267 }
269 ++sock->listeners_num;
270 return listener;
271 } /* listener_create */
273 static void
274 socket_close(sdb_fe_socket_t *sock)
275 {
276 size_t i;
278 assert(sock);
279 for (i = 0; i < sock->listeners_num; ++i)
280 listener_close(sock->listeners + i);
281 } /* socket_close */
283 /*
284 * connection handler functions
285 */
287 static void *
288 connection_handler(void *data)
289 {
290 sdb_fe_socket_t *sock = data;
292 assert(sock);
294 while (42) {
295 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
296 sdb_conn_t *conn;
297 int status;
299 errno = 0;
300 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
301 /* write */ NULL, NULL, &timeout);
302 if (status) {
303 char buf[1024];
305 if (errno == ETIMEDOUT)
306 continue;
307 if (errno == EBADF) /* channel shut down */
308 break;
310 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
311 sdb_strerror(errno, buf, sizeof(buf)));
312 continue;
313 }
315 status = (int)sdb_connection_read(conn);
316 if (status <= 0) {
317 /* error or EOF -> close connection */
318 sdb_object_deref(SDB_OBJ(conn));
319 continue;
320 }
322 /* return the connection to the main loop */
323 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
324 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
325 "connection %s to list of open connections",
326 SDB_OBJ(conn)->name);
327 }
329 /* pass ownership back to list; or destroy in case of an error */
330 sdb_object_deref(SDB_OBJ(conn));
331 }
332 return NULL;
333 } /* connection_handler */
335 static int
336 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
337 {
338 sdb_object_t *obj;
339 int status;
341 obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
342 if (! obj)
343 return -1;
345 status = sdb_llist_append(sock->open_connections, obj);
346 if (status)
347 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
348 "connection %s to list of open connections",
349 obj->name);
351 /* hand ownership over to the list; or destroy in case of an error */
352 sdb_object_deref(obj);
353 return status;
354 } /* connection_accept */
356 static int
357 socket_handle_incoming(sdb_fe_socket_t *sock,
358 fd_set *ready, fd_set *exceptions)
359 {
360 sdb_llist_iter_t *iter;
361 size_t i;
363 for (i = 0; i < sock->listeners_num; ++i) {
364 listener_t *listener = sock->listeners + i;
365 if (FD_ISSET(listener->sock_fd, ready))
366 if (connection_accept(sock, listener))
367 continue;
368 }
370 iter = sdb_llist_get_iter(sock->open_connections);
371 if (! iter) {
372 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
373 "for open connections");
374 return -1;
375 }
377 while (sdb_llist_iter_has_next(iter)) {
378 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
380 if (FD_ISSET(CONN(obj)->fd, exceptions))
381 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
382 CONN(obj)->fd);
384 if (FD_ISSET(CONN(obj)->fd, ready)) {
385 sdb_llist_iter_remove_current(iter);
386 sdb_channel_write(sock->chan, &obj);
387 }
388 }
389 sdb_llist_iter_destroy(iter);
390 return 0;
391 } /* socket_handle_incoming */
393 /*
394 * public API
395 */
397 sdb_fe_socket_t *
398 sdb_fe_sock_create(void)
399 {
400 sdb_fe_socket_t *sock;
402 sock = calloc(1, sizeof(*sock));
403 if (! sock)
404 return NULL;
406 sock->open_connections = sdb_llist_create();
407 if (! sock->open_connections) {
408 sdb_fe_sock_destroy(sock);
409 return NULL;
410 }
411 return sock;
412 } /* sdb_fe_sock_create */
414 void
415 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
416 {
417 size_t i;
419 if (! sock)
420 return;
422 for (i = 0; i < sock->listeners_num; ++i) {
423 listener_destroy(sock->listeners + i);
424 }
425 if (sock->listeners)
426 free(sock->listeners);
427 sock->listeners = NULL;
429 sdb_llist_destroy(sock->open_connections);
430 sock->open_connections = NULL;
431 free(sock);
432 } /* sdb_fe_sock_destroy */
434 int
435 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
436 {
437 listener_t *listener;
439 if ((! sock) || (! address))
440 return -1;
442 listener = listener_create(sock, address);
443 if (! listener)
444 return -1;
445 return 0;
446 } /* sdb_fe_sock_add_listener */
448 int
449 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
450 {
451 fd_set sockets;
452 int max_listen_fd = 0;
453 size_t i;
455 pthread_t handler_threads[loop->num_threads];
456 size_t num_threads;
458 if ((! sock) || (! sock->listeners_num) || sock->chan
459 || (! loop) || (loop->num_threads <= 0))
460 return -1;
462 if (! loop->do_loop)
463 return 0;
465 FD_ZERO(&sockets);
466 for (i = 0; i < sock->listeners_num; ++i) {
467 listener_t *listener = sock->listeners + i;
469 if (listener_listen(listener)) {
470 socket_close(sock);
471 return -1;
472 }
474 FD_SET(listener->sock_fd, &sockets);
475 if (listener->sock_fd > max_listen_fd)
476 max_listen_fd = listener->sock_fd;
477 }
479 sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
480 if (! sock->chan) {
481 socket_close(sock);
482 return -1;
483 }
485 sdb_log(SDB_LOG_INFO, "frontend: Starting %d connection "
486 "handler thread%s managing %d listener%s",
487 loop->num_threads, loop->num_threads == 1 ? "" : "s",
488 sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
490 num_threads = loop->num_threads;
491 memset(&handler_threads, 0, sizeof(handler_threads));
492 for (i = 0; i < num_threads; ++i) {
493 errno = 0;
494 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
495 connection_handler, /* arg = */ sock)) {
496 char errbuf[1024];
497 sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
498 "connection handler thread: %s",
499 sdb_strerror(errno, errbuf, sizeof(errbuf)));
500 num_threads = i;
501 break;
502 }
503 }
505 while (loop->do_loop && num_threads) {
506 struct timeval timeout = { 1, 0 }; /* one second */
507 sdb_llist_iter_t *iter;
509 int max_fd = max_listen_fd;
510 fd_set ready;
511 fd_set exceptions;
512 int n;
514 FD_ZERO(&ready);
515 FD_ZERO(&exceptions);
517 ready = sockets;
519 iter = sdb_llist_get_iter(sock->open_connections);
520 if (! iter) {
521 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
522 "for open connections");
523 break;
524 }
526 while (sdb_llist_iter_has_next(iter)) {
527 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
528 FD_SET(CONN(obj)->fd, &ready);
529 FD_SET(CONN(obj)->fd, &exceptions);
531 if (CONN(obj)->fd > max_fd)
532 max_fd = CONN(obj)->fd;
533 }
534 sdb_llist_iter_destroy(iter);
536 errno = 0;
537 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
538 if (n < 0) {
539 char buf[1024];
541 if (errno == EINTR)
542 continue;
544 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
545 sdb_strerror(errno, buf, sizeof(buf)));
546 break;
547 }
548 else if (! n)
549 continue;
551 /* handle new and open connections */
552 if (socket_handle_incoming(sock, &ready, &exceptions))
553 break;
554 }
556 socket_close(sock);
558 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
559 "to terminate");
560 if (! sdb_channel_shutdown(sock->chan))
561 for (i = 0; i < num_threads; ++i)
562 pthread_join(handler_threads[i], NULL);
563 /* else: we tried our best; let the operating system clean up */
565 sdb_channel_destroy(sock->chan);
566 sock->chan = NULL;
568 if (! num_threads)
569 return -1;
570 return 0;
571 } /* sdb_fe_sock_listen_and_server */
573 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */