12690d8cb83e23557306d8224c67ad1cf6c11e1d
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 <sys/time.h>
47 #include <sys/types.h>
48 #include <sys/select.h>
49 #include <sys/socket.h>
50 #include <sys/un.h>
52 #include <pthread.h>
54 /* name of connection objects */
55 #define CONN_FD_PREFIX "conn#"
56 #define CONN_FD_PLACEHOLDER "XXXXXXX"
58 /*
59 * private data types
60 */
62 typedef struct {
63 int fd;
64 struct sockaddr_storage client_addr;
65 socklen_t client_addr_len;
66 } connection_t;
68 typedef struct {
69 sdb_object_t super;
70 connection_t conn;
71 } connection_obj_t;
72 #define CONN(obj) ((connection_obj_t *)(obj))
74 typedef struct {
75 char *address;
76 int type;
78 int sock_fd;
79 } listener_t;
81 typedef struct {
82 int type;
83 const char *prefix;
85 int (*opener)(listener_t *);
86 } fe_listener_impl_t;
88 struct sdb_fe_socket {
89 listener_t *listeners;
90 size_t listeners_num;
92 sdb_llist_t *open_connections;
93 };
95 /*
96 * connection management functions
97 */
99 static int
100 open_unix_sock(listener_t *listener)
101 {
102 struct sockaddr_un sa;
103 int status;
105 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
106 if (listener->sock_fd < 0) {
107 char buf[1024];
108 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
109 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
110 return -1;
111 }
113 memset(&sa, 0, sizeof(sa));
114 sa.sun_family = AF_UNIX;
115 strncpy(sa.sun_path, listener->address + strlen("unix:"),
116 sizeof(sa.sun_path));
118 status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
119 if (status) {
120 char buf[1024];
121 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
122 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
123 return -1;
124 }
125 return 0;
126 } /* open_unix_sock */
128 /*
129 * private variables
130 */
132 /* the enum has to be sorted the same as the implementations array
133 * to ensure that the type may be used as index into the array */
134 enum {
135 LISTENER_UNIXSOCK = 0,
136 };
137 static fe_listener_impl_t listener_impls[] = {
138 { LISTENER_UNIXSOCK, "unix", open_unix_sock },
139 };
141 /*
142 * private helper functions
143 */
145 static int
146 get_type(const char *address)
147 {
148 char *sep;
149 size_t len;
150 size_t i;
152 sep = strchr(address, (int)':');
153 if (! sep)
154 return -1;
156 assert(sep > address);
157 len = (size_t)(sep - address);
159 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
160 fe_listener_impl_t *impl = listener_impls + i;
162 if (!strncmp(address, impl->prefix, len)) {
163 assert(impl->type == (int)i);
164 return impl->type;
165 }
166 }
167 return -1;
168 } /* get_type */
170 static void
171 listener_destroy(listener_t *listener)
172 {
173 if (! listener)
174 return;
176 if (listener->sock_fd >= 0)
177 close(listener->sock_fd);
179 if (listener->address)
180 free(listener->address);
181 } /* listener_destroy */
183 static listener_t *
184 listener_create(sdb_fe_socket_t *sock, const char *address)
185 {
186 listener_t *listener;
187 int type;
189 type = get_type(address);
190 if (type < 0) {
191 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
192 "in listen address '%s'", address);
193 return NULL;
194 }
196 listener = realloc(sock->listeners,
197 sock->listeners_num * sizeof(*sock->listeners));
198 if (! listener) {
199 char buf[1024];
200 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
201 sdb_strerror(errno, buf, sizeof(buf)));
202 return NULL;
203 }
205 sock->listeners = listener;
206 listener = sock->listeners + sock->listeners_num;
208 listener->sock_fd = -1;
209 listener->address = strdup(address);
210 if (! listener->address) {
211 char buf[1024];
212 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
213 sdb_strerror(errno, buf, sizeof(buf)));
214 listener_destroy(listener);
215 return NULL;
216 }
217 listener->type = type;
219 if (listener_impls[type].opener(listener)) {
220 /* prints error */
221 listener_destroy(listener);
222 return NULL;
223 }
225 ++sock->listeners_num;
226 return listener;
227 } /* listener_create */
229 /*
230 * private data types
231 */
233 static int
234 connection_init(sdb_object_t *obj, va_list ap)
235 {
236 connection_t *conn;
237 int sock_fd;
239 assert(obj);
240 conn = &CONN(obj)->conn;
242 sock_fd = va_arg(ap, int);
244 conn->client_addr_len = sizeof(conn->client_addr);
245 conn->fd = accept(sock_fd, (struct sockaddr *)&conn->client_addr,
246 &conn->client_addr_len);
248 if (conn->fd < 0) {
249 char buf[1024];
250 sdb_log(SDB_LOG_ERR, "frontend: Failed to accept remote "
251 "connection: %s", sdb_strerror(errno,
252 buf, sizeof(buf)));
253 return -1;
254 }
256 if (conn->client_addr.ss_family != AF_UNIX) {
257 sdb_log(SDB_LOG_ERR, "frontend: Accepted connection using "
258 "unexpected family type %d", conn->client_addr.ss_family);
259 return -1;
260 }
262 sdb_log(SDB_LOG_DEBUG, "frontend: Accepted connection on fd=%i\n",
263 conn->fd);
265 /* update the object name */
266 snprintf(obj->name + strlen(CONN_FD_PREFIX),
267 strlen(CONN_FD_PLACEHOLDER), "%i", conn->fd);
268 return 0;
269 } /* connection_init */
271 static void
272 connection_destroy(sdb_object_t *obj)
273 {
274 connection_t *conn;
276 assert(obj);
277 conn = &CONN(obj)->conn;
279 close(conn->fd);
280 conn->fd = -1;
281 } /* connection_destroy */
283 static sdb_type_t connection_type = {
284 /* size = */ sizeof(connection_obj_t),
285 /* init = */ connection_init,
286 /* destroy = */ connection_destroy,
287 };
289 /*
290 * connection handler functions
291 */
293 static void *
294 connection_handler(void *data)
295 {
296 sdb_channel_t *chan = data;
298 assert(chan);
300 while (42) {
301 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
302 connection_obj_t *conn;
303 int status;
305 errno = 0;
306 status = sdb_channel_select(chan, NULL, &conn, NULL, NULL, &timeout);
307 if (status) {
308 char buf[1024];
310 if (errno == ETIMEDOUT)
311 continue;
312 if (errno == EBADF) /* channel shut down */
313 break;
315 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
316 sdb_strerror(errno, buf, sizeof(buf)));
317 continue;
318 }
320 /* XXX */
321 sdb_log(SDB_LOG_INFO, "frontend: Data available on connection fd=%i\n",
322 conn->conn.fd);
323 }
324 return NULL;
325 } /* connection_handler */
327 /*
328 * public API
329 */
331 sdb_fe_socket_t *
332 sdb_fe_sock_create(void)
333 {
334 sdb_fe_socket_t *sock;
336 sock = calloc(1, sizeof(*sock));
337 if (! sock)
338 return NULL;
340 sock->open_connections = sdb_llist_create();
341 if (! sock->open_connections) {
342 sdb_fe_sock_destroy(sock);
343 return NULL;
344 }
345 return sock;
346 } /* sdb_fe_sock_create */
348 void
349 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
350 {
351 size_t i;
353 if (! sock)
354 return;
356 for (i = 0; i < sock->listeners_num; ++i) {
357 listener_destroy(sock->listeners + i);
358 }
359 if (sock->listeners)
360 free(sock->listeners);
361 sock->listeners = NULL;
363 sdb_llist_destroy(sock->open_connections);
364 sock->open_connections = NULL;
365 free(sock);
366 } /* sdb_fe_sock_destroy */
368 int
369 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
370 {
371 listener_t *listener;
373 if ((! sock) || (! address))
374 return -1;
376 listener = listener_create(sock, address);
377 if (! listener)
378 return -1;
379 return 0;
380 } /* sdb_fe_sock_add_listener */
382 int
383 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
384 {
385 sdb_channel_t *chan;
386 fd_set sockets;
387 int max_listen_fd = 0;
388 size_t i;
390 /* XXX: make the number of threads configurable */
391 pthread_t handler_threads[5];
393 if ((! sock) || (! sock->listeners_num) || (! loop))
394 return -1;
396 FD_ZERO(&sockets);
398 for (i = 0; i < sock->listeners_num; ++i) {
399 listener_t *listener = sock->listeners + i;
401 if (listen(listener->sock_fd, /* backlog = */ 32)) {
402 char buf[1024];
403 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
404 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
405 return -1;
406 }
408 FD_SET(listener->sock_fd, &sockets);
409 if (listener->sock_fd > max_listen_fd)
410 max_listen_fd = listener->sock_fd;
411 }
413 chan = sdb_channel_create(1024, sizeof(connection_obj_t *));
414 if (! chan)
415 return -1;
417 memset(&handler_threads, 0, sizeof(handler_threads));
418 /* XXX: error handling */
419 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
420 pthread_create(&handler_threads[i], /* attr = */ NULL,
421 connection_handler, /* arg = */ chan);
423 while (loop->do_loop) {
424 fd_set ready;
425 fd_set exceptions;
426 int max_fd;
427 int n;
429 struct timeval timeout = { 1, 0 }; /* one second */
430 sdb_llist_iter_t *iter;
432 FD_ZERO(&ready);
433 FD_ZERO(&exceptions);
435 ready = sockets;
437 max_fd = max_listen_fd;
439 iter = sdb_llist_get_iter(sock->open_connections);
440 if (! iter) {
441 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
442 "for open connections");
443 return -1;
444 }
446 while (sdb_llist_iter_has_next(iter)) {
447 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
448 FD_SET(CONN(obj)->conn.fd, &ready);
449 FD_SET(CONN(obj)->conn.fd, &exceptions);
451 if (CONN(obj)->conn.fd > max_fd)
452 max_fd = CONN(obj)->conn.fd;
453 }
454 sdb_llist_iter_destroy(iter);
456 errno = 0;
457 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
458 if (n < 0) {
459 char buf[1024];
461 if (errno == EINTR)
462 continue;
464 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
465 sdb_strerror(errno, buf, sizeof(buf)));
466 return -1;
467 }
469 if (! n)
470 continue;
472 for (i = 0; i < sock->listeners_num; ++i) {
473 listener_t *listener = sock->listeners + i;
475 if (FD_ISSET(listener->sock_fd, &ready)) {
476 sdb_object_t *obj;
478 /* the X's will be replaced with the accepted file descriptor
479 * when initializing the object */
480 obj = sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
481 connection_type, listener->sock_fd);
482 if (! obj)
483 continue;
485 if (sdb_llist_append(sock->open_connections, obj)) {
486 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
487 "connection %s to list of open connections",
488 obj->name);
489 sdb_object_deref(obj);
490 continue;
491 }
493 /* hand ownership over to the list */
494 sdb_object_deref(obj);
495 }
496 }
498 iter = sdb_llist_get_iter(sock->open_connections);
499 if (! iter) {
500 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
501 "for open connections");
502 return -1;
503 }
505 while (sdb_llist_iter_has_next(iter)) {
506 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
508 if (FD_ISSET(CONN(obj)->conn.fd, &exceptions))
509 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
510 CONN(obj)->conn.fd);
512 if (FD_ISSET(CONN(obj)->conn.fd, &ready)) {
513 sdb_log(SDB_LOG_INFO, "Data on fd %d", CONN(obj)->conn.fd);
514 sdb_llist_iter_remove_current(iter);
515 sdb_channel_write(chan, &obj);
516 }
517 }
518 sdb_llist_iter_destroy(iter);
519 }
521 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
522 "to terminate");
523 if (! sdb_channel_shutdown(chan))
524 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
525 pthread_join(handler_threads[i], NULL);
526 /* else: we tried our best; let the operating system clean up */
527 return 0;
528 } /* sdb_fe_sock_listen_and_server */
530 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */