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 int socket_instantiate_service(Socket *s) {
184 _cleanup_free_ char *prefix = NULL, *name = NULL;
190 /* This fills in s->service if it isn't filled in yet. For
191 * Accept=yes sockets we create the next connection service
192 * here. For Accept=no this is mostly a NOP since the service
193 * is figured out at load time anyway. */
195 if (UNIT_DEREF(s->service) || !s->accept)
198 prefix = unit_name_to_prefix(UNIT(s)->id);
202 if (asprintf(&name, "%s@%u.service", prefix, s->n_accepted) < 0)
205 r = manager_load_unit(UNIT(s)->manager, name, NULL, NULL, &u);
210 unit_ref_set(&s->service, u);
212 return unit_add_two_dependencies(UNIT(s), UNIT_BEFORE, UNIT_TRIGGERS, u, false);
215 static bool have_non_accept_socket(Socket *s) {
223 LIST_FOREACH(port, p, s->ports) {
225 if (p->type != SOCKET_SOCKET)
228 if (!socket_address_can_accept(&p->address))
235 static int socket_add_mount_links(Socket *s) {
241 LIST_FOREACH(port, p, s->ports) {
242 const char *path = NULL;
244 if (p->type == SOCKET_SOCKET)
245 path = socket_address_get_path(&p->address);
246 else if (p->type == SOCKET_FIFO || p->type == SOCKET_SPECIAL)
252 r = unit_require_mounts_for(UNIT(s), path);
260 static int socket_add_device_link(Socket *s) {
265 if (!s->bind_to_device || streq(s->bind_to_device, "lo"))
268 t = strappenda("/sys/subsystem/net/devices/", s->bind_to_device);
269 return unit_add_node_link(UNIT(s), t, false);
272 static int socket_add_default_dependencies(Socket *s) {
276 r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true);
280 if (UNIT(s)->manager->running_as == SYSTEMD_SYSTEM) {
281 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true);
286 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
289 _pure_ static bool socket_has_exec(Socket *s) {
293 for (i = 0; i < _SOCKET_EXEC_COMMAND_MAX; i++)
294 if (s->exec_command[i])
300 static int socket_add_extras(Socket *s) {
306 if (have_non_accept_socket(s)) {
308 if (!UNIT_DEREF(s->service)) {
311 r = unit_load_related_unit(u, ".service", &x);
315 unit_ref_set(&s->service, x);
318 r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, UNIT_DEREF(s->service), true);
323 r = socket_add_mount_links(s);
327 r = socket_add_device_link(s);
331 r = unit_patch_contexts(u);
335 if (socket_has_exec(s)) {
336 r = unit_add_exec_dependencies(u, &s->exec_context);
340 r = unit_add_default_slice(u, &s->cgroup_context);
345 if (u->default_dependencies) {
346 r = socket_add_default_dependencies(s);
354 static const char *socket_find_symlink_target(Socket *s) {
355 const char *found = NULL;
358 LIST_FOREACH(port, p, s->ports) {
359 const char *f = NULL;
368 if (p->address.sockaddr.un.sun_path[0] != 0)
369 f = p->address.sockaddr.un.sun_path;
387 static int socket_verify(Socket *s) {
390 if (UNIT(s)->load_state != UNIT_LOADED)
394 log_error_unit(UNIT(s)->id, "%s lacks Listen setting. Refusing.", UNIT(s)->id);
398 if (s->accept && have_non_accept_socket(s)) {
399 log_error_unit(UNIT(s)->id, "%s configured for accepting sockets, but sockets are non-accepting. Refusing.",
404 if (s->accept && s->max_connections <= 0) {
405 log_error_unit(UNIT(s)->id, "%s's MaxConnection setting too small. Refusing.", UNIT(s)->id);
409 if (s->accept && UNIT_DEREF(s->service)) {
410 log_error_unit(UNIT(s)->id, "Explicit service configuration for accepting sockets not supported on %s. Refusing.", UNIT(s)->id);
414 if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
415 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
419 if (!strv_isempty(s->symlinks) && !socket_find_symlink_target(s)) {
420 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);
427 static int socket_load(Unit *u) {
428 Socket *s = SOCKET(u);
432 assert(u->load_state == UNIT_STUB);
434 r = unit_load_fragment_and_dropin(u);
438 if (u->load_state == UNIT_LOADED) {
439 /* This is a new unit? Then let's add in some extras */
440 r = socket_add_extras(s);
445 return socket_verify(s);
448 _const_ static const char* listen_lookup(int family, int type) {
450 if (family == AF_NETLINK)
451 return "ListenNetlink";
453 if (type == SOCK_STREAM)
454 return "ListenStream";
455 else if (type == SOCK_DGRAM)
456 return "ListenDatagram";
457 else if (type == SOCK_SEQPACKET)
458 return "ListenSequentialPacket";
460 assert_not_reached("Unknown socket type");
464 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
465 char time_string[FORMAT_TIMESPAN_MAX];
467 Socket *s = SOCKET(u);
474 prefix2 = strappenda(prefix, "\t");
477 "%sSocket State: %s\n"
479 "%sBindIPv6Only: %s\n"
481 "%sSocketMode: %04o\n"
482 "%sDirectoryMode: %04o\n"
486 "%sTransparent: %s\n"
488 "%sPassCredentials: %s\n"
489 "%sPassSecurity: %s\n"
490 "%sTCPCongestion: %s\n"
491 "%sRemoveOnStop: %s\n",
492 prefix, socket_state_to_string(s->state),
493 prefix, socket_result_to_string(s->result),
494 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
496 prefix, s->socket_mode,
497 prefix, s->directory_mode,
498 prefix, yes_no(s->keep_alive),
499 prefix, yes_no(s->no_delay),
500 prefix, yes_no(s->free_bind),
501 prefix, yes_no(s->transparent),
502 prefix, yes_no(s->broadcast),
503 prefix, yes_no(s->pass_cred),
504 prefix, yes_no(s->pass_sec),
505 prefix, strna(s->tcp_congestion),
506 prefix, yes_no(s->remove_on_stop));
508 if (s->control_pid > 0)
510 "%sControl PID: "PID_FMT"\n",
511 prefix, s->control_pid);
513 if (s->bind_to_device)
515 "%sBindToDevice: %s\n",
516 prefix, s->bind_to_device);
521 "%sNConnections: %u\n"
522 "%sMaxConnections: %u\n",
523 prefix, s->n_accepted,
524 prefix, s->n_connections,
525 prefix, s->max_connections);
527 if (s->priority >= 0)
530 prefix, s->priority);
532 if (s->receive_buffer > 0)
534 "%sReceiveBuffer: %zu\n",
535 prefix, s->receive_buffer);
537 if (s->send_buffer > 0)
539 "%sSendBuffer: %zu\n",
540 prefix, s->send_buffer);
552 if (s->pipe_size > 0)
555 prefix, s->pipe_size);
562 if (s->mq_maxmsg > 0)
564 "%sMessageQueueMaxMessages: %li\n",
565 prefix, s->mq_maxmsg);
567 if (s->mq_msgsize > 0)
569 "%sMessageQueueMessageSize: %li\n",
570 prefix, s->mq_msgsize);
575 prefix, yes_no(s->reuse_port));
579 "%sSmackLabel: %s\n",
584 "%sSmackLabelIPIn: %s\n",
585 prefix, s->smack_ip_in);
589 "%sSmackLabelIPOut: %s\n",
590 prefix, s->smack_ip_out);
592 if (!isempty(s->user) || !isempty(s->group))
595 "%sOwnerGroup: %s\n",
596 prefix, strna(s->user),
597 prefix, strna(s->group));
599 if (s->keep_alive_time > 0)
601 "%sKeepAliveTimeSec: %s\n",
602 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_time, USEC_PER_SEC));
604 if (s->keep_alive_interval)
606 "%sKeepAliveIntervalSec: %s\n",
607 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_interval, USEC_PER_SEC));
609 if (s->keep_alive_cnt)
611 "%sKeepAliveProbes: %u\n",
612 prefix, s->keep_alive_cnt);
616 "%sDeferAcceptSec: %s\n",
617 prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->defer_accept, USEC_PER_SEC));
619 LIST_FOREACH(port, p, s->ports) {
621 if (p->type == SOCKET_SOCKET) {
626 if ((r = socket_address_print(&p->address, &k)) < 0)
631 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type), t);
633 } else if (p->type == SOCKET_SPECIAL)
634 fprintf(f, "%sListenSpecial: %s\n", prefix, p->path);
635 else if (p->type == SOCKET_MQUEUE)
636 fprintf(f, "%sListenMessageQueue: %s\n", prefix, p->path);
638 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
641 exec_context_dump(&s->exec_context, f, prefix);
642 kill_context_dump(&s->kill_context, f, prefix);
644 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
645 if (!s->exec_command[c])
648 fprintf(f, "%s-> %s:\n",
649 prefix, socket_exec_command_to_string(c));
651 exec_command_dump_list(s->exec_command[c], f, prefix2);
655 static int instance_from_socket(int fd, unsigned nr, char **instance) {
658 union sockaddr_union local, remote;
664 if (getsockname(fd, &local.sa, &l) < 0)
668 if (getpeername(fd, &remote.sa, &l) < 0)
671 switch (local.sa.sa_family) {
675 a = ntohl(local.in.sin_addr.s_addr),
676 b = ntohl(remote.in.sin_addr.s_addr);
679 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
681 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
682 ntohs(local.in.sin_port),
683 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
684 ntohs(remote.in.sin_port)) < 0)
691 static const unsigned char ipv4_prefix[] = {
692 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
695 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
696 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
698 *a = local.in6.sin6_addr.s6_addr+12,
699 *b = remote.in6.sin6_addr.s6_addr+12;
702 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
704 a[0], a[1], a[2], a[3],
705 ntohs(local.in6.sin6_port),
706 b[0], b[1], b[2], b[3],
707 ntohs(remote.in6.sin6_port)) < 0)
710 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
715 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
716 ntohs(local.in6.sin6_port),
717 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
718 ntohs(remote.in6.sin6_port)) < 0)
729 k = getpeercred(fd, &ucred);
732 "%u-"PID_FMT"-"UID_FMT,
733 nr, ucred.pid, ucred.uid) < 0)
735 } else if (k == -ENODATA) {
736 /* This handles the case where somebody is
737 * connecting from another pid/uid namespace
738 * (e.g. from outside of our container). */
750 assert_not_reached("Unhandled socket type.");
757 static void socket_close_fds(Socket *s) {
763 LIST_FOREACH(port, p, s->ports) {
765 p->event_source = sd_event_source_unref(p->event_source);
770 p->fd = safe_close(p->fd);
772 /* One little note: we should normally not delete any
773 * sockets in the file system here! After all some
774 * other process we spawned might still have a
775 * reference of this fd and wants to continue to use
776 * it. Therefore we delete sockets in the file system
777 * before we create a new one, not after we stopped
780 if (s->remove_on_stop) {
792 socket_address_unlink(&p->address);
801 if (s->remove_on_stop)
802 STRV_FOREACH(i, s->symlinks)
806 static void socket_apply_socket_options(Socket *s, int fd) {
811 int b = s->keep_alive;
812 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
813 log_warning_unit(UNIT(s)->id, "SO_KEEPALIVE failed: %m");
816 if (s->keep_alive_time) {
817 int value = s->keep_alive_time / USEC_PER_SEC;
818 if (setsockopt(fd, SOL_TCP, TCP_KEEPIDLE, &value, sizeof(value)) < 0)
819 log_warning_unit(UNIT(s)->id, "TCP_KEEPIDLE failed: %m");
822 if (s->keep_alive_interval) {
823 int value = s->keep_alive_interval / USEC_PER_SEC;
824 if (setsockopt(fd, SOL_TCP, TCP_KEEPINTVL, &value, sizeof(value)) < 0)
825 log_warning_unit(UNIT(s)->id, "TCP_KEEPINTVL failed: %m");
828 if (s->keep_alive_cnt) {
829 int value = s->keep_alive_cnt;
830 if (setsockopt(fd, SOL_SOCKET, TCP_KEEPCNT, &value, sizeof(value)) < 0)
831 log_warning_unit(UNIT(s)->id, "TCP_KEEPCNT failed: %m");
834 if (s->defer_accept) {
835 int value = s->defer_accept / USEC_PER_SEC;
836 if (setsockopt(fd, SOL_TCP, TCP_DEFER_ACCEPT, &value, sizeof(value)) < 0)
837 log_warning_unit(UNIT(s)->id, "TCP_DEFER_ACCEPT failed: %m");
842 if (setsockopt(fd, SOL_TCP, TCP_NODELAY, &b, sizeof(b)) < 0)
843 log_warning_unit(UNIT(s)->id, "TCP_NODELAY failed: %m");
848 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)) < 0)
849 log_warning_unit(UNIT(s)->id, "SO_BROADCAST failed: %m");
854 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0)
855 log_warning_unit(UNIT(s)->id, "SO_PASSCRED failed: %m");
860 if (setsockopt(fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one)) < 0)
861 log_warning_unit(UNIT(s)->id, "SO_PASSSEC failed: %m");
864 if (s->priority >= 0)
865 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
866 log_warning_unit(UNIT(s)->id, "SO_PRIORITY failed: %m");
868 if (s->receive_buffer > 0) {
869 int value = (int) s->receive_buffer;
871 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
873 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
874 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
875 log_warning_unit(UNIT(s)->id, "SO_RCVBUF failed: %m");
878 if (s->send_buffer > 0) {
879 int value = (int) s->send_buffer;
880 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
881 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
882 log_warning_unit(UNIT(s)->id, "SO_SNDBUF failed: %m");
886 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
887 log_warning_unit(UNIT(s)->id, "SO_MARK failed: %m");
890 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
891 log_warning_unit(UNIT(s)->id, "IP_TOS failed: %m");
893 if (s->ip_ttl >= 0) {
896 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
898 if (socket_ipv6_is_supported())
899 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
902 errno = EAFNOSUPPORT;
906 log_warning_unit(UNIT(s)->id,
907 "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
910 if (s->tcp_congestion)
911 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
912 log_warning_unit(UNIT(s)->id, "TCP_CONGESTION failed: %m");
915 int b = s->reuse_port;
916 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &b, sizeof(b)) < 0)
917 log_warning_unit(UNIT(s)->id, "SO_REUSEPORT failed: %m");
921 if (smack_label_ip_in_fd(fd, s->smack_ip_in) < 0)
922 log_error_unit(UNIT(s)->id, "smack_label_ip_in_fd: %m");
925 if (smack_label_ip_out_fd(fd, s->smack_ip_out) < 0)
926 log_error_unit(UNIT(s)->id, "smack_label_ip_out_fd: %m");
929 static void socket_apply_fifo_options(Socket *s, int fd) {
933 if (s->pipe_size > 0)
934 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
935 log_warning_unit(UNIT(s)->id,
939 if (smack_label_fd(fd, s->smack) < 0)
940 log_error_unit(UNIT(s)->id, "smack_label_fd: %m");
943 static int fifo_address_create(
945 mode_t directory_mode,
956 mkdir_parents_label(path, directory_mode);
958 r = label_context_set(path, S_IFIFO);
962 /* Enforce the right access mode for the fifo */
963 old_mask = umask(~ socket_mode);
965 /* Include the original umask in our mask */
966 umask(~socket_mode | old_mask);
968 r = mkfifo(path, socket_mode);
971 if (r < 0 && errno != EEXIST) {
976 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
981 label_context_clear();
983 if (fstat(fd, &st) < 0) {
988 if (!S_ISFIFO(st.st_mode) ||
989 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
990 st.st_uid != getuid() ||
991 st.st_gid != getgid()) {
1001 label_context_clear();
1007 static int special_address_create(
1017 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
1023 if (fstat(fd, &st) < 0) {
1028 /* Check whether this is a /proc, /sys or /dev file or char device */
1029 if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
1043 static int mq_address_create(
1053 struct mq_attr _attr, *attr = NULL;
1058 if (maxmsg > 0 && msgsize > 0) {
1060 _attr.mq_flags = O_NONBLOCK;
1061 _attr.mq_maxmsg = maxmsg;
1062 _attr.mq_msgsize = msgsize;
1066 /* Enforce the right access mode for the mq */
1067 old_mask = umask(~ mq_mode);
1069 /* Include the original umask in our mask */
1070 umask(~mq_mode | old_mask);
1071 fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
1079 if (fstat(fd, &st) < 0) {
1084 if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
1085 st.st_uid != getuid() ||
1086 st.st_gid != getgid()) {
1100 static int socket_symlink(Socket *s) {
1106 p = socket_find_symlink_target(s);
1110 STRV_FOREACH(i, s->symlinks)
1116 static int socket_open_fds(Socket *s) {
1120 bool know_label = false;
1124 LIST_FOREACH(port, p, s->ports) {
1129 if (p->type == SOCKET_SOCKET) {
1133 r = socket_instantiate_service(s);
1137 if (UNIT_ISSET(s->service) &&
1138 SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]) {
1139 r = label_get_create_label_from_exe(SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]->path, &label);
1140 if (r < 0 && r != -EPERM)
1147 r = socket_address_listen(
1149 SOCK_CLOEXEC|SOCK_NONBLOCK,
1162 socket_apply_socket_options(s, p->fd);
1165 } else if (p->type == SOCKET_SPECIAL) {
1167 r = special_address_create(
1173 } else if (p->type == SOCKET_FIFO) {
1175 r = fifo_address_create(
1183 socket_apply_fifo_options(s, p->fd);
1186 } else if (p->type == SOCKET_MQUEUE) {
1188 r = mq_address_create(
1197 assert_not_reached("Unknown port type");
1204 socket_close_fds(s);
1209 static void socket_unwatch_fds(Socket *s) {
1215 LIST_FOREACH(port, p, s->ports) {
1219 if (!p->event_source)
1222 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
1224 log_debug_unit(UNIT(s)->id, "Failed to disable event source.");
1228 static int socket_watch_fds(Socket *s) {
1234 LIST_FOREACH(port, p, s->ports) {
1238 if (p->event_source)
1239 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
1241 r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
1244 log_warning_unit(UNIT(s)->id, "Failed to watch listening fds: %s", strerror(-r));
1252 socket_unwatch_fds(s);
1256 static void socket_set_state(Socket *s, SocketState state) {
1257 SocketState old_state;
1260 old_state = s->state;
1268 SOCKET_STOP_PRE_SIGTERM,
1269 SOCKET_STOP_PRE_SIGKILL,
1271 SOCKET_FINAL_SIGTERM,
1272 SOCKET_FINAL_SIGKILL)) {
1274 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1275 socket_unwatch_control_pid(s);
1276 s->control_command = NULL;
1277 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1280 if (state != SOCKET_LISTENING)
1281 socket_unwatch_fds(s);
1289 SOCKET_STOP_PRE_SIGTERM,
1290 SOCKET_STOP_PRE_SIGKILL))
1291 socket_close_fds(s);
1293 if (state != old_state)
1294 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s",
1295 UNIT(s)->id, socket_state_to_string(old_state), socket_state_to_string(state));
1297 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
1300 static int socket_coldplug(Unit *u) {
1301 Socket *s = SOCKET(u);
1305 assert(s->state == SOCKET_DEAD);
1307 if (s->deserialized_state == s->state)
1310 if (IN_SET(s->deserialized_state,
1315 SOCKET_STOP_PRE_SIGTERM,
1316 SOCKET_STOP_PRE_SIGKILL,
1318 SOCKET_FINAL_SIGTERM,
1319 SOCKET_FINAL_SIGKILL)) {
1321 if (s->control_pid <= 0)
1324 r = unit_watch_pid(UNIT(s), s->control_pid);
1328 r = socket_arm_timer(s);
1333 if (IN_SET(s->deserialized_state,
1339 SOCKET_STOP_PRE_SIGTERM,
1340 SOCKET_STOP_PRE_SIGKILL)) {
1341 r = socket_open_fds(s);
1346 if (s->deserialized_state == SOCKET_LISTENING) {
1347 r = socket_watch_fds(s);
1352 socket_set_state(s, s->deserialized_state);
1356 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
1357 _cleanup_free_ char **argv = NULL;
1365 unit_realize_cgroup(UNIT(s));
1367 r = unit_setup_exec_runtime(UNIT(s));
1371 r = socket_arm_timer(s);
1375 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1383 UNIT(s)->manager->environment,
1387 UNIT(s)->manager->confirm_spawn,
1388 UNIT(s)->manager->cgroup_supported,
1389 UNIT(s)->cgroup_path,
1390 manager_get_runtime_prefix(UNIT(s)->manager),
1399 r = unit_watch_pid(UNIT(s), pid);
1401 /* FIXME: we need to do something here */
1408 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1412 static int socket_chown(Socket *s, pid_t *_pid) {
1416 r = socket_arm_timer(s);
1420 /* We have to resolve the user names out-of-process, hence
1421 * let's fork here. It's messy, but well, what can we do? */
1429 uid_t uid = (uid_t) -1;
1430 gid_t gid = (gid_t) -1;
1433 default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE, -1);
1434 ignore_signals(SIGPIPE, -1);
1437 if (!isempty(s->user)) {
1438 const char *user = s->user;
1440 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1447 if (!isempty(s->group)) {
1448 const char *group = s->group;
1450 r = get_group_creds(&group, &gid);
1457 LIST_FOREACH(port, p, s->ports) {
1458 const char *path = NULL;
1460 if (p->type == SOCKET_SOCKET)
1461 path = socket_address_get_path(&p->address);
1462 else if (p->type == SOCKET_FIFO)
1468 if (chown(path, uid, gid) < 0) {
1479 log_error("Failed to chown socket at step %s: %s", exit_status_to_string(ret, EXIT_STATUS_SYSTEMD), strerror(-r));
1484 r = unit_watch_pid(UNIT(s), pid);
1492 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1496 static void socket_enter_dead(Socket *s, SocketResult f) {
1499 if (f != SOCKET_SUCCESS)
1502 exec_runtime_destroy(s->exec_runtime);
1503 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1505 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1507 socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
1510 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
1512 static void socket_enter_stop_post(Socket *s, SocketResult f) {
1516 if (f != SOCKET_SUCCESS)
1519 socket_unwatch_control_pid(s);
1520 s->control_command_id = SOCKET_EXEC_STOP_POST;
1521 s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
1523 if (s->control_command) {
1524 r = socket_spawn(s, s->control_command, &s->control_pid);
1528 socket_set_state(s, SOCKET_STOP_POST);
1530 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
1535 log_warning_unit(UNIT(s)->id,
1536 "%s failed to run 'stop-post' task: %s",
1537 UNIT(s)->id, strerror(-r));
1538 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1541 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
1546 if (f != SOCKET_SUCCESS)
1549 r = unit_kill_context(
1552 state != SOCKET_STOP_PRE_SIGTERM && state != SOCKET_FINAL_SIGTERM,
1560 r = socket_arm_timer(s);
1564 socket_set_state(s, state);
1565 } else if (state == SOCKET_STOP_PRE_SIGTERM)
1566 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
1567 else if (state == SOCKET_STOP_PRE_SIGKILL)
1568 socket_enter_stop_post(s, SOCKET_SUCCESS);
1569 else if (state == SOCKET_FINAL_SIGTERM)
1570 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
1572 socket_enter_dead(s, SOCKET_SUCCESS);
1577 log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1579 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1580 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1582 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1585 static void socket_enter_stop_pre(Socket *s, SocketResult f) {
1589 if (f != SOCKET_SUCCESS)
1592 socket_unwatch_control_pid(s);
1593 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1594 s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
1596 if (s->control_command) {
1597 r = socket_spawn(s, s->control_command, &s->control_pid);
1601 socket_set_state(s, SOCKET_STOP_PRE);
1603 socket_enter_stop_post(s, SOCKET_SUCCESS);
1608 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-pre' task: %s", UNIT(s)->id, strerror(-r));
1609 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1612 static void socket_enter_listening(Socket *s) {
1616 r = socket_watch_fds(s);
1618 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1622 socket_set_state(s, SOCKET_LISTENING);
1626 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1629 static void socket_enter_start_post(Socket *s) {
1633 socket_unwatch_control_pid(s);
1634 s->control_command_id = SOCKET_EXEC_START_POST;
1635 s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
1637 if (s->control_command) {
1638 r = socket_spawn(s, s->control_command, &s->control_pid);
1640 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1644 socket_set_state(s, SOCKET_START_POST);
1646 socket_enter_listening(s);
1651 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1654 static void socket_enter_start_chown(Socket *s) {
1659 r = socket_open_fds(s);
1661 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1665 if (!isempty(s->user) || !isempty(s->group)) {
1667 socket_unwatch_control_pid(s);
1668 s->control_command_id = SOCKET_EXEC_START_CHOWN;
1669 s->control_command = NULL;
1671 r = socket_chown(s, &s->control_pid);
1673 log_warning_unit(UNIT(s)->id, "%s failed to fork 'start-chown' task: %s", UNIT(s)->id, strerror(-r));
1677 socket_set_state(s, SOCKET_START_CHOWN);
1679 socket_enter_start_post(s);
1684 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1687 static void socket_enter_start_pre(Socket *s) {
1691 socket_unwatch_control_pid(s);
1692 s->control_command_id = SOCKET_EXEC_START_PRE;
1693 s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
1695 if (s->control_command) {
1696 r = socket_spawn(s, s->control_command, &s->control_pid);
1698 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1702 socket_set_state(s, SOCKET_START_PRE);
1704 socket_enter_start_chown(s);
1709 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1712 static void socket_enter_running(Socket *s, int cfd) {
1713 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1718 /* We don't take connections anymore if we are supposed to
1719 * shut down anyway */
1720 if (unit_stop_pending(UNIT(s))) {
1722 log_debug_unit(UNIT(s)->id, "Suppressing connection request on %s since unit stop is scheduled.", UNIT(s)->id);
1727 /* Flush all sockets by closing and reopening them */
1728 socket_close_fds(s);
1730 r = socket_open_fds(s);
1732 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1733 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1737 r = socket_watch_fds(s);
1739 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1740 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1750 bool pending = false;
1752 /* If there's already a start pending don't bother to
1754 SET_FOREACH(other, UNIT(s)->dependencies[UNIT_TRIGGERS], i)
1755 if (unit_active_or_pending(other)) {
1761 if (!UNIT_ISSET(s->service)) {
1762 log_error_unit(UNIT(s)->id, "%s: service to activate vanished, refusing activation.", UNIT(s)->id);
1767 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, true, &error, NULL);
1772 socket_set_state(s, SOCKET_RUNNING);
1774 _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
1777 if (s->n_connections >= s->max_connections) {
1778 log_warning_unit(UNIT(s)->id, "%s: Too many incoming connections (%u)", UNIT(s)->id, s->n_connections);
1783 r = socket_instantiate_service(s);
1787 r = instance_from_socket(cfd, s->n_accepted, &instance);
1792 /* ENOTCONN is legitimate if TCP RST was received.
1793 * This connection is over, but the socket unit lives on. */
1798 prefix = unit_name_to_prefix(UNIT(s)->id);
1804 name = unit_name_build(prefix, instance, ".service");
1810 r = unit_add_name(UNIT_DEREF(s->service), name);
1814 service = SERVICE(UNIT_DEREF(s->service));
1815 unit_ref_unset(&s->service);
1818 UNIT(service)->no_gc = false;
1820 unit_choose_id(UNIT(service), name);
1822 r = service_set_socket_fd(service, cfd, s);
1827 s->n_connections ++;
1829 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL);
1833 /* Notify clients about changed counters */
1834 unit_add_to_dbus_queue(UNIT(s));
1840 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",
1841 UNIT(s)->id, cfd >= 0 ? "template" : "non-template",
1842 bus_error_message(&error, r));
1844 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1848 static void socket_run_next(Socket *s) {
1852 assert(s->control_command);
1853 assert(s->control_command->command_next);
1855 socket_unwatch_control_pid(s);
1857 s->control_command = s->control_command->command_next;
1859 r = socket_spawn(s, s->control_command, &s->control_pid);
1866 log_warning_unit(UNIT(s)->id, "%s failed to run next task: %s", UNIT(s)->id, strerror(-r));
1868 if (s->state == SOCKET_START_POST)
1869 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1870 else if (s->state == SOCKET_STOP_POST)
1871 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1873 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1876 static int socket_start(Unit *u) {
1877 Socket *s = SOCKET(u);
1881 /* We cannot fulfill this request right now, try again later
1883 if (IN_SET(s->state,
1885 SOCKET_STOP_PRE_SIGKILL,
1886 SOCKET_STOP_PRE_SIGTERM,
1888 SOCKET_FINAL_SIGTERM,
1889 SOCKET_FINAL_SIGKILL))
1892 /* Already on it! */
1893 if (IN_SET(s->state,
1899 /* Cannot run this without the service being around */
1900 if (UNIT_ISSET(s->service)) {
1903 service = SERVICE(UNIT_DEREF(s->service));
1905 if (UNIT(service)->load_state != UNIT_LOADED) {
1906 log_error_unit(u->id, "Socket service %s not loaded, refusing.", UNIT(service)->id);
1910 /* If the service is already active we cannot start the
1912 if (service->state != SERVICE_DEAD &&
1913 service->state != SERVICE_FAILED &&
1914 service->state != SERVICE_AUTO_RESTART) {
1915 log_error_unit(u->id, "Socket service %s already active, refusing.", UNIT(service)->id);
1920 assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1922 s->result = SOCKET_SUCCESS;
1923 socket_enter_start_pre(s);
1928 static int socket_stop(Unit *u) {
1929 Socket *s = SOCKET(u);
1934 if (IN_SET(s->state,
1936 SOCKET_STOP_PRE_SIGTERM,
1937 SOCKET_STOP_PRE_SIGKILL,
1939 SOCKET_FINAL_SIGTERM,
1940 SOCKET_FINAL_SIGKILL))
1943 /* If there's already something running we go directly into
1945 if (IN_SET(s->state,
1948 SOCKET_START_POST)) {
1949 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
1953 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1955 socket_enter_stop_pre(s, SOCKET_SUCCESS);
1959 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1960 Socket *s = SOCKET(u);
1968 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1969 unit_serialize_item(u, f, "result", socket_result_to_string(s->result));
1970 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1972 if (s->control_pid > 0)
1973 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
1975 if (s->control_command_id >= 0)
1976 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1978 LIST_FOREACH(port, p, s->ports) {
1984 copy = fdset_put_dup(fds, p->fd);
1988 if (p->type == SOCKET_SOCKET) {
1989 _cleanup_free_ char *t = NULL;
1991 r = socket_address_print(&p->address, &t);
1995 if (socket_address_family(&p->address) == AF_NETLINK)
1996 unit_serialize_item_format(u, f, "netlink", "%i %s", copy, t);
1998 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
2000 } else if (p->type == SOCKET_SPECIAL)
2001 unit_serialize_item_format(u, f, "special", "%i %s", copy, p->path);
2002 else if (p->type == SOCKET_MQUEUE)
2003 unit_serialize_item_format(u, f, "mqueue", "%i %s", copy, p->path);
2005 assert(p->type == SOCKET_FIFO);
2006 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
2013 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
2014 Socket *s = SOCKET(u);
2020 if (streq(key, "state")) {
2023 state = socket_state_from_string(value);
2025 log_debug_unit(u->id, "Failed to parse state value %s", value);
2027 s->deserialized_state = state;
2028 } else if (streq(key, "result")) {
2031 f = socket_result_from_string(value);
2033 log_debug_unit(u->id, "Failed to parse result value %s", value);
2034 else if (f != SOCKET_SUCCESS)
2037 } else if (streq(key, "n-accepted")) {
2040 if (safe_atou(value, &k) < 0)
2041 log_debug_unit(u->id, "Failed to parse n-accepted value %s", value);
2044 } else if (streq(key, "control-pid")) {
2047 if (parse_pid(value, &pid) < 0)
2048 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
2050 s->control_pid = pid;
2051 } else if (streq(key, "control-command")) {
2052 SocketExecCommand id;
2054 id = socket_exec_command_from_string(value);
2056 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
2058 s->control_command_id = id;
2059 s->control_command = s->exec_command[id];
2061 } else if (streq(key, "fifo")) {
2065 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2066 log_debug_unit(u->id, "Failed to parse fifo value %s", value);
2069 LIST_FOREACH(port, p, s->ports)
2070 if (p->type == SOCKET_FIFO &&
2071 streq_ptr(p->path, value+skip))
2076 p->fd = fdset_remove(fds, fd);
2080 } else if (streq(key, "special")) {
2084 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2085 log_debug_unit(u->id, "Failed to parse special value %s", value);
2088 LIST_FOREACH(port, p, s->ports)
2089 if (p->type == SOCKET_SPECIAL &&
2090 streq_ptr(p->path, value+skip))
2095 p->fd = fdset_remove(fds, fd);
2099 } else if (streq(key, "mqueue")) {
2103 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2104 log_debug_unit(u->id, "Failed to parse mqueue value %s", value);
2107 LIST_FOREACH(port, p, s->ports)
2108 if (p->type == SOCKET_MQUEUE &&
2109 streq_ptr(p->path, value+skip))
2114 p->fd = fdset_remove(fds, fd);
2118 } else if (streq(key, "socket")) {
2119 int fd, type, skip = 0;
2122 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
2123 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2126 LIST_FOREACH(port, p, s->ports)
2127 if (socket_address_is(&p->address, value+skip, type))
2132 p->fd = fdset_remove(fds, fd);
2136 } else if (streq(key, "netlink")) {
2140 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2141 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2144 LIST_FOREACH(port, p, s->ports)
2145 if (socket_address_is_netlink(&p->address, value+skip))
2150 p->fd = fdset_remove(fds, fd);
2154 log_debug_unit(UNIT(s)->id, "Unknown serialization key '%s'", key);
2159 static int socket_distribute_fds(Unit *u, FDSet *fds) {
2160 Socket *s = SOCKET(u);
2165 LIST_FOREACH(port, p, s->ports) {
2169 if (p->type != SOCKET_SOCKET)
2175 FDSET_FOREACH(fd, fds, i) {
2176 if (socket_address_matches_fd(&p->address, fd)) {
2177 p->fd = fdset_remove(fds, fd);
2178 s->deserialized_state = SOCKET_LISTENING;
2187 _pure_ static UnitActiveState socket_active_state(Unit *u) {
2190 return state_translation_table[SOCKET(u)->state];
2193 _pure_ static const char *socket_sub_state_to_string(Unit *u) {
2196 return socket_state_to_string(SOCKET(u)->state);
2199 const char* socket_port_type_to_string(SocketPort *p) {
2207 switch (p->address.type) {
2215 case SOCK_SEQPACKET:
2216 return "SequentialPacket";
2219 if (socket_address_family(&p->address) == AF_NETLINK)
2226 case SOCKET_SPECIAL:
2230 return "MessageQueue";
2240 _pure_ static bool socket_check_gc(Unit *u) {
2241 Socket *s = SOCKET(u);
2245 return s->n_connections > 0;
2248 static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2249 SocketPort *p = userdata;
2255 if (p->socket->state != SOCKET_LISTENING)
2258 log_debug_unit(UNIT(p->socket)->id, "Incoming traffic on %s", UNIT(p->socket)->id);
2260 if (revents != EPOLLIN) {
2262 if (revents & EPOLLHUP)
2263 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.",
2264 UNIT(p->socket)->id);
2266 log_error_unit(UNIT(p->socket)->id, "%s: Got unexpected poll event (0x%x) on socket.",
2267 UNIT(p->socket)->id, revents);
2272 if (p->socket->accept &&
2273 p->type == SOCKET_SOCKET &&
2274 socket_address_can_accept(&p->address)) {
2278 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK);
2284 log_error_unit(UNIT(p->socket)->id,
2285 "Failed to accept socket: %m");
2292 socket_apply_socket_options(p->socket, cfd);
2295 socket_enter_running(p->socket, cfd);
2299 socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
2303 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2304 Socket *s = SOCKET(u);
2310 if (pid != s->control_pid)
2315 if (is_clean_exit(code, status, NULL))
2317 else if (code == CLD_EXITED)
2318 f = SOCKET_FAILURE_EXIT_CODE;
2319 else if (code == CLD_KILLED)
2320 f = SOCKET_FAILURE_SIGNAL;
2321 else if (code == CLD_DUMPED)
2322 f = SOCKET_FAILURE_CORE_DUMP;
2324 assert_not_reached("Unknown sigchld code");
2326 if (s->control_command) {
2327 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2329 if (s->control_command->ignore)
2333 log_full_unit(f == SOCKET_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2335 "%s control process exited, code=%s status=%i",
2336 u->id, sigchld_code_to_string(code), status);
2338 if (f != SOCKET_SUCCESS)
2341 if (s->control_command &&
2342 s->control_command->command_next &&
2343 f == SOCKET_SUCCESS) {
2345 log_debug_unit(u->id,
2346 "%s running next command for state %s",
2347 u->id, socket_state_to_string(s->state));
2350 s->control_command = NULL;
2351 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
2353 /* No further commands for this step, so let's figure
2354 * out what to do next */
2356 log_debug_unit(u->id,
2357 "%s got final SIGCHLD for state %s",
2358 u->id, socket_state_to_string(s->state));
2362 case SOCKET_START_PRE:
2363 if (f == SOCKET_SUCCESS)
2364 socket_enter_start_chown(s);
2366 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
2369 case SOCKET_START_CHOWN:
2370 if (f == SOCKET_SUCCESS)
2371 socket_enter_start_post(s);
2373 socket_enter_stop_pre(s, f);
2376 case SOCKET_START_POST:
2377 if (f == SOCKET_SUCCESS)
2378 socket_enter_listening(s);
2380 socket_enter_stop_pre(s, f);
2383 case SOCKET_STOP_PRE:
2384 case SOCKET_STOP_PRE_SIGTERM:
2385 case SOCKET_STOP_PRE_SIGKILL:
2386 socket_enter_stop_post(s, f);
2389 case SOCKET_STOP_POST:
2390 case SOCKET_FINAL_SIGTERM:
2391 case SOCKET_FINAL_SIGKILL:
2392 socket_enter_dead(s, f);
2396 assert_not_reached("Uh, control process died at wrong time.");
2400 /* Notify clients about changed exit status */
2401 unit_add_to_dbus_queue(u);
2404 static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2405 Socket *s = SOCKET(userdata);
2408 assert(s->timer_event_source == source);
2412 case SOCKET_START_PRE:
2413 log_warning_unit(UNIT(s)->id, "%s starting timed out. Terminating.", UNIT(s)->id);
2414 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2417 case SOCKET_START_CHOWN:
2418 case SOCKET_START_POST:
2419 log_warning_unit(UNIT(s)->id, "%s starting timed out. Stopping.", UNIT(s)->id);
2420 socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
2423 case SOCKET_STOP_PRE:
2424 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2425 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2428 case SOCKET_STOP_PRE_SIGTERM:
2429 if (s->kill_context.send_sigkill) {
2430 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Killing.", UNIT(s)->id);
2431 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2433 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2434 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2438 case SOCKET_STOP_PRE_SIGKILL:
2439 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2440 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2443 case SOCKET_STOP_POST:
2444 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Terminating.", UNIT(s)->id);
2445 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2448 case SOCKET_FINAL_SIGTERM:
2449 if (s->kill_context.send_sigkill) {
2450 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Killing.", UNIT(s)->id);
2451 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2453 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2454 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2458 case SOCKET_FINAL_SIGKILL:
2459 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL (2). Entering failed mode.", UNIT(s)->id);
2460 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2464 assert_not_reached("Timeout at wrong time.");
2470 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
2479 /* Called from the service code for requesting our fds */
2482 LIST_FOREACH(port, p, s->ports)
2492 if (!(rfds = new(int, rn_fds)))
2496 LIST_FOREACH(port, p, s->ports)
2500 assert(k == rn_fds);
2508 static void socket_reset_failed(Unit *u) {
2509 Socket *s = SOCKET(u);
2513 if (s->state == SOCKET_FAILED)
2514 socket_set_state(s, SOCKET_DEAD);
2516 s->result = SOCKET_SUCCESS;
2519 static void socket_notify_service_dead(Socket *s, bool failed_permanent) {
2522 /* The service is dead. Dang!
2524 * This is strictly for one-instance-for-all-connections
2527 if (s->state == SOCKET_RUNNING) {
2528 log_debug_unit(UNIT(s)->id, "%s got notified about service death (failed permanently: %s)", UNIT(s)->id, yes_no(failed_permanent));
2529 if (failed_permanent)
2530 socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_FAILED_PERMANENT);
2532 socket_enter_listening(s);
2536 void socket_connection_unref(Socket *s) {
2539 /* The service is dead. Yay!
2541 * This is strictly for one-instance-per-connection
2544 assert(s->n_connections > 0);
2547 log_debug_unit(UNIT(s)->id, "%s: One connection closed, %u left.", UNIT(s)->id, s->n_connections);
2550 static void socket_trigger_notify(Unit *u, Unit *other) {
2551 Socket *s = SOCKET(u);
2557 /* Don't propagate state changes from the service if we are
2558 already down or accepting connections */
2559 if ((s->state != SOCKET_RUNNING &&
2560 s->state != SOCKET_LISTENING) ||
2564 if (other->load_state != UNIT_LOADED ||
2565 other->type != UNIT_SERVICE)
2568 se = SERVICE(other);
2570 if (se->state == SERVICE_FAILED)
2571 socket_notify_service_dead(s, se->result == SERVICE_FAILURE_START_LIMIT);
2573 if (se->state == SERVICE_DEAD ||
2574 se->state == SERVICE_STOP ||
2575 se->state == SERVICE_STOP_SIGTERM ||
2576 se->state == SERVICE_STOP_SIGKILL ||
2577 se->state == SERVICE_STOP_POST ||
2578 se->state == SERVICE_FINAL_SIGTERM ||
2579 se->state == SERVICE_FINAL_SIGKILL ||
2580 se->state == SERVICE_AUTO_RESTART)
2581 socket_notify_service_dead(s, false);
2583 if (se->state == SERVICE_RUNNING)
2584 socket_set_state(s, SOCKET_RUNNING);
2587 static int socket_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2588 return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
2591 static int socket_get_timeout(Unit *u, uint64_t *timeout) {
2592 Socket *s = SOCKET(u);
2595 if (!s->timer_event_source)
2598 r = sd_event_source_get_time(s->timer_event_source, timeout);
2605 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
2606 [SOCKET_DEAD] = "dead",
2607 [SOCKET_START_PRE] = "start-pre",
2608 [SOCKET_START_CHOWN] = "start-chown",
2609 [SOCKET_START_POST] = "start-post",
2610 [SOCKET_LISTENING] = "listening",
2611 [SOCKET_RUNNING] = "running",
2612 [SOCKET_STOP_PRE] = "stop-pre",
2613 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
2614 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
2615 [SOCKET_STOP_POST] = "stop-post",
2616 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
2617 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
2618 [SOCKET_FAILED] = "failed"
2621 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
2623 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
2624 [SOCKET_EXEC_START_PRE] = "StartPre",
2625 [SOCKET_EXEC_START_CHOWN] = "StartChown",
2626 [SOCKET_EXEC_START_POST] = "StartPost",
2627 [SOCKET_EXEC_STOP_PRE] = "StopPre",
2628 [SOCKET_EXEC_STOP_POST] = "StopPost"
2631 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
2633 static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
2634 [SOCKET_SUCCESS] = "success",
2635 [SOCKET_FAILURE_RESOURCES] = "resources",
2636 [SOCKET_FAILURE_TIMEOUT] = "timeout",
2637 [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
2638 [SOCKET_FAILURE_SIGNAL] = "signal",
2639 [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
2640 [SOCKET_FAILURE_SERVICE_FAILED_PERMANENT] = "service-failed-permanent"
2643 DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
2645 const UnitVTable socket_vtable = {
2646 .object_size = sizeof(Socket),
2647 .exec_context_offset = offsetof(Socket, exec_context),
2648 .cgroup_context_offset = offsetof(Socket, cgroup_context),
2649 .kill_context_offset = offsetof(Socket, kill_context),
2650 .exec_runtime_offset = offsetof(Socket, exec_runtime),
2656 .private_section = "Socket",
2658 .init = socket_init,
2659 .done = socket_done,
2660 .load = socket_load,
2662 .coldplug = socket_coldplug,
2664 .dump = socket_dump,
2666 .start = socket_start,
2667 .stop = socket_stop,
2669 .kill = socket_kill,
2671 .get_timeout = socket_get_timeout,
2673 .serialize = socket_serialize,
2674 .deserialize_item = socket_deserialize_item,
2675 .distribute_fds = socket_distribute_fds,
2677 .active_state = socket_active_state,
2678 .sub_state_to_string = socket_sub_state_to_string,
2680 .check_gc = socket_check_gc,
2682 .sigchld_event = socket_sigchld_event,
2684 .trigger_notify = socket_trigger_notify,
2686 .reset_failed = socket_reset_failed,
2688 .bus_interface = "org.freedesktop.systemd1.Socket",
2689 .bus_vtable = bus_socket_vtable,
2690 .bus_set_property = bus_socket_set_property,
2691 .bus_commit_properties = bus_socket_commit_properties,
2693 .status_message_formats = {
2694 /*.starting_stopping = {
2695 [0] = "Starting socket %s...",
2696 [1] = "Stopping socket %s...",
2698 .finished_start_job = {
2699 [JOB_DONE] = "Listening on %s.",
2700 [JOB_FAILED] = "Failed to listen on %s.",
2701 [JOB_DEPENDENCY] = "Dependency failed for %s.",
2702 [JOB_TIMEOUT] = "Timed out starting %s.",
2704 .finished_stop_job = {
2705 [JOB_DONE] = "Closed %s.",
2706 [JOB_FAILED] = "Failed stopping %s.",
2707 [JOB_TIMEOUT] = "Timed out stopping %s.",