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
;
58 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
59 [SOCKET_DEAD
] = UNIT_INACTIVE
,
60 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
61 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
62 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
63 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
64 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
65 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
66 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
67 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
68 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
69 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
70 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
71 [SOCKET_FAILED
] = UNIT_FAILED
,
72 [SOCKET_CLEANING
] = UNIT_MAINTENANCE
,
75 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
76 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
77 static void flush_ports(Socket
*s
);
79 static void socket_init(Unit
*u
) {
80 Socket
*s
= SOCKET(u
);
83 assert(u
->load_state
== UNIT_STUB
);
85 s
->backlog
= SOMAXCONN_DELUXE
;
86 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
87 s
->directory_mode
= 0755;
88 s
->socket_mode
= 0666;
90 s
->max_connections
= 64;
97 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
98 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
100 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
102 s
->trigger_limit
.interval
= USEC_INFINITY
;
103 s
->trigger_limit
.burst
= UINT_MAX
;
106 static void socket_unwatch_control_pid(Socket
*s
) {
109 if (s
->control_pid
<= 0)
112 unit_unwatch_pid(UNIT(s
), TAKE_PID(s
->control_pid
));
115 static void socket_cleanup_fd_list(SocketPort
*p
) {
118 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
119 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
120 p
->n_auxiliary_fds
= 0;
123 SocketPort
*socket_port_free(SocketPort
*p
) {
127 sd_event_source_unref(p
->event_source
);
129 socket_cleanup_fd_list(p
);
136 void socket_free_ports(Socket
*s
) {
139 LIST_CLEAR(port
, s
->ports
, socket_port_free
);
142 static void socket_done(Unit
*u
) {
143 Socket
*s
= SOCKET(u
);
148 socket_free_ports(s
);
150 while ((p
= set_steal_first(s
->peers_by_address
)))
153 s
->peers_by_address
= set_free(s
->peers_by_address
);
155 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
156 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
157 s
->control_command
= NULL
;
159 socket_unwatch_control_pid(s
);
161 unit_ref_unset(&s
->service
);
163 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
164 s
->bind_to_device
= mfree(s
->bind_to_device
);
166 s
->smack
= mfree(s
->smack
);
167 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
168 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
170 strv_free(s
->symlinks
);
172 s
->user
= mfree(s
->user
);
173 s
->group
= mfree(s
->group
);
175 s
->fdname
= mfree(s
->fdname
);
177 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
180 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
185 if (s
->timer_event_source
) {
186 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
190 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
193 if (usec
== USEC_INFINITY
)
196 r
= sd_event_add_time(
197 UNIT(s
)->manager
->event
,
198 &s
->timer_event_source
,
201 socket_dispatch_timer
, s
);
205 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
210 static bool have_non_accept_socket(Socket
*s
) {
216 LIST_FOREACH(port
, p
, s
->ports
) {
218 if (p
->type
!= SOCKET_SOCKET
)
221 if (!socket_address_can_accept(&p
->address
))
228 static int socket_add_mount_dependencies(Socket
*s
) {
233 LIST_FOREACH(port
, p
, s
->ports
) {
234 const char *path
= NULL
;
236 if (p
->type
== SOCKET_SOCKET
)
237 path
= socket_address_get_path(&p
->address
);
238 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
244 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
252 static int socket_add_device_dependencies(Socket
*s
) {
257 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
260 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
261 return unit_add_node_dependency(UNIT(s
), t
, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
264 static int socket_add_default_dependencies(Socket
*s
) {
268 if (!UNIT(s
)->default_dependencies
)
271 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
275 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
276 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
281 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
284 static bool socket_has_exec(Socket
*s
) {
288 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
289 if (s
->exec_command
[i
])
295 static int socket_add_extras(Socket
*s
) {
301 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
302 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
303 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
304 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
305 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
306 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
307 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
308 * service starts are typical. */
310 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
311 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
313 if (s
->trigger_limit
.burst
== UINT_MAX
) {
315 s
->trigger_limit
.burst
= 200;
317 s
->trigger_limit
.burst
= 20;
320 if (have_non_accept_socket(s
)) {
322 if (!UNIT_DEREF(s
->service
)) {
325 r
= unit_load_related_unit(u
, ".service", &x
);
329 unit_ref_set(&s
->service
, u
, x
);
332 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
337 r
= socket_add_mount_dependencies(s
);
341 r
= socket_add_device_dependencies(s
);
345 r
= unit_patch_contexts(u
);
349 if (socket_has_exec(s
)) {
350 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
355 r
= unit_set_default_slice(u
);
359 r
= socket_add_default_dependencies(s
);
366 static const char *socket_find_symlink_target(Socket
*s
) {
367 const char *found
= NULL
;
369 LIST_FOREACH(port
, p
, s
->ports
) {
370 const char *f
= NULL
;
379 f
= socket_address_get_path(&p
->address
);
397 static int socket_verify(Socket
*s
) {
399 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
402 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
404 if (s
->accept
&& have_non_accept_socket(s
))
405 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
407 if (s
->accept
&& s
->max_connections
<= 0)
408 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "MaxConnection= setting too small. Refusing.");
410 if (s
->accept
&& UNIT_DEREF(s
->service
))
411 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Explicit service configuration for accepting socket units not supported. Refusing.");
413 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
)
414 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
416 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
))
417 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.");
422 static void peer_address_hash_func(const SocketPeer
*s
, struct siphash
*state
) {
425 if (s
->peer
.sa
.sa_family
== AF_INET
)
426 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
427 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
428 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
429 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
430 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
432 assert_not_reached();
435 static int peer_address_compare_func(const SocketPeer
*x
, const SocketPeer
*y
) {
438 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
442 switch (x
->peer
.sa
.sa_family
) {
444 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
446 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
448 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
450 assert_not_reached();
453 DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops
, SocketPeer
, peer_address_hash_func
, peer_address_compare_func
);
455 static int socket_load(Unit
*u
) {
456 Socket
*s
= SOCKET(u
);
460 assert(u
->load_state
== UNIT_STUB
);
462 r
= unit_load_fragment_and_dropin(u
, true);
466 if (u
->load_state
!= UNIT_LOADED
)
469 /* This is a new unit? Then let's add in some extras */
470 r
= socket_add_extras(s
);
474 return socket_verify(s
);
477 static SocketPeer
*socket_peer_new(void) {
480 p
= new(SocketPeer
, 1);
490 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
494 set_remove(p
->socket
->peers_by_address
, p
);
499 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
501 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
502 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
504 .peer_salen
= sizeof(union sockaddr_union
),
511 if (getpeername(fd
, &sa
.peer
.sa
, &sa
.peer_salen
) < 0)
512 return log_unit_error_errno(UNIT(s
), errno
, "getpeername failed: %m");
514 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
519 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
523 i
= set_get(s
->peers_by_address
, &sa
);
525 *p
= socket_peer_ref(i
);
529 remote
= socket_peer_new();
533 remote
->peer
= sa
.peer
;
534 remote
->peer_salen
= sa
.peer_salen
;
536 r
= set_put(s
->peers_by_address
, remote
);
542 *p
= TAKE_PTR(remote
);
546 static const char* listen_lookup(int family
, int type
) {
548 if (family
== AF_NETLINK
)
549 return "ListenNetlink";
551 if (type
== SOCK_STREAM
)
552 return "ListenStream";
553 else if (type
== SOCK_DGRAM
)
554 return "ListenDatagram";
555 else if (type
== SOCK_SEQPACKET
)
556 return "ListenSequentialPacket";
558 assert_not_reached();
562 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
563 Socket
*s
= SOCKET(u
);
564 const char *prefix2
, *str
;
569 prefix
= strempty(prefix
);
570 prefix2
= strjoina(prefix
, "\t");
573 "%sSocket State: %s\n"
575 "%sClean Result: %s\n"
576 "%sBindIPv6Only: %s\n"
578 "%sSocketMode: %04o\n"
579 "%sDirectoryMode: %04o\n"
583 "%sTransparent: %s\n"
585 "%sPassCredentials: %s\n"
586 "%sPassSecurity: %s\n"
587 "%sPassPacketInfo: %s\n"
588 "%sTCPCongestion: %s\n"
589 "%sRemoveOnStop: %s\n"
591 "%sFileDescriptorName: %s\n"
592 "%sSELinuxContextFromNet: %s\n",
593 prefix
, socket_state_to_string(s
->state
),
594 prefix
, socket_result_to_string(s
->result
),
595 prefix
, socket_result_to_string(s
->clean_result
),
596 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
598 prefix
, s
->socket_mode
,
599 prefix
, s
->directory_mode
,
600 prefix
, yes_no(s
->keep_alive
),
601 prefix
, yes_no(s
->no_delay
),
602 prefix
, yes_no(s
->free_bind
),
603 prefix
, yes_no(s
->transparent
),
604 prefix
, yes_no(s
->broadcast
),
605 prefix
, yes_no(s
->pass_cred
),
606 prefix
, yes_no(s
->pass_sec
),
607 prefix
, yes_no(s
->pass_pktinfo
),
608 prefix
, strna(s
->tcp_congestion
),
609 prefix
, yes_no(s
->remove_on_stop
),
610 prefix
, yes_no(s
->writable
),
611 prefix
, socket_fdname(s
),
612 prefix
, yes_no(s
->selinux_context_from_net
));
614 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
)
616 "%sTimestamping: %s\n",
617 prefix
, socket_timestamping_to_string(s
->timestamping
));
619 if (s
->control_pid
> 0)
621 "%sControl PID: "PID_FMT
"\n",
622 prefix
, s
->control_pid
);
624 if (s
->bind_to_device
)
626 "%sBindToDevice: %s\n",
627 prefix
, s
->bind_to_device
);
632 "%sNConnections: %u\n"
633 "%sMaxConnections: %u\n"
634 "%sMaxConnectionsPerSource: %u\n",
635 prefix
, s
->n_accepted
,
636 prefix
, s
->n_connections
,
637 prefix
, s
->max_connections
,
638 prefix
, s
->max_connections_per_source
);
641 "%sFlushPending: %s\n",
642 prefix
, yes_no(s
->flush_pending
));
645 if (s
->priority
>= 0)
648 prefix
, s
->priority
);
650 if (s
->receive_buffer
> 0)
652 "%sReceiveBuffer: %zu\n",
653 prefix
, s
->receive_buffer
);
655 if (s
->send_buffer
> 0)
657 "%sSendBuffer: %zu\n",
658 prefix
, s
->send_buffer
);
670 if (s
->pipe_size
> 0)
673 prefix
, s
->pipe_size
);
680 if (s
->mq_maxmsg
> 0)
682 "%sMessageQueueMaxMessages: %li\n",
683 prefix
, s
->mq_maxmsg
);
685 if (s
->mq_msgsize
> 0)
687 "%sMessageQueueMessageSize: %li\n",
688 prefix
, s
->mq_msgsize
);
693 prefix
, yes_no(s
->reuse_port
));
697 "%sSmackLabel: %s\n",
702 "%sSmackLabelIPIn: %s\n",
703 prefix
, s
->smack_ip_in
);
707 "%sSmackLabelIPOut: %s\n",
708 prefix
, s
->smack_ip_out
);
710 if (!isempty(s
->user
) || !isempty(s
->group
))
713 "%sSocketGroup: %s\n",
714 prefix
, strna(s
->user
),
715 prefix
, strna(s
->group
));
717 if (timestamp_is_set(s
->keep_alive_time
))
719 "%sKeepAliveTimeSec: %s\n",
720 prefix
, FORMAT_TIMESPAN(s
->keep_alive_time
, USEC_PER_SEC
));
722 if (s
->keep_alive_interval
> 0)
724 "%sKeepAliveIntervalSec: %s\n",
725 prefix
, FORMAT_TIMESPAN(s
->keep_alive_interval
, USEC_PER_SEC
));
727 if (s
->keep_alive_cnt
> 0)
729 "%sKeepAliveProbes: %u\n",
730 prefix
, s
->keep_alive_cnt
);
732 if (s
->defer_accept
> 0)
734 "%sDeferAcceptSec: %s\n",
735 prefix
, FORMAT_TIMESPAN(s
->defer_accept
, USEC_PER_SEC
));
737 LIST_FOREACH(port
, p
, s
->ports
) {
740 case SOCKET_SOCKET
: {
741 _cleanup_free_
char *k
= NULL
;
744 r
= socket_address_print(&p
->address
, &k
);
747 fprintf(f
, "%s%s: %m\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
));
749 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), k
);
753 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
755 case SOCKET_USB_FUNCTION
:
756 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
759 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
762 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
767 "%sTriggerLimitIntervalSec: %s\n"
768 "%sTriggerLimitBurst: %u\n",
769 prefix
, FORMAT_TIMESPAN(s
->trigger_limit
.interval
, USEC_PER_SEC
),
770 prefix
, s
->trigger_limit
.burst
);
772 str
= ip_protocol_to_name(s
->socket_protocol
);
774 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
776 if (!strv_isempty(s
->symlinks
)) {
777 fprintf(f
, "%sSymlinks:", prefix
);
778 STRV_FOREACH(q
, s
->symlinks
)
779 fprintf(f
, " %s", *q
);
785 "%sTimeoutSec: %s\n",
786 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
788 exec_context_dump(&s
->exec_context
, f
, prefix
);
789 kill_context_dump(&s
->kill_context
, f
, prefix
);
791 for (SocketExecCommand c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
792 if (!s
->exec_command
[c
])
795 fprintf(f
, "%s-> %s:\n",
796 prefix
, socket_exec_command_to_string(c
));
798 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
801 cgroup_context_dump(UNIT(s
), f
, prefix
);
804 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
807 union sockaddr_union local
, remote
;
813 if (getsockname(fd
, &local
.sa
, &l
) < 0)
817 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
820 switch (local
.sa
.sa_family
) {
824 a
= be32toh(local
.in
.sin_addr
.s_addr
),
825 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
828 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
830 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
831 be16toh(local
.in
.sin_port
),
832 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
833 be16toh(remote
.in
.sin_port
)) < 0)
840 static const unsigned char ipv4_prefix
[] = {
841 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
844 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
845 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
847 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
848 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
851 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
853 a
[0], a
[1], a
[2], a
[3],
854 be16toh(local
.in6
.sin6_port
),
855 b
[0], b
[1], b
[2], b
[3],
856 be16toh(remote
.in6
.sin6_port
)) < 0)
862 IN6_ADDR_TO_STRING(&local
.in6
.sin6_addr
),
863 be16toh(local
.in6
.sin6_port
),
864 IN6_ADDR_TO_STRING(&remote
.in6
.sin6_addr
),
865 be16toh(remote
.in6
.sin6_port
)) < 0)
876 k
= getpeercred(fd
, &ucred
);
879 "%u-"PID_FMT
"-"UID_FMT
,
880 nr
, ucred
.pid
, ucred
.uid
) < 0)
882 } else if (k
== -ENODATA
) {
883 /* This handles the case where somebody is
884 * connecting from another pid/uid namespace
885 * (e.g. from outside of our container). */
900 local
.vm
.svm_cid
, local
.vm
.svm_port
,
901 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
907 assert_not_reached();
914 static void socket_close_fds(Socket
*s
) {
917 LIST_FOREACH(port
, p
, s
->ports
) {
920 was_open
= p
->fd
>= 0;
922 p
->event_source
= sd_event_source_disable_unref(p
->event_source
);
923 p
->fd
= safe_close(p
->fd
);
924 socket_cleanup_fd_list(p
);
926 /* One little note: we should normally not delete any sockets in the file system here! After all some
927 * other process we spawned might still have a reference of this fd and wants to continue to use
928 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
929 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
930 * anyway, but only then. */
932 if (!was_open
|| !s
->remove_on_stop
)
938 (void) unlink(p
->path
);
942 (void) mq_unlink(p
->path
);
946 (void) socket_address_unlink(&p
->address
);
954 if (s
->remove_on_stop
)
955 STRV_FOREACH(i
, s
->symlinks
)
958 /* Note that we don't return NULL here, since s has not been freed. */
961 static void socket_apply_socket_options(Socket
*s
, SocketPort
*p
, int fd
) {
969 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
971 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
974 if (timestamp_is_set(s
->keep_alive_time
)) {
975 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
977 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
980 if (s
->keep_alive_interval
> 0) {
981 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
983 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
986 if (s
->keep_alive_cnt
> 0) {
987 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
989 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
992 if (s
->defer_accept
> 0) {
993 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
995 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
999 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1000 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1002 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1004 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1006 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1011 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1013 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1017 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1019 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1023 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1025 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1028 if (s
->pass_pktinfo
) {
1029 r
= socket_set_recvpktinfo(fd
, socket_address_family(&p
->address
), true);
1031 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable packet info socket option: %m");
1034 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
) {
1035 r
= setsockopt_int(fd
, SOL_SOCKET
,
1036 s
->timestamping
== SOCKET_TIMESTAMPING_NS
? SO_TIMESTAMPNS
: SO_TIMESTAMP
,
1039 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable timestamping socket option, ignoring: %m");
1042 if (s
->priority
>= 0) {
1043 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1045 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1048 if (s
->receive_buffer
> 0) {
1049 r
= fd_set_rcvbuf(fd
, s
->receive_buffer
, false);
1051 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1052 "SO_RCVBUF/SO_RCVBUFFORCE failed: %m");
1055 if (s
->send_buffer
> 0) {
1056 r
= fd_set_sndbuf(fd
, s
->send_buffer
, false);
1058 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1059 "SO_SNDBUF/SO_SNDBUFFORCE failed: %m");
1063 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1065 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1068 if (s
->ip_tos
>= 0) {
1069 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1071 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1074 if (s
->ip_ttl
>= 0) {
1075 r
= socket_set_ttl(fd
, socket_address_family(&p
->address
), s
->ip_ttl
);
1077 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1080 if (s
->tcp_congestion
)
1081 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1082 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1084 if (s
->smack_ip_in
) {
1085 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1087 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1090 if (s
->smack_ip_out
) {
1091 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1093 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1097 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1103 if (s
->pipe_size
> 0)
1104 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1105 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1108 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1110 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1114 static int fifo_address_create(
1116 mode_t directory_mode
,
1117 mode_t socket_mode
) {
1119 _cleanup_close_
int fd
= -EBADF
;
1126 (void) mkdir_parents_label(path
, directory_mode
);
1128 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1132 /* Enforce the right access mode for the fifo */
1133 old_mask
= umask(~socket_mode
);
1135 /* Include the original umask in our mask */
1136 (void) umask(~socket_mode
| old_mask
);
1138 r
= mkfifo(path
, socket_mode
);
1139 (void) umask(old_mask
);
1141 if (r
< 0 && errno
!= EEXIST
) {
1146 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1152 mac_selinux_create_file_clear();
1154 if (fstat(fd
, &st
) < 0) {
1159 if (!S_ISFIFO(st
.st_mode
) ||
1160 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1161 st
.st_uid
!= getuid() ||
1162 st
.st_gid
!= getgid()) {
1170 mac_selinux_create_file_clear();
1174 static int special_address_create(const char *path
, bool writable
) {
1175 _cleanup_close_
int fd
= -EBADF
;
1180 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1184 if (fstat(fd
, &st
) < 0)
1187 /* Check whether this is a /proc, /sys or /dev file or char device */
1188 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1194 static int usbffs_address_create(const char *path
) {
1195 _cleanup_close_
int fd
= -EBADF
;
1200 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1204 if (fstat(fd
, &st
) < 0)
1207 /* Check whether this is a regular file (ffs endpoint) */
1208 if (!S_ISREG(st
.st_mode
))
1214 static int mq_address_create(
1220 _cleanup_close_
int fd
= -EBADF
;
1223 struct mq_attr _attr
, *attr
= NULL
;
1227 if (maxmsg
> 0 && msgsize
> 0) {
1228 _attr
= (struct mq_attr
) {
1229 .mq_flags
= O_NONBLOCK
,
1230 .mq_maxmsg
= maxmsg
,
1231 .mq_msgsize
= msgsize
,
1236 /* Enforce the right access mode for the mq */
1237 old_mask
= umask(~mq_mode
);
1239 /* Include the original umask in our mask */
1240 (void) umask(~mq_mode
| old_mask
);
1241 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1242 (void) umask(old_mask
);
1247 if (fstat(fd
, &st
) < 0)
1250 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1251 st
.st_uid
!= getuid() ||
1252 st
.st_gid
!= getgid())
1258 static int socket_symlink(Socket
*s
) {
1264 p
= socket_find_symlink_target(s
);
1268 STRV_FOREACH(i
, s
->symlinks
) {
1269 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1271 r
= symlink_idempotent(p
, *i
, false);
1273 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1274 /* If there's already something where we want to create the symlink, and the destructive
1275 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1278 if (unlink(*i
) >= 0)
1279 r
= symlink_idempotent(p
, *i
, false);
1283 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s %s %s, ignoring: %m",
1284 p
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *i
);
1290 static int usbffs_write_descs(int fd
, Service
*s
) {
1293 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1296 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1300 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1303 static int usbffs_select_ep(const struct dirent
*d
) {
1304 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1307 static int usbffs_dispatch_eps(SocketPort
*p
) {
1308 _cleanup_free_
struct dirent
**ent
= NULL
;
1312 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1317 p
->auxiliary_fds
= new(int, n
);
1318 if (!p
->auxiliary_fds
) {
1323 p
->n_auxiliary_fds
= n
;
1326 for (size_t i
= 0; i
< n
; ++i
) {
1327 _cleanup_free_
char *ep
= NULL
;
1329 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1337 r
= usbffs_address_create(ep
);
1341 p
->auxiliary_fds
[k
++] = r
;
1348 close_many(p
->auxiliary_fds
, k
);
1349 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1350 p
->n_auxiliary_fds
= 0;
1353 free_many((void**) ent
, n
);
1357 int socket_load_service_unit(Socket
*s
, int cfd
, Unit
**ret
) {
1358 /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1360 * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1364 if (UNIT_ISSET(s
->service
)) {
1365 *ret
= UNIT_DEREF(s
->service
);
1372 /* Build the instance name and load the unit */
1373 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
1376 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
1381 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
1383 if (ERRNO_IS_DISCONNECT(r
))
1384 /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1385 * different errors. This connection is over, but the socket unit lives on. */
1386 return log_unit_debug_errno(UNIT(s
), r
,
1387 "Got %s on incoming socket, assuming aborted connection attempt, ignoring.",
1393 /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1394 * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1395 * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1396 r
= unit_name_build(prefix
, instance
?: "internal", ".service", &name
);
1400 return manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, ret
);
1403 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1411 const char *exec_context
;
1412 _cleanup_free_
char *path
= NULL
;
1414 r
= socket_load_service_unit(s
, -1, &service
);
1420 exec_context
= SERVICE(service
)->exec_context
.selinux_context
;
1424 con
= strdup(exec_context
);
1428 *ret
= TAKE_PTR(con
);
1432 c
= SERVICE(service
)->exec_command
[SERVICE_EXEC_START
];
1436 r
= chase(c
->path
, SERVICE(service
)->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
, NULL
);
1440 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1441 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1450 static int socket_address_listen_do(
1452 const SocketAddress
*address
,
1453 const char *label
) {
1458 return socket_address_listen(
1460 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1472 #define log_address_error_errno(u, address, error, fmt) \
1474 _cleanup_free_ char *_t = NULL; \
1476 (void) socket_address_print(address, &_t); \
1477 log_unit_error_errno(u, error, fmt, strna(_t)); \
1480 static int fork_needed(const SocketAddress
*address
, const ExecContext
*context
) {
1486 /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1488 if (IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
)) {
1489 r
= bpf_firewall_supported();
1492 if (r
!= BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1496 return exec_needs_network_namespace(context
);
1499 static int socket_address_listen_in_cgroup(
1501 const SocketAddress
*address
,
1502 const char *label
) {
1504 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
1511 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1512 * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1513 * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1516 r
= fork_needed(address
, &s
->exec_context
);
1520 /* Shortcut things... */
1521 fd
= socket_address_listen_do(s
, address
, label
);
1523 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1528 r
= unit_setup_exec_runtime(UNIT(s
));
1530 return log_unit_error_errno(UNIT(s
), r
, "Failed acquire runtime: %m");
1532 if (s
->exec_context
.network_namespace_path
&&
1534 s
->exec_runtime
->shared
&&
1535 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1536 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->netns_storage_socket
, s
->exec_context
.network_namespace_path
, CLONE_NEWNET
);
1538 return log_unit_error_errno(UNIT(s
), r
, "Failed to open network namespace path %s: %m", s
->exec_context
.network_namespace_path
);
1541 if (s
->exec_context
.ipc_namespace_path
&&
1543 s
->exec_runtime
->shared
&&
1544 s
->exec_runtime
->shared
->ipcns_storage_socket
[0] >= 0) {
1545 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->ipcns_storage_socket
, s
->exec_context
.ipc_namespace_path
, CLONE_NEWIPC
);
1547 return log_unit_error_errno(UNIT(s
), r
, "Failed to open IPC namespace path %s: %m", s
->exec_context
.ipc_namespace_path
);
1550 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1551 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1553 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1555 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1559 pair
[0] = safe_close(pair
[0]);
1561 if (exec_needs_network_namespace(&s
->exec_context
) &&
1563 s
->exec_runtime
->shared
&&
1564 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1566 if (ns_type_supported(NAMESPACE_NET
)) {
1567 r
= setup_shareable_ns(s
->exec_runtime
->shared
->netns_storage_socket
, CLONE_NEWNET
);
1569 log_unit_error_errno(UNIT(s
), r
, "Failed to join network namespace: %m");
1570 _exit(EXIT_NETWORK
);
1572 } else if (s
->exec_context
.network_namespace_path
) {
1573 log_unit_error(UNIT(s
), "Network namespace path configured but network namespaces not supported.");
1574 _exit(EXIT_NETWORK
);
1576 log_unit_warning(UNIT(s
), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
1579 fd
= socket_address_listen_do(s
, address
, label
);
1581 log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1582 _exit(EXIT_FAILURE
);
1585 r
= send_one_fd(pair
[1], fd
, 0);
1587 log_address_error_errno(UNIT(s
), address
, r
, "Failed to send listening socket (%s) to parent: %m");
1588 _exit(EXIT_FAILURE
);
1591 _exit(EXIT_SUCCESS
);
1594 pair
[1] = safe_close(pair
[1]);
1595 fd
= receive_one_fd(pair
[0], 0);
1597 /* We synchronously wait for the helper, as it shouldn't be slow */
1598 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1605 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to receive listening socket (%s): %m");
1610 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket
*, socket_close_fds
, NULL
);
1612 static int socket_open_fds(Socket
*orig_s
) {
1613 _cleanup_(socket_close_fdsp
) Socket
*s
= orig_s
;
1614 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1615 bool know_label
= false;
1620 LIST_FOREACH(port
, p
, s
->ports
) {
1630 /* Figure out the label, if we don't it know yet. We do it once for the first
1631 * socket where we need this and remember it for the rest. */
1633 r
= socket_determine_selinux_label(s
, &label
);
1635 return log_unit_error_errno(UNIT(s
), r
, "Failed to determine SELinux label: %m");
1640 /* Apply the socket protocol */
1641 switch (p
->address
.type
) {
1644 case SOCK_SEQPACKET
:
1645 if (s
->socket_protocol
== IPPROTO_SCTP
)
1646 p
->address
.protocol
= s
->socket_protocol
;
1650 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1651 p
->address
.protocol
= s
->socket_protocol
;
1655 p
->fd
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1659 socket_apply_socket_options(s
, p
, p
->fd
);
1663 case SOCKET_SPECIAL
:
1665 p
->fd
= special_address_create(p
->path
, s
->writable
);
1667 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open special file %s: %m", p
->path
);
1672 p
->fd
= fifo_address_create(
1677 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open FIFO %s: %m", p
->path
);
1679 socket_apply_fifo_options(s
, p
->fd
);
1685 p
->fd
= mq_address_create(
1691 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open message queue %s: %m", p
->path
);
1694 case SOCKET_USB_FUNCTION
: {
1695 _cleanup_free_
char *ep
= NULL
;
1697 ep
= path_make_absolute("ep0", p
->path
);
1701 p
->fd
= usbffs_address_create(ep
);
1705 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1709 r
= usbffs_dispatch_eps(p
);
1716 assert_not_reached();
1724 static void socket_unwatch_fds(Socket
*s
) {
1729 LIST_FOREACH(port
, p
, s
->ports
) {
1733 if (!p
->event_source
)
1736 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1738 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1742 static int socket_watch_fds(Socket
*s
) {
1747 LIST_FOREACH(port
, p
, s
->ports
) {
1751 if (p
->event_source
) {
1752 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1756 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1760 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1767 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1768 socket_unwatch_fds(s
);
1778 static int socket_check_open(Socket
*s
) {
1779 bool have_open
= false, have_closed
= false;
1783 LIST_FOREACH(port
, p
, s
->ports
) {
1789 if (have_open
&& have_closed
)
1790 return SOCKET_OPEN_SOME
;
1794 return SOCKET_OPEN_ALL
;
1796 return SOCKET_OPEN_NONE
;
1799 static void socket_set_state(Socket
*s
, SocketState state
) {
1800 SocketState old_state
;
1803 if (s
->state
!= state
)
1804 bus_unit_send_pending_change_signal(UNIT(s
), false);
1806 old_state
= s
->state
;
1814 SOCKET_STOP_PRE_SIGTERM
,
1815 SOCKET_STOP_PRE_SIGKILL
,
1817 SOCKET_FINAL_SIGTERM
,
1818 SOCKET_FINAL_SIGKILL
,
1821 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1822 socket_unwatch_control_pid(s
);
1823 s
->control_command
= NULL
;
1824 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1827 if (state
!= SOCKET_LISTENING
)
1828 socket_unwatch_fds(s
);
1836 SOCKET_STOP_PRE_SIGTERM
,
1837 SOCKET_STOP_PRE_SIGKILL
,
1839 socket_close_fds(s
);
1841 if (state
!= old_state
)
1842 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1844 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
1847 static int socket_coldplug(Unit
*u
) {
1848 Socket
*s
= SOCKET(u
);
1852 assert(s
->state
== SOCKET_DEAD
);
1854 if (s
->deserialized_state
== s
->state
)
1857 if (s
->control_pid
> 0 &&
1858 pid_is_unwaited(s
->control_pid
) &&
1859 IN_SET(s
->deserialized_state
,
1864 SOCKET_STOP_PRE_SIGTERM
,
1865 SOCKET_STOP_PRE_SIGKILL
,
1867 SOCKET_FINAL_SIGTERM
,
1868 SOCKET_FINAL_SIGKILL
,
1871 r
= unit_watch_pid(UNIT(s
), s
->control_pid
, false);
1875 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1880 if (IN_SET(s
->deserialized_state
,
1886 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1887 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN state for
1888 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1889 * and if there's a mismatch, warn loudly. */
1891 r
= socket_check_open(s
);
1892 if (r
== SOCKET_OPEN_NONE
)
1893 log_unit_warning(UNIT(s
),
1894 "Socket unit configuration has changed while unit has been running, "
1895 "no open socket file descriptor left. "
1896 "The socket unit is not functional until restarted.");
1897 else if (r
== SOCKET_OPEN_SOME
)
1898 log_unit_warning(UNIT(s
),
1899 "Socket unit configuration has changed while unit has been running, "
1900 "and some socket file descriptors have not been opened yet. "
1901 "The socket unit is not fully functional until restarted.");
1904 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1905 r
= socket_watch_fds(s
);
1910 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
, SOCKET_CLEANING
))
1911 (void) unit_setup_exec_runtime(u
);
1913 socket_set_state(s
, s
->deserialized_state
);
1917 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1919 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1920 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1922 .stdout_fd
= -EBADF
,
1923 .stderr_fd
= -EBADF
,
1933 r
= unit_prepare_exec(UNIT(s
));
1937 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1941 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1945 r
= exec_spawn(UNIT(s
),
1955 r
= unit_watch_pid(UNIT(s
), pid
, true);
1964 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1968 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1972 /* We have to resolve the user names out-of-process, hence
1973 * let's fork here. It's messy, but well, what can we do? */
1975 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1979 uid_t uid
= UID_INVALID
;
1980 gid_t gid
= GID_INVALID
;
1984 if (!isempty(s
->user
)) {
1985 const char *user
= s
->user
;
1987 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1989 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1994 if (!isempty(s
->group
)) {
1995 const char *group
= s
->group
;
1997 r
= get_group_creds(&group
, &gid
, 0);
1999 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
2004 LIST_FOREACH(port
, p
, s
->ports
) {
2005 const char *path
= NULL
;
2007 if (p
->type
== SOCKET_SOCKET
)
2008 path
= socket_address_get_path(&p
->address
);
2009 else if (p
->type
== SOCKET_FIFO
)
2015 if (chown(path
, uid
, gid
) < 0) {
2016 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
2021 _exit(EXIT_SUCCESS
);
2024 r
= unit_watch_pid(UNIT(s
), pid
, true);
2032 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
2036 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
2039 if (s
->result
== SOCKET_SUCCESS
)
2042 if (s
->result
== SOCKET_SUCCESS
)
2043 unit_log_success(UNIT(s
));
2045 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
2047 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2049 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
2051 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2053 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2055 unit_unref_uid_gid(UNIT(s
), true);
2058 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2060 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2064 if (s
->result
== SOCKET_SUCCESS
)
2067 socket_unwatch_control_pid(s
);
2068 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2069 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2071 if (s
->control_command
) {
2072 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2076 socket_set_state(s
, SOCKET_STOP_POST
);
2078 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2083 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2084 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2087 static int state_to_kill_operation(Socket
*s
, SocketState state
) {
2088 if (state
== SOCKET_STOP_PRE_SIGTERM
&& unit_has_job_type(UNIT(s
), JOB_RESTART
))
2089 return KILL_RESTART
;
2091 if (state
== SOCKET_FINAL_SIGTERM
)
2092 return KILL_TERMINATE
;
2097 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2102 if (s
->result
== SOCKET_SUCCESS
)
2105 r
= unit_kill_context(
2108 state_to_kill_operation(s
, state
),
2116 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2120 socket_set_state(s
, state
);
2121 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2122 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2123 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2124 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2125 else if (state
== SOCKET_FINAL_SIGTERM
)
2126 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2128 socket_enter_dead(s
, SOCKET_SUCCESS
);
2133 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2135 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2136 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2138 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2141 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2145 if (s
->result
== SOCKET_SUCCESS
)
2148 socket_unwatch_control_pid(s
);
2149 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2150 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2152 if (s
->control_command
) {
2153 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2157 socket_set_state(s
, SOCKET_STOP_PRE
);
2159 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2164 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2165 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2168 static void socket_enter_listening(Socket
*s
) {
2172 if (!s
->accept
&& s
->flush_pending
) {
2173 log_unit_debug(UNIT(s
), "Flushing socket before listening.");
2177 r
= socket_watch_fds(s
);
2179 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2183 socket_set_state(s
, SOCKET_LISTENING
);
2187 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2190 static void socket_enter_start_post(Socket
*s
) {
2194 socket_unwatch_control_pid(s
);
2195 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2196 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2198 if (s
->control_command
) {
2199 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2201 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2205 socket_set_state(s
, SOCKET_START_POST
);
2207 socket_enter_listening(s
);
2212 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2215 static void socket_enter_start_chown(Socket
*s
) {
2220 r
= socket_open_fds(s
);
2222 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2226 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2228 socket_unwatch_control_pid(s
);
2229 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2230 s
->control_command
= NULL
;
2232 r
= socket_chown(s
, &s
->control_pid
);
2234 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2238 socket_set_state(s
, SOCKET_START_CHOWN
);
2240 socket_enter_start_post(s
);
2245 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2248 static void socket_enter_start_pre(Socket
*s
) {
2252 socket_unwatch_control_pid(s
);
2254 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
2256 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2257 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2259 if (s
->control_command
) {
2260 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2262 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2266 socket_set_state(s
, SOCKET_START_PRE
);
2268 socket_enter_start_chown(s
);
2273 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2276 static void flush_ports(Socket
*s
) {
2279 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2282 LIST_FOREACH(port
, p
, s
->ports
) {
2286 (void) flush_accept(p
->fd
);
2287 (void) flush_fd(p
->fd
);
2291 static void socket_enter_running(Socket
*s
, int cfd_in
) {
2292 /* Note that this call takes possession of the connection fd passed. It either has to assign it
2293 * somewhere or close it. */
2294 _cleanup_close_
int cfd
= cfd_in
;
2296 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2301 /* We don't take connections anymore if we are supposed to shut down anyway */
2302 if (unit_stop_pending(UNIT(s
))) {
2304 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2313 if (!ratelimit_below(&s
->trigger_limit
)) {
2314 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2315 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2320 bool pending
= false;
2323 /* If there's already a start pending don't bother to do anything */
2324 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_TRIGGERS
)
2325 if (unit_active_or_pending(other
)) {
2331 if (!UNIT_ISSET(s
->service
)) {
2332 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOENT
),
2333 "Service to activate vanished, refusing activation.");
2337 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, NULL
, &error
, NULL
);
2342 socket_set_state(s
, SOCKET_RUNNING
);
2344 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2347 if (s
->n_connections
>= s
->max_connections
) {
2348 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2353 if (s
->max_connections_per_source
> 0) {
2354 r
= socket_acquire_peer(s
, cfd
, &p
);
2356 if (ERRNO_IS_DISCONNECT(r
))
2358 /* We didn't have enough resources to acquire peer information, let's fail. */
2361 if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2362 _cleanup_free_
char *t
= NULL
;
2364 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2366 log_unit_warning(UNIT(s
),
2367 "Too many incoming connections (%u) from source %s, dropping connection.",
2368 p
->n_ref
, strnull(t
));
2373 r
= socket_load_service_unit(s
, cfd
, &service
);
2375 if (ERRNO_IS_DISCONNECT(r
))
2380 r
= unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, service
,
2381 false, UNIT_DEPENDENCY_IMPLICIT
);
2387 r
= service_set_socket_fd(SERVICE(service
), cfd
, s
, p
, s
->selinux_context_from_net
);
2389 if (ERRNO_IS_DISCONNECT(r
))
2394 TAKE_FD(cfd
); /* We passed ownership of the fd to the service now. Forget it here. */
2397 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, service
, JOB_REPLACE
, NULL
, &error
, NULL
);
2399 /* We failed to activate the new service, but it still exists. Let's make sure the
2400 * service closes and forgets the connection fd again, immediately. */
2401 service_release_socket_fd(SERVICE(service
));
2405 /* Notify clients about changed counters */
2406 unit_add_to_dbus_queue(UNIT(s
));
2417 if (ERRNO_IS_RESOURCE(r
))
2418 log_unit_warning(UNIT(s
), "Failed to queue service startup job: %s",
2419 bus_error_message(&error
, r
));
2421 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2422 cfd
>= 0 ? "template" : "non-template",
2423 bus_error_message(&error
, r
));
2425 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2428 static void socket_run_next(Socket
*s
) {
2432 assert(s
->control_command
);
2433 assert(s
->control_command
->command_next
);
2435 socket_unwatch_control_pid(s
);
2437 s
->control_command
= s
->control_command
->command_next
;
2439 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2446 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2448 if (s
->state
== SOCKET_START_POST
)
2449 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2450 else if (s
->state
== SOCKET_STOP_POST
)
2451 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2453 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2456 static int socket_start(Unit
*u
) {
2457 Socket
*s
= SOCKET(u
);
2462 /* We cannot fulfill this request right now, try again later
2464 if (IN_SET(s
->state
,
2466 SOCKET_STOP_PRE_SIGKILL
,
2467 SOCKET_STOP_PRE_SIGTERM
,
2469 SOCKET_FINAL_SIGTERM
,
2470 SOCKET_FINAL_SIGKILL
,
2474 /* Already on it! */
2475 if (IN_SET(s
->state
,
2481 /* Cannot run this without the service being around */
2482 if (UNIT_ISSET(s
->service
)) {
2485 service
= SERVICE(UNIT_DEREF(s
->service
));
2487 if (UNIT(service
)->load_state
!= UNIT_LOADED
)
2488 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
2489 "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2491 /* If the service is already active we cannot start the
2493 if (!IN_SET(service
->state
,
2494 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
2495 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
2496 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EBUSY
),
2497 "Socket service %s already active, refusing.", UNIT(service
)->id
);
2500 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2502 r
= unit_acquire_invocation_id(u
);
2506 s
->result
= SOCKET_SUCCESS
;
2507 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2509 u
->reset_accounting
= true;
2511 socket_enter_start_pre(s
);
2515 static int socket_stop(Unit
*u
) {
2516 Socket
*s
= SOCKET(u
);
2521 if (IN_SET(s
->state
,
2523 SOCKET_STOP_PRE_SIGTERM
,
2524 SOCKET_STOP_PRE_SIGKILL
,
2526 SOCKET_FINAL_SIGTERM
,
2527 SOCKET_FINAL_SIGKILL
))
2530 /* If there's already something running we go directly into
2532 if (IN_SET(s
->state
,
2535 SOCKET_START_POST
)) {
2536 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2540 /* If we are currently cleaning, then abort it, brutally. */
2541 if (s
->state
== SOCKET_CLEANING
) {
2542 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2546 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2548 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2552 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2553 Socket
*s
= SOCKET(u
);
2560 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2561 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2562 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2563 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2565 if (s
->control_pid
> 0)
2566 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
2568 if (s
->control_command_id
>= 0)
2569 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2571 LIST_FOREACH(port
, p
, s
->ports
) {
2577 copy
= fdset_put_dup(fds
, p
->fd
);
2579 return log_unit_warning_errno(u
, copy
, "Failed to serialize socket fd: %m");
2581 if (p
->type
== SOCKET_SOCKET
) {
2582 _cleanup_free_
char *t
= NULL
;
2584 r
= socket_address_print(&p
->address
, &t
);
2586 return log_unit_error_errno(u
, r
, "Failed to format socket address: %m");
2588 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2589 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2591 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2592 } else if (p
->type
== SOCKET_SPECIAL
)
2593 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2594 else if (p
->type
== SOCKET_MQUEUE
)
2595 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2596 else if (p
->type
== SOCKET_USB_FUNCTION
)
2597 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2599 assert(p
->type
== SOCKET_FIFO
);
2600 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2607 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2608 Socket
*s
= SOCKET(u
);
2615 if (streq(key
, "state")) {
2618 state
= socket_state_from_string(value
);
2620 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2622 s
->deserialized_state
= state
;
2623 } else if (streq(key
, "result")) {
2626 f
= socket_result_from_string(value
);
2628 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2629 else if (f
!= SOCKET_SUCCESS
)
2632 } else if (streq(key
, "n-accepted")) {
2635 if (safe_atou(value
, &k
) < 0)
2636 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2639 } else if (streq(key
, "n-refused")) {
2642 if (safe_atou(value
, &k
) < 0)
2643 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2646 } else if (streq(key
, "control-pid")) {
2649 if (parse_pid(value
, &pid
) < 0)
2650 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2652 s
->control_pid
= pid
;
2653 } else if (streq(key
, "control-command")) {
2654 SocketExecCommand id
;
2656 id
= socket_exec_command_from_string(value
);
2658 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2660 s
->control_command_id
= id
;
2661 s
->control_command
= s
->exec_command
[id
];
2663 } else if (streq(key
, "fifo")) {
2664 _cleanup_free_
char *fdv
= NULL
;
2668 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2670 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2675 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2676 log_unit_debug(u
, "Invalid fifo value: %s", fdv
);
2680 LIST_FOREACH(port
, p
, s
->ports
)
2682 p
->type
== SOCKET_FIFO
&&
2683 path_equal_or_inode_same(p
->path
, value
, 0)) {
2684 p
->fd
= fdset_remove(fds
, fd
);
2689 log_unit_debug(u
, "No matching fifo socket found: %s", value
);
2691 } else if (streq(key
, "special")) {
2692 _cleanup_free_
char *fdv
= NULL
;
2696 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2698 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2703 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2704 log_unit_debug(u
, "Invalid special value: %s", fdv
);
2708 LIST_FOREACH(port
, p
, s
->ports
)
2710 p
->type
== SOCKET_SPECIAL
&&
2711 path_equal_or_inode_same(p
->path
, value
, 0)) {
2712 p
->fd
= fdset_remove(fds
, fd
);
2717 log_unit_debug(u
, "No matching special socket found: %s", value
);
2719 } else if (streq(key
, "mqueue")) {
2720 _cleanup_free_
char *fdv
= NULL
;
2724 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2726 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2731 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2732 log_unit_debug(u
, "Invalid mqueue value: %s", fdv
);
2736 LIST_FOREACH(port
, p
, s
->ports
)
2738 p
->type
== SOCKET_MQUEUE
&&
2739 streq(p
->path
, value
)) {
2740 p
->fd
= fdset_remove(fds
, fd
);
2745 log_unit_debug(u
, "No matching mqueue socket found: %s", value
);
2747 } else if (streq(key
, "socket")) {
2748 _cleanup_free_
char *fdv
= NULL
, *typev
= NULL
;
2752 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2754 log_unit_debug(u
, "Failed to parse socket fd from value: %s", value
);
2759 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2760 log_unit_debug(u
, "Invalid socket fd: %s", fdv
);
2764 r
= extract_first_word(&value
, &typev
, NULL
, 0);
2766 log_unit_debug(u
, "Failed to parse socket type from value: %s", value
);
2770 if (safe_atoi(typev
, &type
) < 0 || type
< 0) {
2771 log_unit_debug(u
, "Invalid socket type: %s", typev
);
2775 LIST_FOREACH(port
, p
, s
->ports
)
2777 socket_address_is(&p
->address
, value
, type
)) {
2778 p
->fd
= fdset_remove(fds
, fd
);
2783 log_unit_debug(u
, "No matching %s socket found: %s",
2784 socket_address_type_to_string(type
), value
);
2786 } else if (streq(key
, "netlink")) {
2787 _cleanup_free_
char *fdv
= NULL
;
2791 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2793 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2798 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2799 log_unit_debug(u
, "Invalid socket value: %s", fdv
);
2803 LIST_FOREACH(port
, p
, s
->ports
)
2805 socket_address_is_netlink(&p
->address
, value
)) {
2806 p
->fd
= fdset_remove(fds
, fd
);
2811 log_unit_debug(u
, "No matching netlink socket found: %s", value
);
2813 } else if (streq(key
, "ffs")) {
2814 _cleanup_free_
char *fdv
= NULL
;
2818 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2820 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2825 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2826 log_unit_debug(u
, "Invalid ffs value: %s", fdv
);
2830 LIST_FOREACH(port
, p
, s
->ports
)
2832 p
->type
== SOCKET_USB_FUNCTION
&&
2833 path_equal_or_inode_same(p
->path
, value
, 0)) {
2834 p
->fd
= fdset_remove(fds
, fd
);
2839 log_unit_debug(u
, "No matching ffs socket found: %s", value
);
2842 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2847 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2848 Socket
*s
= SOCKET(u
);
2852 LIST_FOREACH(port
, p
, s
->ports
) {
2855 if (p
->type
!= SOCKET_SOCKET
)
2861 FDSET_FOREACH(fd
, fds
) {
2862 if (socket_address_matches_fd(&p
->address
, fd
)) {
2863 p
->fd
= fdset_remove(fds
, fd
);
2864 s
->deserialized_state
= SOCKET_LISTENING
;
2871 static UnitActiveState
socket_active_state(Unit
*u
) {
2874 return state_translation_table
[SOCKET(u
)->state
];
2877 static const char *socket_sub_state_to_string(Unit
*u
) {
2880 return socket_state_to_string(SOCKET(u
)->state
);
2883 const char* socket_port_type_to_string(SocketPort
*p
) {
2891 switch (p
->address
.type
) {
2899 case SOCK_SEQPACKET
:
2900 return "SequentialPacket";
2903 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2911 case SOCKET_SPECIAL
:
2915 return "MessageQueue";
2920 case SOCKET_USB_FUNCTION
:
2921 return "USBFunction";
2928 SocketType
socket_port_type_from_string(const char *s
) {
2931 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2932 return SOCKET_SOCKET
;
2933 else if (streq(s
, "Special"))
2934 return SOCKET_SPECIAL
;
2935 else if (streq(s
, "MessageQueue"))
2936 return SOCKET_MQUEUE
;
2937 else if (streq(s
, "FIFO"))
2939 else if (streq(s
, "USBFunction"))
2940 return SOCKET_USB_FUNCTION
;
2942 return _SOCKET_TYPE_INVALID
;
2945 static bool socket_may_gc(Unit
*u
) {
2946 Socket
*s
= SOCKET(u
);
2950 return s
->n_connections
== 0;
2953 static int socket_accept_do(Socket
*s
, int fd
) {
2959 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2961 /* Convert transient network errors into clean and well-defined EAGAIN */
2962 return ERRNO_IS_ACCEPT_AGAIN(errno
) ? -EAGAIN
: -errno
;
2967 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2968 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
2976 /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
2977 * connection socket is also properly associated with the cgroup. */
2979 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2982 r
= bpf_firewall_supported();
2985 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2988 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2989 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2991 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2993 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2997 pair
[0] = safe_close(pair
[0]);
2999 cfd
= socket_accept_do(s
, fd
);
3000 if (cfd
== -EAGAIN
) /* spurious accept() */
3001 _exit(EXIT_SUCCESS
);
3003 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3004 _exit(EXIT_FAILURE
);
3007 r
= send_one_fd(pair
[1], cfd
, 0);
3009 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
3010 _exit(EXIT_FAILURE
);
3013 _exit(EXIT_SUCCESS
);
3016 pair
[1] = safe_close(pair
[1]);
3017 cfd
= receive_one_fd(pair
[0], 0);
3019 /* We synchronously wait for the helper, as it shouldn't be slow */
3020 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
3026 /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3027 * this is a spurious accept(), let's convert that back to EAGAIN here. */
3031 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
3036 cfd
= socket_accept_do(s
, fd
);
3037 if (cfd
== -EAGAIN
) /* spurious accept(), skip it silently */
3040 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3045 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3046 SocketPort
*p
= ASSERT_PTR(userdata
);
3051 if (p
->socket
->state
!= SOCKET_LISTENING
)
3054 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
3056 if (revents
!= EPOLLIN
) {
3057 if (revents
& EPOLLHUP
)
3058 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.");
3060 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
3064 if (p
->socket
->accept
&&
3065 p
->type
== SOCKET_SOCKET
&&
3066 socket_address_can_accept(&p
->address
)) {
3068 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
3069 if (cfd
== -EAGAIN
) /* Spurious accept() */
3074 socket_apply_socket_options(p
->socket
, p
, cfd
);
3077 socket_enter_running(p
->socket
, cfd
);
3081 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
3085 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3086 Socket
*s
= SOCKET(u
);
3092 if (pid
!= s
->control_pid
)
3097 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
3099 else if (code
== CLD_EXITED
)
3100 f
= SOCKET_FAILURE_EXIT_CODE
;
3101 else if (code
== CLD_KILLED
)
3102 f
= SOCKET_FAILURE_SIGNAL
;
3103 else if (code
== CLD_DUMPED
)
3104 f
= SOCKET_FAILURE_CORE_DUMP
;
3106 assert_not_reached();
3108 if (s
->control_command
) {
3109 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3111 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3115 unit_log_process_exit(
3118 socket_exec_command_to_string(s
->control_command_id
),
3119 f
== SOCKET_SUCCESS
,
3122 if (s
->result
== SOCKET_SUCCESS
)
3125 if (s
->control_command
&&
3126 s
->control_command
->command_next
&&
3127 f
== SOCKET_SUCCESS
) {
3129 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
3132 s
->control_command
= NULL
;
3133 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3135 /* No further commands for this step, so let's figure
3136 * out what to do next */
3138 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
3142 case SOCKET_START_PRE
:
3143 if (f
== SOCKET_SUCCESS
)
3144 socket_enter_start_chown(s
);
3146 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3149 case SOCKET_START_CHOWN
:
3150 if (f
== SOCKET_SUCCESS
)
3151 socket_enter_start_post(s
);
3153 socket_enter_stop_pre(s
, f
);
3156 case SOCKET_START_POST
:
3157 if (f
== SOCKET_SUCCESS
)
3158 socket_enter_listening(s
);
3160 socket_enter_stop_pre(s
, f
);
3163 case SOCKET_STOP_PRE
:
3164 case SOCKET_STOP_PRE_SIGTERM
:
3165 case SOCKET_STOP_PRE_SIGKILL
:
3166 socket_enter_stop_post(s
, f
);
3169 case SOCKET_STOP_POST
:
3170 case SOCKET_FINAL_SIGTERM
:
3171 case SOCKET_FINAL_SIGKILL
:
3172 socket_enter_dead(s
, f
);
3175 case SOCKET_CLEANING
:
3177 if (s
->clean_result
== SOCKET_SUCCESS
)
3178 s
->clean_result
= f
;
3180 socket_enter_dead(s
, SOCKET_SUCCESS
);
3184 assert_not_reached();
3188 /* Notify clients about changed exit status */
3189 unit_add_to_dbus_queue(u
);
3192 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3193 Socket
*s
= SOCKET(userdata
);
3196 assert(s
->timer_event_source
== source
);
3200 case SOCKET_START_PRE
:
3201 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3202 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3205 case SOCKET_START_CHOWN
:
3206 case SOCKET_START_POST
:
3207 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3208 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3211 case SOCKET_STOP_PRE
:
3212 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3213 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3216 case SOCKET_STOP_PRE_SIGTERM
:
3217 if (s
->kill_context
.send_sigkill
) {
3218 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3219 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3221 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3222 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3226 case SOCKET_STOP_PRE_SIGKILL
:
3227 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3228 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3231 case SOCKET_STOP_POST
:
3232 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3233 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3236 case SOCKET_FINAL_SIGTERM
:
3237 if (s
->kill_context
.send_sigkill
) {
3238 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3239 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3241 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3242 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3246 case SOCKET_FINAL_SIGKILL
:
3247 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3248 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3251 case SOCKET_CLEANING
:
3252 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
3254 if (s
->clean_result
== SOCKET_SUCCESS
)
3255 s
->clean_result
= SOCKET_FAILURE_TIMEOUT
;
3257 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, 0);
3261 assert_not_reached();
3267 int socket_collect_fds(Socket
*s
, int **fds
) {
3268 size_t k
= 0, n
= 0;
3274 /* Called from the service code for requesting our fds */
3276 LIST_FOREACH(port
, p
, s
->ports
) {
3279 n
+= p
->n_auxiliary_fds
;
3291 LIST_FOREACH(port
, p
, s
->ports
) {
3294 for (size_t i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3295 rfds
[k
++] = p
->auxiliary_fds
[i
];
3304 static void socket_reset_failed(Unit
*u
) {
3305 Socket
*s
= SOCKET(u
);
3309 if (s
->state
== SOCKET_FAILED
)
3310 socket_set_state(s
, SOCKET_DEAD
);
3312 s
->result
= SOCKET_SUCCESS
;
3313 s
->clean_result
= SOCKET_SUCCESS
;
3316 void socket_connection_unref(Socket
*s
) {
3319 /* The service is dead. Yay!
3321 * This is strictly for one-instance-per-connection
3324 assert(s
->n_connections
> 0);
3327 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3330 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3331 Socket
*s
= SOCKET(u
);
3336 /* Filter out invocations with bogus state */
3337 assert(UNIT_IS_LOAD_COMPLETE(other
->load_state
));
3338 assert(other
->type
== UNIT_SERVICE
);
3340 /* Don't propagate state changes from the service if we are already down */
3341 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3344 /* We don't care for the service state if we are in Accept=yes mode */
3348 /* Propagate start limit hit state */
3349 if (other
->start_limit_hit
) {
3350 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3354 /* Don't propagate anything if there's still a job queued */
3358 if (IN_SET(SERVICE(other
)->state
,
3359 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
3360 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3361 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
3362 socket_enter_listening(s
);
3364 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3365 socket_set_state(s
, SOCKET_RUNNING
);
3368 static int socket_kill(Unit
*u
, KillWho who
, int signo
, int code
, int value
, sd_bus_error
*error
) {
3369 return unit_kill_common(u
, who
, signo
, code
, value
, -1, SOCKET(u
)->control_pid
, error
);
3372 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3373 Socket
*s
= SOCKET(u
);
3377 if (!s
->timer_event_source
)
3380 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3383 if (t
== USEC_INFINITY
)
3390 char *socket_fdname(Socket
*s
) {
3393 /* Returns the name to use for $LISTEN_NAMES. If the user
3394 * didn't specify anything specifically, use the socket unit's
3395 * name as fallback. */
3397 return s
->fdname
?: UNIT(s
)->id
;
3400 static int socket_control_pid(Unit
*u
) {
3401 Socket
*s
= SOCKET(u
);
3405 return s
->control_pid
;
3408 static int socket_clean(Unit
*u
, ExecCleanMask mask
) {
3409 _cleanup_strv_free_
char **l
= NULL
;
3410 Socket
*s
= SOCKET(u
);
3416 if (s
->state
!= SOCKET_DEAD
)
3419 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
3423 if (strv_isempty(l
))
3426 socket_unwatch_control_pid(s
);
3427 s
->clean_result
= SOCKET_SUCCESS
;
3428 s
->control_command
= NULL
;
3429 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3431 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->exec_context
.timeout_clean_usec
));
3435 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
3439 socket_set_state(s
, SOCKET_CLEANING
);
3444 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
3445 s
->clean_result
= SOCKET_FAILURE_RESOURCES
;
3446 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
3450 static int socket_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
3451 Socket
*s
= SOCKET(u
);
3455 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
3458 static int socket_can_start(Unit
*u
) {
3459 Socket
*s
= SOCKET(u
);
3464 r
= unit_test_start_limit(u
);
3466 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
3473 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3474 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3475 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3476 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3477 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3478 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3481 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3483 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3484 [SOCKET_SUCCESS
] = "success",
3485 [SOCKET_FAILURE_RESOURCES
] = "resources",
3486 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3487 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3488 [SOCKET_FAILURE_SIGNAL
] = "signal",
3489 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3490 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3491 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3492 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3495 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3497 static const char* const socket_timestamping_table
[_SOCKET_TIMESTAMPING_MAX
] = {
3498 [SOCKET_TIMESTAMPING_OFF
] = "off",
3499 [SOCKET_TIMESTAMPING_US
] = "us",
3500 [SOCKET_TIMESTAMPING_NS
] = "ns",
3503 DEFINE_STRING_TABLE_LOOKUP(socket_timestamping
, SocketTimestamping
);
3505 SocketTimestamping
socket_timestamping_from_string_harder(const char *p
) {
3506 SocketTimestamping t
;
3510 return _SOCKET_TIMESTAMPING_INVALID
;
3512 t
= socket_timestamping_from_string(p
);
3516 /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3518 if (streq(p
, "nsec"))
3519 return SOCKET_TIMESTAMPING_NS
;
3520 if (STR_IN_SET(p
, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
3521 return SOCKET_TIMESTAMPING_US
;
3523 r
= parse_boolean(p
);
3525 return _SOCKET_TIMESTAMPING_INVALID
;
3527 return r
? SOCKET_TIMESTAMPING_NS
: SOCKET_TIMESTAMPING_OFF
; /* If boolean yes, default to ns accuracy */
3530 const UnitVTable socket_vtable
= {
3531 .object_size
= sizeof(Socket
),
3532 .exec_context_offset
= offsetof(Socket
, exec_context
),
3533 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3534 .kill_context_offset
= offsetof(Socket
, kill_context
),
3535 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3541 .private_section
= "Socket",
3543 .can_transient
= true,
3544 .can_trigger
= true,
3547 .init
= socket_init
,
3548 .done
= socket_done
,
3549 .load
= socket_load
,
3551 .coldplug
= socket_coldplug
,
3553 .dump
= socket_dump
,
3555 .start
= socket_start
,
3556 .stop
= socket_stop
,
3558 .kill
= socket_kill
,
3559 .clean
= socket_clean
,
3560 .can_clean
= socket_can_clean
,
3562 .get_timeout
= socket_get_timeout
,
3564 .serialize
= socket_serialize
,
3565 .deserialize_item
= socket_deserialize_item
,
3566 .distribute_fds
= socket_distribute_fds
,
3568 .active_state
= socket_active_state
,
3569 .sub_state_to_string
= socket_sub_state_to_string
,
3571 .will_restart
= unit_will_restart_default
,
3573 .may_gc
= socket_may_gc
,
3575 .sigchld_event
= socket_sigchld_event
,
3577 .trigger_notify
= socket_trigger_notify
,
3579 .reset_failed
= socket_reset_failed
,
3581 .control_pid
= socket_control_pid
,
3583 .bus_set_property
= bus_socket_set_property
,
3584 .bus_commit_properties
= bus_socket_commit_properties
,
3586 .status_message_formats
= {
3587 .finished_start_job
= {
3588 [JOB_DONE
] = "Listening on %s.",
3589 [JOB_FAILED
] = "Failed to listen on %s.",
3590 [JOB_TIMEOUT
] = "Timed out starting %s.",
3592 .finished_stop_job
= {
3593 [JOB_DONE
] = "Closed %s.",
3594 [JOB_FAILED
] = "Failed stopping %s.",
3595 [JOB_TIMEOUT
] = "Timed out stopping %s.",
3599 .can_start
= socket_can_start
,