1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #include <netinet/tcp.h>
12 #include <linux/sctp.h>
14 #include "alloc-util.h"
15 #include "bpf-firewall.h"
16 #include "bus-error.h"
19 #include "dbus-socket.h"
21 #include "exit-status.h"
23 #include "format-util.h"
25 #include "in-addr-util.h"
27 #include "ip-protocol-list.h"
32 #include "parse-util.h"
33 #include "path-util.h"
34 #include "process-util.h"
35 #include "selinux-util.h"
36 #include "serialize.h"
37 #include "signal-util.h"
38 #include "smack-util.h"
41 #include "string-table.h"
42 #include "string-util.h"
44 #include "unit-name.h"
46 #include "user-util.h"
52 union sockaddr_union peer
;
56 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
57 [SOCKET_DEAD
] = UNIT_INACTIVE
,
58 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
59 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
60 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
61 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
62 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
63 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
64 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
65 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
66 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
67 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
68 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
69 [SOCKET_FAILED
] = UNIT_FAILED
72 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
73 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
75 static void socket_init(Unit
*u
) {
76 Socket
*s
= SOCKET(u
);
79 assert(u
->load_state
== UNIT_STUB
);
81 s
->backlog
= SOMAXCONN
;
82 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
83 s
->directory_mode
= 0755;
84 s
->socket_mode
= 0666;
86 s
->max_connections
= 64;
93 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
94 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
96 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
98 s
->trigger_limit
.interval
= USEC_INFINITY
;
99 s
->trigger_limit
.burst
= (unsigned) -1;
102 static void socket_unwatch_control_pid(Socket
*s
) {
105 if (s
->control_pid
<= 0)
108 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
112 static void socket_cleanup_fd_list(SocketPort
*p
) {
115 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
116 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
117 p
->n_auxiliary_fds
= 0;
120 void socket_free_ports(Socket
*s
) {
125 while ((p
= s
->ports
)) {
126 LIST_REMOVE(port
, s
->ports
, p
);
128 sd_event_source_unref(p
->event_source
);
130 socket_cleanup_fd_list(p
);
137 static void socket_done(Unit
*u
) {
138 Socket
*s
= SOCKET(u
);
143 socket_free_ports(s
);
145 while ((p
= set_steal_first(s
->peers_by_address
)))
148 s
->peers_by_address
= set_free(s
->peers_by_address
);
150 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
151 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
152 s
->control_command
= NULL
;
154 dynamic_creds_unref(&s
->dynamic_creds
);
156 socket_unwatch_control_pid(s
);
158 unit_ref_unset(&s
->service
);
160 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
161 s
->bind_to_device
= mfree(s
->bind_to_device
);
163 s
->smack
= mfree(s
->smack
);
164 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
165 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
167 strv_free(s
->symlinks
);
169 s
->user
= mfree(s
->user
);
170 s
->group
= mfree(s
->group
);
172 s
->fdname
= mfree(s
->fdname
);
174 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
177 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
182 if (s
->timer_event_source
) {
183 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
187 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
190 if (usec
== USEC_INFINITY
)
193 r
= sd_event_add_time(
194 UNIT(s
)->manager
->event
,
195 &s
->timer_event_source
,
198 socket_dispatch_timer
, s
);
202 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
207 int socket_instantiate_service(Socket
*s
) {
208 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
214 /* This fills in s->service if it isn't filled in yet. For
215 * Accept=yes sockets we create the next connection service
216 * here. For Accept=no this is mostly a NOP since the service
217 * is figured out at load time anyway. */
219 if (UNIT_DEREF(s
->service
))
225 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
229 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
232 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
236 unit_ref_set(&s
->service
, UNIT(s
), u
);
238 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false, UNIT_DEPENDENCY_IMPLICIT
);
241 static bool have_non_accept_socket(Socket
*s
) {
249 LIST_FOREACH(port
, p
, s
->ports
) {
251 if (p
->type
!= SOCKET_SOCKET
)
254 if (!socket_address_can_accept(&p
->address
))
261 static int socket_add_mount_dependencies(Socket
*s
) {
267 LIST_FOREACH(port
, p
, s
->ports
) {
268 const char *path
= NULL
;
270 if (p
->type
== SOCKET_SOCKET
)
271 path
= socket_address_get_path(&p
->address
);
272 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
278 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
286 static int socket_add_device_dependencies(Socket
*s
) {
291 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
294 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
295 return unit_add_node_dependency(UNIT(s
), t
, false, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
298 static int socket_add_default_dependencies(Socket
*s
) {
302 if (!UNIT(s
)->default_dependencies
)
305 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
309 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
310 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
315 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
318 _pure_
static bool socket_has_exec(Socket
*s
) {
322 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
323 if (s
->exec_command
[i
])
329 static int socket_add_extras(Socket
*s
) {
335 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
336 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
337 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
338 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
339 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
340 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
341 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
342 * service starts are typical. */
344 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
345 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
347 if (s
->trigger_limit
.burst
== (unsigned) -1) {
349 s
->trigger_limit
.burst
= 200;
351 s
->trigger_limit
.burst
= 20;
354 if (have_non_accept_socket(s
)) {
356 if (!UNIT_DEREF(s
->service
)) {
359 r
= unit_load_related_unit(u
, ".service", &x
);
363 unit_ref_set(&s
->service
, u
, x
);
366 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
371 r
= socket_add_mount_dependencies(s
);
375 r
= socket_add_device_dependencies(s
);
379 r
= unit_patch_contexts(u
);
383 if (socket_has_exec(s
)) {
384 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
389 r
= unit_set_default_slice(u
);
393 r
= socket_add_default_dependencies(s
);
400 static const char *socket_find_symlink_target(Socket
*s
) {
401 const char *found
= NULL
;
404 LIST_FOREACH(port
, p
, s
->ports
) {
405 const char *f
= NULL
;
414 f
= socket_address_get_path(&p
->address
);
432 static int socket_verify(Socket
*s
) {
435 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
439 log_unit_error(UNIT(s
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
443 if (s
->accept
&& have_non_accept_socket(s
)) {
444 log_unit_error(UNIT(s
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
448 if (s
->accept
&& s
->max_connections
<= 0) {
449 log_unit_error(UNIT(s
), "MaxConnection= setting too small. Refusing.");
453 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
454 log_unit_error(UNIT(s
), "Explicit service configuration for accepting socket units not supported. Refusing.");
458 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
459 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
463 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
464 log_unit_error(UNIT(s
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
471 static void peer_address_hash_func(const SocketPeer
*s
, struct siphash
*state
) {
474 if (s
->peer
.sa
.sa_family
== AF_INET
)
475 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
476 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
477 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
478 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
479 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
481 assert_not_reached("Unknown address family.");
484 static int peer_address_compare_func(const SocketPeer
*x
, const SocketPeer
*y
) {
487 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
491 switch(x
->peer
.sa
.sa_family
) {
493 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
495 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
497 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
499 assert_not_reached("Black sheep in the family!");
502 DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops
, SocketPeer
, peer_address_hash_func
, peer_address_compare_func
);
504 static int socket_load(Unit
*u
) {
505 Socket
*s
= SOCKET(u
);
509 assert(u
->load_state
== UNIT_STUB
);
511 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
515 r
= unit_load_fragment_and_dropin(u
);
519 if (u
->load_state
== UNIT_LOADED
) {
520 /* This is a new unit? Then let's add in some extras */
521 r
= socket_add_extras(s
);
526 return socket_verify(s
);
529 static SocketPeer
*socket_peer_new(void) {
532 p
= new0(SocketPeer
, 1);
541 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
545 set_remove(p
->socket
->peers_by_address
, p
);
550 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
552 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
553 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
554 SocketPeer sa
= {}, *i
;
555 socklen_t salen
= sizeof(sa
.peer
);
561 r
= getpeername(fd
, &sa
.peer
.sa
, &salen
);
563 return log_error_errno(errno
, "getpeername failed: %m");
565 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
570 i
= set_get(s
->peers_by_address
, &sa
);
572 *p
= socket_peer_ref(i
);
576 remote
= socket_peer_new();
580 remote
->peer
= sa
.peer
;
581 remote
->peer_salen
= salen
;
583 r
= set_put(s
->peers_by_address
, remote
);
589 *p
= TAKE_PTR(remote
);
594 _const_
static const char* listen_lookup(int family
, int type
) {
596 if (family
== AF_NETLINK
)
597 return "ListenNetlink";
599 if (type
== SOCK_STREAM
)
600 return "ListenStream";
601 else if (type
== SOCK_DGRAM
)
602 return "ListenDatagram";
603 else if (type
== SOCK_SEQPACKET
)
604 return "ListenSequentialPacket";
606 assert_not_reached("Unknown socket type");
610 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
611 char time_string
[FORMAT_TIMESPAN_MAX
];
613 Socket
*s
= SOCKET(u
);
615 const char *prefix2
, *str
;
620 prefix
= strempty(prefix
);
621 prefix2
= strjoina(prefix
, "\t");
624 "%sSocket State: %s\n"
626 "%sBindIPv6Only: %s\n"
628 "%sSocketMode: %04o\n"
629 "%sDirectoryMode: %04o\n"
633 "%sTransparent: %s\n"
635 "%sPassCredentials: %s\n"
636 "%sPassSecurity: %s\n"
637 "%sTCPCongestion: %s\n"
638 "%sRemoveOnStop: %s\n"
640 "%sFileDescriptorName: %s\n"
641 "%sSELinuxContextFromNet: %s\n",
642 prefix
, socket_state_to_string(s
->state
),
643 prefix
, socket_result_to_string(s
->result
),
644 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
646 prefix
, s
->socket_mode
,
647 prefix
, s
->directory_mode
,
648 prefix
, yes_no(s
->keep_alive
),
649 prefix
, yes_no(s
->no_delay
),
650 prefix
, yes_no(s
->free_bind
),
651 prefix
, yes_no(s
->transparent
),
652 prefix
, yes_no(s
->broadcast
),
653 prefix
, yes_no(s
->pass_cred
),
654 prefix
, yes_no(s
->pass_sec
),
655 prefix
, strna(s
->tcp_congestion
),
656 prefix
, yes_no(s
->remove_on_stop
),
657 prefix
, yes_no(s
->writable
),
658 prefix
, socket_fdname(s
),
659 prefix
, yes_no(s
->selinux_context_from_net
));
661 if (s
->control_pid
> 0)
663 "%sControl PID: "PID_FMT
"\n",
664 prefix
, s
->control_pid
);
666 if (s
->bind_to_device
)
668 "%sBindToDevice: %s\n",
669 prefix
, s
->bind_to_device
);
674 "%sNConnections: %u\n"
675 "%sMaxConnections: %u\n"
676 "%sMaxConnectionsPerSource: %u\n",
677 prefix
, s
->n_accepted
,
678 prefix
, s
->n_connections
,
679 prefix
, s
->max_connections
,
680 prefix
, s
->max_connections_per_source
);
682 if (s
->priority
>= 0)
685 prefix
, s
->priority
);
687 if (s
->receive_buffer
> 0)
689 "%sReceiveBuffer: %zu\n",
690 prefix
, s
->receive_buffer
);
692 if (s
->send_buffer
> 0)
694 "%sSendBuffer: %zu\n",
695 prefix
, s
->send_buffer
);
707 if (s
->pipe_size
> 0)
710 prefix
, s
->pipe_size
);
717 if (s
->mq_maxmsg
> 0)
719 "%sMessageQueueMaxMessages: %li\n",
720 prefix
, s
->mq_maxmsg
);
722 if (s
->mq_msgsize
> 0)
724 "%sMessageQueueMessageSize: %li\n",
725 prefix
, s
->mq_msgsize
);
730 prefix
, yes_no(s
->reuse_port
));
734 "%sSmackLabel: %s\n",
739 "%sSmackLabelIPIn: %s\n",
740 prefix
, s
->smack_ip_in
);
744 "%sSmackLabelIPOut: %s\n",
745 prefix
, s
->smack_ip_out
);
747 if (!isempty(s
->user
) || !isempty(s
->group
))
750 "%sSocketGroup: %s\n",
751 prefix
, strna(s
->user
),
752 prefix
, strna(s
->group
));
754 if (s
->keep_alive_time
> 0)
756 "%sKeepAliveTimeSec: %s\n",
757 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
759 if (s
->keep_alive_interval
> 0)
761 "%sKeepAliveIntervalSec: %s\n",
762 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
764 if (s
->keep_alive_cnt
> 0)
766 "%sKeepAliveProbes: %u\n",
767 prefix
, s
->keep_alive_cnt
);
769 if (s
->defer_accept
> 0)
771 "%sDeferAcceptSec: %s\n",
772 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
774 LIST_FOREACH(port
, p
, s
->ports
) {
777 case SOCKET_SOCKET
: {
778 _cleanup_free_
char *k
= NULL
;
782 r
= socket_address_print(&p
->address
, &k
);
788 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
792 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
794 case SOCKET_USB_FUNCTION
:
795 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
798 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
801 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
806 "%sTriggerLimitIntervalSec: %s\n"
807 "%sTriggerLimitBurst: %u\n",
808 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
809 prefix
, s
->trigger_limit
.burst
);
811 str
= ip_protocol_to_name(s
->socket_protocol
);
813 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
815 if (!strv_isempty(s
->symlinks
)) {
818 fprintf(f
, "%sSymlinks:", prefix
);
819 STRV_FOREACH(q
, s
->symlinks
)
820 fprintf(f
, " %s", *q
);
826 "%sTimeoutSec: %s\n",
827 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->timeout_usec
, USEC_PER_SEC
));
829 exec_context_dump(&s
->exec_context
, f
, prefix
);
830 kill_context_dump(&s
->kill_context
, f
, prefix
);
832 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
833 if (!s
->exec_command
[c
])
836 fprintf(f
, "%s-> %s:\n",
837 prefix
, socket_exec_command_to_string(c
));
839 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
842 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
845 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
848 union sockaddr_union local
, remote
;
854 if (getsockname(fd
, &local
.sa
, &l
) < 0)
858 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
861 switch (local
.sa
.sa_family
) {
865 a
= be32toh(local
.in
.sin_addr
.s_addr
),
866 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
869 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
871 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
872 be16toh(local
.in
.sin_port
),
873 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
874 be16toh(remote
.in
.sin_port
)) < 0)
881 static const unsigned char ipv4_prefix
[] = {
882 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
885 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
886 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
888 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
889 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
892 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
894 a
[0], a
[1], a
[2], a
[3],
895 be16toh(local
.in6
.sin6_port
),
896 b
[0], b
[1], b
[2], b
[3],
897 be16toh(remote
.in6
.sin6_port
)) < 0)
900 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
905 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
906 be16toh(local
.in6
.sin6_port
),
907 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
908 be16toh(remote
.in6
.sin6_port
)) < 0)
919 k
= getpeercred(fd
, &ucred
);
922 "%u-"PID_FMT
"-"UID_FMT
,
923 nr
, ucred
.pid
, ucred
.uid
) < 0)
925 } else if (k
== -ENODATA
) {
926 /* This handles the case where somebody is
927 * connecting from another pid/uid namespace
928 * (e.g. from outside of our container). */
943 local
.vm
.svm_cid
, local
.vm
.svm_port
,
944 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
950 assert_not_reached("Unhandled socket type.");
957 static void socket_close_fds(Socket
*s
) {
963 LIST_FOREACH(port
, p
, s
->ports
) {
966 was_open
= p
->fd
>= 0;
968 p
->event_source
= sd_event_source_unref(p
->event_source
);
969 p
->fd
= safe_close(p
->fd
);
970 socket_cleanup_fd_list(p
);
972 /* One little note: we should normally not delete any sockets in the file system here! After all some
973 * other process we spawned might still have a reference of this fd and wants to continue to use
974 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
975 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
976 * anyway, but only then. */
978 if (!was_open
|| !s
->remove_on_stop
)
984 (void) unlink(p
->path
);
988 (void) mq_unlink(p
->path
);
992 (void) socket_address_unlink(&p
->address
);
1000 if (s
->remove_on_stop
)
1001 STRV_FOREACH(i
, s
->symlinks
)
1005 static void socket_apply_socket_options(Socket
*s
, int fd
) {
1011 if (s
->keep_alive
) {
1012 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
1014 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
1017 if (s
->keep_alive_time
> 0) {
1018 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
1020 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
1023 if (s
->keep_alive_interval
> 0) {
1024 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
1026 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
1029 if (s
->keep_alive_cnt
> 0) {
1030 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
1032 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
1035 if (s
->defer_accept
> 0) {
1036 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
1038 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
1042 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1043 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1045 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1047 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1049 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1054 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1056 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1060 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1062 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1066 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1068 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1071 if (s
->priority
>= 0) {
1072 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1074 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1077 if (s
->receive_buffer
> 0) {
1078 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1079 if (setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, s
->receive_buffer
) < 0) {
1080 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, s
->receive_buffer
);
1082 log_unit_warning_errno(UNIT(s
), r
, "SO_RCVBUF failed: %m");
1086 if (s
->send_buffer
> 0) {
1087 if (setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, s
->send_buffer
) < 0) {
1088 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, s
->send_buffer
);
1090 log_unit_warning_errno(UNIT(s
), r
, "SO_SNDBUF failed: %m");
1095 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1097 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1100 if (s
->ip_tos
>= 0) {
1101 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1103 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1106 if (s
->ip_ttl
>= 0) {
1109 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TTL
, s
->ip_ttl
);
1111 if (socket_ipv6_is_supported())
1112 x
= setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, s
->ip_ttl
);
1117 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1120 if (s
->tcp_congestion
)
1121 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1122 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1124 if (s
->smack_ip_in
) {
1125 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1127 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1130 if (s
->smack_ip_out
) {
1131 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1133 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1137 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1143 if (s
->pipe_size
> 0)
1144 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1145 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1148 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1150 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1154 static int fifo_address_create(
1156 mode_t directory_mode
,
1157 mode_t socket_mode
) {
1159 _cleanup_close_
int fd
= -1;
1166 (void) mkdir_parents_label(path
, directory_mode
);
1168 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1172 /* Enforce the right access mode for the fifo */
1173 old_mask
= umask(~socket_mode
);
1175 /* Include the original umask in our mask */
1176 (void) umask(~socket_mode
| old_mask
);
1178 r
= mkfifo(path
, socket_mode
);
1179 (void) umask(old_mask
);
1181 if (r
< 0 && errno
!= EEXIST
) {
1186 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1192 mac_selinux_create_file_clear();
1194 if (fstat(fd
, &st
) < 0) {
1199 if (!S_ISFIFO(st
.st_mode
) ||
1200 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1201 st
.st_uid
!= getuid() ||
1202 st
.st_gid
!= getgid()) {
1210 mac_selinux_create_file_clear();
1214 static int special_address_create(const char *path
, bool writable
) {
1215 _cleanup_close_
int fd
= -1;
1220 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1224 if (fstat(fd
, &st
) < 0)
1227 /* Check whether this is a /proc, /sys or /dev file or char device */
1228 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1234 static int usbffs_address_create(const char *path
) {
1235 _cleanup_close_
int fd
= -1;
1240 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1244 if (fstat(fd
, &st
) < 0)
1247 /* Check whether this is a regular file (ffs endpoint) */
1248 if (!S_ISREG(st
.st_mode
))
1254 static int mq_address_create(
1260 _cleanup_close_
int fd
= -1;
1263 struct mq_attr _attr
, *attr
= NULL
;
1267 if (maxmsg
> 0 && msgsize
> 0) {
1268 _attr
= (struct mq_attr
) {
1269 .mq_flags
= O_NONBLOCK
,
1270 .mq_maxmsg
= maxmsg
,
1271 .mq_msgsize
= msgsize
,
1276 /* Enforce the right access mode for the mq */
1277 old_mask
= umask(~mq_mode
);
1279 /* Include the original umask in our mask */
1280 (void) umask(~mq_mode
| old_mask
);
1281 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1282 (void) umask(old_mask
);
1287 if (fstat(fd
, &st
) < 0)
1290 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1291 st
.st_uid
!= getuid() ||
1292 st
.st_gid
!= getgid())
1298 static int socket_symlink(Socket
*s
) {
1305 p
= socket_find_symlink_target(s
);
1309 STRV_FOREACH(i
, s
->symlinks
) {
1310 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1312 r
= symlink_idempotent(p
, *i
, false);
1314 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1315 /* If there's already something where we want to create the symlink, and the destructive
1316 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1319 if (unlink(*i
) >= 0)
1320 r
= symlink_idempotent(p
, *i
, false);
1324 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s → %s, ignoring: %m", p
, *i
);
1330 static int usbffs_write_descs(int fd
, Service
*s
) {
1333 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1336 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1340 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1343 static int usbffs_select_ep(const struct dirent
*d
) {
1344 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1347 static int usbffs_dispatch_eps(SocketPort
*p
) {
1348 _cleanup_free_
struct dirent
**ent
= NULL
;
1352 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1357 p
->auxiliary_fds
= new(int, n
);
1358 if (!p
->auxiliary_fds
) {
1363 p
->n_auxiliary_fds
= n
;
1366 for (i
= 0; i
< n
; ++i
) {
1367 _cleanup_free_
char *ep
= NULL
;
1369 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1375 path_simplify(ep
, false);
1377 r
= usbffs_address_create(ep
);
1381 p
->auxiliary_fds
[k
++] = r
;
1388 close_many(p
->auxiliary_fds
, k
);
1389 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1390 p
->n_auxiliary_fds
= 0;
1393 for (i
= 0; i
< n
; ++i
)
1399 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1402 _cleanup_free_
char *path
= NULL
;
1408 if (s
->selinux_context_from_net
) {
1409 /* If this is requested, get label from the network label */
1411 r
= mac_selinux_get_our_label(ret
);
1412 if (r
== -EOPNOTSUPP
)
1416 /* Otherwise, get it from the executable we are about to start */
1417 r
= socket_instantiate_service(s
);
1421 if (!UNIT_ISSET(s
->service
))
1424 service
= SERVICE(UNIT_DEREF(s
->service
));
1425 c
= service
->exec_command
[SERVICE_EXEC_START
];
1429 r
= chase_symlinks(c
->path
, service
->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
);
1433 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1434 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1445 static int socket_address_listen_do(
1447 const SocketAddress
*address
,
1448 const char *label
) {
1453 return socket_address_listen(
1455 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1467 static int socket_address_listen_in_cgroup(
1469 const SocketAddress
*address
,
1470 const char *label
) {
1472 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1479 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1480 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1481 * unit's cgroup for the purpose of BPF filtering and such. */
1483 if (!IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
1484 goto shortcut
; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1486 r
= bpf_firewall_supported();
1489 if (r
== BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1492 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1493 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1495 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1497 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1501 pair
[0] = safe_close(pair
[0]);
1503 fd
= socket_address_listen_do(s
, address
, label
);
1505 log_unit_error_errno(UNIT(s
), fd
, "Failed to create listening socket: %m");
1506 _exit(EXIT_FAILURE
);
1509 r
= send_one_fd(pair
[1], fd
, 0);
1511 log_unit_error_errno(UNIT(s
), r
, "Failed to send listening socket to parent: %m");
1512 _exit(EXIT_FAILURE
);
1515 _exit(EXIT_SUCCESS
);
1518 pair
[1] = safe_close(pair
[1]);
1519 fd
= receive_one_fd(pair
[0], 0);
1521 /* We synchronously wait for the helper, as it shouldn't be slow */
1522 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1529 return log_unit_error_errno(UNIT(s
), fd
, "Failed to receive listening socket: %m");
1534 fd
= socket_address_listen_do(s
, address
, label
);
1536 return log_error_errno(fd
, "Failed to create listening socket: %m");
1541 static int socket_open_fds(Socket
*s
) {
1542 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1543 bool know_label
= false;
1549 LIST_FOREACH(port
, p
, s
->ports
) {
1559 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1560 * we need this and remember it for the rest. */
1562 r
= socket_determine_selinux_label(s
, &label
);
1569 /* Apply the socket protocol */
1570 switch (p
->address
.type
) {
1573 case SOCK_SEQPACKET
:
1574 if (s
->socket_protocol
== IPPROTO_SCTP
)
1575 p
->address
.protocol
= s
->socket_protocol
;
1579 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1580 p
->address
.protocol
= s
->socket_protocol
;
1584 r
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1589 socket_apply_socket_options(s
, p
->fd
);
1593 case SOCKET_SPECIAL
:
1595 p
->fd
= special_address_create(p
->path
, s
->writable
);
1604 p
->fd
= fifo_address_create(
1613 socket_apply_fifo_options(s
, p
->fd
);
1619 p
->fd
= mq_address_create(
1630 case SOCKET_USB_FUNCTION
: {
1631 _cleanup_free_
char *ep
= NULL
;
1633 ep
= path_make_absolute("ep0", p
->path
);
1635 p
->fd
= usbffs_address_create(ep
);
1641 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1645 r
= usbffs_dispatch_eps(p
);
1652 assert_not_reached("Unknown port type");
1659 socket_close_fds(s
);
1663 static void socket_unwatch_fds(Socket
*s
) {
1669 LIST_FOREACH(port
, p
, s
->ports
) {
1673 if (!p
->event_source
)
1676 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1678 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1682 static int socket_watch_fds(Socket
*s
) {
1688 LIST_FOREACH(port
, p
, s
->ports
) {
1692 if (p
->event_source
) {
1693 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1697 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1701 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1708 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1709 socket_unwatch_fds(s
);
1719 static int socket_check_open(Socket
*s
) {
1720 bool have_open
= false, have_closed
= false;
1725 LIST_FOREACH(port
, p
, s
->ports
) {
1731 if (have_open
&& have_closed
)
1732 return SOCKET_OPEN_SOME
;
1736 return SOCKET_OPEN_ALL
;
1738 return SOCKET_OPEN_NONE
;
1741 static void socket_set_state(Socket
*s
, SocketState state
) {
1742 SocketState old_state
;
1745 old_state
= s
->state
;
1753 SOCKET_STOP_PRE_SIGTERM
,
1754 SOCKET_STOP_PRE_SIGKILL
,
1756 SOCKET_FINAL_SIGTERM
,
1757 SOCKET_FINAL_SIGKILL
)) {
1759 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1760 socket_unwatch_control_pid(s
);
1761 s
->control_command
= NULL
;
1762 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1765 if (state
!= SOCKET_LISTENING
)
1766 socket_unwatch_fds(s
);
1774 SOCKET_STOP_PRE_SIGTERM
,
1775 SOCKET_STOP_PRE_SIGKILL
))
1776 socket_close_fds(s
);
1778 if (state
!= old_state
)
1779 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1781 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
1784 static int socket_coldplug(Unit
*u
) {
1785 Socket
*s
= SOCKET(u
);
1789 assert(s
->state
== SOCKET_DEAD
);
1791 if (s
->deserialized_state
== s
->state
)
1794 if (s
->control_pid
> 0 &&
1795 pid_is_unwaited(s
->control_pid
) &&
1796 IN_SET(s
->deserialized_state
,
1801 SOCKET_STOP_PRE_SIGTERM
,
1802 SOCKET_STOP_PRE_SIGKILL
,
1804 SOCKET_FINAL_SIGTERM
,
1805 SOCKET_FINAL_SIGKILL
)) {
1807 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1811 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1816 if (IN_SET(s
->deserialized_state
,
1822 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1823 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1824 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1825 * and if there's a mismatch, warn loudly. */
1827 r
= socket_check_open(s
);
1828 if (r
== SOCKET_OPEN_NONE
)
1829 log_unit_warning(UNIT(s
),
1830 "Socket unit configuration has changed while unit has been running, "
1831 "no open socket file descriptor left. "
1832 "The socket unit is not functional until restarted.");
1833 else if (r
== SOCKET_OPEN_SOME
)
1834 log_unit_warning(UNIT(s
),
1835 "Socket unit configuration has changed while unit has been running, "
1836 "and some socket file descriptors have not been opened yet. "
1837 "The socket unit is not fully functional until restarted.");
1840 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1841 r
= socket_watch_fds(s
);
1846 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
)) {
1847 (void) unit_setup_dynamic_creds(u
);
1848 (void) unit_setup_exec_runtime(u
);
1851 socket_set_state(s
, s
->deserialized_state
);
1855 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1857 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1858 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1871 r
= unit_prepare_exec(UNIT(s
));
1875 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1879 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1883 r
= exec_spawn(UNIT(s
),
1893 r
= unit_watch_pid(UNIT(s
), pid
);
1895 /* FIXME: we need to do something here */
1903 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1907 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1911 /* We have to resolve the user names out-of-process, hence
1912 * let's fork here. It's messy, but well, what can we do? */
1914 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1918 uid_t uid
= UID_INVALID
;
1919 gid_t gid
= GID_INVALID
;
1924 if (!isempty(s
->user
)) {
1925 const char *user
= s
->user
;
1927 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1929 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1934 if (!isempty(s
->group
)) {
1935 const char *group
= s
->group
;
1937 r
= get_group_creds(&group
, &gid
, 0);
1939 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1944 LIST_FOREACH(port
, p
, s
->ports
) {
1945 const char *path
= NULL
;
1947 if (p
->type
== SOCKET_SOCKET
)
1948 path
= socket_address_get_path(&p
->address
);
1949 else if (p
->type
== SOCKET_FIFO
)
1955 if (chown(path
, uid
, gid
) < 0) {
1956 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1961 _exit(EXIT_SUCCESS
);
1964 r
= unit_watch_pid(UNIT(s
), pid
);
1972 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1976 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1979 if (s
->result
== SOCKET_SUCCESS
)
1982 if (s
->result
== SOCKET_SUCCESS
)
1983 unit_log_success(UNIT(s
));
1985 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
1987 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1989 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
1991 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
1993 unit_unref_uid_gid(UNIT(s
), true);
1995 dynamic_creds_destroy(&s
->dynamic_creds
);
1998 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2000 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2004 if (s
->result
== SOCKET_SUCCESS
)
2007 socket_unwatch_control_pid(s
);
2008 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2009 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2011 if (s
->control_command
) {
2012 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2016 socket_set_state(s
, SOCKET_STOP_POST
);
2018 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2023 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2024 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2027 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2032 if (s
->result
== SOCKET_SUCCESS
)
2035 r
= unit_kill_context(
2038 !IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FINAL_SIGTERM
) ?
2039 KILL_KILL
: KILL_TERMINATE
,
2047 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2051 socket_set_state(s
, state
);
2052 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2053 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2054 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2055 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2056 else if (state
== SOCKET_FINAL_SIGTERM
)
2057 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2059 socket_enter_dead(s
, SOCKET_SUCCESS
);
2064 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2066 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2067 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2069 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2072 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2076 if (s
->result
== SOCKET_SUCCESS
)
2079 socket_unwatch_control_pid(s
);
2080 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2081 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2083 if (s
->control_command
) {
2084 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2088 socket_set_state(s
, SOCKET_STOP_PRE
);
2090 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2095 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2096 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2099 static void socket_enter_listening(Socket
*s
) {
2103 r
= socket_watch_fds(s
);
2105 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2109 socket_set_state(s
, SOCKET_LISTENING
);
2113 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2116 static void socket_enter_start_post(Socket
*s
) {
2120 socket_unwatch_control_pid(s
);
2121 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2122 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2124 if (s
->control_command
) {
2125 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2127 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2131 socket_set_state(s
, SOCKET_START_POST
);
2133 socket_enter_listening(s
);
2138 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2141 static void socket_enter_start_chown(Socket
*s
) {
2146 r
= socket_open_fds(s
);
2148 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2152 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2154 socket_unwatch_control_pid(s
);
2155 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2156 s
->control_command
= NULL
;
2158 r
= socket_chown(s
, &s
->control_pid
);
2160 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2164 socket_set_state(s
, SOCKET_START_CHOWN
);
2166 socket_enter_start_post(s
);
2171 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2174 static void socket_enter_start_pre(Socket
*s
) {
2178 socket_unwatch_control_pid(s
);
2180 unit_warn_leftover_processes(UNIT(s
));
2182 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2183 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2185 if (s
->control_command
) {
2186 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2188 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2192 socket_set_state(s
, SOCKET_START_PRE
);
2194 socket_enter_start_chown(s
);
2199 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2202 static void flush_ports(Socket
*s
) {
2205 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2208 LIST_FOREACH(port
, p
, s
->ports
) {
2212 (void) flush_accept(p
->fd
);
2213 (void) flush_fd(p
->fd
);
2217 static void socket_enter_running(Socket
*s
, int cfd
) {
2218 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2221 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2226 /* We don't take connections anymore if we are supposed to shut down anyway */
2227 if (unit_stop_pending(UNIT(s
))) {
2229 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2239 if (!ratelimit_below(&s
->trigger_limit
)) {
2240 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2241 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2246 bool pending
= false;
2251 /* If there's already a start pending don't bother to
2253 HASHMAP_FOREACH_KEY(v
, other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2254 if (unit_active_or_pending(other
)) {
2260 if (!UNIT_ISSET(s
->service
)) {
2261 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2266 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2271 socket_set_state(s
, SOCKET_RUNNING
);
2273 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2274 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2277 if (s
->n_connections
>= s
->max_connections
) {
2278 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2283 if (s
->max_connections_per_source
> 0) {
2284 r
= socket_acquire_peer(s
, cfd
, &p
);
2287 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2288 _cleanup_free_
char *t
= NULL
;
2290 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2292 log_unit_warning(UNIT(s
),
2293 "Too many incoming connections (%u) from source %s, dropping connection.",
2294 p
->n_ref
, strnull(t
));
2299 r
= socket_instantiate_service(s
);
2303 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2308 /* ENOTCONN is legitimate if TCP RST was received.
2309 * This connection is over, but the socket unit lives on. */
2310 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2314 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2318 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2322 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2326 service
= SERVICE(UNIT_DEREF(s
->service
));
2327 unit_ref_unset(&s
->service
);
2330 unit_choose_id(UNIT(service
), name
);
2332 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2336 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2339 service
->peer
= TAKE_PTR(p
); /* Pass ownership of the peer reference */
2341 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2343 /* We failed to activate the new service, but it still exists. Let's make sure the service
2344 * closes and forgets the connection fd again, immediately. */
2345 service_close_socket_fd(service
);
2349 /* Notify clients about changed counters */
2350 unit_add_to_dbus_queue(UNIT(s
));
2361 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2362 cfd
>= 0 ? "template" : "non-template",
2363 bus_error_message(&error
, r
));
2365 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2369 static void socket_run_next(Socket
*s
) {
2373 assert(s
->control_command
);
2374 assert(s
->control_command
->command_next
);
2376 socket_unwatch_control_pid(s
);
2378 s
->control_command
= s
->control_command
->command_next
;
2380 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2387 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2389 if (s
->state
== SOCKET_START_POST
)
2390 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2391 else if (s
->state
== SOCKET_STOP_POST
)
2392 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2394 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2397 static int socket_start(Unit
*u
) {
2398 Socket
*s
= SOCKET(u
);
2403 /* We cannot fulfill this request right now, try again later
2405 if (IN_SET(s
->state
,
2407 SOCKET_STOP_PRE_SIGKILL
,
2408 SOCKET_STOP_PRE_SIGTERM
,
2410 SOCKET_FINAL_SIGTERM
,
2411 SOCKET_FINAL_SIGKILL
))
2414 /* Already on it! */
2415 if (IN_SET(s
->state
,
2421 /* Cannot run this without the service being around */
2422 if (UNIT_ISSET(s
->service
)) {
2425 service
= SERVICE(UNIT_DEREF(s
->service
));
2427 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2428 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2432 /* If the service is already active we cannot start the
2434 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
2435 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2440 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2442 r
= unit_start_limit_test(u
);
2444 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2448 r
= unit_acquire_invocation_id(u
);
2452 s
->result
= SOCKET_SUCCESS
;
2453 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2455 u
->reset_accounting
= true;
2457 socket_enter_start_pre(s
);
2461 static int socket_stop(Unit
*u
) {
2462 Socket
*s
= SOCKET(u
);
2467 if (IN_SET(s
->state
,
2469 SOCKET_STOP_PRE_SIGTERM
,
2470 SOCKET_STOP_PRE_SIGKILL
,
2472 SOCKET_FINAL_SIGTERM
,
2473 SOCKET_FINAL_SIGKILL
))
2476 /* If there's already something running we go directly into
2478 if (IN_SET(s
->state
,
2481 SOCKET_START_POST
)) {
2482 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2486 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2488 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2492 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2493 Socket
*s
= SOCKET(u
);
2501 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2502 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2503 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2504 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2506 if (s
->control_pid
> 0)
2507 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
2509 if (s
->control_command_id
>= 0)
2510 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2512 LIST_FOREACH(port
, p
, s
->ports
) {
2518 copy
= fdset_put_dup(fds
, p
->fd
);
2520 return log_warning_errno(copy
, "Failed to serialize socket fd: %m");
2522 if (p
->type
== SOCKET_SOCKET
) {
2523 _cleanup_free_
char *t
= NULL
;
2525 r
= socket_address_print(&p
->address
, &t
);
2527 return log_error_errno(r
, "Failed to format socket address: %m");
2529 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2530 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2532 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2533 } else if (p
->type
== SOCKET_SPECIAL
)
2534 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2535 else if (p
->type
== SOCKET_MQUEUE
)
2536 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2537 else if (p
->type
== SOCKET_USB_FUNCTION
)
2538 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2540 assert(p
->type
== SOCKET_FIFO
);
2541 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2548 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2552 p
->fd
= fdset_remove(fds
, fd
);
2555 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2556 Socket
*s
= SOCKET(u
);
2562 if (streq(key
, "state")) {
2565 state
= socket_state_from_string(value
);
2567 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2569 s
->deserialized_state
= state
;
2570 } else if (streq(key
, "result")) {
2573 f
= socket_result_from_string(value
);
2575 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2576 else if (f
!= SOCKET_SUCCESS
)
2579 } else if (streq(key
, "n-accepted")) {
2582 if (safe_atou(value
, &k
) < 0)
2583 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2586 } else if (streq(key
, "n-refused")) {
2589 if (safe_atou(value
, &k
) < 0)
2590 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2593 } else if (streq(key
, "control-pid")) {
2596 if (parse_pid(value
, &pid
) < 0)
2597 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2599 s
->control_pid
= pid
;
2600 } else if (streq(key
, "control-command")) {
2601 SocketExecCommand id
;
2603 id
= socket_exec_command_from_string(value
);
2605 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2607 s
->control_command_id
= id
;
2608 s
->control_command
= s
->exec_command
[id
];
2610 } else if (streq(key
, "fifo")) {
2614 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2615 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2617 LIST_FOREACH(port
, p
, s
->ports
)
2618 if (p
->type
== SOCKET_FIFO
&&
2619 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2620 socket_port_take_fd(p
, fds
, fd
);
2624 } else if (streq(key
, "special")) {
2628 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2629 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2631 LIST_FOREACH(port
, p
, s
->ports
)
2632 if (p
->type
== SOCKET_SPECIAL
&&
2633 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2634 socket_port_take_fd(p
, fds
, fd
);
2638 } else if (streq(key
, "mqueue")) {
2642 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2643 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2645 LIST_FOREACH(port
, p
, s
->ports
)
2646 if (p
->type
== SOCKET_MQUEUE
&&
2647 streq(p
->path
, value
+skip
)) {
2648 socket_port_take_fd(p
, fds
, fd
);
2652 } else if (streq(key
, "socket")) {
2653 int fd
, type
, skip
= 0;
2656 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2657 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2659 LIST_FOREACH(port
, p
, s
->ports
)
2660 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2661 socket_port_take_fd(p
, fds
, fd
);
2665 } else if (streq(key
, "netlink")) {
2669 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2670 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2672 LIST_FOREACH(port
, p
, s
->ports
)
2673 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2674 socket_port_take_fd(p
, fds
, fd
);
2678 } else if (streq(key
, "ffs")) {
2682 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2683 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2685 LIST_FOREACH(port
, p
, s
->ports
)
2686 if (p
->type
== SOCKET_USB_FUNCTION
&&
2687 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2688 socket_port_take_fd(p
, fds
, fd
);
2693 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2698 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2699 Socket
*s
= SOCKET(u
);
2704 LIST_FOREACH(port
, p
, s
->ports
) {
2708 if (p
->type
!= SOCKET_SOCKET
)
2714 FDSET_FOREACH(fd
, fds
, i
) {
2715 if (socket_address_matches_fd(&p
->address
, fd
)) {
2716 p
->fd
= fdset_remove(fds
, fd
);
2717 s
->deserialized_state
= SOCKET_LISTENING
;
2724 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2727 return state_translation_table
[SOCKET(u
)->state
];
2730 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2733 return socket_state_to_string(SOCKET(u
)->state
);
2736 const char* socket_port_type_to_string(SocketPort
*p
) {
2744 switch (p
->address
.type
) {
2752 case SOCK_SEQPACKET
:
2753 return "SequentialPacket";
2756 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2764 case SOCKET_SPECIAL
:
2768 return "MessageQueue";
2773 case SOCKET_USB_FUNCTION
:
2774 return "USBFunction";
2781 SocketType
socket_port_type_from_string(const char *s
) {
2784 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2785 return SOCKET_SOCKET
;
2786 else if (streq(s
, "Special"))
2787 return SOCKET_SPECIAL
;
2788 else if (streq(s
, "MessageQueue"))
2789 return SOCKET_MQUEUE
;
2790 else if (streq(s
, "FIFO"))
2792 else if (streq(s
, "USBFunction"))
2793 return SOCKET_USB_FUNCTION
;
2795 return _SOCKET_TYPE_INVALID
;
2798 _pure_
static bool socket_may_gc(Unit
*u
) {
2799 Socket
*s
= SOCKET(u
);
2803 return s
->n_connections
== 0;
2806 static int socket_accept_do(Socket
*s
, int fd
) {
2813 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2827 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2828 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
2836 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2837 * connection socket is also properly associated with the cgroup. */
2839 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2842 r
= bpf_firewall_supported();
2845 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2848 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2849 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2851 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2853 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2857 pair
[0] = safe_close(pair
[0]);
2859 cfd
= socket_accept_do(s
, fd
);
2861 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2862 _exit(EXIT_FAILURE
);
2865 r
= send_one_fd(pair
[1], cfd
, 0);
2867 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
2868 _exit(EXIT_FAILURE
);
2871 _exit(EXIT_SUCCESS
);
2874 pair
[1] = safe_close(pair
[1]);
2875 cfd
= receive_one_fd(pair
[0], 0);
2877 /* We synchronously wait for the helper, as it shouldn't be slow */
2878 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
2885 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
2890 cfd
= socket_accept_do(s
, fd
);
2892 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2897 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2898 SocketPort
*p
= userdata
;
2904 if (p
->socket
->state
!= SOCKET_LISTENING
)
2907 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2909 if (revents
!= EPOLLIN
) {
2911 if (revents
& EPOLLHUP
)
2912 log_unit_error(UNIT(p
->socket
), "Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.");
2914 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2918 if (p
->socket
->accept
&&
2919 p
->type
== SOCKET_SOCKET
&&
2920 socket_address_can_accept(&p
->address
)) {
2922 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
2926 socket_apply_socket_options(p
->socket
, cfd
);
2929 socket_enter_running(p
->socket
, cfd
);
2933 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2937 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2938 Socket
*s
= SOCKET(u
);
2944 if (pid
!= s
->control_pid
)
2949 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
2951 else if (code
== CLD_EXITED
)
2952 f
= SOCKET_FAILURE_EXIT_CODE
;
2953 else if (code
== CLD_KILLED
)
2954 f
= SOCKET_FAILURE_SIGNAL
;
2955 else if (code
== CLD_DUMPED
)
2956 f
= SOCKET_FAILURE_CORE_DUMP
;
2958 assert_not_reached("Unknown sigchld code");
2960 if (s
->control_command
) {
2961 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2963 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
2967 unit_log_process_exit(
2968 u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
,
2970 socket_exec_command_to_string(s
->control_command_id
),
2973 if (s
->result
== SOCKET_SUCCESS
)
2976 if (s
->control_command
&&
2977 s
->control_command
->command_next
&&
2978 f
== SOCKET_SUCCESS
) {
2980 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2983 s
->control_command
= NULL
;
2984 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2986 /* No further commands for this step, so let's figure
2987 * out what to do next */
2989 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2993 case SOCKET_START_PRE
:
2994 if (f
== SOCKET_SUCCESS
)
2995 socket_enter_start_chown(s
);
2997 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3000 case SOCKET_START_CHOWN
:
3001 if (f
== SOCKET_SUCCESS
)
3002 socket_enter_start_post(s
);
3004 socket_enter_stop_pre(s
, f
);
3007 case SOCKET_START_POST
:
3008 if (f
== SOCKET_SUCCESS
)
3009 socket_enter_listening(s
);
3011 socket_enter_stop_pre(s
, f
);
3014 case SOCKET_STOP_PRE
:
3015 case SOCKET_STOP_PRE_SIGTERM
:
3016 case SOCKET_STOP_PRE_SIGKILL
:
3017 socket_enter_stop_post(s
, f
);
3020 case SOCKET_STOP_POST
:
3021 case SOCKET_FINAL_SIGTERM
:
3022 case SOCKET_FINAL_SIGKILL
:
3023 socket_enter_dead(s
, f
);
3027 assert_not_reached("Uh, control process died at wrong time.");
3031 /* Notify clients about changed exit status */
3032 unit_add_to_dbus_queue(u
);
3035 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3036 Socket
*s
= SOCKET(userdata
);
3039 assert(s
->timer_event_source
== source
);
3043 case SOCKET_START_PRE
:
3044 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3045 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3048 case SOCKET_START_CHOWN
:
3049 case SOCKET_START_POST
:
3050 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3051 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3054 case SOCKET_STOP_PRE
:
3055 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3056 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3059 case SOCKET_STOP_PRE_SIGTERM
:
3060 if (s
->kill_context
.send_sigkill
) {
3061 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3062 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3064 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3065 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3069 case SOCKET_STOP_PRE_SIGKILL
:
3070 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3071 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3074 case SOCKET_STOP_POST
:
3075 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3076 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3079 case SOCKET_FINAL_SIGTERM
:
3080 if (s
->kill_context
.send_sigkill
) {
3081 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3082 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3084 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3085 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3089 case SOCKET_FINAL_SIGKILL
:
3090 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3091 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3095 assert_not_reached("Timeout at wrong time.");
3101 int socket_collect_fds(Socket
*s
, int **fds
) {
3102 size_t k
= 0, n
= 0;
3109 /* Called from the service code for requesting our fds */
3111 LIST_FOREACH(port
, p
, s
->ports
) {
3114 n
+= p
->n_auxiliary_fds
;
3126 LIST_FOREACH(port
, p
, s
->ports
) {
3131 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3132 rfds
[k
++] = p
->auxiliary_fds
[i
];
3141 static void socket_reset_failed(Unit
*u
) {
3142 Socket
*s
= SOCKET(u
);
3146 if (s
->state
== SOCKET_FAILED
)
3147 socket_set_state(s
, SOCKET_DEAD
);
3149 s
->result
= SOCKET_SUCCESS
;
3152 void socket_connection_unref(Socket
*s
) {
3155 /* The service is dead. Yay!
3157 * This is strictly for one-instance-per-connection
3160 assert(s
->n_connections
> 0);
3163 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3166 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3167 Socket
*s
= SOCKET(u
);
3172 /* Filter out invocations with bogus state */
3173 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
3176 /* Don't propagate state changes from the service if we are already down */
3177 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3180 /* We don't care for the service state if we are in Accept=yes mode */
3184 /* Propagate start limit hit state */
3185 if (other
->start_limit_hit
) {
3186 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3190 /* Don't propagate anything if there's still a job queued */
3194 if (IN_SET(SERVICE(other
)->state
,
3195 SERVICE_DEAD
, SERVICE_FAILED
,
3196 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3197 SERVICE_AUTO_RESTART
))
3198 socket_enter_listening(s
);
3200 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3201 socket_set_state(s
, SOCKET_RUNNING
);
3204 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3205 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3208 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3209 Socket
*s
= SOCKET(u
);
3213 if (!s
->timer_event_source
)
3216 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3219 if (t
== USEC_INFINITY
)
3226 char *socket_fdname(Socket
*s
) {
3229 /* Returns the name to use for $LISTEN_NAMES. If the user
3230 * didn't specify anything specifically, use the socket unit's
3231 * name as fallback. */
3233 return s
->fdname
?: UNIT(s
)->id
;
3236 static int socket_control_pid(Unit
*u
) {
3237 Socket
*s
= SOCKET(u
);
3241 return s
->control_pid
;
3244 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3245 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3246 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3247 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3248 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3249 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3252 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3254 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3255 [SOCKET_SUCCESS
] = "success",
3256 [SOCKET_FAILURE_RESOURCES
] = "resources",
3257 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3258 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3259 [SOCKET_FAILURE_SIGNAL
] = "signal",
3260 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3261 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3262 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3263 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3266 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3268 const UnitVTable socket_vtable
= {
3269 .object_size
= sizeof(Socket
),
3270 .exec_context_offset
= offsetof(Socket
, exec_context
),
3271 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3272 .kill_context_offset
= offsetof(Socket
, kill_context
),
3273 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3274 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3280 .private_section
= "Socket",
3282 .can_transient
= true,
3284 .init
= socket_init
,
3285 .done
= socket_done
,
3286 .load
= socket_load
,
3288 .coldplug
= socket_coldplug
,
3290 .dump
= socket_dump
,
3292 .start
= socket_start
,
3293 .stop
= socket_stop
,
3295 .kill
= socket_kill
,
3297 .get_timeout
= socket_get_timeout
,
3299 .serialize
= socket_serialize
,
3300 .deserialize_item
= socket_deserialize_item
,
3301 .distribute_fds
= socket_distribute_fds
,
3303 .active_state
= socket_active_state
,
3304 .sub_state_to_string
= socket_sub_state_to_string
,
3306 .may_gc
= socket_may_gc
,
3308 .sigchld_event
= socket_sigchld_event
,
3310 .trigger_notify
= socket_trigger_notify
,
3312 .reset_failed
= socket_reset_failed
,
3314 .control_pid
= socket_control_pid
,
3316 .bus_vtable
= bus_socket_vtable
,
3317 .bus_set_property
= bus_socket_set_property
,
3318 .bus_commit_properties
= bus_socket_commit_properties
,
3320 .status_message_formats
= {
3321 /*.starting_stopping = {
3322 [0] = "Starting socket %s...",
3323 [1] = "Stopping socket %s...",
3325 .finished_start_job
= {
3326 [JOB_DONE
] = "Listening on %s.",
3327 [JOB_FAILED
] = "Failed to listen on %s.",
3328 [JOB_TIMEOUT
] = "Timed out starting %s.",
3330 .finished_stop_job
= {
3331 [JOB_DONE
] = "Closed %s.",
3332 [JOB_FAILED
] = "Failed stopping %s.",
3333 [JOB_TIMEOUT
] = "Timed out stopping %s.",