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) {
1177 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
1179 log_debug_unit(UNIT(s)->id, "Failed to disable event source.");
1184 static int socket_watch_fds(Socket *s) {
1190 LIST_FOREACH(port, p, s->ports) {
1194 if (p->event_source)
1195 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
1197 r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
1200 log_warning_unit(UNIT(s)->id, "Failed to watch listening fds: %s", strerror(-r));
1208 socket_unwatch_fds(s);
1212 static void socket_set_state(Socket *s, SocketState state) {
1213 SocketState old_state;
1216 old_state = s->state;
1224 SOCKET_STOP_PRE_SIGTERM,
1225 SOCKET_STOP_PRE_SIGKILL,
1227 SOCKET_FINAL_SIGTERM,
1228 SOCKET_FINAL_SIGKILL)) {
1230 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1231 socket_unwatch_control_pid(s);
1232 s->control_command = NULL;
1233 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1236 if (state != SOCKET_LISTENING)
1237 socket_unwatch_fds(s);
1245 SOCKET_STOP_PRE_SIGTERM,
1246 SOCKET_STOP_PRE_SIGKILL))
1247 socket_close_fds(s);
1249 if (state != old_state)
1250 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s",
1251 UNIT(s)->id, socket_state_to_string(old_state), socket_state_to_string(state));
1253 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
1256 static int socket_coldplug(Unit *u) {
1257 Socket *s = SOCKET(u);
1261 assert(s->state == SOCKET_DEAD);
1263 if (s->deserialized_state == s->state)
1266 if (IN_SET(s->deserialized_state,
1271 SOCKET_STOP_PRE_SIGTERM,
1272 SOCKET_STOP_PRE_SIGKILL,
1274 SOCKET_FINAL_SIGTERM,
1275 SOCKET_FINAL_SIGKILL)) {
1277 if (s->control_pid <= 0)
1280 r = unit_watch_pid(UNIT(s), s->control_pid);
1284 r = socket_arm_timer(s);
1289 if (IN_SET(s->deserialized_state,
1295 SOCKET_STOP_PRE_SIGTERM,
1296 SOCKET_STOP_PRE_SIGKILL)) {
1297 r = socket_open_fds(s);
1302 if (s->deserialized_state == SOCKET_LISTENING) {
1303 r = socket_watch_fds(s);
1308 socket_set_state(s, s->deserialized_state);
1312 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
1313 _cleanup_free_ char **argv = NULL;
1321 unit_realize_cgroup(UNIT(s));
1323 r = unit_setup_exec_runtime(UNIT(s));
1327 r = socket_arm_timer(s);
1331 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1339 UNIT(s)->manager->environment,
1343 UNIT(s)->manager->confirm_spawn,
1344 UNIT(s)->manager->cgroup_supported,
1345 UNIT(s)->cgroup_path,
1346 manager_get_runtime_prefix(UNIT(s)->manager),
1353 r = unit_watch_pid(UNIT(s), pid);
1355 /* FIXME: we need to do something here */
1362 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1366 static int socket_chown(Socket *s, pid_t *_pid) {
1370 r = socket_arm_timer(s);
1374 /* We have to resolve the user names out-of-process, hence
1375 * let's fork here. It's messy, but well, what can we do? */
1383 uid_t uid = (uid_t) -1;
1384 gid_t gid = (gid_t) -1;
1387 default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE, -1);
1388 ignore_signals(SIGPIPE, -1);
1391 if (!isempty(s->user)) {
1392 const char *user = s->user;
1394 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1401 if (!isempty(s->group)) {
1402 const char *group = s->group;
1404 r = get_group_creds(&group, &gid);
1411 LIST_FOREACH(port, p, s->ports) {
1414 if (p->type == SOCKET_SOCKET)
1415 path = socket_address_get_path(&p->address);
1416 else if (p->type == SOCKET_FIFO)
1422 if (chown(path, uid, gid) < 0) {
1433 log_error("Failed to chown socket at step %s: %s", exit_status_to_string(ret, EXIT_STATUS_SYSTEMD), strerror(-r));
1438 r = unit_watch_pid(UNIT(s), pid);
1446 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1450 static void socket_enter_dead(Socket *s, SocketResult f) {
1453 if (f != SOCKET_SUCCESS)
1456 exec_runtime_destroy(s->exec_runtime);
1457 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1459 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1461 socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
1464 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
1466 static void socket_enter_stop_post(Socket *s, SocketResult f) {
1470 if (f != SOCKET_SUCCESS)
1473 socket_unwatch_control_pid(s);
1474 s->control_command_id = SOCKET_EXEC_STOP_POST;
1475 s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
1477 if (s->control_command) {
1478 r = socket_spawn(s, s->control_command, &s->control_pid);
1482 socket_set_state(s, SOCKET_STOP_POST);
1484 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
1489 log_warning_unit(UNIT(s)->id,
1490 "%s failed to run 'stop-post' task: %s",
1491 UNIT(s)->id, strerror(-r));
1492 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1495 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
1500 if (f != SOCKET_SUCCESS)
1503 r = unit_kill_context(
1506 state != SOCKET_STOP_PRE_SIGTERM && state != SOCKET_FINAL_SIGTERM,
1514 r = socket_arm_timer(s);
1518 socket_set_state(s, state);
1519 } else if (state == SOCKET_STOP_PRE_SIGTERM)
1520 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
1521 else if (state == SOCKET_STOP_PRE_SIGKILL)
1522 socket_enter_stop_post(s, SOCKET_SUCCESS);
1523 else if (state == SOCKET_FINAL_SIGTERM)
1524 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
1526 socket_enter_dead(s, SOCKET_SUCCESS);
1531 log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1533 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1534 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1536 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1539 static void socket_enter_stop_pre(Socket *s, SocketResult f) {
1543 if (f != SOCKET_SUCCESS)
1546 socket_unwatch_control_pid(s);
1547 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1548 s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
1550 if (s->control_command) {
1551 r = socket_spawn(s, s->control_command, &s->control_pid);
1555 socket_set_state(s, SOCKET_STOP_PRE);
1557 socket_enter_stop_post(s, SOCKET_SUCCESS);
1562 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-pre' task: %s", UNIT(s)->id, strerror(-r));
1563 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1566 static void socket_enter_listening(Socket *s) {
1570 r = socket_watch_fds(s);
1572 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1576 socket_set_state(s, SOCKET_LISTENING);
1580 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1583 static void socket_enter_start_post(Socket *s) {
1587 socket_unwatch_control_pid(s);
1588 s->control_command_id = SOCKET_EXEC_START_POST;
1589 s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
1591 if (s->control_command) {
1592 r = socket_spawn(s, s->control_command, &s->control_pid);
1594 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1598 socket_set_state(s, SOCKET_START_POST);
1600 socket_enter_listening(s);
1605 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1608 static void socket_enter_start_chown(Socket *s) {
1613 r = socket_open_fds(s);
1615 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1619 if (!isempty(s->user) || !isempty(s->group)) {
1621 socket_unwatch_control_pid(s);
1622 s->control_command_id = SOCKET_EXEC_START_CHOWN;
1623 s->control_command = NULL;
1625 r = socket_chown(s, &s->control_pid);
1627 log_warning_unit(UNIT(s)->id, "%s failed to fork 'start-chown' task: %s", UNIT(s)->id, strerror(-r));
1631 socket_set_state(s, SOCKET_START_CHOWN);
1633 socket_enter_start_post(s);
1638 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1641 static void socket_enter_start_pre(Socket *s) {
1645 socket_unwatch_control_pid(s);
1646 s->control_command_id = SOCKET_EXEC_START_PRE;
1647 s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
1649 if (s->control_command) {
1650 r = socket_spawn(s, s->control_command, &s->control_pid);
1652 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1656 socket_set_state(s, SOCKET_START_PRE);
1658 socket_enter_start_chown(s);
1663 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1666 static void socket_enter_running(Socket *s, int cfd) {
1667 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1672 /* We don't take connections anymore if we are supposed to
1673 * shut down anyway */
1674 if (unit_stop_pending(UNIT(s))) {
1676 log_debug_unit(UNIT(s)->id, "Suppressing connection request on %s since unit stop is scheduled.", UNIT(s)->id);
1681 /* Flush all sockets by closing and reopening them */
1682 socket_close_fds(s);
1684 r = socket_open_fds(s);
1686 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1687 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1691 r = socket_watch_fds(s);
1693 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1694 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1704 bool pending = false;
1706 /* If there's already a start pending don't bother to
1708 SET_FOREACH(other, UNIT(s)->dependencies[UNIT_TRIGGERS], i)
1709 if (unit_active_or_pending(other)) {
1715 if (!UNIT_ISSET(s->service)) {
1716 log_error_unit(UNIT(s)->id, "%s: service to activate vanished, refusing activation.", UNIT(s)->id);
1721 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, true, &error, NULL);
1726 socket_set_state(s, SOCKET_RUNNING);
1728 _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
1731 if (s->n_connections >= s->max_connections) {
1732 log_warning_unit(UNIT(s)->id, "%s: Too many incoming connections (%u)", UNIT(s)->id, s->n_connections);
1737 r = socket_instantiate_service(s);
1741 r = instance_from_socket(cfd, s->n_accepted, &instance);
1746 /* ENOTCONN is legitimate if TCP RST was received.
1747 * This connection is over, but the socket unit lives on. */
1752 prefix = unit_name_to_prefix(UNIT(s)->id);
1758 name = unit_name_build(prefix, instance, ".service");
1764 r = unit_add_name(UNIT_DEREF(s->service), name);
1768 service = SERVICE(UNIT_DEREF(s->service));
1769 unit_ref_unset(&s->service);
1772 UNIT(service)->no_gc = false;
1774 unit_choose_id(UNIT(service), name);
1776 r = service_set_socket_fd(service, cfd, s);
1781 s->n_connections ++;
1783 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL);
1787 /* Notify clients about changed counters */
1788 unit_add_to_dbus_queue(UNIT(s));
1794 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",
1795 UNIT(s)->id, cfd >= 0 ? "template" : "non-template",
1796 bus_error_message(&error, r));
1798 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1802 static void socket_run_next(Socket *s) {
1806 assert(s->control_command);
1807 assert(s->control_command->command_next);
1809 socket_unwatch_control_pid(s);
1811 s->control_command = s->control_command->command_next;
1813 r = socket_spawn(s, s->control_command, &s->control_pid);
1820 log_warning_unit(UNIT(s)->id, "%s failed to run next task: %s", UNIT(s)->id, strerror(-r));
1822 if (s->state == SOCKET_START_POST)
1823 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1824 else if (s->state == SOCKET_STOP_POST)
1825 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1827 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1830 static int socket_start(Unit *u) {
1831 Socket *s = SOCKET(u);
1835 /* We cannot fulfill this request right now, try again later
1837 if (IN_SET(s->state,
1839 SOCKET_STOP_PRE_SIGKILL,
1840 SOCKET_STOP_PRE_SIGTERM,
1842 SOCKET_FINAL_SIGTERM,
1843 SOCKET_FINAL_SIGKILL))
1846 if (IN_SET(s->state,
1852 /* Cannot run this without the service being around */
1853 if (UNIT_ISSET(s->service)) {
1856 service = SERVICE(UNIT_DEREF(s->service));
1858 if (UNIT(service)->load_state != UNIT_LOADED) {
1859 log_error_unit(u->id, "Socket service %s not loaded, refusing.", UNIT(service)->id);
1863 /* If the service is already active we cannot start the
1865 if (service->state != SERVICE_DEAD &&
1866 service->state != SERVICE_FAILED &&
1867 service->state != SERVICE_AUTO_RESTART) {
1868 log_error_unit(u->id, "Socket service %s already active, refusing.", UNIT(service)->id);
1872 #ifdef HAVE_SYSV_COMPAT
1873 if (service->is_sysv) {
1874 log_error_unit(u->id,
1875 "Using SysV services for socket activation is not supported. Refusing.");
1881 assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1883 s->result = SOCKET_SUCCESS;
1884 socket_enter_start_pre(s);
1889 static int socket_stop(Unit *u) {
1890 Socket *s = SOCKET(u);
1895 if (IN_SET(s->state,
1897 SOCKET_STOP_PRE_SIGTERM,
1898 SOCKET_STOP_PRE_SIGKILL,
1900 SOCKET_FINAL_SIGTERM,
1901 SOCKET_FINAL_SIGKILL))
1904 /* If there's already something running we go directly into
1906 if (IN_SET(s->state,
1909 SOCKET_START_POST)) {
1910 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
1914 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1916 socket_enter_stop_pre(s, SOCKET_SUCCESS);
1920 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1921 Socket *s = SOCKET(u);
1929 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1930 unit_serialize_item(u, f, "result", socket_result_to_string(s->result));
1931 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1933 if (s->control_pid > 0)
1934 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
1936 if (s->control_command_id >= 0)
1937 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1939 LIST_FOREACH(port, p, s->ports) {
1945 copy = fdset_put_dup(fds, p->fd);
1949 if (p->type == SOCKET_SOCKET) {
1950 _cleanup_free_ char *t = NULL;
1952 r = socket_address_print(&p->address, &t);
1956 if (socket_address_family(&p->address) == AF_NETLINK)
1957 unit_serialize_item_format(u, f, "netlink", "%i %s", copy, t);
1959 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1961 } else if (p->type == SOCKET_SPECIAL)
1962 unit_serialize_item_format(u, f, "special", "%i %s", copy, p->path);
1963 else if (p->type == SOCKET_MQUEUE)
1964 unit_serialize_item_format(u, f, "mqueue", "%i %s", copy, p->path);
1966 assert(p->type == SOCKET_FIFO);
1967 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1974 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1975 Socket *s = SOCKET(u);
1981 if (streq(key, "state")) {
1984 state = socket_state_from_string(value);
1986 log_debug_unit(u->id, "Failed to parse state value %s", value);
1988 s->deserialized_state = state;
1989 } else if (streq(key, "result")) {
1992 f = socket_result_from_string(value);
1994 log_debug_unit(u->id, "Failed to parse result value %s", value);
1995 else if (f != SOCKET_SUCCESS)
1998 } else if (streq(key, "n-accepted")) {
2001 if (safe_atou(value, &k) < 0)
2002 log_debug_unit(u->id, "Failed to parse n-accepted value %s", value);
2005 } else if (streq(key, "control-pid")) {
2008 if (parse_pid(value, &pid) < 0)
2009 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
2011 s->control_pid = pid;
2012 } else if (streq(key, "control-command")) {
2013 SocketExecCommand id;
2015 id = socket_exec_command_from_string(value);
2017 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
2019 s->control_command_id = id;
2020 s->control_command = s->exec_command[id];
2022 } else if (streq(key, "fifo")) {
2026 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2027 log_debug_unit(u->id, "Failed to parse fifo value %s", value);
2030 LIST_FOREACH(port, p, s->ports)
2031 if (p->type == SOCKET_FIFO &&
2032 streq_ptr(p->path, value+skip))
2037 p->fd = fdset_remove(fds, fd);
2041 } else if (streq(key, "special")) {
2045 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2046 log_debug_unit(u->id, "Failed to parse special value %s", value);
2049 LIST_FOREACH(port, p, s->ports)
2050 if (p->type == SOCKET_SPECIAL &&
2051 streq_ptr(p->path, value+skip))
2056 p->fd = fdset_remove(fds, fd);
2060 } else if (streq(key, "mqueue")) {
2064 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2065 log_debug_unit(u->id, "Failed to parse mqueue value %s", value);
2068 LIST_FOREACH(port, p, s->ports)
2069 if (p->type == SOCKET_MQUEUE &&
2070 streq_ptr(p->path, value+skip))
2075 p->fd = fdset_remove(fds, fd);
2079 } else if (streq(key, "socket")) {
2080 int fd, type, skip = 0;
2083 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
2084 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2087 LIST_FOREACH(port, p, s->ports)
2088 if (socket_address_is(&p->address, value+skip, type))
2093 p->fd = fdset_remove(fds, fd);
2097 } else if (streq(key, "netlink")) {
2101 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2102 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2105 LIST_FOREACH(port, p, s->ports)
2106 if (socket_address_is_netlink(&p->address, value+skip))
2111 p->fd = fdset_remove(fds, fd);
2115 log_debug_unit(UNIT(s)->id, "Unknown serialization key '%s'", key);
2120 static int socket_distribute_fds(Unit *u, FDSet *fds) {
2121 Socket *s = SOCKET(u);
2126 LIST_FOREACH(port, p, s->ports) {
2130 if (p->type != SOCKET_SOCKET)
2136 FDSET_FOREACH(fd, fds, i) {
2137 if (socket_address_matches_fd(&p->address, fd)) {
2138 p->fd = fdset_remove(fds, fd);
2139 s->deserialized_state = SOCKET_LISTENING;
2148 _pure_ static UnitActiveState socket_active_state(Unit *u) {
2151 return state_translation_table[SOCKET(u)->state];
2154 _pure_ static const char *socket_sub_state_to_string(Unit *u) {
2157 return socket_state_to_string(SOCKET(u)->state);
2160 const char* socket_port_type_to_string(SocketPort *p) {
2168 switch (p->address.type) {
2176 case SOCK_SEQPACKET:
2177 return "SequentialPacket";
2180 if (socket_address_family(&p->address) == AF_NETLINK)
2187 case SOCKET_SPECIAL:
2191 return "MessageQueue";
2201 _pure_ static bool socket_check_gc(Unit *u) {
2202 Socket *s = SOCKET(u);
2206 return s->n_connections > 0;
2209 static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2210 SocketPort *p = userdata;
2216 if (p->socket->state != SOCKET_LISTENING)
2219 log_debug_unit(UNIT(p->socket)->id, "Incoming traffic on %s", UNIT(p->socket)->id);
2221 if (revents != EPOLLIN) {
2223 if (revents & EPOLLHUP)
2224 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.",
2225 UNIT(p->socket)->id);
2227 log_error_unit(UNIT(p->socket)->id, "%s: Got unexpected poll event (0x%x) on socket.",
2228 UNIT(p->socket)->id, revents);
2233 if (p->socket->accept &&
2234 p->type == SOCKET_SOCKET &&
2235 socket_address_can_accept(&p->address)) {
2239 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK);
2245 log_error_unit(UNIT(p->socket)->id,
2246 "Failed to accept socket: %m");
2253 socket_apply_socket_options(p->socket, cfd);
2256 socket_enter_running(p->socket, cfd);
2260 socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
2264 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2265 Socket *s = SOCKET(u);
2271 if (pid != s->control_pid)
2276 if (is_clean_exit(code, status, NULL))
2278 else if (code == CLD_EXITED)
2279 f = SOCKET_FAILURE_EXIT_CODE;
2280 else if (code == CLD_KILLED)
2281 f = SOCKET_FAILURE_SIGNAL;
2282 else if (code == CLD_DUMPED)
2283 f = SOCKET_FAILURE_CORE_DUMP;
2285 assert_not_reached("Unknown code");
2287 if (s->control_command) {
2288 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2290 if (s->control_command->ignore)
2294 log_full_unit(f == SOCKET_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2296 "%s control process exited, code=%s status=%i",
2297 u->id, sigchld_code_to_string(code), status);
2299 if (f != SOCKET_SUCCESS)
2302 if (s->control_command &&
2303 s->control_command->command_next &&
2304 f == SOCKET_SUCCESS) {
2306 log_debug_unit(u->id,
2307 "%s running next command for state %s",
2308 u->id, socket_state_to_string(s->state));
2311 s->control_command = NULL;
2312 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
2314 /* No further commands for this step, so let's figure
2315 * out what to do next */
2317 log_debug_unit(u->id,
2318 "%s got final SIGCHLD for state %s",
2319 u->id, socket_state_to_string(s->state));
2323 case SOCKET_START_PRE:
2324 if (f == SOCKET_SUCCESS)
2325 socket_enter_start_chown(s);
2327 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
2330 case SOCKET_START_CHOWN:
2331 if (f == SOCKET_SUCCESS)
2332 socket_enter_start_post(s);
2334 socket_enter_stop_pre(s, f);
2337 case SOCKET_START_POST:
2338 if (f == SOCKET_SUCCESS)
2339 socket_enter_listening(s);
2341 socket_enter_stop_pre(s, f);
2344 case SOCKET_STOP_PRE:
2345 case SOCKET_STOP_PRE_SIGTERM:
2346 case SOCKET_STOP_PRE_SIGKILL:
2347 socket_enter_stop_post(s, f);
2350 case SOCKET_STOP_POST:
2351 case SOCKET_FINAL_SIGTERM:
2352 case SOCKET_FINAL_SIGKILL:
2353 socket_enter_dead(s, f);
2357 assert_not_reached("Uh, control process died at wrong time.");
2361 /* Notify clients about changed exit status */
2362 unit_add_to_dbus_queue(u);
2365 static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2366 Socket *s = SOCKET(userdata);
2369 assert(s->timer_event_source == source);
2373 case SOCKET_START_PRE:
2374 log_warning_unit(UNIT(s)->id, "%s starting timed out. Terminating.", UNIT(s)->id);
2375 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2378 case SOCKET_START_CHOWN:
2379 case SOCKET_START_POST:
2380 log_warning_unit(UNIT(s)->id, "%s starting timed out. Stopping.", UNIT(s)->id);
2381 socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
2384 case SOCKET_STOP_PRE:
2385 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2386 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2389 case SOCKET_STOP_PRE_SIGTERM:
2390 if (s->kill_context.send_sigkill) {
2391 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Killing.", UNIT(s)->id);
2392 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2394 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2395 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2399 case SOCKET_STOP_PRE_SIGKILL:
2400 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2401 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2404 case SOCKET_STOP_POST:
2405 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Terminating.", UNIT(s)->id);
2406 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2409 case SOCKET_FINAL_SIGTERM:
2410 if (s->kill_context.send_sigkill) {
2411 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Killing.", UNIT(s)->id);
2412 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2414 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2415 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2419 case SOCKET_FINAL_SIGKILL:
2420 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL (2). Entering failed mode.", UNIT(s)->id);
2421 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2425 assert_not_reached("Timeout at wrong time.");
2431 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
2440 /* Called from the service code for requesting our fds */
2443 LIST_FOREACH(port, p, s->ports)
2453 if (!(rfds = new(int, rn_fds)))
2457 LIST_FOREACH(port, p, s->ports)
2461 assert(k == rn_fds);
2469 static void socket_reset_failed(Unit *u) {
2470 Socket *s = SOCKET(u);
2474 if (s->state == SOCKET_FAILED)
2475 socket_set_state(s, SOCKET_DEAD);
2477 s->result = SOCKET_SUCCESS;
2480 static void socket_notify_service_dead(Socket *s, bool failed_permanent) {
2483 /* The service is dead. Dang!
2485 * This is strictly for one-instance-for-all-connections
2488 if (s->state == SOCKET_RUNNING) {
2489 log_debug_unit(UNIT(s)->id, "%s got notified about service death (failed permanently: %s)", UNIT(s)->id, yes_no(failed_permanent));
2490 if (failed_permanent)
2491 socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_FAILED_PERMANENT);
2493 socket_enter_listening(s);
2497 void socket_connection_unref(Socket *s) {
2500 /* The service is dead. Yay!
2502 * This is strictly for one-instance-per-connection
2505 assert(s->n_connections > 0);
2508 log_debug_unit(UNIT(s)->id, "%s: One connection closed, %u left.", UNIT(s)->id, s->n_connections);
2511 static void socket_trigger_notify(Unit *u, Unit *other) {
2512 Socket *s = SOCKET(u);
2518 /* Don't propagate state changes from the service if we are
2519 already down or accepting connections */
2520 if ((s->state != SOCKET_RUNNING &&
2521 s->state != SOCKET_LISTENING) ||
2525 if (other->load_state != UNIT_LOADED ||
2526 other->type != UNIT_SERVICE)
2529 se = SERVICE(other);
2531 if (se->state == SERVICE_FAILED)
2532 socket_notify_service_dead(s, se->result == SERVICE_FAILURE_START_LIMIT);
2534 if (se->state == SERVICE_DEAD ||
2535 se->state == SERVICE_STOP ||
2536 se->state == SERVICE_STOP_SIGTERM ||
2537 se->state == SERVICE_STOP_SIGKILL ||
2538 se->state == SERVICE_STOP_POST ||
2539 se->state == SERVICE_FINAL_SIGTERM ||
2540 se->state == SERVICE_FINAL_SIGKILL ||
2541 se->state == SERVICE_AUTO_RESTART)
2542 socket_notify_service_dead(s, false);
2544 if (se->state == SERVICE_RUNNING)
2545 socket_set_state(s, SOCKET_RUNNING);
2548 static int socket_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2549 return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
2552 static int socket_get_timeout(Unit *u, uint64_t *timeout) {
2553 Socket *s = SOCKET(u);
2556 if (!s->timer_event_source)
2559 r = sd_event_source_get_time(s->timer_event_source, timeout);
2566 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
2567 [SOCKET_DEAD] = "dead",
2568 [SOCKET_START_PRE] = "start-pre",
2569 [SOCKET_START_CHOWN] = "start-chown",
2570 [SOCKET_START_POST] = "start-post",
2571 [SOCKET_LISTENING] = "listening",
2572 [SOCKET_RUNNING] = "running",
2573 [SOCKET_STOP_PRE] = "stop-pre",
2574 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
2575 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
2576 [SOCKET_STOP_POST] = "stop-post",
2577 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
2578 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
2579 [SOCKET_FAILED] = "failed"
2582 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
2584 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
2585 [SOCKET_EXEC_START_PRE] = "StartPre",
2586 [SOCKET_EXEC_START_CHOWN] = "StartChown",
2587 [SOCKET_EXEC_START_POST] = "StartPost",
2588 [SOCKET_EXEC_STOP_PRE] = "StopPre",
2589 [SOCKET_EXEC_STOP_POST] = "StopPost"
2592 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
2594 static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
2595 [SOCKET_SUCCESS] = "success",
2596 [SOCKET_FAILURE_RESOURCES] = "resources",
2597 [SOCKET_FAILURE_TIMEOUT] = "timeout",
2598 [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
2599 [SOCKET_FAILURE_SIGNAL] = "signal",
2600 [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
2601 [SOCKET_FAILURE_SERVICE_FAILED_PERMANENT] = "service-failed-permanent"
2604 DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
2606 const UnitVTable socket_vtable = {
2607 .object_size = sizeof(Socket),
2608 .exec_context_offset = offsetof(Socket, exec_context),
2609 .cgroup_context_offset = offsetof(Socket, cgroup_context),
2610 .kill_context_offset = offsetof(Socket, kill_context),
2611 .exec_runtime_offset = offsetof(Socket, exec_runtime),
2617 .private_section = "Socket",
2619 .init = socket_init,
2620 .done = socket_done,
2621 .load = socket_load,
2623 .coldplug = socket_coldplug,
2625 .dump = socket_dump,
2627 .start = socket_start,
2628 .stop = socket_stop,
2630 .kill = socket_kill,
2632 .get_timeout = socket_get_timeout,
2634 .serialize = socket_serialize,
2635 .deserialize_item = socket_deserialize_item,
2636 .distribute_fds = socket_distribute_fds,
2638 .active_state = socket_active_state,
2639 .sub_state_to_string = socket_sub_state_to_string,
2641 .check_gc = socket_check_gc,
2643 .sigchld_event = socket_sigchld_event,
2645 .trigger_notify = socket_trigger_notify,
2647 .reset_failed = socket_reset_failed,
2649 .bus_interface = "org.freedesktop.systemd1.Socket",
2650 .bus_vtable = bus_socket_vtable,
2651 .bus_set_property = bus_socket_set_property,
2652 .bus_commit_properties = bus_socket_commit_properties,
2654 .status_message_formats = {
2655 /*.starting_stopping = {
2656 [0] = "Starting socket %s...",
2657 [1] = "Stopping socket %s...",
2659 .finished_start_job = {
2660 [JOB_DONE] = "Listening on %s.",
2661 [JOB_FAILED] = "Failed to listen on %s.",
2662 [JOB_DEPENDENCY] = "Dependency failed for %s.",
2663 [JOB_TIMEOUT] = "Timed out starting %s.",
2665 .finished_stop_job = {
2666 [JOB_DONE] = "Closed %s.",
2667 [JOB_FAILED] = "Failed stopping %s.",
2668 [JOB_TIMEOUT] = "Timed out stopping %s.",