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 u->meta.no_gc = true;
173 s->service = SERVICE(u);
177 static bool have_non_accept_socket(Socket *s) {
185 LIST_FOREACH(port, p, s->ports) {
187 if (p->type != SOCKET_SOCKET)
190 if (!socket_address_can_accept(&p->address))
197 static int socket_verify(Socket *s) {
200 if (s->meta.load_state != UNIT_LOADED)
204 log_error("%s lacks Listen setting. Refusing.", s->meta.id);
208 if (s->accept && have_non_accept_socket(s)) {
209 log_error("%s configured for accepting sockets, but sockets are non-accepting. Refusing.", s->meta.id);
213 if (s->accept && s->max_connections <= 0) {
214 log_error("%s's MaxConnection setting too small. Refusing.", s->meta.id);
218 if (s->accept && s->service) {
219 log_error("Explicit service configuration for accepting sockets not supported on %s. Refusing.", s->meta.id);
223 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
224 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
231 static bool socket_needs_mount(Socket *s, const char *prefix) {
236 LIST_FOREACH(port, p, s->ports) {
238 if (p->type == SOCKET_SOCKET) {
239 if (socket_address_needs_mount(&p->address, prefix))
242 assert(p->type == SOCKET_FIFO);
243 if (path_startswith(p->path, prefix))
251 int socket_add_one_mount_link(Socket *s, Mount *m) {
257 if (s->meta.load_state != UNIT_LOADED ||
258 m->meta.load_state != UNIT_LOADED)
261 if (!socket_needs_mount(s, m->where))
264 if ((r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
270 static int socket_add_mount_links(Socket *s) {
276 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_MOUNT])
277 if ((r = socket_add_one_mount_link(s, (Mount*) other)) < 0)
283 static int socket_add_device_link(Socket *s) {
289 if (!s->bind_to_device)
292 if (asprintf(&t, "/sys/subsystem/net/devices/%s", s->bind_to_device) < 0)
295 r = unit_add_node_link(UNIT(s), t, false);
301 static int socket_add_default_dependencies(Socket *s) {
305 if (s->meta.manager->running_as == MANAGER_SYSTEM) {
306 if ((r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
309 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 0)
313 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
316 static int socket_load(Unit *u) {
317 Socket *s = SOCKET(u);
321 assert(u->meta.load_state == UNIT_STUB);
323 if ((r = unit_load_fragment_and_dropin(u)) < 0)
326 /* This is a new unit? Then let's add in some extras */
327 if (u->meta.load_state == UNIT_LOADED) {
329 if (have_non_accept_socket(s)) {
332 if ((r = unit_load_related_unit(u, ".service", (Unit**) &s->service)) < 0)
335 if ((r = unit_add_dependency(u, UNIT_BEFORE, UNIT(s->service), true)) < 0)
339 if ((r = socket_add_mount_links(s)) < 0)
342 if ((r = socket_add_device_link(s)) < 0)
345 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
348 if ((r = unit_add_default_cgroups(u)) < 0)
351 if (s->meta.default_dependencies)
352 if ((r = socket_add_default_dependencies(s)) < 0)
356 return socket_verify(s);
359 static const char* listen_lookup(int type) {
361 if (type == SOCK_STREAM)
362 return "ListenStream";
363 else if (type == SOCK_DGRAM)
364 return "ListenDatagram";
365 else if (type == SOCK_SEQPACKET)
366 return "ListenSequentialPacket";
368 assert_not_reached("Unknown socket type");
372 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
375 Socket *s = SOCKET(u);
383 p2 = strappend(prefix, "\t");
384 prefix2 = p2 ? p2 : prefix;
387 "%sSocket State: %s\n"
388 "%sBindIPv6Only: %s\n"
390 "%sSocketMode: %04o\n"
391 "%sDirectoryMode: %04o\n"
394 "%sTCPCongestion: %s\n",
395 prefix, socket_state_to_string(s->state),
396 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
398 prefix, s->socket_mode,
399 prefix, s->directory_mode,
400 prefix, yes_no(s->keep_alive),
401 prefix, yes_no(s->free_bind),
402 prefix, strna(s->tcp_congestion));
404 if (s->control_pid > 0)
406 "%sControl PID: %lu\n",
407 prefix, (unsigned long) s->control_pid);
409 if (s->bind_to_device)
411 "%sBindToDevice: %s\n",
412 prefix, s->bind_to_device);
417 "%sNConnections: %u\n"
418 "%sMaxConnections: %u\n",
419 prefix, s->n_accepted,
420 prefix, s->n_connections,
421 prefix, s->max_connections);
423 if (s->priority >= 0)
426 prefix, s->priority);
428 if (s->receive_buffer > 0)
430 "%sReceiveBuffer: %zu\n",
431 prefix, s->receive_buffer);
433 if (s->send_buffer > 0)
435 "%sSendBuffer: %zu\n",
436 prefix, s->send_buffer);
448 if (s->pipe_size > 0)
451 prefix, s->pipe_size);
458 LIST_FOREACH(port, p, s->ports) {
460 if (p->type == SOCKET_SOCKET) {
465 if ((r = socket_address_print(&p->address, &k)) < 0)
470 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(p->address.type), t);
473 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
476 exec_context_dump(&s->exec_context, f, prefix);
478 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
479 if (!s->exec_command[c])
482 fprintf(f, "%s-> %s:\n",
483 prefix, socket_exec_command_to_string(c));
485 exec_command_dump_list(s->exec_command[c], f, prefix2);
491 static int instance_from_socket(int fd, unsigned nr, char **instance) {
496 struct sockaddr_un un;
497 struct sockaddr_in in;
498 struct sockaddr_in6 in6;
499 struct sockaddr_storage storage;
506 if (getsockname(fd, &local.sa, &l) < 0)
510 if (getpeername(fd, &remote.sa, &l) < 0)
513 switch (local.sa.sa_family) {
517 a = ntohl(local.in.sin_addr.s_addr),
518 b = ntohl(remote.in.sin_addr.s_addr);
521 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
522 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
523 ntohs(local.in.sin_port),
524 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
525 ntohs(remote.in.sin_port)) < 0)
532 static const char ipv4_prefix[] = {
533 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
536 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
537 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
539 *a = local.in6.sin6_addr.s6_addr+12,
540 *b = remote.in6.sin6_addr.s6_addr+12;
543 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
544 a[0], a[1], a[2], a[3],
545 ntohs(local.in6.sin6_port),
546 b[0], b[1], b[2], b[3],
547 ntohs(remote.in6.sin6_port)) < 0)
550 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
554 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
555 ntohs(local.in6.sin6_port),
556 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
557 ntohs(remote.in6.sin6_port)) < 0)
568 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
574 (unsigned long) ucred.pid,
575 (unsigned long) ucred.uid) < 0)
582 assert_not_reached("Unhandled socket type.");
589 static void socket_close_fds(Socket *s) {
594 LIST_FOREACH(port, p, s->ports) {
598 unit_unwatch_fd(UNIT(s), &p->fd_watch);
599 close_nointr_nofail(p->fd);
601 /* One little note: we should never delete any sockets
602 * in the file system here! After all some other
603 * process we spawned might still have a reference of
604 * this fd and wants to continue to use it. Therefore
605 * we delete sockets in the file system before we
606 * create a new one, not after we stopped using
613 static void socket_apply_socket_options(Socket *s, int fd) {
618 int b = s->keep_alive;
619 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
620 log_warning("SO_KEEPALIVE failed: %m");
623 if (s->priority >= 0)
624 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
625 log_warning("SO_PRIORITY failed: %m");
627 if (s->receive_buffer > 0) {
628 int value = (int) s->receive_buffer;
629 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
630 log_warning("SO_RCVBUF failed: %m");
633 if (s->send_buffer > 0) {
634 int value = (int) s->send_buffer;
635 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
636 log_warning("SO_SNDBUF failed: %m");
640 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
641 log_warning("SO_MARK failed: %m");
644 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
645 log_warning("IP_TOS failed: %m");
647 if (s->ip_ttl >= 0) {
650 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
652 if (socket_ipv6_is_supported())
653 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
656 errno = EAFNOSUPPORT;
660 log_warning("IP_TTL/IPV6_UNICAST_HOPS failed: %m");
663 if (s->tcp_congestion)
664 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
665 log_warning("TCP_CONGESTION failed: %m");
668 static void socket_apply_fifo_options(Socket *s, int fd) {
672 if (s->pipe_size > 0)
673 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
674 log_warning("F_SETPIPE_SZ: %m");
678 static int fifo_address_create(
680 mode_t directory_mode,
691 mkdir_parents(path, directory_mode);
693 if ((r = label_fifofile_set(path)) < 0)
696 /* Enforce the right access mode for the fifo */
697 old_mask = umask(~ socket_mode);
699 /* Include the original umask in our mask */
700 umask(~socket_mode | old_mask);
702 r = mkfifo(path, socket_mode);
710 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
717 if (fstat(fd, &st) < 0) {
722 if (!S_ISFIFO(st.st_mode) ||
723 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
724 st.st_uid != getuid() ||
725 st.st_gid != getgid()) {
738 close_nointr_nofail(fd);
743 static int socket_open_fds(Socket *s) {
747 bool know_label = false;
751 LIST_FOREACH(port, p, s->ports) {
756 if (p->type == SOCKET_SOCKET) {
760 if ((r = socket_instantiate_service(s)) < 0)
763 if (s->service && s->service->exec_command[SERVICE_EXEC_START])
764 if ((r = label_get_socket_label_from_exe(s->service->exec_command[SERVICE_EXEC_START]->path, &label)) < 0)
770 if ((r = socket_address_listen(
782 socket_apply_socket_options(s, p->fd);
784 } else if (p->type == SOCKET_FIFO) {
786 if ((r = fifo_address_create(
793 socket_apply_fifo_options(s, p->fd);
796 assert_not_reached("Unknown port type");
808 static void socket_unwatch_fds(Socket *s) {
813 LIST_FOREACH(port, p, s->ports) {
817 unit_unwatch_fd(UNIT(s), &p->fd_watch);
821 static int socket_watch_fds(Socket *s) {
827 LIST_FOREACH(port, p, s->ports) {
831 p->fd_watch.socket_accept =
833 p->type == SOCKET_SOCKET &&
834 socket_address_can_accept(&p->address);
836 if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
843 socket_unwatch_fds(s);
847 static void socket_set_state(Socket *s, SocketState state) {
848 SocketState old_state;
851 old_state = s->state;
854 if (state != SOCKET_START_PRE &&
855 state != SOCKET_START_POST &&
856 state != SOCKET_STOP_PRE &&
857 state != SOCKET_STOP_PRE_SIGTERM &&
858 state != SOCKET_STOP_PRE_SIGKILL &&
859 state != SOCKET_STOP_POST &&
860 state != SOCKET_FINAL_SIGTERM &&
861 state != SOCKET_FINAL_SIGKILL) {
862 unit_unwatch_timer(UNIT(s), &s->timer_watch);
863 socket_unwatch_control_pid(s);
864 s->control_command = NULL;
865 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
868 if (state != SOCKET_LISTENING)
869 socket_unwatch_fds(s);
871 if (state != SOCKET_START_POST &&
872 state != SOCKET_LISTENING &&
873 state != SOCKET_RUNNING &&
874 state != SOCKET_STOP_PRE &&
875 state != SOCKET_STOP_PRE_SIGTERM &&
876 state != SOCKET_STOP_PRE_SIGKILL)
879 if (state != old_state)
880 log_debug("%s changed %s -> %s",
882 socket_state_to_string(old_state),
883 socket_state_to_string(state));
885 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
888 static int socket_coldplug(Unit *u) {
889 Socket *s = SOCKET(u);
893 assert(s->state == SOCKET_DEAD);
895 if (s->deserialized_state != s->state) {
897 if (s->deserialized_state == SOCKET_START_PRE ||
898 s->deserialized_state == SOCKET_START_POST ||
899 s->deserialized_state == SOCKET_STOP_PRE ||
900 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
901 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
902 s->deserialized_state == SOCKET_STOP_POST ||
903 s->deserialized_state == SOCKET_FINAL_SIGTERM ||
904 s->deserialized_state == SOCKET_FINAL_SIGKILL) {
906 if (s->control_pid <= 0)
909 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
912 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
916 if (s->deserialized_state == SOCKET_START_POST ||
917 s->deserialized_state == SOCKET_LISTENING ||
918 s->deserialized_state == SOCKET_RUNNING ||
919 s->deserialized_state == SOCKET_STOP_PRE ||
920 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
921 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
922 if ((r = socket_open_fds(s)) < 0)
925 if (s->deserialized_state == SOCKET_LISTENING)
926 if ((r = socket_watch_fds(s)) < 0)
929 socket_set_state(s, s->deserialized_state);
935 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
944 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
947 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
956 s->meta.manager->environment,
960 s->meta.manager->confirm_spawn,
961 s->meta.cgroup_bondings,
968 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
969 /* FIXME: we need to do something here */
977 unit_unwatch_timer(UNIT(s), &s->timer_watch);
982 static void socket_enter_dead(Socket *s, bool success) {
988 socket_set_state(s, s->failure ? SOCKET_FAILED : SOCKET_DEAD);
991 static void socket_enter_signal(Socket *s, SocketState state, bool success);
993 static void socket_enter_stop_post(Socket *s, bool success) {
1000 socket_unwatch_control_pid(s);
1002 s->control_command_id = SOCKET_EXEC_STOP_POST;
1004 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
1005 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1008 socket_set_state(s, SOCKET_STOP_POST);
1010 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, true);
1015 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1016 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1019 static void socket_enter_signal(Socket *s, SocketState state, bool success) {
1021 Set *pid_set = NULL;
1022 bool wait_for_exit = false;
1029 if (s->exec_context.kill_mode != KILL_NONE) {
1030 int sig = (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1032 if (s->control_pid > 0) {
1033 if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1035 s->control_pid, sig) < 0 && errno != ESRCH)
1037 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1039 wait_for_exit = true;
1042 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1044 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1049 /* Exclude the control pid from being killed via the cgroup */
1050 if (s->control_pid > 0)
1051 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1054 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1055 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1056 log_warning("Failed to kill control group: %s", strerror(-r));
1058 wait_for_exit = true;
1064 if (wait_for_exit) {
1065 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1068 socket_set_state(s, state);
1069 } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1070 socket_enter_stop_post(s, true);
1072 socket_enter_dead(s, true);
1077 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1079 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1080 socket_enter_stop_post(s, false);
1082 socket_enter_dead(s, false);
1088 static void socket_enter_stop_pre(Socket *s, bool success) {
1095 socket_unwatch_control_pid(s);
1097 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1099 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
1100 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1103 socket_set_state(s, SOCKET_STOP_PRE);
1105 socket_enter_stop_post(s, true);
1110 log_warning("%s failed to run 'stop-pre' task: %s", s->meta.id, strerror(-r));
1111 socket_enter_stop_post(s, false);
1114 static void socket_enter_listening(Socket *s) {
1118 if ((r = socket_watch_fds(s)) < 0) {
1119 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1123 socket_set_state(s, SOCKET_LISTENING);
1127 socket_enter_stop_pre(s, false);
1130 static void socket_enter_start_post(Socket *s) {
1134 if ((r = socket_open_fds(s)) < 0) {
1135 log_warning("%s failed to listen on sockets: %s", s->meta.id, strerror(-r));
1139 socket_unwatch_control_pid(s);
1141 s->control_command_id = SOCKET_EXEC_START_POST;
1143 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
1144 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0) {
1145 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1149 socket_set_state(s, SOCKET_START_POST);
1151 socket_enter_listening(s);
1156 socket_enter_stop_pre(s, false);
1159 static void socket_enter_start_pre(Socket *s) {
1163 socket_unwatch_control_pid(s);
1165 s->control_command_id = SOCKET_EXEC_START_PRE;
1167 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
1168 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1171 socket_set_state(s, SOCKET_START_PRE);
1173 socket_enter_start_post(s);
1178 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1179 socket_enter_dead(s, false);
1182 static void socket_enter_running(Socket *s, int cfd) {
1187 dbus_error_init(&error);
1189 /* We don't take connections anymore if we are supposed to
1190 * shut down anyway */
1191 if (unit_pending_inactive(UNIT(s))) {
1193 close_nointr_nofail(cfd);
1195 /* Flush all sockets by closing and reopening them */
1196 socket_close_fds(s);
1198 if ((r = socket_watch_fds(s)) < 0) {
1199 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1200 socket_enter_stop_pre(s, false);
1208 bool pending = false;
1211 /* If there's already a start pending don't bother to
1213 LIST_FOREACH(units_per_type, i, s->meta.manager->units_per_type[UNIT_SERVICE]) {
1214 Service *service = (Service *) i;
1216 if (!set_get(service->configured_sockets, s))
1219 if (!unit_pending_active(UNIT(service)))
1227 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s->service), JOB_REPLACE, true, &error, NULL)) < 0)
1230 socket_set_state(s, SOCKET_RUNNING);
1232 char *prefix, *instance = NULL, *name;
1235 if (s->n_connections >= s->max_connections) {
1236 log_warning("Too many incoming connections (%u)", s->n_connections);
1237 close_nointr_nofail(cfd);
1241 if ((r = socket_instantiate_service(s)) < 0)
1244 if ((r = instance_from_socket(cfd, s->n_accepted, &instance)) < 0)
1247 if (!(prefix = unit_name_to_prefix(s->meta.id))) {
1253 name = unit_name_build(prefix, instance, ".service");
1262 if ((r = unit_add_name(UNIT(s->service), name)) < 0) {
1267 service = s->service;
1271 service->meta.no_gc = false;
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)
1285 /* Notify clients about changed counters */
1286 unit_add_to_dbus_queue(UNIT(s));
1292 log_warning("%s failed to queue socket startup job: %s", s->meta.id, bus_error(&error, r));
1293 socket_enter_stop_pre(s, false);
1296 close_nointr_nofail(cfd);
1298 dbus_error_free(&error);
1301 static void socket_run_next(Socket *s, bool success) {
1305 assert(s->control_command);
1306 assert(s->control_command->command_next);
1311 socket_unwatch_control_pid(s);
1313 s->control_command = s->control_command->command_next;
1315 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1321 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1323 if (s->state == SOCKET_START_POST)
1324 socket_enter_stop_pre(s, false);
1325 else if (s->state == SOCKET_STOP_POST)
1326 socket_enter_dead(s, false);
1328 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1331 static int socket_start(Unit *u) {
1332 Socket *s = SOCKET(u);
1336 /* We cannot fulfill this request right now, try again later
1338 if (s->state == SOCKET_STOP_PRE ||
1339 s->state == SOCKET_STOP_PRE_SIGKILL ||
1340 s->state == SOCKET_STOP_PRE_SIGTERM ||
1341 s->state == SOCKET_STOP_POST ||
1342 s->state == SOCKET_FINAL_SIGTERM ||
1343 s->state == SOCKET_FINAL_SIGKILL)
1346 if (s->state == SOCKET_START_PRE ||
1347 s->state == SOCKET_START_POST)
1350 /* Cannot run this without the service being around */
1352 if (s->service->meta.load_state != UNIT_LOADED)
1355 /* If the service is alredy actvie we cannot start the
1357 if (s->service->state != SERVICE_DEAD &&
1358 s->service->state != SERVICE_FAILED &&
1359 s->service->state != SERVICE_AUTO_RESTART)
1363 assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1366 socket_enter_start_pre(s);
1370 static int socket_stop(Unit *u) {
1371 Socket *s = SOCKET(u);
1376 if (s->state == SOCKET_STOP_PRE ||
1377 s->state == SOCKET_STOP_PRE_SIGTERM ||
1378 s->state == SOCKET_STOP_PRE_SIGKILL ||
1379 s->state == SOCKET_STOP_POST ||
1380 s->state == SOCKET_FINAL_SIGTERM ||
1381 s->state == SOCKET_FINAL_SIGKILL)
1384 /* If there's already something running we go directly into
1386 if (s->state == SOCKET_START_PRE ||
1387 s->state == SOCKET_START_POST) {
1388 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, true);
1392 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1394 socket_enter_stop_pre(s, true);
1398 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1399 Socket *s = SOCKET(u);
1407 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1408 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1409 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1411 if (s->control_pid > 0)
1412 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1414 if (s->control_command_id >= 0)
1415 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1417 LIST_FOREACH(port, p, s->ports) {
1423 if ((copy = fdset_put_dup(fds, p->fd)) < 0)
1426 if (p->type == SOCKET_SOCKET) {
1429 if ((r = socket_address_print(&p->address, &t)) < 0)
1432 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1435 assert(p->type == SOCKET_FIFO);
1436 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1443 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1444 Socket *s = SOCKET(u);
1451 if (streq(key, "state")) {
1454 if ((state = socket_state_from_string(value)) < 0)
1455 log_debug("Failed to parse state value %s", value);
1457 s->deserialized_state = state;
1458 } else if (streq(key, "failure")) {
1461 if ((b = parse_boolean(value)) < 0)
1462 log_debug("Failed to parse failure value %s", value);
1464 s->failure = b || s->failure;
1466 } else if (streq(key, "n-accepted")) {
1469 if (safe_atou(value, &k) < 0)
1470 log_debug("Failed to parse n-accepted value %s", value);
1473 } else if (streq(key, "control-pid")) {
1476 if (parse_pid(value, &pid) < 0)
1477 log_debug("Failed to parse control-pid value %s", value);
1479 s->control_pid = pid;
1480 } else if (streq(key, "control-command")) {
1481 SocketExecCommand id;
1483 if ((id = socket_exec_command_from_string(value)) < 0)
1484 log_debug("Failed to parse exec-command value %s", value);
1486 s->control_command_id = id;
1487 s->control_command = s->exec_command[id];
1489 } else if (streq(key, "fifo")) {
1493 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1494 log_debug("Failed to parse fifo value %s", value);
1497 LIST_FOREACH(port, p, s->ports)
1498 if (streq(p->path, value+skip))
1503 close_nointr_nofail(p->fd);
1504 p->fd = fdset_remove(fds, fd);
1508 } else if (streq(key, "socket")) {
1509 int fd, type, skip = 0;
1512 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
1513 log_debug("Failed to parse socket value %s", value);
1516 LIST_FOREACH(port, p, s->ports)
1517 if (socket_address_is(&p->address, value+skip, type))
1522 close_nointr_nofail(p->fd);
1523 p->fd = fdset_remove(fds, fd);
1528 log_debug("Unknown serialization key '%s'", key);
1533 static UnitActiveState socket_active_state(Unit *u) {
1536 return state_translation_table[SOCKET(u)->state];
1539 static const char *socket_sub_state_to_string(Unit *u) {
1542 return socket_state_to_string(SOCKET(u)->state);
1545 static bool socket_check_gc(Unit *u) {
1546 Socket *s = SOCKET(u);
1550 return s->n_connections > 0;
1553 static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
1554 Socket *s = SOCKET(u);
1560 if (s->state != SOCKET_LISTENING)
1563 log_debug("Incoming traffic on %s", u->meta.id);
1565 if (events != EPOLLIN) {
1566 log_error("Got invalid poll event on socket.");
1570 if (w->socket_accept) {
1573 if ((cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK)) < 0) {
1578 log_error("Failed to accept socket: %m");
1585 socket_apply_socket_options(s, cfd);
1588 socket_enter_running(s, cfd);
1592 socket_enter_stop_pre(s, false);
1595 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1596 Socket *s = SOCKET(u);
1602 if (pid != s->control_pid)
1607 success = is_clean_exit(code, status);
1609 if (s->control_command) {
1610 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
1612 if (s->control_command->ignore)
1616 log_full(success ? LOG_DEBUG : LOG_NOTICE,
1617 "%s control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1618 s->failure = s->failure || !success;
1620 if (s->control_command && s->control_command->command_next && success) {
1621 log_debug("%s running next command for state %s", u->meta.id, socket_state_to_string(s->state));
1622 socket_run_next(s, success);
1624 s->control_command = NULL;
1625 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1627 /* No further commands for this step, so let's figure
1628 * out what to do next */
1630 log_debug("%s got final SIGCHLD for state %s", u->meta.id, socket_state_to_string(s->state));
1634 case SOCKET_START_PRE:
1636 socket_enter_start_post(s);
1638 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1641 case SOCKET_START_POST:
1643 socket_enter_listening(s);
1645 socket_enter_stop_pre(s, false);
1648 case SOCKET_STOP_PRE:
1649 case SOCKET_STOP_PRE_SIGTERM:
1650 case SOCKET_STOP_PRE_SIGKILL:
1651 socket_enter_stop_post(s, success);
1654 case SOCKET_STOP_POST:
1655 case SOCKET_FINAL_SIGTERM:
1656 case SOCKET_FINAL_SIGKILL:
1657 socket_enter_dead(s, success);
1661 assert_not_reached("Uh, control process died at wrong time.");
1665 /* Notify clients about changed exit status */
1666 unit_add_to_dbus_queue(u);
1669 static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
1670 Socket *s = SOCKET(u);
1673 assert(elapsed == 1);
1674 assert(w == &s->timer_watch);
1678 case SOCKET_START_PRE:
1679 log_warning("%s starting timed out. Terminating.", u->meta.id);
1680 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1682 case SOCKET_START_POST:
1683 log_warning("%s starting timed out. Stopping.", u->meta.id);
1684 socket_enter_stop_pre(s, false);
1687 case SOCKET_STOP_PRE:
1688 log_warning("%s stopping timed out. Terminating.", u->meta.id);
1689 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, false);
1692 case SOCKET_STOP_PRE_SIGTERM:
1693 if (s->exec_context.send_sigkill) {
1694 log_warning("%s stopping timed out. Killing.", u->meta.id);
1695 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, false);
1697 log_warning("%s stopping timed out. Skipping SIGKILL. Ignoring.", u->meta.id);
1698 socket_enter_stop_post(s, false);
1702 case SOCKET_STOP_PRE_SIGKILL:
1703 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
1704 socket_enter_stop_post(s, false);
1707 case SOCKET_STOP_POST:
1708 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
1709 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1712 case SOCKET_FINAL_SIGTERM:
1713 if (s->exec_context.send_sigkill) {
1714 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
1715 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, false);
1717 log_warning("%s stopping timed out (2). Skipping SIGKILL. Ignoring.", u->meta.id);
1718 socket_enter_dead(s, false);
1722 case SOCKET_FINAL_SIGKILL:
1723 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
1724 socket_enter_dead(s, false);
1728 assert_not_reached("Timeout at wrong time.");
1732 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
1741 /* Called from the service code for requesting our fds */
1744 LIST_FOREACH(port, p, s->ports)
1748 if (!(rfds = new(int, rn_fds)))
1752 LIST_FOREACH(port, p, s->ports)
1756 assert(k == rn_fds);
1764 void socket_notify_service_dead(Socket *s) {
1767 /* The service is dead. Dang!
1769 * This is strictly for one-instance-for-all-connections
1772 if (s->state == SOCKET_RUNNING) {
1773 log_debug("%s got notified about service death.", s->meta.id);
1774 socket_enter_listening(s);
1778 void socket_connection_unref(Socket *s) {
1781 /* The service is dead. Yay!
1783 * This is strictly for one-onstance-per-connection
1786 assert(s->n_connections > 0);
1789 log_debug("%s: One connection closed, %u left.", s->meta.id, s->n_connections);
1792 static void socket_reset_failed(Unit *u) {
1793 Socket *s = SOCKET(u);
1797 if (s->state == SOCKET_FAILED)
1798 socket_set_state(s, SOCKET_DEAD);
1803 static int socket_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
1804 Socket *s = SOCKET(u);
1806 Set *pid_set = NULL;
1810 if (who == KILL_MAIN) {
1811 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "Socket units have no main processes");
1815 if (s->control_pid <= 0 && who == KILL_CONTROL) {
1816 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
1820 if (s->control_pid > 0)
1821 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
1824 if (mode == KILL_CONTROL_GROUP) {
1827 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
1830 /* Exclude the control pid from being killed via the cgroup */
1831 if (s->control_pid > 0)
1832 if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
1837 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
1838 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1849 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
1850 [SOCKET_DEAD] = "dead",
1851 [SOCKET_START_PRE] = "start-pre",
1852 [SOCKET_START_POST] = "start-post",
1853 [SOCKET_LISTENING] = "listening",
1854 [SOCKET_RUNNING] = "running",
1855 [SOCKET_STOP_PRE] = "stop-pre",
1856 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
1857 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
1858 [SOCKET_STOP_POST] = "stop-post",
1859 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
1860 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
1861 [SOCKET_FAILED] = "failed"
1864 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
1866 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
1867 [SOCKET_EXEC_START_PRE] = "StartPre",
1868 [SOCKET_EXEC_START_POST] = "StartPost",
1869 [SOCKET_EXEC_STOP_PRE] = "StopPre",
1870 [SOCKET_EXEC_STOP_POST] = "StopPost"
1873 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
1875 const UnitVTable socket_vtable = {
1876 .suffix = ".socket",
1878 .init = socket_init,
1879 .done = socket_done,
1880 .load = socket_load,
1882 .kill = socket_kill,
1884 .coldplug = socket_coldplug,
1886 .dump = socket_dump,
1888 .start = socket_start,
1889 .stop = socket_stop,
1891 .serialize = socket_serialize,
1892 .deserialize_item = socket_deserialize_item,
1894 .active_state = socket_active_state,
1895 .sub_state_to_string = socket_sub_state_to_string,
1897 .check_gc = socket_check_gc,
1899 .fd_event = socket_fd_event,
1900 .sigchld_event = socket_sigchld_event,
1901 .timer_event = socket_timer_event,
1903 .reset_failed = socket_reset_failed,
1905 .bus_interface = "org.freedesktop.systemd1.Socket",
1906 .bus_message_handler = bus_socket_message_handler,
1907 .bus_invalidating_properties = bus_socket_invalidating_properties