1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/types.h>
27 #include <sys/epoll.h>
29 #include <arpa/inet.h>
30 #include <selinux/selinux.h>
34 #include "netinet/tcp.h"
36 #include "load-dropin.h"
37 #include "load-fragment.h"
39 #include "unit-name.h"
40 #include "dbus-socket.h"
43 #include "bus-errors.h"
45 static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
46 [SOCKET_DEAD] = UNIT_INACTIVE,
47 [SOCKET_START_PRE] = UNIT_ACTIVATING,
48 [SOCKET_START_POST] = UNIT_ACTIVATING,
49 [SOCKET_LISTENING] = UNIT_ACTIVE,
50 [SOCKET_RUNNING] = UNIT_ACTIVE,
51 [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
52 [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
53 [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
54 [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
55 [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
56 [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
57 [SOCKET_MAINTENANCE] = UNIT_MAINTENANCE
60 static void socket_init(Unit *u) {
61 Socket *s = SOCKET(u);
64 assert(u->meta.load_state == UNIT_STUB);
66 s->backlog = SOMAXCONN;
67 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
68 s->directory_mode = 0755;
69 s->socket_mode = 0666;
71 s->max_connections = 64;
78 exec_context_init(&s->exec_context);
80 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
83 static void socket_unwatch_control_pid(Socket *s) {
86 if (s->control_pid <= 0)
89 unit_unwatch_pid(UNIT(s), s->control_pid);
93 static void socket_done(Unit *u) {
94 Socket *s = SOCKET(u);
100 while ((p = s->ports)) {
101 LIST_REMOVE(SocketPort, port, s->ports, p);
104 unit_unwatch_fd(UNIT(s), &p->fd_watch);
105 close_nointr_nofail(p->fd);
112 exec_context_done(&s->exec_context);
113 exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
114 s->control_command = NULL;
116 socket_unwatch_control_pid(s);
120 free(s->tcp_congestion);
121 s->tcp_congestion = NULL;
123 free(s->bind_to_device);
124 s->bind_to_device = NULL;
126 unit_unwatch_timer(u, &s->timer_watch);
128 /* Make sure no service instance refers to us anymore. */
129 LIST_FOREACH(units_per_type, i, u->meta.manager->units_per_type[UNIT_SERVICE]) {
130 Service *service = (Service *) i;
132 if (service->socket == s)
133 service->socket = NULL;
137 static int socket_instantiate_service(Socket *s) {
144 /* This fills in s->service if it isn't filled in yet. For
145 * Accept=yes sockets we create the next connection service
146 * here. For Accept=no this is mostly a NOP since the service
147 * is figured out at load time anyway. */
154 if (!(prefix = unit_name_to_prefix(s->meta.id)))
157 r = asprintf(&name, "%s@%u.service", prefix, s->n_accepted);
163 r = manager_load_unit(s->meta.manager, name, NULL, NULL, &u);
169 s->service = SERVICE(u);
173 static bool have_non_accept_socket(Socket *s) {
181 LIST_FOREACH(port, p, s->ports) {
183 if (p->type != SOCKET_SOCKET)
186 if (!socket_address_can_accept(&p->address))
193 static int socket_verify(Socket *s) {
196 if (s->meta.load_state != UNIT_LOADED)
200 log_error("%s lacks Listen setting. Refusing.", s->meta.id);
204 if (s->accept && have_non_accept_socket(s)) {
205 log_error("%s configured for accepting sockets, but sockets are non-accepting. Refusing.", s->meta.id);
209 if (s->accept && s->max_connections <= 0) {
210 log_error("%s's MaxConnection setting too small. Refusing.", s->meta.id);
214 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
215 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
222 static bool socket_needs_mount(Socket *s, const char *prefix) {
227 LIST_FOREACH(port, p, s->ports) {
229 if (p->type == SOCKET_SOCKET) {
230 if (socket_address_needs_mount(&p->address, prefix))
233 assert(p->type == SOCKET_FIFO);
234 if (path_startswith(p->path, prefix))
242 int socket_add_one_mount_link(Socket *s, Mount *m) {
248 if (s->meta.load_state != UNIT_LOADED ||
249 m->meta.load_state != UNIT_LOADED)
252 if (!socket_needs_mount(s, m->where))
255 if ((r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
261 static int socket_add_mount_links(Socket *s) {
267 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_MOUNT])
268 if ((r = socket_add_one_mount_link(s, (Mount*) other)) < 0)
274 static int socket_add_device_link(Socket *s) {
280 if (!s->bind_to_device)
283 if (asprintf(&t, "/sys/subsystem/net/devices/%s", s->bind_to_device) < 0)
286 r = unit_add_node_link(UNIT(s), t, false);
292 static int socket_add_default_dependencies(Socket *s) {
296 if (s->meta.manager->running_as == MANAGER_SYSTEM)
297 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 0)
300 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
303 static int socket_load(Unit *u) {
304 Socket *s = SOCKET(u);
308 assert(u->meta.load_state == UNIT_STUB);
310 if ((r = unit_load_fragment_and_dropin(u)) < 0)
313 /* This is a new unit? Then let's add in some extras */
314 if (u->meta.load_state == UNIT_LOADED) {
316 if (have_non_accept_socket(s)) {
317 if ((r = unit_load_related_unit(u, ".service", (Unit**) &s->service)) < 0)
320 if ((r = unit_add_dependency(u, UNIT_BEFORE, UNIT(s->service), true)) < 0)
324 if ((r = socket_add_mount_links(s)) < 0)
327 if ((r = socket_add_device_link(s)) < 0)
330 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
333 if ((r = unit_add_default_cgroup(u)) < 0)
336 if (s->meta.default_dependencies)
337 if ((r = socket_add_default_dependencies(s)) < 0)
341 return socket_verify(s);
344 static const char* listen_lookup(int type) {
346 if (type == SOCK_STREAM)
347 return "ListenStream";
348 else if (type == SOCK_DGRAM)
349 return "ListenDatagram";
350 else if (type == SOCK_SEQPACKET)
351 return "ListenSequentialPacket";
353 assert_not_reached("Unknown socket type");
357 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
360 Socket *s = SOCKET(u);
368 p2 = strappend(prefix, "\t");
369 prefix2 = p2 ? p2 : prefix;
372 "%sSocket State: %s\n"
373 "%sBindIPv6Only: %s\n"
375 "%sSocketMode: %04o\n"
376 "%sDirectoryMode: %04o\n"
379 "%sTCPCongestion: %s\n",
380 prefix, socket_state_to_string(s->state),
381 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
383 prefix, s->socket_mode,
384 prefix, s->directory_mode,
385 prefix, yes_no(s->keep_alive),
386 prefix, yes_no(s->free_bind),
387 prefix, s->tcp_congestion);
389 if (s->control_pid > 0)
391 "%sControl PID: %lu\n",
392 prefix, (unsigned long) s->control_pid);
394 if (s->bind_to_device)
396 "%sBindToDevice: %s\n",
397 prefix, s->bind_to_device);
402 "%sNConnections: %u\n"
403 "%sMaxConnections: %u\n",
404 prefix, s->n_accepted,
405 prefix, s->n_connections,
406 prefix, s->max_connections);
408 if (s->priority >= 0)
411 prefix, s->priority);
413 if (s->receive_buffer > 0)
415 "%sReceiveBuffer: %zu\n",
416 prefix, s->receive_buffer);
418 if (s->send_buffer > 0)
420 "%sSendBuffer: %zu\n",
421 prefix, s->send_buffer);
433 if (s->pipe_size > 0)
436 prefix, s->pipe_size);
443 LIST_FOREACH(port, p, s->ports) {
445 if (p->type == SOCKET_SOCKET) {
450 if ((r = socket_address_print(&p->address, &k)) < 0)
455 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(p->address.type), k);
458 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
461 exec_context_dump(&s->exec_context, f, prefix);
463 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
464 if (!s->exec_command[c])
467 fprintf(f, "%s-> %s:\n",
468 prefix, socket_exec_command_to_string(c));
470 exec_command_dump_list(s->exec_command[c], f, prefix2);
476 static int instance_from_socket(int fd, unsigned nr, char **instance) {
481 struct sockaddr_un un;
482 struct sockaddr_in in;
483 struct sockaddr_in6 in6;
484 struct sockaddr_storage storage;
491 if (getsockname(fd, &local.sa, &l) < 0)
495 if (getpeername(fd, &remote.sa, &l) < 0)
498 switch (local.sa.sa_family) {
502 a = ntohl(local.in.sin_addr.s_addr),
503 b = ntohl(remote.in.sin_addr.s_addr);
506 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
507 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
508 ntohs(local.in.sin_port),
509 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
510 ntohs(remote.in.sin_port)) < 0)
517 static const char ipv4_prefix[] = {
518 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
521 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
522 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
524 *a = local.in6.sin6_addr.s6_addr+12,
525 *b = remote.in6.sin6_addr.s6_addr+12;
528 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
529 a[0], a[1], a[2], a[3],
530 ntohs(local.in6.sin6_port),
531 b[0], b[1], b[2], b[3],
532 ntohs(remote.in6.sin6_port)) < 0)
535 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
539 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
540 ntohs(local.in6.sin6_port),
541 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
542 ntohs(remote.in6.sin6_port)) < 0)
553 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
559 (unsigned long) ucred.pid,
560 (unsigned long) ucred.uid) < 0)
567 assert_not_reached("Unhandled socket type.");
574 static void socket_close_fds(Socket *s) {
579 LIST_FOREACH(port, p, s->ports) {
583 unit_unwatch_fd(UNIT(s), &p->fd_watch);
584 close_nointr_nofail(p->fd);
586 /* One little note: we should never delete any sockets
587 * in the file system here! After all some other
588 * process we spawned might still have a reference of
589 * this fd and wants to continue to use it. Therefore
590 * we delete sockets in the file system before we
591 * create a new one, not after we stopped using
598 static void socket_apply_socket_options(Socket *s, int fd) {
603 int b = s->keep_alive;
604 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
605 log_warning("SO_KEEPALIVE failed: %m");
608 if (s->priority >= 0)
609 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
610 log_warning("SO_PRIORITY failed: %m");
612 if (s->receive_buffer > 0) {
613 int value = (int) s->receive_buffer;
614 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
615 log_warning("SO_RCVBUF failed: %m");
618 if (s->send_buffer > 0) {
619 int value = (int) s->send_buffer;
620 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
621 log_warning("SO_SNDBUF failed: %m");
625 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
626 log_warning("SO_MARK failed: %m");
629 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
630 log_warning("IP_TOS failed: %m");
632 if (s->ip_ttl >= 0) {
635 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
636 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
639 log_warning("IP_TTL/IPV6_UNICAST_HOPS failed: %m");
642 if (s->tcp_congestion)
643 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
644 log_warning("TCP_CONGESTION failed: %m");
647 static void socket_apply_fifo_options(Socket *s, int fd) {
651 if (s->pipe_size > 0)
652 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
653 log_warning("F_SETPIPE_SZ: %m");
656 static int selinux_getconfromexe(
658 security_context_t *newcon) {
660 security_context_t mycon = NULL, fcon = NULL;
661 security_class_t sclass;
668 r = getfilecon(exe, &fcon);
672 sclass = string_to_security_class("process");
673 r = security_compute_create(mycon, fcon, sclass, newcon);
684 static int selinux_getfileconfrompath(
685 const security_context_t scon,
688 security_context_t *fcon) {
690 security_context_t dir_con = NULL;
691 security_class_t sclass;
694 r = getfilecon(path, &dir_con);
697 if ((sclass = string_to_security_class(class)) != 0)
698 r = security_compute_create(scon, dir_con, sclass, fcon);
707 static int fifo_address_create(
709 mode_t directory_mode,
711 security_context_t scon,
717 security_context_t filecon = NULL;
722 mkdir_parents(path, directory_mode);
725 if (scon && ((r = selinux_getfileconfrompath(scon, path, "fifo_file", &filecon)) == 0)) {
726 r = setfscreatecon(filecon);
729 log_error("Failed to set SELinux file context (%s) on %s: %m", scon, path);
736 if (r < 0 && security_getenforce() == 1)
740 /* Enforce the right access mode for the fifo */
741 old_mask = umask(~ socket_mode);
743 /* Include the original umask in our mask */
744 umask(~socket_mode | old_mask);
746 r = mkfifo(path, socket_mode);
754 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
759 setfscreatecon(NULL);
761 if (fstat(fd, &st) < 0) {
766 if (!S_ISFIFO(st.st_mode) ||
767 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
768 st.st_uid != getuid() ||
769 st.st_gid != getgid()) {
779 setfscreatecon(NULL);
781 close_nointr_nofail(fd);
786 static int socket_open_fds(Socket *s) {
789 security_context_t scon = NULL;
793 if ((r = socket_instantiate_service(s)) < 0)
796 if (selinux_getconfromexe(s->service->exec_command[SERVICE_EXEC_START]->path, &scon) < 0) {
797 log_error("Failed to get SELinux exec context for %s \n", s->service->exec_command[SERVICE_EXEC_START]->path);
798 if (security_getenforce() == 1)
802 log_debug("SELinux Socket context for %s set to %s\n", s->service->exec_command[SERVICE_EXEC_START]->path, scon);
803 LIST_FOREACH(port, p, s->ports) {
808 if (p->type == SOCKET_SOCKET) {
810 if ((r = socket_address_listen(
822 socket_apply_socket_options(s, p->fd);
824 } else if (p->type == SOCKET_FIFO) {
826 if ((r = fifo_address_create(
834 socket_apply_fifo_options(s, p->fd);
837 assert_not_reached("Unknown port type");
849 static void socket_unwatch_fds(Socket *s) {
854 LIST_FOREACH(port, p, s->ports) {
858 unit_unwatch_fd(UNIT(s), &p->fd_watch);
862 static int socket_watch_fds(Socket *s) {
868 LIST_FOREACH(port, p, s->ports) {
872 p->fd_watch.socket_accept =
874 p->type == SOCKET_SOCKET &&
875 socket_address_can_accept(&p->address);
877 if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
884 socket_unwatch_fds(s);
888 static void socket_set_state(Socket *s, SocketState state) {
889 SocketState old_state;
892 old_state = s->state;
895 if (state != SOCKET_START_PRE &&
896 state != SOCKET_START_POST &&
897 state != SOCKET_STOP_PRE &&
898 state != SOCKET_STOP_PRE_SIGTERM &&
899 state != SOCKET_STOP_PRE_SIGKILL &&
900 state != SOCKET_STOP_POST &&
901 state != SOCKET_FINAL_SIGTERM &&
902 state != SOCKET_FINAL_SIGKILL) {
903 unit_unwatch_timer(UNIT(s), &s->timer_watch);
904 socket_unwatch_control_pid(s);
905 s->control_command = NULL;
906 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
909 if (state != SOCKET_LISTENING)
910 socket_unwatch_fds(s);
912 if (state != SOCKET_START_POST &&
913 state != SOCKET_LISTENING &&
914 state != SOCKET_RUNNING &&
915 state != SOCKET_STOP_PRE &&
916 state != SOCKET_STOP_PRE_SIGTERM &&
917 state != SOCKET_STOP_PRE_SIGKILL)
920 if (state != old_state)
921 log_debug("%s changed %s -> %s",
923 socket_state_to_string(old_state),
924 socket_state_to_string(state));
926 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
929 static int socket_coldplug(Unit *u) {
930 Socket *s = SOCKET(u);
934 assert(s->state == SOCKET_DEAD);
936 if (s->deserialized_state != s->state) {
938 if (s->deserialized_state == SOCKET_START_PRE ||
939 s->deserialized_state == SOCKET_START_POST ||
940 s->deserialized_state == SOCKET_STOP_PRE ||
941 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
942 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
943 s->deserialized_state == SOCKET_STOP_POST ||
944 s->deserialized_state == SOCKET_FINAL_SIGTERM ||
945 s->deserialized_state == SOCKET_FINAL_SIGKILL) {
947 if (s->control_pid <= 0)
950 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
953 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
957 if (s->deserialized_state == SOCKET_START_POST ||
958 s->deserialized_state == SOCKET_LISTENING ||
959 s->deserialized_state == SOCKET_RUNNING ||
960 s->deserialized_state == SOCKET_STOP_PRE ||
961 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
962 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
963 if ((r = socket_open_fds(s)) < 0)
966 if (s->deserialized_state == SOCKET_LISTENING)
967 if ((r = socket_watch_fds(s)) < 0)
970 socket_set_state(s, s->deserialized_state);
976 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
985 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
988 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
997 s->meta.manager->environment,
1001 s->meta.manager->confirm_spawn,
1002 s->meta.cgroup_bondings,
1009 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1010 /* FIXME: we need to do something here */
1018 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1023 static void socket_enter_dead(Socket *s, bool success) {
1029 socket_set_state(s, s->failure ? SOCKET_MAINTENANCE : SOCKET_DEAD);
1032 static void socket_enter_signal(Socket *s, SocketState state, bool success);
1034 static void socket_enter_stop_post(Socket *s, bool success) {
1041 socket_unwatch_control_pid(s);
1043 s->control_command_id = SOCKET_EXEC_STOP_POST;
1045 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
1046 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1049 socket_set_state(s, SOCKET_STOP_POST);
1051 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, true);
1056 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1057 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1060 static void socket_enter_signal(Socket *s, SocketState state, bool success) {
1069 if (s->exec_context.kill_mode != KILL_NONE) {
1070 int sig = (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1072 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1074 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1075 if (r != -EAGAIN && r != -ESRCH)
1081 if (!sent && s->control_pid > 0)
1082 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH) {
1088 if (sent && s->control_pid > 0) {
1089 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1092 socket_set_state(s, state);
1093 } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1094 socket_enter_stop_post(s, true);
1096 socket_enter_dead(s, true);
1101 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1103 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1104 socket_enter_stop_post(s, false);
1106 socket_enter_dead(s, false);
1109 static void socket_enter_stop_pre(Socket *s, bool success) {
1116 socket_unwatch_control_pid(s);
1118 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1120 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
1121 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1124 socket_set_state(s, SOCKET_STOP_PRE);
1126 socket_enter_stop_post(s, true);
1131 log_warning("%s failed to run 'stop-pre' task: %s", s->meta.id, strerror(-r));
1132 socket_enter_stop_post(s, false);
1135 static void socket_enter_listening(Socket *s) {
1139 if ((r = socket_watch_fds(s)) < 0) {
1140 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1144 socket_set_state(s, SOCKET_LISTENING);
1148 socket_enter_stop_pre(s, false);
1151 static void socket_enter_start_post(Socket *s) {
1155 if ((r = socket_open_fds(s)) < 0) {
1156 log_warning("%s failed to listen on sockets: %s", s->meta.id, strerror(-r));
1160 socket_unwatch_control_pid(s);
1162 s->control_command_id = SOCKET_EXEC_START_POST;
1164 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
1165 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0) {
1166 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1170 socket_set_state(s, SOCKET_START_POST);
1172 socket_enter_listening(s);
1177 socket_enter_stop_pre(s, false);
1180 static void socket_enter_start_pre(Socket *s) {
1184 socket_unwatch_control_pid(s);
1186 s->control_command_id = SOCKET_EXEC_START_PRE;
1188 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
1189 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1192 socket_set_state(s, SOCKET_START_PRE);
1194 socket_enter_start_post(s);
1199 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1200 socket_enter_dead(s, false);
1203 static void socket_enter_running(Socket *s, int cfd) {
1208 dbus_error_init(&error);
1210 /* We don't take connections anymore if we are supposed to
1211 * shut down anyway */
1212 if (s->meta.job && s->meta.job->type == JOB_STOP) {
1214 close_nointr_nofail(cfd);
1216 /* Flush all sockets by closing and reopening them */
1217 socket_close_fds(s);
1219 if ((r = socket_watch_fds(s)) < 0) {
1220 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1221 socket_enter_stop_pre(s, false);
1229 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s->service), JOB_REPLACE, true, &error, NULL)) < 0)
1232 socket_set_state(s, SOCKET_RUNNING);
1234 char *prefix, *instance = NULL, *name;
1237 if (s->n_connections >= s->max_connections) {
1238 log_warning("Too many incoming connections (%u)", s->n_connections);
1239 close_nointr_nofail(cfd);
1243 if ((r = socket_instantiate_service(s)) < 0)
1246 if ((r = instance_from_socket(cfd, s->n_accepted, &instance)) < 0)
1249 if (!(prefix = unit_name_to_prefix(s->meta.id))) {
1255 name = unit_name_build(prefix, instance, ".service");
1264 if ((r = unit_add_name(UNIT(s->service), name)) < 0) {
1269 service = s->service;
1273 unit_choose_id(UNIT(service), name);
1276 if ((r = service_set_socket_fd(service, cfd, s)) < 0)
1280 s->n_connections ++;
1282 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL)) < 0)
1289 log_warning("%s failed to queue socket startup job: %s", s->meta.id, bus_error(&error, r));
1290 socket_enter_stop_pre(s, false);
1293 close_nointr_nofail(cfd);
1295 dbus_error_free(&error);
1298 static void socket_run_next(Socket *s, bool success) {
1302 assert(s->control_command);
1303 assert(s->control_command->command_next);
1308 socket_unwatch_control_pid(s);
1310 s->control_command = s->control_command->command_next;
1312 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1318 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1320 if (s->state == SOCKET_START_POST)
1321 socket_enter_stop_pre(s, false);
1322 else if (s->state == SOCKET_STOP_POST)
1323 socket_enter_dead(s, false);
1325 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1328 static int socket_start(Unit *u) {
1329 Socket *s = SOCKET(u);
1333 /* We cannot fulfill this request right now, try again later
1335 if (s->state == SOCKET_STOP_PRE ||
1336 s->state == SOCKET_STOP_PRE_SIGKILL ||
1337 s->state == SOCKET_STOP_PRE_SIGTERM ||
1338 s->state == SOCKET_STOP_POST ||
1339 s->state == SOCKET_FINAL_SIGTERM ||
1340 s->state == SOCKET_FINAL_SIGKILL)
1343 if (s->state == SOCKET_START_PRE ||
1344 s->state == SOCKET_START_POST)
1347 /* Cannot run this without the service being around */
1349 if (s->service->meta.load_state != UNIT_LOADED)
1352 /* If the service is alredy actvie we cannot start the
1354 if (s->service->state != SERVICE_DEAD &&
1355 s->service->state != SERVICE_MAINTENANCE &&
1356 s->service->state != SERVICE_AUTO_RESTART)
1360 assert(s->state == SOCKET_DEAD || s->state == SOCKET_MAINTENANCE);
1363 socket_enter_start_pre(s);
1367 static int socket_stop(Unit *u) {
1368 Socket *s = SOCKET(u);
1373 if (s->state == SOCKET_STOP_PRE ||
1374 s->state == SOCKET_STOP_PRE_SIGTERM ||
1375 s->state == SOCKET_STOP_PRE_SIGKILL ||
1376 s->state == SOCKET_STOP_POST ||
1377 s->state == SOCKET_FINAL_SIGTERM ||
1378 s->state == SOCKET_FINAL_SIGKILL)
1381 /* If there's already something running we go directly into
1383 if (s->state == SOCKET_START_PRE ||
1384 s->state == SOCKET_START_POST) {
1385 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, true);
1389 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1391 socket_enter_stop_pre(s, true);
1395 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1396 Socket *s = SOCKET(u);
1404 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1405 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1406 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1408 if (s->control_pid > 0)
1409 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1411 if (s->control_command_id >= 0)
1412 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1414 LIST_FOREACH(port, p, s->ports) {
1420 if ((copy = fdset_put_dup(fds, p->fd)) < 0)
1423 if (p->type == SOCKET_SOCKET) {
1426 if ((r = socket_address_print(&p->address, &t)) < 0)
1429 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1432 assert(p->type == SOCKET_FIFO);
1433 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1440 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1441 Socket *s = SOCKET(u);
1449 if (streq(key, "state")) {
1452 if ((state = socket_state_from_string(value)) < 0)
1453 log_debug("Failed to parse state value %s", value);
1455 s->deserialized_state = state;
1456 } else if (streq(key, "failure")) {
1459 if ((b = parse_boolean(value)) < 0)
1460 log_debug("Failed to parse failure value %s", value);
1462 s->failure = b || s->failure;
1464 } else if (streq(key, "n-accepted")) {
1467 if ((r = safe_atou(value, &k)) < 0)
1468 log_debug("Failed to parse n-accepted value %s", value);
1471 } else if (streq(key, "control-pid")) {
1474 if ((r = parse_pid(value, &pid)) < 0)
1475 log_debug("Failed to parse control-pid value %s", value);
1477 s->control_pid = pid;
1478 } else if (streq(key, "control-command")) {
1479 SocketExecCommand id;
1481 if ((id = socket_exec_command_from_string(value)) < 0)
1482 log_debug("Failed to parse exec-command value %s", value);
1484 s->control_command_id = id;
1485 s->control_command = s->exec_command[id];
1487 } else if (streq(key, "fifo")) {
1491 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1492 log_debug("Failed to parse fifo value %s", value);
1495 LIST_FOREACH(port, p, s->ports)
1496 if (streq(p->path, value+skip))
1501 close_nointr_nofail(p->fd);
1502 p->fd = fdset_remove(fds, fd);
1506 } else if (streq(key, "socket")) {
1507 int fd, type, skip = 0;
1510 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
1511 log_debug("Failed to parse socket value %s", value);
1514 LIST_FOREACH(port, p, s->ports)
1515 if (socket_address_is(&p->address, value+skip, type))
1520 close_nointr_nofail(p->fd);
1521 p->fd = fdset_remove(fds, fd);
1526 log_debug("Unknown serialization key '%s'", key);
1531 static UnitActiveState socket_active_state(Unit *u) {
1534 return state_translation_table[SOCKET(u)->state];
1537 static const char *socket_sub_state_to_string(Unit *u) {
1540 return socket_state_to_string(SOCKET(u)->state);
1543 static bool socket_check_gc(Unit *u) {
1544 Socket *s = SOCKET(u);
1548 return s->n_connections > 0;
1551 static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
1552 Socket *s = SOCKET(u);
1558 if (s->state != SOCKET_LISTENING)
1561 log_debug("Incoming traffic on %s", u->meta.id);
1563 if (events != EPOLLIN) {
1564 log_error("Got invalid poll event on socket.");
1568 if (w->socket_accept) {
1571 if ((cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK)) < 0) {
1576 log_error("Failed to accept socket: %m");
1583 socket_apply_socket_options(s, cfd);
1586 socket_enter_running(s, cfd);
1590 socket_enter_stop_pre(s, false);
1593 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1594 Socket *s = SOCKET(u);
1600 if (pid != s->control_pid)
1605 success = is_clean_exit(code, status);
1607 if (s->control_command) {
1608 exec_status_exit(&s->control_command->exec_status, pid, code, status);
1610 if (s->control_command->ignore)
1614 log_full(success ? LOG_DEBUG : LOG_NOTICE,
1615 "%s control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1616 s->failure = s->failure || !success;
1618 if (s->control_command && s->control_command->command_next && success) {
1619 log_debug("%s running next command for state %s", u->meta.id, socket_state_to_string(s->state));
1620 socket_run_next(s, success);
1622 s->control_command = NULL;
1623 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1625 /* No further commands for this step, so let's figure
1626 * out what to do next */
1628 log_debug("%s got final SIGCHLD for state %s", u->meta.id, socket_state_to_string(s->state));
1632 case SOCKET_START_PRE:
1634 socket_enter_start_post(s);
1636 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1639 case SOCKET_START_POST:
1641 socket_enter_listening(s);
1643 socket_enter_stop_pre(s, false);
1646 case SOCKET_STOP_PRE:
1647 case SOCKET_STOP_PRE_SIGTERM:
1648 case SOCKET_STOP_PRE_SIGKILL:
1649 socket_enter_stop_post(s, success);
1652 case SOCKET_STOP_POST:
1653 case SOCKET_FINAL_SIGTERM:
1654 case SOCKET_FINAL_SIGKILL:
1655 socket_enter_dead(s, success);
1659 assert_not_reached("Uh, control process died at wrong time.");
1664 static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
1665 Socket *s = SOCKET(u);
1668 assert(elapsed == 1);
1669 assert(w == &s->timer_watch);
1673 case SOCKET_START_PRE:
1674 log_warning("%s starting timed out. Terminating.", u->meta.id);
1675 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1677 case SOCKET_START_POST:
1678 log_warning("%s starting timed out. Stopping.", u->meta.id);
1679 socket_enter_stop_pre(s, false);
1682 case SOCKET_STOP_PRE:
1683 log_warning("%s stopping timed out. Terminating.", u->meta.id);
1684 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, false);
1687 case SOCKET_STOP_PRE_SIGTERM:
1688 log_warning("%s stopping timed out. Killing.", u->meta.id);
1689 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, false);
1692 case SOCKET_STOP_PRE_SIGKILL:
1693 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
1694 socket_enter_stop_post(s, false);
1697 case SOCKET_STOP_POST:
1698 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
1699 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1702 case SOCKET_FINAL_SIGTERM:
1703 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
1704 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, false);
1707 case SOCKET_FINAL_SIGKILL:
1708 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
1709 socket_enter_dead(s, false);
1713 assert_not_reached("Timeout at wrong time.");
1717 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
1726 /* Called from the service code for requesting our fds */
1729 LIST_FOREACH(port, p, s->ports)
1733 if (!(rfds = new(int, rn_fds)) < 0)
1737 LIST_FOREACH(port, p, s->ports)
1741 assert(k == rn_fds);
1749 void socket_notify_service_dead(Socket *s) {
1752 /* The service is dead. Dang!
1754 * This is strictly for one-instance-for-all-connections
1757 if (s->state == SOCKET_RUNNING) {
1758 log_debug("%s got notified about service death.", s->meta.id);
1759 socket_enter_listening(s);
1763 void socket_connection_unref(Socket *s) {
1766 /* The service is dead. Yay!
1768 * This is strictly for one-onstance-per-connection
1771 assert(s->n_connections > 0);
1774 log_debug("%s: One connection closed, %u left.", s->meta.id, s->n_connections);
1777 static void socket_reset_maintenance(Unit *u) {
1778 Socket *s = SOCKET(u);
1782 if (s->state == SOCKET_MAINTENANCE)
1783 socket_set_state(s, SOCKET_DEAD);
1788 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
1789 [SOCKET_DEAD] = "dead",
1790 [SOCKET_START_PRE] = "start-pre",
1791 [SOCKET_START_POST] = "start-post",
1792 [SOCKET_LISTENING] = "listening",
1793 [SOCKET_RUNNING] = "running",
1794 [SOCKET_STOP_PRE] = "stop-pre",
1795 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
1796 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
1797 [SOCKET_STOP_POST] = "stop-post",
1798 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
1799 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
1800 [SOCKET_MAINTENANCE] = "maintenance"
1803 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
1805 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
1806 [SOCKET_EXEC_START_PRE] = "StartPre",
1807 [SOCKET_EXEC_START_POST] = "StartPost",
1808 [SOCKET_EXEC_STOP_PRE] = "StopPre",
1809 [SOCKET_EXEC_STOP_POST] = "StopPost"
1812 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
1814 const UnitVTable socket_vtable = {
1815 .suffix = ".socket",
1817 .init = socket_init,
1818 .done = socket_done,
1819 .load = socket_load,
1821 .coldplug = socket_coldplug,
1823 .dump = socket_dump,
1825 .start = socket_start,
1826 .stop = socket_stop,
1828 .serialize = socket_serialize,
1829 .deserialize_item = socket_deserialize_item,
1831 .active_state = socket_active_state,
1832 .sub_state_to_string = socket_sub_state_to_string,
1834 .check_gc = socket_check_gc,
1836 .fd_event = socket_fd_event,
1837 .sigchld_event = socket_sigchld_event,
1838 .timer_event = socket_timer_event,
1840 .reset_maintenance = socket_reset_maintenance,
1842 .bus_message_handler = bus_socket_message_handler