3662a2650cc41d313ea5c6e8613c59810825fd50
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 static int
328 accept_connection(sdb_fe_socket_t *sock, listener_t *listener)
329 {
330 sdb_object_t *obj;
332 /* the X's will be replaced with the accepted file descriptor
333 * when initializing the object */
334 obj = sdb_object_create(CONN_FD_PREFIX CONN_FD_PLACEHOLDER,
335 connection_type, listener->sock_fd);
336 if (! obj)
337 return -1;
339 if (sdb_llist_append(sock->open_connections, obj)) {
340 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
341 "connection %s to list of open connections",
342 obj->name);
343 sdb_object_deref(obj);
344 return -1;
345 }
347 /* hand ownership over to the list */
348 sdb_object_deref(obj);
349 return 0;
350 } /* accept_connection */
352 /*
353 * public API
354 */
356 sdb_fe_socket_t *
357 sdb_fe_sock_create(void)
358 {
359 sdb_fe_socket_t *sock;
361 sock = calloc(1, sizeof(*sock));
362 if (! sock)
363 return NULL;
365 sock->open_connections = sdb_llist_create();
366 if (! sock->open_connections) {
367 sdb_fe_sock_destroy(sock);
368 return NULL;
369 }
370 return sock;
371 } /* sdb_fe_sock_create */
373 void
374 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
375 {
376 size_t i;
378 if (! sock)
379 return;
381 for (i = 0; i < sock->listeners_num; ++i) {
382 listener_destroy(sock->listeners + i);
383 }
384 if (sock->listeners)
385 free(sock->listeners);
386 sock->listeners = NULL;
388 sdb_llist_destroy(sock->open_connections);
389 sock->open_connections = NULL;
390 free(sock);
391 } /* sdb_fe_sock_destroy */
393 int
394 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
395 {
396 listener_t *listener;
398 if ((! sock) || (! address))
399 return -1;
401 listener = listener_create(sock, address);
402 if (! listener)
403 return -1;
404 return 0;
405 } /* sdb_fe_sock_add_listener */
407 int
408 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
409 {
410 sdb_channel_t *chan;
411 fd_set sockets;
412 int max_listen_fd = 0;
413 size_t i;
415 /* XXX: make the number of threads configurable */
416 pthread_t handler_threads[5];
418 if ((! sock) || (! sock->listeners_num) || (! loop))
419 return -1;
421 FD_ZERO(&sockets);
423 for (i = 0; i < sock->listeners_num; ++i) {
424 listener_t *listener = sock->listeners + i;
426 if (listen(listener->sock_fd, /* backlog = */ 32)) {
427 char buf[1024];
428 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
429 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
430 return -1;
431 }
433 FD_SET(listener->sock_fd, &sockets);
434 if (listener->sock_fd > max_listen_fd)
435 max_listen_fd = listener->sock_fd;
436 }
438 chan = sdb_channel_create(1024, sizeof(connection_obj_t *));
439 if (! chan)
440 return -1;
442 memset(&handler_threads, 0, sizeof(handler_threads));
443 /* XXX: error handling */
444 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
445 pthread_create(&handler_threads[i], /* attr = */ NULL,
446 connection_handler, /* arg = */ chan);
448 while (loop->do_loop) {
449 fd_set ready;
450 fd_set exceptions;
451 int max_fd;
452 int n;
454 struct timeval timeout = { 1, 0 }; /* one second */
455 sdb_llist_iter_t *iter;
457 FD_ZERO(&ready);
458 FD_ZERO(&exceptions);
460 ready = sockets;
462 max_fd = max_listen_fd;
464 iter = sdb_llist_get_iter(sock->open_connections);
465 if (! iter) {
466 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
467 "for open connections");
468 return -1;
469 }
471 while (sdb_llist_iter_has_next(iter)) {
472 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
473 FD_SET(CONN(obj)->conn.fd, &ready);
474 FD_SET(CONN(obj)->conn.fd, &exceptions);
476 if (CONN(obj)->conn.fd > max_fd)
477 max_fd = CONN(obj)->conn.fd;
478 }
479 sdb_llist_iter_destroy(iter);
481 errno = 0;
482 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
483 if (n < 0) {
484 char buf[1024];
486 if (errno == EINTR)
487 continue;
489 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
490 sdb_strerror(errno, buf, sizeof(buf)));
491 return -1;
492 }
494 if (! n)
495 continue;
497 for (i = 0; i < sock->listeners_num; ++i) {
498 listener_t *listener = sock->listeners + i;
499 if (FD_ISSET(listener->sock_fd, &ready))
500 if (accept_connection(sock, listener))
501 continue;
502 }
504 iter = sdb_llist_get_iter(sock->open_connections);
505 if (! iter) {
506 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
507 "for open connections");
508 return -1;
509 }
511 while (sdb_llist_iter_has_next(iter)) {
512 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
514 if (FD_ISSET(CONN(obj)->conn.fd, &exceptions))
515 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
516 CONN(obj)->conn.fd);
518 if (FD_ISSET(CONN(obj)->conn.fd, &ready)) {
519 sdb_log(SDB_LOG_INFO, "Data on fd %d", CONN(obj)->conn.fd);
520 sdb_llist_iter_remove_current(iter);
521 sdb_channel_write(chan, &obj);
522 }
523 }
524 sdb_llist_iter_destroy(iter);
525 }
527 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
528 "to terminate");
529 if (! sdb_channel_shutdown(chan))
530 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
531 pthread_join(handler_threads[i], NULL);
532 /* else: we tried our best; let the operating system clean up */
533 return 0;
534 } /* sdb_fe_sock_listen_and_server */
536 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */