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
= ASSERT_PTR(SOCKET(u
));
160 socket_free_ports(s
);
162 while ((p
= set_steal_first(s
->peers_by_address
)))
165 s
->peers_by_address
= set_free(s
->peers_by_address
);
167 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
169 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
170 s
->control_command
= NULL
;
172 socket_unwatch_control_pid(s
);
174 unit_ref_unset(&s
->service
);
176 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
177 s
->bind_to_device
= mfree(s
->bind_to_device
);
179 s
->smack
= mfree(s
->smack
);
180 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
181 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
183 strv_free(s
->symlinks
);
185 s
->user
= mfree(s
->user
);
186 s
->group
= mfree(s
->group
);
188 s
->fdname
= mfree(s
->fdname
);
190 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
193 static int socket_arm_timer(Socket
*s
, bool relative
, usec_t usec
) {
196 return unit_arm_timer(UNIT(s
), &s
->timer_event_source
, relative
, usec
, socket_dispatch_timer
);
199 static bool have_non_accept_socket(Socket
*s
) {
205 LIST_FOREACH(port
, p
, s
->ports
) {
207 if (p
->type
!= SOCKET_SOCKET
)
210 if (!socket_address_can_accept(&p
->address
))
217 static int socket_add_mount_dependencies(Socket
*s
) {
222 LIST_FOREACH(port
, p
, s
->ports
) {
223 const char *path
= NULL
;
225 if (p
->type
== SOCKET_SOCKET
)
226 path
= socket_address_get_path(&p
->address
);
227 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
233 r
= unit_add_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
, UNIT_MOUNT_REQUIRES
);
241 static int socket_add_device_dependencies(Socket
*s
) {
246 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
249 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
250 return unit_add_node_dependency(UNIT(s
), t
, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
253 static int socket_add_default_dependencies(Socket
*s
) {
258 if (!UNIT(s
)->default_dependencies
)
261 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
265 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
266 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
271 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
274 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
) {
287 Unit
*u
= UNIT(ASSERT_PTR(s
));
290 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
291 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
292 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
293 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
294 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
295 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
296 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
297 * service starts are typical.
299 * For the poll limit we follow a similar rule, but use 3/4th of the trigger limit parameters, to
300 * trigger this earlier. */
302 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
303 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
304 if (s
->trigger_limit
.burst
== UINT_MAX
)
305 s
->trigger_limit
.burst
= s
->accept
? 200 : 20;
307 if (s
->poll_limit_interval
== USEC_INFINITY
)
308 s
->poll_limit_interval
= 2 * USEC_PER_SEC
;
309 if (s
->poll_limit_burst
== UINT_MAX
)
310 s
->poll_limit_burst
= s
->accept
? 150 : 15;
312 if (have_non_accept_socket(s
)) {
314 if (!UNIT_DEREF(s
->service
)) {
317 r
= unit_load_related_unit(u
, ".service", &x
);
321 unit_ref_set(&s
->service
, u
, x
);
324 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
329 r
= socket_add_mount_dependencies(s
);
333 r
= socket_add_device_dependencies(s
);
337 r
= unit_patch_contexts(u
);
341 if (socket_has_exec(s
)) {
342 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
347 r
= unit_set_default_slice(u
);
351 r
= socket_add_default_dependencies(s
);
358 static const char *socket_find_symlink_target(Socket
*s
) {
359 const char *found
= NULL
;
361 LIST_FOREACH(port
, p
, s
->ports
) {
362 const char *f
= NULL
;
371 f
= socket_address_get_path(&p
->address
);
389 static int socket_verify(Socket
*s
) {
391 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
394 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
396 if (s
->accept
&& have_non_accept_socket(s
))
397 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
399 if (s
->accept
&& s
->max_connections
<= 0)
400 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "MaxConnection= setting too small. Refusing.");
402 if (s
->accept
&& UNIT_DEREF(s
->service
))
403 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Explicit service configuration for accepting socket units not supported. Refusing.");
405 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
)
406 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
408 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
))
409 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.");
414 static void peer_address_hash_func(const SocketPeer
*s
, struct siphash
*state
) {
417 if (s
->peer
.sa
.sa_family
== AF_INET
)
418 siphash24_compress_typesafe(s
->peer
.in
.sin_addr
, state
);
419 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
420 siphash24_compress_typesafe(s
->peer
.in6
.sin6_addr
, state
);
421 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
422 siphash24_compress_typesafe(s
->peer
.vm
.svm_cid
, state
);
423 else if (s
->peer
.sa
.sa_family
== AF_UNIX
)
424 siphash24_compress_typesafe(s
->peer_cred
.uid
, state
);
426 assert_not_reached();
429 static int peer_address_compare_func(const SocketPeer
*x
, const SocketPeer
*y
) {
432 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
436 switch (x
->peer
.sa
.sa_family
) {
438 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
440 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
442 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
444 return CMP(x
->peer_cred
.uid
, y
->peer_cred
.uid
);
446 assert_not_reached();
449 DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops
, SocketPeer
, peer_address_hash_func
, peer_address_compare_func
);
451 static int socket_load(Unit
*u
) {
452 Socket
*s
= ASSERT_PTR(SOCKET(u
));
455 assert(u
->load_state
== UNIT_STUB
);
457 r
= unit_load_fragment_and_dropin(u
, true);
461 if (u
->load_state
!= UNIT_LOADED
)
464 /* This is a new unit? Then let's add in some extras */
465 r
= socket_add_extras(s
);
469 return socket_verify(s
);
472 static SocketPeer
*socket_peer_dup(const SocketPeer
*q
) {
477 p
= new(SocketPeer
, 1);
484 .peer_salen
= q
->peer_salen
,
485 .peer_cred
= q
->peer_cred
,
491 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
495 set_remove(p
->socket
->peers_by_address
, p
);
500 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
502 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**ret
) {
503 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
505 .peer_salen
= sizeof(union sockaddr_union
),
506 .peer_cred
= UCRED_INVALID
,
514 if (getpeername(fd
, &key
.peer
.sa
, &key
.peer_salen
) < 0)
515 return log_unit_error_errno(UNIT(s
), errno
, "getpeername() failed: %m");
517 switch (key
.peer
.sa
.sa_family
) {
524 r
= getpeercred(fd
, &key
.peer_cred
);
526 return log_unit_error_errno(UNIT(s
), r
, "Failed to get peer credentials of socket: %m");
534 i
= set_get(s
->peers_by_address
, &key
);
536 *ret
= socket_peer_ref(i
);
540 remote
= socket_peer_dup(&key
);
544 r
= set_ensure_put(&s
->peers_by_address
, &peer_address_hash_ops
, remote
);
546 return log_unit_error_errno(UNIT(s
), r
, "Failed to insert peer info into hash table: %m");
550 *ret
= TAKE_PTR(remote
);
554 static const char* listen_lookup(int family
, int type
) {
556 if (family
== AF_NETLINK
)
557 return "ListenNetlink";
559 if (type
== SOCK_STREAM
)
560 return "ListenStream";
561 else if (type
== SOCK_DGRAM
)
562 return "ListenDatagram";
563 else if (type
== SOCK_SEQPACKET
)
564 return "ListenSequentialPacket";
566 assert_not_reached();
570 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
571 Socket
*s
= ASSERT_PTR(SOCKET(u
));
572 const char *prefix2
, *str
;
576 prefix
= strempty(prefix
);
577 prefix2
= strjoina(prefix
, "\t");
580 "%sSocket State: %s\n"
582 "%sClean Result: %s\n"
583 "%sBindIPv6Only: %s\n"
585 "%sSocketMode: %04o\n"
586 "%sDirectoryMode: %04o\n"
590 "%sTransparent: %s\n"
592 "%sPassCredentials: %s\n"
593 "%sPassFileDescriptorsToExec: %s\n"
594 "%sPassSecurity: %s\n"
595 "%sPassPacketInfo: %s\n"
596 "%sTCPCongestion: %s\n"
597 "%sRemoveOnStop: %s\n"
599 "%sFileDescriptorName: %s\n"
600 "%sSELinuxContextFromNet: %s\n",
601 prefix
, socket_state_to_string(s
->state
),
602 prefix
, socket_result_to_string(s
->result
),
603 prefix
, socket_result_to_string(s
->clean_result
),
604 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
606 prefix
, s
->socket_mode
,
607 prefix
, s
->directory_mode
,
608 prefix
, yes_no(s
->keep_alive
),
609 prefix
, yes_no(s
->no_delay
),
610 prefix
, yes_no(s
->free_bind
),
611 prefix
, yes_no(s
->transparent
),
612 prefix
, yes_no(s
->broadcast
),
613 prefix
, yes_no(s
->pass_cred
),
614 prefix
, yes_no(s
->pass_fds_to_exec
),
615 prefix
, yes_no(s
->pass_sec
),
616 prefix
, yes_no(s
->pass_pktinfo
),
617 prefix
, strna(s
->tcp_congestion
),
618 prefix
, yes_no(s
->remove_on_stop
),
619 prefix
, yes_no(s
->writable
),
620 prefix
, socket_fdname(s
),
621 prefix
, yes_no(s
->selinux_context_from_net
));
623 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
)
625 "%sTimestamping: %s\n",
626 prefix
, socket_timestamping_to_string(s
->timestamping
));
628 if (pidref_is_set(&s
->control_pid
))
630 "%sControl PID: "PID_FMT
"\n",
631 prefix
, s
->control_pid
.pid
);
633 if (s
->bind_to_device
)
635 "%sBindToDevice: %s\n",
636 prefix
, s
->bind_to_device
);
641 "%sNConnections: %u\n"
642 "%sMaxConnections: %u\n"
643 "%sMaxConnectionsPerSource: %u\n",
644 prefix
, s
->n_accepted
,
645 prefix
, s
->n_connections
,
646 prefix
, s
->max_connections
,
647 prefix
, s
->max_connections_per_source
);
650 "%sFlushPending: %s\n",
651 prefix
, yes_no(s
->flush_pending
));
654 if (s
->priority
>= 0)
657 prefix
, s
->priority
);
659 if (s
->receive_buffer
> 0)
661 "%sReceiveBuffer: %zu\n",
662 prefix
, s
->receive_buffer
);
664 if (s
->send_buffer
> 0)
666 "%sSendBuffer: %zu\n",
667 prefix
, s
->send_buffer
);
679 if (s
->pipe_size
> 0)
682 prefix
, s
->pipe_size
);
689 if (s
->mq_maxmsg
> 0)
691 "%sMessageQueueMaxMessages: %li\n",
692 prefix
, s
->mq_maxmsg
);
694 if (s
->mq_msgsize
> 0)
696 "%sMessageQueueMessageSize: %li\n",
697 prefix
, s
->mq_msgsize
);
702 prefix
, yes_no(s
->reuse_port
));
706 "%sSmackLabel: %s\n",
711 "%sSmackLabelIPIn: %s\n",
712 prefix
, s
->smack_ip_in
);
716 "%sSmackLabelIPOut: %s\n",
717 prefix
, s
->smack_ip_out
);
719 if (!isempty(s
->user
) || !isempty(s
->group
))
722 "%sSocketGroup: %s\n",
723 prefix
, strna(s
->user
),
724 prefix
, strna(s
->group
));
726 if (timestamp_is_set(s
->keep_alive_time
))
728 "%sKeepAliveTimeSec: %s\n",
729 prefix
, FORMAT_TIMESPAN(s
->keep_alive_time
, USEC_PER_SEC
));
731 if (s
->keep_alive_interval
> 0)
733 "%sKeepAliveIntervalSec: %s\n",
734 prefix
, FORMAT_TIMESPAN(s
->keep_alive_interval
, USEC_PER_SEC
));
736 if (s
->keep_alive_cnt
> 0)
738 "%sKeepAliveProbes: %u\n",
739 prefix
, s
->keep_alive_cnt
);
741 if (s
->defer_accept
> 0)
743 "%sDeferAcceptSec: %s\n",
744 prefix
, FORMAT_TIMESPAN(s
->defer_accept
, USEC_PER_SEC
));
746 LIST_FOREACH(port
, p
, s
->ports
) {
749 case SOCKET_SOCKET
: {
750 _cleanup_free_
char *k
= NULL
;
753 r
= socket_address_print(&p
->address
, &k
);
756 fprintf(f
, "%s%s: %m\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
));
758 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), k
);
762 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
764 case SOCKET_USB_FUNCTION
:
765 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
768 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
771 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
776 "%sTriggerLimitIntervalSec: %s\n"
777 "%sTriggerLimitBurst: %u\n"
778 "%sPollLimitIntervalSec: %s\n"
779 "%sPollLimitBurst: %u\n",
780 prefix
, FORMAT_TIMESPAN(s
->trigger_limit
.interval
, USEC_PER_SEC
),
781 prefix
, s
->trigger_limit
.burst
,
782 prefix
, FORMAT_TIMESPAN(s
->poll_limit_interval
, USEC_PER_SEC
),
783 prefix
, s
->poll_limit_burst
);
785 str
= ip_protocol_to_name(s
->socket_protocol
);
787 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
789 if (!strv_isempty(s
->symlinks
)) {
790 fprintf(f
, "%sSymlinks:", prefix
);
791 STRV_FOREACH(q
, s
->symlinks
)
792 fprintf(f
, " %s", *q
);
798 "%sTimeoutSec: %s\n",
799 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
801 exec_context_dump(&s
->exec_context
, f
, prefix
);
802 kill_context_dump(&s
->kill_context
, f
, prefix
);
804 for (SocketExecCommand c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
805 if (!s
->exec_command
[c
])
808 fprintf(f
, "%s%s %s:\n",
809 prefix
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), socket_exec_command_to_string(c
));
811 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
814 cgroup_context_dump(UNIT(s
), f
, prefix
);
817 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
820 union sockaddr_union local
, remote
;
826 if (getsockname(fd
, &local
.sa
, &l
) < 0)
830 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
833 switch (local
.sa
.sa_family
) {
837 a
= be32toh(local
.in
.sin_addr
.s_addr
),
838 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
841 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
843 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
844 be16toh(local
.in
.sin_port
),
845 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
846 be16toh(remote
.in
.sin_port
)) < 0)
853 static const unsigned char ipv4_prefix
[] = {
854 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
857 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
858 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
860 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
861 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
864 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
866 a
[0], a
[1], a
[2], a
[3],
867 be16toh(local
.in6
.sin6_port
),
868 b
[0], b
[1], b
[2], b
[3],
869 be16toh(remote
.in6
.sin6_port
)) < 0)
875 IN6_ADDR_TO_STRING(&local
.in6
.sin6_addr
),
876 be16toh(local
.in6
.sin6_port
),
877 IN6_ADDR_TO_STRING(&remote
.in6
.sin6_addr
),
878 be16toh(remote
.in6
.sin6_port
)) < 0)
889 k
= getpeercred(fd
, &ucred
);
892 "%u-"PID_FMT
"-"UID_FMT
,
893 nr
, ucred
.pid
, ucred
.uid
) < 0)
895 } else if (k
== -ENODATA
) {
896 /* This handles the case where somebody is
897 * connecting from another pid/uid namespace
898 * (e.g. from outside of our container). */
913 local
.vm
.svm_cid
, local
.vm
.svm_port
,
914 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
920 assert_not_reached();
927 static void socket_close_fds(Socket
*s
) {
930 LIST_FOREACH(port
, p
, s
->ports
) {
933 was_open
= p
->fd
>= 0;
935 p
->event_source
= sd_event_source_disable_unref(p
->event_source
);
936 p
->fd
= safe_close(p
->fd
);
937 socket_cleanup_fd_list(p
);
939 /* One little note: we should normally not delete any sockets in the file system here! After all some
940 * other process we spawned might still have a reference of this fd and wants to continue to use
941 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
942 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
943 * anyway, but only then. */
945 if (!was_open
|| !s
->remove_on_stop
)
951 (void) unlink(p
->path
);
955 (void) mq_unlink(p
->path
);
959 (void) socket_address_unlink(&p
->address
);
967 if (s
->remove_on_stop
)
968 STRV_FOREACH(i
, s
->symlinks
)
971 /* Note that we don't return NULL here, since s has not been freed. */
974 static void socket_apply_socket_options(Socket
*s
, SocketPort
*p
, int fd
) {
982 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
984 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
987 if (timestamp_is_set(s
->keep_alive_time
)) {
988 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
990 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
993 if (s
->keep_alive_interval
> 0) {
994 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
996 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
999 if (s
->keep_alive_cnt
> 0) {
1000 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
1002 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
1005 if (s
->defer_accept
> 0) {
1006 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
1008 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
1012 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1013 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1015 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1017 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1019 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1024 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1026 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1030 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1032 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1036 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1038 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1041 if (s
->pass_pktinfo
) {
1042 r
= socket_set_recvpktinfo(fd
, socket_address_family(&p
->address
), true);
1044 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable packet info socket option: %m");
1047 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
) {
1048 r
= setsockopt_int(fd
, SOL_SOCKET
,
1049 s
->timestamping
== SOCKET_TIMESTAMPING_NS
? SO_TIMESTAMPNS
: SO_TIMESTAMP
,
1052 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable timestamping socket option, ignoring: %m");
1055 if (s
->priority
>= 0) {
1056 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1058 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1061 if (s
->receive_buffer
> 0) {
1062 r
= fd_set_rcvbuf(fd
, s
->receive_buffer
, false);
1064 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1065 "SO_RCVBUF/SO_RCVBUFFORCE failed: %m");
1068 if (s
->send_buffer
> 0) {
1069 r
= fd_set_sndbuf(fd
, s
->send_buffer
, false);
1071 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1072 "SO_SNDBUF/SO_SNDBUFFORCE failed: %m");
1076 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1078 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1081 if (s
->ip_tos
>= 0) {
1082 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1084 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1087 if (s
->ip_ttl
>= 0) {
1088 r
= socket_set_ttl(fd
, socket_address_family(&p
->address
), s
->ip_ttl
);
1090 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1093 if (s
->tcp_congestion
)
1094 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1095 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1097 if (s
->smack_ip_in
) {
1098 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1100 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1103 if (s
->smack_ip_out
) {
1104 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1106 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1110 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1116 if (s
->pipe_size
> 0)
1117 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1118 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1121 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1123 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1127 static int fifo_address_create(
1129 mode_t directory_mode
,
1130 mode_t socket_mode
) {
1132 _cleanup_close_
int fd
= -EBADF
;
1139 (void) mkdir_parents_label(path
, directory_mode
);
1141 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1145 /* Enforce the right access mode for the fifo */
1146 old_mask
= umask(~socket_mode
);
1148 /* Include the original umask in our mask */
1149 (void) umask(~socket_mode
| old_mask
);
1151 r
= mkfifo(path
, socket_mode
);
1152 (void) umask(old_mask
);
1154 if (r
< 0 && errno
!= EEXIST
) {
1159 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1165 mac_selinux_create_file_clear();
1167 if (fstat(fd
, &st
) < 0) {
1172 if (!S_ISFIFO(st
.st_mode
) ||
1173 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1174 st
.st_uid
!= getuid() ||
1175 st
.st_gid
!= getgid()) {
1183 mac_selinux_create_file_clear();
1187 static int special_address_create(const char *path
, bool writable
) {
1188 _cleanup_close_
int fd
= -EBADF
;
1193 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1197 if (fstat(fd
, &st
) < 0)
1200 /* Check whether this is a /proc, /sys or /dev file or char device */
1201 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1207 static int usbffs_address_create(const char *path
) {
1208 _cleanup_close_
int fd
= -EBADF
;
1213 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1217 if (fstat(fd
, &st
) < 0)
1220 /* Check whether this is a regular file (ffs endpoint) */
1221 if (!S_ISREG(st
.st_mode
))
1227 static int mq_address_create(
1233 _cleanup_close_
int fd
= -EBADF
;
1236 struct mq_attr _attr
, *attr
= NULL
;
1240 if (maxmsg
> 0 && msgsize
> 0) {
1241 _attr
= (struct mq_attr
) {
1242 .mq_flags
= O_NONBLOCK
,
1243 .mq_maxmsg
= maxmsg
,
1244 .mq_msgsize
= msgsize
,
1249 /* Enforce the right access mode for the mq */
1250 old_mask
= umask(~mq_mode
);
1252 /* Include the original umask in our mask */
1253 (void) umask(~mq_mode
| old_mask
);
1254 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1255 (void) umask(old_mask
);
1260 if (fstat(fd
, &st
) < 0)
1263 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1264 st
.st_uid
!= getuid() ||
1265 st
.st_gid
!= getgid())
1271 static int socket_symlink(Socket
*s
) {
1277 p
= socket_find_symlink_target(s
);
1281 STRV_FOREACH(i
, s
->symlinks
) {
1282 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1284 r
= symlink_idempotent(p
, *i
, false);
1286 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1287 /* If there's already something where we want to create the symlink, and the destructive
1288 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1291 if (unlink(*i
) >= 0)
1292 r
= symlink_idempotent(p
, *i
, false);
1296 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s %s %s, ignoring: %m",
1297 p
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *i
);
1303 static int usbffs_write_descs(int fd
, Service
*s
) {
1309 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1312 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1316 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1319 static int usbffs_select_ep(const struct dirent
*d
) {
1320 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1323 static int usbffs_dispatch_eps(SocketPort
*p
) {
1324 _cleanup_free_
struct dirent
**ent
= NULL
;
1328 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1333 p
->auxiliary_fds
= new(int, n
);
1334 if (!p
->auxiliary_fds
) {
1339 p
->n_auxiliary_fds
= n
;
1342 for (size_t i
= 0; i
< n
; ++i
) {
1343 _cleanup_free_
char *ep
= NULL
;
1345 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1353 r
= usbffs_address_create(ep
);
1357 p
->auxiliary_fds
[k
++] = r
;
1364 close_many(p
->auxiliary_fds
, k
);
1365 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1366 p
->n_auxiliary_fds
= 0;
1369 free_many((void**) ent
, n
);
1373 int socket_load_service_unit(Socket
*s
, int cfd
, Unit
**ret
) {
1376 /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1378 * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1385 if (UNIT_ISSET(s
->service
)) {
1386 *ret
= UNIT_DEREF(s
->service
);
1393 /* Build the instance name and load the unit */
1394 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
1396 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
1401 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
1403 if (ERRNO_IS_DISCONNECT(r
))
1404 /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1405 * different errors. This connection is over, but the socket unit lives on. */
1406 return log_unit_debug_errno(UNIT(s
), r
,
1407 "Got %s on incoming socket, assuming aborted connection attempt, ignoring.",
1413 /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1414 * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1415 * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1416 r
= unit_name_build(prefix
, instance
?: "internal", ".service", &name
);
1420 return manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, ret
);
1423 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1430 r
= socket_load_service_unit(s
, /* cfd= */ -EBADF
, &service
);
1431 if (r
== -ENODATA
) {
1438 r
= service_determine_exec_selinux_label(SERVICE(service
), ret
);
1439 if (r
== -ENODATA
) {
1446 static int socket_address_listen_do(
1448 const SocketAddress
*address
,
1449 const char *label
) {
1454 return socket_address_listen(
1456 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1468 #define log_address_error_errno(u, address, error, fmt) \
1470 _cleanup_free_ char *_t = NULL; \
1472 (void) socket_address_print(address, &_t); \
1473 log_unit_error_errno(u, error, fmt, strna(_t)); \
1476 static int fork_needed(const SocketAddress
*address
, Socket
*s
) {
1482 /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1484 /* If there are any NFTSet= directives with cgroup source, we need the cgroup */
1486 CGroupContext
*c
= unit_get_cgroup_context(u
);
1488 FOREACH_ARRAY(nft_set
, c
->nft_set_context
.sets
, c
->nft_set_context
.n_sets
)
1489 if (nft_set
->source
== NFT_SET_SOURCE_CGROUP
)
1492 if (IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
)) {
1493 r
= bpf_firewall_supported();
1496 if (r
!= BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1500 return exec_needs_network_namespace(&s
->exec_context
);
1503 static int socket_address_listen_in_cgroup(
1505 const SocketAddress
*address
,
1506 const char *label
) {
1508 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
1509 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
1515 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1516 * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1517 * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1520 r
= fork_needed(address
, s
);
1524 /* Shortcut things... */
1525 fd
= socket_address_listen_do(s
, address
, label
);
1527 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1532 r
= unit_setup_exec_runtime(UNIT(s
));
1534 return log_unit_error_errno(UNIT(s
), r
, "Failed acquire runtime: %m");
1536 if (s
->exec_context
.network_namespace_path
&&
1538 s
->exec_runtime
->shared
&&
1539 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1540 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->netns_storage_socket
, s
->exec_context
.network_namespace_path
, CLONE_NEWNET
);
1542 return log_unit_error_errno(UNIT(s
), r
, "Failed to open network namespace path %s: %m", s
->exec_context
.network_namespace_path
);
1545 if (s
->exec_context
.ipc_namespace_path
&&
1547 s
->exec_runtime
->shared
&&
1548 s
->exec_runtime
->shared
->ipcns_storage_socket
[0] >= 0) {
1549 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->ipcns_storage_socket
, s
->exec_context
.ipc_namespace_path
, CLONE_NEWIPC
);
1551 return log_unit_error_errno(UNIT(s
), r
, "Failed to open IPC namespace path %s: %m", s
->exec_context
.ipc_namespace_path
);
1554 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1555 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1557 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1559 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1563 pair
[0] = safe_close(pair
[0]);
1565 if (exec_needs_network_namespace(&s
->exec_context
) &&
1567 s
->exec_runtime
->shared
&&
1568 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1570 if (ns_type_supported(NAMESPACE_NET
)) {
1571 r
= setup_shareable_ns(s
->exec_runtime
->shared
->netns_storage_socket
, CLONE_NEWNET
);
1573 log_unit_error_errno(UNIT(s
), r
, "Failed to join network namespace: %m");
1574 _exit(EXIT_NETWORK
);
1576 } else if (s
->exec_context
.network_namespace_path
) {
1577 log_unit_error(UNIT(s
), "Network namespace path configured but network namespaces not supported.");
1578 _exit(EXIT_NETWORK
);
1580 log_unit_warning(UNIT(s
), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
1583 fd
= socket_address_listen_do(s
, address
, label
);
1585 log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1586 _exit(EXIT_FAILURE
);
1589 r
= send_one_fd(pair
[1], fd
, 0);
1591 log_address_error_errno(UNIT(s
), address
, r
, "Failed to send listening socket (%s) to parent: %m");
1592 _exit(EXIT_FAILURE
);
1595 _exit(EXIT_SUCCESS
);
1598 pair
[1] = safe_close(pair
[1]);
1599 fd
= receive_one_fd(pair
[0], 0);
1601 /* We synchronously wait for the helper, as it shouldn't be slow */
1602 r
= wait_for_terminate_and_check("(sd-listen)", pid
.pid
, WAIT_LOG_ABNORMAL
);
1609 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to receive listening socket (%s): %m");
1614 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket
*, socket_close_fds
, NULL
);
1616 static int socket_open_fds(Socket
*orig_s
) {
1617 _cleanup_(socket_close_fdsp
) Socket
*s
= orig_s
;
1618 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1619 bool know_label
= false;
1624 LIST_FOREACH(port
, p
, s
->ports
) {
1634 /* Figure out the label, if we don't it know yet. We do it once for the first
1635 * socket where we need this and remember it for the rest. */
1637 r
= socket_determine_selinux_label(s
, &label
);
1639 return log_unit_error_errno(UNIT(s
), r
, "Failed to determine SELinux label: %m");
1644 /* Apply the socket protocol */
1645 switch (p
->address
.type
) {
1648 case SOCK_SEQPACKET
:
1649 if (s
->socket_protocol
== IPPROTO_SCTP
)
1650 p
->address
.protocol
= s
->socket_protocol
;
1654 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1655 p
->address
.protocol
= s
->socket_protocol
;
1659 p
->fd
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1663 socket_apply_socket_options(s
, p
, p
->fd
);
1667 case SOCKET_SPECIAL
:
1669 p
->fd
= special_address_create(p
->path
, s
->writable
);
1671 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open special file %s: %m", p
->path
);
1676 p
->fd
= fifo_address_create(
1681 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open FIFO %s: %m", p
->path
);
1683 socket_apply_fifo_options(s
, p
->fd
);
1689 p
->fd
= mq_address_create(
1695 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open message queue %s: %m", p
->path
);
1698 case SOCKET_USB_FUNCTION
: {
1699 _cleanup_free_
char *ep
= NULL
;
1701 ep
= path_make_absolute("ep0", p
->path
);
1705 p
->fd
= usbffs_address_create(ep
);
1709 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1713 r
= usbffs_dispatch_eps(p
);
1720 assert_not_reached();
1728 static void socket_unwatch_fds(Socket
*s
) {
1733 LIST_FOREACH(port
, p
, s
->ports
) {
1737 if (!p
->event_source
)
1740 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1742 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1746 static int socket_watch_fds(Socket
*s
) {
1751 LIST_FOREACH(port
, p
, s
->ports
) {
1755 if (p
->event_source
) {
1756 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1760 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1764 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1767 r
= sd_event_source_set_ratelimit(p
->event_source
, s
->poll_limit_interval
, s
->poll_limit_burst
);
1769 log_unit_debug_errno(UNIT(s
), r
, "Failed to set poll limit on I/O event source, ignoring: %m");
1775 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1776 socket_unwatch_fds(s
);
1786 static int socket_check_open(Socket
*s
) {
1787 bool have_open
= false, have_closed
= false;
1791 LIST_FOREACH(port
, p
, s
->ports
) {
1797 if (have_open
&& have_closed
)
1798 return SOCKET_OPEN_SOME
;
1802 return SOCKET_OPEN_ALL
;
1804 return SOCKET_OPEN_NONE
;
1807 static void socket_set_state(Socket
*s
, SocketState state
) {
1808 SocketState old_state
;
1812 if (s
->state
!= state
)
1813 bus_unit_send_pending_change_signal(UNIT(s
), false);
1815 old_state
= s
->state
;
1818 if (!SOCKET_STATE_WITH_PROCESS(state
)) {
1819 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1820 socket_unwatch_control_pid(s
);
1821 s
->control_command
= NULL
;
1822 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1825 if (state
!= SOCKET_LISTENING
)
1826 socket_unwatch_fds(s
);
1834 SOCKET_STOP_PRE_SIGTERM
,
1835 SOCKET_STOP_PRE_SIGKILL
,
1837 socket_close_fds(s
);
1839 if (state
!= old_state
)
1840 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1842 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
1845 static int socket_coldplug(Unit
*u
) {
1846 Socket
*s
= ASSERT_PTR(SOCKET(u
));
1849 assert(s
->state
== SOCKET_DEAD
);
1851 if (s
->deserialized_state
== s
->state
)
1854 if (pidref_is_set(&s
->control_pid
) &&
1855 pidref_is_unwaited(&s
->control_pid
) > 0 &&
1856 SOCKET_STATE_WITH_PROCESS(s
->deserialized_state
)) {
1858 r
= unit_watch_pidref(UNIT(s
), &s
->control_pid
, /* exclusive= */ false);
1862 r
= socket_arm_timer(s
, /* relative= */ false, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1867 if (IN_SET(s
->deserialized_state
,
1873 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1874 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN state for
1875 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1876 * and if there's a mismatch, warn loudly. */
1878 r
= socket_check_open(s
);
1879 if (r
== SOCKET_OPEN_NONE
)
1880 log_unit_warning(UNIT(s
),
1881 "Socket unit configuration has changed while unit has been running, "
1882 "no open socket file descriptor left. "
1883 "The socket unit is not functional until restarted.");
1884 else if (r
== SOCKET_OPEN_SOME
)
1885 log_unit_warning(UNIT(s
),
1886 "Socket unit configuration has changed while unit has been running, "
1887 "and some socket file descriptors have not been opened yet. "
1888 "The socket unit is not fully functional until restarted.");
1891 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1892 r
= socket_watch_fds(s
);
1897 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
, SOCKET_CLEANING
))
1898 (void) unit_setup_exec_runtime(u
);
1900 socket_set_state(s
, s
->deserialized_state
);
1904 static int socket_spawn(Socket
*s
, ExecCommand
*c
, PidRef
*ret_pid
) {
1905 _cleanup_(exec_params_shallow_clear
) ExecParameters exec_params
= EXEC_PARAMETERS_INIT(
1906 EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
);
1907 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1914 r
= unit_prepare_exec(UNIT(s
));
1918 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
1922 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1926 /* Note that ExecStartPre= command doesn't inherit any FDs. It runs before we open listen FDs. */
1927 if (s
->pass_fds_to_exec
) {
1928 _cleanup_strv_free_
char **fd_names
= NULL
;
1929 _cleanup_free_
int *fds
= NULL
;
1932 n_fds
= socket_collect_fds(s
, &fds
);
1936 r
= strv_extend_n(&fd_names
, socket_fdname(s
), n_fds
);
1940 exec_params
.flags
|= EXEC_PASS_FDS
;
1941 exec_params
.fds
= TAKE_PTR(fds
);
1942 exec_params
.fd_names
= TAKE_PTR(fd_names
);
1943 exec_params
.n_socket_fds
= n_fds
;
1946 r
= exec_spawn(UNIT(s
),
1956 r
= unit_watch_pidref(UNIT(s
), &pidref
, /* exclusive= */ true);
1960 *ret_pid
= TAKE_PIDREF(pidref
);
1964 static int socket_chown(Socket
*s
, PidRef
*ret_pid
) {
1965 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
1970 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
1974 /* We have to resolve the user names out-of-process, hence
1975 * let's fork here. It's messy, but well, what can we do? */
1977 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1981 uid_t uid
= UID_INVALID
;
1982 gid_t gid
= GID_INVALID
;
1986 if (!isempty(s
->user
)) {
1987 const char *user
= s
->user
;
1989 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1991 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1996 if (!isempty(s
->group
)) {
1997 const char *group
= s
->group
;
1999 r
= get_group_creds(&group
, &gid
, 0);
2001 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
2006 LIST_FOREACH(port
, p
, s
->ports
) {
2007 const char *path
= NULL
;
2009 if (p
->type
== SOCKET_SOCKET
)
2010 path
= socket_address_get_path(&p
->address
);
2011 else if (p
->type
== SOCKET_FIFO
)
2017 if (chown(path
, uid
, gid
) < 0) {
2018 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
2023 _exit(EXIT_SUCCESS
);
2026 r
= unit_watch_pidref(UNIT(s
), &pid
, /* exclusive= */ true);
2030 *ret_pid
= TAKE_PIDREF(pid
);
2034 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
2037 if (s
->result
== SOCKET_SUCCESS
)
2040 if (s
->result
== SOCKET_SUCCESS
)
2041 unit_log_success(UNIT(s
));
2043 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
2045 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2047 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
2049 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2051 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2053 unit_unref_uid_gid(UNIT(s
), true);
2056 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2058 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2063 if (s
->result
== SOCKET_SUCCESS
)
2066 socket_unwatch_control_pid(s
);
2067 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2068 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2070 if (s
->control_command
) {
2071 pidref_done(&s
->control_pid
);
2073 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2075 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-post' task: %m");
2076 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2080 socket_set_state(s
, SOCKET_STOP_POST
);
2082 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2085 static int state_to_kill_operation(Socket
*s
, SocketState state
) {
2086 if (state
== SOCKET_STOP_PRE_SIGTERM
&& unit_has_job_type(UNIT(s
), JOB_RESTART
))
2087 return KILL_RESTART
;
2089 if (state
== SOCKET_FINAL_SIGTERM
)
2090 return KILL_TERMINATE
;
2095 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2100 if (s
->result
== SOCKET_SUCCESS
)
2103 r
= unit_kill_context(UNIT(s
), state_to_kill_operation(s
, state
));
2105 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2110 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
2112 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2116 socket_set_state(s
, state
);
2117 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2118 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2119 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2120 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2121 else if (state
== SOCKET_FINAL_SIGTERM
)
2122 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2124 socket_enter_dead(s
, SOCKET_SUCCESS
);
2129 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2130 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2132 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2135 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2140 if (s
->result
== SOCKET_SUCCESS
)
2143 socket_unwatch_control_pid(s
);
2144 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2145 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2147 if (s
->control_command
) {
2148 pidref_done(&s
->control_pid
);
2150 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2152 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-pre' task: %m");
2153 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2157 socket_set_state(s
, SOCKET_STOP_PRE
);
2159 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2162 static void socket_enter_listening(Socket
*s
) {
2167 if (!s
->accept
&& s
->flush_pending
) {
2168 log_unit_debug(UNIT(s
), "Flushing socket before listening.");
2172 r
= socket_watch_fds(s
);
2174 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2175 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2179 socket_set_state(s
, SOCKET_LISTENING
);
2182 static void socket_enter_start_post(Socket
*s
) {
2187 socket_unwatch_control_pid(s
);
2188 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2189 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2191 if (s
->control_command
) {
2192 pidref_done(&s
->control_pid
);
2194 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2196 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-post' task: %m");
2197 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2201 socket_set_state(s
, SOCKET_START_POST
);
2203 socket_enter_listening(s
);
2206 static void socket_enter_start_chown(Socket
*s
) {
2211 r
= socket_open_fds(s
);
2213 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2217 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2219 socket_unwatch_control_pid(s
);
2220 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2221 s
->control_command
= NULL
;
2223 r
= socket_chown(s
, &s
->control_pid
);
2225 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-chown' task: %m");
2229 socket_set_state(s
, SOCKET_START_CHOWN
);
2231 socket_enter_start_post(s
);
2236 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2239 static void socket_enter_start_pre(Socket
*s
) {
2244 socket_unwatch_control_pid(s
);
2246 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
2248 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2249 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2251 if (s
->control_command
) {
2252 pidref_done(&s
->control_pid
);
2254 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2256 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-pre' task: %m");
2257 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2261 socket_set_state(s
, SOCKET_START_PRE
);
2263 socket_enter_start_chown(s
);
2266 static void flush_ports(Socket
*s
) {
2269 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2272 LIST_FOREACH(port
, p
, s
->ports
) {
2276 (void) flush_accept(p
->fd
);
2277 (void) flush_fd(p
->fd
);
2281 static void socket_enter_running(Socket
*s
, int cfd_in
) {
2282 /* Note that this call takes possession of the connection fd passed. It either has to assign it
2283 * somewhere or close it. */
2284 _cleanup_close_
int cfd
= cfd_in
;
2285 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2290 /* We don't take connections anymore if we are supposed to shut down anyway */
2291 if (unit_stop_pending(UNIT(s
))) {
2293 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2302 if (!ratelimit_below(&s
->trigger_limit
)) {
2303 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2304 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2308 if (cfd
< 0) { /* Accept=no case */
2309 bool pending
= false;
2312 /* If there's already a start pending don't bother to do anything */
2313 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_TRIGGERS
)
2314 if (unit_active_or_pending(other
)) {
2320 if (!UNIT_ISSET(s
->service
)) {
2321 log_unit_warning(UNIT(s
),
2322 "Service to activate vanished, refusing activation.");
2326 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, NULL
, &error
, NULL
);
2331 socket_set_state(s
, SOCKET_RUNNING
);
2332 } else { /* Accept=yes case */
2333 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2336 if (s
->n_connections
>= s
->max_connections
) {
2337 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2342 if (s
->max_connections_per_source
> 0) {
2343 r
= socket_acquire_peer(s
, cfd
, &p
);
2345 if (ERRNO_IS_DISCONNECT(r
))
2347 /* We didn't have enough resources to acquire peer information, let's fail. */
2350 if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2351 _cleanup_free_
char *t
= NULL
;
2353 if (p
->peer
.sa
.sa_family
== AF_UNIX
)
2354 (void) asprintf(&t
, "UID " UID_FMT
, p
->peer_cred
.uid
);
2356 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, /* translate_ipv6= */ true, /* include_port= */ false, &t
);
2358 log_unit_warning(UNIT(s
),
2359 "Too many incoming connections (%u) from source %s, dropping connection.",
2360 p
->n_ref
, strnull(t
));
2365 r
= socket_load_service_unit(s
, cfd
, &service
);
2366 if (ERRNO_IS_NEG_DISCONNECT(r
))
2368 if (r
< 0 || UNIT_IS_LOAD_ERROR(service
->load_state
)) {
2369 log_unit_warning_errno(UNIT(s
), r
< 0 ? r
: service
->load_error
,
2370 "Failed to load connection service unit: %m");
2373 if (service
->load_state
== UNIT_MASKED
) {
2374 log_unit_warning(UNIT(s
), "Connection service unit is masked, refusing.");
2380 r
= service_set_socket_fd(SERVICE(service
), cfd
, s
, p
, s
->selinux_context_from_net
);
2382 if (ERRNO_IS_DISCONNECT(r
))
2385 log_unit_warning_errno(UNIT(s
), r
, "Failed to set socket on service: %m");
2389 /* We passed ownership of the fd and socket peer to the service now. */
2395 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, service
, JOB_REPLACE
, NULL
, &error
, NULL
);
2397 /* We failed to activate the new service, but it still exists. Let's make sure the
2398 * service closes and forgets the connection fd again, immediately. */
2399 service_release_socket_fd(SERVICE(service
));
2403 /* Notify clients about changed counters */
2404 unit_add_to_dbus_queue(UNIT(s
));
2414 log_unit_warning_errno(UNIT(s
), r
, "Failed to queue service startup job%s: %s",
2415 cfd
>= 0 && !ERRNO_IS_RESOURCE(r
) ? " (Maybe the service is missing or is a template unit?)" : "",
2416 bus_error_message(&error
, r
));
2419 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2422 static void socket_run_next(Socket
*s
) {
2426 assert(s
->control_command
);
2427 assert(s
->control_command
->command_next
);
2429 socket_unwatch_control_pid(s
);
2431 s
->control_command
= s
->control_command
->command_next
;
2433 pidref_done(&s
->control_pid
);
2435 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2437 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn next task: %m");
2439 if (s
->state
== SOCKET_START_POST
)
2440 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2441 else if (s
->state
== SOCKET_STOP_POST
)
2442 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2444 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2448 static int socket_start(Unit
*u
) {
2449 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2452 /* We cannot fulfill this request right now, try again later
2454 if (IN_SET(s
->state
,
2456 SOCKET_STOP_PRE_SIGKILL
,
2457 SOCKET_STOP_PRE_SIGTERM
,
2459 SOCKET_FINAL_SIGTERM
,
2460 SOCKET_FINAL_SIGKILL
,
2464 /* Already on it! */
2465 if (IN_SET(s
->state
,
2471 /* Cannot run this without the service being around */
2472 if (UNIT_ISSET(s
->service
)) {
2475 service
= SERVICE(UNIT_DEREF(s
->service
));
2477 if (UNIT(service
)->load_state
!= UNIT_LOADED
)
2478 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
2479 "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2481 /* If the service is already active we cannot start the
2483 if (!IN_SET(service
->state
,
2484 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
2485 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
2486 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EBUSY
),
2487 "Socket service %s already active, refusing.", UNIT(service
)->id
);
2490 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2492 r
= unit_acquire_invocation_id(u
);
2496 s
->result
= SOCKET_SUCCESS
;
2497 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2499 if (s
->cgroup_runtime
)
2500 s
->cgroup_runtime
->reset_accounting
= true;
2502 socket_enter_start_pre(s
);
2506 static int socket_stop(Unit
*u
) {
2507 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2510 if (IN_SET(s
->state
,
2512 SOCKET_STOP_PRE_SIGTERM
,
2513 SOCKET_STOP_PRE_SIGKILL
,
2515 SOCKET_FINAL_SIGTERM
,
2516 SOCKET_FINAL_SIGKILL
))
2519 /* If there's already something running we go directly into
2521 if (IN_SET(s
->state
,
2524 SOCKET_START_POST
)) {
2525 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2529 /* If we are currently cleaning, then abort it, brutally. */
2530 if (s
->state
== SOCKET_CLEANING
) {
2531 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2535 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2537 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2541 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2542 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2548 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2549 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2550 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2551 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2552 (void) serialize_pidref(f
, fds
, "control-pid", &s
->control_pid
);
2554 if (s
->control_command_id
>= 0)
2555 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2557 LIST_FOREACH(port
, p
, s
->ports
) {
2563 copy
= fdset_put_dup(fds
, p
->fd
);
2565 return log_unit_warning_errno(u
, copy
, "Failed to serialize socket fd: %m");
2567 if (p
->type
== SOCKET_SOCKET
) {
2568 _cleanup_free_
char *t
= NULL
;
2570 r
= socket_address_print(&p
->address
, &t
);
2572 return log_unit_error_errno(u
, r
, "Failed to format socket address: %m");
2574 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2575 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2577 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2578 } else if (p
->type
== SOCKET_SPECIAL
)
2579 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2580 else if (p
->type
== SOCKET_MQUEUE
)
2581 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2582 else if (p
->type
== SOCKET_USB_FUNCTION
)
2583 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2585 assert(p
->type
== SOCKET_FIFO
);
2586 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2590 (void) serialize_ratelimit(f
, "trigger-ratelimit", &s
->trigger_limit
);
2595 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2596 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2602 if (streq(key
, "state")) {
2605 state
= socket_state_from_string(value
);
2607 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2609 s
->deserialized_state
= state
;
2610 } else if (streq(key
, "result")) {
2613 f
= socket_result_from_string(value
);
2615 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2616 else if (f
!= SOCKET_SUCCESS
)
2619 } else if (streq(key
, "n-accepted")) {
2622 if (safe_atou(value
, &k
) < 0)
2623 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2626 } else if (streq(key
, "n-refused")) {
2629 if (safe_atou(value
, &k
) < 0)
2630 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2633 } else if (streq(key
, "control-pid")) {
2635 if (!pidref_is_set(&s
->control_pid
))
2636 (void) deserialize_pidref(fds
, value
, &s
->control_pid
);
2638 } else if (streq(key
, "control-command")) {
2639 SocketExecCommand id
;
2641 id
= socket_exec_command_from_string(value
);
2643 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2645 s
->control_command_id
= id
;
2646 s
->control_command
= s
->exec_command
[id
];
2648 } else if (streq(key
, "fifo")) {
2649 _cleanup_free_
char *fdv
= NULL
;
2653 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2655 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2660 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2661 log_unit_debug(u
, "Invalid fifo value: %s", fdv
);
2665 LIST_FOREACH(port
, p
, s
->ports
)
2667 p
->type
== SOCKET_FIFO
&&
2668 path_equal_or_inode_same(p
->path
, value
, 0)) {
2669 p
->fd
= fdset_remove(fds
, fd
);
2674 log_unit_debug(u
, "No matching fifo socket found: %s", value
);
2676 } else if (streq(key
, "special")) {
2677 _cleanup_free_
char *fdv
= NULL
;
2681 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2683 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2688 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2689 log_unit_debug(u
, "Invalid special value: %s", fdv
);
2693 LIST_FOREACH(port
, p
, s
->ports
)
2695 p
->type
== SOCKET_SPECIAL
&&
2696 path_equal_or_inode_same(p
->path
, value
, 0)) {
2697 p
->fd
= fdset_remove(fds
, fd
);
2702 log_unit_debug(u
, "No matching special socket found: %s", value
);
2704 } else if (streq(key
, "mqueue")) {
2705 _cleanup_free_
char *fdv
= NULL
;
2709 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2711 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2716 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2717 log_unit_debug(u
, "Invalid mqueue value: %s", fdv
);
2721 LIST_FOREACH(port
, p
, s
->ports
)
2723 p
->type
== SOCKET_MQUEUE
&&
2724 streq(p
->path
, value
)) {
2725 p
->fd
= fdset_remove(fds
, fd
);
2730 log_unit_debug(u
, "No matching mqueue socket found: %s", value
);
2732 } else if (streq(key
, "socket")) {
2733 _cleanup_free_
char *fdv
= NULL
, *typev
= NULL
;
2737 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2739 log_unit_debug(u
, "Failed to parse socket fd from value: %s", value
);
2744 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2745 log_unit_debug(u
, "Invalid socket fd: %s", fdv
);
2749 r
= extract_first_word(&value
, &typev
, NULL
, 0);
2751 log_unit_debug(u
, "Failed to parse socket type from value: %s", value
);
2755 if (safe_atoi(typev
, &type
) < 0 || type
< 0) {
2756 log_unit_debug(u
, "Invalid socket type: %s", typev
);
2760 LIST_FOREACH(port
, p
, s
->ports
)
2762 socket_address_is(&p
->address
, value
, type
)) {
2763 p
->fd
= fdset_remove(fds
, fd
);
2768 log_unit_debug(u
, "No matching %s socket found: %s",
2769 socket_address_type_to_string(type
), value
);
2771 } else if (streq(key
, "netlink")) {
2772 _cleanup_free_
char *fdv
= NULL
;
2776 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2778 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2783 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2784 log_unit_debug(u
, "Invalid socket value: %s", fdv
);
2788 LIST_FOREACH(port
, p
, s
->ports
)
2790 socket_address_is_netlink(&p
->address
, value
)) {
2791 p
->fd
= fdset_remove(fds
, fd
);
2796 log_unit_debug(u
, "No matching netlink socket found: %s", value
);
2798 } else if (streq(key
, "ffs")) {
2799 _cleanup_free_
char *fdv
= NULL
;
2803 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2805 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2810 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2811 log_unit_debug(u
, "Invalid ffs value: %s", fdv
);
2815 LIST_FOREACH(port
, p
, s
->ports
)
2817 p
->type
== SOCKET_USB_FUNCTION
&&
2818 path_equal_or_inode_same(p
->path
, value
, 0)) {
2819 p
->fd
= fdset_remove(fds
, fd
);
2824 log_unit_debug(u
, "No matching ffs socket found: %s", value
);
2826 } else if (streq(key
, "trigger-ratelimit"))
2827 deserialize_ratelimit(&s
->trigger_limit
, key
, value
);
2830 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2835 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2836 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2838 LIST_FOREACH(port
, p
, s
->ports
) {
2841 if (p
->type
!= SOCKET_SOCKET
)
2847 FDSET_FOREACH(fd
, fds
) {
2848 if (socket_address_matches_fd(&p
->address
, fd
)) {
2849 p
->fd
= fdset_remove(fds
, fd
);
2850 s
->deserialized_state
= SOCKET_LISTENING
;
2857 static UnitActiveState
socket_active_state(Unit
*u
) {
2858 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2860 return state_translation_table
[s
->state
];
2863 static const char *socket_sub_state_to_string(Unit
*u
) {
2864 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2866 return socket_state_to_string(s
->state
);
2869 int socket_port_to_address(const SocketPort
*p
, char **ret
) {
2870 _cleanup_free_
char *address
= NULL
;
2877 case SOCKET_SOCKET
: {
2878 r
= socket_address_print(&p
->address
, &address
);
2885 case SOCKET_SPECIAL
:
2888 case SOCKET_USB_FUNCTION
:
2889 address
= strdup(p
->path
);
2895 assert_not_reached();
2898 *ret
= TAKE_PTR(address
);
2903 const char* socket_port_type_to_string(SocketPort
*p
) {
2910 switch (p
->address
.type
) {
2918 case SOCK_SEQPACKET
:
2919 return "SequentialPacket";
2922 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2930 case SOCKET_SPECIAL
:
2934 return "MessageQueue";
2939 case SOCKET_USB_FUNCTION
:
2940 return "USBFunction";
2947 SocketType
socket_port_type_from_string(const char *s
) {
2950 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2951 return SOCKET_SOCKET
;
2952 else if (streq(s
, "Special"))
2953 return SOCKET_SPECIAL
;
2954 else if (streq(s
, "MessageQueue"))
2955 return SOCKET_MQUEUE
;
2956 else if (streq(s
, "FIFO"))
2958 else if (streq(s
, "USBFunction"))
2959 return SOCKET_USB_FUNCTION
;
2961 return _SOCKET_TYPE_INVALID
;
2964 static bool socket_may_gc(Unit
*u
) {
2965 Socket
*s
= ASSERT_PTR(SOCKET(u
));
2967 return s
->n_connections
== 0;
2970 static int socket_accept_do(Socket
*s
, int fd
) {
2976 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2978 /* Convert transient network errors into clean and well-defined EAGAIN */
2979 return ERRNO_IS_ACCEPT_AGAIN(errno
) ? -EAGAIN
: -errno
;
2984 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2985 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
2986 _cleanup_close_pair_
int pair
[2] = EBADF_PAIR
;
2993 /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
2994 * connection socket is also properly associated with the cgroup. */
2996 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2999 r
= bpf_firewall_supported();
3002 if (r
== BPF_FIREWALL_UNSUPPORTED
)
3005 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
3006 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
3008 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
3010 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
3014 pair
[0] = safe_close(pair
[0]);
3016 cfd
= socket_accept_do(s
, fd
);
3017 if (cfd
== -EAGAIN
) /* spurious accept() */
3018 _exit(EXIT_SUCCESS
);
3020 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3021 _exit(EXIT_FAILURE
);
3024 r
= send_one_fd(pair
[1], cfd
, 0);
3026 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
3027 _exit(EXIT_FAILURE
);
3030 _exit(EXIT_SUCCESS
);
3033 pair
[1] = safe_close(pair
[1]);
3034 cfd
= receive_one_fd(pair
[0], 0);
3036 /* We synchronously wait for the helper, as it shouldn't be slow */
3037 r
= wait_for_terminate_and_check("(sd-accept)", pid
.pid
, WAIT_LOG_ABNORMAL
);
3043 /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3044 * this is a spurious accept(), let's convert that back to EAGAIN here. */
3048 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
3053 cfd
= socket_accept_do(s
, fd
);
3054 if (cfd
== -EAGAIN
) /* spurious accept(), skip it silently */
3057 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3062 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3063 SocketPort
*p
= ASSERT_PTR(userdata
);
3068 if (p
->socket
->state
!= SOCKET_LISTENING
)
3071 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
3073 if (revents
!= EPOLLIN
) {
3074 if (revents
& EPOLLHUP
)
3075 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.");
3077 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
3081 if (p
->socket
->accept
&&
3082 p
->type
== SOCKET_SOCKET
&&
3083 socket_address_can_accept(&p
->address
)) {
3085 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
3086 if (cfd
== -EAGAIN
) /* Spurious accept() */
3091 socket_apply_socket_options(p
->socket
, p
, cfd
);
3094 socket_enter_running(p
->socket
, cfd
);
3098 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
3102 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3103 Socket
*s
= ASSERT_PTR(SOCKET(u
));
3108 if (pid
!= s
->control_pid
.pid
)
3111 pidref_done(&s
->control_pid
);
3113 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
3115 else if (code
== CLD_EXITED
)
3116 f
= SOCKET_FAILURE_EXIT_CODE
;
3117 else if (code
== CLD_KILLED
)
3118 f
= SOCKET_FAILURE_SIGNAL
;
3119 else if (code
== CLD_DUMPED
)
3120 f
= SOCKET_FAILURE_CORE_DUMP
;
3122 assert_not_reached();
3124 if (s
->control_command
) {
3125 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3127 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3131 unit_log_process_exit(
3134 socket_exec_command_to_string(s
->control_command_id
),
3135 f
== SOCKET_SUCCESS
,
3138 if (s
->result
== SOCKET_SUCCESS
)
3141 if (s
->control_command
&&
3142 s
->control_command
->command_next
&&
3143 f
== SOCKET_SUCCESS
) {
3145 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
3148 s
->control_command
= NULL
;
3149 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3151 /* No further commands for this step, so let's figure
3152 * out what to do next */
3154 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
3158 case SOCKET_START_PRE
:
3159 if (f
== SOCKET_SUCCESS
)
3160 socket_enter_start_chown(s
);
3162 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3165 case SOCKET_START_CHOWN
:
3166 if (f
== SOCKET_SUCCESS
)
3167 socket_enter_start_post(s
);
3169 socket_enter_stop_pre(s
, f
);
3172 case SOCKET_START_POST
:
3173 if (f
== SOCKET_SUCCESS
)
3174 socket_enter_listening(s
);
3176 socket_enter_stop_pre(s
, f
);
3179 case SOCKET_STOP_PRE
:
3180 case SOCKET_STOP_PRE_SIGTERM
:
3181 case SOCKET_STOP_PRE_SIGKILL
:
3182 socket_enter_stop_post(s
, f
);
3185 case SOCKET_STOP_POST
:
3186 case SOCKET_FINAL_SIGTERM
:
3187 case SOCKET_FINAL_SIGKILL
:
3188 socket_enter_dead(s
, f
);
3191 case SOCKET_CLEANING
:
3193 if (s
->clean_result
== SOCKET_SUCCESS
)
3194 s
->clean_result
= f
;
3196 socket_enter_dead(s
, SOCKET_SUCCESS
);
3200 assert_not_reached();
3204 /* Notify clients about changed exit status */
3205 unit_add_to_dbus_queue(u
);
3208 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3209 Socket
*s
= ASSERT_PTR(SOCKET(userdata
));
3211 assert(s
->timer_event_source
== source
);
3215 case SOCKET_START_PRE
:
3216 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3217 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3220 case SOCKET_START_CHOWN
:
3221 case SOCKET_START_POST
:
3222 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3223 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3226 case SOCKET_STOP_PRE
:
3227 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3228 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3231 case SOCKET_STOP_PRE_SIGTERM
:
3232 if (s
->kill_context
.send_sigkill
) {
3233 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3234 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3236 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3237 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3241 case SOCKET_STOP_PRE_SIGKILL
:
3242 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3243 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3246 case SOCKET_STOP_POST
:
3247 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3248 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3251 case SOCKET_FINAL_SIGTERM
:
3252 if (s
->kill_context
.send_sigkill
) {
3253 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3254 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3256 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3257 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3261 case SOCKET_FINAL_SIGKILL
:
3262 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3263 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3266 case SOCKET_CLEANING
:
3267 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
3269 if (s
->clean_result
== SOCKET_SUCCESS
)
3270 s
->clean_result
= SOCKET_FAILURE_TIMEOUT
;
3272 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, 0);
3276 assert_not_reached();
3282 int socket_collect_fds(Socket
*s
, int **ret
) {
3283 size_t n
= 0, k
= 0;
3288 /* Called from the service code for requesting our fds */
3290 LIST_FOREACH(port
, p
, s
->ports
) {
3293 n
+= p
->n_auxiliary_fds
;
3301 int *fds
= new(int, n
);
3305 LIST_FOREACH(port
, p
, s
->ports
) {
3308 FOREACH_ARRAY(i
, p
->auxiliary_fds
, p
->n_auxiliary_fds
)
3318 static void socket_reset_failed(Unit
*u
) {
3319 Socket
*s
= SOCKET(u
);
3323 if (s
->state
== SOCKET_FAILED
)
3324 socket_set_state(s
, SOCKET_DEAD
);
3326 s
->result
= SOCKET_SUCCESS
;
3327 s
->clean_result
= SOCKET_SUCCESS
;
3330 void socket_connection_unref(Socket
*s
) {
3333 /* The service is dead. Yay!
3335 * This is strictly for one-instance-per-connection
3338 assert(s
->n_connections
> 0);
3341 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3344 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3345 Socket
*s
= ASSERT_PTR(SOCKET(u
));
3349 /* Filter out invocations with bogus state */
3350 assert(UNIT_IS_LOAD_COMPLETE(other
->load_state
));
3351 assert(other
->type
== UNIT_SERVICE
);
3353 /* Don't propagate state changes from the service if we are already down */
3354 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3357 /* We don't care for the service state if we are in Accept=yes mode */
3361 /* Propagate start limit hit state */
3362 if (other
->start_limit_hit
) {
3363 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3367 /* Don't propagate anything if there's still a job queued */
3371 if (IN_SET(SERVICE(other
)->state
,
3372 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
3373 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3374 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
3375 socket_enter_listening(s
);
3377 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3378 socket_set_state(s
, SOCKET_RUNNING
);
3381 static void socket_handoff_timestamp(
3383 const struct ucred
*ucred
,
3384 const dual_timestamp
*ts
) {
3386 Socket
*s
= ASSERT_PTR(SOCKET(u
));
3391 if (s
->control_pid
.pid
== ucred
->pid
&& s
->control_command
) {
3392 exec_status_handoff(&s
->control_command
->exec_status
, ucred
, ts
);
3393 unit_add_to_dbus_queue(u
);
3397 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3398 Socket
*s
= ASSERT_PTR(SOCKET(u
));
3402 if (!s
->timer_event_source
)
3405 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3408 if (t
== USEC_INFINITY
)
3415 char *socket_fdname(Socket
*s
) {
3418 /* Returns the name to use for $LISTEN_NAMES. If the user
3419 * didn't specify anything specifically, use the socket unit's
3420 * name as fallback. */
3422 return s
->fdname
?: UNIT(s
)->id
;
3425 static PidRef
*socket_control_pid(Unit
*u
) {
3426 return &ASSERT_PTR(SOCKET(u
))->control_pid
;
3429 static int socket_clean(Unit
*u
, ExecCleanMask mask
) {
3430 Socket
*s
= ASSERT_PTR(SOCKET(u
));
3431 _cleanup_strv_free_
char **l
= NULL
;
3436 if (s
->state
!= SOCKET_DEAD
)
3439 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
3443 if (strv_isempty(l
))
3446 socket_unwatch_control_pid(s
);
3447 s
->clean_result
= SOCKET_SUCCESS
;
3448 s
->control_command
= NULL
;
3449 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3451 r
= socket_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
3453 log_unit_warning_errno(u
, r
, "Failed to install timer: %m");
3457 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
3459 log_unit_warning_errno(u
, r
, "Failed to spawn cleaning task: %m");
3463 socket_set_state(s
, SOCKET_CLEANING
);
3467 s
->clean_result
= SOCKET_FAILURE_RESOURCES
;
3468 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
3472 static int socket_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
3473 Socket
*s
= ASSERT_PTR(SOCKET(u
));
3475 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
3478 static int socket_can_start(Unit
*u
) {
3479 Socket
*s
= ASSERT_PTR(SOCKET(u
));
3482 r
= unit_test_start_limit(u
);
3484 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
3491 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3492 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3493 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3494 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3495 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3496 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost",
3499 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3501 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3502 [SOCKET_SUCCESS
] = "success",
3503 [SOCKET_FAILURE_RESOURCES
] = "resources",
3504 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3505 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3506 [SOCKET_FAILURE_SIGNAL
] = "signal",
3507 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3508 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3509 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3510 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit",
3513 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3515 static const char* const socket_timestamping_table
[_SOCKET_TIMESTAMPING_MAX
] = {
3516 [SOCKET_TIMESTAMPING_OFF
] = "off",
3517 [SOCKET_TIMESTAMPING_US
] = "us",
3518 [SOCKET_TIMESTAMPING_NS
] = "ns",
3521 DEFINE_STRING_TABLE_LOOKUP(socket_timestamping
, SocketTimestamping
);
3523 SocketTimestamping
socket_timestamping_from_string_harder(const char *p
) {
3524 SocketTimestamping t
;
3528 return _SOCKET_TIMESTAMPING_INVALID
;
3530 t
= socket_timestamping_from_string(p
);
3534 /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3536 if (streq(p
, "nsec"))
3537 return SOCKET_TIMESTAMPING_NS
;
3538 if (STR_IN_SET(p
, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
3539 return SOCKET_TIMESTAMPING_US
;
3541 r
= parse_boolean(p
);
3543 return _SOCKET_TIMESTAMPING_INVALID
;
3545 return r
? SOCKET_TIMESTAMPING_NS
: SOCKET_TIMESTAMPING_OFF
; /* If boolean yes, default to ns accuracy */
3548 const UnitVTable socket_vtable
= {
3549 .object_size
= sizeof(Socket
),
3550 .exec_context_offset
= offsetof(Socket
, exec_context
),
3551 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3552 .kill_context_offset
= offsetof(Socket
, kill_context
),
3553 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3554 .cgroup_runtime_offset
= offsetof(Socket
, cgroup_runtime
),
3560 .private_section
= "Socket",
3562 .can_transient
= true,
3563 .can_trigger
= true,
3566 .init
= socket_init
,
3567 .done
= socket_done
,
3568 .load
= socket_load
,
3570 .coldplug
= socket_coldplug
,
3572 .dump
= socket_dump
,
3574 .start
= socket_start
,
3575 .stop
= socket_stop
,
3577 .clean
= socket_clean
,
3578 .can_clean
= socket_can_clean
,
3580 .get_timeout
= socket_get_timeout
,
3582 .serialize
= socket_serialize
,
3583 .deserialize_item
= socket_deserialize_item
,
3584 .distribute_fds
= socket_distribute_fds
,
3586 .active_state
= socket_active_state
,
3587 .sub_state_to_string
= socket_sub_state_to_string
,
3589 .will_restart
= unit_will_restart_default
,
3591 .may_gc
= socket_may_gc
,
3593 .sigchld_event
= socket_sigchld_event
,
3595 .trigger_notify
= socket_trigger_notify
,
3597 .reset_failed
= socket_reset_failed
,
3599 .notify_handoff_timestamp
= socket_handoff_timestamp
,
3601 .control_pid
= socket_control_pid
,
3603 .bus_set_property
= bus_socket_set_property
,
3604 .bus_commit_properties
= bus_socket_commit_properties
,
3606 .status_message_formats
= {
3607 .finished_start_job
= {
3608 [JOB_DONE
] = "Listening on %s.",
3609 [JOB_FAILED
] = "Failed to listen on %s.",
3610 [JOB_TIMEOUT
] = "Timed out starting %s.",
3612 .finished_stop_job
= {
3613 [JOB_DONE
] = "Closed %s.",
3614 [JOB_FAILED
] = "Failed stopping %s.",
3615 [JOB_TIMEOUT
] = "Timed out stopping %s.",
3619 .can_start
= socket_can_start
,