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/connection.h"
32 #include "frontend/sock.h"
34 #include "utils/channel.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 <fcntl.h>
49 #include <sys/time.h>
50 #include <sys/types.h>
51 #include <sys/select.h>
52 #include <sys/socket.h>
53 #include <sys/un.h>
55 #include <pthread.h>
57 /* name of connection objects */
58 #define CONN_FD_PREFIX "conn#"
59 #define CONN_FD_PLACEHOLDER "XXXXXXX"
61 /*
62 * private data types
63 */
65 typedef struct {
66 sdb_object_t super;
68 /* connection and client information */
69 struct sockaddr_storage client_addr;
70 socklen_t client_addr_len;
72 sdb_conn_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 /* try to reopen */
242 if (listener->sock_fd < 0)
243 if (listener_impls[listener->type].opener(listener))
244 return -1;
245 assert(listener->sock_fd >= 0);
247 if (listen(listener->sock_fd, /* backlog = */ 32)) {
248 char buf[1024];
249 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
250 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
251 return -1;
252 }
253 return 0;
254 } /* listener_listen */
256 static void
257 listener_close(listener_t *listener)
258 {
259 assert(listener);
261 if (listener->sock_fd < 0)
262 return;
264 close(listener->sock_fd);
265 listener->sock_fd = -1;
266 } /* listener_close */
268 static void
269 socket_close(sdb_fe_socket_t *sock)
270 {
271 size_t i;
273 assert(sock);
274 for (i = 0; i < sock->listeners_num; ++i)
275 listener_close(sock->listeners + i);
276 } /* socket_close */
278 /*
279 * private data types
280 */
282 static int
283 connection_init(sdb_object_t *obj, va_list ap)
284 {
285 connection_obj_t *conn;
286 int sock_fd;
287 int sock_fl;
289 assert(obj);
290 conn = CONN(obj);
292 sock_fd = va_arg(ap, int);
294 CONN(obj)->conn.buf = sdb_strbuf_create(/* size = */ 128);
295 if (! CONN(obj)->conn.buf) {
296 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate a read buffer "
297 "for a new remote connection");
298 return -1;
299 }
301 conn->client_addr_len = sizeof(conn->client_addr);
302 conn->conn.fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
303 &conn->client_addr_len);
305 if (conn->conn.fd < 0) {
306 char buf[1024];
307 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
308 "connection: %s", sdb_strerror(errno,
309 buf, sizeof(buf)));
310 return -1;
311 }
313 if (conn->client_addr.ss_family != AF_UNIX) {
314 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
315 "unexpected family type %d", conn->client_addr.ss_family);
316 return -1;
317 }
319 sock_fl = fcntl(conn->conn.fd, F_GETFL);
320 if (fcntl(conn->conn.fd, F_SETFL, sock_fl | O_NONBLOCK)) {
321 char buf[1024];
322 sdb_log(SDB_LOG_ERR, "frontend: Failed to switch connection conn#%i "
323 "to non-blocking mode: %s", conn->conn.fd,
324 sdb_strerror(errno, buf, sizeof(buf)));
325 return -1;
326 }
328 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i",
329 conn->conn.fd);
331 /* update the object name */
332 snprintf(obj->name + strlen(CONN_FD_PREFIX),
333 strlen(CONN_FD_PLACEHOLDER), "%i", conn->conn.fd);
334 return 0;
335 } /* connection_init */
337 static void
338 connection_destroy(sdb_object_t *obj)
339 {
340 connection_obj_t *conn;
341 size_t len;
343 assert(obj);
344 conn = CONN(obj);
346 len = sdb_strbuf_len(conn->conn.buf);
347 if (len)
348 sdb_log(SDB_LOG_INFO, "frontend: Discarding incomplete command "
349 "(%zu bytes left in buffer)", len);
351 sdb_log(SDB_LOG_DEBUG, "frontend: Closing connection on fd=%i",
352 conn->conn.fd);
353 close(conn->conn.fd);
354 conn->conn.fd = -1;
356 sdb_strbuf_destroy(CONN(obj)->conn.buf);
357 } /* connection_destroy */
359 static sdb_type_t connection_type = {
360 /* size = */ sizeof(connection_obj_t),
361 /* init = */ connection_init,
362 /* destroy = */ connection_destroy,
363 };
365 /*
366 * connection handler functions
367 */
369 static void *
370 connection_handler(void *data)
371 {
372 sdb_fe_socket_t *sock = data;
374 assert(sock);
376 while (42) {
377 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
378 connection_obj_t *conn;
379 int status;
381 errno = 0;
382 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
383 /* write */ NULL, NULL, &timeout);
384 if (status) {
385 char buf[1024];
387 if (errno == ETIMEDOUT)
388 continue;
389 if (errno == EBADF) /* channel shut down */
390 break;
392 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
393 sdb_strerror(errno, buf, sizeof(buf)));
394 continue;
395 }
397 status = (int)sdb_connection_read(&conn->conn);
398 if (status <= 0) {
399 /* error or EOF -> close connection */
400 sdb_object_deref(SDB_OBJ(conn));
401 continue;
402 }
404 /* return the connection to the main loop */
405 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
406 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
407 "connection %s to list of open connections",
408 SDB_OBJ(conn)->name);
409 }
411 /* pass ownership back to list; or destroy in case of an error */
412 sdb_object_deref(SDB_OBJ(conn));
413 }
414 return NULL;
415 } /* connection_handler */
417 static int
418 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
419 {
420 sdb_object_t *obj;
422 /* the placeholder will be replaced with the accepted file
423 * descriptor when initializing the object */
424 obj = sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
425 connection_type, listener->sock_fd);
426 if (! obj)
427 return -1;
429 if (sdb_llist_append(sock->open_connections, obj)) {
430 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
431 "connection %s to list of open connections",
432 obj->name);
433 sdb_object_deref(obj);
434 return -1;
435 }
437 /* hand ownership over to the list */
438 sdb_object_deref(obj);
439 return 0;
440 } /* connection_accept */
442 static int
443 socket_handle_incoming(sdb_fe_socket_t *sock,
444 fd_set *ready, fd_set *exceptions)
445 {
446 sdb_llist_iter_t *iter;
447 size_t i;
449 for (i = 0; i < sock->listeners_num; ++i) {
450 listener_t *listener = sock->listeners + i;
451 if (FD_ISSET(listener->sock_fd, ready))
452 if (connection_accept(sock, listener))
453 continue;
454 }
456 iter = sdb_llist_get_iter(sock->open_connections);
457 if (! iter) {
458 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
459 "for open connections");
460 return -1;
461 }
463 while (sdb_llist_iter_has_next(iter)) {
464 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
466 if (FD_ISSET(CONN(obj)->conn.fd, exceptions))
467 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
468 CONN(obj)->conn.fd);
470 if (FD_ISSET(CONN(obj)->conn.fd, ready)) {
471 sdb_llist_iter_remove_current(iter);
472 sdb_channel_write(sock->chan, &obj);
473 }
474 }
475 sdb_llist_iter_destroy(iter);
476 return 0;
477 } /* socket_handle_incoming */
479 /*
480 * public API
481 */
483 sdb_fe_socket_t *
484 sdb_fe_sock_create(void)
485 {
486 sdb_fe_socket_t *sock;
488 sock = calloc(1, sizeof(*sock));
489 if (! sock)
490 return NULL;
492 sock->open_connections = sdb_llist_create();
493 if (! sock->open_connections) {
494 sdb_fe_sock_destroy(sock);
495 return NULL;
496 }
497 return sock;
498 } /* sdb_fe_sock_create */
500 void
501 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
502 {
503 size_t i;
505 if (! sock)
506 return;
508 for (i = 0; i < sock->listeners_num; ++i) {
509 listener_destroy(sock->listeners + i);
510 }
511 if (sock->listeners)
512 free(sock->listeners);
513 sock->listeners = NULL;
515 sdb_llist_destroy(sock->open_connections);
516 sock->open_connections = NULL;
517 free(sock);
518 } /* sdb_fe_sock_destroy */
520 int
521 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
522 {
523 listener_t *listener;
525 if ((! sock) || (! address))
526 return -1;
528 listener = listener_create(sock, address);
529 if (! listener)
530 return -1;
531 return 0;
532 } /* sdb_fe_sock_add_listener */
534 int
535 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
536 {
537 fd_set sockets;
538 int max_listen_fd = 0;
539 size_t i;
541 /* XXX: make the number of threads configurable */
542 pthread_t handler_threads[5];
544 if ((! sock) || (! sock->listeners_num) || (! loop) || sock->chan)
545 return -1;
547 FD_ZERO(&sockets);
548 for (i = 0; i < sock->listeners_num; ++i) {
549 listener_t *listener = sock->listeners + i;
551 if (listener_listen(listener)) {
552 socket_close(sock);
553 return -1;
554 }
556 FD_SET(listener->sock_fd, &sockets);
557 if (listener->sock_fd > max_listen_fd)
558 max_listen_fd = listener->sock_fd;
559 }
561 sock->chan = sdb_channel_create(1024, sizeof(connection_obj_t *));
562 if (! sock->chan) {
563 socket_close(sock);
564 return -1;
565 }
567 memset(&handler_threads, 0, sizeof(handler_threads));
568 /* XXX: error handling */
569 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
570 pthread_create(&handler_threads[i], /* attr = */ NULL,
571 connection_handler, /* arg = */ sock);
573 while (loop->do_loop) {
574 struct timeval timeout = { 1, 0 }; /* one second */
575 sdb_llist_iter_t *iter;
577 int max_fd = max_listen_fd;
578 fd_set ready;
579 fd_set exceptions;
580 int n;
582 FD_ZERO(&ready);
583 FD_ZERO(&exceptions);
585 ready = sockets;
587 iter = sdb_llist_get_iter(sock->open_connections);
588 if (! iter) {
589 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
590 "for open connections");
591 break;
592 }
594 while (sdb_llist_iter_has_next(iter)) {
595 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
596 FD_SET(CONN(obj)->conn.fd, &ready);
597 FD_SET(CONN(obj)->conn.fd, &exceptions);
599 if (CONN(obj)->conn.fd > max_fd)
600 max_fd = CONN(obj)->conn.fd;
601 }
602 sdb_llist_iter_destroy(iter);
604 errno = 0;
605 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
606 if (n < 0) {
607 char buf[1024];
609 if (errno == EINTR)
610 continue;
612 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
613 sdb_strerror(errno, buf, sizeof(buf)));
614 break;
615 }
616 else if (! n)
617 continue;
619 /* handle new and open connections */
620 if (socket_handle_incoming(sock, &ready, &exceptions))
621 break;
622 }
624 socket_close(sock);
626 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
627 "to terminate");
628 if (! sdb_channel_shutdown(sock->chan))
629 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
630 pthread_join(handler_threads[i], NULL);
631 /* else: we tried our best; let the operating system clean up */
633 sdb_channel_destroy(sock->chan);
634 sock->chan = NULL;
635 return 0;
636 } /* sdb_fe_sock_listen_and_server */
638 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */