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 #if HAVE_CONFIG_H
29 # include "config.h"
30 #endif /* HAVE_CONFIG_H */
32 #include "sysdb.h"
33 #include "core/object.h"
34 #include "frontend/connection-private.h"
35 #include "frontend/sock.h"
37 #include "utils/channel.h"
38 #include "utils/error.h"
39 #include "utils/llist.h"
40 #include "utils/os.h"
41 #include "utils/strbuf.h"
43 #include <assert.h>
44 #include <errno.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
50 #include <unistd.h>
52 #include <sys/time.h>
53 #include <sys/types.h>
54 #include <sys/select.h>
55 #include <sys/socket.h>
56 #include <sys/param.h>
57 #include <sys/un.h>
59 #ifdef HAVE_UCRED_H
60 # include <ucred.h>
61 #endif
62 #ifdef HAVE_SYS_UCRED_H
63 # include <sys/ucred.h>
64 #endif
66 #include <pwd.h>
68 #include <libgen.h>
69 #include <pthread.h>
71 /*
72 * private data types
73 */
75 typedef struct {
76 char *address;
77 int type;
79 int sock_fd;
80 int (*accept)(sdb_conn_t *);
81 int (*peer)(sdb_conn_t *);
82 } listener_t;
84 typedef struct {
85 int type;
86 const char *prefix;
88 int (*open)(listener_t *);
89 void (*close)(listener_t *);
90 } fe_listener_impl_t;
92 struct sdb_fe_socket {
93 listener_t *listeners;
94 size_t listeners_num;
96 sdb_llist_t *open_connections;
98 /* channel used for communication between main
99 * and connection handler threads */
100 sdb_channel_t *chan;
101 };
103 /*
104 * connection management functions
105 */
107 static int
108 unixsock_peer(sdb_conn_t *conn)
109 {
110 uid_t uid;
112 struct passwd pw_entry;
113 struct passwd *result = NULL;
114 char buf[1024];
116 #ifdef SO_PEERCRED
117 struct ucred cred;
118 socklen_t len = sizeof(cred);
120 if (getsockopt(conn->fd, SOL_SOCKET, SO_PEERCRED, &cred, &len)
121 || (len != sizeof(cred))) {
122 char errbuf[1024];
123 sdb_log(SDB_LOG_ERR, "frontend: Failed to determine peer for "
124 "connection conn#%i: %s", conn->fd,
125 sdb_strerror(errno, errbuf, sizeof(errbuf)));
126 return -1;
127 }
128 uid = cred.uid;
129 #else /* SO_PEERCRED */
130 sdb_log(SDB_LOG_ERR, "frontend: Failed to determine peer for "
131 "connection conn#%i: operation not supported", conn->fd);
132 return -1;
133 #endif
135 memset(&pw_entry, 0, sizeof(pw_entry));
136 if (getpwuid_r(uid, &pw_entry, buf, sizeof(buf), &result) || (! result)
137 || (! (conn->username = strdup(result->pw_name)))) {
138 char errbuf[1024];
139 sdb_log(SDB_LOG_ERR, "frontend: Failed to determine peer for "
140 "connection conn#%i: %s", conn->fd,
141 sdb_strerror(errno, errbuf, sizeof(errbuf)));
142 return -1;
143 }
144 return 0;
145 } /* unixsock_peer */
147 static int
148 open_unixsock(listener_t *listener)
149 {
150 char *addr_copy;
151 char *base_dir;
152 struct sockaddr_un sa;
153 int status;
155 listener->sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
156 if (listener->sock_fd < 0) {
157 char buf[1024];
158 sdb_log(SDB_LOG_ERR, "frontend: Failed to open UNIX socket %s: %s",
159 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
160 return -1;
161 }
163 memset(&sa, 0, sizeof(sa));
164 sa.sun_family = AF_UNIX;
165 strncpy(sa.sun_path, listener->address, sizeof(sa.sun_path));
167 addr_copy = strdup(listener->address);
168 if (! addr_copy) {
169 char errbuf[1024];
170 sdb_log(SDB_LOG_ERR, "frontend: strdup failed: %s",
171 sdb_strerror(errno, errbuf, sizeof(errbuf)));
172 return -1;
173 }
174 base_dir = dirname(addr_copy);
176 /* ensure that the directory exists */
177 if (sdb_mkdir_all(base_dir, 0777)) {
178 char errbuf[1024];
179 sdb_log(SDB_LOG_ERR, "frontend: Failed to create directory '%s': %s",
180 base_dir, sdb_strerror(errno, errbuf, sizeof(errbuf)));
181 free(addr_copy);
182 return -1;
183 }
184 free(addr_copy);
186 if (unlink(listener->address) && (errno != ENOENT)) {
187 char errbuf[1024];
188 sdb_log(SDB_LOG_WARNING, "frontend: Failed to remove stale UNIX "
189 "socket %s: %s", listener->address,
190 sdb_strerror(errno, errbuf, sizeof(errbuf)));
191 }
193 status = bind(listener->sock_fd, (struct sockaddr *)&sa, sizeof(sa));
194 if (status) {
195 char buf[1024];
196 sdb_log(SDB_LOG_ERR, "frontend: Failed to bind to UNIX socket %s: %s",
197 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
198 return -1;
199 }
201 listener->peer = unixsock_peer;
202 return 0;
203 } /* open_unixsock */
205 static void
206 close_unixsock(listener_t *listener)
207 {
208 assert(listener);
210 if (! listener->address)
211 return;
213 if (listener->sock_fd >= 0)
214 close(listener->sock_fd);
215 listener->sock_fd = -1;
217 unlink(listener->address);
218 } /* close_unixsock */
220 /*
221 * private variables
222 */
224 /* the enum has to be sorted the same as the implementations array
225 * to ensure that the type may be used as index into the array */
226 enum {
227 LISTENER_UNIXSOCK = 0, /* this is the default */
228 };
229 static fe_listener_impl_t listener_impls[] = {
230 { LISTENER_UNIXSOCK, "unix", open_unixsock, close_unixsock },
231 };
233 /*
234 * private helper functions
235 */
237 static int
238 listener_listen(listener_t *listener)
239 {
240 assert(listener);
242 /* try to reopen */
243 if (listener->sock_fd < 0)
244 if (listener_impls[listener->type].open(listener))
245 return -1;
246 assert(listener->sock_fd >= 0);
248 if (listen(listener->sock_fd, /* backlog = */ 32)) {
249 char buf[1024];
250 sdb_log(SDB_LOG_ERR, "frontend: Failed to listen on socket %s: %s",
251 listener->address, sdb_strerror(errno, buf, sizeof(buf)));
252 return -1;
253 }
254 return 0;
255 } /* listener_listen */
257 static void
258 listener_close(listener_t *listener)
259 {
260 assert(listener);
262 if (listener_impls[listener->type].close)
263 listener_impls[listener->type].close(listener);
265 if (listener->sock_fd >= 0)
266 close(listener->sock_fd);
267 listener->sock_fd = -1;
268 } /* listener_close */
270 static int
271 get_type(const char *address)
272 {
273 char *sep;
274 size_t len;
275 size_t i;
277 sep = strchr(address, (int)':');
278 if (! sep)
279 return listener_impls[0].type;
281 assert(sep > address);
282 len = (size_t)(sep - address);
284 for (i = 0; i < SDB_STATIC_ARRAY_LEN(listener_impls); ++i) {
285 fe_listener_impl_t *impl = listener_impls + i;
287 if (!strncmp(address, impl->prefix, len)) {
288 assert(impl->type == (int)i);
289 return impl->type;
290 }
291 }
292 return -1;
293 } /* get_type */
295 static void
296 listener_destroy(listener_t *listener)
297 {
298 if (! listener)
299 return;
301 listener_close(listener);
303 if (listener->address)
304 free(listener->address);
305 listener->address = NULL;
306 } /* listener_destroy */
308 static listener_t *
309 listener_create(sdb_fe_socket_t *sock, const char *address)
310 {
311 listener_t *listener;
312 size_t len;
313 int type;
315 type = get_type(address);
316 if (type < 0) {
317 sdb_log(SDB_LOG_ERR, "frontend: Unsupported address type specified "
318 "in listen address '%s'", address);
319 return NULL;
320 }
322 listener = realloc(sock->listeners,
323 (sock->listeners_num + 1) * sizeof(*sock->listeners));
324 if (! listener) {
325 char buf[1024];
326 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
327 sdb_strerror(errno, buf, sizeof(buf)));
328 return NULL;
329 }
331 sock->listeners = listener;
332 listener = sock->listeners + sock->listeners_num;
334 len = strlen(listener_impls[type].prefix);
335 if ((! strncmp(address, listener_impls[type].prefix, len))
336 && (address[len] == ':'))
337 address += strlen(listener_impls[type].prefix) + 1;
339 listener->sock_fd = -1;
340 listener->address = strdup(address);
341 if (! listener->address) {
342 char buf[1024];
343 sdb_log(SDB_LOG_ERR, "frontend: Failed to allocate memory: %s",
344 sdb_strerror(errno, buf, sizeof(buf)));
345 listener_destroy(listener);
346 return NULL;
347 }
348 listener->type = type;
349 listener->accept = NULL;
351 if (listener_impls[type].open(listener)) {
352 /* prints error */
353 listener_destroy(listener);
354 return NULL;
355 }
357 ++sock->listeners_num;
358 return listener;
359 } /* listener_create */
361 static void
362 socket_clear(sdb_fe_socket_t *sock)
363 {
364 size_t i;
366 assert(sock);
367 for (i = 0; i < sock->listeners_num; ++i)
368 listener_destroy(sock->listeners + i);
369 if (sock->listeners)
370 free(sock->listeners);
371 sock->listeners = NULL;
372 sock->listeners_num = 0;
373 } /* socket_clear */
375 static void
376 socket_close(sdb_fe_socket_t *sock)
377 {
378 size_t i;
380 assert(sock);
381 for (i = 0; i < sock->listeners_num; ++i)
382 listener_close(sock->listeners + i);
383 } /* socket_close */
385 /*
386 * connection handler functions
387 */
389 static void *
390 connection_handler(void *data)
391 {
392 sdb_fe_socket_t *sock = data;
394 assert(sock);
396 while (42) {
397 struct timespec timeout = { 0, 500000000 }; /* .5 seconds */
398 sdb_conn_t *conn;
399 int status;
401 errno = 0;
402 status = sdb_channel_select(sock->chan, /* read */ NULL, &conn,
403 /* write */ NULL, NULL, &timeout);
404 if (status) {
405 char buf[1024];
407 if (errno == ETIMEDOUT)
408 continue;
409 if (errno == EBADF) /* channel shut down */
410 break;
412 sdb_log(SDB_LOG_ERR, "frontend: Failed to read from channel: %s",
413 sdb_strerror(errno, buf, sizeof(buf)));
414 continue;
415 }
417 status = (int)sdb_connection_handle(conn);
418 if (status <= 0) {
419 /* error or EOF -> close connection */
420 sdb_object_deref(SDB_OBJ(conn));
421 continue;
422 }
424 /* return the connection to the main loop */
425 if (sdb_llist_append(sock->open_connections, SDB_OBJ(conn))) {
426 sdb_log(SDB_LOG_ERR, "frontend: Failed to re-append "
427 "connection %s to list of open connections",
428 SDB_OBJ(conn)->name);
429 }
431 /* pass ownership back to list; or destroy in case of an error */
432 sdb_object_deref(SDB_OBJ(conn));
433 }
434 return NULL;
435 } /* connection_handler */
437 static int
438 connection_accept(sdb_fe_socket_t *sock, listener_t *listener)
439 {
440 sdb_object_t *obj;
441 int status;
443 obj = SDB_OBJ(sdb_connection_accept(listener->sock_fd));
444 if (! obj)
445 return -1;
447 if (listener->accept && listener->accept(CONN(obj))) {
448 /* accept() is expected to log an error */
449 sdb_object_deref(obj);
450 return -1;
451 }
452 if (listener->peer && listener->peer(CONN(obj))) {
453 /* peer() is expected to log an error */
454 sdb_object_deref(obj);
455 return -1;
456 }
458 status = sdb_llist_append(sock->open_connections, obj);
459 if (status)
460 sdb_log(SDB_LOG_ERR, "frontend: Failed to append "
461 "connection %s to list of open connections",
462 obj->name);
464 /* hand ownership over to the list; or destroy in case of an error */
465 sdb_object_deref(obj);
466 return status;
467 } /* connection_accept */
469 static int
470 socket_handle_incoming(sdb_fe_socket_t *sock,
471 fd_set *ready, fd_set *exceptions)
472 {
473 sdb_llist_iter_t *iter;
474 size_t i;
476 for (i = 0; i < sock->listeners_num; ++i) {
477 listener_t *listener = sock->listeners + i;
478 if (FD_ISSET(listener->sock_fd, ready))
479 if (connection_accept(sock, listener))
480 continue;
481 }
483 iter = sdb_llist_get_iter(sock->open_connections);
484 if (! iter) {
485 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
486 "for open connections");
487 return -1;
488 }
490 while (sdb_llist_iter_has_next(iter)) {
491 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
493 if (FD_ISSET(CONN(obj)->fd, exceptions)) {
494 sdb_log(SDB_LOG_INFO, "Exception on fd %d",
495 CONN(obj)->fd);
496 /* close the connection */
497 sdb_llist_iter_remove_current(iter);
498 sdb_object_deref(obj);
499 continue;
500 }
502 if (FD_ISSET(CONN(obj)->fd, ready)) {
503 sdb_llist_iter_remove_current(iter);
504 sdb_channel_write(sock->chan, &obj);
505 }
506 }
507 sdb_llist_iter_destroy(iter);
508 return 0;
509 } /* socket_handle_incoming */
511 /*
512 * public API
513 */
515 sdb_fe_socket_t *
516 sdb_fe_sock_create(void)
517 {
518 sdb_fe_socket_t *sock;
520 sock = calloc(1, sizeof(*sock));
521 if (! sock)
522 return NULL;
524 sock->open_connections = sdb_llist_create();
525 if (! sock->open_connections) {
526 sdb_fe_sock_destroy(sock);
527 return NULL;
528 }
529 return sock;
530 } /* sdb_fe_sock_create */
532 void
533 sdb_fe_sock_destroy(sdb_fe_socket_t *sock)
534 {
535 if (! sock)
536 return;
538 socket_clear(sock);
540 sdb_llist_destroy(sock->open_connections);
541 sock->open_connections = NULL;
542 free(sock);
543 } /* sdb_fe_sock_destroy */
545 int
546 sdb_fe_sock_add_listener(sdb_fe_socket_t *sock, const char *address)
547 {
548 listener_t *listener;
550 if ((! sock) || (! address))
551 return -1;
553 listener = listener_create(sock, address);
554 if (! listener)
555 return -1;
556 return 0;
557 } /* sdb_fe_sock_add_listener */
559 void
560 sdb_fe_sock_clear_listeners(sdb_fe_socket_t *sock)
561 {
562 if (! sock)
563 return;
565 socket_clear(sock);
566 } /* sdb_fe_sock_clear_listeners */
568 int
569 sdb_fe_sock_listen_and_serve(sdb_fe_socket_t *sock, sdb_fe_loop_t *loop)
570 {
571 fd_set sockets;
572 int max_listen_fd = 0;
573 size_t i;
575 pthread_t handler_threads[loop->num_threads];
576 size_t num_threads;
578 if ((! sock) || (! sock->listeners_num) || sock->chan
579 || (! loop) || (loop->num_threads <= 0))
580 return -1;
582 if (! loop->do_loop)
583 return 0;
585 FD_ZERO(&sockets);
586 for (i = 0; i < sock->listeners_num; ++i) {
587 listener_t *listener = sock->listeners + i;
589 if (listener_listen(listener)) {
590 socket_close(sock);
591 return -1;
592 }
594 FD_SET(listener->sock_fd, &sockets);
595 if (listener->sock_fd > max_listen_fd)
596 max_listen_fd = listener->sock_fd;
597 }
599 sock->chan = sdb_channel_create(1024, sizeof(sdb_conn_t *));
600 if (! sock->chan) {
601 socket_close(sock);
602 return -1;
603 }
605 sdb_log(SDB_LOG_INFO, "frontend: Starting %zu connection "
606 "handler thread%s managing %zu listener%s",
607 loop->num_threads, loop->num_threads == 1 ? "" : "s",
608 sock->listeners_num, sock->listeners_num == 1 ? "" : "s");
610 num_threads = loop->num_threads;
611 memset(&handler_threads, 0, sizeof(handler_threads));
612 for (i = 0; i < num_threads; ++i) {
613 errno = 0;
614 if (pthread_create(&handler_threads[i], /* attr = */ NULL,
615 connection_handler, /* arg = */ sock)) {
616 char errbuf[1024];
617 sdb_log(SDB_LOG_ERR, "frontend: Failed to create "
618 "connection handler thread: %s",
619 sdb_strerror(errno, errbuf, sizeof(errbuf)));
620 num_threads = i;
621 break;
622 }
623 }
625 while (loop->do_loop && num_threads) {
626 struct timeval timeout = { 1, 0 }; /* one second */
627 sdb_llist_iter_t *iter;
629 int max_fd = max_listen_fd;
630 fd_set ready;
631 fd_set exceptions;
632 int n;
634 FD_ZERO(&ready);
635 FD_ZERO(&exceptions);
637 ready = sockets;
639 iter = sdb_llist_get_iter(sock->open_connections);
640 if (! iter) {
641 sdb_log(SDB_LOG_ERR, "frontend: Failed to acquire iterator "
642 "for open connections");
643 break;
644 }
646 while (sdb_llist_iter_has_next(iter)) {
647 sdb_object_t *obj = sdb_llist_iter_get_next(iter);
649 if (CONN(obj)->fd < 0) {
650 sdb_llist_iter_remove_current(iter);
651 sdb_object_deref(obj);
652 continue;
653 }
655 FD_SET(CONN(obj)->fd, &ready);
656 FD_SET(CONN(obj)->fd, &exceptions);
658 if (CONN(obj)->fd > max_fd)
659 max_fd = CONN(obj)->fd;
660 }
661 sdb_llist_iter_destroy(iter);
663 errno = 0;
664 n = select(max_fd + 1, &ready, NULL, &exceptions, &timeout);
665 if (n < 0) {
666 char buf[1024];
668 if (errno == EINTR)
669 continue;
671 sdb_log(SDB_LOG_ERR, "frontend: Failed to monitor sockets: %s",
672 sdb_strerror(errno, buf, sizeof(buf)));
673 break;
674 }
675 else if (! n)
676 continue;
678 /* handle new and open connections */
679 if (socket_handle_incoming(sock, &ready, &exceptions))
680 break;
681 }
683 socket_close(sock);
685 sdb_log(SDB_LOG_INFO, "frontend: Waiting for connection handler threads "
686 "to terminate");
687 if (! sdb_channel_shutdown(sock->chan))
688 for (i = 0; i < num_threads; ++i)
689 pthread_join(handler_threads[i], NULL);
690 /* else: we tried our best; let the operating system clean up */
692 sdb_channel_destroy(sock->chan);
693 sock->chan = NULL;
695 if (! num_threads)
696 return -1;
697 return 0;
698 } /* sdb_fe_sock_listen_and_server */
700 /* vim: set tw=78 sw=4 ts=4 noexpandtab : */