1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
7 #include <netinet/tcp.h>
11 #include <linux/sctp.h>
13 #include "alloc-util.h"
14 #include "bpf-firewall.h"
15 #include "bus-error.h"
18 #include "constants.h"
20 #include "dbus-socket.h"
21 #include "dbus-unit.h"
22 #include "errno-list.h"
23 #include "exit-status.h"
25 #include "format-util.h"
26 #include "in-addr-util.h"
28 #include "ip-protocol-list.h"
29 #include "label-util.h"
31 #include "mkdir-label.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"
38 #include "signal-util.h"
39 #include "smack-util.h"
41 #include "socket-netlink.h"
43 #include "string-table.h"
44 #include "string-util.h"
46 #include "unit-name.h"
48 #include "user-util.h"
54 union sockaddr_union peer
;
56 struct ucred peer_cred
;
59 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
60 [SOCKET_DEAD
] = UNIT_INACTIVE
,
61 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
62 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
63 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
64 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
65 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
66 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
67 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
68 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
69 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
70 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
71 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
72 [SOCKET_FAILED
] = UNIT_FAILED
,
73 [SOCKET_CLEANING
] = UNIT_MAINTENANCE
,
76 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
77 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
78 static void flush_ports(Socket
*s
);
80 static bool SOCKET_STATE_WITH_PROCESS(SocketState state
) {
86 SOCKET_STOP_PRE_SIGTERM
,
87 SOCKET_STOP_PRE_SIGKILL
,
94 static void socket_init(Unit
*u
) {
95 Socket
*s
= SOCKET(u
);
98 assert(u
->load_state
== UNIT_STUB
);
100 s
->backlog
= SOMAXCONN_DELUXE
;
101 s
->timeout_usec
= u
->manager
->defaults
.timeout_start_usec
;
102 s
->directory_mode
= 0755;
103 s
->socket_mode
= 0666;
105 s
->max_connections
= 64;
112 s
->exec_context
.std_output
= u
->manager
->defaults
.std_output
;
113 s
->exec_context
.std_error
= u
->manager
->defaults
.std_error
;
115 s
->control_pid
= PIDREF_NULL
;
116 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
118 s
->trigger_limit
= RATELIMIT_OFF
;
120 s
->poll_limit_interval
= USEC_INFINITY
;
121 s
->poll_limit_burst
= UINT_MAX
;
124 static void socket_unwatch_control_pid(Socket
*s
) {
126 unit_unwatch_pidref_done(UNIT(s
), &s
->control_pid
);
129 static void socket_cleanup_fd_list(SocketPort
*p
) {
132 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
133 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
134 p
->n_auxiliary_fds
= 0;
137 SocketPort
*socket_port_free(SocketPort
*p
) {
141 sd_event_source_unref(p
->event_source
);
143 socket_cleanup_fd_list(p
);
150 void socket_free_ports(Socket
*s
) {
153 LIST_CLEAR(port
, s
->ports
, socket_port_free
);
156 static void socket_done(Unit
*u
) {
157 Socket
*s
= SOCKET(u
);
162 socket_free_ports(s
);
164 while ((p
= set_steal_first(s
->peers_by_address
)))
167 s
->peers_by_address
= set_free(s
->peers_by_address
);
169 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
171 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
172 s
->control_command
= NULL
;
174 socket_unwatch_control_pid(s
);
176 unit_ref_unset(&s
->service
);
178 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
179 s
->bind_to_device
= mfree(s
->bind_to_device
);
181 s
->smack
= mfree(s
->smack
);
182 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
183 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
185 strv_free(s
->symlinks
);
187 s
->user
= mfree(s
->user
);
188 s
->group
= mfree(s
->group
);
190 s
->fdname
= mfree(s
->fdname
);
192 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
195 static int socket_arm_timer(Socket
*s
, bool relative
, usec_t usec
) {
198 return unit_arm_timer(UNIT(s
), &s
->timer_event_source
, relative
, usec
, socket_dispatch_timer
);
201 static bool have_non_accept_socket(Socket
*s
) {
207 LIST_FOREACH(port
, p
, s
->ports
) {
209 if (p
->type
!= SOCKET_SOCKET
)
212 if (!socket_address_can_accept(&p
->address
))
219 static int socket_add_mount_dependencies(Socket
*s
) {
224 LIST_FOREACH(port
, p
, s
->ports
) {
225 const char *path
= NULL
;
227 if (p
->type
== SOCKET_SOCKET
)
228 path
= socket_address_get_path(&p
->address
);
229 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
235 r
= unit_add_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
, UNIT_MOUNT_REQUIRES
);
243 static int socket_add_device_dependencies(Socket
*s
) {
248 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
251 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
252 return unit_add_node_dependency(UNIT(s
), t
, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
255 static int socket_add_default_dependencies(Socket
*s
) {
259 if (!UNIT(s
)->default_dependencies
)
262 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
266 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
267 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
272 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
275 static bool socket_has_exec(Socket
*s
) {
279 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
280 if (s
->exec_command
[i
])
286 static int socket_add_extras(Socket
*s
) {
292 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
293 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
294 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
295 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
296 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
297 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
298 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
299 * service starts are typical.
301 * For the poll limit we follow a similar rule, but use 3/4th of the trigger limit parameters, to
302 * trigger this earlier. */
304 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
305 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
306 if (s
->trigger_limit
.burst
== UINT_MAX
)
307 s
->trigger_limit
.burst
= s
->accept
? 200 : 20;
309 if (s
->poll_limit_interval
== USEC_INFINITY
)
310 s
->poll_limit_interval
= 2 * USEC_PER_SEC
;
311 if (s
->poll_limit_burst
== UINT_MAX
)
312 s
->poll_limit_burst
= s
->accept
? 150 : 15;
314 if (have_non_accept_socket(s
)) {
316 if (!UNIT_DEREF(s
->service
)) {
319 r
= unit_load_related_unit(u
, ".service", &x
);
323 unit_ref_set(&s
->service
, u
, x
);
326 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
331 r
= socket_add_mount_dependencies(s
);
335 r
= socket_add_device_dependencies(s
);
339 r
= unit_patch_contexts(u
);
343 if (socket_has_exec(s
)) {
344 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
349 r
= unit_set_default_slice(u
);
353 r
= socket_add_default_dependencies(s
);
360 static const char *socket_find_symlink_target(Socket
*s
) {
361 const char *found
= NULL
;
363 LIST_FOREACH(port
, p
, s
->ports
) {
364 const char *f
= NULL
;
373 f
= socket_address_get_path(&p
->address
);
391 static int socket_verify(Socket
*s
) {
393 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
396 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
398 if (s
->accept
&& have_non_accept_socket(s
))
399 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
401 if (s
->accept
&& s
->max_connections
<= 0)
402 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "MaxConnection= setting too small. Refusing.");
404 if (s
->accept
&& UNIT_DEREF(s
->service
))
405 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Explicit service configuration for accepting socket units not supported. Refusing.");
407 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
)
408 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
410 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
))
411 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
416 static void peer_address_hash_func(const SocketPeer
*s
, struct siphash
*state
) {
419 if (s
->peer
.sa
.sa_family
== AF_INET
)
420 siphash24_compress_typesafe(s
->peer
.in
.sin_addr
, state
);
421 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
422 siphash24_compress_typesafe(s
->peer
.in6
.sin6_addr
, state
);
423 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
424 siphash24_compress_typesafe(s
->peer
.vm
.svm_cid
, state
);
425 else if (s
->peer
.sa
.sa_family
== AF_UNIX
)
426 siphash24_compress_typesafe(s
->peer_cred
.uid
, state
);
428 assert_not_reached();
431 static int peer_address_compare_func(const SocketPeer
*x
, const SocketPeer
*y
) {
434 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
438 switch (x
->peer
.sa
.sa_family
) {
440 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
442 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
444 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
446 return CMP(x
->peer_cred
.uid
, y
->peer_cred
.uid
);
448 assert_not_reached();
451 DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops
, SocketPeer
, peer_address_hash_func
, peer_address_compare_func
);
453 static int socket_load(Unit
*u
) {
454 Socket
*s
= SOCKET(u
);
458 assert(u
->load_state
== UNIT_STUB
);
460 r
= unit_load_fragment_and_dropin(u
, true);
464 if (u
->load_state
!= UNIT_LOADED
)
467 /* This is a new unit? Then let's add in some extras */
468 r
= socket_add_extras(s
);
472 return socket_verify(s
);
475 static SocketPeer
*socket_peer_dup(const SocketPeer
*q
) {
480 p
= new(SocketPeer
, 1);
487 .peer_salen
= q
->peer_salen
,
488 .peer_cred
= q
->peer_cred
,
494 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
498 set_remove(p
->socket
->peers_by_address
, p
);
503 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
505 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**ret
) {
506 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
508 .peer_salen
= sizeof(union sockaddr_union
),
509 .peer_cred
= UCRED_INVALID
,
517 if (getpeername(fd
, &key
.peer
.sa
, &key
.peer_salen
) < 0)
518 return log_unit_error_errno(UNIT(s
), errno
, "getpeername() failed: %m");
520 switch (key
.peer
.sa
.sa_family
) {
527 r
= getpeercred(fd
, &key
.peer_cred
);
529 return log_unit_error_errno(UNIT(s
), r
, "Failed to get peer credentials of socket: %m");
537 i
= set_get(s
->peers_by_address
, &key
);
539 *ret
= socket_peer_ref(i
);
543 remote
= socket_peer_dup(&key
);
547 r
= set_ensure_put(&s
->peers_by_address
, &peer_address_hash_ops
, remote
);
549 return log_unit_error_errno(UNIT(s
), r
, "Failed to insert peer info into hash table: %m");
553 *ret
= TAKE_PTR(remote
);
557 static const char* listen_lookup(int family
, int type
) {
559 if (family
== AF_NETLINK
)
560 return "ListenNetlink";
562 if (type
== SOCK_STREAM
)
563 return "ListenStream";
564 else if (type
== SOCK_DGRAM
)
565 return "ListenDatagram";
566 else if (type
== SOCK_SEQPACKET
)
567 return "ListenSequentialPacket";
569 assert_not_reached();
573 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
574 Socket
*s
= SOCKET(u
);
575 const char *prefix2
, *str
;
580 prefix
= strempty(prefix
);
581 prefix2
= strjoina(prefix
, "\t");
584 "%sSocket State: %s\n"
586 "%sClean Result: %s\n"
587 "%sBindIPv6Only: %s\n"
589 "%sSocketMode: %04o\n"
590 "%sDirectoryMode: %04o\n"
594 "%sTransparent: %s\n"
596 "%sPassCredentials: %s\n"
597 "%sPassSecurity: %s\n"
598 "%sPassPacketInfo: %s\n"
599 "%sTCPCongestion: %s\n"
600 "%sRemoveOnStop: %s\n"
602 "%sFileDescriptorName: %s\n"
603 "%sSELinuxContextFromNet: %s\n",
604 prefix
, socket_state_to_string(s
->state
),
605 prefix
, socket_result_to_string(s
->result
),
606 prefix
, socket_result_to_string(s
->clean_result
),
607 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
609 prefix
, s
->socket_mode
,
610 prefix
, s
->directory_mode
,
611 prefix
, yes_no(s
->keep_alive
),
612 prefix
, yes_no(s
->no_delay
),
613 prefix
, yes_no(s
->free_bind
),
614 prefix
, yes_no(s
->transparent
),
615 prefix
, yes_no(s
->broadcast
),
616 prefix
, yes_no(s
->pass_cred
),
617 prefix
, yes_no(s
->pass_sec
),
618 prefix
, yes_no(s
->pass_pktinfo
),
619 prefix
, strna(s
->tcp_congestion
),
620 prefix
, yes_no(s
->remove_on_stop
),
621 prefix
, yes_no(s
->writable
),
622 prefix
, socket_fdname(s
),
623 prefix
, yes_no(s
->selinux_context_from_net
));
625 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
)
627 "%sTimestamping: %s\n",
628 prefix
, socket_timestamping_to_string(s
->timestamping
));
630 if (pidref_is_set(&s
->control_pid
))
632 "%sControl PID: "PID_FMT
"\n",
633 prefix
, s
->control_pid
.pid
);
635 if (s
->bind_to_device
)
637 "%sBindToDevice: %s\n",
638 prefix
, s
->bind_to_device
);
643 "%sNConnections: %u\n"
644 "%sMaxConnections: %u\n"
645 "%sMaxConnectionsPerSource: %u\n",
646 prefix
, s
->n_accepted
,
647 prefix
, s
->n_connections
,
648 prefix
, s
->max_connections
,
649 prefix
, s
->max_connections_per_source
);
652 "%sFlushPending: %s\n",
653 prefix
, yes_no(s
->flush_pending
));
656 if (s
->priority
>= 0)
659 prefix
, s
->priority
);
661 if (s
->receive_buffer
> 0)
663 "%sReceiveBuffer: %zu\n",
664 prefix
, s
->receive_buffer
);
666 if (s
->send_buffer
> 0)
668 "%sSendBuffer: %zu\n",
669 prefix
, s
->send_buffer
);
681 if (s
->pipe_size
> 0)
684 prefix
, s
->pipe_size
);
691 if (s
->mq_maxmsg
> 0)
693 "%sMessageQueueMaxMessages: %li\n",
694 prefix
, s
->mq_maxmsg
);
696 if (s
->mq_msgsize
> 0)
698 "%sMessageQueueMessageSize: %li\n",
699 prefix
, s
->mq_msgsize
);
704 prefix
, yes_no(s
->reuse_port
));
708 "%sSmackLabel: %s\n",
713 "%sSmackLabelIPIn: %s\n",
714 prefix
, s
->smack_ip_in
);
718 "%sSmackLabelIPOut: %s\n",
719 prefix
, s
->smack_ip_out
);
721 if (!isempty(s
->user
) || !isempty(s
->group
))
724 "%sSocketGroup: %s\n",
725 prefix
, strna(s
->user
),
726 prefix
, strna(s
->group
));
728 if (timestamp_is_set(s
->keep_alive_time
))
730 "%sKeepAliveTimeSec: %s\n",
731 prefix
, FORMAT_TIMESPAN(s
->keep_alive_time
, USEC_PER_SEC
));
733 if (s
->keep_alive_interval
> 0)
735 "%sKeepAliveIntervalSec: %s\n",
736 prefix
, FORMAT_TIMESPAN(s
->keep_alive_interval
, USEC_PER_SEC
));
738 if (s
->keep_alive_cnt
> 0)
740 "%sKeepAliveProbes: %u\n",
741 prefix
, s
->keep_alive_cnt
);
743 if (s
->defer_accept
> 0)
745 "%sDeferAcceptSec: %s\n",
746 prefix
, FORMAT_TIMESPAN(s
->defer_accept
, USEC_PER_SEC
));
748 LIST_FOREACH(port
, p
, s
->ports
) {
751 case SOCKET_SOCKET
: {
752 _cleanup_free_
char *k
= NULL
;
755 r
= socket_address_print(&p
->address
, &k
);
758 fprintf(f
, "%s%s: %m\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
));
760 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), k
);
764 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
766 case SOCKET_USB_FUNCTION
:
767 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
770 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
773 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
778 "%sTriggerLimitIntervalSec: %s\n"
779 "%sTriggerLimitBurst: %u\n"
780 "%sPollLimitIntervalSec: %s\n"
781 "%sPollLimitBurst: %u\n",
782 prefix
, FORMAT_TIMESPAN(s
->trigger_limit
.interval
, USEC_PER_SEC
),
783 prefix
, s
->trigger_limit
.burst
,
784 prefix
, FORMAT_TIMESPAN(s
->poll_limit_interval
, USEC_PER_SEC
),
785 prefix
, s
->poll_limit_burst
);
787 str
= ip_protocol_to_name(s
->socket_protocol
);
789 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
791 if (!strv_isempty(s
->symlinks
)) {
792 fprintf(f
, "%sSymlinks:", prefix
);
793 STRV_FOREACH(q
, s
->symlinks
)
794 fprintf(f
, " %s", *q
);
800 "%sTimeoutSec: %s\n",
801 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
803 exec_context_dump(&s
->exec_context
, f
, prefix
);
804 kill_context_dump(&s
->kill_context
, f
, prefix
);
806 for (SocketExecCommand c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
807 if (!s
->exec_command
[c
])
810 fprintf(f
, "%s-> %s:\n",
811 prefix
, socket_exec_command_to_string(c
));
813 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
816 cgroup_context_dump(UNIT(s
), f
, prefix
);
819 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
822 union sockaddr_union local
, remote
;
828 if (getsockname(fd
, &local
.sa
, &l
) < 0)
832 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
835 switch (local
.sa
.sa_family
) {
839 a
= be32toh(local
.in
.sin_addr
.s_addr
),
840 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
843 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
845 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
846 be16toh(local
.in
.sin_port
),
847 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
848 be16toh(remote
.in
.sin_port
)) < 0)
855 static const unsigned char ipv4_prefix
[] = {
856 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
859 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
860 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
862 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
863 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
866 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
868 a
[0], a
[1], a
[2], a
[3],
869 be16toh(local
.in6
.sin6_port
),
870 b
[0], b
[1], b
[2], b
[3],
871 be16toh(remote
.in6
.sin6_port
)) < 0)
877 IN6_ADDR_TO_STRING(&local
.in6
.sin6_addr
),
878 be16toh(local
.in6
.sin6_port
),
879 IN6_ADDR_TO_STRING(&remote
.in6
.sin6_addr
),
880 be16toh(remote
.in6
.sin6_port
)) < 0)
891 k
= getpeercred(fd
, &ucred
);
894 "%u-"PID_FMT
"-"UID_FMT
,
895 nr
, ucred
.pid
, ucred
.uid
) < 0)
897 } else if (k
== -ENODATA
) {
898 /* This handles the case where somebody is
899 * connecting from another pid/uid namespace
900 * (e.g. from outside of our container). */
915 local
.vm
.svm_cid
, local
.vm
.svm_port
,
916 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
922 assert_not_reached();
929 static void socket_close_fds(Socket
*s
) {
932 LIST_FOREACH(port
, p
, s
->ports
) {
935 was_open
= p
->fd
>= 0;
937 p
->event_source
= sd_event_source_disable_unref(p
->event_source
);
938 p
->fd
= safe_close(p
->fd
);
939 socket_cleanup_fd_list(p
);
941 /* One little note: we should normally not delete any sockets in the file system here! After all some
942 * other process we spawned might still have a reference of this fd and wants to continue to use
943 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
944 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
945 * anyway, but only then. */
947 if (!was_open
|| !s
->remove_on_stop
)
953 (void) unlink(p
->path
);
957 (void) mq_unlink(p
->path
);
961 (void) socket_address_unlink(&p
->address
);
969 if (s
->remove_on_stop
)
970 STRV_FOREACH(i
, s
->symlinks
)
973 /* Note that we don't return NULL here, since s has not been freed. */
976 static void socket_apply_socket_options(Socket
*s
, SocketPort
*p
, int fd
) {
984 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
986 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
989 if (timestamp_is_set(s
->keep_alive_time
)) {
990 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
992 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
995 if (s
->keep_alive_interval
> 0) {
996 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
998 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
1001 if (s
->keep_alive_cnt
> 0) {
1002 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
1004 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
1007 if (s
->defer_accept
> 0) {
1008 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
1010 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
1014 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1015 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1017 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1019 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1021 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1026 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1028 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1032 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1034 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1038 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1040 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1043 if (s
->pass_pktinfo
) {
1044 r
= socket_set_recvpktinfo(fd
, socket_address_family(&p
->address
), true);
1046 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable packet info socket option: %m");
1049 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
) {
1050 r
= setsockopt_int(fd
, SOL_SOCKET
,
1051 s
->timestamping
== SOCKET_TIMESTAMPING_NS
? SO_TIMESTAMPNS
: SO_TIMESTAMP
,
1054 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable timestamping socket option, ignoring: %m");
1057 if (s
->priority
>= 0) {
1058 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1060 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1063 if (s
->receive_buffer
> 0) {
1064 r
= fd_set_rcvbuf(fd
, s
->receive_buffer
, false);
1066 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1067 "SO_RCVBUF/SO_RCVBUFFORCE failed: %m");
1070 if (s
->send_buffer
> 0) {
1071 r
= fd_set_sndbuf(fd
, s
->send_buffer
, false);
1073 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1074 "SO_SNDBUF/SO_SNDBUFFORCE failed: %m");
1078 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1080 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1083 if (s
->ip_tos
>= 0) {
1084 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1086 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1089 if (s
->ip_ttl
>= 0) {
1090 r
= socket_set_ttl(fd
, socket_address_family(&p
->address
), s
->ip_ttl
);
1092 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1095 if (s
->tcp_congestion
)
1096 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1097 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1099 if (s
->smack_ip_in
) {
1100 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1102 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1105 if (s
->smack_ip_out
) {
1106 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1108 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1112 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1118 if (s
->pipe_size
> 0)
1119 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1120 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1123 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1125 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1129 static int fifo_address_create(
1131 mode_t directory_mode
,
1132 mode_t socket_mode
) {
1134 _cleanup_close_
int fd
= -EBADF
;
1141 (void) mkdir_parents_label(path
, directory_mode
);
1143 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1147 /* Enforce the right access mode for the fifo */
1148 old_mask
= umask(~socket_mode
);
1150 /* Include the original umask in our mask */
1151 (void) umask(~socket_mode
| old_mask
);
1153 r
= mkfifo(path
, socket_mode
);
1154 (void) umask(old_mask
);
1156 if (r
< 0 && errno
!= EEXIST
) {
1161 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1167 mac_selinux_create_file_clear();
1169 if (fstat(fd
, &st
) < 0) {
1174 if (!S_ISFIFO(st
.st_mode
) ||
1175 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1176 st
.st_uid
!= getuid() ||
1177 st
.st_gid
!= getgid()) {
1185 mac_selinux_create_file_clear();
1189 static int special_address_create(const char *path
, bool writable
) {
1190 _cleanup_close_
int fd
= -EBADF
;
1195 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1199 if (fstat(fd
, &st
) < 0)
1202 /* Check whether this is a /proc, /sys or /dev file or char device */
1203 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1209 static int usbffs_address_create(const char *path
) {
1210 _cleanup_close_
int fd
= -EBADF
;
1215 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1219 if (fstat(fd
, &st
) < 0)
1222 /* Check whether this is a regular file (ffs endpoint) */
1223 if (!S_ISREG(st
.st_mode
))
1229 static int mq_address_create(
1235 _cleanup_close_
int fd
= -EBADF
;
1238 struct mq_attr _attr
, *attr
= NULL
;
1242 if (maxmsg
> 0 && msgsize
> 0) {
1243 _attr
= (struct mq_attr
) {
1244 .mq_flags
= O_NONBLOCK
,
1245 .mq_maxmsg
= maxmsg
,
1246 .mq_msgsize
= msgsize
,
1251 /* Enforce the right access mode for the mq */
1252 old_mask
= umask(~mq_mode
);
1254 /* Include the original umask in our mask */
1255 (void) umask(~mq_mode
| old_mask
);
1256 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1257 (void) umask(old_mask
);
1262 if (fstat(fd
, &st
) < 0)
1265 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1266 st
.st_uid
!= getuid() ||
1267 st
.st_gid
!= getgid())
1273 static int socket_symlink(Socket
*s
) {
1279 p
= socket_find_symlink_target(s
);
1283 STRV_FOREACH(i
, s
->symlinks
) {
1284 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1286 r
= symlink_idempotent(p
, *i
, false);
1288 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1289 /* If there's already something where we want to create the symlink, and the destructive
1290 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1293 if (unlink(*i
) >= 0)
1294 r
= symlink_idempotent(p
, *i
, false);
1298 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s %s %s, ignoring: %m",
1299 p
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *i
);
1305 static int usbffs_write_descs(int fd
, Service
*s
) {
1308 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1311 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1315 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1318 static int usbffs_select_ep(const struct dirent
*d
) {
1319 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1322 static int usbffs_dispatch_eps(SocketPort
*p
) {
1323 _cleanup_free_
struct dirent
**ent
= NULL
;
1327 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1332 p
->auxiliary_fds
= new(int, n
);
1333 if (!p
->auxiliary_fds
) {
1338 p
->n_auxiliary_fds
= n
;
1341 for (size_t i
= 0; i
< n
; ++i
) {
1342 _cleanup_free_
char *ep
= NULL
;
1344 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1352 r
= usbffs_address_create(ep
);
1356 p
->auxiliary_fds
[k
++] = r
;
1363 close_many(p
->auxiliary_fds
, k
);
1364 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1365 p
->n_auxiliary_fds
= 0;
1368 free_many((void**) ent
, n
);
1372 int socket_load_service_unit(Socket
*s
, int cfd
, Unit
**ret
) {
1373 /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1375 * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1379 if (UNIT_ISSET(s
->service
)) {
1380 *ret
= UNIT_DEREF(s
->service
);
1387 /* Build the instance name and load the unit */
1388 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
1391 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
1396 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
1398 if (ERRNO_IS_DISCONNECT(r
))
1399 /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1400 * different errors. This connection is over, but the socket unit lives on. */
1401 return log_unit_debug_errno(UNIT(s
), r
,
1402 "Got %s on incoming socket, assuming aborted connection attempt, ignoring.",
1408 /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1409 * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1410 * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1411 r
= unit_name_build(prefix
, instance
?: "internal", ".service", &name
);
1415 return manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, ret
);
1418 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1425 r
= socket_load_service_unit(s
, /* cfd= */ -EBADF
, &service
);
1426 if (r
== -ENODATA
) {
1433 r
= service_determine_exec_selinux_label(SERVICE(service
), ret
);
1434 if (r
== -ENODATA
) {
1441 static int socket_address_listen_do(
1443 const SocketAddress
*address
,
1444 const char *label
) {
1449 return socket_address_listen(
1451 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1463 #define log_address_error_errno(u, address, error, fmt) \
1465 _cleanup_free_ char *_t = NULL; \
1467 (void) socket_address_print(address, &_t); \
1468 log_unit_error_errno(u, error, fmt, strna(_t)); \
1471 static int fork_needed(const SocketAddress
*address
, Socket
*s
) {
1477 /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1479 /* If there are any NFTSet= directives with cgroup source, we need the cgroup */
1481 CGroupContext
*c
= unit_get_cgroup_context(u
);
1483 FOREACH_ARRAY(nft_set
, c
->nft_set_context
.sets
, c
->nft_set_context
.n_sets
)
1484 if (nft_set
->source
== NFT_SET_SOURCE_CGROUP
)
1487 if (IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
)) {
1488 r
= bpf_firewall_supported();
1491 if (r
!= BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1495 return exec_needs_network_namespace(&s
->exec_context
);
1498 static int socket_address_listen_in_cgroup(
1500 const SocketAddress
*address
,
1501 const char *label
) {
1503 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
1504 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
1510 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1511 * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1512 * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1515 r
= fork_needed(address
, s
);
1519 /* Shortcut things... */
1520 fd
= socket_address_listen_do(s
, address
, label
);
1522 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1527 r
= unit_setup_exec_runtime(UNIT(s
));
1529 return log_unit_error_errno(UNIT(s
), r
, "Failed acquire runtime: %m");
1531 if (s
->exec_context
.network_namespace_path
&&
1533 s
->exec_runtime
->shared
&&
1534 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1535 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->netns_storage_socket
, s
->exec_context
.network_namespace_path
, CLONE_NEWNET
);
1537 return log_unit_error_errno(UNIT(s
), r
, "Failed to open network namespace path %s: %m", s
->exec_context
.network_namespace_path
);
1540 if (s
->exec_context
.ipc_namespace_path
&&
1542 s
->exec_runtime
->shared
&&
1543 s
->exec_runtime
->shared
->ipcns_storage_socket
[0] >= 0) {
1544 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->ipcns_storage_socket
, s
->exec_context
.ipc_namespace_path
, CLONE_NEWIPC
);
1546 return log_unit_error_errno(UNIT(s
), r
, "Failed to open IPC namespace path %s: %m", s
->exec_context
.ipc_namespace_path
);
1549 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1550 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1552 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1554 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1558 pair
[0] = safe_close(pair
[0]);
1560 if (exec_needs_network_namespace(&s
->exec_context
) &&
1562 s
->exec_runtime
->shared
&&
1563 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1565 if (ns_type_supported(NAMESPACE_NET
)) {
1566 r
= setup_shareable_ns(s
->exec_runtime
->shared
->netns_storage_socket
, CLONE_NEWNET
);
1568 log_unit_error_errno(UNIT(s
), r
, "Failed to join network namespace: %m");
1569 _exit(EXIT_NETWORK
);
1571 } else if (s
->exec_context
.network_namespace_path
) {
1572 log_unit_error(UNIT(s
), "Network namespace path configured but network namespaces not supported.");
1573 _exit(EXIT_NETWORK
);
1575 log_unit_warning(UNIT(s
), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
1578 fd
= socket_address_listen_do(s
, address
, label
);
1580 log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1581 _exit(EXIT_FAILURE
);
1584 r
= send_one_fd(pair
[1], fd
, 0);
1586 log_address_error_errno(UNIT(s
), address
, r
, "Failed to send listening socket (%s) to parent: %m");
1587 _exit(EXIT_FAILURE
);
1590 _exit(EXIT_SUCCESS
);
1593 pair
[1] = safe_close(pair
[1]);
1594 fd
= receive_one_fd(pair
[0], 0);
1596 /* We synchronously wait for the helper, as it shouldn't be slow */
1597 r
= wait_for_terminate_and_check("(sd-listen)", pid
.pid
, WAIT_LOG_ABNORMAL
);
1604 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to receive listening socket (%s): %m");
1609 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket
*, socket_close_fds
, NULL
);
1611 static int socket_open_fds(Socket
*orig_s
) {
1612 _cleanup_(socket_close_fdsp
) Socket
*s
= orig_s
;
1613 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1614 bool know_label
= false;
1619 LIST_FOREACH(port
, p
, s
->ports
) {
1629 /* Figure out the label, if we don't it know yet. We do it once for the first
1630 * socket where we need this and remember it for the rest. */
1632 r
= socket_determine_selinux_label(s
, &label
);
1634 return log_unit_error_errno(UNIT(s
), r
, "Failed to determine SELinux label: %m");
1639 /* Apply the socket protocol */
1640 switch (p
->address
.type
) {
1643 case SOCK_SEQPACKET
:
1644 if (s
->socket_protocol
== IPPROTO_SCTP
)
1645 p
->address
.protocol
= s
->socket_protocol
;
1649 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1650 p
->address
.protocol
= s
->socket_protocol
;
1654 p
->fd
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1658 socket_apply_socket_options(s
, p
, p
->fd
);
1662 case SOCKET_SPECIAL
:
1664 p
->fd
= special_address_create(p
->path
, s
->writable
);
1666 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open special file %s: %m", p
->path
);
1671 p
->fd
= fifo_address_create(
1676 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open FIFO %s: %m", p
->path
);
1678 socket_apply_fifo_options(s
, p
->fd
);
1684 p
->fd
= mq_address_create(
1690 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open message queue %s: %m", p
->path
);
1693 case SOCKET_USB_FUNCTION
: {
1694 _cleanup_free_
char *ep
= NULL
;
1696 ep
= path_make_absolute("ep0", p
->path
);
1700 p
->fd
= usbffs_address_create(ep
);
1704 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1708 r
= usbffs_dispatch_eps(p
);
1715 assert_not_reached();
1723 static void socket_unwatch_fds(Socket
*s
) {
1728 LIST_FOREACH(port
, p
, s
->ports
) {
1732 if (!p
->event_source
)
1735 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1737 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1741 static int socket_watch_fds(Socket
*s
) {
1746 LIST_FOREACH(port
, p
, s
->ports
) {
1750 if (p
->event_source
) {
1751 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1755 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1759 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1762 r
= sd_event_source_set_ratelimit(p
->event_source
, s
->poll_limit_interval
, s
->poll_limit_burst
);
1764 log_unit_debug_errno(UNIT(s
), r
, "Failed to set poll limit on I/O event source, ignoring: %m");
1770 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1771 socket_unwatch_fds(s
);
1781 static int socket_check_open(Socket
*s
) {
1782 bool have_open
= false, have_closed
= false;
1786 LIST_FOREACH(port
, p
, s
->ports
) {
1792 if (have_open
&& have_closed
)
1793 return SOCKET_OPEN_SOME
;
1797 return SOCKET_OPEN_ALL
;
1799 return SOCKET_OPEN_NONE
;
1802 static void socket_set_state(Socket
*s
, SocketState state
) {
1803 SocketState old_state
;
1806 if (s
->state
!= state
)
1807 bus_unit_send_pending_change_signal(UNIT(s
), false);
1809 old_state
= s
->state
;
1812 if (!SOCKET_STATE_WITH_PROCESS(state
)) {
1813 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1814 socket_unwatch_control_pid(s
);
1815 s
->control_command
= NULL
;
1816 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1819 if (state
!= SOCKET_LISTENING
)
1820 socket_unwatch_fds(s
);
1828 SOCKET_STOP_PRE_SIGTERM
,
1829 SOCKET_STOP_PRE_SIGKILL
,
1831 socket_close_fds(s
);
1833 if (state
!= old_state
)
1834 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1836 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
1839 static int socket_coldplug(Unit
*u
) {
1840 Socket
*s
= SOCKET(u
);
1844 assert(s
->state
== SOCKET_DEAD
);
1846 if (s
->deserialized_state
== s
->state
)
1849 if (pidref_is_set(&s
->control_pid
) &&
1850 pidref_is_unwaited(&s
->control_pid
) > 0 &&
1851 SOCKET_STATE_WITH_PROCESS(s
->deserialized_state
)) {
1853 r
= unit_watch_pidref(UNIT(s
), &s
->control_pid
, /* exclusive= */ false);
1857 r
= socket_arm_timer(s
, /* relative= */ false, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1862 if (IN_SET(s
->deserialized_state
,
1868 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1869 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN state for
1870 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1871 * and if there's a mismatch, warn loudly. */
1873 r
= socket_check_open(s
);
1874 if (r
== SOCKET_OPEN_NONE
)
1875 log_unit_warning(UNIT(s
),
1876 "Socket unit configuration has changed while unit has been running, "
1877 "no open socket file descriptor left. "
1878 "The socket unit is not functional until restarted.");
1879 else if (r
== SOCKET_OPEN_SOME
)
1880 log_unit_warning(UNIT(s
),
1881 "Socket unit configuration has changed while unit has been running, "
1882 "and some socket file descriptors have not been opened yet. "
1883 "The socket unit is not fully functional until restarted.");
1886 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1887 r
= socket_watch_fds(s
);
1892 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
, SOCKET_CLEANING
))
1893 (void) unit_setup_exec_runtime(u
);
1895 socket_set_state(s
, s
->deserialized_state
);
1899 static int socket_spawn(Socket
*s
, ExecCommand
*c
, PidRef
*ret_pid
) {
1901 _cleanup_(exec_params_shallow_clear
) ExecParameters exec_params
= EXEC_PARAMETERS_INIT(
1902 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
);
1903 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1910 r
= unit_prepare_exec(UNIT(s
));
1914 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
1918 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1922 r
= exec_spawn(UNIT(s
),
1932 r
= unit_watch_pidref(UNIT(s
), &pidref
, /* exclusive= */ true);
1936 *ret_pid
= TAKE_PIDREF(pidref
);
1940 static int socket_chown(Socket
*s
, PidRef
*ret_pid
) {
1941 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
1946 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
1950 /* We have to resolve the user names out-of-process, hence
1951 * let's fork here. It's messy, but well, what can we do? */
1953 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1957 uid_t uid
= UID_INVALID
;
1958 gid_t gid
= GID_INVALID
;
1962 if (!isempty(s
->user
)) {
1963 const char *user
= s
->user
;
1965 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1967 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1972 if (!isempty(s
->group
)) {
1973 const char *group
= s
->group
;
1975 r
= get_group_creds(&group
, &gid
, 0);
1977 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1982 LIST_FOREACH(port
, p
, s
->ports
) {
1983 const char *path
= NULL
;
1985 if (p
->type
== SOCKET_SOCKET
)
1986 path
= socket_address_get_path(&p
->address
);
1987 else if (p
->type
== SOCKET_FIFO
)
1993 if (chown(path
, uid
, gid
) < 0) {
1994 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1999 _exit(EXIT_SUCCESS
);
2002 r
= unit_watch_pidref(UNIT(s
), &pid
, /* exclusive= */ true);
2006 *ret_pid
= TAKE_PIDREF(pid
);
2010 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
2013 if (s
->result
== SOCKET_SUCCESS
)
2016 if (s
->result
== SOCKET_SUCCESS
)
2017 unit_log_success(UNIT(s
));
2019 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
2021 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2023 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
2025 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2027 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2029 unit_unref_uid_gid(UNIT(s
), true);
2032 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2034 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2038 if (s
->result
== SOCKET_SUCCESS
)
2041 socket_unwatch_control_pid(s
);
2042 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2043 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2045 if (s
->control_command
) {
2046 pidref_done(&s
->control_pid
);
2048 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2050 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-post' task: %m");
2051 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2055 socket_set_state(s
, SOCKET_STOP_POST
);
2057 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2060 static int state_to_kill_operation(Socket
*s
, SocketState state
) {
2061 if (state
== SOCKET_STOP_PRE_SIGTERM
&& unit_has_job_type(UNIT(s
), JOB_RESTART
))
2062 return KILL_RESTART
;
2064 if (state
== SOCKET_FINAL_SIGTERM
)
2065 return KILL_TERMINATE
;
2070 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2075 if (s
->result
== SOCKET_SUCCESS
)
2078 r
= unit_kill_context(UNIT(s
), state_to_kill_operation(s
, state
));
2080 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2085 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
2087 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2091 socket_set_state(s
, state
);
2092 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2093 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2094 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2095 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2096 else if (state
== SOCKET_FINAL_SIGTERM
)
2097 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2099 socket_enter_dead(s
, SOCKET_SUCCESS
);
2104 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2105 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2107 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2110 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2114 if (s
->result
== SOCKET_SUCCESS
)
2117 socket_unwatch_control_pid(s
);
2118 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2119 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2121 if (s
->control_command
) {
2122 pidref_done(&s
->control_pid
);
2124 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2126 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-pre' task: %m");
2127 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2131 socket_set_state(s
, SOCKET_STOP_PRE
);
2133 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2136 static void socket_enter_listening(Socket
*s
) {
2140 if (!s
->accept
&& s
->flush_pending
) {
2141 log_unit_debug(UNIT(s
), "Flushing socket before listening.");
2145 r
= socket_watch_fds(s
);
2147 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2148 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2152 socket_set_state(s
, SOCKET_LISTENING
);
2155 static void socket_enter_start_post(Socket
*s
) {
2159 socket_unwatch_control_pid(s
);
2160 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2161 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2163 if (s
->control_command
) {
2164 pidref_done(&s
->control_pid
);
2166 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2168 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-post' task: %m");
2169 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2173 socket_set_state(s
, SOCKET_START_POST
);
2175 socket_enter_listening(s
);
2178 static void socket_enter_start_chown(Socket
*s
) {
2183 r
= socket_open_fds(s
);
2185 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2189 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2191 socket_unwatch_control_pid(s
);
2192 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2193 s
->control_command
= NULL
;
2195 r
= socket_chown(s
, &s
->control_pid
);
2197 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-chown' task: %m");
2201 socket_set_state(s
, SOCKET_START_CHOWN
);
2203 socket_enter_start_post(s
);
2208 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2211 static void socket_enter_start_pre(Socket
*s
) {
2215 socket_unwatch_control_pid(s
);
2217 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
2219 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2220 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2222 if (s
->control_command
) {
2223 pidref_done(&s
->control_pid
);
2225 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2227 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-pre' task: %m");
2228 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2232 socket_set_state(s
, SOCKET_START_PRE
);
2234 socket_enter_start_chown(s
);
2237 static void flush_ports(Socket
*s
) {
2240 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2243 LIST_FOREACH(port
, p
, s
->ports
) {
2247 (void) flush_accept(p
->fd
);
2248 (void) flush_fd(p
->fd
);
2252 static void socket_enter_running(Socket
*s
, int cfd_in
) {
2253 /* Note that this call takes possession of the connection fd passed. It either has to assign it
2254 * somewhere or close it. */
2255 _cleanup_close_
int cfd
= cfd_in
;
2257 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2262 /* We don't take connections anymore if we are supposed to shut down anyway */
2263 if (unit_stop_pending(UNIT(s
))) {
2265 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2274 if (!ratelimit_below(&s
->trigger_limit
)) {
2275 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2276 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2280 if (cfd
< 0) { /* Accept=no case */
2281 bool pending
= false;
2284 /* If there's already a start pending don't bother to do anything */
2285 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_TRIGGERS
)
2286 if (unit_active_or_pending(other
)) {
2292 if (!UNIT_ISSET(s
->service
)) {
2293 r
= log_unit_warning_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOENT
),
2294 "Service to activate vanished, refusing activation.");
2298 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, NULL
, &error
, NULL
);
2303 socket_set_state(s
, SOCKET_RUNNING
);
2304 } else { /* Accept=yes case */
2305 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2308 if (s
->n_connections
>= s
->max_connections
) {
2309 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2314 if (s
->max_connections_per_source
> 0) {
2315 r
= socket_acquire_peer(s
, cfd
, &p
);
2317 if (ERRNO_IS_DISCONNECT(r
))
2319 /* We didn't have enough resources to acquire peer information, let's fail. */
2322 if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2323 _cleanup_free_
char *t
= NULL
;
2325 if (p
->peer
.sa
.sa_family
== AF_UNIX
)
2326 (void) asprintf(&t
, "UID " UID_FMT
, p
->peer_cred
.uid
);
2328 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, /* translate_ipv6= */ true, /* include_port= */ false, &t
);
2330 log_unit_warning(UNIT(s
),
2331 "Too many incoming connections (%u) from source %s, dropping connection.",
2332 p
->n_ref
, strnull(t
));
2337 r
= socket_load_service_unit(s
, cfd
, &service
);
2339 if (ERRNO_IS_DISCONNECT(r
))
2342 log_unit_warning_errno(UNIT(s
), r
, "Failed to load connection service unit: %m");
2346 r
= unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, service
,
2347 false, UNIT_DEPENDENCY_IMPLICIT
);
2349 log_unit_warning_errno(UNIT(s
), r
, "Failed to add Before=/Triggers= dependencies on connection unit: %m");
2355 r
= service_set_socket_fd(SERVICE(service
), cfd
, s
, p
, s
->selinux_context_from_net
);
2357 if (ERRNO_IS_DISCONNECT(r
))
2360 log_unit_warning_errno(UNIT(s
), r
, "Failed to set socket on service: %m");
2364 TAKE_FD(cfd
); /* We passed ownership of the fd to the service now. Forget it here. */
2367 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, service
, JOB_REPLACE
, NULL
, &error
, NULL
);
2369 /* We failed to activate the new service, but it still exists. Let's make sure the
2370 * service closes and forgets the connection fd again, immediately. */
2371 service_release_socket_fd(SERVICE(service
));
2375 /* Notify clients about changed counters */
2376 unit_add_to_dbus_queue(UNIT(s
));
2386 if (ERRNO_IS_RESOURCE(r
))
2387 log_unit_warning(UNIT(s
), "Failed to queue service startup job: %s",
2388 bus_error_message(&error
, r
));
2390 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2391 cfd
>= 0 ? "template" : "non-template",
2392 bus_error_message(&error
, r
));
2395 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2398 static void socket_run_next(Socket
*s
) {
2402 assert(s
->control_command
);
2403 assert(s
->control_command
->command_next
);
2405 socket_unwatch_control_pid(s
);
2407 s
->control_command
= s
->control_command
->command_next
;
2409 pidref_done(&s
->control_pid
);
2411 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2413 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn next task: %m");
2415 if (s
->state
== SOCKET_START_POST
)
2416 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2417 else if (s
->state
== SOCKET_STOP_POST
)
2418 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2420 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2424 static int socket_start(Unit
*u
) {
2425 Socket
*s
= SOCKET(u
);
2430 /* We cannot fulfill this request right now, try again later
2432 if (IN_SET(s
->state
,
2434 SOCKET_STOP_PRE_SIGKILL
,
2435 SOCKET_STOP_PRE_SIGTERM
,
2437 SOCKET_FINAL_SIGTERM
,
2438 SOCKET_FINAL_SIGKILL
,
2442 /* Already on it! */
2443 if (IN_SET(s
->state
,
2449 /* Cannot run this without the service being around */
2450 if (UNIT_ISSET(s
->service
)) {
2453 service
= SERVICE(UNIT_DEREF(s
->service
));
2455 if (UNIT(service
)->load_state
!= UNIT_LOADED
)
2456 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
2457 "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2459 /* If the service is already active we cannot start the
2461 if (!IN_SET(service
->state
,
2462 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
2463 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
2464 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EBUSY
),
2465 "Socket service %s already active, refusing.", UNIT(service
)->id
);
2468 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2470 r
= unit_acquire_invocation_id(u
);
2474 s
->result
= SOCKET_SUCCESS
;
2475 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2477 if (s
->cgroup_runtime
)
2478 s
->cgroup_runtime
->reset_accounting
= true;
2480 socket_enter_start_pre(s
);
2484 static int socket_stop(Unit
*u
) {
2485 Socket
*s
= SOCKET(u
);
2490 if (IN_SET(s
->state
,
2492 SOCKET_STOP_PRE_SIGTERM
,
2493 SOCKET_STOP_PRE_SIGKILL
,
2495 SOCKET_FINAL_SIGTERM
,
2496 SOCKET_FINAL_SIGKILL
))
2499 /* If there's already something running we go directly into
2501 if (IN_SET(s
->state
,
2504 SOCKET_START_POST
)) {
2505 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2509 /* If we are currently cleaning, then abort it, brutally. */
2510 if (s
->state
== SOCKET_CLEANING
) {
2511 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2515 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2517 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2521 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2522 Socket
*s
= SOCKET(u
);
2529 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2530 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2531 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2532 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2533 (void) serialize_pidref(f
, fds
, "control-pid", &s
->control_pid
);
2535 if (s
->control_command_id
>= 0)
2536 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2538 LIST_FOREACH(port
, p
, s
->ports
) {
2544 copy
= fdset_put_dup(fds
, p
->fd
);
2546 return log_unit_warning_errno(u
, copy
, "Failed to serialize socket fd: %m");
2548 if (p
->type
== SOCKET_SOCKET
) {
2549 _cleanup_free_
char *t
= NULL
;
2551 r
= socket_address_print(&p
->address
, &t
);
2553 return log_unit_error_errno(u
, r
, "Failed to format socket address: %m");
2555 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2556 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2558 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2559 } else if (p
->type
== SOCKET_SPECIAL
)
2560 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2561 else if (p
->type
== SOCKET_MQUEUE
)
2562 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2563 else if (p
->type
== SOCKET_USB_FUNCTION
)
2564 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2566 assert(p
->type
== SOCKET_FIFO
);
2567 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2571 (void) serialize_ratelimit(f
, "trigger-ratelimit", &s
->trigger_limit
);
2576 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2577 Socket
*s
= SOCKET(u
);
2584 if (streq(key
, "state")) {
2587 state
= socket_state_from_string(value
);
2589 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2591 s
->deserialized_state
= state
;
2592 } else if (streq(key
, "result")) {
2595 f
= socket_result_from_string(value
);
2597 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2598 else if (f
!= SOCKET_SUCCESS
)
2601 } else if (streq(key
, "n-accepted")) {
2604 if (safe_atou(value
, &k
) < 0)
2605 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2608 } else if (streq(key
, "n-refused")) {
2611 if (safe_atou(value
, &k
) < 0)
2612 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2615 } else if (streq(key
, "control-pid")) {
2616 pidref_done(&s
->control_pid
);
2617 (void) deserialize_pidref(fds
, value
, &s
->control_pid
);
2619 } else if (streq(key
, "control-command")) {
2620 SocketExecCommand id
;
2622 id
= socket_exec_command_from_string(value
);
2624 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2626 s
->control_command_id
= id
;
2627 s
->control_command
= s
->exec_command
[id
];
2629 } else if (streq(key
, "fifo")) {
2630 _cleanup_free_
char *fdv
= NULL
;
2634 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2636 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2641 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2642 log_unit_debug(u
, "Invalid fifo value: %s", fdv
);
2646 LIST_FOREACH(port
, p
, s
->ports
)
2648 p
->type
== SOCKET_FIFO
&&
2649 path_equal_or_inode_same(p
->path
, value
, 0)) {
2650 p
->fd
= fdset_remove(fds
, fd
);
2655 log_unit_debug(u
, "No matching fifo socket found: %s", value
);
2657 } else if (streq(key
, "special")) {
2658 _cleanup_free_
char *fdv
= NULL
;
2662 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2664 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2669 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2670 log_unit_debug(u
, "Invalid special value: %s", fdv
);
2674 LIST_FOREACH(port
, p
, s
->ports
)
2676 p
->type
== SOCKET_SPECIAL
&&
2677 path_equal_or_inode_same(p
->path
, value
, 0)) {
2678 p
->fd
= fdset_remove(fds
, fd
);
2683 log_unit_debug(u
, "No matching special socket found: %s", value
);
2685 } else if (streq(key
, "mqueue")) {
2686 _cleanup_free_
char *fdv
= NULL
;
2690 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2692 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2697 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2698 log_unit_debug(u
, "Invalid mqueue value: %s", fdv
);
2702 LIST_FOREACH(port
, p
, s
->ports
)
2704 p
->type
== SOCKET_MQUEUE
&&
2705 streq(p
->path
, value
)) {
2706 p
->fd
= fdset_remove(fds
, fd
);
2711 log_unit_debug(u
, "No matching mqueue socket found: %s", value
);
2713 } else if (streq(key
, "socket")) {
2714 _cleanup_free_
char *fdv
= NULL
, *typev
= NULL
;
2718 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2720 log_unit_debug(u
, "Failed to parse socket fd from value: %s", value
);
2725 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2726 log_unit_debug(u
, "Invalid socket fd: %s", fdv
);
2730 r
= extract_first_word(&value
, &typev
, NULL
, 0);
2732 log_unit_debug(u
, "Failed to parse socket type from value: %s", value
);
2736 if (safe_atoi(typev
, &type
) < 0 || type
< 0) {
2737 log_unit_debug(u
, "Invalid socket type: %s", typev
);
2741 LIST_FOREACH(port
, p
, s
->ports
)
2743 socket_address_is(&p
->address
, value
, type
)) {
2744 p
->fd
= fdset_remove(fds
, fd
);
2749 log_unit_debug(u
, "No matching %s socket found: %s",
2750 socket_address_type_to_string(type
), value
);
2752 } else if (streq(key
, "netlink")) {
2753 _cleanup_free_
char *fdv
= NULL
;
2757 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2759 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2764 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2765 log_unit_debug(u
, "Invalid socket value: %s", fdv
);
2769 LIST_FOREACH(port
, p
, s
->ports
)
2771 socket_address_is_netlink(&p
->address
, value
)) {
2772 p
->fd
= fdset_remove(fds
, fd
);
2777 log_unit_debug(u
, "No matching netlink socket found: %s", value
);
2779 } else if (streq(key
, "ffs")) {
2780 _cleanup_free_
char *fdv
= NULL
;
2784 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2786 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2791 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2792 log_unit_debug(u
, "Invalid ffs value: %s", fdv
);
2796 LIST_FOREACH(port
, p
, s
->ports
)
2798 p
->type
== SOCKET_USB_FUNCTION
&&
2799 path_equal_or_inode_same(p
->path
, value
, 0)) {
2800 p
->fd
= fdset_remove(fds
, fd
);
2805 log_unit_debug(u
, "No matching ffs socket found: %s", value
);
2807 } else if (streq(key
, "trigger-ratelimit"))
2808 deserialize_ratelimit(&s
->trigger_limit
, key
, value
);
2811 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2816 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2817 Socket
*s
= SOCKET(u
);
2821 LIST_FOREACH(port
, p
, s
->ports
) {
2824 if (p
->type
!= SOCKET_SOCKET
)
2830 FDSET_FOREACH(fd
, fds
) {
2831 if (socket_address_matches_fd(&p
->address
, fd
)) {
2832 p
->fd
= fdset_remove(fds
, fd
);
2833 s
->deserialized_state
= SOCKET_LISTENING
;
2840 static UnitActiveState
socket_active_state(Unit
*u
) {
2843 return state_translation_table
[SOCKET(u
)->state
];
2846 static const char *socket_sub_state_to_string(Unit
*u
) {
2849 return socket_state_to_string(SOCKET(u
)->state
);
2852 int socket_port_to_address(const SocketPort
*p
, char **ret
) {
2853 _cleanup_free_
char *address
= NULL
;
2860 case SOCKET_SOCKET
: {
2861 r
= socket_address_print(&p
->address
, &address
);
2868 case SOCKET_SPECIAL
:
2871 case SOCKET_USB_FUNCTION
:
2872 address
= strdup(p
->path
);
2878 assert_not_reached();
2881 *ret
= TAKE_PTR(address
);
2886 const char* socket_port_type_to_string(SocketPort
*p
) {
2894 switch (p
->address
.type
) {
2902 case SOCK_SEQPACKET
:
2903 return "SequentialPacket";
2906 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2914 case SOCKET_SPECIAL
:
2918 return "MessageQueue";
2923 case SOCKET_USB_FUNCTION
:
2924 return "USBFunction";
2931 SocketType
socket_port_type_from_string(const char *s
) {
2934 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2935 return SOCKET_SOCKET
;
2936 else if (streq(s
, "Special"))
2937 return SOCKET_SPECIAL
;
2938 else if (streq(s
, "MessageQueue"))
2939 return SOCKET_MQUEUE
;
2940 else if (streq(s
, "FIFO"))
2942 else if (streq(s
, "USBFunction"))
2943 return SOCKET_USB_FUNCTION
;
2945 return _SOCKET_TYPE_INVALID
;
2948 static bool socket_may_gc(Unit
*u
) {
2949 Socket
*s
= SOCKET(u
);
2953 return s
->n_connections
== 0;
2956 static int socket_accept_do(Socket
*s
, int fd
) {
2962 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2964 /* Convert transient network errors into clean and well-defined EAGAIN */
2965 return ERRNO_IS_ACCEPT_AGAIN(errno
) ? -EAGAIN
: -errno
;
2970 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2971 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
2972 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
2979 /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
2980 * connection socket is also properly associated with the cgroup. */
2982 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2985 r
= bpf_firewall_supported();
2988 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2991 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2992 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2994 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2996 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
3000 pair
[0] = safe_close(pair
[0]);
3002 cfd
= socket_accept_do(s
, fd
);
3003 if (cfd
== -EAGAIN
) /* spurious accept() */
3004 _exit(EXIT_SUCCESS
);
3006 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3007 _exit(EXIT_FAILURE
);
3010 r
= send_one_fd(pair
[1], cfd
, 0);
3012 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
3013 _exit(EXIT_FAILURE
);
3016 _exit(EXIT_SUCCESS
);
3019 pair
[1] = safe_close(pair
[1]);
3020 cfd
= receive_one_fd(pair
[0], 0);
3022 /* We synchronously wait for the helper, as it shouldn't be slow */
3023 r
= wait_for_terminate_and_check("(sd-accept)", pid
.pid
, WAIT_LOG_ABNORMAL
);
3029 /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3030 * this is a spurious accept(), let's convert that back to EAGAIN here. */
3034 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
3039 cfd
= socket_accept_do(s
, fd
);
3040 if (cfd
== -EAGAIN
) /* spurious accept(), skip it silently */
3043 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3048 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3049 SocketPort
*p
= ASSERT_PTR(userdata
);
3054 if (p
->socket
->state
!= SOCKET_LISTENING
)
3057 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
3059 if (revents
!= EPOLLIN
) {
3060 if (revents
& EPOLLHUP
)
3061 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.");
3063 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
3067 if (p
->socket
->accept
&&
3068 p
->type
== SOCKET_SOCKET
&&
3069 socket_address_can_accept(&p
->address
)) {
3071 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
3072 if (cfd
== -EAGAIN
) /* Spurious accept() */
3077 socket_apply_socket_options(p
->socket
, p
, cfd
);
3080 socket_enter_running(p
->socket
, cfd
);
3084 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
3088 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3089 Socket
*s
= SOCKET(u
);
3095 if (pid
!= s
->control_pid
.pid
)
3098 pidref_done(&s
->control_pid
);
3100 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
3102 else if (code
== CLD_EXITED
)
3103 f
= SOCKET_FAILURE_EXIT_CODE
;
3104 else if (code
== CLD_KILLED
)
3105 f
= SOCKET_FAILURE_SIGNAL
;
3106 else if (code
== CLD_DUMPED
)
3107 f
= SOCKET_FAILURE_CORE_DUMP
;
3109 assert_not_reached();
3111 if (s
->control_command
) {
3112 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3114 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3118 unit_log_process_exit(
3121 socket_exec_command_to_string(s
->control_command_id
),
3122 f
== SOCKET_SUCCESS
,
3125 if (s
->result
== SOCKET_SUCCESS
)
3128 if (s
->control_command
&&
3129 s
->control_command
->command_next
&&
3130 f
== SOCKET_SUCCESS
) {
3132 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
3135 s
->control_command
= NULL
;
3136 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3138 /* No further commands for this step, so let's figure
3139 * out what to do next */
3141 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
3145 case SOCKET_START_PRE
:
3146 if (f
== SOCKET_SUCCESS
)
3147 socket_enter_start_chown(s
);
3149 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3152 case SOCKET_START_CHOWN
:
3153 if (f
== SOCKET_SUCCESS
)
3154 socket_enter_start_post(s
);
3156 socket_enter_stop_pre(s
, f
);
3159 case SOCKET_START_POST
:
3160 if (f
== SOCKET_SUCCESS
)
3161 socket_enter_listening(s
);
3163 socket_enter_stop_pre(s
, f
);
3166 case SOCKET_STOP_PRE
:
3167 case SOCKET_STOP_PRE_SIGTERM
:
3168 case SOCKET_STOP_PRE_SIGKILL
:
3169 socket_enter_stop_post(s
, f
);
3172 case SOCKET_STOP_POST
:
3173 case SOCKET_FINAL_SIGTERM
:
3174 case SOCKET_FINAL_SIGKILL
:
3175 socket_enter_dead(s
, f
);
3178 case SOCKET_CLEANING
:
3180 if (s
->clean_result
== SOCKET_SUCCESS
)
3181 s
->clean_result
= f
;
3183 socket_enter_dead(s
, SOCKET_SUCCESS
);
3187 assert_not_reached();
3191 /* Notify clients about changed exit status */
3192 unit_add_to_dbus_queue(u
);
3195 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3196 Socket
*s
= SOCKET(userdata
);
3199 assert(s
->timer_event_source
== source
);
3203 case SOCKET_START_PRE
:
3204 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3205 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3208 case SOCKET_START_CHOWN
:
3209 case SOCKET_START_POST
:
3210 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3211 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3214 case SOCKET_STOP_PRE
:
3215 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3216 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3219 case SOCKET_STOP_PRE_SIGTERM
:
3220 if (s
->kill_context
.send_sigkill
) {
3221 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3222 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3224 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3225 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3229 case SOCKET_STOP_PRE_SIGKILL
:
3230 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3231 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3234 case SOCKET_STOP_POST
:
3235 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3236 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3239 case SOCKET_FINAL_SIGTERM
:
3240 if (s
->kill_context
.send_sigkill
) {
3241 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3242 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3244 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3245 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3249 case SOCKET_FINAL_SIGKILL
:
3250 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3251 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3254 case SOCKET_CLEANING
:
3255 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
3257 if (s
->clean_result
== SOCKET_SUCCESS
)
3258 s
->clean_result
= SOCKET_FAILURE_TIMEOUT
;
3260 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, 0);
3264 assert_not_reached();
3270 int socket_collect_fds(Socket
*s
, int **fds
) {
3271 size_t k
= 0, n
= 0;
3277 /* Called from the service code for requesting our fds */
3279 LIST_FOREACH(port
, p
, s
->ports
) {
3282 n
+= p
->n_auxiliary_fds
;
3294 LIST_FOREACH(port
, p
, s
->ports
) {
3297 for (size_t i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3298 rfds
[k
++] = p
->auxiliary_fds
[i
];
3307 static void socket_reset_failed(Unit
*u
) {
3308 Socket
*s
= SOCKET(u
);
3312 if (s
->state
== SOCKET_FAILED
)
3313 socket_set_state(s
, SOCKET_DEAD
);
3315 s
->result
= SOCKET_SUCCESS
;
3316 s
->clean_result
= SOCKET_SUCCESS
;
3319 void socket_connection_unref(Socket
*s
) {
3322 /* The service is dead. Yay!
3324 * This is strictly for one-instance-per-connection
3327 assert(s
->n_connections
> 0);
3330 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3333 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3334 Socket
*s
= SOCKET(u
);
3339 /* Filter out invocations with bogus state */
3340 assert(UNIT_IS_LOAD_COMPLETE(other
->load_state
));
3341 assert(other
->type
== UNIT_SERVICE
);
3343 /* Don't propagate state changes from the service if we are already down */
3344 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3347 /* We don't care for the service state if we are in Accept=yes mode */
3351 /* Propagate start limit hit state */
3352 if (other
->start_limit_hit
) {
3353 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3357 /* Don't propagate anything if there's still a job queued */
3361 if (IN_SET(SERVICE(other
)->state
,
3362 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
3363 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3364 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
3365 socket_enter_listening(s
);
3367 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3368 socket_set_state(s
, SOCKET_RUNNING
);
3371 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3372 Socket
*s
= SOCKET(u
);
3376 if (!s
->timer_event_source
)
3379 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3382 if (t
== USEC_INFINITY
)
3389 char *socket_fdname(Socket
*s
) {
3392 /* Returns the name to use for $LISTEN_NAMES. If the user
3393 * didn't specify anything specifically, use the socket unit's
3394 * name as fallback. */
3396 return s
->fdname
?: UNIT(s
)->id
;
3399 static PidRef
*socket_control_pid(Unit
*u
) {
3400 return &ASSERT_PTR(SOCKET(u
))->control_pid
;
3403 static int socket_clean(Unit
*u
, ExecCleanMask mask
) {
3404 _cleanup_strv_free_
char **l
= NULL
;
3405 Socket
*s
= SOCKET(u
);
3411 if (s
->state
!= SOCKET_DEAD
)
3414 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
3418 if (strv_isempty(l
))
3421 socket_unwatch_control_pid(s
);
3422 s
->clean_result
= SOCKET_SUCCESS
;
3423 s
->control_command
= NULL
;
3424 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3426 r
= socket_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
3428 log_unit_warning_errno(u
, r
, "Failed to install timer: %m");
3432 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
3434 log_unit_warning_errno(u
, r
, "Failed to spawn cleaning task: %m");
3438 socket_set_state(s
, SOCKET_CLEANING
);
3442 s
->clean_result
= SOCKET_FAILURE_RESOURCES
;
3443 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
3447 static int socket_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
3448 Socket
*s
= SOCKET(u
);
3452 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
3455 static int socket_can_start(Unit
*u
) {
3456 Socket
*s
= SOCKET(u
);
3461 r
= unit_test_start_limit(u
);
3463 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
3470 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3471 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3472 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3473 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3474 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3475 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3478 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3480 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3481 [SOCKET_SUCCESS
] = "success",
3482 [SOCKET_FAILURE_RESOURCES
] = "resources",
3483 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3484 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3485 [SOCKET_FAILURE_SIGNAL
] = "signal",
3486 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3487 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3488 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3489 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3492 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3494 static const char* const socket_timestamping_table
[_SOCKET_TIMESTAMPING_MAX
] = {
3495 [SOCKET_TIMESTAMPING_OFF
] = "off",
3496 [SOCKET_TIMESTAMPING_US
] = "us",
3497 [SOCKET_TIMESTAMPING_NS
] = "ns",
3500 DEFINE_STRING_TABLE_LOOKUP(socket_timestamping
, SocketTimestamping
);
3502 SocketTimestamping
socket_timestamping_from_string_harder(const char *p
) {
3503 SocketTimestamping t
;
3507 return _SOCKET_TIMESTAMPING_INVALID
;
3509 t
= socket_timestamping_from_string(p
);
3513 /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3515 if (streq(p
, "nsec"))
3516 return SOCKET_TIMESTAMPING_NS
;
3517 if (STR_IN_SET(p
, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
3518 return SOCKET_TIMESTAMPING_US
;
3520 r
= parse_boolean(p
);
3522 return _SOCKET_TIMESTAMPING_INVALID
;
3524 return r
? SOCKET_TIMESTAMPING_NS
: SOCKET_TIMESTAMPING_OFF
; /* If boolean yes, default to ns accuracy */
3527 const UnitVTable socket_vtable
= {
3528 .object_size
= sizeof(Socket
),
3529 .exec_context_offset
= offsetof(Socket
, exec_context
),
3530 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3531 .kill_context_offset
= offsetof(Socket
, kill_context
),
3532 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3533 .cgroup_runtime_offset
= offsetof(Socket
, cgroup_runtime
),
3539 .private_section
= "Socket",
3541 .can_transient
= true,
3542 .can_trigger
= true,
3545 .init
= socket_init
,
3546 .done
= socket_done
,
3547 .load
= socket_load
,
3549 .coldplug
= socket_coldplug
,
3551 .dump
= socket_dump
,
3553 .start
= socket_start
,
3554 .stop
= socket_stop
,
3556 .clean
= socket_clean
,
3557 .can_clean
= socket_can_clean
,
3559 .get_timeout
= socket_get_timeout
,
3561 .serialize
= socket_serialize
,
3562 .deserialize_item
= socket_deserialize_item
,
3563 .distribute_fds
= socket_distribute_fds
,
3565 .active_state
= socket_active_state
,
3566 .sub_state_to_string
= socket_sub_state_to_string
,
3568 .will_restart
= unit_will_restart_default
,
3570 .may_gc
= socket_may_gc
,
3572 .sigchld_event
= socket_sigchld_event
,
3574 .trigger_notify
= socket_trigger_notify
,
3576 .reset_failed
= socket_reset_failed
,
3578 .control_pid
= socket_control_pid
,
3580 .bus_set_property
= bus_socket_set_property
,
3581 .bus_commit_properties
= bus_socket_commit_properties
,
3583 .status_message_formats
= {
3584 .finished_start_job
= {
3585 [JOB_DONE
] = "Listening on %s.",
3586 [JOB_FAILED
] = "Failed to listen on %s.",
3587 [JOB_TIMEOUT
] = "Timed out starting %s.",
3589 .finished_stop_job
= {
3590 [JOB_DONE
] = "Closed %s.",
3591 [JOB_FAILED
] = "Failed stopping %s.",
3592 [JOB_TIMEOUT
] = "Timed out stopping %s.",
3596 .can_start
= socket_can_start
,