65884ea945bf61fe935b48fe60ab819b453b1eb8
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 } fe_listener_impl_t;
73 struct sdb_fe_socket {
74 listener_t *listeners;
75 size_t listeners_num;
77 sdb_llist_t *open_connections;
79 /* channel used for communication between main
80 * and connection handler threads */
81 sdb_channel_t *chan;
82 };
84 /*
85 * connection management functions
86 */
88 static int
89 open_unix_sock(listener_t *listener)
90 {
91 struct sockaddr_un sa;
92 int status;
94 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
95 if (listener->sock_fd < 0) {
96 char buf[1024];
97 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
98 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
99 return -1;
100 }
102 memset(&sa, 0, sizeof(sa));
103 sa.sun_family = AF_UNIX;
104 strncpy(sa.sun_path, listener->address + strlen("unix:"),
105 sizeof(sa.sun_path));
107 if (unlink(listener->address + strlen("unix:")) && (errno != ENOENT)) {
108 char errbuf[1024];
109 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
110 "socket %s: %s", listener->address + strlen("unix:"),
111 sdb_strerror(errno, errbuf, sizeof(errbuf)));
112 }
114 status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
115 if (status) {
116 char buf[1024];
117 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
118 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
119 return -1;
120 }
121 return 0;
122 } /* open_unix_sock */
124 /*
125 * private variables
126 */
128 /* the enum has to be sorted the same as the implementations array
129 * to ensure that the type may be used as index into the array */
130 enum {
131 LISTENER_UNIXSOCK = 0,
132 };
133 static fe_listener_impl_t listener_impls[] = {
134 { LISTENER_UNIXSOCK, "unix", open_unix_sock },
135 };
137 /*
138 * private helper functions
139 */
141 static int
142 get_type(const char *address)
143 {
144 char *sep;
145 size_t len;
146 size_t i;
148 sep = strchr(address, (int)':');
149 if (! sep)
150 return -1;
152 assert(sep > address);
153 len = (size_t)(sep - address);
155 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
156 fe_listener_impl_t *impl = listener_impls + i;
158 if (!strncmp(address, impl->prefix, len)) {
159 assert(impl->type == (int)i);
160 return impl->type;
161 }
162 }
163 return -1;
164 } /* get_type */
166 static void
167 listener_destroy(listener_t *listener)
168 {
169 if (! listener)
170 return;
172 if (listener->sock_fd >= 0)
173 close(listener->sock_fd);
174 listener->sock_fd = -1;
176 if (listener->address)
177 free(listener->address);
178 } /* listener_destroy */
180 static listener_t *
181 listener_create(sdb_fe_socket_t *sock, const char *address)
182 {
183 listener_t *listener;
184 int type;
186 type = get_type(address);
187 if (type < 0) {
188 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
189 "in listen address '%s'", address);
190 return NULL;
191 }
193 listener = realloc(sock->listeners,
194 sock->listeners_num * sizeof(*sock->listeners));
195 if (! listener) {
196 char buf[1024];
197 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
198 sdb_strerror(errno, buf, sizeof(buf)));
199 return NULL;
200 }
202 sock->listeners = listener;
203 listener = sock->listeners + sock->listeners_num;
205 listener->sock_fd = -1;
206 listener->address = strdup(address);
207 if (! listener->address) {
208 char buf[1024];
209 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
210 sdb_strerror(errno, buf, sizeof(buf)));
211 listener_destroy(listener);
212 return NULL;
213 }
214 listener->type = type;
216 if (listener_impls[type].opener(listener)) {
217 /* prints error */
218 listener_destroy(listener);
219 return NULL;
220 }
222 ++sock->listeners_num;
223 return listener;
224 } /* listener_create */
226 static int
227 listener_listen(listener_t *listener)
228 {
229 assert(listener);
231 /* try to reopen */
232 if (listener->sock_fd < 0)
233 if (listener_impls[listener->type].opener(listener))
234 return -1;
235 assert(listener->sock_fd >= 0);
237 if (listen(listener->sock_fd, /* backlog = */ 32)) {
238 char buf[1024];
239 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
240 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
241 return -1;
242 }
243 return 0;
244 } /* listener_listen */
246 static void
247 listener_close(listener_t *listener)
248 {
249 assert(listener);
251 if (listener->sock_fd < 0)
252 return;
254 close(listener->sock_fd);
255 listener->sock_fd = -1;
256 } /* listener_close */
258 static void
259 socket_close(sdb_fe_socket_t *sock)
260 {
261 size_t i;
263 assert(sock);
264 for (i = 0; i < sock->listeners_num; ++i)
265 listener_close(sock->listeners + i);
266 } /* socket_close */
268 /*
269 * connection handler functions
270 */
272 static void *
273 connection_handler(void *data)
274 {
275 sdb_fe_socket_t *sock = data;
277 assert(sock);
279 while (42) {
280 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
281 sdb_conn_t *conn;
282 int status;
284 errno = 0;
285 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
286 /* write */ NULL, NULL, &timeout);
287 if (status) {
288 char buf[1024];
290 if (errno == ETIMEDOUT)
291 continue;
292 if (errno == EBADF) /* channel shut down */
293 break;
295 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
296 sdb_strerror(errno, buf, sizeof(buf)));
297 continue;
298 }
300 status = (int)sdb_connection_read(conn);
301 if (status <= 0) {
302 /* error or EOF -> close connection */
303 sdb_object_deref(SDB_OBJ(conn));
304 continue;
305 }
307 /* return the connection to the main loop */
308 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
309 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
310 "connection %s to list of open connections",
311 SDB_OBJ(conn)->name);
312 }
314 /* pass ownership back to list; or destroy in case of an error */
315 sdb_object_deref(SDB_OBJ(conn));
316 }
317 return NULL;
318 } /* connection_handler */
320 static int
321 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
322 {
323 sdb_object_t *obj;
324 int status;
326 obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
327 if (! obj)
328 return -1;
330 status = sdb_llist_append(sock->open_connections, obj);
331 if (status)
332 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
333 "connection %s to list of open connections",
334 obj->name);
336 /* hand ownership over to the list; or destroy in case of an error */
337 sdb_object_deref(obj);
338 return status;
339 } /* connection_accept */
341 static int
342 socket_handle_incoming(sdb_fe_socket_t *sock,
343 fd_set *ready, fd_set *exceptions)
344 {
345 sdb_llist_iter_t *iter;
346 size_t i;
348 for (i = 0; i < sock->listeners_num; ++i) {
349 listener_t *listener = sock->listeners + i;
350 if (FD_ISSET(listener->sock_fd, ready))
351 if (connection_accept(sock, listener))
352 continue;
353 }
355 iter = sdb_llist_get_iter(sock->open_connections);
356 if (! iter) {
357 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
358 "for open connections");
359 return -1;
360 }
362 while (sdb_llist_iter_has_next(iter)) {
363 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
365 if (FD_ISSET(CONN(obj)->fd, exceptions))
366 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
367 CONN(obj)->fd);
369 if (FD_ISSET(CONN(obj)->fd, ready)) {
370 sdb_llist_iter_remove_current(iter);
371 sdb_channel_write(sock->chan, &obj);
372 }
373 }
374 sdb_llist_iter_destroy(iter);
375 return 0;
376 } /* socket_handle_incoming */
378 /*
379 * public API
380 */
382 sdb_fe_socket_t *
383 sdb_fe_sock_create(void)
384 {
385 sdb_fe_socket_t *sock;
387 sock = calloc(1, sizeof(*sock));
388 if (! sock)
389 return NULL;
391 sock->open_connections = sdb_llist_create();
392 if (! sock->open_connections) {
393 sdb_fe_sock_destroy(sock);
394 return NULL;
395 }
396 return sock;
397 } /* sdb_fe_sock_create */
399 void
400 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
401 {
402 size_t i;
404 if (! sock)
405 return;
407 for (i = 0; i < sock->listeners_num; ++i) {
408 listener_destroy(sock->listeners + i);
409 }
410 if (sock->listeners)
411 free(sock->listeners);
412 sock->listeners = NULL;
414 sdb_llist_destroy(sock->open_connections);
415 sock->open_connections = NULL;
416 free(sock);
417 } /* sdb_fe_sock_destroy */
419 int
420 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
421 {
422 listener_t *listener;
424 if ((! sock) || (! address))
425 return -1;
427 listener = listener_create(sock, address);
428 if (! listener)
429 return -1;
430 return 0;
431 } /* sdb_fe_sock_add_listener */
433 int
434 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
435 {
436 fd_set sockets;
437 int max_listen_fd = 0;
438 size_t i;
440 /* XXX: make the number of threads configurable */
441 pthread_t handler_threads[5];
443 if ((! sock) || (! sock->listeners_num) || (! loop) || sock->chan)
444 return -1;
446 FD_ZERO(&sockets);
447 for (i = 0; i < sock->listeners_num; ++i) {
448 listener_t *listener = sock->listeners + i;
450 if (listener_listen(listener)) {
451 socket_close(sock);
452 return -1;
453 }
455 FD_SET(listener->sock_fd, &sockets);
456 if (listener->sock_fd > max_listen_fd)
457 max_listen_fd = listener->sock_fd;
458 }
460 sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
461 if (! sock->chan) {
462 socket_close(sock);
463 return -1;
464 }
466 memset(&handler_threads, 0, sizeof(handler_threads));
467 /* XXX: error handling */
468 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
469 pthread_create(&handler_threads[i], /* attr = */ NULL,
470 connection_handler, /* arg = */ sock);
472 while (loop->do_loop) {
473 struct timeval timeout = { 1, 0 }; /* one second */
474 sdb_llist_iter_t *iter;
476 int max_fd = max_listen_fd;
477 fd_set ready;
478 fd_set exceptions;
479 int n;
481 FD_ZERO(&ready);
482 FD_ZERO(&exceptions);
484 ready = sockets;
486 iter = sdb_llist_get_iter(sock->open_connections);
487 if (! iter) {
488 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
489 "for open connections");
490 break;
491 }
493 while (sdb_llist_iter_has_next(iter)) {
494 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
495 FD_SET(CONN(obj)->fd, &ready);
496 FD_SET(CONN(obj)->fd, &exceptions);
498 if (CONN(obj)->fd > max_fd)
499 max_fd = CONN(obj)->fd;
500 }
501 sdb_llist_iter_destroy(iter);
503 errno = 0;
504 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
505 if (n < 0) {
506 char buf[1024];
508 if (errno == EINTR)
509 continue;
511 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
512 sdb_strerror(errno, buf, sizeof(buf)));
513 break;
514 }
515 else if (! n)
516 continue;
518 /* handle new and open connections */
519 if (socket_handle_incoming(sock, &ready, &exceptions))
520 break;
521 }
523 socket_close(sock);
525 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
526 "to terminate");
527 if (! sdb_channel_shutdown(sock->chan))
528 for (i = 0; i < SDB_STATIC_ARRAY_LEN(handler_threads); ++i)
529 pthread_join(handler_threads[i], NULL);
530 /* else: we tried our best; let the operating system clean up */
532 sdb_channel_destroy(sock->chan);
533 sock->chan = NULL;
534 return 0;
535 } /* sdb_fe_sock_listen_and_server */
537 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */