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
->defaults
.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
->defaults
.std_output
;
98 s
->exec_context
.std_error
= u
->manager
->defaults
.std_error
;
100 s
->control_pid
= PIDREF_NULL
;
101 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
103 s
->trigger_limit
.interval
= USEC_INFINITY
;
104 s
->trigger_limit
.burst
= UINT_MAX
;
107 static void socket_unwatch_control_pid(Socket
*s
) {
110 if (!pidref_is_set(&s
->control_pid
))
113 unit_unwatch_pid(UNIT(s
), s
->control_pid
.pid
);
114 pidref_done(&s
->control_pid
);
117 static void socket_cleanup_fd_list(SocketPort
*p
) {
120 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
121 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
122 p
->n_auxiliary_fds
= 0;
125 SocketPort
*socket_port_free(SocketPort
*p
) {
129 sd_event_source_unref(p
->event_source
);
131 socket_cleanup_fd_list(p
);
138 void socket_free_ports(Socket
*s
) {
141 LIST_CLEAR(port
, s
->ports
, socket_port_free
);
144 static void socket_done(Unit
*u
) {
145 Socket
*s
= SOCKET(u
);
150 socket_free_ports(s
);
152 while ((p
= set_steal_first(s
->peers_by_address
)))
155 s
->peers_by_address
= set_free(s
->peers_by_address
);
157 s
->exec_runtime
= exec_runtime_free(s
->exec_runtime
);
158 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
159 s
->control_command
= NULL
;
161 socket_unwatch_control_pid(s
);
163 unit_ref_unset(&s
->service
);
165 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
166 s
->bind_to_device
= mfree(s
->bind_to_device
);
168 s
->smack
= mfree(s
->smack
);
169 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
170 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
172 strv_free(s
->symlinks
);
174 s
->user
= mfree(s
->user
);
175 s
->group
= mfree(s
->group
);
177 s
->fdname
= mfree(s
->fdname
);
179 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
182 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
187 if (s
->timer_event_source
) {
188 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
192 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
195 if (usec
== USEC_INFINITY
)
198 r
= sd_event_add_time(
199 UNIT(s
)->manager
->event
,
200 &s
->timer_event_source
,
203 socket_dispatch_timer
, s
);
207 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
212 static bool have_non_accept_socket(Socket
*s
) {
218 LIST_FOREACH(port
, p
, s
->ports
) {
220 if (p
->type
!= SOCKET_SOCKET
)
223 if (!socket_address_can_accept(&p
->address
))
230 static int socket_add_mount_dependencies(Socket
*s
) {
235 LIST_FOREACH(port
, p
, s
->ports
) {
236 const char *path
= NULL
;
238 if (p
->type
== SOCKET_SOCKET
)
239 path
= socket_address_get_path(&p
->address
);
240 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
246 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
254 static int socket_add_device_dependencies(Socket
*s
) {
259 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
262 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
263 return unit_add_node_dependency(UNIT(s
), t
, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
266 static int socket_add_default_dependencies(Socket
*s
) {
270 if (!UNIT(s
)->default_dependencies
)
273 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
277 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
278 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
283 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
286 static bool socket_has_exec(Socket
*s
) {
290 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
291 if (s
->exec_command
[i
])
297 static int socket_add_extras(Socket
*s
) {
303 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
304 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
305 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
306 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
307 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
308 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
309 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
310 * service starts are typical. */
312 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
313 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
315 if (s
->trigger_limit
.burst
== UINT_MAX
) {
317 s
->trigger_limit
.burst
= 200;
319 s
->trigger_limit
.burst
= 20;
322 if (have_non_accept_socket(s
)) {
324 if (!UNIT_DEREF(s
->service
)) {
327 r
= unit_load_related_unit(u
, ".service", &x
);
331 unit_ref_set(&s
->service
, u
, x
);
334 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
339 r
= socket_add_mount_dependencies(s
);
343 r
= socket_add_device_dependencies(s
);
347 r
= unit_patch_contexts(u
);
351 if (socket_has_exec(s
)) {
352 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
357 r
= unit_set_default_slice(u
);
361 r
= socket_add_default_dependencies(s
);
368 static const char *socket_find_symlink_target(Socket
*s
) {
369 const char *found
= NULL
;
371 LIST_FOREACH(port
, p
, s
->ports
) {
372 const char *f
= NULL
;
381 f
= socket_address_get_path(&p
->address
);
399 static int socket_verify(Socket
*s
) {
401 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
404 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
406 if (s
->accept
&& have_non_accept_socket(s
))
407 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
409 if (s
->accept
&& s
->max_connections
<= 0)
410 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "MaxConnection= setting too small. Refusing.");
412 if (s
->accept
&& UNIT_DEREF(s
->service
))
413 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Explicit service configuration for accepting socket units not supported. Refusing.");
415 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
)
416 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
418 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
))
419 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.");
424 static void peer_address_hash_func(const SocketPeer
*s
, struct siphash
*state
) {
427 if (s
->peer
.sa
.sa_family
== AF_INET
)
428 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
429 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
430 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
431 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
432 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
434 assert_not_reached();
437 static int peer_address_compare_func(const SocketPeer
*x
, const SocketPeer
*y
) {
440 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
444 switch (x
->peer
.sa
.sa_family
) {
446 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
448 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
450 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
452 assert_not_reached();
455 DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops
, SocketPeer
, peer_address_hash_func
, peer_address_compare_func
);
457 static int socket_load(Unit
*u
) {
458 Socket
*s
= SOCKET(u
);
462 assert(u
->load_state
== UNIT_STUB
);
464 r
= unit_load_fragment_and_dropin(u
, true);
468 if (u
->load_state
!= UNIT_LOADED
)
471 /* This is a new unit? Then let's add in some extras */
472 r
= socket_add_extras(s
);
476 return socket_verify(s
);
479 static SocketPeer
*socket_peer_new(void) {
482 p
= new(SocketPeer
, 1);
492 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
496 set_remove(p
->socket
->peers_by_address
, p
);
501 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
503 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
504 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
506 .peer_salen
= sizeof(union sockaddr_union
),
513 if (getpeername(fd
, &sa
.peer
.sa
, &sa
.peer_salen
) < 0)
514 return log_unit_error_errno(UNIT(s
), errno
, "getpeername failed: %m");
516 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
521 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
525 i
= set_get(s
->peers_by_address
, &sa
);
527 *p
= socket_peer_ref(i
);
531 remote
= socket_peer_new();
535 remote
->peer
= sa
.peer
;
536 remote
->peer_salen
= sa
.peer_salen
;
538 r
= set_put(s
->peers_by_address
, remote
);
544 *p
= TAKE_PTR(remote
);
548 static const char* listen_lookup(int family
, int type
) {
550 if (family
== AF_NETLINK
)
551 return "ListenNetlink";
553 if (type
== SOCK_STREAM
)
554 return "ListenStream";
555 else if (type
== SOCK_DGRAM
)
556 return "ListenDatagram";
557 else if (type
== SOCK_SEQPACKET
)
558 return "ListenSequentialPacket";
560 assert_not_reached();
564 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
565 Socket
*s
= SOCKET(u
);
566 const char *prefix2
, *str
;
571 prefix
= strempty(prefix
);
572 prefix2
= strjoina(prefix
, "\t");
575 "%sSocket State: %s\n"
577 "%sClean Result: %s\n"
578 "%sBindIPv6Only: %s\n"
580 "%sSocketMode: %04o\n"
581 "%sDirectoryMode: %04o\n"
585 "%sTransparent: %s\n"
587 "%sPassCredentials: %s\n"
588 "%sPassSecurity: %s\n"
589 "%sPassPacketInfo: %s\n"
590 "%sTCPCongestion: %s\n"
591 "%sRemoveOnStop: %s\n"
593 "%sFileDescriptorName: %s\n"
594 "%sSELinuxContextFromNet: %s\n",
595 prefix
, socket_state_to_string(s
->state
),
596 prefix
, socket_result_to_string(s
->result
),
597 prefix
, socket_result_to_string(s
->clean_result
),
598 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
600 prefix
, s
->socket_mode
,
601 prefix
, s
->directory_mode
,
602 prefix
, yes_no(s
->keep_alive
),
603 prefix
, yes_no(s
->no_delay
),
604 prefix
, yes_no(s
->free_bind
),
605 prefix
, yes_no(s
->transparent
),
606 prefix
, yes_no(s
->broadcast
),
607 prefix
, yes_no(s
->pass_cred
),
608 prefix
, yes_no(s
->pass_sec
),
609 prefix
, yes_no(s
->pass_pktinfo
),
610 prefix
, strna(s
->tcp_congestion
),
611 prefix
, yes_no(s
->remove_on_stop
),
612 prefix
, yes_no(s
->writable
),
613 prefix
, socket_fdname(s
),
614 prefix
, yes_no(s
->selinux_context_from_net
));
616 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
)
618 "%sTimestamping: %s\n",
619 prefix
, socket_timestamping_to_string(s
->timestamping
));
621 if (pidref_is_set(&s
->control_pid
))
623 "%sControl PID: "PID_FMT
"\n",
624 prefix
, s
->control_pid
.pid
);
626 if (s
->bind_to_device
)
628 "%sBindToDevice: %s\n",
629 prefix
, s
->bind_to_device
);
634 "%sNConnections: %u\n"
635 "%sMaxConnections: %u\n"
636 "%sMaxConnectionsPerSource: %u\n",
637 prefix
, s
->n_accepted
,
638 prefix
, s
->n_connections
,
639 prefix
, s
->max_connections
,
640 prefix
, s
->max_connections_per_source
);
643 "%sFlushPending: %s\n",
644 prefix
, yes_no(s
->flush_pending
));
647 if (s
->priority
>= 0)
650 prefix
, s
->priority
);
652 if (s
->receive_buffer
> 0)
654 "%sReceiveBuffer: %zu\n",
655 prefix
, s
->receive_buffer
);
657 if (s
->send_buffer
> 0)
659 "%sSendBuffer: %zu\n",
660 prefix
, s
->send_buffer
);
672 if (s
->pipe_size
> 0)
675 prefix
, s
->pipe_size
);
682 if (s
->mq_maxmsg
> 0)
684 "%sMessageQueueMaxMessages: %li\n",
685 prefix
, s
->mq_maxmsg
);
687 if (s
->mq_msgsize
> 0)
689 "%sMessageQueueMessageSize: %li\n",
690 prefix
, s
->mq_msgsize
);
695 prefix
, yes_no(s
->reuse_port
));
699 "%sSmackLabel: %s\n",
704 "%sSmackLabelIPIn: %s\n",
705 prefix
, s
->smack_ip_in
);
709 "%sSmackLabelIPOut: %s\n",
710 prefix
, s
->smack_ip_out
);
712 if (!isempty(s
->user
) || !isempty(s
->group
))
715 "%sSocketGroup: %s\n",
716 prefix
, strna(s
->user
),
717 prefix
, strna(s
->group
));
719 if (timestamp_is_set(s
->keep_alive_time
))
721 "%sKeepAliveTimeSec: %s\n",
722 prefix
, FORMAT_TIMESPAN(s
->keep_alive_time
, USEC_PER_SEC
));
724 if (s
->keep_alive_interval
> 0)
726 "%sKeepAliveIntervalSec: %s\n",
727 prefix
, FORMAT_TIMESPAN(s
->keep_alive_interval
, USEC_PER_SEC
));
729 if (s
->keep_alive_cnt
> 0)
731 "%sKeepAliveProbes: %u\n",
732 prefix
, s
->keep_alive_cnt
);
734 if (s
->defer_accept
> 0)
736 "%sDeferAcceptSec: %s\n",
737 prefix
, FORMAT_TIMESPAN(s
->defer_accept
, USEC_PER_SEC
));
739 LIST_FOREACH(port
, p
, s
->ports
) {
742 case SOCKET_SOCKET
: {
743 _cleanup_free_
char *k
= NULL
;
746 r
= socket_address_print(&p
->address
, &k
);
749 fprintf(f
, "%s%s: %m\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
));
751 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), k
);
755 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
757 case SOCKET_USB_FUNCTION
:
758 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
761 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
764 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
769 "%sTriggerLimitIntervalSec: %s\n"
770 "%sTriggerLimitBurst: %u\n",
771 prefix
, FORMAT_TIMESPAN(s
->trigger_limit
.interval
, USEC_PER_SEC
),
772 prefix
, s
->trigger_limit
.burst
);
774 str
= ip_protocol_to_name(s
->socket_protocol
);
776 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
778 if (!strv_isempty(s
->symlinks
)) {
779 fprintf(f
, "%sSymlinks:", prefix
);
780 STRV_FOREACH(q
, s
->symlinks
)
781 fprintf(f
, " %s", *q
);
787 "%sTimeoutSec: %s\n",
788 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
790 exec_context_dump(&s
->exec_context
, f
, prefix
);
791 kill_context_dump(&s
->kill_context
, f
, prefix
);
793 for (SocketExecCommand c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
794 if (!s
->exec_command
[c
])
797 fprintf(f
, "%s-> %s:\n",
798 prefix
, socket_exec_command_to_string(c
));
800 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
803 cgroup_context_dump(UNIT(s
), f
, prefix
);
806 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
809 union sockaddr_union local
, remote
;
815 if (getsockname(fd
, &local
.sa
, &l
) < 0)
819 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
822 switch (local
.sa
.sa_family
) {
826 a
= be32toh(local
.in
.sin_addr
.s_addr
),
827 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
830 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
832 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
833 be16toh(local
.in
.sin_port
),
834 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
835 be16toh(remote
.in
.sin_port
)) < 0)
842 static const unsigned char ipv4_prefix
[] = {
843 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
846 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
847 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
849 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
850 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
853 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
855 a
[0], a
[1], a
[2], a
[3],
856 be16toh(local
.in6
.sin6_port
),
857 b
[0], b
[1], b
[2], b
[3],
858 be16toh(remote
.in6
.sin6_port
)) < 0)
864 IN6_ADDR_TO_STRING(&local
.in6
.sin6_addr
),
865 be16toh(local
.in6
.sin6_port
),
866 IN6_ADDR_TO_STRING(&remote
.in6
.sin6_addr
),
867 be16toh(remote
.in6
.sin6_port
)) < 0)
878 k
= getpeercred(fd
, &ucred
);
881 "%u-"PID_FMT
"-"UID_FMT
,
882 nr
, ucred
.pid
, ucred
.uid
) < 0)
884 } else if (k
== -ENODATA
) {
885 /* This handles the case where somebody is
886 * connecting from another pid/uid namespace
887 * (e.g. from outside of our container). */
902 local
.vm
.svm_cid
, local
.vm
.svm_port
,
903 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
909 assert_not_reached();
916 static void socket_close_fds(Socket
*s
) {
919 LIST_FOREACH(port
, p
, s
->ports
) {
922 was_open
= p
->fd
>= 0;
924 p
->event_source
= sd_event_source_disable_unref(p
->event_source
);
925 p
->fd
= safe_close(p
->fd
);
926 socket_cleanup_fd_list(p
);
928 /* One little note: we should normally not delete any sockets in the file system here! After all some
929 * other process we spawned might still have a reference of this fd and wants to continue to use
930 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
931 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
932 * anyway, but only then. */
934 if (!was_open
|| !s
->remove_on_stop
)
940 (void) unlink(p
->path
);
944 (void) mq_unlink(p
->path
);
948 (void) socket_address_unlink(&p
->address
);
956 if (s
->remove_on_stop
)
957 STRV_FOREACH(i
, s
->symlinks
)
960 /* Note that we don't return NULL here, since s has not been freed. */
963 static void socket_apply_socket_options(Socket
*s
, SocketPort
*p
, int fd
) {
971 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
973 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
976 if (timestamp_is_set(s
->keep_alive_time
)) {
977 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
979 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
982 if (s
->keep_alive_interval
> 0) {
983 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
985 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
988 if (s
->keep_alive_cnt
> 0) {
989 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
991 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
994 if (s
->defer_accept
> 0) {
995 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
997 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
1001 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1002 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1004 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1006 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1008 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1013 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1015 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1019 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1021 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1025 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1027 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1030 if (s
->pass_pktinfo
) {
1031 r
= socket_set_recvpktinfo(fd
, socket_address_family(&p
->address
), true);
1033 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable packet info socket option: %m");
1036 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
) {
1037 r
= setsockopt_int(fd
, SOL_SOCKET
,
1038 s
->timestamping
== SOCKET_TIMESTAMPING_NS
? SO_TIMESTAMPNS
: SO_TIMESTAMP
,
1041 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable timestamping socket option, ignoring: %m");
1044 if (s
->priority
>= 0) {
1045 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1047 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1050 if (s
->receive_buffer
> 0) {
1051 r
= fd_set_rcvbuf(fd
, s
->receive_buffer
, false);
1053 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1054 "SO_RCVBUF/SO_RCVBUFFORCE failed: %m");
1057 if (s
->send_buffer
> 0) {
1058 r
= fd_set_sndbuf(fd
, s
->send_buffer
, false);
1060 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1061 "SO_SNDBUF/SO_SNDBUFFORCE failed: %m");
1065 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1067 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1070 if (s
->ip_tos
>= 0) {
1071 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1073 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1076 if (s
->ip_ttl
>= 0) {
1077 r
= socket_set_ttl(fd
, socket_address_family(&p
->address
), s
->ip_ttl
);
1079 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1082 if (s
->tcp_congestion
)
1083 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1084 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1086 if (s
->smack_ip_in
) {
1087 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1089 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1092 if (s
->smack_ip_out
) {
1093 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1095 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1099 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1105 if (s
->pipe_size
> 0)
1106 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1107 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1110 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1112 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1116 static int fifo_address_create(
1118 mode_t directory_mode
,
1119 mode_t socket_mode
) {
1121 _cleanup_close_
int fd
= -EBADF
;
1128 (void) mkdir_parents_label(path
, directory_mode
);
1130 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1134 /* Enforce the right access mode for the fifo */
1135 old_mask
= umask(~socket_mode
);
1137 /* Include the original umask in our mask */
1138 (void) umask(~socket_mode
| old_mask
);
1140 r
= mkfifo(path
, socket_mode
);
1141 (void) umask(old_mask
);
1143 if (r
< 0 && errno
!= EEXIST
) {
1148 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1154 mac_selinux_create_file_clear();
1156 if (fstat(fd
, &st
) < 0) {
1161 if (!S_ISFIFO(st
.st_mode
) ||
1162 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1163 st
.st_uid
!= getuid() ||
1164 st
.st_gid
!= getgid()) {
1172 mac_selinux_create_file_clear();
1176 static int special_address_create(const char *path
, bool writable
) {
1177 _cleanup_close_
int fd
= -EBADF
;
1182 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1186 if (fstat(fd
, &st
) < 0)
1189 /* Check whether this is a /proc, /sys or /dev file or char device */
1190 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1196 static int usbffs_address_create(const char *path
) {
1197 _cleanup_close_
int fd
= -EBADF
;
1202 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1206 if (fstat(fd
, &st
) < 0)
1209 /* Check whether this is a regular file (ffs endpoint) */
1210 if (!S_ISREG(st
.st_mode
))
1216 static int mq_address_create(
1222 _cleanup_close_
int fd
= -EBADF
;
1225 struct mq_attr _attr
, *attr
= NULL
;
1229 if (maxmsg
> 0 && msgsize
> 0) {
1230 _attr
= (struct mq_attr
) {
1231 .mq_flags
= O_NONBLOCK
,
1232 .mq_maxmsg
= maxmsg
,
1233 .mq_msgsize
= msgsize
,
1238 /* Enforce the right access mode for the mq */
1239 old_mask
= umask(~mq_mode
);
1241 /* Include the original umask in our mask */
1242 (void) umask(~mq_mode
| old_mask
);
1243 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1244 (void) umask(old_mask
);
1249 if (fstat(fd
, &st
) < 0)
1252 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1253 st
.st_uid
!= getuid() ||
1254 st
.st_gid
!= getgid())
1260 static int socket_symlink(Socket
*s
) {
1266 p
= socket_find_symlink_target(s
);
1270 STRV_FOREACH(i
, s
->symlinks
) {
1271 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1273 r
= symlink_idempotent(p
, *i
, false);
1275 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1276 /* If there's already something where we want to create the symlink, and the destructive
1277 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1280 if (unlink(*i
) >= 0)
1281 r
= symlink_idempotent(p
, *i
, false);
1285 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s %s %s, ignoring: %m",
1286 p
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *i
);
1292 static int usbffs_write_descs(int fd
, Service
*s
) {
1295 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1298 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1302 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1305 static int usbffs_select_ep(const struct dirent
*d
) {
1306 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1309 static int usbffs_dispatch_eps(SocketPort
*p
) {
1310 _cleanup_free_
struct dirent
**ent
= NULL
;
1314 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1319 p
->auxiliary_fds
= new(int, n
);
1320 if (!p
->auxiliary_fds
) {
1325 p
->n_auxiliary_fds
= n
;
1328 for (size_t i
= 0; i
< n
; ++i
) {
1329 _cleanup_free_
char *ep
= NULL
;
1331 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1339 r
= usbffs_address_create(ep
);
1343 p
->auxiliary_fds
[k
++] = r
;
1350 close_many(p
->auxiliary_fds
, k
);
1351 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1352 p
->n_auxiliary_fds
= 0;
1355 free_many((void**) ent
, n
);
1359 int socket_load_service_unit(Socket
*s
, int cfd
, Unit
**ret
) {
1360 /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1362 * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1366 if (UNIT_ISSET(s
->service
)) {
1367 *ret
= UNIT_DEREF(s
->service
);
1374 /* Build the instance name and load the unit */
1375 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
1378 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
1383 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
1385 if (ERRNO_IS_DISCONNECT(r
))
1386 /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1387 * different errors. This connection is over, but the socket unit lives on. */
1388 return log_unit_debug_errno(UNIT(s
), r
,
1389 "Got %s on incoming socket, assuming aborted connection attempt, ignoring.",
1395 /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1396 * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1397 * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1398 r
= unit_name_build(prefix
, instance
?: "internal", ".service", &name
);
1402 return manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, ret
);
1405 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1413 const char *exec_context
;
1414 _cleanup_free_
char *path
= NULL
;
1416 r
= socket_load_service_unit(s
, -1, &service
);
1422 exec_context
= SERVICE(service
)->exec_context
.selinux_context
;
1426 con
= strdup(exec_context
);
1430 *ret
= TAKE_PTR(con
);
1434 c
= SERVICE(service
)->exec_command
[SERVICE_EXEC_START
];
1438 r
= chase(c
->path
, SERVICE(service
)->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
, NULL
);
1442 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1443 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1452 static int socket_address_listen_do(
1454 const SocketAddress
*address
,
1455 const char *label
) {
1460 return socket_address_listen(
1462 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1474 #define log_address_error_errno(u, address, error, fmt) \
1476 _cleanup_free_ char *_t = NULL; \
1478 (void) socket_address_print(address, &_t); \
1479 log_unit_error_errno(u, error, fmt, strna(_t)); \
1482 static int fork_needed(const SocketAddress
*address
, const ExecContext
*context
) {
1488 /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1490 if (IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
)) {
1491 r
= bpf_firewall_supported();
1494 if (r
!= BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1498 return exec_needs_network_namespace(context
);
1501 static int socket_address_listen_in_cgroup(
1503 const SocketAddress
*address
,
1504 const char *label
) {
1506 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
1513 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1514 * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1515 * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1518 r
= fork_needed(address
, &s
->exec_context
);
1522 /* Shortcut things... */
1523 fd
= socket_address_listen_do(s
, address
, label
);
1525 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1530 r
= unit_setup_exec_runtime(UNIT(s
));
1532 return log_unit_error_errno(UNIT(s
), r
, "Failed acquire runtime: %m");
1534 if (s
->exec_context
.network_namespace_path
&&
1536 s
->exec_runtime
->shared
&&
1537 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1538 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->netns_storage_socket
, s
->exec_context
.network_namespace_path
, CLONE_NEWNET
);
1540 return log_unit_error_errno(UNIT(s
), r
, "Failed to open network namespace path %s: %m", s
->exec_context
.network_namespace_path
);
1543 if (s
->exec_context
.ipc_namespace_path
&&
1545 s
->exec_runtime
->shared
&&
1546 s
->exec_runtime
->shared
->ipcns_storage_socket
[0] >= 0) {
1547 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->ipcns_storage_socket
, s
->exec_context
.ipc_namespace_path
, CLONE_NEWIPC
);
1549 return log_unit_error_errno(UNIT(s
), r
, "Failed to open IPC namespace path %s: %m", s
->exec_context
.ipc_namespace_path
);
1552 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1553 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1555 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1557 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1561 pair
[0] = safe_close(pair
[0]);
1563 if (exec_needs_network_namespace(&s
->exec_context
) &&
1565 s
->exec_runtime
->shared
&&
1566 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1568 if (ns_type_supported(NAMESPACE_NET
)) {
1569 r
= setup_shareable_ns(s
->exec_runtime
->shared
->netns_storage_socket
, CLONE_NEWNET
);
1571 log_unit_error_errno(UNIT(s
), r
, "Failed to join network namespace: %m");
1572 _exit(EXIT_NETWORK
);
1574 } else if (s
->exec_context
.network_namespace_path
) {
1575 log_unit_error(UNIT(s
), "Network namespace path configured but network namespaces not supported.");
1576 _exit(EXIT_NETWORK
);
1578 log_unit_warning(UNIT(s
), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
1581 fd
= socket_address_listen_do(s
, address
, label
);
1583 log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1584 _exit(EXIT_FAILURE
);
1587 r
= send_one_fd(pair
[1], fd
, 0);
1589 log_address_error_errno(UNIT(s
), address
, r
, "Failed to send listening socket (%s) to parent: %m");
1590 _exit(EXIT_FAILURE
);
1593 _exit(EXIT_SUCCESS
);
1596 pair
[1] = safe_close(pair
[1]);
1597 fd
= receive_one_fd(pair
[0], 0);
1599 /* We synchronously wait for the helper, as it shouldn't be slow */
1600 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1607 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to receive listening socket (%s): %m");
1612 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket
*, socket_close_fds
, NULL
);
1614 static int socket_open_fds(Socket
*orig_s
) {
1615 _cleanup_(socket_close_fdsp
) Socket
*s
= orig_s
;
1616 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1617 bool know_label
= false;
1622 LIST_FOREACH(port
, p
, s
->ports
) {
1632 /* Figure out the label, if we don't it know yet. We do it once for the first
1633 * socket where we need this and remember it for the rest. */
1635 r
= socket_determine_selinux_label(s
, &label
);
1637 return log_unit_error_errno(UNIT(s
), r
, "Failed to determine SELinux label: %m");
1642 /* Apply the socket protocol */
1643 switch (p
->address
.type
) {
1646 case SOCK_SEQPACKET
:
1647 if (s
->socket_protocol
== IPPROTO_SCTP
)
1648 p
->address
.protocol
= s
->socket_protocol
;
1652 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1653 p
->address
.protocol
= s
->socket_protocol
;
1657 p
->fd
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1661 socket_apply_socket_options(s
, p
, p
->fd
);
1665 case SOCKET_SPECIAL
:
1667 p
->fd
= special_address_create(p
->path
, s
->writable
);
1669 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open special file %s: %m", p
->path
);
1674 p
->fd
= fifo_address_create(
1679 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open FIFO %s: %m", p
->path
);
1681 socket_apply_fifo_options(s
, p
->fd
);
1687 p
->fd
= mq_address_create(
1693 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open message queue %s: %m", p
->path
);
1696 case SOCKET_USB_FUNCTION
: {
1697 _cleanup_free_
char *ep
= NULL
;
1699 ep
= path_make_absolute("ep0", p
->path
);
1703 p
->fd
= usbffs_address_create(ep
);
1707 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1711 r
= usbffs_dispatch_eps(p
);
1718 assert_not_reached();
1726 static void socket_unwatch_fds(Socket
*s
) {
1731 LIST_FOREACH(port
, p
, s
->ports
) {
1735 if (!p
->event_source
)
1738 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1740 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1744 static int socket_watch_fds(Socket
*s
) {
1749 LIST_FOREACH(port
, p
, s
->ports
) {
1753 if (p
->event_source
) {
1754 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1758 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1762 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1769 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1770 socket_unwatch_fds(s
);
1780 static int socket_check_open(Socket
*s
) {
1781 bool have_open
= false, have_closed
= false;
1785 LIST_FOREACH(port
, p
, s
->ports
) {
1791 if (have_open
&& have_closed
)
1792 return SOCKET_OPEN_SOME
;
1796 return SOCKET_OPEN_ALL
;
1798 return SOCKET_OPEN_NONE
;
1801 static void socket_set_state(Socket
*s
, SocketState state
) {
1802 SocketState old_state
;
1805 if (s
->state
!= state
)
1806 bus_unit_send_pending_change_signal(UNIT(s
), false);
1808 old_state
= s
->state
;
1816 SOCKET_STOP_PRE_SIGTERM
,
1817 SOCKET_STOP_PRE_SIGKILL
,
1819 SOCKET_FINAL_SIGTERM
,
1820 SOCKET_FINAL_SIGKILL
,
1823 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1824 socket_unwatch_control_pid(s
);
1825 s
->control_command
= NULL
;
1826 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1829 if (state
!= SOCKET_LISTENING
)
1830 socket_unwatch_fds(s
);
1838 SOCKET_STOP_PRE_SIGTERM
,
1839 SOCKET_STOP_PRE_SIGKILL
,
1841 socket_close_fds(s
);
1843 if (state
!= old_state
)
1844 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1846 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
1849 static int socket_coldplug(Unit
*u
) {
1850 Socket
*s
= SOCKET(u
);
1854 assert(s
->state
== SOCKET_DEAD
);
1856 if (s
->deserialized_state
== s
->state
)
1859 if (pidref_is_set(&s
->control_pid
) &&
1860 pid_is_unwaited(s
->control_pid
.pid
) &&
1861 IN_SET(s
->deserialized_state
,
1866 SOCKET_STOP_PRE_SIGTERM
,
1867 SOCKET_STOP_PRE_SIGKILL
,
1869 SOCKET_FINAL_SIGTERM
,
1870 SOCKET_FINAL_SIGKILL
,
1873 r
= unit_watch_pid(UNIT(s
), s
->control_pid
.pid
, /* exclusive= */ false);
1877 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1882 if (IN_SET(s
->deserialized_state
,
1888 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1889 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN state for
1890 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1891 * and if there's a mismatch, warn loudly. */
1893 r
= socket_check_open(s
);
1894 if (r
== SOCKET_OPEN_NONE
)
1895 log_unit_warning(UNIT(s
),
1896 "Socket unit configuration has changed while unit has been running, "
1897 "no open socket file descriptor left. "
1898 "The socket unit is not functional until restarted.");
1899 else if (r
== SOCKET_OPEN_SOME
)
1900 log_unit_warning(UNIT(s
),
1901 "Socket unit configuration has changed while unit has been running, "
1902 "and some socket file descriptors have not been opened yet. "
1903 "The socket unit is not fully functional until restarted.");
1906 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1907 r
= socket_watch_fds(s
);
1912 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
, SOCKET_CLEANING
))
1913 (void) unit_setup_exec_runtime(u
);
1915 socket_set_state(s
, s
->deserialized_state
);
1919 static int socket_spawn(Socket
*s
, ExecCommand
*c
, PidRef
*ret_pid
) {
1921 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1922 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1924 .stdout_fd
= -EBADF
,
1925 .stderr_fd
= -EBADF
,
1928 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1936 r
= unit_prepare_exec(UNIT(s
));
1940 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1944 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1948 r
= exec_spawn(UNIT(s
),
1958 r
= pidref_set_pid(&pidref
, pid
);
1962 r
= unit_watch_pid(UNIT(s
), pidref
.pid
, /* exclusive= */ true);
1966 *ret_pid
= TAKE_PIDREF(pidref
);
1970 static int socket_chown(Socket
*s
, PidRef
*ret_pid
) {
1971 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1977 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1981 /* We have to resolve the user names out-of-process, hence
1982 * let's fork here. It's messy, but well, what can we do? */
1984 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1988 uid_t uid
= UID_INVALID
;
1989 gid_t gid
= GID_INVALID
;
1993 if (!isempty(s
->user
)) {
1994 const char *user
= s
->user
;
1996 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1998 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
2003 if (!isempty(s
->group
)) {
2004 const char *group
= s
->group
;
2006 r
= get_group_creds(&group
, &gid
, 0);
2008 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
2013 LIST_FOREACH(port
, p
, s
->ports
) {
2014 const char *path
= NULL
;
2016 if (p
->type
== SOCKET_SOCKET
)
2017 path
= socket_address_get_path(&p
->address
);
2018 else if (p
->type
== SOCKET_FIFO
)
2024 if (chown(path
, uid
, gid
) < 0) {
2025 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
2030 _exit(EXIT_SUCCESS
);
2033 r
= pidref_set_pid(&pidref
, pid
);
2037 r
= unit_watch_pid(UNIT(s
), pidref
.pid
, /* exclusive= */ true);
2041 *ret_pid
= TAKE_PIDREF(pidref
);
2045 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
2048 if (s
->result
== SOCKET_SUCCESS
)
2051 if (s
->result
== SOCKET_SUCCESS
)
2052 unit_log_success(UNIT(s
));
2054 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
2056 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2058 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
2060 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2062 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2064 unit_unref_uid_gid(UNIT(s
), true);
2067 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2069 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2073 if (s
->result
== SOCKET_SUCCESS
)
2076 socket_unwatch_control_pid(s
);
2077 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2078 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2080 if (s
->control_command
) {
2081 pidref_done(&s
->control_pid
);
2083 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2087 socket_set_state(s
, SOCKET_STOP_POST
);
2089 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2094 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2095 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2098 static int state_to_kill_operation(Socket
*s
, SocketState state
) {
2099 if (state
== SOCKET_STOP_PRE_SIGTERM
&& unit_has_job_type(UNIT(s
), JOB_RESTART
))
2100 return KILL_RESTART
;
2102 if (state
== SOCKET_FINAL_SIGTERM
)
2103 return KILL_TERMINATE
;
2108 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2113 if (s
->result
== SOCKET_SUCCESS
)
2116 r
= unit_kill_context(
2119 state_to_kill_operation(s
, state
),
2127 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2131 socket_set_state(s
, state
);
2132 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2133 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2134 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2135 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2136 else if (state
== SOCKET_FINAL_SIGTERM
)
2137 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2139 socket_enter_dead(s
, SOCKET_SUCCESS
);
2144 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2146 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2147 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2149 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2152 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2156 if (s
->result
== SOCKET_SUCCESS
)
2159 socket_unwatch_control_pid(s
);
2160 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2161 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2163 if (s
->control_command
) {
2164 pidref_done(&s
->control_pid
);
2166 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2170 socket_set_state(s
, SOCKET_STOP_PRE
);
2172 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2177 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2178 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2181 static void socket_enter_listening(Socket
*s
) {
2185 if (!s
->accept
&& s
->flush_pending
) {
2186 log_unit_debug(UNIT(s
), "Flushing socket before listening.");
2190 r
= socket_watch_fds(s
);
2192 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2196 socket_set_state(s
, SOCKET_LISTENING
);
2200 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2203 static void socket_enter_start_post(Socket
*s
) {
2207 socket_unwatch_control_pid(s
);
2208 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2209 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2211 if (s
->control_command
) {
2212 pidref_done(&s
->control_pid
);
2214 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2216 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2220 socket_set_state(s
, SOCKET_START_POST
);
2222 socket_enter_listening(s
);
2227 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2230 static void socket_enter_start_chown(Socket
*s
) {
2235 r
= socket_open_fds(s
);
2237 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2241 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2243 socket_unwatch_control_pid(s
);
2244 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2245 s
->control_command
= NULL
;
2247 r
= socket_chown(s
, &s
->control_pid
);
2249 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2253 socket_set_state(s
, SOCKET_START_CHOWN
);
2255 socket_enter_start_post(s
);
2260 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2263 static void socket_enter_start_pre(Socket
*s
) {
2267 socket_unwatch_control_pid(s
);
2269 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
2271 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2272 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2274 if (s
->control_command
) {
2275 pidref_done(&s
->control_pid
);
2277 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2279 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2283 socket_set_state(s
, SOCKET_START_PRE
);
2285 socket_enter_start_chown(s
);
2290 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2293 static void flush_ports(Socket
*s
) {
2296 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2299 LIST_FOREACH(port
, p
, s
->ports
) {
2303 (void) flush_accept(p
->fd
);
2304 (void) flush_fd(p
->fd
);
2308 static void socket_enter_running(Socket
*s
, int cfd_in
) {
2309 /* Note that this call takes possession of the connection fd passed. It either has to assign it
2310 * somewhere or close it. */
2311 _cleanup_close_
int cfd
= cfd_in
;
2313 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2318 /* We don't take connections anymore if we are supposed to shut down anyway */
2319 if (unit_stop_pending(UNIT(s
))) {
2321 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2330 if (!ratelimit_below(&s
->trigger_limit
)) {
2331 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2332 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2337 bool pending
= false;
2340 /* If there's already a start pending don't bother to do anything */
2341 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_TRIGGERS
)
2342 if (unit_active_or_pending(other
)) {
2348 if (!UNIT_ISSET(s
->service
)) {
2349 r
= log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOENT
),
2350 "Service to activate vanished, refusing activation.");
2354 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, NULL
, &error
, NULL
);
2359 socket_set_state(s
, SOCKET_RUNNING
);
2361 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2364 if (s
->n_connections
>= s
->max_connections
) {
2365 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2370 if (s
->max_connections_per_source
> 0) {
2371 r
= socket_acquire_peer(s
, cfd
, &p
);
2373 if (ERRNO_IS_DISCONNECT(r
))
2375 /* We didn't have enough resources to acquire peer information, let's fail. */
2378 if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2379 _cleanup_free_
char *t
= NULL
;
2381 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2383 log_unit_warning(UNIT(s
),
2384 "Too many incoming connections (%u) from source %s, dropping connection.",
2385 p
->n_ref
, strnull(t
));
2390 r
= socket_load_service_unit(s
, cfd
, &service
);
2392 if (ERRNO_IS_DISCONNECT(r
))
2397 r
= unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, service
,
2398 false, UNIT_DEPENDENCY_IMPLICIT
);
2404 r
= service_set_socket_fd(SERVICE(service
), cfd
, s
, p
, s
->selinux_context_from_net
);
2406 if (ERRNO_IS_DISCONNECT(r
))
2411 TAKE_FD(cfd
); /* We passed ownership of the fd to the service now. Forget it here. */
2414 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, service
, JOB_REPLACE
, NULL
, &error
, NULL
);
2416 /* We failed to activate the new service, but it still exists. Let's make sure the
2417 * service closes and forgets the connection fd again, immediately. */
2418 service_release_socket_fd(SERVICE(service
));
2422 /* Notify clients about changed counters */
2423 unit_add_to_dbus_queue(UNIT(s
));
2434 if (ERRNO_IS_RESOURCE(r
))
2435 log_unit_warning(UNIT(s
), "Failed to queue service startup job: %s",
2436 bus_error_message(&error
, r
));
2438 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2439 cfd
>= 0 ? "template" : "non-template",
2440 bus_error_message(&error
, r
));
2442 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2445 static void socket_run_next(Socket
*s
) {
2449 assert(s
->control_command
);
2450 assert(s
->control_command
->command_next
);
2452 socket_unwatch_control_pid(s
);
2454 s
->control_command
= s
->control_command
->command_next
;
2456 pidref_done(&s
->control_pid
);
2458 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2465 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2467 if (s
->state
== SOCKET_START_POST
)
2468 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2469 else if (s
->state
== SOCKET_STOP_POST
)
2470 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2472 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2475 static int socket_start(Unit
*u
) {
2476 Socket
*s
= SOCKET(u
);
2481 /* We cannot fulfill this request right now, try again later
2483 if (IN_SET(s
->state
,
2485 SOCKET_STOP_PRE_SIGKILL
,
2486 SOCKET_STOP_PRE_SIGTERM
,
2488 SOCKET_FINAL_SIGTERM
,
2489 SOCKET_FINAL_SIGKILL
,
2493 /* Already on it! */
2494 if (IN_SET(s
->state
,
2500 /* Cannot run this without the service being around */
2501 if (UNIT_ISSET(s
->service
)) {
2504 service
= SERVICE(UNIT_DEREF(s
->service
));
2506 if (UNIT(service
)->load_state
!= UNIT_LOADED
)
2507 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
2508 "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2510 /* If the service is already active we cannot start the
2512 if (!IN_SET(service
->state
,
2513 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
2514 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
2515 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EBUSY
),
2516 "Socket service %s already active, refusing.", UNIT(service
)->id
);
2519 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2521 r
= unit_acquire_invocation_id(u
);
2525 s
->result
= SOCKET_SUCCESS
;
2526 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2528 u
->reset_accounting
= true;
2530 socket_enter_start_pre(s
);
2534 static int socket_stop(Unit
*u
) {
2535 Socket
*s
= SOCKET(u
);
2540 if (IN_SET(s
->state
,
2542 SOCKET_STOP_PRE_SIGTERM
,
2543 SOCKET_STOP_PRE_SIGKILL
,
2545 SOCKET_FINAL_SIGTERM
,
2546 SOCKET_FINAL_SIGKILL
))
2549 /* If there's already something running we go directly into
2551 if (IN_SET(s
->state
,
2554 SOCKET_START_POST
)) {
2555 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2559 /* If we are currently cleaning, then abort it, brutally. */
2560 if (s
->state
== SOCKET_CLEANING
) {
2561 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2565 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2567 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2571 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2572 Socket
*s
= SOCKET(u
);
2579 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2580 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2581 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2582 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2584 if (pidref_is_set(&s
->control_pid
))
2585 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
.pid
);
2587 if (s
->control_command_id
>= 0)
2588 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2590 LIST_FOREACH(port
, p
, s
->ports
) {
2596 copy
= fdset_put_dup(fds
, p
->fd
);
2598 return log_unit_warning_errno(u
, copy
, "Failed to serialize socket fd: %m");
2600 if (p
->type
== SOCKET_SOCKET
) {
2601 _cleanup_free_
char *t
= NULL
;
2603 r
= socket_address_print(&p
->address
, &t
);
2605 return log_unit_error_errno(u
, r
, "Failed to format socket address: %m");
2607 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2608 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2610 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2611 } else if (p
->type
== SOCKET_SPECIAL
)
2612 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2613 else if (p
->type
== SOCKET_MQUEUE
)
2614 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2615 else if (p
->type
== SOCKET_USB_FUNCTION
)
2616 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2618 assert(p
->type
== SOCKET_FIFO
);
2619 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2626 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2627 Socket
*s
= SOCKET(u
);
2634 if (streq(key
, "state")) {
2637 state
= socket_state_from_string(value
);
2639 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2641 s
->deserialized_state
= state
;
2642 } else if (streq(key
, "result")) {
2645 f
= socket_result_from_string(value
);
2647 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2648 else if (f
!= SOCKET_SUCCESS
)
2651 } else if (streq(key
, "n-accepted")) {
2654 if (safe_atou(value
, &k
) < 0)
2655 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2658 } else if (streq(key
, "n-refused")) {
2661 if (safe_atou(value
, &k
) < 0)
2662 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2665 } else if (streq(key
, "control-pid")) {
2666 pidref_done(&s
->control_pid
);
2667 r
= pidref_set_pidstr(&s
->control_pid
, value
);
2669 log_debug_errno(r
, "Failed to pin control PID '%s', ignoring: %m", value
);
2670 } else if (streq(key
, "control-command")) {
2671 SocketExecCommand id
;
2673 id
= socket_exec_command_from_string(value
);
2675 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2677 s
->control_command_id
= id
;
2678 s
->control_command
= s
->exec_command
[id
];
2680 } else if (streq(key
, "fifo")) {
2681 _cleanup_free_
char *fdv
= NULL
;
2685 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2687 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2692 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2693 log_unit_debug(u
, "Invalid fifo value: %s", fdv
);
2697 LIST_FOREACH(port
, p
, s
->ports
)
2699 p
->type
== SOCKET_FIFO
&&
2700 path_equal_or_inode_same(p
->path
, value
, 0)) {
2701 p
->fd
= fdset_remove(fds
, fd
);
2706 log_unit_debug(u
, "No matching fifo socket found: %s", value
);
2708 } else if (streq(key
, "special")) {
2709 _cleanup_free_
char *fdv
= NULL
;
2713 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2715 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2720 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2721 log_unit_debug(u
, "Invalid special value: %s", fdv
);
2725 LIST_FOREACH(port
, p
, s
->ports
)
2727 p
->type
== SOCKET_SPECIAL
&&
2728 path_equal_or_inode_same(p
->path
, value
, 0)) {
2729 p
->fd
= fdset_remove(fds
, fd
);
2734 log_unit_debug(u
, "No matching special socket found: %s", value
);
2736 } else if (streq(key
, "mqueue")) {
2737 _cleanup_free_
char *fdv
= NULL
;
2741 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2743 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2748 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2749 log_unit_debug(u
, "Invalid mqueue value: %s", fdv
);
2753 LIST_FOREACH(port
, p
, s
->ports
)
2755 p
->type
== SOCKET_MQUEUE
&&
2756 streq(p
->path
, value
)) {
2757 p
->fd
= fdset_remove(fds
, fd
);
2762 log_unit_debug(u
, "No matching mqueue socket found: %s", value
);
2764 } else if (streq(key
, "socket")) {
2765 _cleanup_free_
char *fdv
= NULL
, *typev
= NULL
;
2769 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2771 log_unit_debug(u
, "Failed to parse socket fd from value: %s", value
);
2776 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2777 log_unit_debug(u
, "Invalid socket fd: %s", fdv
);
2781 r
= extract_first_word(&value
, &typev
, NULL
, 0);
2783 log_unit_debug(u
, "Failed to parse socket type from value: %s", value
);
2787 if (safe_atoi(typev
, &type
) < 0 || type
< 0) {
2788 log_unit_debug(u
, "Invalid socket type: %s", typev
);
2792 LIST_FOREACH(port
, p
, s
->ports
)
2794 socket_address_is(&p
->address
, value
, type
)) {
2795 p
->fd
= fdset_remove(fds
, fd
);
2800 log_unit_debug(u
, "No matching %s socket found: %s",
2801 socket_address_type_to_string(type
), value
);
2803 } else if (streq(key
, "netlink")) {
2804 _cleanup_free_
char *fdv
= NULL
;
2808 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2810 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2815 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2816 log_unit_debug(u
, "Invalid socket value: %s", fdv
);
2820 LIST_FOREACH(port
, p
, s
->ports
)
2822 socket_address_is_netlink(&p
->address
, value
)) {
2823 p
->fd
= fdset_remove(fds
, fd
);
2828 log_unit_debug(u
, "No matching netlink socket found: %s", value
);
2830 } else if (streq(key
, "ffs")) {
2831 _cleanup_free_
char *fdv
= NULL
;
2835 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2837 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2842 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2843 log_unit_debug(u
, "Invalid ffs value: %s", fdv
);
2847 LIST_FOREACH(port
, p
, s
->ports
)
2849 p
->type
== SOCKET_USB_FUNCTION
&&
2850 path_equal_or_inode_same(p
->path
, value
, 0)) {
2851 p
->fd
= fdset_remove(fds
, fd
);
2856 log_unit_debug(u
, "No matching ffs socket found: %s", value
);
2859 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2864 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2865 Socket
*s
= SOCKET(u
);
2869 LIST_FOREACH(port
, p
, s
->ports
) {
2872 if (p
->type
!= SOCKET_SOCKET
)
2878 FDSET_FOREACH(fd
, fds
) {
2879 if (socket_address_matches_fd(&p
->address
, fd
)) {
2880 p
->fd
= fdset_remove(fds
, fd
);
2881 s
->deserialized_state
= SOCKET_LISTENING
;
2888 static UnitActiveState
socket_active_state(Unit
*u
) {
2891 return state_translation_table
[SOCKET(u
)->state
];
2894 static const char *socket_sub_state_to_string(Unit
*u
) {
2897 return socket_state_to_string(SOCKET(u
)->state
);
2900 const char* socket_port_type_to_string(SocketPort
*p
) {
2908 switch (p
->address
.type
) {
2916 case SOCK_SEQPACKET
:
2917 return "SequentialPacket";
2920 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2928 case SOCKET_SPECIAL
:
2932 return "MessageQueue";
2937 case SOCKET_USB_FUNCTION
:
2938 return "USBFunction";
2945 SocketType
socket_port_type_from_string(const char *s
) {
2948 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2949 return SOCKET_SOCKET
;
2950 else if (streq(s
, "Special"))
2951 return SOCKET_SPECIAL
;
2952 else if (streq(s
, "MessageQueue"))
2953 return SOCKET_MQUEUE
;
2954 else if (streq(s
, "FIFO"))
2956 else if (streq(s
, "USBFunction"))
2957 return SOCKET_USB_FUNCTION
;
2959 return _SOCKET_TYPE_INVALID
;
2962 static bool socket_may_gc(Unit
*u
) {
2963 Socket
*s
= SOCKET(u
);
2967 return s
->n_connections
== 0;
2970 static int socket_accept_do(Socket
*s
, int fd
) {
2976 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2978 /* Convert transient network errors into clean and well-defined EAGAIN */
2979 return ERRNO_IS_ACCEPT_AGAIN(errno
) ? -EAGAIN
: -errno
;
2984 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2985 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
2993 /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
2994 * connection socket is also properly associated with the cgroup. */
2996 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2999 r
= bpf_firewall_supported();
3002 if (r
== BPF_FIREWALL_UNSUPPORTED
)
3005 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
3006 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
3008 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
3010 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
3014 pair
[0] = safe_close(pair
[0]);
3016 cfd
= socket_accept_do(s
, fd
);
3017 if (cfd
== -EAGAIN
) /* spurious accept() */
3018 _exit(EXIT_SUCCESS
);
3020 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3021 _exit(EXIT_FAILURE
);
3024 r
= send_one_fd(pair
[1], cfd
, 0);
3026 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
3027 _exit(EXIT_FAILURE
);
3030 _exit(EXIT_SUCCESS
);
3033 pair
[1] = safe_close(pair
[1]);
3034 cfd
= receive_one_fd(pair
[0], 0);
3036 /* We synchronously wait for the helper, as it shouldn't be slow */
3037 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
3043 /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3044 * this is a spurious accept(), let's convert that back to EAGAIN here. */
3048 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
3053 cfd
= socket_accept_do(s
, fd
);
3054 if (cfd
== -EAGAIN
) /* spurious accept(), skip it silently */
3057 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3062 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3063 SocketPort
*p
= ASSERT_PTR(userdata
);
3068 if (p
->socket
->state
!= SOCKET_LISTENING
)
3071 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
3073 if (revents
!= EPOLLIN
) {
3074 if (revents
& EPOLLHUP
)
3075 log_unit_error(UNIT(p
->socket
), "Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.");
3077 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
3081 if (p
->socket
->accept
&&
3082 p
->type
== SOCKET_SOCKET
&&
3083 socket_address_can_accept(&p
->address
)) {
3085 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
3086 if (cfd
== -EAGAIN
) /* Spurious accept() */
3091 socket_apply_socket_options(p
->socket
, p
, cfd
);
3094 socket_enter_running(p
->socket
, cfd
);
3098 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
3102 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3103 Socket
*s
= SOCKET(u
);
3109 if (pid
!= s
->control_pid
.pid
)
3112 pidref_done(&s
->control_pid
);
3114 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
3116 else if (code
== CLD_EXITED
)
3117 f
= SOCKET_FAILURE_EXIT_CODE
;
3118 else if (code
== CLD_KILLED
)
3119 f
= SOCKET_FAILURE_SIGNAL
;
3120 else if (code
== CLD_DUMPED
)
3121 f
= SOCKET_FAILURE_CORE_DUMP
;
3123 assert_not_reached();
3125 if (s
->control_command
) {
3126 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3128 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3132 unit_log_process_exit(
3135 socket_exec_command_to_string(s
->control_command_id
),
3136 f
== SOCKET_SUCCESS
,
3139 if (s
->result
== SOCKET_SUCCESS
)
3142 if (s
->control_command
&&
3143 s
->control_command
->command_next
&&
3144 f
== SOCKET_SUCCESS
) {
3146 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
3149 s
->control_command
= NULL
;
3150 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3152 /* No further commands for this step, so let's figure
3153 * out what to do next */
3155 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
3159 case SOCKET_START_PRE
:
3160 if (f
== SOCKET_SUCCESS
)
3161 socket_enter_start_chown(s
);
3163 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3166 case SOCKET_START_CHOWN
:
3167 if (f
== SOCKET_SUCCESS
)
3168 socket_enter_start_post(s
);
3170 socket_enter_stop_pre(s
, f
);
3173 case SOCKET_START_POST
:
3174 if (f
== SOCKET_SUCCESS
)
3175 socket_enter_listening(s
);
3177 socket_enter_stop_pre(s
, f
);
3180 case SOCKET_STOP_PRE
:
3181 case SOCKET_STOP_PRE_SIGTERM
:
3182 case SOCKET_STOP_PRE_SIGKILL
:
3183 socket_enter_stop_post(s
, f
);
3186 case SOCKET_STOP_POST
:
3187 case SOCKET_FINAL_SIGTERM
:
3188 case SOCKET_FINAL_SIGKILL
:
3189 socket_enter_dead(s
, f
);
3192 case SOCKET_CLEANING
:
3194 if (s
->clean_result
== SOCKET_SUCCESS
)
3195 s
->clean_result
= f
;
3197 socket_enter_dead(s
, SOCKET_SUCCESS
);
3201 assert_not_reached();
3205 /* Notify clients about changed exit status */
3206 unit_add_to_dbus_queue(u
);
3209 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3210 Socket
*s
= SOCKET(userdata
);
3213 assert(s
->timer_event_source
== source
);
3217 case SOCKET_START_PRE
:
3218 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3219 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3222 case SOCKET_START_CHOWN
:
3223 case SOCKET_START_POST
:
3224 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3225 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3228 case SOCKET_STOP_PRE
:
3229 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3230 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3233 case SOCKET_STOP_PRE_SIGTERM
:
3234 if (s
->kill_context
.send_sigkill
) {
3235 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3236 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3238 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3239 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3243 case SOCKET_STOP_PRE_SIGKILL
:
3244 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3245 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3248 case SOCKET_STOP_POST
:
3249 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3250 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3253 case SOCKET_FINAL_SIGTERM
:
3254 if (s
->kill_context
.send_sigkill
) {
3255 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3256 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3258 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3259 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3263 case SOCKET_FINAL_SIGKILL
:
3264 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3265 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3268 case SOCKET_CLEANING
:
3269 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
3271 if (s
->clean_result
== SOCKET_SUCCESS
)
3272 s
->clean_result
= SOCKET_FAILURE_TIMEOUT
;
3274 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, 0);
3278 assert_not_reached();
3284 int socket_collect_fds(Socket
*s
, int **fds
) {
3285 size_t k
= 0, n
= 0;
3291 /* Called from the service code for requesting our fds */
3293 LIST_FOREACH(port
, p
, s
->ports
) {
3296 n
+= p
->n_auxiliary_fds
;
3308 LIST_FOREACH(port
, p
, s
->ports
) {
3311 for (size_t i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3312 rfds
[k
++] = p
->auxiliary_fds
[i
];
3321 static void socket_reset_failed(Unit
*u
) {
3322 Socket
*s
= SOCKET(u
);
3326 if (s
->state
== SOCKET_FAILED
)
3327 socket_set_state(s
, SOCKET_DEAD
);
3329 s
->result
= SOCKET_SUCCESS
;
3330 s
->clean_result
= SOCKET_SUCCESS
;
3333 void socket_connection_unref(Socket
*s
) {
3336 /* The service is dead. Yay!
3338 * This is strictly for one-instance-per-connection
3341 assert(s
->n_connections
> 0);
3344 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3347 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3348 Socket
*s
= SOCKET(u
);
3353 /* Filter out invocations with bogus state */
3354 assert(UNIT_IS_LOAD_COMPLETE(other
->load_state
));
3355 assert(other
->type
== UNIT_SERVICE
);
3357 /* Don't propagate state changes from the service if we are already down */
3358 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3361 /* We don't care for the service state if we are in Accept=yes mode */
3365 /* Propagate start limit hit state */
3366 if (other
->start_limit_hit
) {
3367 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3371 /* Don't propagate anything if there's still a job queued */
3375 if (IN_SET(SERVICE(other
)->state
,
3376 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
3377 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3378 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
3379 socket_enter_listening(s
);
3381 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3382 socket_set_state(s
, SOCKET_RUNNING
);
3385 static int socket_kill(Unit
*u
, KillWho who
, int signo
, int code
, int value
, sd_bus_error
*error
) {
3386 return unit_kill_common(u
, who
, signo
, code
, value
, -1, SOCKET(u
)->control_pid
.pid
, error
);
3389 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3390 Socket
*s
= SOCKET(u
);
3394 if (!s
->timer_event_source
)
3397 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3400 if (t
== USEC_INFINITY
)
3407 char *socket_fdname(Socket
*s
) {
3410 /* Returns the name to use for $LISTEN_NAMES. If the user
3411 * didn't specify anything specifically, use the socket unit's
3412 * name as fallback. */
3414 return s
->fdname
?: UNIT(s
)->id
;
3417 static int socket_control_pid(Unit
*u
) {
3418 Socket
*s
= SOCKET(u
);
3422 return s
->control_pid
.pid
;
3425 static int socket_clean(Unit
*u
, ExecCleanMask mask
) {
3426 _cleanup_strv_free_
char **l
= NULL
;
3427 Socket
*s
= SOCKET(u
);
3434 if (s
->state
!= SOCKET_DEAD
)
3437 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
3441 if (strv_isempty(l
))
3444 socket_unwatch_control_pid(s
);
3445 s
->clean_result
= SOCKET_SUCCESS
;
3446 s
->control_command
= NULL
;
3447 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3449 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->exec_context
.timeout_clean_usec
));
3453 r
= unit_fork_and_watch_rm_rf(u
, l
, &pid
);
3457 r
= pidref_set_pid(&s
->control_pid
, pid
);
3461 socket_set_state(s
, SOCKET_CLEANING
);
3465 log_unit_warning_errno(u
, r
, "Failed to initiate cleaning: %m");
3466 s
->clean_result
= SOCKET_FAILURE_RESOURCES
;
3467 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
3471 static int socket_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
3472 Socket
*s
= SOCKET(u
);
3476 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
3479 static int socket_can_start(Unit
*u
) {
3480 Socket
*s
= SOCKET(u
);
3485 r
= unit_test_start_limit(u
);
3487 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
3494 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3495 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3496 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3497 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3498 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3499 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3502 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3504 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3505 [SOCKET_SUCCESS
] = "success",
3506 [SOCKET_FAILURE_RESOURCES
] = "resources",
3507 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3508 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3509 [SOCKET_FAILURE_SIGNAL
] = "signal",
3510 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3511 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3512 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3513 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3516 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3518 static const char* const socket_timestamping_table
[_SOCKET_TIMESTAMPING_MAX
] = {
3519 [SOCKET_TIMESTAMPING_OFF
] = "off",
3520 [SOCKET_TIMESTAMPING_US
] = "us",
3521 [SOCKET_TIMESTAMPING_NS
] = "ns",
3524 DEFINE_STRING_TABLE_LOOKUP(socket_timestamping
, SocketTimestamping
);
3526 SocketTimestamping
socket_timestamping_from_string_harder(const char *p
) {
3527 SocketTimestamping t
;
3531 return _SOCKET_TIMESTAMPING_INVALID
;
3533 t
= socket_timestamping_from_string(p
);
3537 /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3539 if (streq(p
, "nsec"))
3540 return SOCKET_TIMESTAMPING_NS
;
3541 if (STR_IN_SET(p
, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
3542 return SOCKET_TIMESTAMPING_US
;
3544 r
= parse_boolean(p
);
3546 return _SOCKET_TIMESTAMPING_INVALID
;
3548 return r
? SOCKET_TIMESTAMPING_NS
: SOCKET_TIMESTAMPING_OFF
; /* If boolean yes, default to ns accuracy */
3551 const UnitVTable socket_vtable
= {
3552 .object_size
= sizeof(Socket
),
3553 .exec_context_offset
= offsetof(Socket
, exec_context
),
3554 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3555 .kill_context_offset
= offsetof(Socket
, kill_context
),
3556 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3562 .private_section
= "Socket",
3564 .can_transient
= true,
3565 .can_trigger
= true,
3568 .init
= socket_init
,
3569 .done
= socket_done
,
3570 .load
= socket_load
,
3572 .coldplug
= socket_coldplug
,
3574 .dump
= socket_dump
,
3576 .start
= socket_start
,
3577 .stop
= socket_stop
,
3579 .kill
= socket_kill
,
3580 .clean
= socket_clean
,
3581 .can_clean
= socket_can_clean
,
3583 .get_timeout
= socket_get_timeout
,
3585 .serialize
= socket_serialize
,
3586 .deserialize_item
= socket_deserialize_item
,
3587 .distribute_fds
= socket_distribute_fds
,
3589 .active_state
= socket_active_state
,
3590 .sub_state_to_string
= socket_sub_state_to_string
,
3592 .will_restart
= unit_will_restart_default
,
3594 .may_gc
= socket_may_gc
,
3596 .sigchld_event
= socket_sigchld_event
,
3598 .trigger_notify
= socket_trigger_notify
,
3600 .reset_failed
= socket_reset_failed
,
3602 .control_pid
= socket_control_pid
,
3604 .bus_set_property
= bus_socket_set_property
,
3605 .bus_commit_properties
= bus_socket_commit_properties
,
3607 .status_message_formats
= {
3608 .finished_start_job
= {
3609 [JOB_DONE
] = "Listening on %s.",
3610 [JOB_FAILED
] = "Failed to listen on %s.",
3611 [JOB_TIMEOUT
] = "Timed out starting %s.",
3613 .finished_stop_job
= {
3614 [JOB_DONE
] = "Closed %s.",
3615 [JOB_FAILED
] = "Failed stopping %s.",
3616 [JOB_TIMEOUT
] = "Timed out stopping %s.",
3620 .can_start
= socket_can_start
,