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
) {
141 while ((p
= s
->ports
)) {
142 LIST_REMOVE(port
, s
->ports
, p
);
147 static void socket_done(Unit
*u
) {
148 Socket
*s
= SOCKET(u
);
153 socket_free_ports(s
);
155 while ((p
= set_steal_first(s
->peers_by_address
)))
158 s
->peers_by_address
= set_free(s
->peers_by_address
);
160 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
161 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
162 s
->control_command
= NULL
;
164 socket_unwatch_control_pid(s
);
166 unit_ref_unset(&s
->service
);
168 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
169 s
->bind_to_device
= mfree(s
->bind_to_device
);
171 s
->smack
= mfree(s
->smack
);
172 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
173 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
175 strv_free(s
->symlinks
);
177 s
->user
= mfree(s
->user
);
178 s
->group
= mfree(s
->group
);
180 s
->fdname
= mfree(s
->fdname
);
182 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
185 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
190 if (s
->timer_event_source
) {
191 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
195 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
198 if (usec
== USEC_INFINITY
)
201 r
= sd_event_add_time(
202 UNIT(s
)->manager
->event
,
203 &s
->timer_event_source
,
206 socket_dispatch_timer
, s
);
210 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
215 static bool have_non_accept_socket(Socket
*s
) {
221 LIST_FOREACH(port
, p
, s
->ports
) {
223 if (p
->type
!= SOCKET_SOCKET
)
226 if (!socket_address_can_accept(&p
->address
))
233 static int socket_add_mount_dependencies(Socket
*s
) {
238 LIST_FOREACH(port
, p
, s
->ports
) {
239 const char *path
= NULL
;
241 if (p
->type
== SOCKET_SOCKET
)
242 path
= socket_address_get_path(&p
->address
);
243 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
249 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
257 static int socket_add_device_dependencies(Socket
*s
) {
262 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
265 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
266 return unit_add_node_dependency(UNIT(s
), t
, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
269 static int socket_add_default_dependencies(Socket
*s
) {
273 if (!UNIT(s
)->default_dependencies
)
276 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
280 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
281 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
286 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
290 return exec_context_add_default_dependencies(UNIT(s
), &s
->exec_context
);
293 _pure_
static bool socket_has_exec(Socket
*s
) {
297 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
298 if (s
->exec_command
[i
])
304 static int socket_add_extras(Socket
*s
) {
310 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
311 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
312 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
313 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
314 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
315 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
316 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
317 * service starts are typical. */
319 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
320 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
322 if (s
->trigger_limit
.burst
== UINT_MAX
) {
324 s
->trigger_limit
.burst
= 200;
326 s
->trigger_limit
.burst
= 20;
329 if (have_non_accept_socket(s
)) {
331 if (!UNIT_DEREF(s
->service
)) {
334 r
= unit_load_related_unit(u
, ".service", &x
);
338 unit_ref_set(&s
->service
, u
, x
);
341 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
346 r
= socket_add_mount_dependencies(s
);
350 r
= socket_add_device_dependencies(s
);
354 r
= unit_patch_contexts(u
);
358 if (socket_has_exec(s
)) {
359 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
364 r
= unit_set_default_slice(u
);
368 r
= socket_add_default_dependencies(s
);
375 static const char *socket_find_symlink_target(Socket
*s
) {
376 const char *found
= NULL
;
378 LIST_FOREACH(port
, p
, s
->ports
) {
379 const char *f
= NULL
;
388 f
= socket_address_get_path(&p
->address
);
406 static int socket_verify(Socket
*s
) {
408 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
411 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
413 if (s
->accept
&& have_non_accept_socket(s
))
414 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
416 if (s
->accept
&& s
->max_connections
<= 0)
417 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "MaxConnection= setting too small. Refusing.");
419 if (s
->accept
&& UNIT_DEREF(s
->service
))
420 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Explicit service configuration for accepting socket units not supported. Refusing.");
422 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
)
423 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
425 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
))
426 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.");
431 static void peer_address_hash_func(const SocketPeer
*s
, struct siphash
*state
) {
434 if (s
->peer
.sa
.sa_family
== AF_INET
)
435 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
436 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
437 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
438 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
439 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
441 assert_not_reached();
444 static int peer_address_compare_func(const SocketPeer
*x
, const SocketPeer
*y
) {
447 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
451 switch (x
->peer
.sa
.sa_family
) {
453 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
455 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
457 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
459 assert_not_reached();
462 DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops
, SocketPeer
, peer_address_hash_func
, peer_address_compare_func
);
464 static int socket_load(Unit
*u
) {
465 Socket
*s
= SOCKET(u
);
469 assert(u
->load_state
== UNIT_STUB
);
471 r
= unit_load_fragment_and_dropin(u
, true);
475 if (u
->load_state
!= UNIT_LOADED
)
478 /* This is a new unit? Then let's add in some extras */
479 r
= socket_add_extras(s
);
483 return socket_verify(s
);
486 static SocketPeer
*socket_peer_new(void) {
489 p
= new(SocketPeer
, 1);
499 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
503 set_remove(p
->socket
->peers_by_address
, p
);
508 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
510 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
511 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
513 .peer_salen
= sizeof(union sockaddr_union
),
520 if (getpeername(fd
, &sa
.peer
.sa
, &sa
.peer_salen
) < 0)
521 return log_unit_error_errno(UNIT(s
), errno
, "getpeername failed: %m");
523 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
528 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
532 i
= set_get(s
->peers_by_address
, &sa
);
534 *p
= socket_peer_ref(i
);
538 remote
= socket_peer_new();
542 remote
->peer
= sa
.peer
;
543 remote
->peer_salen
= sa
.peer_salen
;
545 r
= set_put(s
->peers_by_address
, remote
);
551 *p
= TAKE_PTR(remote
);
555 _const_
static const char* listen_lookup(int family
, int type
) {
557 if (family
== AF_NETLINK
)
558 return "ListenNetlink";
560 if (type
== SOCK_STREAM
)
561 return "ListenStream";
562 else if (type
== SOCK_DGRAM
)
563 return "ListenDatagram";
564 else if (type
== SOCK_SEQPACKET
)
565 return "ListenSequentialPacket";
567 assert_not_reached();
571 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
572 Socket
*s
= SOCKET(u
);
573 const char *prefix2
, *str
;
578 prefix
= strempty(prefix
);
579 prefix2
= strjoina(prefix
, "\t");
582 "%sSocket State: %s\n"
584 "%sClean Result: %s\n"
585 "%sBindIPv6Only: %s\n"
587 "%sSocketMode: %04o\n"
588 "%sDirectoryMode: %04o\n"
592 "%sTransparent: %s\n"
594 "%sPassCredentials: %s\n"
595 "%sPassSecurity: %s\n"
596 "%sPassPacketInfo: %s\n"
597 "%sTCPCongestion: %s\n"
598 "%sRemoveOnStop: %s\n"
600 "%sFileDescriptorName: %s\n"
601 "%sSELinuxContextFromNet: %s\n",
602 prefix
, socket_state_to_string(s
->state
),
603 prefix
, socket_result_to_string(s
->result
),
604 prefix
, socket_result_to_string(s
->clean_result
),
605 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
607 prefix
, s
->socket_mode
,
608 prefix
, s
->directory_mode
,
609 prefix
, yes_no(s
->keep_alive
),
610 prefix
, yes_no(s
->no_delay
),
611 prefix
, yes_no(s
->free_bind
),
612 prefix
, yes_no(s
->transparent
),
613 prefix
, yes_no(s
->broadcast
),
614 prefix
, yes_no(s
->pass_cred
),
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 (s
->control_pid
> 0)
630 "%sControl PID: "PID_FMT
"\n",
631 prefix
, s
->control_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 prefix
, FORMAT_TIMESPAN(s
->trigger_limit
.interval
, USEC_PER_SEC
),
779 prefix
, s
->trigger_limit
.burst
);
781 str
= ip_protocol_to_name(s
->socket_protocol
);
783 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
785 if (!strv_isempty(s
->symlinks
)) {
786 fprintf(f
, "%sSymlinks:", prefix
);
787 STRV_FOREACH(q
, s
->symlinks
)
788 fprintf(f
, " %s", *q
);
794 "%sTimeoutSec: %s\n",
795 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
797 exec_context_dump(&s
->exec_context
, f
, prefix
);
798 kill_context_dump(&s
->kill_context
, f
, prefix
);
800 for (SocketExecCommand c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
801 if (!s
->exec_command
[c
])
804 fprintf(f
, "%s-> %s:\n",
805 prefix
, socket_exec_command_to_string(c
));
807 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
810 cgroup_context_dump(UNIT(s
), f
, prefix
);
813 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
816 union sockaddr_union local
, remote
;
822 if (getsockname(fd
, &local
.sa
, &l
) < 0)
826 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
829 switch (local
.sa
.sa_family
) {
833 a
= be32toh(local
.in
.sin_addr
.s_addr
),
834 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
837 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
839 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
840 be16toh(local
.in
.sin_port
),
841 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
842 be16toh(remote
.in
.sin_port
)) < 0)
849 static const unsigned char ipv4_prefix
[] = {
850 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
853 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
854 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
856 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
857 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
860 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
862 a
[0], a
[1], a
[2], a
[3],
863 be16toh(local
.in6
.sin6_port
),
864 b
[0], b
[1], b
[2], b
[3],
865 be16toh(remote
.in6
.sin6_port
)) < 0)
871 IN6_ADDR_TO_STRING(&local
.in6
.sin6_addr
),
872 be16toh(local
.in6
.sin6_port
),
873 IN6_ADDR_TO_STRING(&remote
.in6
.sin6_addr
),
874 be16toh(remote
.in6
.sin6_port
)) < 0)
885 k
= getpeercred(fd
, &ucred
);
888 "%u-"PID_FMT
"-"UID_FMT
,
889 nr
, ucred
.pid
, ucred
.uid
) < 0)
891 } else if (k
== -ENODATA
) {
892 /* This handles the case where somebody is
893 * connecting from another pid/uid namespace
894 * (e.g. from outside of our container). */
909 local
.vm
.svm_cid
, local
.vm
.svm_port
,
910 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
916 assert_not_reached();
923 static void socket_close_fds(Socket
*s
) {
926 LIST_FOREACH(port
, p
, s
->ports
) {
929 was_open
= p
->fd
>= 0;
931 p
->event_source
= sd_event_source_disable_unref(p
->event_source
);
932 p
->fd
= safe_close(p
->fd
);
933 socket_cleanup_fd_list(p
);
935 /* One little note: we should normally not delete any sockets in the file system here! After all some
936 * other process we spawned might still have a reference of this fd and wants to continue to use
937 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
938 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
939 * anyway, but only then. */
941 if (!was_open
|| !s
->remove_on_stop
)
947 (void) unlink(p
->path
);
951 (void) mq_unlink(p
->path
);
955 (void) socket_address_unlink(&p
->address
);
963 if (s
->remove_on_stop
)
964 STRV_FOREACH(i
, s
->symlinks
)
967 /* Note that we don't return NULL here, since s has not been freed. */
970 static void socket_apply_socket_options(Socket
*s
, SocketPort
*p
, int fd
) {
978 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
980 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
983 if (timestamp_is_set(s
->keep_alive_time
)) {
984 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
986 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
989 if (s
->keep_alive_interval
> 0) {
990 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
992 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
995 if (s
->keep_alive_cnt
> 0) {
996 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
998 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
1001 if (s
->defer_accept
> 0) {
1002 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
1004 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
1008 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1009 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1011 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1013 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1015 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1020 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1022 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1026 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1028 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1032 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1034 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1037 if (s
->pass_pktinfo
) {
1038 r
= socket_set_recvpktinfo(fd
, socket_address_family(&p
->address
), true);
1040 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable packet info socket option: %m");
1043 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
) {
1044 r
= setsockopt_int(fd
, SOL_SOCKET
,
1045 s
->timestamping
== SOCKET_TIMESTAMPING_NS
? SO_TIMESTAMPNS
: SO_TIMESTAMP
,
1048 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable timestamping socket option, ignoring: %m");
1051 if (s
->priority
>= 0) {
1052 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1054 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1057 if (s
->receive_buffer
> 0) {
1058 r
= fd_set_rcvbuf(fd
, s
->receive_buffer
, false);
1060 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1061 "SO_RCVBUF/SO_RCVBUFFORCE failed: %m");
1064 if (s
->send_buffer
> 0) {
1065 r
= fd_set_sndbuf(fd
, s
->send_buffer
, false);
1067 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1068 "SO_SNDBUF/SO_SNDBUFFORCE failed: %m");
1072 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1074 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1077 if (s
->ip_tos
>= 0) {
1078 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1080 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1083 if (s
->ip_ttl
>= 0) {
1084 r
= socket_set_ttl(fd
, socket_address_family(&p
->address
), s
->ip_ttl
);
1086 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1089 if (s
->tcp_congestion
)
1090 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1091 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1093 if (s
->smack_ip_in
) {
1094 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1096 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1099 if (s
->smack_ip_out
) {
1100 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1102 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1106 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1112 if (s
->pipe_size
> 0)
1113 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1114 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1117 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1119 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1123 static int fifo_address_create(
1125 mode_t directory_mode
,
1126 mode_t socket_mode
) {
1128 _cleanup_close_
int fd
= -EBADF
;
1135 (void) mkdir_parents_label(path
, directory_mode
);
1137 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1141 /* Enforce the right access mode for the fifo */
1142 old_mask
= umask(~socket_mode
);
1144 /* Include the original umask in our mask */
1145 (void) umask(~socket_mode
| old_mask
);
1147 r
= mkfifo(path
, socket_mode
);
1148 (void) umask(old_mask
);
1150 if (r
< 0 && errno
!= EEXIST
) {
1155 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1161 mac_selinux_create_file_clear();
1163 if (fstat(fd
, &st
) < 0) {
1168 if (!S_ISFIFO(st
.st_mode
) ||
1169 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1170 st
.st_uid
!= getuid() ||
1171 st
.st_gid
!= getgid()) {
1179 mac_selinux_create_file_clear();
1183 static int special_address_create(const char *path
, bool writable
) {
1184 _cleanup_close_
int fd
= -EBADF
;
1189 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1193 if (fstat(fd
, &st
) < 0)
1196 /* Check whether this is a /proc, /sys or /dev file or char device */
1197 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1203 static int usbffs_address_create(const char *path
) {
1204 _cleanup_close_
int fd
= -EBADF
;
1209 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1213 if (fstat(fd
, &st
) < 0)
1216 /* Check whether this is a regular file (ffs endpoint) */
1217 if (!S_ISREG(st
.st_mode
))
1223 static int mq_address_create(
1229 _cleanup_close_
int fd
= -EBADF
;
1232 struct mq_attr _attr
, *attr
= NULL
;
1236 if (maxmsg
> 0 && msgsize
> 0) {
1237 _attr
= (struct mq_attr
) {
1238 .mq_flags
= O_NONBLOCK
,
1239 .mq_maxmsg
= maxmsg
,
1240 .mq_msgsize
= msgsize
,
1245 /* Enforce the right access mode for the mq */
1246 old_mask
= umask(~mq_mode
);
1248 /* Include the original umask in our mask */
1249 (void) umask(~mq_mode
| old_mask
);
1250 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1251 (void) umask(old_mask
);
1256 if (fstat(fd
, &st
) < 0)
1259 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1260 st
.st_uid
!= getuid() ||
1261 st
.st_gid
!= getgid())
1267 static int socket_symlink(Socket
*s
) {
1273 p
= socket_find_symlink_target(s
);
1277 STRV_FOREACH(i
, s
->symlinks
) {
1278 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1280 r
= symlink_idempotent(p
, *i
, false);
1282 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1283 /* If there's already something where we want to create the symlink, and the destructive
1284 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1287 if (unlink(*i
) >= 0)
1288 r
= symlink_idempotent(p
, *i
, false);
1292 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s %s %s, ignoring: %m",
1293 p
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *i
);
1299 static int usbffs_write_descs(int fd
, Service
*s
) {
1302 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1305 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1309 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1312 static int usbffs_select_ep(const struct dirent
*d
) {
1313 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1316 static int usbffs_dispatch_eps(SocketPort
*p
) {
1317 _cleanup_free_
struct dirent
**ent
= NULL
;
1321 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1326 p
->auxiliary_fds
= new(int, n
);
1327 if (!p
->auxiliary_fds
) {
1332 p
->n_auxiliary_fds
= n
;
1335 for (size_t i
= 0; i
< n
; ++i
) {
1336 _cleanup_free_
char *ep
= NULL
;
1338 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1346 r
= usbffs_address_create(ep
);
1350 p
->auxiliary_fds
[k
++] = r
;
1357 close_many(p
->auxiliary_fds
, k
);
1358 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1359 p
->n_auxiliary_fds
= 0;
1362 for (size_t i
= 0; i
< n
; ++i
)
1368 int socket_load_service_unit(Socket
*s
, int cfd
, Unit
**ret
) {
1369 /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1371 * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1375 if (UNIT_ISSET(s
->service
)) {
1376 *ret
= UNIT_DEREF(s
->service
);
1383 /* Build the instance name and load the unit */
1384 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
1387 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
1392 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
1393 if (ERRNO_IS_DISCONNECT(r
))
1394 /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1395 * different errors. This connection is over, but the socket unit lives on. */
1396 return log_unit_debug_errno(UNIT(s
), r
,
1397 "Got %s on incoming socket, assuming aborted connection attempt, ignoring.",
1403 /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1404 * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1405 * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1406 r
= unit_name_build(prefix
, instance
?: "internal", ".service", &name
);
1410 return manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, ret
);
1413 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1421 const char *exec_context
;
1422 _cleanup_free_
char *path
= NULL
;
1424 r
= socket_load_service_unit(s
, -1, &service
);
1430 exec_context
= SERVICE(service
)->exec_context
.selinux_context
;
1434 con
= strdup(exec_context
);
1438 *ret
= TAKE_PTR(con
);
1442 c
= SERVICE(service
)->exec_command
[SERVICE_EXEC_START
];
1446 r
= chase(c
->path
, SERVICE(service
)->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
, NULL
);
1450 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1451 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1460 static int socket_address_listen_do(
1462 const SocketAddress
*address
,
1463 const char *label
) {
1468 return socket_address_listen(
1470 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1482 #define log_address_error_errno(u, address, error, fmt) \
1484 _cleanup_free_ char *_t = NULL; \
1486 (void) socket_address_print(address, &_t); \
1487 log_unit_error_errno(u, error, fmt, strna(_t)); \
1490 static int fork_needed(const SocketAddress
*address
, const ExecContext
*context
) {
1496 /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1498 if (IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
)) {
1499 r
= bpf_firewall_supported();
1502 if (r
!= BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1506 return exec_needs_network_namespace(context
);
1509 static int socket_address_listen_in_cgroup(
1511 const SocketAddress
*address
,
1512 const char *label
) {
1514 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
1521 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1522 * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1523 * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1526 r
= fork_needed(address
, &s
->exec_context
);
1530 /* Shortcut things... */
1531 fd
= socket_address_listen_do(s
, address
, label
);
1533 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1538 r
= unit_setup_exec_runtime(UNIT(s
));
1540 return log_unit_error_errno(UNIT(s
), r
, "Failed acquire runtime: %m");
1542 if (s
->exec_context
.network_namespace_path
&&
1544 s
->exec_runtime
->shared
&&
1545 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1546 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->netns_storage_socket
, s
->exec_context
.network_namespace_path
, CLONE_NEWNET
);
1548 return log_unit_error_errno(UNIT(s
), r
, "Failed to open network namespace path %s: %m", s
->exec_context
.network_namespace_path
);
1551 if (s
->exec_context
.ipc_namespace_path
&&
1553 s
->exec_runtime
->shared
&&
1554 s
->exec_runtime
->shared
->ipcns_storage_socket
[0] >= 0) {
1555 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->ipcns_storage_socket
, s
->exec_context
.ipc_namespace_path
, CLONE_NEWIPC
);
1557 return log_unit_error_errno(UNIT(s
), r
, "Failed to open IPC namespace path %s: %m", s
->exec_context
.ipc_namespace_path
);
1560 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1561 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1563 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1565 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1569 pair
[0] = safe_close(pair
[0]);
1571 if (exec_needs_network_namespace(&s
->exec_context
) &&
1573 s
->exec_runtime
->shared
&&
1574 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1576 if (ns_type_supported(NAMESPACE_NET
)) {
1577 r
= setup_shareable_ns(s
->exec_runtime
->shared
->netns_storage_socket
, CLONE_NEWNET
);
1579 log_unit_error_errno(UNIT(s
), r
, "Failed to join network namespace: %m");
1580 _exit(EXIT_NETWORK
);
1582 } else if (s
->exec_context
.network_namespace_path
) {
1583 log_unit_error(UNIT(s
), "Network namespace path configured but network namespaces not supported.");
1584 _exit(EXIT_NETWORK
);
1586 log_unit_warning(UNIT(s
), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
1589 fd
= socket_address_listen_do(s
, address
, label
);
1591 log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1592 _exit(EXIT_FAILURE
);
1595 r
= send_one_fd(pair
[1], fd
, 0);
1597 log_address_error_errno(UNIT(s
), address
, r
, "Failed to send listening socket (%s) to parent: %m");
1598 _exit(EXIT_FAILURE
);
1601 _exit(EXIT_SUCCESS
);
1604 pair
[1] = safe_close(pair
[1]);
1605 fd
= receive_one_fd(pair
[0], 0);
1607 /* We synchronously wait for the helper, as it shouldn't be slow */
1608 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1615 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to receive listening socket (%s): %m");
1620 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket
*, socket_close_fds
, NULL
);
1622 static int socket_open_fds(Socket
*orig_s
) {
1623 _cleanup_(socket_close_fdsp
) Socket
*s
= orig_s
;
1624 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1625 bool know_label
= false;
1630 LIST_FOREACH(port
, p
, s
->ports
) {
1640 /* Figure out the label, if we don't it know yet. We do it once for the first
1641 * socket where we need this and remember it for the rest. */
1643 r
= socket_determine_selinux_label(s
, &label
);
1645 return log_unit_error_errno(UNIT(s
), r
, "Failed to determine SELinux label: %m");
1650 /* Apply the socket protocol */
1651 switch (p
->address
.type
) {
1654 case SOCK_SEQPACKET
:
1655 if (s
->socket_protocol
== IPPROTO_SCTP
)
1656 p
->address
.protocol
= s
->socket_protocol
;
1660 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1661 p
->address
.protocol
= s
->socket_protocol
;
1665 p
->fd
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1669 socket_apply_socket_options(s
, p
, p
->fd
);
1673 case SOCKET_SPECIAL
:
1675 p
->fd
= special_address_create(p
->path
, s
->writable
);
1677 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open special file %s: %m", p
->path
);
1682 p
->fd
= fifo_address_create(
1687 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open FIFO %s: %m", p
->path
);
1689 socket_apply_fifo_options(s
, p
->fd
);
1695 p
->fd
= mq_address_create(
1701 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open message queue %s: %m", p
->path
);
1704 case SOCKET_USB_FUNCTION
: {
1705 _cleanup_free_
char *ep
= NULL
;
1707 ep
= path_make_absolute("ep0", p
->path
);
1711 p
->fd
= usbffs_address_create(ep
);
1715 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1719 r
= usbffs_dispatch_eps(p
);
1726 assert_not_reached();
1734 static void socket_unwatch_fds(Socket
*s
) {
1739 LIST_FOREACH(port
, p
, s
->ports
) {
1743 if (!p
->event_source
)
1746 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1748 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1752 static int socket_watch_fds(Socket
*s
) {
1757 LIST_FOREACH(port
, p
, s
->ports
) {
1761 if (p
->event_source
) {
1762 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1766 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1770 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1777 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1778 socket_unwatch_fds(s
);
1788 static int socket_check_open(Socket
*s
) {
1789 bool have_open
= false, have_closed
= false;
1793 LIST_FOREACH(port
, p
, s
->ports
) {
1799 if (have_open
&& have_closed
)
1800 return SOCKET_OPEN_SOME
;
1804 return SOCKET_OPEN_ALL
;
1806 return SOCKET_OPEN_NONE
;
1809 static void socket_set_state(Socket
*s
, SocketState state
) {
1810 SocketState old_state
;
1813 if (s
->state
!= state
)
1814 bus_unit_send_pending_change_signal(UNIT(s
), false);
1816 old_state
= s
->state
;
1824 SOCKET_STOP_PRE_SIGTERM
,
1825 SOCKET_STOP_PRE_SIGKILL
,
1827 SOCKET_FINAL_SIGTERM
,
1828 SOCKET_FINAL_SIGKILL
,
1831 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1832 socket_unwatch_control_pid(s
);
1833 s
->control_command
= NULL
;
1834 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1837 if (state
!= SOCKET_LISTENING
)
1838 socket_unwatch_fds(s
);
1846 SOCKET_STOP_PRE_SIGTERM
,
1847 SOCKET_STOP_PRE_SIGKILL
,
1849 socket_close_fds(s
);
1851 if (state
!= old_state
)
1852 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1854 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
1857 static int socket_coldplug(Unit
*u
) {
1858 Socket
*s
= SOCKET(u
);
1862 assert(s
->state
== SOCKET_DEAD
);
1864 if (s
->deserialized_state
== s
->state
)
1867 if (s
->control_pid
> 0 &&
1868 pid_is_unwaited(s
->control_pid
) &&
1869 IN_SET(s
->deserialized_state
,
1874 SOCKET_STOP_PRE_SIGTERM
,
1875 SOCKET_STOP_PRE_SIGKILL
,
1877 SOCKET_FINAL_SIGTERM
,
1878 SOCKET_FINAL_SIGKILL
,
1881 r
= unit_watch_pid(UNIT(s
), s
->control_pid
, false);
1885 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1890 if (IN_SET(s
->deserialized_state
,
1896 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1897 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN state for
1898 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1899 * and if there's a mismatch, warn loudly. */
1901 r
= socket_check_open(s
);
1902 if (r
== SOCKET_OPEN_NONE
)
1903 log_unit_warning(UNIT(s
),
1904 "Socket unit configuration has changed while unit has been running, "
1905 "no open socket file descriptor left. "
1906 "The socket unit is not functional until restarted.");
1907 else if (r
== SOCKET_OPEN_SOME
)
1908 log_unit_warning(UNIT(s
),
1909 "Socket unit configuration has changed while unit has been running, "
1910 "and some socket file descriptors have not been opened yet. "
1911 "The socket unit is not fully functional until restarted.");
1914 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1915 r
= socket_watch_fds(s
);
1920 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
, SOCKET_CLEANING
))
1921 (void) unit_setup_exec_runtime(u
);
1923 socket_set_state(s
, s
->deserialized_state
);
1927 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1929 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1930 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1932 .stdout_fd
= -EBADF
,
1933 .stderr_fd
= -EBADF
,
1943 r
= unit_prepare_exec(UNIT(s
));
1947 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1951 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1955 r
= exec_spawn(UNIT(s
),
1965 r
= unit_watch_pid(UNIT(s
), pid
, true);
1974 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1978 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1982 /* We have to resolve the user names out-of-process, hence
1983 * let's fork here. It's messy, but well, what can we do? */
1985 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1989 uid_t uid
= UID_INVALID
;
1990 gid_t gid
= GID_INVALID
;
1994 if (!isempty(s
->user
)) {
1995 const char *user
= s
->user
;
1997 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1999 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
2004 if (!isempty(s
->group
)) {
2005 const char *group
= s
->group
;
2007 r
= get_group_creds(&group
, &gid
, 0);
2009 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
2014 LIST_FOREACH(port
, p
, s
->ports
) {
2015 const char *path
= NULL
;
2017 if (p
->type
== SOCKET_SOCKET
)
2018 path
= socket_address_get_path(&p
->address
);
2019 else if (p
->type
== SOCKET_FIFO
)
2025 if (chown(path
, uid
, gid
) < 0) {
2026 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
2031 _exit(EXIT_SUCCESS
);
2034 r
= unit_watch_pid(UNIT(s
), pid
, true);
2042 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
2046 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
2049 if (s
->result
== SOCKET_SUCCESS
)
2052 if (s
->result
== SOCKET_SUCCESS
)
2053 unit_log_success(UNIT(s
));
2055 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
2057 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2059 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
2061 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2063 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2065 unit_unref_uid_gid(UNIT(s
), true);
2068 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2070 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2074 if (s
->result
== SOCKET_SUCCESS
)
2077 socket_unwatch_control_pid(s
);
2078 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2079 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2081 if (s
->control_command
) {
2082 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2086 socket_set_state(s
, SOCKET_STOP_POST
);
2088 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2093 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2094 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2097 static int state_to_kill_operation(Socket
*s
, SocketState state
) {
2098 if (state
== SOCKET_STOP_PRE_SIGTERM
&& unit_has_job_type(UNIT(s
), JOB_RESTART
))
2099 return KILL_RESTART
;
2101 if (state
== SOCKET_FINAL_SIGTERM
)
2102 return KILL_TERMINATE
;
2107 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2112 if (s
->result
== SOCKET_SUCCESS
)
2115 r
= unit_kill_context(
2118 state_to_kill_operation(s
, state
),
2126 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2130 socket_set_state(s
, state
);
2131 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2132 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2133 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2134 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2135 else if (state
== SOCKET_FINAL_SIGTERM
)
2136 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2138 socket_enter_dead(s
, SOCKET_SUCCESS
);
2143 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2145 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2146 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2148 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2151 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2155 if (s
->result
== SOCKET_SUCCESS
)
2158 socket_unwatch_control_pid(s
);
2159 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2160 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2162 if (s
->control_command
) {
2163 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2167 socket_set_state(s
, SOCKET_STOP_PRE
);
2169 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2174 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2175 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2178 static void socket_enter_listening(Socket
*s
) {
2182 if (!s
->accept
&& s
->flush_pending
) {
2183 log_unit_debug(UNIT(s
), "Flushing socket before listening.");
2187 r
= socket_watch_fds(s
);
2189 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2193 socket_set_state(s
, SOCKET_LISTENING
);
2197 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2200 static void socket_enter_start_post(Socket
*s
) {
2204 socket_unwatch_control_pid(s
);
2205 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2206 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2208 if (s
->control_command
) {
2209 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2211 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2215 socket_set_state(s
, SOCKET_START_POST
);
2217 socket_enter_listening(s
);
2222 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2225 static void socket_enter_start_chown(Socket
*s
) {
2230 r
= socket_open_fds(s
);
2232 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2236 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2238 socket_unwatch_control_pid(s
);
2239 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2240 s
->control_command
= NULL
;
2242 r
= socket_chown(s
, &s
->control_pid
);
2244 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2248 socket_set_state(s
, SOCKET_START_CHOWN
);
2250 socket_enter_start_post(s
);
2255 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2258 static void socket_enter_start_pre(Socket
*s
) {
2262 socket_unwatch_control_pid(s
);
2264 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
2266 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2267 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2269 if (s
->control_command
) {
2270 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2272 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2276 socket_set_state(s
, SOCKET_START_PRE
);
2278 socket_enter_start_chown(s
);
2283 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2286 static void flush_ports(Socket
*s
) {
2289 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2292 LIST_FOREACH(port
, p
, s
->ports
) {
2296 (void) flush_accept(p
->fd
);
2297 (void) flush_fd(p
->fd
);
2301 static void socket_enter_running(Socket
*s
, int cfd_in
) {
2302 /* Note that this call takes possession of the connection fd passed. It either has to assign it
2303 * somewhere or close it. */
2304 _cleanup_close_
int cfd
= cfd_in
;
2306 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2311 /* We don't take connections anymore if we are supposed to shut down anyway */
2312 if (unit_stop_pending(UNIT(s
))) {
2314 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2323 if (!ratelimit_below(&s
->trigger_limit
)) {
2324 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2325 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2330 bool pending
= false;
2333 /* If there's already a start pending don't bother to do anything */
2334 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_TRIGGERS
)
2335 if (unit_active_or_pending(other
)) {
2341 if (!UNIT_ISSET(s
->service
)) {
2342 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOENT
),
2343 "Service to activate vanished, refusing activation.");
2347 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, NULL
, &error
, NULL
);
2352 socket_set_state(s
, SOCKET_RUNNING
);
2354 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2357 if (s
->n_connections
>= s
->max_connections
) {
2358 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2363 if (s
->max_connections_per_source
> 0) {
2364 r
= socket_acquire_peer(s
, cfd
, &p
);
2365 if (ERRNO_IS_DISCONNECT(r
))
2367 if (r
< 0) /* We didn't have enough resources to acquire peer information, let's fail. */
2369 if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2370 _cleanup_free_
char *t
= NULL
;
2372 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2374 log_unit_warning(UNIT(s
),
2375 "Too many incoming connections (%u) from source %s, dropping connection.",
2376 p
->n_ref
, strnull(t
));
2381 r
= socket_load_service_unit(s
, cfd
, &service
);
2382 if (ERRNO_IS_DISCONNECT(r
))
2387 r
= unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, service
,
2388 false, UNIT_DEPENDENCY_IMPLICIT
);
2394 r
= service_set_socket_fd(SERVICE(service
), cfd
, s
, p
, s
->selinux_context_from_net
);
2395 if (ERRNO_IS_DISCONNECT(r
))
2400 TAKE_FD(cfd
); /* We passed ownership of the fd to the service now. Forget it here. */
2403 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, service
, JOB_REPLACE
, NULL
, &error
, NULL
);
2405 /* We failed to activate the new service, but it still exists. Let's make sure the
2406 * service closes and forgets the connection fd again, immediately. */
2407 service_release_socket_fd(SERVICE(service
));
2411 /* Notify clients about changed counters */
2412 unit_add_to_dbus_queue(UNIT(s
));
2423 if (ERRNO_IS_RESOURCE(r
))
2424 log_unit_warning(UNIT(s
), "Failed to queue service startup job: %s",
2425 bus_error_message(&error
, r
));
2427 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2428 cfd
>= 0 ? "template" : "non-template",
2429 bus_error_message(&error
, r
));
2431 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2434 static void socket_run_next(Socket
*s
) {
2438 assert(s
->control_command
);
2439 assert(s
->control_command
->command_next
);
2441 socket_unwatch_control_pid(s
);
2443 s
->control_command
= s
->control_command
->command_next
;
2445 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2452 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2454 if (s
->state
== SOCKET_START_POST
)
2455 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2456 else if (s
->state
== SOCKET_STOP_POST
)
2457 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2459 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2462 static int socket_start(Unit
*u
) {
2463 Socket
*s
= SOCKET(u
);
2468 /* We cannot fulfill this request right now, try again later
2470 if (IN_SET(s
->state
,
2472 SOCKET_STOP_PRE_SIGKILL
,
2473 SOCKET_STOP_PRE_SIGTERM
,
2475 SOCKET_FINAL_SIGTERM
,
2476 SOCKET_FINAL_SIGKILL
,
2480 /* Already on it! */
2481 if (IN_SET(s
->state
,
2487 /* Cannot run this without the service being around */
2488 if (UNIT_ISSET(s
->service
)) {
2491 service
= SERVICE(UNIT_DEREF(s
->service
));
2493 if (UNIT(service
)->load_state
!= UNIT_LOADED
)
2494 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
), "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2496 /* If the service is already active we cannot start the
2498 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED_BEFORE_AUTO_RESTART
, SERVICE_AUTO_RESTART
))
2499 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EBUSY
), "Socket service %s already active, refusing.", UNIT(service
)->id
);
2502 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2504 r
= unit_acquire_invocation_id(u
);
2508 s
->result
= SOCKET_SUCCESS
;
2509 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2511 u
->reset_accounting
= true;
2513 socket_enter_start_pre(s
);
2517 static int socket_stop(Unit
*u
) {
2518 Socket
*s
= SOCKET(u
);
2523 if (IN_SET(s
->state
,
2525 SOCKET_STOP_PRE_SIGTERM
,
2526 SOCKET_STOP_PRE_SIGKILL
,
2528 SOCKET_FINAL_SIGTERM
,
2529 SOCKET_FINAL_SIGKILL
))
2532 /* If there's already something running we go directly into
2534 if (IN_SET(s
->state
,
2537 SOCKET_START_POST
)) {
2538 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2542 /* If we are currently cleaning, then abort it, brutally. */
2543 if (s
->state
== SOCKET_CLEANING
) {
2544 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2548 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2550 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2554 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2555 Socket
*s
= SOCKET(u
);
2562 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2563 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2564 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2565 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2567 if (s
->control_pid
> 0)
2568 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
2570 if (s
->control_command_id
>= 0)
2571 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2573 LIST_FOREACH(port
, p
, s
->ports
) {
2579 copy
= fdset_put_dup(fds
, p
->fd
);
2581 return log_unit_warning_errno(u
, copy
, "Failed to serialize socket fd: %m");
2583 if (p
->type
== SOCKET_SOCKET
) {
2584 _cleanup_free_
char *t
= NULL
;
2586 r
= socket_address_print(&p
->address
, &t
);
2588 return log_unit_error_errno(u
, r
, "Failed to format socket address: %m");
2590 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2591 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2593 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2594 } else if (p
->type
== SOCKET_SPECIAL
)
2595 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2596 else if (p
->type
== SOCKET_MQUEUE
)
2597 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2598 else if (p
->type
== SOCKET_USB_FUNCTION
)
2599 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2601 assert(p
->type
== SOCKET_FIFO
);
2602 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2609 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2610 Socket
*s
= SOCKET(u
);
2617 if (streq(key
, "state")) {
2620 state
= socket_state_from_string(value
);
2622 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2624 s
->deserialized_state
= state
;
2625 } else if (streq(key
, "result")) {
2628 f
= socket_result_from_string(value
);
2630 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2631 else if (f
!= SOCKET_SUCCESS
)
2634 } else if (streq(key
, "n-accepted")) {
2637 if (safe_atou(value
, &k
) < 0)
2638 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2641 } else if (streq(key
, "n-refused")) {
2644 if (safe_atou(value
, &k
) < 0)
2645 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2648 } else if (streq(key
, "control-pid")) {
2651 if (parse_pid(value
, &pid
) < 0)
2652 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2654 s
->control_pid
= pid
;
2655 } else if (streq(key
, "control-command")) {
2656 SocketExecCommand id
;
2658 id
= socket_exec_command_from_string(value
);
2660 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2662 s
->control_command_id
= id
;
2663 s
->control_command
= s
->exec_command
[id
];
2665 } else if (streq(key
, "fifo")) {
2666 _cleanup_free_
char *fdv
= NULL
;
2670 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2672 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2677 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2678 log_unit_debug(u
, "Invalid fifo value: %s", fdv
);
2682 LIST_FOREACH(port
, p
, s
->ports
)
2684 p
->type
== SOCKET_FIFO
&&
2685 path_equal_or_inode_same(p
->path
, value
, 0)) {
2686 p
->fd
= fdset_remove(fds
, fd
);
2691 log_unit_debug(u
, "No matching fifo socket found: %s", value
);
2693 } else if (streq(key
, "special")) {
2694 _cleanup_free_
char *fdv
= NULL
;
2698 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2700 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2705 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2706 log_unit_debug(u
, "Invalid special value: %s", fdv
);
2710 LIST_FOREACH(port
, p
, s
->ports
)
2712 p
->type
== SOCKET_SPECIAL
&&
2713 path_equal_or_inode_same(p
->path
, value
, 0)) {
2714 p
->fd
= fdset_remove(fds
, fd
);
2719 log_unit_debug(u
, "No matching special socket found: %s", value
);
2721 } else if (streq(key
, "mqueue")) {
2722 _cleanup_free_
char *fdv
= NULL
;
2726 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2728 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2733 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2734 log_unit_debug(u
, "Invalid mqueue value: %s", fdv
);
2738 LIST_FOREACH(port
, p
, s
->ports
)
2740 p
->type
== SOCKET_MQUEUE
&&
2741 streq(p
->path
, value
)) {
2742 p
->fd
= fdset_remove(fds
, fd
);
2747 log_unit_debug(u
, "No matching mqueue socket found: %s", value
);
2749 } else if (streq(key
, "socket")) {
2750 _cleanup_free_
char *fdv
= NULL
, *typev
= NULL
;
2754 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2756 log_unit_debug(u
, "Failed to parse socket fd from value: %s", value
);
2761 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2762 log_unit_debug(u
, "Invalid socket fd: %s", fdv
);
2766 r
= extract_first_word(&value
, &typev
, NULL
, 0);
2768 log_unit_debug(u
, "Failed to parse socket type from value: %s", value
);
2772 if (safe_atoi(typev
, &type
) < 0 || type
< 0) {
2773 log_unit_debug(u
, "Invalid socket type: %s", typev
);
2777 LIST_FOREACH(port
, p
, s
->ports
)
2779 socket_address_is(&p
->address
, value
, type
)) {
2780 p
->fd
= fdset_remove(fds
, fd
);
2785 log_unit_debug(u
, "No matching %s socket found: %s",
2786 socket_address_type_to_string(type
), value
);
2788 } else if (streq(key
, "netlink")) {
2789 _cleanup_free_
char *fdv
= NULL
;
2793 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2795 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2800 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2801 log_unit_debug(u
, "Invalid socket value: %s", fdv
);
2805 LIST_FOREACH(port
, p
, s
->ports
)
2807 socket_address_is_netlink(&p
->address
, value
)) {
2808 p
->fd
= fdset_remove(fds
, fd
);
2813 log_unit_debug(u
, "No matching netlink socket found: %s", value
);
2815 } else if (streq(key
, "ffs")) {
2816 _cleanup_free_
char *fdv
= NULL
;
2820 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2822 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2827 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2828 log_unit_debug(u
, "Invalid ffs value: %s", fdv
);
2832 LIST_FOREACH(port
, p
, s
->ports
)
2834 p
->type
== SOCKET_USB_FUNCTION
&&
2835 path_equal_or_inode_same(p
->path
, value
, 0)) {
2836 p
->fd
= fdset_remove(fds
, fd
);
2841 log_unit_debug(u
, "No matching ffs socket found: %s", value
);
2844 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2849 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2850 Socket
*s
= SOCKET(u
);
2854 LIST_FOREACH(port
, p
, s
->ports
) {
2857 if (p
->type
!= SOCKET_SOCKET
)
2863 FDSET_FOREACH(fd
, fds
) {
2864 if (socket_address_matches_fd(&p
->address
, fd
)) {
2865 p
->fd
= fdset_remove(fds
, fd
);
2866 s
->deserialized_state
= SOCKET_LISTENING
;
2873 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2876 return state_translation_table
[SOCKET(u
)->state
];
2879 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2882 return socket_state_to_string(SOCKET(u
)->state
);
2885 const char* socket_port_type_to_string(SocketPort
*p
) {
2893 switch (p
->address
.type
) {
2901 case SOCK_SEQPACKET
:
2902 return "SequentialPacket";
2905 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2913 case SOCKET_SPECIAL
:
2917 return "MessageQueue";
2922 case SOCKET_USB_FUNCTION
:
2923 return "USBFunction";
2930 SocketType
socket_port_type_from_string(const char *s
) {
2933 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2934 return SOCKET_SOCKET
;
2935 else if (streq(s
, "Special"))
2936 return SOCKET_SPECIAL
;
2937 else if (streq(s
, "MessageQueue"))
2938 return SOCKET_MQUEUE
;
2939 else if (streq(s
, "FIFO"))
2941 else if (streq(s
, "USBFunction"))
2942 return SOCKET_USB_FUNCTION
;
2944 return _SOCKET_TYPE_INVALID
;
2947 _pure_
static bool socket_may_gc(Unit
*u
) {
2948 Socket
*s
= SOCKET(u
);
2952 return s
->n_connections
== 0;
2955 static int socket_accept_do(Socket
*s
, int fd
) {
2961 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2963 /* Convert transient network errors into clean and well-defined EAGAIN */
2964 return ERRNO_IS_ACCEPT_AGAIN(errno
) ? -EAGAIN
: -errno
;
2969 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2970 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
2978 /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
2979 * connection socket is also properly associated with the cgroup. */
2981 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2984 r
= bpf_firewall_supported();
2987 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2990 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2991 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2993 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2995 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2999 pair
[0] = safe_close(pair
[0]);
3001 cfd
= socket_accept_do(s
, fd
);
3002 if (cfd
== -EAGAIN
) /* spurious accept() */
3003 _exit(EXIT_SUCCESS
);
3005 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3006 _exit(EXIT_FAILURE
);
3009 r
= send_one_fd(pair
[1], cfd
, 0);
3011 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
3012 _exit(EXIT_FAILURE
);
3015 _exit(EXIT_SUCCESS
);
3018 pair
[1] = safe_close(pair
[1]);
3019 cfd
= receive_one_fd(pair
[0], 0);
3021 /* We synchronously wait for the helper, as it shouldn't be slow */
3022 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
3028 /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3029 * this is a spurious accept(), let's convert that back to EAGAIN here. */
3033 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
3038 cfd
= socket_accept_do(s
, fd
);
3039 if (cfd
== -EAGAIN
) /* spurious accept(), skip it silently */
3042 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3047 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3048 SocketPort
*p
= ASSERT_PTR(userdata
);
3053 if (p
->socket
->state
!= SOCKET_LISTENING
)
3056 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
3058 if (revents
!= EPOLLIN
) {
3059 if (revents
& EPOLLHUP
)
3060 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.");
3062 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
3066 if (p
->socket
->accept
&&
3067 p
->type
== SOCKET_SOCKET
&&
3068 socket_address_can_accept(&p
->address
)) {
3070 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
3071 if (cfd
== -EAGAIN
) /* Spurious accept() */
3076 socket_apply_socket_options(p
->socket
, p
, cfd
);
3079 socket_enter_running(p
->socket
, cfd
);
3083 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
3087 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3088 Socket
*s
= SOCKET(u
);
3094 if (pid
!= s
->control_pid
)
3099 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
3101 else if (code
== CLD_EXITED
)
3102 f
= SOCKET_FAILURE_EXIT_CODE
;
3103 else if (code
== CLD_KILLED
)
3104 f
= SOCKET_FAILURE_SIGNAL
;
3105 else if (code
== CLD_DUMPED
)
3106 f
= SOCKET_FAILURE_CORE_DUMP
;
3108 assert_not_reached();
3110 if (s
->control_command
) {
3111 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3113 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3117 unit_log_process_exit(
3120 socket_exec_command_to_string(s
->control_command_id
),
3121 f
== SOCKET_SUCCESS
,
3124 if (s
->result
== SOCKET_SUCCESS
)
3127 if (s
->control_command
&&
3128 s
->control_command
->command_next
&&
3129 f
== SOCKET_SUCCESS
) {
3131 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
3134 s
->control_command
= NULL
;
3135 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3137 /* No further commands for this step, so let's figure
3138 * out what to do next */
3140 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
3144 case SOCKET_START_PRE
:
3145 if (f
== SOCKET_SUCCESS
)
3146 socket_enter_start_chown(s
);
3148 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3151 case SOCKET_START_CHOWN
:
3152 if (f
== SOCKET_SUCCESS
)
3153 socket_enter_start_post(s
);
3155 socket_enter_stop_pre(s
, f
);
3158 case SOCKET_START_POST
:
3159 if (f
== SOCKET_SUCCESS
)
3160 socket_enter_listening(s
);
3162 socket_enter_stop_pre(s
, f
);
3165 case SOCKET_STOP_PRE
:
3166 case SOCKET_STOP_PRE_SIGTERM
:
3167 case SOCKET_STOP_PRE_SIGKILL
:
3168 socket_enter_stop_post(s
, f
);
3171 case SOCKET_STOP_POST
:
3172 case SOCKET_FINAL_SIGTERM
:
3173 case SOCKET_FINAL_SIGKILL
:
3174 socket_enter_dead(s
, f
);
3177 case SOCKET_CLEANING
:
3179 if (s
->clean_result
== SOCKET_SUCCESS
)
3180 s
->clean_result
= f
;
3182 socket_enter_dead(s
, SOCKET_SUCCESS
);
3186 assert_not_reached();
3190 /* Notify clients about changed exit status */
3191 unit_add_to_dbus_queue(u
);
3194 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3195 Socket
*s
= SOCKET(userdata
);
3198 assert(s
->timer_event_source
== source
);
3202 case SOCKET_START_PRE
:
3203 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3204 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3207 case SOCKET_START_CHOWN
:
3208 case SOCKET_START_POST
:
3209 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3210 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3213 case SOCKET_STOP_PRE
:
3214 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3215 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3218 case SOCKET_STOP_PRE_SIGTERM
:
3219 if (s
->kill_context
.send_sigkill
) {
3220 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3221 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3223 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3224 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3228 case SOCKET_STOP_PRE_SIGKILL
:
3229 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3230 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3233 case SOCKET_STOP_POST
:
3234 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3235 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3238 case SOCKET_FINAL_SIGTERM
:
3239 if (s
->kill_context
.send_sigkill
) {
3240 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3241 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3243 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3244 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3248 case SOCKET_FINAL_SIGKILL
:
3249 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3250 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3253 case SOCKET_CLEANING
:
3254 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
3256 if (s
->clean_result
== SOCKET_SUCCESS
)
3257 s
->clean_result
= SOCKET_FAILURE_TIMEOUT
;
3259 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, 0);
3263 assert_not_reached();
3269 int socket_collect_fds(Socket
*s
, int **fds
) {
3270 size_t k
= 0, n
= 0;
3276 /* Called from the service code for requesting our fds */
3278 LIST_FOREACH(port
, p
, s
->ports
) {
3281 n
+= p
->n_auxiliary_fds
;
3293 LIST_FOREACH(port
, p
, s
->ports
) {
3296 for (size_t i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3297 rfds
[k
++] = p
->auxiliary_fds
[i
];
3306 static void socket_reset_failed(Unit
*u
) {
3307 Socket
*s
= SOCKET(u
);
3311 if (s
->state
== SOCKET_FAILED
)
3312 socket_set_state(s
, SOCKET_DEAD
);
3314 s
->result
= SOCKET_SUCCESS
;
3315 s
->clean_result
= SOCKET_SUCCESS
;
3318 void socket_connection_unref(Socket
*s
) {
3321 /* The service is dead. Yay!
3323 * This is strictly for one-instance-per-connection
3326 assert(s
->n_connections
> 0);
3329 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3332 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3333 Socket
*s
= SOCKET(u
);
3338 /* Filter out invocations with bogus state */
3339 assert(UNIT_IS_LOAD_COMPLETE(other
->load_state
));
3340 assert(other
->type
== UNIT_SERVICE
);
3342 /* Don't propagate state changes from the service if we are already down */
3343 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3346 /* We don't care for the service state if we are in Accept=yes mode */
3350 /* Propagate start limit hit state */
3351 if (other
->start_limit_hit
) {
3352 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3356 /* Don't propagate anything if there's still a job queued */
3360 if (IN_SET(SERVICE(other
)->state
,
3361 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
3362 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3363 SERVICE_AUTO_RESTART
))
3364 socket_enter_listening(s
);
3366 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3367 socket_set_state(s
, SOCKET_RUNNING
);
3370 static int socket_kill(Unit
*u
, KillWho who
, int signo
, int code
, int value
, sd_bus_error
*error
) {
3371 return unit_kill_common(u
, who
, signo
, code
, value
, -1, SOCKET(u
)->control_pid
, error
);
3374 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3375 Socket
*s
= SOCKET(u
);
3379 if (!s
->timer_event_source
)
3382 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3385 if (t
== USEC_INFINITY
)
3392 char *socket_fdname(Socket
*s
) {
3395 /* Returns the name to use for $LISTEN_NAMES. If the user
3396 * didn't specify anything specifically, use the socket unit's
3397 * name as fallback. */
3399 return s
->fdname
?: UNIT(s
)->id
;
3402 static int socket_control_pid(Unit
*u
) {
3403 Socket
*s
= SOCKET(u
);
3407 return s
->control_pid
;
3410 static int socket_clean(Unit
*u
, ExecCleanMask mask
) {
3411 _cleanup_strv_free_
char **l
= NULL
;
3412 Socket
*s
= SOCKET(u
);
3418 if (s
->state
!= SOCKET_DEAD
)
3421 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
3425 if (strv_isempty(l
))
3428 socket_unwatch_control_pid(s
);
3429 s
->clean_result
= SOCKET_SUCCESS
;
3430 s
->control_command
= NULL
;
3431 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3433 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->exec_context
.timeout_clean_usec
));
3437 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
3441 socket_set_state(s
, SOCKET_CLEANING
);
3446 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
3447 s
->clean_result
= SOCKET_FAILURE_RESOURCES
;
3448 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
3452 static int socket_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
3453 Socket
*s
= SOCKET(u
);
3457 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
3460 static int socket_can_start(Unit
*u
) {
3461 Socket
*s
= SOCKET(u
);
3466 r
= unit_test_start_limit(u
);
3468 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
3475 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3476 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3477 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3478 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3479 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3480 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3483 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3485 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3486 [SOCKET_SUCCESS
] = "success",
3487 [SOCKET_FAILURE_RESOURCES
] = "resources",
3488 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3489 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3490 [SOCKET_FAILURE_SIGNAL
] = "signal",
3491 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3492 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3493 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3494 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3497 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3499 static const char* const socket_timestamping_table
[_SOCKET_TIMESTAMPING_MAX
] = {
3500 [SOCKET_TIMESTAMPING_OFF
] = "off",
3501 [SOCKET_TIMESTAMPING_US
] = "us",
3502 [SOCKET_TIMESTAMPING_NS
] = "ns",
3505 DEFINE_STRING_TABLE_LOOKUP(socket_timestamping
, SocketTimestamping
);
3507 SocketTimestamping
socket_timestamping_from_string_harder(const char *p
) {
3508 SocketTimestamping t
;
3512 return _SOCKET_TIMESTAMPING_INVALID
;
3514 t
= socket_timestamping_from_string(p
);
3518 /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3520 if (streq(p
, "nsec"))
3521 return SOCKET_TIMESTAMPING_NS
;
3522 if (STR_IN_SET(p
, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
3523 return SOCKET_TIMESTAMPING_US
;
3525 r
= parse_boolean(p
);
3527 return _SOCKET_TIMESTAMPING_INVALID
;
3529 return r
? SOCKET_TIMESTAMPING_NS
: SOCKET_TIMESTAMPING_OFF
; /* If boolean yes, default to ns accuracy */
3532 const UnitVTable socket_vtable
= {
3533 .object_size
= sizeof(Socket
),
3534 .exec_context_offset
= offsetof(Socket
, exec_context
),
3535 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3536 .kill_context_offset
= offsetof(Socket
, kill_context
),
3537 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3543 .private_section
= "Socket",
3545 .can_transient
= true,
3546 .can_trigger
= true,
3549 .init
= socket_init
,
3550 .done
= socket_done
,
3551 .load
= socket_load
,
3553 .coldplug
= socket_coldplug
,
3555 .dump
= socket_dump
,
3557 .start
= socket_start
,
3558 .stop
= socket_stop
,
3560 .kill
= socket_kill
,
3561 .clean
= socket_clean
,
3562 .can_clean
= socket_can_clean
,
3564 .get_timeout
= socket_get_timeout
,
3566 .serialize
= socket_serialize
,
3567 .deserialize_item
= socket_deserialize_item
,
3568 .distribute_fds
= socket_distribute_fds
,
3570 .active_state
= socket_active_state
,
3571 .sub_state_to_string
= socket_sub_state_to_string
,
3573 .will_restart
= unit_will_restart_default
,
3575 .may_gc
= socket_may_gc
,
3577 .sigchld_event
= socket_sigchld_event
,
3579 .trigger_notify
= socket_trigger_notify
,
3581 .reset_failed
= socket_reset_failed
,
3583 .control_pid
= socket_control_pid
,
3585 .bus_set_property
= bus_socket_set_property
,
3586 .bus_commit_properties
= bus_socket_commit_properties
,
3588 .status_message_formats
= {
3589 .finished_start_job
= {
3590 [JOB_DONE
] = "Listening on %s.",
3591 [JOB_FAILED
] = "Failed to listen on %s.",
3592 [JOB_TIMEOUT
] = "Timed out starting %s.",
3594 .finished_stop_job
= {
3595 [JOB_DONE
] = "Closed %s.",
3596 [JOB_FAILED
] = "Failed stopping %s.",
3597 [JOB_TIMEOUT
] = "Timed out stopping %s.",
3601 .can_start
= socket_can_start
,