1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
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>
33 #include "netinet/tcp.h"
35 #include "load-dropin.h"
36 #include "load-fragment.h"
38 #include "unit-name.h"
39 #include "dbus-socket.h"
42 #include "bus-errors.h"
44 #include "exit-status.h"
46 static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
47 [SOCKET_DEAD] = UNIT_INACTIVE,
48 [SOCKET_START_PRE] = UNIT_ACTIVATING,
49 [SOCKET_START_POST] = UNIT_ACTIVATING,
50 [SOCKET_LISTENING] = UNIT_ACTIVE,
51 [SOCKET_RUNNING] = UNIT_ACTIVE,
52 [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
53 [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
54 [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
55 [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
56 [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
57 [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
58 [SOCKET_FAILED] = UNIT_FAILED
61 static void socket_init(Unit *u) {
62 Socket *s = SOCKET(u);
65 assert(u->meta.load_state == UNIT_STUB);
67 s->backlog = SOMAXCONN;
68 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
69 s->directory_mode = 0755;
70 s->socket_mode = 0666;
72 s->max_connections = 64;
79 exec_context_init(&s->exec_context);
80 s->exec_context.std_output = u->meta.manager->default_std_output;
81 s->exec_context.std_error = u->meta.manager->default_std_error;
83 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
86 static void socket_unwatch_control_pid(Socket *s) {
89 if (s->control_pid <= 0)
92 unit_unwatch_pid(UNIT(s), s->control_pid);
96 static void socket_done(Unit *u) {
97 Socket *s = SOCKET(u);
103 while ((p = s->ports)) {
104 LIST_REMOVE(SocketPort, port, s->ports, p);
107 unit_unwatch_fd(UNIT(s), &p->fd_watch);
108 close_nointr_nofail(p->fd);
115 exec_context_done(&s->exec_context);
116 exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
117 s->control_command = NULL;
119 socket_unwatch_control_pid(s);
123 free(s->tcp_congestion);
124 s->tcp_congestion = NULL;
126 free(s->bind_to_device);
127 s->bind_to_device = NULL;
129 unit_unwatch_timer(u, &s->timer_watch);
131 /* Make sure no service instance refers to us anymore. */
132 LIST_FOREACH(units_per_type, i, u->meta.manager->units_per_type[UNIT_SERVICE]) {
133 Service *service = (Service *) i;
135 if (service->accept_socket == s)
136 service->accept_socket = NULL;
138 set_remove(service->configured_sockets, s);
142 static int socket_instantiate_service(Socket *s) {
149 /* This fills in s->service if it isn't filled in yet. For
150 * Accept=yes sockets we create the next connection service
151 * here. For Accept=no this is mostly a NOP since the service
152 * is figured out at load time anyway. */
159 if (!(prefix = unit_name_to_prefix(s->meta.id)))
162 r = asprintf(&name, "%s@%u.service", prefix, s->n_accepted);
168 r = manager_load_unit(s->meta.manager, name, NULL, NULL, &u);
174 #ifdef HAVE_SYSV_COMPAT
175 if (SERVICE(u)->sysv_path) {
176 log_error("Using SysV services for socket activation is not supported. Refusing.");
181 u->meta.no_gc = true;
182 s->service = SERVICE(u);
186 static bool have_non_accept_socket(Socket *s) {
194 LIST_FOREACH(port, p, s->ports) {
196 if (p->type != SOCKET_SOCKET)
199 if (!socket_address_can_accept(&p->address))
206 static int socket_verify(Socket *s) {
209 if (s->meta.load_state != UNIT_LOADED)
213 log_error("%s lacks Listen setting. Refusing.", s->meta.id);
217 if (s->accept && have_non_accept_socket(s)) {
218 log_error("%s configured for accepting sockets, but sockets are non-accepting. Refusing.", s->meta.id);
222 if (s->accept && s->max_connections <= 0) {
223 log_error("%s's MaxConnection setting too small. Refusing.", s->meta.id);
227 if (s->accept && s->service) {
228 log_error("Explicit service configuration for accepting sockets not supported on %s. Refusing.", s->meta.id);
232 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
233 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
240 static bool socket_needs_mount(Socket *s, const char *prefix) {
245 LIST_FOREACH(port, p, s->ports) {
247 if (p->type == SOCKET_SOCKET) {
248 if (socket_address_needs_mount(&p->address, prefix))
251 assert(p->type == SOCKET_FIFO);
252 if (path_startswith(p->path, prefix))
260 int socket_add_one_mount_link(Socket *s, Mount *m) {
266 if (s->meta.load_state != UNIT_LOADED ||
267 m->meta.load_state != UNIT_LOADED)
270 if (!socket_needs_mount(s, m->where))
273 if ((r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
279 static int socket_add_mount_links(Socket *s) {
285 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_MOUNT])
286 if ((r = socket_add_one_mount_link(s, (Mount*) other)) < 0)
292 static int socket_add_device_link(Socket *s) {
298 if (!s->bind_to_device)
301 if (asprintf(&t, "/sys/subsystem/net/devices/%s", s->bind_to_device) < 0)
304 r = unit_add_node_link(UNIT(s), t, false);
310 static int socket_add_default_dependencies(Socket *s) {
314 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
315 if ((r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
318 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 0)
322 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
325 static int socket_load(Unit *u) {
326 Socket *s = SOCKET(u);
330 assert(u->meta.load_state == UNIT_STUB);
332 if ((r = unit_load_fragment_and_dropin(u)) < 0)
335 /* This is a new unit? Then let's add in some extras */
336 if (u->meta.load_state == UNIT_LOADED) {
338 if (have_non_accept_socket(s)) {
341 if ((r = unit_load_related_unit(u, ".service", (Unit**) &s->service)) < 0)
344 if ((r = unit_add_dependency(u, UNIT_BEFORE, UNIT(s->service), true)) < 0)
348 if ((r = socket_add_mount_links(s)) < 0)
351 if ((r = socket_add_device_link(s)) < 0)
354 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
357 if ((r = unit_add_default_cgroups(u)) < 0)
360 if (s->meta.default_dependencies)
361 if ((r = socket_add_default_dependencies(s)) < 0)
365 return socket_verify(s);
368 static const char* listen_lookup(int type) {
370 if (type == SOCK_STREAM)
371 return "ListenStream";
372 else if (type == SOCK_DGRAM)
373 return "ListenDatagram";
374 else if (type == SOCK_SEQPACKET)
375 return "ListenSequentialPacket";
377 assert_not_reached("Unknown socket type");
381 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
384 Socket *s = SOCKET(u);
392 p2 = strappend(prefix, "\t");
393 prefix2 = p2 ? p2 : prefix;
396 "%sSocket State: %s\n"
397 "%sBindIPv6Only: %s\n"
399 "%sSocketMode: %04o\n"
400 "%sDirectoryMode: %04o\n"
403 "%sTCPCongestion: %s\n",
404 prefix, socket_state_to_string(s->state),
405 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
407 prefix, s->socket_mode,
408 prefix, s->directory_mode,
409 prefix, yes_no(s->keep_alive),
410 prefix, yes_no(s->free_bind),
411 prefix, strna(s->tcp_congestion));
413 if (s->control_pid > 0)
415 "%sControl PID: %lu\n",
416 prefix, (unsigned long) s->control_pid);
418 if (s->bind_to_device)
420 "%sBindToDevice: %s\n",
421 prefix, s->bind_to_device);
426 "%sNConnections: %u\n"
427 "%sMaxConnections: %u\n",
428 prefix, s->n_accepted,
429 prefix, s->n_connections,
430 prefix, s->max_connections);
432 if (s->priority >= 0)
435 prefix, s->priority);
437 if (s->receive_buffer > 0)
439 "%sReceiveBuffer: %zu\n",
440 prefix, s->receive_buffer);
442 if (s->send_buffer > 0)
444 "%sSendBuffer: %zu\n",
445 prefix, s->send_buffer);
457 if (s->pipe_size > 0)
460 prefix, s->pipe_size);
467 LIST_FOREACH(port, p, s->ports) {
469 if (p->type == SOCKET_SOCKET) {
474 if ((r = socket_address_print(&p->address, &k)) < 0)
479 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(p->address.type), t);
482 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
485 exec_context_dump(&s->exec_context, f, prefix);
487 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
488 if (!s->exec_command[c])
491 fprintf(f, "%s-> %s:\n",
492 prefix, socket_exec_command_to_string(c));
494 exec_command_dump_list(s->exec_command[c], f, prefix2);
500 static int instance_from_socket(int fd, unsigned nr, char **instance) {
505 struct sockaddr_un un;
506 struct sockaddr_in in;
507 struct sockaddr_in6 in6;
508 struct sockaddr_storage storage;
515 if (getsockname(fd, &local.sa, &l) < 0)
519 if (getpeername(fd, &remote.sa, &l) < 0)
522 switch (local.sa.sa_family) {
526 a = ntohl(local.in.sin_addr.s_addr),
527 b = ntohl(remote.in.sin_addr.s_addr);
530 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
531 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
532 ntohs(local.in.sin_port),
533 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
534 ntohs(remote.in.sin_port)) < 0)
541 static const char ipv4_prefix[] = {
542 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
545 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
546 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
548 *a = local.in6.sin6_addr.s6_addr+12,
549 *b = remote.in6.sin6_addr.s6_addr+12;
552 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
553 a[0], a[1], a[2], a[3],
554 ntohs(local.in6.sin6_port),
555 b[0], b[1], b[2], b[3],
556 ntohs(remote.in6.sin6_port)) < 0)
559 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
563 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
564 ntohs(local.in6.sin6_port),
565 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
566 ntohs(remote.in6.sin6_port)) < 0)
577 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
583 (unsigned long) ucred.pid,
584 (unsigned long) ucred.uid) < 0)
591 assert_not_reached("Unhandled socket type.");
598 static void socket_close_fds(Socket *s) {
603 LIST_FOREACH(port, p, s->ports) {
607 unit_unwatch_fd(UNIT(s), &p->fd_watch);
608 close_nointr_nofail(p->fd);
610 /* One little note: we should never delete any sockets
611 * in the file system here! After all some other
612 * process we spawned might still have a reference of
613 * this fd and wants to continue to use it. Therefore
614 * we delete sockets in the file system before we
615 * create a new one, not after we stopped using
622 static void socket_apply_socket_options(Socket *s, int fd) {
627 int b = s->keep_alive;
628 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
629 log_warning("SO_KEEPALIVE failed: %m");
632 if (s->priority >= 0)
633 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
634 log_warning("SO_PRIORITY failed: %m");
636 if (s->receive_buffer > 0) {
637 int value = (int) s->receive_buffer;
638 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
639 log_warning("SO_RCVBUF failed: %m");
642 if (s->send_buffer > 0) {
643 int value = (int) s->send_buffer;
644 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
645 log_warning("SO_SNDBUF failed: %m");
649 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
650 log_warning("SO_MARK failed: %m");
653 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
654 log_warning("IP_TOS failed: %m");
656 if (s->ip_ttl >= 0) {
659 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
661 if (socket_ipv6_is_supported())
662 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
665 errno = EAFNOSUPPORT;
669 log_warning("IP_TTL/IPV6_UNICAST_HOPS failed: %m");
672 if (s->tcp_congestion)
673 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
674 log_warning("TCP_CONGESTION failed: %m");
677 static void socket_apply_fifo_options(Socket *s, int fd) {
681 if (s->pipe_size > 0)
682 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
683 log_warning("F_SETPIPE_SZ: %m");
687 static int fifo_address_create(
689 mode_t directory_mode,
700 mkdir_parents(path, directory_mode);
702 if ((r = label_fifofile_set(path)) < 0)
705 /* Enforce the right access mode for the fifo */
706 old_mask = umask(~ socket_mode);
708 /* Include the original umask in our mask */
709 umask(~socket_mode | old_mask);
711 r = mkfifo(path, socket_mode);
719 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
726 if (fstat(fd, &st) < 0) {
731 if (!S_ISFIFO(st.st_mode) ||
732 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
733 st.st_uid != getuid() ||
734 st.st_gid != getgid()) {
747 close_nointr_nofail(fd);
752 static int socket_open_fds(Socket *s) {
756 bool know_label = false;
760 LIST_FOREACH(port, p, s->ports) {
765 if (p->type == SOCKET_SOCKET) {
769 if ((r = socket_instantiate_service(s)) < 0)
772 if (s->service && s->service->exec_command[SERVICE_EXEC_START])
773 if ((r = label_get_socket_label_from_exe(s->service->exec_command[SERVICE_EXEC_START]->path, &label)) < 0)
779 if ((r = socket_address_listen(
791 socket_apply_socket_options(s, p->fd);
793 } else if (p->type == SOCKET_FIFO) {
795 if ((r = fifo_address_create(
802 socket_apply_fifo_options(s, p->fd);
805 assert_not_reached("Unknown port type");
817 static void socket_unwatch_fds(Socket *s) {
822 LIST_FOREACH(port, p, s->ports) {
826 unit_unwatch_fd(UNIT(s), &p->fd_watch);
830 static int socket_watch_fds(Socket *s) {
836 LIST_FOREACH(port, p, s->ports) {
840 p->fd_watch.socket_accept =
842 p->type == SOCKET_SOCKET &&
843 socket_address_can_accept(&p->address);
845 if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
852 socket_unwatch_fds(s);
856 static void socket_set_state(Socket *s, SocketState state) {
857 SocketState old_state;
860 old_state = s->state;
863 if (state != SOCKET_START_PRE &&
864 state != SOCKET_START_POST &&
865 state != SOCKET_STOP_PRE &&
866 state != SOCKET_STOP_PRE_SIGTERM &&
867 state != SOCKET_STOP_PRE_SIGKILL &&
868 state != SOCKET_STOP_POST &&
869 state != SOCKET_FINAL_SIGTERM &&
870 state != SOCKET_FINAL_SIGKILL) {
871 unit_unwatch_timer(UNIT(s), &s->timer_watch);
872 socket_unwatch_control_pid(s);
873 s->control_command = NULL;
874 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
877 if (state != SOCKET_LISTENING)
878 socket_unwatch_fds(s);
880 if (state != SOCKET_START_POST &&
881 state != SOCKET_LISTENING &&
882 state != SOCKET_RUNNING &&
883 state != SOCKET_STOP_PRE &&
884 state != SOCKET_STOP_PRE_SIGTERM &&
885 state != SOCKET_STOP_PRE_SIGKILL)
888 if (state != old_state)
889 log_debug("%s changed %s -> %s",
891 socket_state_to_string(old_state),
892 socket_state_to_string(state));
894 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
897 static int socket_coldplug(Unit *u) {
898 Socket *s = SOCKET(u);
902 assert(s->state == SOCKET_DEAD);
904 if (s->deserialized_state != s->state) {
906 if (s->deserialized_state == SOCKET_START_PRE ||
907 s->deserialized_state == SOCKET_START_POST ||
908 s->deserialized_state == SOCKET_STOP_PRE ||
909 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
910 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
911 s->deserialized_state == SOCKET_STOP_POST ||
912 s->deserialized_state == SOCKET_FINAL_SIGTERM ||
913 s->deserialized_state == SOCKET_FINAL_SIGKILL) {
915 if (s->control_pid <= 0)
918 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
921 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
925 if (s->deserialized_state == SOCKET_START_POST ||
926 s->deserialized_state == SOCKET_LISTENING ||
927 s->deserialized_state == SOCKET_RUNNING ||
928 s->deserialized_state == SOCKET_STOP_PRE ||
929 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
930 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
931 if ((r = socket_open_fds(s)) < 0)
934 if (s->deserialized_state == SOCKET_LISTENING)
935 if ((r = socket_watch_fds(s)) < 0)
938 socket_set_state(s, s->deserialized_state);
944 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
953 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
956 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
965 s->meta.manager->environment,
969 s->meta.manager->confirm_spawn,
970 s->meta.cgroup_bondings,
977 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
978 /* FIXME: we need to do something here */
986 unit_unwatch_timer(UNIT(s), &s->timer_watch);
991 static void socket_enter_dead(Socket *s, bool success) {
997 socket_set_state(s, s->failure ? SOCKET_FAILED : SOCKET_DEAD);
1000 static void socket_enter_signal(Socket *s, SocketState state, bool success);
1002 static void socket_enter_stop_post(Socket *s, bool success) {
1009 socket_unwatch_control_pid(s);
1011 s->control_command_id = SOCKET_EXEC_STOP_POST;
1013 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
1014 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1017 socket_set_state(s, SOCKET_STOP_POST);
1019 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, true);
1024 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1025 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1028 static void socket_enter_signal(Socket *s, SocketState state, bool success) {
1030 Set *pid_set = NULL;
1031 bool wait_for_exit = false;
1038 if (s->exec_context.kill_mode != KILL_NONE) {
1039 int sig = (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1041 if (s->control_pid > 0) {
1042 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1044 s->control_pid, sig) < 0 && errno != ESRCH)
1046 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1048 wait_for_exit = true;
1051 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1053 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1058 /* Exclude the control pid from being killed via the cgroup */
1059 if (s->control_pid > 0)
1060 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1063 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1064 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1065 log_warning("Failed to kill control group: %s", strerror(-r));
1067 wait_for_exit = true;
1073 if (wait_for_exit) {
1074 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1077 socket_set_state(s, state);
1078 } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1079 socket_enter_stop_post(s, true);
1081 socket_enter_dead(s, true);
1086 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1088 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1089 socket_enter_stop_post(s, false);
1091 socket_enter_dead(s, false);
1097 static void socket_enter_stop_pre(Socket *s, bool success) {
1104 socket_unwatch_control_pid(s);
1106 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1108 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
1109 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1112 socket_set_state(s, SOCKET_STOP_PRE);
1114 socket_enter_stop_post(s, true);
1119 log_warning("%s failed to run 'stop-pre' task: %s", s->meta.id, strerror(-r));
1120 socket_enter_stop_post(s, false);
1123 static void socket_enter_listening(Socket *s) {
1127 if ((r = socket_watch_fds(s)) < 0) {
1128 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1132 socket_set_state(s, SOCKET_LISTENING);
1136 socket_enter_stop_pre(s, false);
1139 static void socket_enter_start_post(Socket *s) {
1143 if ((r = socket_open_fds(s)) < 0) {
1144 log_warning("%s failed to listen on sockets: %s", s->meta.id, strerror(-r));
1148 socket_unwatch_control_pid(s);
1150 s->control_command_id = SOCKET_EXEC_START_POST;
1152 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
1153 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0) {
1154 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1158 socket_set_state(s, SOCKET_START_POST);
1160 socket_enter_listening(s);
1165 socket_enter_stop_pre(s, false);
1168 static void socket_enter_start_pre(Socket *s) {
1172 socket_unwatch_control_pid(s);
1174 s->control_command_id = SOCKET_EXEC_START_PRE;
1176 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
1177 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1180 socket_set_state(s, SOCKET_START_PRE);
1182 socket_enter_start_post(s);
1187 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1188 socket_enter_dead(s, false);
1191 static void socket_enter_running(Socket *s, int cfd) {
1196 dbus_error_init(&error);
1198 /* We don't take connections anymore if we are supposed to
1199 * shut down anyway */
1200 if (unit_pending_inactive(UNIT(s))) {
1201 log_debug("Suppressing connection request on %s since unit stop is scheduled.", s->meta.id);
1204 close_nointr_nofail(cfd);
1206 /* Flush all sockets by closing and reopening them */
1207 socket_close_fds(s);
1209 if ((r = socket_watch_fds(s)) < 0) {
1210 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1211 socket_enter_stop_pre(s, false);
1219 bool pending = false;
1222 /* If there's already a start pending don't bother to
1224 LIST_FOREACH(units_per_type, i, s->meta.manager->units_per_type[UNIT_SERVICE]) {
1225 Service *service = (Service *) i;
1227 if (!set_get(service->configured_sockets, s))
1230 if (!unit_pending_active(UNIT(service)))
1238 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s->service), JOB_REPLACE, true, &error, NULL)) < 0)
1241 socket_set_state(s, SOCKET_RUNNING);
1243 char *prefix, *instance = NULL, *name;
1246 if (s->n_connections >= s->max_connections) {
1247 log_warning("Too many incoming connections (%u)", s->n_connections);
1248 close_nointr_nofail(cfd);
1252 if ((r = socket_instantiate_service(s)) < 0)
1255 if ((r = instance_from_socket(cfd, s->n_accepted, &instance)) < 0)
1258 if (!(prefix = unit_name_to_prefix(s->meta.id))) {
1264 name = unit_name_build(prefix, instance, ".service");
1273 if ((r = unit_add_name(UNIT(s->service), name)) < 0) {
1278 service = s->service;
1282 service->meta.no_gc = false;
1284 unit_choose_id(UNIT(service), name);
1287 if ((r = service_set_socket_fd(service, cfd, s)) < 0)
1291 s->n_connections ++;
1293 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL)) < 0)
1296 /* Notify clients about changed counters */
1297 unit_add_to_dbus_queue(UNIT(s));
1303 log_warning("%s failed to queue socket startup job: %s", s->meta.id, bus_error(&error, r));
1304 socket_enter_stop_pre(s, false);
1307 close_nointr_nofail(cfd);
1309 dbus_error_free(&error);
1312 static void socket_run_next(Socket *s, bool success) {
1316 assert(s->control_command);
1317 assert(s->control_command->command_next);
1322 socket_unwatch_control_pid(s);
1324 s->control_command = s->control_command->command_next;
1326 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1332 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1334 if (s->state == SOCKET_START_POST)
1335 socket_enter_stop_pre(s, false);
1336 else if (s->state == SOCKET_STOP_POST)
1337 socket_enter_dead(s, false);
1339 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1342 static int socket_start(Unit *u) {
1343 Socket *s = SOCKET(u);
1347 /* We cannot fulfill this request right now, try again later
1349 if (s->state == SOCKET_STOP_PRE ||
1350 s->state == SOCKET_STOP_PRE_SIGKILL ||
1351 s->state == SOCKET_STOP_PRE_SIGTERM ||
1352 s->state == SOCKET_STOP_POST ||
1353 s->state == SOCKET_FINAL_SIGTERM ||
1354 s->state == SOCKET_FINAL_SIGKILL)
1357 if (s->state == SOCKET_START_PRE ||
1358 s->state == SOCKET_START_POST)
1361 /* Cannot run this without the service being around */
1363 if (s->service->meta.load_state != UNIT_LOADED)
1366 /* If the service is alredy active we cannot start the
1368 if (s->service->state != SERVICE_DEAD &&
1369 s->service->state != SERVICE_FAILED &&
1370 s->service->state != SERVICE_AUTO_RESTART)
1373 #ifdef HAVE_SYSV_COMPAT
1374 if (s->service->sysv_path) {
1375 log_error("Using SysV services for socket activation is not supported. Refusing.");
1381 assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1384 socket_enter_start_pre(s);
1388 static int socket_stop(Unit *u) {
1389 Socket *s = SOCKET(u);
1394 if (s->state == SOCKET_STOP_PRE ||
1395 s->state == SOCKET_STOP_PRE_SIGTERM ||
1396 s->state == SOCKET_STOP_PRE_SIGKILL ||
1397 s->state == SOCKET_STOP_POST ||
1398 s->state == SOCKET_FINAL_SIGTERM ||
1399 s->state == SOCKET_FINAL_SIGKILL)
1402 /* If there's already something running we go directly into
1404 if (s->state == SOCKET_START_PRE ||
1405 s->state == SOCKET_START_POST) {
1406 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, true);
1410 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1412 socket_enter_stop_pre(s, true);
1416 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1417 Socket *s = SOCKET(u);
1425 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1426 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1427 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1429 if (s->control_pid > 0)
1430 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1432 if (s->control_command_id >= 0)
1433 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1435 LIST_FOREACH(port, p, s->ports) {
1441 if ((copy = fdset_put_dup(fds, p->fd)) < 0)
1444 if (p->type == SOCKET_SOCKET) {
1447 if ((r = socket_address_print(&p->address, &t)) < 0)
1450 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1453 assert(p->type == SOCKET_FIFO);
1454 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1461 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1462 Socket *s = SOCKET(u);
1469 if (streq(key, "state")) {
1472 if ((state = socket_state_from_string(value)) < 0)
1473 log_debug("Failed to parse state value %s", value);
1475 s->deserialized_state = state;
1476 } else if (streq(key, "failure")) {
1479 if ((b = parse_boolean(value)) < 0)
1480 log_debug("Failed to parse failure value %s", value);
1482 s->failure = b || s->failure;
1484 } else if (streq(key, "n-accepted")) {
1487 if (safe_atou(value, &k) < 0)
1488 log_debug("Failed to parse n-accepted value %s", value);
1491 } else if (streq(key, "control-pid")) {
1494 if (parse_pid(value, &pid) < 0)
1495 log_debug("Failed to parse control-pid value %s", value);
1497 s->control_pid = pid;
1498 } else if (streq(key, "control-command")) {
1499 SocketExecCommand id;
1501 if ((id = socket_exec_command_from_string(value)) < 0)
1502 log_debug("Failed to parse exec-command value %s", value);
1504 s->control_command_id = id;
1505 s->control_command = s->exec_command[id];
1507 } else if (streq(key, "fifo")) {
1511 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1512 log_debug("Failed to parse fifo value %s", value);
1515 LIST_FOREACH(port, p, s->ports)
1516 if (streq(p->path, value+skip))
1521 close_nointr_nofail(p->fd);
1522 p->fd = fdset_remove(fds, fd);
1526 } else if (streq(key, "socket")) {
1527 int fd, type, skip = 0;
1530 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
1531 log_debug("Failed to parse socket value %s", value);
1534 LIST_FOREACH(port, p, s->ports)
1535 if (socket_address_is(&p->address, value+skip, type))
1540 close_nointr_nofail(p->fd);
1541 p->fd = fdset_remove(fds, fd);
1546 log_debug("Unknown serialization key '%s'", key);
1551 static UnitActiveState socket_active_state(Unit *u) {
1554 return state_translation_table[SOCKET(u)->state];
1557 static const char *socket_sub_state_to_string(Unit *u) {
1560 return socket_state_to_string(SOCKET(u)->state);
1563 static bool socket_check_gc(Unit *u) {
1564 Socket *s = SOCKET(u);
1568 return s->n_connections > 0;
1571 static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
1572 Socket *s = SOCKET(u);
1578 if (s->state != SOCKET_LISTENING)
1581 log_debug("Incoming traffic on %s", u->meta.id);
1583 if (events != EPOLLIN) {
1584 log_error("Got invalid poll event on socket.");
1588 if (w->socket_accept) {
1591 if ((cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK)) < 0) {
1596 log_error("Failed to accept socket: %m");
1603 socket_apply_socket_options(s, cfd);
1606 socket_enter_running(s, cfd);
1610 socket_enter_stop_pre(s, false);
1613 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1614 Socket *s = SOCKET(u);
1620 if (pid != s->control_pid)
1625 success = is_clean_exit(code, status);
1627 if (s->control_command) {
1628 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
1630 if (s->control_command->ignore)
1634 log_full(success ? LOG_DEBUG : LOG_NOTICE,
1635 "%s control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1636 s->failure = s->failure || !success;
1638 if (s->control_command && s->control_command->command_next && success) {
1639 log_debug("%s running next command for state %s", u->meta.id, socket_state_to_string(s->state));
1640 socket_run_next(s, success);
1642 s->control_command = NULL;
1643 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1645 /* No further commands for this step, so let's figure
1646 * out what to do next */
1648 log_debug("%s got final SIGCHLD for state %s", u->meta.id, socket_state_to_string(s->state));
1652 case SOCKET_START_PRE:
1654 socket_enter_start_post(s);
1656 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1659 case SOCKET_START_POST:
1661 socket_enter_listening(s);
1663 socket_enter_stop_pre(s, false);
1666 case SOCKET_STOP_PRE:
1667 case SOCKET_STOP_PRE_SIGTERM:
1668 case SOCKET_STOP_PRE_SIGKILL:
1669 socket_enter_stop_post(s, success);
1672 case SOCKET_STOP_POST:
1673 case SOCKET_FINAL_SIGTERM:
1674 case SOCKET_FINAL_SIGKILL:
1675 socket_enter_dead(s, success);
1679 assert_not_reached("Uh, control process died at wrong time.");
1683 /* Notify clients about changed exit status */
1684 unit_add_to_dbus_queue(u);
1687 static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
1688 Socket *s = SOCKET(u);
1691 assert(elapsed == 1);
1692 assert(w == &s->timer_watch);
1696 case SOCKET_START_PRE:
1697 log_warning("%s starting timed out. Terminating.", u->meta.id);
1698 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1700 case SOCKET_START_POST:
1701 log_warning("%s starting timed out. Stopping.", u->meta.id);
1702 socket_enter_stop_pre(s, false);
1705 case SOCKET_STOP_PRE:
1706 log_warning("%s stopping timed out. Terminating.", u->meta.id);
1707 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, false);
1710 case SOCKET_STOP_PRE_SIGTERM:
1711 if (s->exec_context.send_sigkill) {
1712 log_warning("%s stopping timed out. Killing.", u->meta.id);
1713 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, false);
1715 log_warning("%s stopping timed out. Skipping SIGKILL. Ignoring.", u->meta.id);
1716 socket_enter_stop_post(s, false);
1720 case SOCKET_STOP_PRE_SIGKILL:
1721 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
1722 socket_enter_stop_post(s, false);
1725 case SOCKET_STOP_POST:
1726 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
1727 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1730 case SOCKET_FINAL_SIGTERM:
1731 if (s->exec_context.send_sigkill) {
1732 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
1733 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, false);
1735 log_warning("%s stopping timed out (2). Skipping SIGKILL. Ignoring.", u->meta.id);
1736 socket_enter_dead(s, false);
1740 case SOCKET_FINAL_SIGKILL:
1741 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
1742 socket_enter_dead(s, false);
1746 assert_not_reached("Timeout at wrong time.");
1750 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
1759 /* Called from the service code for requesting our fds */
1762 LIST_FOREACH(port, p, s->ports)
1766 if (!(rfds = new(int, rn_fds)))
1770 LIST_FOREACH(port, p, s->ports)
1774 assert(k == rn_fds);
1782 void socket_notify_service_dead(Socket *s) {
1785 /* The service is dead. Dang!
1787 * This is strictly for one-instance-for-all-connections
1790 if (s->state == SOCKET_RUNNING) {
1791 log_debug("%s got notified about service death.", s->meta.id);
1792 socket_enter_listening(s);
1796 void socket_connection_unref(Socket *s) {
1799 /* The service is dead. Yay!
1801 * This is strictly for one-onstance-per-connection
1804 assert(s->n_connections > 0);
1807 log_debug("%s: One connection closed, %u left.", s->meta.id, s->n_connections);
1810 static void socket_reset_failed(Unit *u) {
1811 Socket *s = SOCKET(u);
1815 if (s->state == SOCKET_FAILED)
1816 socket_set_state(s, SOCKET_DEAD);
1821 static int socket_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
1822 Socket *s = SOCKET(u);
1824 Set *pid_set = NULL;
1828 if (who == KILL_MAIN) {
1829 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "Socket units have no main processes");
1833 if (s->control_pid <= 0 && who == KILL_CONTROL) {
1834 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
1838 if (s->control_pid > 0)
1839 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
1842 if (mode == KILL_CONTROL_GROUP) {
1845 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
1848 /* Exclude the control pid from being killed via the cgroup */
1849 if (s->control_pid > 0)
1850 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
1855 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
1856 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1867 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
1868 [SOCKET_DEAD] = "dead",
1869 [SOCKET_START_PRE] = "start-pre",
1870 [SOCKET_START_POST] = "start-post",
1871 [SOCKET_LISTENING] = "listening",
1872 [SOCKET_RUNNING] = "running",
1873 [SOCKET_STOP_PRE] = "stop-pre",
1874 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
1875 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
1876 [SOCKET_STOP_POST] = "stop-post",
1877 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
1878 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
1879 [SOCKET_FAILED] = "failed"
1882 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
1884 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
1885 [SOCKET_EXEC_START_PRE] = "StartPre",
1886 [SOCKET_EXEC_START_POST] = "StartPost",
1887 [SOCKET_EXEC_STOP_PRE] = "StopPre",
1888 [SOCKET_EXEC_STOP_POST] = "StopPost"
1891 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
1893 const UnitVTable socket_vtable = {
1894 .suffix = ".socket",
1896 .init = socket_init,
1897 .done = socket_done,
1898 .load = socket_load,
1900 .kill = socket_kill,
1902 .coldplug = socket_coldplug,
1904 .dump = socket_dump,
1906 .start = socket_start,
1907 .stop = socket_stop,
1909 .serialize = socket_serialize,
1910 .deserialize_item = socket_deserialize_item,
1912 .active_state = socket_active_state,
1913 .sub_state_to_string = socket_sub_state_to_string,
1915 .check_gc = socket_check_gc,
1917 .fd_event = socket_fd_event,
1918 .sigchld_event = socket_sigchld_event,
1919 .timer_event = socket_timer_event,
1921 .reset_failed = socket_reset_failed,
1923 .bus_interface = "org.freedesktop.systemd1.Socket",
1924 .bus_message_handler = bus_socket_message_handler,
1925 .bus_invalidating_properties = bus_socket_invalidating_properties