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 Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/types.h>
27 #include <sys/epoll.h>
29 #include <arpa/inet.h>
30 #include <netinet/tcp.h>
32 #include <sys/xattr.h>
36 #include "load-dropin.h"
37 #include "load-fragment.h"
40 #include "path-util.h"
41 #include "unit-name.h"
42 #include "unit-printf.h"
46 #include "exit-status.h"
48 #include "smack-util.h"
50 #include "bus-error.h"
51 #include "dbus-socket.h"
55 static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
56 [SOCKET_DEAD] = UNIT_INACTIVE,
57 [SOCKET_START_PRE] = UNIT_ACTIVATING,
58 [SOCKET_START_CHOWN] = UNIT_ACTIVATING,
59 [SOCKET_START_POST] = UNIT_ACTIVATING,
60 [SOCKET_LISTENING] = UNIT_ACTIVE,
61 [SOCKET_RUNNING] = UNIT_ACTIVE,
62 [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
63 [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
64 [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
65 [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
66 [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
67 [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
68 [SOCKET_FAILED] = UNIT_FAILED
71 static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
72 static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
74 static void socket_init(Unit *u) {
75 Socket *s = SOCKET(u);
78 assert(u->load_state == UNIT_STUB);
80 s->backlog = SOMAXCONN;
81 s->timeout_usec = u->manager->default_timeout_start_usec;
82 s->directory_mode = 0755;
83 s->socket_mode = 0666;
85 s->max_connections = 64;
92 s->exec_context.std_output = u->manager->default_std_output;
93 s->exec_context.std_error = u->manager->default_std_error;
95 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
98 static void socket_unwatch_control_pid(Socket *s) {
101 if (s->control_pid <= 0)
104 unit_unwatch_pid(UNIT(s), s->control_pid);
108 void socket_free_ports(Socket *s) {
113 while ((p = s->ports)) {
114 LIST_REMOVE(port, s->ports, p);
116 sd_event_source_unref(p->event_source);
124 static void socket_done(Unit *u) {
125 Socket *s = SOCKET(u);
129 socket_free_ports(s);
131 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
132 exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
133 s->control_command = NULL;
135 socket_unwatch_control_pid(s);
137 unit_ref_unset(&s->service);
139 free(s->tcp_congestion);
140 s->tcp_congestion = NULL;
142 free(s->bind_to_device);
143 s->bind_to_device = NULL;
146 free(s->smack_ip_in);
147 free(s->smack_ip_out);
149 strv_free(s->symlinks);
154 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
157 static int socket_arm_timer(Socket *s) {
162 if (s->timeout_usec <= 0) {
163 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
167 if (s->timer_event_source) {
168 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + s->timeout_usec);
172 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
175 return sd_event_add_time(
176 UNIT(s)->manager->event,
177 &s->timer_event_source,
179 now(CLOCK_MONOTONIC) + s->timeout_usec, 0,
180 socket_dispatch_timer, s);
183 static int socket_instantiate_service(Socket *s) {
184 _cleanup_free_ char *prefix = NULL;
185 _cleanup_free_ char *name = NULL;
191 /* This fills in s->service if it isn't filled in yet. For
192 * Accept=yes sockets we create the next connection service
193 * here. For Accept=no this is mostly a NOP since the service
194 * is figured out at load time anyway. */
196 if (UNIT_DEREF(s->service))
201 prefix = unit_name_to_prefix(UNIT(s)->id);
205 if (asprintf(&name, "%s@%u.service", prefix, s->n_accepted) < 0)
208 r = manager_load_unit(UNIT(s)->manager, name, NULL, NULL, &u);
212 #ifdef HAVE_SYSV_COMPAT
213 if (SERVICE(u)->is_sysv) {
214 log_error("Using SysV services for socket activation is not supported. Refusing.");
220 unit_ref_set(&s->service, u);
222 return unit_add_two_dependencies(UNIT(s), UNIT_BEFORE, UNIT_TRIGGERS, u, false);
225 static bool have_non_accept_socket(Socket *s) {
233 LIST_FOREACH(port, p, s->ports) {
235 if (p->type != SOCKET_SOCKET)
238 if (!socket_address_can_accept(&p->address))
245 static int socket_add_mount_links(Socket *s) {
251 LIST_FOREACH(port, p, s->ports) {
252 const char *path = NULL;
254 if (p->type == SOCKET_SOCKET)
255 path = socket_address_get_path(&p->address);
256 else if (p->type == SOCKET_FIFO || p->type == SOCKET_SPECIAL)
262 r = unit_require_mounts_for(UNIT(s), path);
270 static int socket_add_device_link(Socket *s) {
275 if (!s->bind_to_device || streq(s->bind_to_device, "lo"))
278 t = strappenda("/sys/subsystem/net/devices/", s->bind_to_device);
279 return unit_add_node_link(UNIT(s), t, false);
282 static int socket_add_default_dependencies(Socket *s) {
286 r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true);
290 if (UNIT(s)->manager->running_as == SYSTEMD_SYSTEM) {
291 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true);
296 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
299 _pure_ static bool socket_has_exec(Socket *s) {
303 for (i = 0; i < _SOCKET_EXEC_COMMAND_MAX; i++)
304 if (s->exec_command[i])
310 static int socket_add_extras(Socket *s) {
316 if (have_non_accept_socket(s)) {
318 if (!UNIT_DEREF(s->service)) {
321 r = unit_load_related_unit(u, ".service", &x);
325 unit_ref_set(&s->service, x);
328 r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, UNIT_DEREF(s->service), true);
333 r = socket_add_mount_links(s);
337 r = socket_add_device_link(s);
341 r = unit_patch_contexts(u);
345 if (socket_has_exec(s)) {
346 r = unit_add_exec_dependencies(u, &s->exec_context);
350 r = unit_add_default_slice(u, &s->cgroup_context);
355 if (u->default_dependencies) {
356 r = socket_add_default_dependencies(s);
364 static const char *socket_find_symlink_target(Socket *s) {
365 const char *found = NULL;
368 LIST_FOREACH(port, p, s->ports) {
369 const char *f = NULL;
378 if (p->address.sockaddr.un.sun_path[0] != 0)
379 f = p->address.sockaddr.un.sun_path;
397 static int socket_verify(Socket *s) {
400 if (UNIT(s)->load_state != UNIT_LOADED)
404 log_error_unit(UNIT(s)->id, "%s lacks Listen setting. Refusing.", UNIT(s)->id);
408 if (s->accept && have_non_accept_socket(s)) {
409 log_error_unit(UNIT(s)->id, "%s configured for accepting sockets, but sockets are non-accepting. Refusing.",
414 if (s->accept && s->max_connections <= 0) {
415 log_error_unit(UNIT(s)->id, "%s's MaxConnection setting too small. Refusing.", UNIT(s)->id);
419 if (s->accept && UNIT_DEREF(s->service)) {
420 log_error_unit(UNIT(s)->id, "Explicit service configuration for accepting sockets not supported on %s. Refusing.", UNIT(s)->id);
424 if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
425 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
429 if (!strv_isempty(s->symlinks) && !socket_find_symlink_target(s)) {
430 log_error_unit(UNIT(s)->id, "%s has symlinks set but none or more than one node in the file system. Refusing.", UNIT(s)->id);
437 static int socket_load(Unit *u) {
438 Socket *s = SOCKET(u);
442 assert(u->load_state == UNIT_STUB);
444 r = unit_load_fragment_and_dropin(u);
448 if (u->load_state == UNIT_LOADED) {
449 /* This is a new unit? Then let's add in some extras */
450 r = socket_add_extras(s);
455 return socket_verify(s);
458 _const_ static const char* listen_lookup(int family, int type) {
460 if (family == AF_NETLINK)
461 return "ListenNetlink";
463 if (type == SOCK_STREAM)
464 return "ListenStream";
465 else if (type == SOCK_DGRAM)
466 return "ListenDatagram";
467 else if (type == SOCK_SEQPACKET)
468 return "ListenSequentialPacket";
470 assert_not_reached("Unknown socket type");
474 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
476 Socket *s = SOCKET(u);
483 prefix2 = strappenda(prefix, "\t");
486 "%sSocket State: %s\n"
488 "%sBindIPv6Only: %s\n"
490 "%sSocketMode: %04o\n"
491 "%sDirectoryMode: %04o\n"
494 "%sTransparent: %s\n"
496 "%sPassCredentials: %s\n"
497 "%sPassSecurity: %s\n"
498 "%sTCPCongestion: %s\n"
499 "%sRemoveOnStop: %s\n",
500 prefix, socket_state_to_string(s->state),
501 prefix, socket_result_to_string(s->result),
502 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
504 prefix, s->socket_mode,
505 prefix, s->directory_mode,
506 prefix, yes_no(s->keep_alive),
507 prefix, yes_no(s->free_bind),
508 prefix, yes_no(s->transparent),
509 prefix, yes_no(s->broadcast),
510 prefix, yes_no(s->pass_cred),
511 prefix, yes_no(s->pass_sec),
512 prefix, strna(s->tcp_congestion),
513 prefix, yes_no(s->remove_on_stop));
515 if (s->control_pid > 0)
517 "%sControl PID: "PID_FMT"\n",
518 prefix, s->control_pid);
520 if (s->bind_to_device)
522 "%sBindToDevice: %s\n",
523 prefix, s->bind_to_device);
528 "%sNConnections: %u\n"
529 "%sMaxConnections: %u\n",
530 prefix, s->n_accepted,
531 prefix, s->n_connections,
532 prefix, s->max_connections);
534 if (s->priority >= 0)
537 prefix, s->priority);
539 if (s->receive_buffer > 0)
541 "%sReceiveBuffer: %zu\n",
542 prefix, s->receive_buffer);
544 if (s->send_buffer > 0)
546 "%sSendBuffer: %zu\n",
547 prefix, s->send_buffer);
559 if (s->pipe_size > 0)
562 prefix, s->pipe_size);
569 if (s->mq_maxmsg > 0)
571 "%sMessageQueueMaxMessages: %li\n",
572 prefix, s->mq_maxmsg);
574 if (s->mq_msgsize > 0)
576 "%sMessageQueueMessageSize: %li\n",
577 prefix, s->mq_msgsize);
582 prefix, yes_no(s->reuse_port));
586 "%sSmackLabel: %s\n",
591 "%sSmackLabelIPIn: %s\n",
592 prefix, s->smack_ip_in);
596 "%sSmackLabelIPOut: %s\n",
597 prefix, s->smack_ip_out);
599 if (!isempty(s->user) || !isempty(s->group))
602 "%sOwnerGroup: %s\n",
603 prefix, strna(s->user),
604 prefix, strna(s->group));
606 LIST_FOREACH(port, p, s->ports) {
608 if (p->type == SOCKET_SOCKET) {
613 if ((r = socket_address_print(&p->address, &k)) < 0)
618 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type), t);
620 } else if (p->type == SOCKET_SPECIAL)
621 fprintf(f, "%sListenSpecial: %s\n", prefix, p->path);
622 else if (p->type == SOCKET_MQUEUE)
623 fprintf(f, "%sListenMessageQueue: %s\n", prefix, p->path);
625 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
628 exec_context_dump(&s->exec_context, f, prefix);
629 kill_context_dump(&s->kill_context, f, prefix);
631 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
632 if (!s->exec_command[c])
635 fprintf(f, "%s-> %s:\n",
636 prefix, socket_exec_command_to_string(c));
638 exec_command_dump_list(s->exec_command[c], f, prefix2);
642 static int instance_from_socket(int fd, unsigned nr, char **instance) {
645 union sockaddr_union local, remote;
651 if (getsockname(fd, &local.sa, &l) < 0)
655 if (getpeername(fd, &remote.sa, &l) < 0)
658 switch (local.sa.sa_family) {
662 a = ntohl(local.in.sin_addr.s_addr),
663 b = ntohl(remote.in.sin_addr.s_addr);
666 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
668 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
669 ntohs(local.in.sin_port),
670 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
671 ntohs(remote.in.sin_port)) < 0)
678 static const unsigned char ipv4_prefix[] = {
679 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
682 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
683 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
685 *a = local.in6.sin6_addr.s6_addr+12,
686 *b = remote.in6.sin6_addr.s6_addr+12;
689 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
691 a[0], a[1], a[2], a[3],
692 ntohs(local.in6.sin6_port),
693 b[0], b[1], b[2], b[3],
694 ntohs(remote.in6.sin6_port)) < 0)
697 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
702 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
703 ntohs(local.in6.sin6_port),
704 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
705 ntohs(remote.in6.sin6_port)) < 0)
716 k = getpeercred(fd, &ucred);
719 "%u-"PID_FMT"-"UID_FMT,
720 nr, ucred.pid, ucred.uid) < 0)
722 } else if (k == -ENODATA) {
723 /* This handles the case where somebody is
724 * connecting from another pid/uid namespace
725 * (e.g. from outside of our container). */
737 assert_not_reached("Unhandled socket type.");
744 static void socket_close_fds(Socket *s) {
750 LIST_FOREACH(port, p, s->ports) {
752 p->event_source = sd_event_source_unref(p->event_source);
757 p->fd = safe_close(p->fd);
759 /* One little note: we should normally not delete any
760 * sockets in the file system here! After all some
761 * other process we spawned might still have a
762 * reference of this fd and wants to continue to use
763 * it. Therefore we delete sockets in the file system
764 * before we create a new one, not after we stopped
767 if (s->remove_on_stop) {
779 socket_address_unlink(&p->address);
788 if (s->remove_on_stop)
789 STRV_FOREACH(i, s->symlinks)
793 static void socket_apply_socket_options(Socket *s, int fd) {
798 int b = s->keep_alive;
799 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
800 log_warning_unit(UNIT(s)->id, "SO_KEEPALIVE failed: %m");
805 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)) < 0)
806 log_warning_unit(UNIT(s)->id, "SO_BROADCAST failed: %m");
811 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0)
812 log_warning_unit(UNIT(s)->id, "SO_PASSCRED failed: %m");
817 if (setsockopt(fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one)) < 0)
818 log_warning_unit(UNIT(s)->id, "SO_PASSSEC failed: %m");
821 if (s->priority >= 0)
822 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
823 log_warning_unit(UNIT(s)->id, "SO_PRIORITY failed: %m");
825 if (s->receive_buffer > 0) {
826 int value = (int) s->receive_buffer;
828 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
830 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
831 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
832 log_warning_unit(UNIT(s)->id, "SO_RCVBUF failed: %m");
835 if (s->send_buffer > 0) {
836 int value = (int) s->send_buffer;
837 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
838 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
839 log_warning_unit(UNIT(s)->id, "SO_SNDBUF failed: %m");
843 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
844 log_warning_unit(UNIT(s)->id, "SO_MARK failed: %m");
847 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
848 log_warning_unit(UNIT(s)->id, "IP_TOS failed: %m");
850 if (s->ip_ttl >= 0) {
853 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
855 if (socket_ipv6_is_supported())
856 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
859 errno = EAFNOSUPPORT;
863 log_warning_unit(UNIT(s)->id,
864 "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
867 if (s->tcp_congestion)
868 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
869 log_warning_unit(UNIT(s)->id, "TCP_CONGESTION failed: %m");
872 int b = s->reuse_port;
873 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &b, sizeof(b)) < 0)
874 log_warning_unit(UNIT(s)->id, "SO_REUSEPORT failed: %m");
878 if (smack_label_ip_in_fd(fd, s->smack_ip_in) < 0)
879 log_error_unit(UNIT(s)->id, "smack_label_ip_in_fd: %m");
882 if (smack_label_ip_out_fd(fd, s->smack_ip_out) < 0)
883 log_error_unit(UNIT(s)->id, "smack_label_ip_out_fd: %m");
886 static void socket_apply_fifo_options(Socket *s, int fd) {
890 if (s->pipe_size > 0)
891 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
892 log_warning_unit(UNIT(s)->id,
896 if (smack_label_fd(fd, s->smack) < 0)
897 log_error_unit(UNIT(s)->id, "smack_label_fd: %m");
900 static int fifo_address_create(
902 mode_t directory_mode,
913 mkdir_parents_label(path, directory_mode);
915 r = label_context_set(path, S_IFIFO);
919 /* Enforce the right access mode for the fifo */
920 old_mask = umask(~ socket_mode);
922 /* Include the original umask in our mask */
923 umask(~socket_mode | old_mask);
925 r = mkfifo(path, socket_mode);
928 if (r < 0 && errno != EEXIST) {
933 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
938 label_context_clear();
940 if (fstat(fd, &st) < 0) {
945 if (!S_ISFIFO(st.st_mode) ||
946 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
947 st.st_uid != getuid() ||
948 st.st_gid != getgid()) {
958 label_context_clear();
964 static int special_address_create(
974 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
980 if (fstat(fd, &st) < 0) {
985 /* Check whether this is a /proc, /sys or /dev file or char device */
986 if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
1000 static int mq_address_create(
1010 struct mq_attr _attr, *attr = NULL;
1015 if (maxmsg > 0 && msgsize > 0) {
1017 _attr.mq_flags = O_NONBLOCK;
1018 _attr.mq_maxmsg = maxmsg;
1019 _attr.mq_msgsize = msgsize;
1023 /* Enforce the right access mode for the mq */
1024 old_mask = umask(~ mq_mode);
1026 /* Include the original umask in our mask */
1027 umask(~mq_mode | old_mask);
1028 fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
1036 if (fstat(fd, &st) < 0) {
1041 if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
1042 st.st_uid != getuid() ||
1043 st.st_gid != getgid()) {
1057 static int socket_symlink(Socket *s) {
1063 p = socket_find_symlink_target(s);
1067 STRV_FOREACH(i, s->symlinks)
1073 static int socket_open_fds(Socket *s) {
1077 bool know_label = false;
1081 LIST_FOREACH(port, p, s->ports) {
1086 if (p->type == SOCKET_SOCKET) {
1090 r = socket_instantiate_service(s);
1094 if (UNIT_ISSET(s->service) &&
1095 SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]) {
1096 r = label_get_create_label_from_exe(SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]->path, &label);
1097 if (r < 0 && r != -EPERM)
1104 r = socket_address_listen(
1106 SOCK_CLOEXEC|SOCK_NONBLOCK,
1119 socket_apply_socket_options(s, p->fd);
1122 } else if (p->type == SOCKET_SPECIAL) {
1124 r = special_address_create(
1130 } else if (p->type == SOCKET_FIFO) {
1132 r = fifo_address_create(
1140 socket_apply_fifo_options(s, p->fd);
1143 } else if (p->type == SOCKET_MQUEUE) {
1145 r = mq_address_create(
1154 assert_not_reached("Unknown port type");
1161 socket_close_fds(s);
1166 static void socket_unwatch_fds(Socket *s) {
1172 LIST_FOREACH(port, p, s->ports) {
1176 if (!p->event_source)
1179 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
1181 log_debug_unit(UNIT(s)->id, "Failed to disable event source.");
1185 static int socket_watch_fds(Socket *s) {
1191 LIST_FOREACH(port, p, s->ports) {
1195 if (p->event_source)
1196 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
1198 r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
1201 log_warning_unit(UNIT(s)->id, "Failed to watch listening fds: %s", strerror(-r));
1209 socket_unwatch_fds(s);
1213 static void socket_set_state(Socket *s, SocketState state) {
1214 SocketState old_state;
1217 old_state = s->state;
1225 SOCKET_STOP_PRE_SIGTERM,
1226 SOCKET_STOP_PRE_SIGKILL,
1228 SOCKET_FINAL_SIGTERM,
1229 SOCKET_FINAL_SIGKILL)) {
1231 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1232 socket_unwatch_control_pid(s);
1233 s->control_command = NULL;
1234 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1237 if (state != SOCKET_LISTENING)
1238 socket_unwatch_fds(s);
1246 SOCKET_STOP_PRE_SIGTERM,
1247 SOCKET_STOP_PRE_SIGKILL))
1248 socket_close_fds(s);
1250 if (state != old_state)
1251 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s",
1252 UNIT(s)->id, socket_state_to_string(old_state), socket_state_to_string(state));
1254 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
1257 static int socket_coldplug(Unit *u) {
1258 Socket *s = SOCKET(u);
1262 assert(s->state == SOCKET_DEAD);
1264 if (s->deserialized_state == s->state)
1267 if (IN_SET(s->deserialized_state,
1272 SOCKET_STOP_PRE_SIGTERM,
1273 SOCKET_STOP_PRE_SIGKILL,
1275 SOCKET_FINAL_SIGTERM,
1276 SOCKET_FINAL_SIGKILL)) {
1278 if (s->control_pid <= 0)
1281 r = unit_watch_pid(UNIT(s), s->control_pid);
1285 r = socket_arm_timer(s);
1290 if (IN_SET(s->deserialized_state,
1296 SOCKET_STOP_PRE_SIGTERM,
1297 SOCKET_STOP_PRE_SIGKILL)) {
1298 r = socket_open_fds(s);
1303 if (s->deserialized_state == SOCKET_LISTENING) {
1304 r = socket_watch_fds(s);
1309 socket_set_state(s, s->deserialized_state);
1313 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
1314 _cleanup_free_ char **argv = NULL;
1322 unit_realize_cgroup(UNIT(s));
1324 r = unit_setup_exec_runtime(UNIT(s));
1328 r = socket_arm_timer(s);
1332 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1340 UNIT(s)->manager->environment,
1344 UNIT(s)->manager->confirm_spawn,
1345 UNIT(s)->manager->cgroup_supported,
1346 UNIT(s)->cgroup_path,
1347 manager_get_runtime_prefix(UNIT(s)->manager),
1354 r = unit_watch_pid(UNIT(s), pid);
1356 /* FIXME: we need to do something here */
1363 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1367 static int socket_chown(Socket *s, pid_t *_pid) {
1371 r = socket_arm_timer(s);
1375 /* We have to resolve the user names out-of-process, hence
1376 * let's fork here. It's messy, but well, what can we do? */
1384 uid_t uid = (uid_t) -1;
1385 gid_t gid = (gid_t) -1;
1388 default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE, -1);
1389 ignore_signals(SIGPIPE, -1);
1392 if (!isempty(s->user)) {
1393 const char *user = s->user;
1395 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1402 if (!isempty(s->group)) {
1403 const char *group = s->group;
1405 r = get_group_creds(&group, &gid);
1412 LIST_FOREACH(port, p, s->ports) {
1413 const char *path = NULL;
1415 if (p->type == SOCKET_SOCKET)
1416 path = socket_address_get_path(&p->address);
1417 else if (p->type == SOCKET_FIFO)
1423 if (chown(path, uid, gid) < 0) {
1434 log_error("Failed to chown socket at step %s: %s", exit_status_to_string(ret, EXIT_STATUS_SYSTEMD), strerror(-r));
1439 r = unit_watch_pid(UNIT(s), pid);
1447 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1451 static void socket_enter_dead(Socket *s, SocketResult f) {
1454 if (f != SOCKET_SUCCESS)
1457 exec_runtime_destroy(s->exec_runtime);
1458 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1460 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1462 socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
1465 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
1467 static void socket_enter_stop_post(Socket *s, SocketResult f) {
1471 if (f != SOCKET_SUCCESS)
1474 socket_unwatch_control_pid(s);
1475 s->control_command_id = SOCKET_EXEC_STOP_POST;
1476 s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
1478 if (s->control_command) {
1479 r = socket_spawn(s, s->control_command, &s->control_pid);
1483 socket_set_state(s, SOCKET_STOP_POST);
1485 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
1490 log_warning_unit(UNIT(s)->id,
1491 "%s failed to run 'stop-post' task: %s",
1492 UNIT(s)->id, strerror(-r));
1493 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1496 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
1501 if (f != SOCKET_SUCCESS)
1504 r = unit_kill_context(
1507 state != SOCKET_STOP_PRE_SIGTERM && state != SOCKET_FINAL_SIGTERM,
1515 r = socket_arm_timer(s);
1519 socket_set_state(s, state);
1520 } else if (state == SOCKET_STOP_PRE_SIGTERM)
1521 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
1522 else if (state == SOCKET_STOP_PRE_SIGKILL)
1523 socket_enter_stop_post(s, SOCKET_SUCCESS);
1524 else if (state == SOCKET_FINAL_SIGTERM)
1525 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
1527 socket_enter_dead(s, SOCKET_SUCCESS);
1532 log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1534 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1535 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1537 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1540 static void socket_enter_stop_pre(Socket *s, SocketResult f) {
1544 if (f != SOCKET_SUCCESS)
1547 socket_unwatch_control_pid(s);
1548 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1549 s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
1551 if (s->control_command) {
1552 r = socket_spawn(s, s->control_command, &s->control_pid);
1556 socket_set_state(s, SOCKET_STOP_PRE);
1558 socket_enter_stop_post(s, SOCKET_SUCCESS);
1563 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-pre' task: %s", UNIT(s)->id, strerror(-r));
1564 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1567 static void socket_enter_listening(Socket *s) {
1571 r = socket_watch_fds(s);
1573 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1577 socket_set_state(s, SOCKET_LISTENING);
1581 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1584 static void socket_enter_start_post(Socket *s) {
1588 socket_unwatch_control_pid(s);
1589 s->control_command_id = SOCKET_EXEC_START_POST;
1590 s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
1592 if (s->control_command) {
1593 r = socket_spawn(s, s->control_command, &s->control_pid);
1595 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1599 socket_set_state(s, SOCKET_START_POST);
1601 socket_enter_listening(s);
1606 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1609 static void socket_enter_start_chown(Socket *s) {
1614 r = socket_open_fds(s);
1616 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1620 if (!isempty(s->user) || !isempty(s->group)) {
1622 socket_unwatch_control_pid(s);
1623 s->control_command_id = SOCKET_EXEC_START_CHOWN;
1624 s->control_command = NULL;
1626 r = socket_chown(s, &s->control_pid);
1628 log_warning_unit(UNIT(s)->id, "%s failed to fork 'start-chown' task: %s", UNIT(s)->id, strerror(-r));
1632 socket_set_state(s, SOCKET_START_CHOWN);
1634 socket_enter_start_post(s);
1639 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1642 static void socket_enter_start_pre(Socket *s) {
1646 socket_unwatch_control_pid(s);
1647 s->control_command_id = SOCKET_EXEC_START_PRE;
1648 s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
1650 if (s->control_command) {
1651 r = socket_spawn(s, s->control_command, &s->control_pid);
1653 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1657 socket_set_state(s, SOCKET_START_PRE);
1659 socket_enter_start_chown(s);
1664 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1667 static void socket_enter_running(Socket *s, int cfd) {
1668 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1673 /* We don't take connections anymore if we are supposed to
1674 * shut down anyway */
1675 if (unit_stop_pending(UNIT(s))) {
1677 log_debug_unit(UNIT(s)->id, "Suppressing connection request on %s since unit stop is scheduled.", UNIT(s)->id);
1682 /* Flush all sockets by closing and reopening them */
1683 socket_close_fds(s);
1685 r = socket_open_fds(s);
1687 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1688 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1692 r = socket_watch_fds(s);
1694 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1695 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1705 bool pending = false;
1707 /* If there's already a start pending don't bother to
1709 SET_FOREACH(other, UNIT(s)->dependencies[UNIT_TRIGGERS], i)
1710 if (unit_active_or_pending(other)) {
1716 if (!UNIT_ISSET(s->service)) {
1717 log_error_unit(UNIT(s)->id, "%s: service to activate vanished, refusing activation.", UNIT(s)->id);
1722 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, true, &error, NULL);
1727 socket_set_state(s, SOCKET_RUNNING);
1729 _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
1732 if (s->n_connections >= s->max_connections) {
1733 log_warning_unit(UNIT(s)->id, "%s: Too many incoming connections (%u)", UNIT(s)->id, s->n_connections);
1738 r = socket_instantiate_service(s);
1742 r = instance_from_socket(cfd, s->n_accepted, &instance);
1747 /* ENOTCONN is legitimate if TCP RST was received.
1748 * This connection is over, but the socket unit lives on. */
1753 prefix = unit_name_to_prefix(UNIT(s)->id);
1759 name = unit_name_build(prefix, instance, ".service");
1765 r = unit_add_name(UNIT_DEREF(s->service), name);
1769 service = SERVICE(UNIT_DEREF(s->service));
1770 unit_ref_unset(&s->service);
1773 UNIT(service)->no_gc = false;
1775 unit_choose_id(UNIT(service), name);
1777 r = service_set_socket_fd(service, cfd, s);
1782 s->n_connections ++;
1784 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL);
1788 /* Notify clients about changed counters */
1789 unit_add_to_dbus_queue(UNIT(s));
1795 log_warning_unit(UNIT(s)->id, "%s failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
1796 UNIT(s)->id, cfd >= 0 ? "template" : "non-template",
1797 bus_error_message(&error, r));
1799 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1803 static void socket_run_next(Socket *s) {
1807 assert(s->control_command);
1808 assert(s->control_command->command_next);
1810 socket_unwatch_control_pid(s);
1812 s->control_command = s->control_command->command_next;
1814 r = socket_spawn(s, s->control_command, &s->control_pid);
1821 log_warning_unit(UNIT(s)->id, "%s failed to run next task: %s", UNIT(s)->id, strerror(-r));
1823 if (s->state == SOCKET_START_POST)
1824 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1825 else if (s->state == SOCKET_STOP_POST)
1826 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1828 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1831 static int socket_start(Unit *u) {
1832 Socket *s = SOCKET(u);
1836 /* We cannot fulfill this request right now, try again later
1838 if (IN_SET(s->state,
1840 SOCKET_STOP_PRE_SIGKILL,
1841 SOCKET_STOP_PRE_SIGTERM,
1843 SOCKET_FINAL_SIGTERM,
1844 SOCKET_FINAL_SIGKILL))
1847 /* Already on it! */
1848 if (IN_SET(s->state,
1854 /* Cannot run this without the service being around */
1855 if (UNIT_ISSET(s->service)) {
1858 service = SERVICE(UNIT_DEREF(s->service));
1860 if (UNIT(service)->load_state != UNIT_LOADED) {
1861 log_error_unit(u->id, "Socket service %s not loaded, refusing.", UNIT(service)->id);
1865 /* If the service is already active we cannot start the
1867 if (service->state != SERVICE_DEAD &&
1868 service->state != SERVICE_FAILED &&
1869 service->state != SERVICE_AUTO_RESTART) {
1870 log_error_unit(u->id, "Socket service %s already active, refusing.", UNIT(service)->id);
1874 #ifdef HAVE_SYSV_COMPAT
1875 if (service->is_sysv) {
1876 log_error_unit(u->id, "Using SysV services for socket activation is not supported. Refusing.");
1882 assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1884 s->result = SOCKET_SUCCESS;
1885 socket_enter_start_pre(s);
1890 static int socket_stop(Unit *u) {
1891 Socket *s = SOCKET(u);
1896 if (IN_SET(s->state,
1898 SOCKET_STOP_PRE_SIGTERM,
1899 SOCKET_STOP_PRE_SIGKILL,
1901 SOCKET_FINAL_SIGTERM,
1902 SOCKET_FINAL_SIGKILL))
1905 /* If there's already something running we go directly into
1907 if (IN_SET(s->state,
1910 SOCKET_START_POST)) {
1911 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
1915 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1917 socket_enter_stop_pre(s, SOCKET_SUCCESS);
1921 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1922 Socket *s = SOCKET(u);
1930 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1931 unit_serialize_item(u, f, "result", socket_result_to_string(s->result));
1932 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1934 if (s->control_pid > 0)
1935 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
1937 if (s->control_command_id >= 0)
1938 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1940 LIST_FOREACH(port, p, s->ports) {
1946 copy = fdset_put_dup(fds, p->fd);
1950 if (p->type == SOCKET_SOCKET) {
1951 _cleanup_free_ char *t = NULL;
1953 r = socket_address_print(&p->address, &t);
1957 if (socket_address_family(&p->address) == AF_NETLINK)
1958 unit_serialize_item_format(u, f, "netlink", "%i %s", copy, t);
1960 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1962 } else if (p->type == SOCKET_SPECIAL)
1963 unit_serialize_item_format(u, f, "special", "%i %s", copy, p->path);
1964 else if (p->type == SOCKET_MQUEUE)
1965 unit_serialize_item_format(u, f, "mqueue", "%i %s", copy, p->path);
1967 assert(p->type == SOCKET_FIFO);
1968 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1975 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1976 Socket *s = SOCKET(u);
1982 if (streq(key, "state")) {
1985 state = socket_state_from_string(value);
1987 log_debug_unit(u->id, "Failed to parse state value %s", value);
1989 s->deserialized_state = state;
1990 } else if (streq(key, "result")) {
1993 f = socket_result_from_string(value);
1995 log_debug_unit(u->id, "Failed to parse result value %s", value);
1996 else if (f != SOCKET_SUCCESS)
1999 } else if (streq(key, "n-accepted")) {
2002 if (safe_atou(value, &k) < 0)
2003 log_debug_unit(u->id, "Failed to parse n-accepted value %s", value);
2006 } else if (streq(key, "control-pid")) {
2009 if (parse_pid(value, &pid) < 0)
2010 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
2012 s->control_pid = pid;
2013 } else if (streq(key, "control-command")) {
2014 SocketExecCommand id;
2016 id = socket_exec_command_from_string(value);
2018 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
2020 s->control_command_id = id;
2021 s->control_command = s->exec_command[id];
2023 } else if (streq(key, "fifo")) {
2027 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2028 log_debug_unit(u->id, "Failed to parse fifo value %s", value);
2031 LIST_FOREACH(port, p, s->ports)
2032 if (p->type == SOCKET_FIFO &&
2033 streq_ptr(p->path, value+skip))
2038 p->fd = fdset_remove(fds, fd);
2042 } else if (streq(key, "special")) {
2046 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2047 log_debug_unit(u->id, "Failed to parse special value %s", value);
2050 LIST_FOREACH(port, p, s->ports)
2051 if (p->type == SOCKET_SPECIAL &&
2052 streq_ptr(p->path, value+skip))
2057 p->fd = fdset_remove(fds, fd);
2061 } else if (streq(key, "mqueue")) {
2065 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2066 log_debug_unit(u->id, "Failed to parse mqueue value %s", value);
2069 LIST_FOREACH(port, p, s->ports)
2070 if (p->type == SOCKET_MQUEUE &&
2071 streq_ptr(p->path, value+skip))
2076 p->fd = fdset_remove(fds, fd);
2080 } else if (streq(key, "socket")) {
2081 int fd, type, skip = 0;
2084 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
2085 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2088 LIST_FOREACH(port, p, s->ports)
2089 if (socket_address_is(&p->address, value+skip, type))
2094 p->fd = fdset_remove(fds, fd);
2098 } else if (streq(key, "netlink")) {
2102 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2103 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2106 LIST_FOREACH(port, p, s->ports)
2107 if (socket_address_is_netlink(&p->address, value+skip))
2112 p->fd = fdset_remove(fds, fd);
2116 log_debug_unit(UNIT(s)->id, "Unknown serialization key '%s'", key);
2121 static int socket_distribute_fds(Unit *u, FDSet *fds) {
2122 Socket *s = SOCKET(u);
2127 LIST_FOREACH(port, p, s->ports) {
2131 if (p->type != SOCKET_SOCKET)
2137 FDSET_FOREACH(fd, fds, i) {
2138 if (socket_address_matches_fd(&p->address, fd)) {
2139 p->fd = fdset_remove(fds, fd);
2140 s->deserialized_state = SOCKET_LISTENING;
2149 _pure_ static UnitActiveState socket_active_state(Unit *u) {
2152 return state_translation_table[SOCKET(u)->state];
2155 _pure_ static const char *socket_sub_state_to_string(Unit *u) {
2158 return socket_state_to_string(SOCKET(u)->state);
2161 const char* socket_port_type_to_string(SocketPort *p) {
2169 switch (p->address.type) {
2177 case SOCK_SEQPACKET:
2178 return "SequentialPacket";
2181 if (socket_address_family(&p->address) == AF_NETLINK)
2188 case SOCKET_SPECIAL:
2192 return "MessageQueue";
2202 _pure_ static bool socket_check_gc(Unit *u) {
2203 Socket *s = SOCKET(u);
2207 return s->n_connections > 0;
2210 static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2211 SocketPort *p = userdata;
2217 if (p->socket->state != SOCKET_LISTENING)
2220 log_debug_unit(UNIT(p->socket)->id, "Incoming traffic on %s", UNIT(p->socket)->id);
2222 if (revents != EPOLLIN) {
2224 if (revents & EPOLLHUP)
2225 log_error_unit(UNIT(p->socket)->id, "%s: Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.",
2226 UNIT(p->socket)->id);
2228 log_error_unit(UNIT(p->socket)->id, "%s: Got unexpected poll event (0x%x) on socket.",
2229 UNIT(p->socket)->id, revents);
2234 if (p->socket->accept &&
2235 p->type == SOCKET_SOCKET &&
2236 socket_address_can_accept(&p->address)) {
2240 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK);
2246 log_error_unit(UNIT(p->socket)->id,
2247 "Failed to accept socket: %m");
2254 socket_apply_socket_options(p->socket, cfd);
2257 socket_enter_running(p->socket, cfd);
2261 socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
2265 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2266 Socket *s = SOCKET(u);
2272 if (pid != s->control_pid)
2277 if (is_clean_exit(code, status, NULL))
2279 else if (code == CLD_EXITED)
2280 f = SOCKET_FAILURE_EXIT_CODE;
2281 else if (code == CLD_KILLED)
2282 f = SOCKET_FAILURE_SIGNAL;
2283 else if (code == CLD_DUMPED)
2284 f = SOCKET_FAILURE_CORE_DUMP;
2286 assert_not_reached("Unknown sigchld code");
2288 if (s->control_command) {
2289 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2291 if (s->control_command->ignore)
2295 log_full_unit(f == SOCKET_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2297 "%s control process exited, code=%s status=%i",
2298 u->id, sigchld_code_to_string(code), status);
2300 if (f != SOCKET_SUCCESS)
2303 if (s->control_command &&
2304 s->control_command->command_next &&
2305 f == SOCKET_SUCCESS) {
2307 log_debug_unit(u->id,
2308 "%s running next command for state %s",
2309 u->id, socket_state_to_string(s->state));
2312 s->control_command = NULL;
2313 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
2315 /* No further commands for this step, so let's figure
2316 * out what to do next */
2318 log_debug_unit(u->id,
2319 "%s got final SIGCHLD for state %s",
2320 u->id, socket_state_to_string(s->state));
2324 case SOCKET_START_PRE:
2325 if (f == SOCKET_SUCCESS)
2326 socket_enter_start_chown(s);
2328 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
2331 case SOCKET_START_CHOWN:
2332 if (f == SOCKET_SUCCESS)
2333 socket_enter_start_post(s);
2335 socket_enter_stop_pre(s, f);
2338 case SOCKET_START_POST:
2339 if (f == SOCKET_SUCCESS)
2340 socket_enter_listening(s);
2342 socket_enter_stop_pre(s, f);
2345 case SOCKET_STOP_PRE:
2346 case SOCKET_STOP_PRE_SIGTERM:
2347 case SOCKET_STOP_PRE_SIGKILL:
2348 socket_enter_stop_post(s, f);
2351 case SOCKET_STOP_POST:
2352 case SOCKET_FINAL_SIGTERM:
2353 case SOCKET_FINAL_SIGKILL:
2354 socket_enter_dead(s, f);
2358 assert_not_reached("Uh, control process died at wrong time.");
2362 /* Notify clients about changed exit status */
2363 unit_add_to_dbus_queue(u);
2366 static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2367 Socket *s = SOCKET(userdata);
2370 assert(s->timer_event_source == source);
2374 case SOCKET_START_PRE:
2375 log_warning_unit(UNIT(s)->id, "%s starting timed out. Terminating.", UNIT(s)->id);
2376 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2379 case SOCKET_START_CHOWN:
2380 case SOCKET_START_POST:
2381 log_warning_unit(UNIT(s)->id, "%s starting timed out. Stopping.", UNIT(s)->id);
2382 socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
2385 case SOCKET_STOP_PRE:
2386 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2387 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2390 case SOCKET_STOP_PRE_SIGTERM:
2391 if (s->kill_context.send_sigkill) {
2392 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Killing.", UNIT(s)->id);
2393 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2395 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2396 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2400 case SOCKET_STOP_PRE_SIGKILL:
2401 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2402 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2405 case SOCKET_STOP_POST:
2406 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Terminating.", UNIT(s)->id);
2407 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2410 case SOCKET_FINAL_SIGTERM:
2411 if (s->kill_context.send_sigkill) {
2412 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Killing.", UNIT(s)->id);
2413 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2415 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2416 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2420 case SOCKET_FINAL_SIGKILL:
2421 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL (2). Entering failed mode.", UNIT(s)->id);
2422 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2426 assert_not_reached("Timeout at wrong time.");
2432 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
2441 /* Called from the service code for requesting our fds */
2444 LIST_FOREACH(port, p, s->ports)
2454 if (!(rfds = new(int, rn_fds)))
2458 LIST_FOREACH(port, p, s->ports)
2462 assert(k == rn_fds);
2470 static void socket_reset_failed(Unit *u) {
2471 Socket *s = SOCKET(u);
2475 if (s->state == SOCKET_FAILED)
2476 socket_set_state(s, SOCKET_DEAD);
2478 s->result = SOCKET_SUCCESS;
2481 static void socket_notify_service_dead(Socket *s, bool failed_permanent) {
2484 /* The service is dead. Dang!
2486 * This is strictly for one-instance-for-all-connections
2489 if (s->state == SOCKET_RUNNING) {
2490 log_debug_unit(UNIT(s)->id, "%s got notified about service death (failed permanently: %s)", UNIT(s)->id, yes_no(failed_permanent));
2491 if (failed_permanent)
2492 socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_FAILED_PERMANENT);
2494 socket_enter_listening(s);
2498 void socket_connection_unref(Socket *s) {
2501 /* The service is dead. Yay!
2503 * This is strictly for one-instance-per-connection
2506 assert(s->n_connections > 0);
2509 log_debug_unit(UNIT(s)->id, "%s: One connection closed, %u left.", UNIT(s)->id, s->n_connections);
2512 static void socket_trigger_notify(Unit *u, Unit *other) {
2513 Socket *s = SOCKET(u);
2519 /* Don't propagate state changes from the service if we are
2520 already down or accepting connections */
2521 if ((s->state != SOCKET_RUNNING &&
2522 s->state != SOCKET_LISTENING) ||
2526 if (other->load_state != UNIT_LOADED ||
2527 other->type != UNIT_SERVICE)
2530 se = SERVICE(other);
2532 if (se->state == SERVICE_FAILED)
2533 socket_notify_service_dead(s, se->result == SERVICE_FAILURE_START_LIMIT);
2535 if (se->state == SERVICE_DEAD ||
2536 se->state == SERVICE_STOP ||
2537 se->state == SERVICE_STOP_SIGTERM ||
2538 se->state == SERVICE_STOP_SIGKILL ||
2539 se->state == SERVICE_STOP_POST ||
2540 se->state == SERVICE_FINAL_SIGTERM ||
2541 se->state == SERVICE_FINAL_SIGKILL ||
2542 se->state == SERVICE_AUTO_RESTART)
2543 socket_notify_service_dead(s, false);
2545 if (se->state == SERVICE_RUNNING)
2546 socket_set_state(s, SOCKET_RUNNING);
2549 static int socket_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2550 return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
2553 static int socket_get_timeout(Unit *u, uint64_t *timeout) {
2554 Socket *s = SOCKET(u);
2557 if (!s->timer_event_source)
2560 r = sd_event_source_get_time(s->timer_event_source, timeout);
2567 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
2568 [SOCKET_DEAD] = "dead",
2569 [SOCKET_START_PRE] = "start-pre",
2570 [SOCKET_START_CHOWN] = "start-chown",
2571 [SOCKET_START_POST] = "start-post",
2572 [SOCKET_LISTENING] = "listening",
2573 [SOCKET_RUNNING] = "running",
2574 [SOCKET_STOP_PRE] = "stop-pre",
2575 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
2576 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
2577 [SOCKET_STOP_POST] = "stop-post",
2578 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
2579 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
2580 [SOCKET_FAILED] = "failed"
2583 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
2585 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
2586 [SOCKET_EXEC_START_PRE] = "StartPre",
2587 [SOCKET_EXEC_START_CHOWN] = "StartChown",
2588 [SOCKET_EXEC_START_POST] = "StartPost",
2589 [SOCKET_EXEC_STOP_PRE] = "StopPre",
2590 [SOCKET_EXEC_STOP_POST] = "StopPost"
2593 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
2595 static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
2596 [SOCKET_SUCCESS] = "success",
2597 [SOCKET_FAILURE_RESOURCES] = "resources",
2598 [SOCKET_FAILURE_TIMEOUT] = "timeout",
2599 [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
2600 [SOCKET_FAILURE_SIGNAL] = "signal",
2601 [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
2602 [SOCKET_FAILURE_SERVICE_FAILED_PERMANENT] = "service-failed-permanent"
2605 DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
2607 const UnitVTable socket_vtable = {
2608 .object_size = sizeof(Socket),
2609 .exec_context_offset = offsetof(Socket, exec_context),
2610 .cgroup_context_offset = offsetof(Socket, cgroup_context),
2611 .kill_context_offset = offsetof(Socket, kill_context),
2612 .exec_runtime_offset = offsetof(Socket, exec_runtime),
2618 .private_section = "Socket",
2620 .init = socket_init,
2621 .done = socket_done,
2622 .load = socket_load,
2624 .coldplug = socket_coldplug,
2626 .dump = socket_dump,
2628 .start = socket_start,
2629 .stop = socket_stop,
2631 .kill = socket_kill,
2633 .get_timeout = socket_get_timeout,
2635 .serialize = socket_serialize,
2636 .deserialize_item = socket_deserialize_item,
2637 .distribute_fds = socket_distribute_fds,
2639 .active_state = socket_active_state,
2640 .sub_state_to_string = socket_sub_state_to_string,
2642 .check_gc = socket_check_gc,
2644 .sigchld_event = socket_sigchld_event,
2646 .trigger_notify = socket_trigger_notify,
2648 .reset_failed = socket_reset_failed,
2650 .bus_interface = "org.freedesktop.systemd1.Socket",
2651 .bus_vtable = bus_socket_vtable,
2652 .bus_set_property = bus_socket_set_property,
2653 .bus_commit_properties = bus_socket_commit_properties,
2655 .status_message_formats = {
2656 /*.starting_stopping = {
2657 [0] = "Starting socket %s...",
2658 [1] = "Stopping socket %s...",
2660 .finished_start_job = {
2661 [JOB_DONE] = "Listening on %s.",
2662 [JOB_FAILED] = "Failed to listen on %s.",
2663 [JOB_DEPENDENCY] = "Dependency failed for %s.",
2664 [JOB_TIMEOUT] = "Timed out starting %s.",
2666 .finished_stop_job = {
2667 [JOB_DONE] = "Closed %s.",
2668 [JOB_FAILED] = "Failed stopping %s.",
2669 [JOB_TIMEOUT] = "Timed out stopping %s.",