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);
81 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
84 static void socket_unwatch_control_pid(Socket *s) {
87 if (s->control_pid <= 0)
90 unit_unwatch_pid(UNIT(s), s->control_pid);
94 static void socket_done(Unit *u) {
95 Socket *s = SOCKET(u);
101 while ((p = s->ports)) {
102 LIST_REMOVE(SocketPort, port, s->ports, p);
105 unit_unwatch_fd(UNIT(s), &p->fd_watch);
106 close_nointr_nofail(p->fd);
113 exec_context_done(&s->exec_context);
114 exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
115 s->control_command = NULL;
117 socket_unwatch_control_pid(s);
121 free(s->tcp_congestion);
122 s->tcp_congestion = NULL;
124 free(s->bind_to_device);
125 s->bind_to_device = NULL;
127 unit_unwatch_timer(u, &s->timer_watch);
129 /* Make sure no service instance refers to us anymore. */
130 LIST_FOREACH(units_per_type, i, u->meta.manager->units_per_type[UNIT_SERVICE]) {
131 Service *service = (Service *) i;
133 if (service->accept_socket == s)
134 service->accept_socket = NULL;
136 set_remove(service->configured_sockets, s);
140 static int socket_instantiate_service(Socket *s) {
147 /* This fills in s->service if it isn't filled in yet. For
148 * Accept=yes sockets we create the next connection service
149 * here. For Accept=no this is mostly a NOP since the service
150 * is figured out at load time anyway. */
157 if (!(prefix = unit_name_to_prefix(s->meta.id)))
160 r = asprintf(&name, "%s@%u.service", prefix, s->n_accepted);
166 r = manager_load_unit(s->meta.manager, name, NULL, NULL, &u);
172 #ifdef HAVE_SYSV_COMPAT
173 if (SERVICE(u)->sysv_path) {
174 log_error("Using SysV services for socket activation is not supported. Refusing.");
179 u->meta.no_gc = true;
180 s->service = SERVICE(u);
184 static bool have_non_accept_socket(Socket *s) {
192 LIST_FOREACH(port, p, s->ports) {
194 if (p->type != SOCKET_SOCKET)
197 if (!socket_address_can_accept(&p->address))
204 static int socket_verify(Socket *s) {
207 if (s->meta.load_state != UNIT_LOADED)
211 log_error("%s lacks Listen setting. Refusing.", s->meta.id);
215 if (s->accept && have_non_accept_socket(s)) {
216 log_error("%s configured for accepting sockets, but sockets are non-accepting. Refusing.", s->meta.id);
220 if (s->accept && s->max_connections <= 0) {
221 log_error("%s's MaxConnection setting too small. Refusing.", s->meta.id);
225 if (s->accept && s->service) {
226 log_error("Explicit service configuration for accepting sockets not supported on %s. Refusing.", s->meta.id);
230 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
231 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
238 static bool socket_needs_mount(Socket *s, const char *prefix) {
243 LIST_FOREACH(port, p, s->ports) {
245 if (p->type == SOCKET_SOCKET) {
246 if (socket_address_needs_mount(&p->address, prefix))
249 assert(p->type == SOCKET_FIFO);
250 if (path_startswith(p->path, prefix))
258 int socket_add_one_mount_link(Socket *s, Mount *m) {
264 if (s->meta.load_state != UNIT_LOADED ||
265 m->meta.load_state != UNIT_LOADED)
268 if (!socket_needs_mount(s, m->where))
271 if ((r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
277 static int socket_add_mount_links(Socket *s) {
283 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_MOUNT])
284 if ((r = socket_add_one_mount_link(s, (Mount*) other)) < 0)
290 static int socket_add_device_link(Socket *s) {
296 if (!s->bind_to_device)
299 if (asprintf(&t, "/sys/subsystem/net/devices/%s", s->bind_to_device) < 0)
302 r = unit_add_node_link(UNIT(s), t, false);
308 static int socket_add_default_dependencies(Socket *s) {
312 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
313 if ((r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
316 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 0)
320 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
323 static int socket_load(Unit *u) {
324 Socket *s = SOCKET(u);
328 assert(u->meta.load_state == UNIT_STUB);
330 if ((r = unit_load_fragment_and_dropin(u)) < 0)
333 /* This is a new unit? Then let's add in some extras */
334 if (u->meta.load_state == UNIT_LOADED) {
336 if (have_non_accept_socket(s)) {
339 if ((r = unit_load_related_unit(u, ".service", (Unit**) &s->service)) < 0)
342 if ((r = unit_add_dependency(u, UNIT_BEFORE, UNIT(s->service), true)) < 0)
346 if ((r = socket_add_mount_links(s)) < 0)
349 if ((r = socket_add_device_link(s)) < 0)
352 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
355 if ((r = unit_add_default_cgroups(u)) < 0)
358 if (s->meta.default_dependencies)
359 if ((r = socket_add_default_dependencies(s)) < 0)
363 return socket_verify(s);
366 static const char* listen_lookup(int type) {
368 if (type == SOCK_STREAM)
369 return "ListenStream";
370 else if (type == SOCK_DGRAM)
371 return "ListenDatagram";
372 else if (type == SOCK_SEQPACKET)
373 return "ListenSequentialPacket";
375 assert_not_reached("Unknown socket type");
379 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
382 Socket *s = SOCKET(u);
390 p2 = strappend(prefix, "\t");
391 prefix2 = p2 ? p2 : prefix;
394 "%sSocket State: %s\n"
395 "%sBindIPv6Only: %s\n"
397 "%sSocketMode: %04o\n"
398 "%sDirectoryMode: %04o\n"
401 "%sTCPCongestion: %s\n",
402 prefix, socket_state_to_string(s->state),
403 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
405 prefix, s->socket_mode,
406 prefix, s->directory_mode,
407 prefix, yes_no(s->keep_alive),
408 prefix, yes_no(s->free_bind),
409 prefix, strna(s->tcp_congestion));
411 if (s->control_pid > 0)
413 "%sControl PID: %lu\n",
414 prefix, (unsigned long) s->control_pid);
416 if (s->bind_to_device)
418 "%sBindToDevice: %s\n",
419 prefix, s->bind_to_device);
424 "%sNConnections: %u\n"
425 "%sMaxConnections: %u\n",
426 prefix, s->n_accepted,
427 prefix, s->n_connections,
428 prefix, s->max_connections);
430 if (s->priority >= 0)
433 prefix, s->priority);
435 if (s->receive_buffer > 0)
437 "%sReceiveBuffer: %zu\n",
438 prefix, s->receive_buffer);
440 if (s->send_buffer > 0)
442 "%sSendBuffer: %zu\n",
443 prefix, s->send_buffer);
455 if (s->pipe_size > 0)
458 prefix, s->pipe_size);
465 LIST_FOREACH(port, p, s->ports) {
467 if (p->type == SOCKET_SOCKET) {
472 if ((r = socket_address_print(&p->address, &k)) < 0)
477 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(p->address.type), t);
480 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
483 exec_context_dump(&s->exec_context, f, prefix);
485 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
486 if (!s->exec_command[c])
489 fprintf(f, "%s-> %s:\n",
490 prefix, socket_exec_command_to_string(c));
492 exec_command_dump_list(s->exec_command[c], f, prefix2);
498 static int instance_from_socket(int fd, unsigned nr, char **instance) {
503 struct sockaddr_un un;
504 struct sockaddr_in in;
505 struct sockaddr_in6 in6;
506 struct sockaddr_storage storage;
513 if (getsockname(fd, &local.sa, &l) < 0)
517 if (getpeername(fd, &remote.sa, &l) < 0)
520 switch (local.sa.sa_family) {
524 a = ntohl(local.in.sin_addr.s_addr),
525 b = ntohl(remote.in.sin_addr.s_addr);
528 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
529 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
530 ntohs(local.in.sin_port),
531 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
532 ntohs(remote.in.sin_port)) < 0)
539 static const char ipv4_prefix[] = {
540 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
543 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
544 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
546 *a = local.in6.sin6_addr.s6_addr+12,
547 *b = remote.in6.sin6_addr.s6_addr+12;
550 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
551 a[0], a[1], a[2], a[3],
552 ntohs(local.in6.sin6_port),
553 b[0], b[1], b[2], b[3],
554 ntohs(remote.in6.sin6_port)) < 0)
557 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
561 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
562 ntohs(local.in6.sin6_port),
563 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
564 ntohs(remote.in6.sin6_port)) < 0)
575 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
581 (unsigned long) ucred.pid,
582 (unsigned long) ucred.uid) < 0)
589 assert_not_reached("Unhandled socket type.");
596 static void socket_close_fds(Socket *s) {
601 LIST_FOREACH(port, p, s->ports) {
605 unit_unwatch_fd(UNIT(s), &p->fd_watch);
606 close_nointr_nofail(p->fd);
608 /* One little note: we should never delete any sockets
609 * in the file system here! After all some other
610 * process we spawned might still have a reference of
611 * this fd and wants to continue to use it. Therefore
612 * we delete sockets in the file system before we
613 * create a new one, not after we stopped using
620 static void socket_apply_socket_options(Socket *s, int fd) {
625 int b = s->keep_alive;
626 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
627 log_warning("SO_KEEPALIVE failed: %m");
630 if (s->priority >= 0)
631 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
632 log_warning("SO_PRIORITY failed: %m");
634 if (s->receive_buffer > 0) {
635 int value = (int) s->receive_buffer;
636 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
637 log_warning("SO_RCVBUF failed: %m");
640 if (s->send_buffer > 0) {
641 int value = (int) s->send_buffer;
642 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
643 log_warning("SO_SNDBUF failed: %m");
647 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
648 log_warning("SO_MARK failed: %m");
651 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
652 log_warning("IP_TOS failed: %m");
654 if (s->ip_ttl >= 0) {
657 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
659 if (socket_ipv6_is_supported())
660 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
663 errno = EAFNOSUPPORT;
667 log_warning("IP_TTL/IPV6_UNICAST_HOPS failed: %m");
670 if (s->tcp_congestion)
671 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
672 log_warning("TCP_CONGESTION failed: %m");
675 static void socket_apply_fifo_options(Socket *s, int fd) {
679 if (s->pipe_size > 0)
680 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
681 log_warning("F_SETPIPE_SZ: %m");
685 static int fifo_address_create(
687 mode_t directory_mode,
698 mkdir_parents(path, directory_mode);
700 if ((r = label_fifofile_set(path)) < 0)
703 /* Enforce the right access mode for the fifo */
704 old_mask = umask(~ socket_mode);
706 /* Include the original umask in our mask */
707 umask(~socket_mode | old_mask);
709 r = mkfifo(path, socket_mode);
717 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
724 if (fstat(fd, &st) < 0) {
729 if (!S_ISFIFO(st.st_mode) ||
730 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
731 st.st_uid != getuid() ||
732 st.st_gid != getgid()) {
745 close_nointr_nofail(fd);
750 static int socket_open_fds(Socket *s) {
754 bool know_label = false;
758 LIST_FOREACH(port, p, s->ports) {
763 if (p->type == SOCKET_SOCKET) {
767 if ((r = socket_instantiate_service(s)) < 0)
770 if (s->service && s->service->exec_command[SERVICE_EXEC_START])
771 if ((r = label_get_socket_label_from_exe(s->service->exec_command[SERVICE_EXEC_START]->path, &label)) < 0)
777 if ((r = socket_address_listen(
789 socket_apply_socket_options(s, p->fd);
791 } else if (p->type == SOCKET_FIFO) {
793 if ((r = fifo_address_create(
800 socket_apply_fifo_options(s, p->fd);
803 assert_not_reached("Unknown port type");
815 static void socket_unwatch_fds(Socket *s) {
820 LIST_FOREACH(port, p, s->ports) {
824 unit_unwatch_fd(UNIT(s), &p->fd_watch);
828 static int socket_watch_fds(Socket *s) {
834 LIST_FOREACH(port, p, s->ports) {
838 p->fd_watch.socket_accept =
840 p->type == SOCKET_SOCKET &&
841 socket_address_can_accept(&p->address);
843 if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
850 socket_unwatch_fds(s);
854 static void socket_set_state(Socket *s, SocketState state) {
855 SocketState old_state;
858 old_state = s->state;
861 if (state != SOCKET_START_PRE &&
862 state != SOCKET_START_POST &&
863 state != SOCKET_STOP_PRE &&
864 state != SOCKET_STOP_PRE_SIGTERM &&
865 state != SOCKET_STOP_PRE_SIGKILL &&
866 state != SOCKET_STOP_POST &&
867 state != SOCKET_FINAL_SIGTERM &&
868 state != SOCKET_FINAL_SIGKILL) {
869 unit_unwatch_timer(UNIT(s), &s->timer_watch);
870 socket_unwatch_control_pid(s);
871 s->control_command = NULL;
872 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
875 if (state != SOCKET_LISTENING)
876 socket_unwatch_fds(s);
878 if (state != SOCKET_START_POST &&
879 state != SOCKET_LISTENING &&
880 state != SOCKET_RUNNING &&
881 state != SOCKET_STOP_PRE &&
882 state != SOCKET_STOP_PRE_SIGTERM &&
883 state != SOCKET_STOP_PRE_SIGKILL)
886 if (state != old_state)
887 log_debug("%s changed %s -> %s",
889 socket_state_to_string(old_state),
890 socket_state_to_string(state));
892 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
895 static int socket_coldplug(Unit *u) {
896 Socket *s = SOCKET(u);
900 assert(s->state == SOCKET_DEAD);
902 if (s->deserialized_state != s->state) {
904 if (s->deserialized_state == SOCKET_START_PRE ||
905 s->deserialized_state == SOCKET_START_POST ||
906 s->deserialized_state == SOCKET_STOP_PRE ||
907 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
908 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
909 s->deserialized_state == SOCKET_STOP_POST ||
910 s->deserialized_state == SOCKET_FINAL_SIGTERM ||
911 s->deserialized_state == SOCKET_FINAL_SIGKILL) {
913 if (s->control_pid <= 0)
916 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
919 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
923 if (s->deserialized_state == SOCKET_START_POST ||
924 s->deserialized_state == SOCKET_LISTENING ||
925 s->deserialized_state == SOCKET_RUNNING ||
926 s->deserialized_state == SOCKET_STOP_PRE ||
927 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
928 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
929 if ((r = socket_open_fds(s)) < 0)
932 if (s->deserialized_state == SOCKET_LISTENING)
933 if ((r = socket_watch_fds(s)) < 0)
936 socket_set_state(s, s->deserialized_state);
942 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
951 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
954 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
963 s->meta.manager->environment,
967 s->meta.manager->confirm_spawn,
968 s->meta.cgroup_bondings,
975 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
976 /* FIXME: we need to do something here */
984 unit_unwatch_timer(UNIT(s), &s->timer_watch);
989 static void socket_enter_dead(Socket *s, bool success) {
995 socket_set_state(s, s->failure ? SOCKET_FAILED : SOCKET_DEAD);
998 static void socket_enter_signal(Socket *s, SocketState state, bool success);
1000 static void socket_enter_stop_post(Socket *s, bool success) {
1007 socket_unwatch_control_pid(s);
1009 s->control_command_id = SOCKET_EXEC_STOP_POST;
1011 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
1012 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1015 socket_set_state(s, SOCKET_STOP_POST);
1017 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, true);
1022 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1023 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1026 static void socket_enter_signal(Socket *s, SocketState state, bool success) {
1028 Set *pid_set = NULL;
1029 bool wait_for_exit = false;
1036 if (s->exec_context.kill_mode != KILL_NONE) {
1037 int sig = (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1039 if (s->control_pid > 0) {
1040 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1042 s->control_pid, sig) < 0 && errno != ESRCH)
1044 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1046 wait_for_exit = true;
1049 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1051 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1056 /* Exclude the control pid from being killed via the cgroup */
1057 if (s->control_pid > 0)
1058 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1061 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1062 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1063 log_warning("Failed to kill control group: %s", strerror(-r));
1065 wait_for_exit = true;
1071 if (wait_for_exit) {
1072 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1075 socket_set_state(s, state);
1076 } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1077 socket_enter_stop_post(s, true);
1079 socket_enter_dead(s, true);
1084 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1086 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1087 socket_enter_stop_post(s, false);
1089 socket_enter_dead(s, false);
1095 static void socket_enter_stop_pre(Socket *s, bool success) {
1102 socket_unwatch_control_pid(s);
1104 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1106 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
1107 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1110 socket_set_state(s, SOCKET_STOP_PRE);
1112 socket_enter_stop_post(s, true);
1117 log_warning("%s failed to run 'stop-pre' task: %s", s->meta.id, strerror(-r));
1118 socket_enter_stop_post(s, false);
1121 static void socket_enter_listening(Socket *s) {
1125 if ((r = socket_watch_fds(s)) < 0) {
1126 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1130 socket_set_state(s, SOCKET_LISTENING);
1134 socket_enter_stop_pre(s, false);
1137 static void socket_enter_start_post(Socket *s) {
1141 if ((r = socket_open_fds(s)) < 0) {
1142 log_warning("%s failed to listen on sockets: %s", s->meta.id, strerror(-r));
1146 socket_unwatch_control_pid(s);
1148 s->control_command_id = SOCKET_EXEC_START_POST;
1150 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
1151 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0) {
1152 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1156 socket_set_state(s, SOCKET_START_POST);
1158 socket_enter_listening(s);
1163 socket_enter_stop_pre(s, false);
1166 static void socket_enter_start_pre(Socket *s) {
1170 socket_unwatch_control_pid(s);
1172 s->control_command_id = SOCKET_EXEC_START_PRE;
1174 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
1175 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1178 socket_set_state(s, SOCKET_START_PRE);
1180 socket_enter_start_post(s);
1185 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1186 socket_enter_dead(s, false);
1189 static void socket_enter_running(Socket *s, int cfd) {
1194 dbus_error_init(&error);
1196 /* We don't take connections anymore if we are supposed to
1197 * shut down anyway */
1198 if (unit_pending_inactive(UNIT(s))) {
1199 log_debug("Suppressing connection request on %s since unit stop is scheduled.", s->meta.id);
1202 close_nointr_nofail(cfd);
1204 /* Flush all sockets by closing and reopening them */
1205 socket_close_fds(s);
1207 if ((r = socket_watch_fds(s)) < 0) {
1208 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1209 socket_enter_stop_pre(s, false);
1217 bool pending = false;
1220 /* If there's already a start pending don't bother to
1222 LIST_FOREACH(units_per_type, i, s->meta.manager->units_per_type[UNIT_SERVICE]) {
1223 Service *service = (Service *) i;
1225 if (!set_get(service->configured_sockets, s))
1228 if (!unit_pending_active(UNIT(service)))
1236 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s->service), JOB_REPLACE, true, &error, NULL)) < 0)
1239 socket_set_state(s, SOCKET_RUNNING);
1241 char *prefix, *instance = NULL, *name;
1244 if (s->n_connections >= s->max_connections) {
1245 log_warning("Too many incoming connections (%u)", s->n_connections);
1246 close_nointr_nofail(cfd);
1250 if ((r = socket_instantiate_service(s)) < 0)
1253 if ((r = instance_from_socket(cfd, s->n_accepted, &instance)) < 0)
1256 if (!(prefix = unit_name_to_prefix(s->meta.id))) {
1262 name = unit_name_build(prefix, instance, ".service");
1271 if ((r = unit_add_name(UNIT(s->service), name)) < 0) {
1276 service = s->service;
1280 service->meta.no_gc = false;
1282 unit_choose_id(UNIT(service), name);
1285 if ((r = service_set_socket_fd(service, cfd, s)) < 0)
1289 s->n_connections ++;
1291 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL)) < 0)
1294 /* Notify clients about changed counters */
1295 unit_add_to_dbus_queue(UNIT(s));
1301 log_warning("%s failed to queue socket startup job: %s", s->meta.id, bus_error(&error, r));
1302 socket_enter_stop_pre(s, false);
1305 close_nointr_nofail(cfd);
1307 dbus_error_free(&error);
1310 static void socket_run_next(Socket *s, bool success) {
1314 assert(s->control_command);
1315 assert(s->control_command->command_next);
1320 socket_unwatch_control_pid(s);
1322 s->control_command = s->control_command->command_next;
1324 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1330 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1332 if (s->state == SOCKET_START_POST)
1333 socket_enter_stop_pre(s, false);
1334 else if (s->state == SOCKET_STOP_POST)
1335 socket_enter_dead(s, false);
1337 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1340 static int socket_start(Unit *u) {
1341 Socket *s = SOCKET(u);
1345 /* We cannot fulfill this request right now, try again later
1347 if (s->state == SOCKET_STOP_PRE ||
1348 s->state == SOCKET_STOP_PRE_SIGKILL ||
1349 s->state == SOCKET_STOP_PRE_SIGTERM ||
1350 s->state == SOCKET_STOP_POST ||
1351 s->state == SOCKET_FINAL_SIGTERM ||
1352 s->state == SOCKET_FINAL_SIGKILL)
1355 if (s->state == SOCKET_START_PRE ||
1356 s->state == SOCKET_START_POST)
1359 /* Cannot run this without the service being around */
1361 if (s->service->meta.load_state != UNIT_LOADED)
1364 /* If the service is alredy active we cannot start the
1366 if (s->service->state != SERVICE_DEAD &&
1367 s->service->state != SERVICE_FAILED &&
1368 s->service->state != SERVICE_AUTO_RESTART)
1371 #ifdef HAVE_SYSV_COMPAT
1372 if (s->service->sysv_path) {
1373 log_error("Using SysV services for socket activation is not supported. Refusing.");
1379 assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1382 socket_enter_start_pre(s);
1386 static int socket_stop(Unit *u) {
1387 Socket *s = SOCKET(u);
1392 if (s->state == SOCKET_STOP_PRE ||
1393 s->state == SOCKET_STOP_PRE_SIGTERM ||
1394 s->state == SOCKET_STOP_PRE_SIGKILL ||
1395 s->state == SOCKET_STOP_POST ||
1396 s->state == SOCKET_FINAL_SIGTERM ||
1397 s->state == SOCKET_FINAL_SIGKILL)
1400 /* If there's already something running we go directly into
1402 if (s->state == SOCKET_START_PRE ||
1403 s->state == SOCKET_START_POST) {
1404 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, true);
1408 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1410 socket_enter_stop_pre(s, true);
1414 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1415 Socket *s = SOCKET(u);
1423 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1424 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1425 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1427 if (s->control_pid > 0)
1428 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1430 if (s->control_command_id >= 0)
1431 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1433 LIST_FOREACH(port, p, s->ports) {
1439 if ((copy = fdset_put_dup(fds, p->fd)) < 0)
1442 if (p->type == SOCKET_SOCKET) {
1445 if ((r = socket_address_print(&p->address, &t)) < 0)
1448 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1451 assert(p->type == SOCKET_FIFO);
1452 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1459 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1460 Socket *s = SOCKET(u);
1467 if (streq(key, "state")) {
1470 if ((state = socket_state_from_string(value)) < 0)
1471 log_debug("Failed to parse state value %s", value);
1473 s->deserialized_state = state;
1474 } else if (streq(key, "failure")) {
1477 if ((b = parse_boolean(value)) < 0)
1478 log_debug("Failed to parse failure value %s", value);
1480 s->failure = b || s->failure;
1482 } else if (streq(key, "n-accepted")) {
1485 if (safe_atou(value, &k) < 0)
1486 log_debug("Failed to parse n-accepted value %s", value);
1489 } else if (streq(key, "control-pid")) {
1492 if (parse_pid(value, &pid) < 0)
1493 log_debug("Failed to parse control-pid value %s", value);
1495 s->control_pid = pid;
1496 } else if (streq(key, "control-command")) {
1497 SocketExecCommand id;
1499 if ((id = socket_exec_command_from_string(value)) < 0)
1500 log_debug("Failed to parse exec-command value %s", value);
1502 s->control_command_id = id;
1503 s->control_command = s->exec_command[id];
1505 } else if (streq(key, "fifo")) {
1509 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1510 log_debug("Failed to parse fifo value %s", value);
1513 LIST_FOREACH(port, p, s->ports)
1514 if (streq(p->path, value+skip))
1519 close_nointr_nofail(p->fd);
1520 p->fd = fdset_remove(fds, fd);
1524 } else if (streq(key, "socket")) {
1525 int fd, type, skip = 0;
1528 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
1529 log_debug("Failed to parse socket value %s", value);
1532 LIST_FOREACH(port, p, s->ports)
1533 if (socket_address_is(&p->address, value+skip, type))
1538 close_nointr_nofail(p->fd);
1539 p->fd = fdset_remove(fds, fd);
1544 log_debug("Unknown serialization key '%s'", key);
1549 static UnitActiveState socket_active_state(Unit *u) {
1552 return state_translation_table[SOCKET(u)->state];
1555 static const char *socket_sub_state_to_string(Unit *u) {
1558 return socket_state_to_string(SOCKET(u)->state);
1561 static bool socket_check_gc(Unit *u) {
1562 Socket *s = SOCKET(u);
1566 return s->n_connections > 0;
1569 static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
1570 Socket *s = SOCKET(u);
1576 if (s->state != SOCKET_LISTENING)
1579 log_debug("Incoming traffic on %s", u->meta.id);
1581 if (events != EPOLLIN) {
1582 log_error("Got invalid poll event on socket.");
1586 if (w->socket_accept) {
1589 if ((cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK)) < 0) {
1594 log_error("Failed to accept socket: %m");
1601 socket_apply_socket_options(s, cfd);
1604 socket_enter_running(s, cfd);
1608 socket_enter_stop_pre(s, false);
1611 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1612 Socket *s = SOCKET(u);
1618 if (pid != s->control_pid)
1623 success = is_clean_exit(code, status);
1625 if (s->control_command) {
1626 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
1628 if (s->control_command->ignore)
1632 log_full(success ? LOG_DEBUG : LOG_NOTICE,
1633 "%s control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1634 s->failure = s->failure || !success;
1636 if (s->control_command && s->control_command->command_next && success) {
1637 log_debug("%s running next command for state %s", u->meta.id, socket_state_to_string(s->state));
1638 socket_run_next(s, success);
1640 s->control_command = NULL;
1641 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1643 /* No further commands for this step, so let's figure
1644 * out what to do next */
1646 log_debug("%s got final SIGCHLD for state %s", u->meta.id, socket_state_to_string(s->state));
1650 case SOCKET_START_PRE:
1652 socket_enter_start_post(s);
1654 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1657 case SOCKET_START_POST:
1659 socket_enter_listening(s);
1661 socket_enter_stop_pre(s, false);
1664 case SOCKET_STOP_PRE:
1665 case SOCKET_STOP_PRE_SIGTERM:
1666 case SOCKET_STOP_PRE_SIGKILL:
1667 socket_enter_stop_post(s, success);
1670 case SOCKET_STOP_POST:
1671 case SOCKET_FINAL_SIGTERM:
1672 case SOCKET_FINAL_SIGKILL:
1673 socket_enter_dead(s, success);
1677 assert_not_reached("Uh, control process died at wrong time.");
1681 /* Notify clients about changed exit status */
1682 unit_add_to_dbus_queue(u);
1685 static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
1686 Socket *s = SOCKET(u);
1689 assert(elapsed == 1);
1690 assert(w == &s->timer_watch);
1694 case SOCKET_START_PRE:
1695 log_warning("%s starting timed out. Terminating.", u->meta.id);
1696 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1698 case SOCKET_START_POST:
1699 log_warning("%s starting timed out. Stopping.", u->meta.id);
1700 socket_enter_stop_pre(s, false);
1703 case SOCKET_STOP_PRE:
1704 log_warning("%s stopping timed out. Terminating.", u->meta.id);
1705 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, false);
1708 case SOCKET_STOP_PRE_SIGTERM:
1709 if (s->exec_context.send_sigkill) {
1710 log_warning("%s stopping timed out. Killing.", u->meta.id);
1711 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, false);
1713 log_warning("%s stopping timed out. Skipping SIGKILL. Ignoring.", u->meta.id);
1714 socket_enter_stop_post(s, false);
1718 case SOCKET_STOP_PRE_SIGKILL:
1719 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
1720 socket_enter_stop_post(s, false);
1723 case SOCKET_STOP_POST:
1724 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
1725 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1728 case SOCKET_FINAL_SIGTERM:
1729 if (s->exec_context.send_sigkill) {
1730 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
1731 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, false);
1733 log_warning("%s stopping timed out (2). Skipping SIGKILL. Ignoring.", u->meta.id);
1734 socket_enter_dead(s, false);
1738 case SOCKET_FINAL_SIGKILL:
1739 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
1740 socket_enter_dead(s, false);
1744 assert_not_reached("Timeout at wrong time.");
1748 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
1757 /* Called from the service code for requesting our fds */
1760 LIST_FOREACH(port, p, s->ports)
1764 if (!(rfds = new(int, rn_fds)))
1768 LIST_FOREACH(port, p, s->ports)
1772 assert(k == rn_fds);
1780 void socket_notify_service_dead(Socket *s) {
1783 /* The service is dead. Dang!
1785 * This is strictly for one-instance-for-all-connections
1788 if (s->state == SOCKET_RUNNING) {
1789 log_debug("%s got notified about service death.", s->meta.id);
1790 socket_enter_listening(s);
1794 void socket_connection_unref(Socket *s) {
1797 /* The service is dead. Yay!
1799 * This is strictly for one-onstance-per-connection
1802 assert(s->n_connections > 0);
1805 log_debug("%s: One connection closed, %u left.", s->meta.id, s->n_connections);
1808 static void socket_reset_failed(Unit *u) {
1809 Socket *s = SOCKET(u);
1813 if (s->state == SOCKET_FAILED)
1814 socket_set_state(s, SOCKET_DEAD);
1819 static int socket_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
1820 Socket *s = SOCKET(u);
1822 Set *pid_set = NULL;
1826 if (who == KILL_MAIN) {
1827 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "Socket units have no main processes");
1831 if (s->control_pid <= 0 && who == KILL_CONTROL) {
1832 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
1836 if (s->control_pid > 0)
1837 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
1840 if (mode == KILL_CONTROL_GROUP) {
1843 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
1846 /* Exclude the control pid from being killed via the cgroup */
1847 if (s->control_pid > 0)
1848 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
1853 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
1854 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1865 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
1866 [SOCKET_DEAD] = "dead",
1867 [SOCKET_START_PRE] = "start-pre",
1868 [SOCKET_START_POST] = "start-post",
1869 [SOCKET_LISTENING] = "listening",
1870 [SOCKET_RUNNING] = "running",
1871 [SOCKET_STOP_PRE] = "stop-pre",
1872 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
1873 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
1874 [SOCKET_STOP_POST] = "stop-post",
1875 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
1876 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
1877 [SOCKET_FAILED] = "failed"
1880 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
1882 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
1883 [SOCKET_EXEC_START_PRE] = "StartPre",
1884 [SOCKET_EXEC_START_POST] = "StartPost",
1885 [SOCKET_EXEC_STOP_PRE] = "StopPre",
1886 [SOCKET_EXEC_STOP_POST] = "StopPost"
1889 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
1891 const UnitVTable socket_vtable = {
1892 .suffix = ".socket",
1894 .init = socket_init,
1895 .done = socket_done,
1896 .load = socket_load,
1898 .kill = socket_kill,
1900 .coldplug = socket_coldplug,
1902 .dump = socket_dump,
1904 .start = socket_start,
1905 .stop = socket_stop,
1907 .serialize = socket_serialize,
1908 .deserialize_item = socket_deserialize_item,
1910 .active_state = socket_active_state,
1911 .sub_state_to_string = socket_sub_state_to_string,
1913 .check_gc = socket_check_gc,
1915 .fd_event = socket_fd_event,
1916 .sigchld_event = socket_sigchld_event,
1917 .timer_event = socket_timer_event,
1919 .reset_failed = socket_reset_failed,
1921 .bus_interface = "org.freedesktop.systemd1.Socket",
1922 .bus_message_handler = bus_socket_message_handler,
1923 .bus_invalidating_properties = bus_socket_invalidating_properties