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) {
466 Socket *s = SOCKET(u);
473 prefix2 = strappenda(prefix, "\t");
476 "%sSocket State: %s\n"
478 "%sBindIPv6Only: %s\n"
480 "%sSocketMode: %04o\n"
481 "%sDirectoryMode: %04o\n"
485 "%sTransparent: %s\n"
487 "%sPassCredentials: %s\n"
488 "%sPassSecurity: %s\n"
489 "%sTCPCongestion: %s\n"
490 "%sRemoveOnStop: %s\n",
491 prefix, socket_state_to_string(s->state),
492 prefix, socket_result_to_string(s->result),
493 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
495 prefix, s->socket_mode,
496 prefix, s->directory_mode,
497 prefix, yes_no(s->keep_alive),
498 prefix, yes_no(s->no_delay),
499 prefix, yes_no(s->free_bind),
500 prefix, yes_no(s->transparent),
501 prefix, yes_no(s->broadcast),
502 prefix, yes_no(s->pass_cred),
503 prefix, yes_no(s->pass_sec),
504 prefix, strna(s->tcp_congestion),
505 prefix, yes_no(s->remove_on_stop));
507 if (s->control_pid > 0)
509 "%sControl PID: "PID_FMT"\n",
510 prefix, s->control_pid);
512 if (s->bind_to_device)
514 "%sBindToDevice: %s\n",
515 prefix, s->bind_to_device);
520 "%sNConnections: %u\n"
521 "%sMaxConnections: %u\n",
522 prefix, s->n_accepted,
523 prefix, s->n_connections,
524 prefix, s->max_connections);
526 if (s->priority >= 0)
529 prefix, s->priority);
531 if (s->receive_buffer > 0)
533 "%sReceiveBuffer: %zu\n",
534 prefix, s->receive_buffer);
536 if (s->send_buffer > 0)
538 "%sSendBuffer: %zu\n",
539 prefix, s->send_buffer);
551 if (s->pipe_size > 0)
554 prefix, s->pipe_size);
561 if (s->mq_maxmsg > 0)
563 "%sMessageQueueMaxMessages: %li\n",
564 prefix, s->mq_maxmsg);
566 if (s->mq_msgsize > 0)
568 "%sMessageQueueMessageSize: %li\n",
569 prefix, s->mq_msgsize);
574 prefix, yes_no(s->reuse_port));
578 "%sSmackLabel: %s\n",
583 "%sSmackLabelIPIn: %s\n",
584 prefix, s->smack_ip_in);
588 "%sSmackLabelIPOut: %s\n",
589 prefix, s->smack_ip_out);
591 if (!isempty(s->user) || !isempty(s->group))
594 "%sOwnerGroup: %s\n",
595 prefix, strna(s->user),
596 prefix, strna(s->group));
598 LIST_FOREACH(port, p, s->ports) {
600 if (p->type == SOCKET_SOCKET) {
605 if ((r = socket_address_print(&p->address, &k)) < 0)
610 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type), t);
612 } else if (p->type == SOCKET_SPECIAL)
613 fprintf(f, "%sListenSpecial: %s\n", prefix, p->path);
614 else if (p->type == SOCKET_MQUEUE)
615 fprintf(f, "%sListenMessageQueue: %s\n", prefix, p->path);
617 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
620 exec_context_dump(&s->exec_context, f, prefix);
621 kill_context_dump(&s->kill_context, f, prefix);
623 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
624 if (!s->exec_command[c])
627 fprintf(f, "%s-> %s:\n",
628 prefix, socket_exec_command_to_string(c));
630 exec_command_dump_list(s->exec_command[c], f, prefix2);
634 static int instance_from_socket(int fd, unsigned nr, char **instance) {
637 union sockaddr_union local, remote;
643 if (getsockname(fd, &local.sa, &l) < 0)
647 if (getpeername(fd, &remote.sa, &l) < 0)
650 switch (local.sa.sa_family) {
654 a = ntohl(local.in.sin_addr.s_addr),
655 b = ntohl(remote.in.sin_addr.s_addr);
658 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
660 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
661 ntohs(local.in.sin_port),
662 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
663 ntohs(remote.in.sin_port)) < 0)
670 static const unsigned char ipv4_prefix[] = {
671 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
674 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
675 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
677 *a = local.in6.sin6_addr.s6_addr+12,
678 *b = remote.in6.sin6_addr.s6_addr+12;
681 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
683 a[0], a[1], a[2], a[3],
684 ntohs(local.in6.sin6_port),
685 b[0], b[1], b[2], b[3],
686 ntohs(remote.in6.sin6_port)) < 0)
689 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
694 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
695 ntohs(local.in6.sin6_port),
696 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
697 ntohs(remote.in6.sin6_port)) < 0)
708 k = getpeercred(fd, &ucred);
711 "%u-"PID_FMT"-"UID_FMT,
712 nr, ucred.pid, ucred.uid) < 0)
714 } else if (k == -ENODATA) {
715 /* This handles the case where somebody is
716 * connecting from another pid/uid namespace
717 * (e.g. from outside of our container). */
729 assert_not_reached("Unhandled socket type.");
736 static void socket_close_fds(Socket *s) {
742 LIST_FOREACH(port, p, s->ports) {
744 p->event_source = sd_event_source_unref(p->event_source);
749 p->fd = safe_close(p->fd);
751 /* One little note: we should normally not delete any
752 * sockets in the file system here! After all some
753 * other process we spawned might still have a
754 * reference of this fd and wants to continue to use
755 * it. Therefore we delete sockets in the file system
756 * before we create a new one, not after we stopped
759 if (s->remove_on_stop) {
771 socket_address_unlink(&p->address);
780 if (s->remove_on_stop)
781 STRV_FOREACH(i, s->symlinks)
785 static void socket_apply_socket_options(Socket *s, int fd) {
790 int b = s->keep_alive;
791 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
792 log_warning_unit(UNIT(s)->id, "SO_KEEPALIVE failed: %m");
797 if (setsockopt(fd, SOL_TCP, TCP_NODELAY, &b, sizeof(b)) < 0)
798 log_warning_unit(UNIT(s)->id, "TCP_NODELAY failed: %m");
803 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)) < 0)
804 log_warning_unit(UNIT(s)->id, "SO_BROADCAST failed: %m");
809 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0)
810 log_warning_unit(UNIT(s)->id, "SO_PASSCRED failed: %m");
815 if (setsockopt(fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one)) < 0)
816 log_warning_unit(UNIT(s)->id, "SO_PASSSEC failed: %m");
819 if (s->priority >= 0)
820 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
821 log_warning_unit(UNIT(s)->id, "SO_PRIORITY failed: %m");
823 if (s->receive_buffer > 0) {
824 int value = (int) s->receive_buffer;
826 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
828 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
829 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
830 log_warning_unit(UNIT(s)->id, "SO_RCVBUF failed: %m");
833 if (s->send_buffer > 0) {
834 int value = (int) s->send_buffer;
835 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
836 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
837 log_warning_unit(UNIT(s)->id, "SO_SNDBUF failed: %m");
841 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
842 log_warning_unit(UNIT(s)->id, "SO_MARK failed: %m");
845 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
846 log_warning_unit(UNIT(s)->id, "IP_TOS failed: %m");
848 if (s->ip_ttl >= 0) {
851 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
853 if (socket_ipv6_is_supported())
854 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
857 errno = EAFNOSUPPORT;
861 log_warning_unit(UNIT(s)->id,
862 "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
865 if (s->tcp_congestion)
866 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
867 log_warning_unit(UNIT(s)->id, "TCP_CONGESTION failed: %m");
870 int b = s->reuse_port;
871 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &b, sizeof(b)) < 0)
872 log_warning_unit(UNIT(s)->id, "SO_REUSEPORT failed: %m");
876 if (smack_label_ip_in_fd(fd, s->smack_ip_in) < 0)
877 log_error_unit(UNIT(s)->id, "smack_label_ip_in_fd: %m");
880 if (smack_label_ip_out_fd(fd, s->smack_ip_out) < 0)
881 log_error_unit(UNIT(s)->id, "smack_label_ip_out_fd: %m");
884 static void socket_apply_fifo_options(Socket *s, int fd) {
888 if (s->pipe_size > 0)
889 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
890 log_warning_unit(UNIT(s)->id,
894 if (smack_label_fd(fd, s->smack) < 0)
895 log_error_unit(UNIT(s)->id, "smack_label_fd: %m");
898 static int fifo_address_create(
900 mode_t directory_mode,
911 mkdir_parents_label(path, directory_mode);
913 r = label_context_set(path, S_IFIFO);
917 /* Enforce the right access mode for the fifo */
918 old_mask = umask(~ socket_mode);
920 /* Include the original umask in our mask */
921 umask(~socket_mode | old_mask);
923 r = mkfifo(path, socket_mode);
926 if (r < 0 && errno != EEXIST) {
931 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
936 label_context_clear();
938 if (fstat(fd, &st) < 0) {
943 if (!S_ISFIFO(st.st_mode) ||
944 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
945 st.st_uid != getuid() ||
946 st.st_gid != getgid()) {
956 label_context_clear();
962 static int special_address_create(
972 fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
978 if (fstat(fd, &st) < 0) {
983 /* Check whether this is a /proc, /sys or /dev file or char device */
984 if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
998 static int mq_address_create(
1008 struct mq_attr _attr, *attr = NULL;
1013 if (maxmsg > 0 && msgsize > 0) {
1015 _attr.mq_flags = O_NONBLOCK;
1016 _attr.mq_maxmsg = maxmsg;
1017 _attr.mq_msgsize = msgsize;
1021 /* Enforce the right access mode for the mq */
1022 old_mask = umask(~ mq_mode);
1024 /* Include the original umask in our mask */
1025 umask(~mq_mode | old_mask);
1026 fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
1034 if (fstat(fd, &st) < 0) {
1039 if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
1040 st.st_uid != getuid() ||
1041 st.st_gid != getgid()) {
1055 static int socket_symlink(Socket *s) {
1061 p = socket_find_symlink_target(s);
1065 STRV_FOREACH(i, s->symlinks)
1071 static int socket_open_fds(Socket *s) {
1075 bool know_label = false;
1079 LIST_FOREACH(port, p, s->ports) {
1084 if (p->type == SOCKET_SOCKET) {
1088 r = socket_instantiate_service(s);
1092 if (UNIT_ISSET(s->service) &&
1093 SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]) {
1094 r = label_get_create_label_from_exe(SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]->path, &label);
1095 if (r < 0 && r != -EPERM)
1102 r = socket_address_listen(
1104 SOCK_CLOEXEC|SOCK_NONBLOCK,
1117 socket_apply_socket_options(s, p->fd);
1120 } else if (p->type == SOCKET_SPECIAL) {
1122 r = special_address_create(
1128 } else if (p->type == SOCKET_FIFO) {
1130 r = fifo_address_create(
1138 socket_apply_fifo_options(s, p->fd);
1141 } else if (p->type == SOCKET_MQUEUE) {
1143 r = mq_address_create(
1152 assert_not_reached("Unknown port type");
1159 socket_close_fds(s);
1164 static void socket_unwatch_fds(Socket *s) {
1170 LIST_FOREACH(port, p, s->ports) {
1174 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.");
1183 static int socket_watch_fds(Socket *s) {
1189 LIST_FOREACH(port, p, s->ports) {
1193 if (p->event_source)
1194 r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
1196 r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
1199 log_warning_unit(UNIT(s)->id, "Failed to watch listening fds: %s", strerror(-r));
1207 socket_unwatch_fds(s);
1211 static void socket_set_state(Socket *s, SocketState state) {
1212 SocketState old_state;
1215 old_state = s->state;
1223 SOCKET_STOP_PRE_SIGTERM,
1224 SOCKET_STOP_PRE_SIGKILL,
1226 SOCKET_FINAL_SIGTERM,
1227 SOCKET_FINAL_SIGKILL)) {
1229 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1230 socket_unwatch_control_pid(s);
1231 s->control_command = NULL;
1232 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1235 if (state != SOCKET_LISTENING)
1236 socket_unwatch_fds(s);
1244 SOCKET_STOP_PRE_SIGTERM,
1245 SOCKET_STOP_PRE_SIGKILL))
1246 socket_close_fds(s);
1248 if (state != old_state)
1249 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s",
1250 UNIT(s)->id, socket_state_to_string(old_state), socket_state_to_string(state));
1252 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
1255 static int socket_coldplug(Unit *u) {
1256 Socket *s = SOCKET(u);
1260 assert(s->state == SOCKET_DEAD);
1262 if (s->deserialized_state == s->state)
1265 if (IN_SET(s->deserialized_state,
1270 SOCKET_STOP_PRE_SIGTERM,
1271 SOCKET_STOP_PRE_SIGKILL,
1273 SOCKET_FINAL_SIGTERM,
1274 SOCKET_FINAL_SIGKILL)) {
1276 if (s->control_pid <= 0)
1279 r = unit_watch_pid(UNIT(s), s->control_pid);
1283 r = socket_arm_timer(s);
1288 if (IN_SET(s->deserialized_state,
1294 SOCKET_STOP_PRE_SIGTERM,
1295 SOCKET_STOP_PRE_SIGKILL)) {
1296 r = socket_open_fds(s);
1301 if (s->deserialized_state == SOCKET_LISTENING) {
1302 r = socket_watch_fds(s);
1307 socket_set_state(s, s->deserialized_state);
1311 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
1312 _cleanup_free_ char **argv = NULL;
1320 unit_realize_cgroup(UNIT(s));
1322 r = unit_setup_exec_runtime(UNIT(s));
1326 r = socket_arm_timer(s);
1330 r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1338 UNIT(s)->manager->environment,
1342 UNIT(s)->manager->confirm_spawn,
1343 UNIT(s)->manager->cgroup_supported,
1344 UNIT(s)->cgroup_path,
1345 manager_get_runtime_prefix(UNIT(s)->manager),
1354 r = unit_watch_pid(UNIT(s), pid);
1356 /* FIXME: we need to do something here */
1363 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1367 static int socket_chown(Socket *s, pid_t *_pid) {
1371 r = socket_arm_timer(s);
1375 /* We have to resolve the user names out-of-process, hence
1376 * let's fork here. It's messy, but well, what can we do? */
1384 uid_t uid = (uid_t) -1;
1385 gid_t gid = (gid_t) -1;
1388 default_signals(SIGNALS_CRASH_HANDLER, SIGNALS_IGNORE, -1);
1389 ignore_signals(SIGPIPE, -1);
1392 if (!isempty(s->user)) {
1393 const char *user = s->user;
1395 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1402 if (!isempty(s->group)) {
1403 const char *group = s->group;
1405 r = get_group_creds(&group, &gid);
1412 LIST_FOREACH(port, p, s->ports) {
1413 const char *path = NULL;
1415 if (p->type == SOCKET_SOCKET)
1416 path = socket_address_get_path(&p->address);
1417 else if (p->type == SOCKET_FIFO)
1423 if (chown(path, uid, gid) < 0) {
1434 log_error("Failed to chown socket at step %s: %s", exit_status_to_string(ret, EXIT_STATUS_SYSTEMD), strerror(-r));
1439 r = unit_watch_pid(UNIT(s), pid);
1447 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1451 static void socket_enter_dead(Socket *s, SocketResult f) {
1454 if (f != SOCKET_SUCCESS)
1457 exec_runtime_destroy(s->exec_runtime);
1458 s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1460 exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1462 socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
1465 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
1467 static void socket_enter_stop_post(Socket *s, SocketResult f) {
1471 if (f != SOCKET_SUCCESS)
1474 socket_unwatch_control_pid(s);
1475 s->control_command_id = SOCKET_EXEC_STOP_POST;
1476 s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
1478 if (s->control_command) {
1479 r = socket_spawn(s, s->control_command, &s->control_pid);
1483 socket_set_state(s, SOCKET_STOP_POST);
1485 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
1490 log_warning_unit(UNIT(s)->id,
1491 "%s failed to run 'stop-post' task: %s",
1492 UNIT(s)->id, strerror(-r));
1493 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1496 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
1501 if (f != SOCKET_SUCCESS)
1504 r = unit_kill_context(
1507 state != SOCKET_STOP_PRE_SIGTERM && state != SOCKET_FINAL_SIGTERM,
1515 r = socket_arm_timer(s);
1519 socket_set_state(s, state);
1520 } else if (state == SOCKET_STOP_PRE_SIGTERM)
1521 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
1522 else if (state == SOCKET_STOP_PRE_SIGKILL)
1523 socket_enter_stop_post(s, SOCKET_SUCCESS);
1524 else if (state == SOCKET_FINAL_SIGTERM)
1525 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
1527 socket_enter_dead(s, SOCKET_SUCCESS);
1532 log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1534 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1535 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1537 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1540 static void socket_enter_stop_pre(Socket *s, SocketResult f) {
1544 if (f != SOCKET_SUCCESS)
1547 socket_unwatch_control_pid(s);
1548 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1549 s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
1551 if (s->control_command) {
1552 r = socket_spawn(s, s->control_command, &s->control_pid);
1556 socket_set_state(s, SOCKET_STOP_PRE);
1558 socket_enter_stop_post(s, SOCKET_SUCCESS);
1563 log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-pre' task: %s", UNIT(s)->id, strerror(-r));
1564 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1567 static void socket_enter_listening(Socket *s) {
1571 r = socket_watch_fds(s);
1573 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1577 socket_set_state(s, SOCKET_LISTENING);
1581 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1584 static void socket_enter_start_post(Socket *s) {
1588 socket_unwatch_control_pid(s);
1589 s->control_command_id = SOCKET_EXEC_START_POST;
1590 s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
1592 if (s->control_command) {
1593 r = socket_spawn(s, s->control_command, &s->control_pid);
1595 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1599 socket_set_state(s, SOCKET_START_POST);
1601 socket_enter_listening(s);
1606 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1609 static void socket_enter_start_chown(Socket *s) {
1614 r = socket_open_fds(s);
1616 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1620 if (!isempty(s->user) || !isempty(s->group)) {
1622 socket_unwatch_control_pid(s);
1623 s->control_command_id = SOCKET_EXEC_START_CHOWN;
1624 s->control_command = NULL;
1626 r = socket_chown(s, &s->control_pid);
1628 log_warning_unit(UNIT(s)->id, "%s failed to fork 'start-chown' task: %s", UNIT(s)->id, strerror(-r));
1632 socket_set_state(s, SOCKET_START_CHOWN);
1634 socket_enter_start_post(s);
1639 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1642 static void socket_enter_start_pre(Socket *s) {
1646 socket_unwatch_control_pid(s);
1647 s->control_command_id = SOCKET_EXEC_START_PRE;
1648 s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
1650 if (s->control_command) {
1651 r = socket_spawn(s, s->control_command, &s->control_pid);
1653 log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1657 socket_set_state(s, SOCKET_START_PRE);
1659 socket_enter_start_chown(s);
1664 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1667 static void socket_enter_running(Socket *s, int cfd) {
1668 _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1673 /* We don't take connections anymore if we are supposed to
1674 * shut down anyway */
1675 if (unit_stop_pending(UNIT(s))) {
1677 log_debug_unit(UNIT(s)->id, "Suppressing connection request on %s since unit stop is scheduled.", UNIT(s)->id);
1682 /* Flush all sockets by closing and reopening them */
1683 socket_close_fds(s);
1685 r = socket_open_fds(s);
1687 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1688 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1692 r = socket_watch_fds(s);
1694 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1695 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1705 bool pending = false;
1707 /* If there's already a start pending don't bother to
1709 SET_FOREACH(other, UNIT(s)->dependencies[UNIT_TRIGGERS], i)
1710 if (unit_active_or_pending(other)) {
1716 if (!UNIT_ISSET(s->service)) {
1717 log_error_unit(UNIT(s)->id, "%s: service to activate vanished, refusing activation.", UNIT(s)->id);
1722 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, true, &error, NULL);
1727 socket_set_state(s, SOCKET_RUNNING);
1729 _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
1732 if (s->n_connections >= s->max_connections) {
1733 log_warning_unit(UNIT(s)->id, "%s: Too many incoming connections (%u)", UNIT(s)->id, s->n_connections);
1738 r = socket_instantiate_service(s);
1742 r = instance_from_socket(cfd, s->n_accepted, &instance);
1747 /* ENOTCONN is legitimate if TCP RST was received.
1748 * This connection is over, but the socket unit lives on. */
1753 prefix = unit_name_to_prefix(UNIT(s)->id);
1759 name = unit_name_build(prefix, instance, ".service");
1765 r = unit_add_name(UNIT_DEREF(s->service), name);
1769 service = SERVICE(UNIT_DEREF(s->service));
1770 unit_ref_unset(&s->service);
1773 UNIT(service)->no_gc = false;
1775 unit_choose_id(UNIT(service), name);
1777 r = service_set_socket_fd(service, cfd, s);
1782 s->n_connections ++;
1784 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL);
1788 /* Notify clients about changed counters */
1789 unit_add_to_dbus_queue(UNIT(s));
1795 log_warning_unit(UNIT(s)->id, "%s failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
1796 UNIT(s)->id, cfd >= 0 ? "template" : "non-template",
1797 bus_error_message(&error, r));
1799 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1803 static void socket_run_next(Socket *s) {
1807 assert(s->control_command);
1808 assert(s->control_command->command_next);
1810 socket_unwatch_control_pid(s);
1812 s->control_command = s->control_command->command_next;
1814 r = socket_spawn(s, s->control_command, &s->control_pid);
1821 log_warning_unit(UNIT(s)->id, "%s failed to run next task: %s", UNIT(s)->id, strerror(-r));
1823 if (s->state == SOCKET_START_POST)
1824 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1825 else if (s->state == SOCKET_STOP_POST)
1826 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1828 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1831 static int socket_start(Unit *u) {
1832 Socket *s = SOCKET(u);
1836 /* We cannot fulfill this request right now, try again later
1838 if (IN_SET(s->state,
1840 SOCKET_STOP_PRE_SIGKILL,
1841 SOCKET_STOP_PRE_SIGTERM,
1843 SOCKET_FINAL_SIGTERM,
1844 SOCKET_FINAL_SIGKILL))
1847 /* Already on it! */
1848 if (IN_SET(s->state,
1854 /* Cannot run this without the service being around */
1855 if (UNIT_ISSET(s->service)) {
1858 service = SERVICE(UNIT_DEREF(s->service));
1860 if (UNIT(service)->load_state != UNIT_LOADED) {
1861 log_error_unit(u->id, "Socket service %s not loaded, refusing.", UNIT(service)->id);
1865 /* If the service is already active we cannot start the
1867 if (service->state != SERVICE_DEAD &&
1868 service->state != SERVICE_FAILED &&
1869 service->state != SERVICE_AUTO_RESTART) {
1870 log_error_unit(u->id, "Socket service %s already active, refusing.", UNIT(service)->id);
1875 assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1877 s->result = SOCKET_SUCCESS;
1878 socket_enter_start_pre(s);
1883 static int socket_stop(Unit *u) {
1884 Socket *s = SOCKET(u);
1889 if (IN_SET(s->state,
1891 SOCKET_STOP_PRE_SIGTERM,
1892 SOCKET_STOP_PRE_SIGKILL,
1894 SOCKET_FINAL_SIGTERM,
1895 SOCKET_FINAL_SIGKILL))
1898 /* If there's already something running we go directly into
1900 if (IN_SET(s->state,
1903 SOCKET_START_POST)) {
1904 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
1908 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1910 socket_enter_stop_pre(s, SOCKET_SUCCESS);
1914 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1915 Socket *s = SOCKET(u);
1923 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1924 unit_serialize_item(u, f, "result", socket_result_to_string(s->result));
1925 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1927 if (s->control_pid > 0)
1928 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
1930 if (s->control_command_id >= 0)
1931 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1933 LIST_FOREACH(port, p, s->ports) {
1939 copy = fdset_put_dup(fds, p->fd);
1943 if (p->type == SOCKET_SOCKET) {
1944 _cleanup_free_ char *t = NULL;
1946 r = socket_address_print(&p->address, &t);
1950 if (socket_address_family(&p->address) == AF_NETLINK)
1951 unit_serialize_item_format(u, f, "netlink", "%i %s", copy, t);
1953 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1955 } else if (p->type == SOCKET_SPECIAL)
1956 unit_serialize_item_format(u, f, "special", "%i %s", copy, p->path);
1957 else if (p->type == SOCKET_MQUEUE)
1958 unit_serialize_item_format(u, f, "mqueue", "%i %s", copy, p->path);
1960 assert(p->type == SOCKET_FIFO);
1961 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1968 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1969 Socket *s = SOCKET(u);
1975 if (streq(key, "state")) {
1978 state = socket_state_from_string(value);
1980 log_debug_unit(u->id, "Failed to parse state value %s", value);
1982 s->deserialized_state = state;
1983 } else if (streq(key, "result")) {
1986 f = socket_result_from_string(value);
1988 log_debug_unit(u->id, "Failed to parse result value %s", value);
1989 else if (f != SOCKET_SUCCESS)
1992 } else if (streq(key, "n-accepted")) {
1995 if (safe_atou(value, &k) < 0)
1996 log_debug_unit(u->id, "Failed to parse n-accepted value %s", value);
1999 } else if (streq(key, "control-pid")) {
2002 if (parse_pid(value, &pid) < 0)
2003 log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
2005 s->control_pid = pid;
2006 } else if (streq(key, "control-command")) {
2007 SocketExecCommand id;
2009 id = socket_exec_command_from_string(value);
2011 log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
2013 s->control_command_id = id;
2014 s->control_command = s->exec_command[id];
2016 } else if (streq(key, "fifo")) {
2020 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2021 log_debug_unit(u->id, "Failed to parse fifo value %s", value);
2024 LIST_FOREACH(port, p, s->ports)
2025 if (p->type == SOCKET_FIFO &&
2026 streq_ptr(p->path, value+skip))
2031 p->fd = fdset_remove(fds, fd);
2035 } else if (streq(key, "special")) {
2039 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2040 log_debug_unit(u->id, "Failed to parse special value %s", value);
2043 LIST_FOREACH(port, p, s->ports)
2044 if (p->type == SOCKET_SPECIAL &&
2045 streq_ptr(p->path, value+skip))
2050 p->fd = fdset_remove(fds, fd);
2054 } else if (streq(key, "mqueue")) {
2058 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2059 log_debug_unit(u->id, "Failed to parse mqueue value %s", value);
2062 LIST_FOREACH(port, p, s->ports)
2063 if (p->type == SOCKET_MQUEUE &&
2064 streq_ptr(p->path, value+skip))
2069 p->fd = fdset_remove(fds, fd);
2073 } else if (streq(key, "socket")) {
2074 int fd, type, skip = 0;
2077 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
2078 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2081 LIST_FOREACH(port, p, s->ports)
2082 if (socket_address_is(&p->address, value+skip, type))
2087 p->fd = fdset_remove(fds, fd);
2091 } else if (streq(key, "netlink")) {
2095 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
2096 log_debug_unit(u->id, "Failed to parse socket value %s", value);
2099 LIST_FOREACH(port, p, s->ports)
2100 if (socket_address_is_netlink(&p->address, value+skip))
2105 p->fd = fdset_remove(fds, fd);
2109 log_debug_unit(UNIT(s)->id, "Unknown serialization key '%s'", key);
2114 static int socket_distribute_fds(Unit *u, FDSet *fds) {
2115 Socket *s = SOCKET(u);
2120 LIST_FOREACH(port, p, s->ports) {
2124 if (p->type != SOCKET_SOCKET)
2130 FDSET_FOREACH(fd, fds, i) {
2131 if (socket_address_matches_fd(&p->address, fd)) {
2132 p->fd = fdset_remove(fds, fd);
2133 s->deserialized_state = SOCKET_LISTENING;
2142 _pure_ static UnitActiveState socket_active_state(Unit *u) {
2145 return state_translation_table[SOCKET(u)->state];
2148 _pure_ static const char *socket_sub_state_to_string(Unit *u) {
2151 return socket_state_to_string(SOCKET(u)->state);
2154 const char* socket_port_type_to_string(SocketPort *p) {
2162 switch (p->address.type) {
2170 case SOCK_SEQPACKET:
2171 return "SequentialPacket";
2174 if (socket_address_family(&p->address) == AF_NETLINK)
2181 case SOCKET_SPECIAL:
2185 return "MessageQueue";
2195 _pure_ static bool socket_check_gc(Unit *u) {
2196 Socket *s = SOCKET(u);
2200 return s->n_connections > 0;
2203 static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
2204 SocketPort *p = userdata;
2210 if (p->socket->state != SOCKET_LISTENING)
2213 log_debug_unit(UNIT(p->socket)->id, "Incoming traffic on %s", UNIT(p->socket)->id);
2215 if (revents != EPOLLIN) {
2217 if (revents & EPOLLHUP)
2218 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.",
2219 UNIT(p->socket)->id);
2221 log_error_unit(UNIT(p->socket)->id, "%s: Got unexpected poll event (0x%x) on socket.",
2222 UNIT(p->socket)->id, revents);
2227 if (p->socket->accept &&
2228 p->type == SOCKET_SOCKET &&
2229 socket_address_can_accept(&p->address)) {
2233 cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK);
2239 log_error_unit(UNIT(p->socket)->id,
2240 "Failed to accept socket: %m");
2247 socket_apply_socket_options(p->socket, cfd);
2250 socket_enter_running(p->socket, cfd);
2254 socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
2258 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2259 Socket *s = SOCKET(u);
2265 if (pid != s->control_pid)
2270 if (is_clean_exit(code, status, NULL))
2272 else if (code == CLD_EXITED)
2273 f = SOCKET_FAILURE_EXIT_CODE;
2274 else if (code == CLD_KILLED)
2275 f = SOCKET_FAILURE_SIGNAL;
2276 else if (code == CLD_DUMPED)
2277 f = SOCKET_FAILURE_CORE_DUMP;
2279 assert_not_reached("Unknown sigchld code");
2281 if (s->control_command) {
2282 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2284 if (s->control_command->ignore)
2288 log_full_unit(f == SOCKET_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2290 "%s control process exited, code=%s status=%i",
2291 u->id, sigchld_code_to_string(code), status);
2293 if (f != SOCKET_SUCCESS)
2296 if (s->control_command &&
2297 s->control_command->command_next &&
2298 f == SOCKET_SUCCESS) {
2300 log_debug_unit(u->id,
2301 "%s running next command for state %s",
2302 u->id, socket_state_to_string(s->state));
2305 s->control_command = NULL;
2306 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
2308 /* No further commands for this step, so let's figure
2309 * out what to do next */
2311 log_debug_unit(u->id,
2312 "%s got final SIGCHLD for state %s",
2313 u->id, socket_state_to_string(s->state));
2317 case SOCKET_START_PRE:
2318 if (f == SOCKET_SUCCESS)
2319 socket_enter_start_chown(s);
2321 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
2324 case SOCKET_START_CHOWN:
2325 if (f == SOCKET_SUCCESS)
2326 socket_enter_start_post(s);
2328 socket_enter_stop_pre(s, f);
2331 case SOCKET_START_POST:
2332 if (f == SOCKET_SUCCESS)
2333 socket_enter_listening(s);
2335 socket_enter_stop_pre(s, f);
2338 case SOCKET_STOP_PRE:
2339 case SOCKET_STOP_PRE_SIGTERM:
2340 case SOCKET_STOP_PRE_SIGKILL:
2341 socket_enter_stop_post(s, f);
2344 case SOCKET_STOP_POST:
2345 case SOCKET_FINAL_SIGTERM:
2346 case SOCKET_FINAL_SIGKILL:
2347 socket_enter_dead(s, f);
2351 assert_not_reached("Uh, control process died at wrong time.");
2355 /* Notify clients about changed exit status */
2356 unit_add_to_dbus_queue(u);
2359 static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2360 Socket *s = SOCKET(userdata);
2363 assert(s->timer_event_source == source);
2367 case SOCKET_START_PRE:
2368 log_warning_unit(UNIT(s)->id, "%s starting timed out. Terminating.", UNIT(s)->id);
2369 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2372 case SOCKET_START_CHOWN:
2373 case SOCKET_START_POST:
2374 log_warning_unit(UNIT(s)->id, "%s starting timed out. Stopping.", UNIT(s)->id);
2375 socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
2378 case SOCKET_STOP_PRE:
2379 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Terminating.", UNIT(s)->id);
2380 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2383 case SOCKET_STOP_PRE_SIGTERM:
2384 if (s->kill_context.send_sigkill) {
2385 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Killing.", UNIT(s)->id);
2386 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2388 log_warning_unit(UNIT(s)->id, "%s stopping timed out. Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2389 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2393 case SOCKET_STOP_PRE_SIGKILL:
2394 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2395 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2398 case SOCKET_STOP_POST:
2399 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Terminating.", UNIT(s)->id);
2400 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2403 case SOCKET_FINAL_SIGTERM:
2404 if (s->kill_context.send_sigkill) {
2405 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Killing.", UNIT(s)->id);
2406 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2408 log_warning_unit(UNIT(s)->id, "%s stopping timed out (2). Skipping SIGKILL. Ignoring.", UNIT(s)->id);
2409 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2413 case SOCKET_FINAL_SIGKILL:
2414 log_warning_unit(UNIT(s)->id, "%s still around after SIGKILL (2). Entering failed mode.", UNIT(s)->id);
2415 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2419 assert_not_reached("Timeout at wrong time.");
2425 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
2434 /* Called from the service code for requesting our fds */
2437 LIST_FOREACH(port, p, s->ports)
2447 if (!(rfds = new(int, rn_fds)))
2451 LIST_FOREACH(port, p, s->ports)
2455 assert(k == rn_fds);
2463 static void socket_reset_failed(Unit *u) {
2464 Socket *s = SOCKET(u);
2468 if (s->state == SOCKET_FAILED)
2469 socket_set_state(s, SOCKET_DEAD);
2471 s->result = SOCKET_SUCCESS;
2474 static void socket_notify_service_dead(Socket *s, bool failed_permanent) {
2477 /* The service is dead. Dang!
2479 * This is strictly for one-instance-for-all-connections
2482 if (s->state == SOCKET_RUNNING) {
2483 log_debug_unit(UNIT(s)->id, "%s got notified about service death (failed permanently: %s)", UNIT(s)->id, yes_no(failed_permanent));
2484 if (failed_permanent)
2485 socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_FAILED_PERMANENT);
2487 socket_enter_listening(s);
2491 void socket_connection_unref(Socket *s) {
2494 /* The service is dead. Yay!
2496 * This is strictly for one-instance-per-connection
2499 assert(s->n_connections > 0);
2502 log_debug_unit(UNIT(s)->id, "%s: One connection closed, %u left.", UNIT(s)->id, s->n_connections);
2505 static void socket_trigger_notify(Unit *u, Unit *other) {
2506 Socket *s = SOCKET(u);
2512 /* Don't propagate state changes from the service if we are
2513 already down or accepting connections */
2514 if ((s->state != SOCKET_RUNNING &&
2515 s->state != SOCKET_LISTENING) ||
2519 if (other->load_state != UNIT_LOADED ||
2520 other->type != UNIT_SERVICE)
2523 se = SERVICE(other);
2525 if (se->state == SERVICE_FAILED)
2526 socket_notify_service_dead(s, se->result == SERVICE_FAILURE_START_LIMIT);
2528 if (se->state == SERVICE_DEAD ||
2529 se->state == SERVICE_STOP ||
2530 se->state == SERVICE_STOP_SIGTERM ||
2531 se->state == SERVICE_STOP_SIGKILL ||
2532 se->state == SERVICE_STOP_POST ||
2533 se->state == SERVICE_FINAL_SIGTERM ||
2534 se->state == SERVICE_FINAL_SIGKILL ||
2535 se->state == SERVICE_AUTO_RESTART)
2536 socket_notify_service_dead(s, false);
2538 if (se->state == SERVICE_RUNNING)
2539 socket_set_state(s, SOCKET_RUNNING);
2542 static int socket_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2543 return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
2546 static int socket_get_timeout(Unit *u, uint64_t *timeout) {
2547 Socket *s = SOCKET(u);
2550 if (!s->timer_event_source)
2553 r = sd_event_source_get_time(s->timer_event_source, timeout);
2560 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
2561 [SOCKET_DEAD] = "dead",
2562 [SOCKET_START_PRE] = "start-pre",
2563 [SOCKET_START_CHOWN] = "start-chown",
2564 [SOCKET_START_POST] = "start-post",
2565 [SOCKET_LISTENING] = "listening",
2566 [SOCKET_RUNNING] = "running",
2567 [SOCKET_STOP_PRE] = "stop-pre",
2568 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
2569 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
2570 [SOCKET_STOP_POST] = "stop-post",
2571 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
2572 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
2573 [SOCKET_FAILED] = "failed"
2576 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
2578 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
2579 [SOCKET_EXEC_START_PRE] = "StartPre",
2580 [SOCKET_EXEC_START_CHOWN] = "StartChown",
2581 [SOCKET_EXEC_START_POST] = "StartPost",
2582 [SOCKET_EXEC_STOP_PRE] = "StopPre",
2583 [SOCKET_EXEC_STOP_POST] = "StopPost"
2586 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
2588 static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
2589 [SOCKET_SUCCESS] = "success",
2590 [SOCKET_FAILURE_RESOURCES] = "resources",
2591 [SOCKET_FAILURE_TIMEOUT] = "timeout",
2592 [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
2593 [SOCKET_FAILURE_SIGNAL] = "signal",
2594 [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
2595 [SOCKET_FAILURE_SERVICE_FAILED_PERMANENT] = "service-failed-permanent"
2598 DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
2600 const UnitVTable socket_vtable = {
2601 .object_size = sizeof(Socket),
2602 .exec_context_offset = offsetof(Socket, exec_context),
2603 .cgroup_context_offset = offsetof(Socket, cgroup_context),
2604 .kill_context_offset = offsetof(Socket, kill_context),
2605 .exec_runtime_offset = offsetof(Socket, exec_runtime),
2611 .private_section = "Socket",
2613 .init = socket_init,
2614 .done = socket_done,
2615 .load = socket_load,
2617 .coldplug = socket_coldplug,
2619 .dump = socket_dump,
2621 .start = socket_start,
2622 .stop = socket_stop,
2624 .kill = socket_kill,
2626 .get_timeout = socket_get_timeout,
2628 .serialize = socket_serialize,
2629 .deserialize_item = socket_deserialize_item,
2630 .distribute_fds = socket_distribute_fds,
2632 .active_state = socket_active_state,
2633 .sub_state_to_string = socket_sub_state_to_string,
2635 .check_gc = socket_check_gc,
2637 .sigchld_event = socket_sigchld_event,
2639 .trigger_notify = socket_trigger_notify,
2641 .reset_failed = socket_reset_failed,
2643 .bus_interface = "org.freedesktop.systemd1.Socket",
2644 .bus_vtable = bus_socket_vtable,
2645 .bus_set_property = bus_socket_set_property,
2646 .bus_commit_properties = bus_socket_commit_properties,
2648 .status_message_formats = {
2649 /*.starting_stopping = {
2650 [0] = "Starting socket %s...",
2651 [1] = "Stopping socket %s...",
2653 .finished_start_job = {
2654 [JOB_DONE] = "Listening on %s.",
2655 [JOB_FAILED] = "Failed to listen on %s.",
2656 [JOB_DEPENDENCY] = "Dependency failed for %s.",
2657 [JOB_TIMEOUT] = "Timed out starting %s.",
2659 .finished_stop_job = {
2660 [JOB_DONE] = "Closed %s.",
2661 [JOB_FAILED] = "Failed stopping %s.",
2662 [JOB_TIMEOUT] = "Timed out stopping %s.",