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
;
106 s
->poll_limit_interval
= USEC_INFINITY
;
107 s
->poll_limit_burst
= UINT_MAX
;
110 static void socket_unwatch_control_pid(Socket
*s
) {
113 if (!pidref_is_set(&s
->control_pid
))
116 unit_unwatch_pid(UNIT(s
), s
->control_pid
.pid
);
117 pidref_done(&s
->control_pid
);
120 static void socket_cleanup_fd_list(SocketPort
*p
) {
123 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
124 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
125 p
->n_auxiliary_fds
= 0;
128 SocketPort
*socket_port_free(SocketPort
*p
) {
132 sd_event_source_unref(p
->event_source
);
134 socket_cleanup_fd_list(p
);
141 void socket_free_ports(Socket
*s
) {
144 LIST_CLEAR(port
, s
->ports
, socket_port_free
);
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
, bool relative
, usec_t usec
) {
188 return unit_arm_timer(UNIT(s
), &s
->timer_event_source
, relative
, usec
, socket_dispatch_timer
);
191 static bool have_non_accept_socket(Socket
*s
) {
197 LIST_FOREACH(port
, p
, s
->ports
) {
199 if (p
->type
!= SOCKET_SOCKET
)
202 if (!socket_address_can_accept(&p
->address
))
209 static int socket_add_mount_dependencies(Socket
*s
) {
214 LIST_FOREACH(port
, p
, s
->ports
) {
215 const char *path
= NULL
;
217 if (p
->type
== SOCKET_SOCKET
)
218 path
= socket_address_get_path(&p
->address
);
219 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
225 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
233 static int socket_add_device_dependencies(Socket
*s
) {
238 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
241 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
242 return unit_add_node_dependency(UNIT(s
), t
, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
245 static int socket_add_default_dependencies(Socket
*s
) {
249 if (!UNIT(s
)->default_dependencies
)
252 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
256 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
257 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
262 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
265 static bool socket_has_exec(Socket
*s
) {
269 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
270 if (s
->exec_command
[i
])
276 static int socket_add_extras(Socket
*s
) {
282 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
283 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
284 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
285 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
286 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
287 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
288 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
289 * service starts are typical.
291 * For the poll limit we follow a similar rule, but use 3/4th of the trigger limit parameters, to
292 * trigger this earlier. */
294 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
295 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
296 if (s
->trigger_limit
.burst
== UINT_MAX
)
297 s
->trigger_limit
.burst
= s
->accept
? 200 : 20;
299 if (s
->poll_limit_interval
== USEC_INFINITY
)
300 s
->poll_limit_interval
= 2 * USEC_PER_SEC
;
301 if (s
->poll_limit_burst
== UINT_MAX
)
302 s
->poll_limit_burst
= s
->accept
? 150 : 15;
304 if (have_non_accept_socket(s
)) {
306 if (!UNIT_DEREF(s
->service
)) {
309 r
= unit_load_related_unit(u
, ".service", &x
);
313 unit_ref_set(&s
->service
, u
, x
);
316 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
321 r
= socket_add_mount_dependencies(s
);
325 r
= socket_add_device_dependencies(s
);
329 r
= unit_patch_contexts(u
);
333 if (socket_has_exec(s
)) {
334 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
339 r
= unit_set_default_slice(u
);
343 r
= socket_add_default_dependencies(s
);
350 static const char *socket_find_symlink_target(Socket
*s
) {
351 const char *found
= NULL
;
353 LIST_FOREACH(port
, p
, s
->ports
) {
354 const char *f
= NULL
;
363 f
= socket_address_get_path(&p
->address
);
381 static int socket_verify(Socket
*s
) {
383 assert(UNIT(s
)->load_state
== UNIT_LOADED
);
386 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
388 if (s
->accept
&& have_non_accept_socket(s
))
389 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
391 if (s
->accept
&& s
->max_connections
<= 0)
392 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "MaxConnection= setting too small. Refusing.");
394 if (s
->accept
&& UNIT_DEREF(s
->service
))
395 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Explicit service configuration for accepting socket units not supported. Refusing.");
397 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
)
398 return log_unit_error_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOEXEC
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
400 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
))
401 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.");
406 static void peer_address_hash_func(const SocketPeer
*s
, struct siphash
*state
) {
409 if (s
->peer
.sa
.sa_family
== AF_INET
)
410 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
411 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
412 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
413 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
414 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
416 assert_not_reached();
419 static int peer_address_compare_func(const SocketPeer
*x
, const SocketPeer
*y
) {
422 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
426 switch (x
->peer
.sa
.sa_family
) {
428 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
430 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
432 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
434 assert_not_reached();
437 DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops
, SocketPeer
, peer_address_hash_func
, peer_address_compare_func
);
439 static int socket_load(Unit
*u
) {
440 Socket
*s
= SOCKET(u
);
444 assert(u
->load_state
== UNIT_STUB
);
446 r
= unit_load_fragment_and_dropin(u
, true);
450 if (u
->load_state
!= UNIT_LOADED
)
453 /* This is a new unit? Then let's add in some extras */
454 r
= socket_add_extras(s
);
458 return socket_verify(s
);
461 static SocketPeer
*socket_peer_new(void) {
464 p
= new(SocketPeer
, 1);
474 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
478 set_remove(p
->socket
->peers_by_address
, p
);
483 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
485 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**ret
) {
486 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
488 .peer_salen
= sizeof(union sockaddr_union
),
496 if (getpeername(fd
, &sa
.peer
.sa
, &sa
.peer_salen
) < 0)
497 return log_unit_error_errno(UNIT(s
), errno
, "getpeername() failed: %m");
499 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
504 i
= set_get(s
->peers_by_address
, &sa
);
506 *ret
= socket_peer_ref(i
);
510 remote
= socket_peer_new();
514 remote
->peer
= sa
.peer
;
515 remote
->peer_salen
= sa
.peer_salen
;
517 r
= set_ensure_put(&s
->peers_by_address
, &peer_address_hash_ops
, remote
);
519 return log_unit_error_errno(UNIT(s
), r
, "Failed to insert peer info into hash table: %m");
523 *ret
= TAKE_PTR(remote
);
527 static const char* listen_lookup(int family
, int type
) {
529 if (family
== AF_NETLINK
)
530 return "ListenNetlink";
532 if (type
== SOCK_STREAM
)
533 return "ListenStream";
534 else if (type
== SOCK_DGRAM
)
535 return "ListenDatagram";
536 else if (type
== SOCK_SEQPACKET
)
537 return "ListenSequentialPacket";
539 assert_not_reached();
543 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
544 Socket
*s
= SOCKET(u
);
545 const char *prefix2
, *str
;
550 prefix
= strempty(prefix
);
551 prefix2
= strjoina(prefix
, "\t");
554 "%sSocket State: %s\n"
556 "%sClean Result: %s\n"
557 "%sBindIPv6Only: %s\n"
559 "%sSocketMode: %04o\n"
560 "%sDirectoryMode: %04o\n"
564 "%sTransparent: %s\n"
566 "%sPassCredentials: %s\n"
567 "%sPassSecurity: %s\n"
568 "%sPassPacketInfo: %s\n"
569 "%sTCPCongestion: %s\n"
570 "%sRemoveOnStop: %s\n"
572 "%sFileDescriptorName: %s\n"
573 "%sSELinuxContextFromNet: %s\n",
574 prefix
, socket_state_to_string(s
->state
),
575 prefix
, socket_result_to_string(s
->result
),
576 prefix
, socket_result_to_string(s
->clean_result
),
577 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
579 prefix
, s
->socket_mode
,
580 prefix
, s
->directory_mode
,
581 prefix
, yes_no(s
->keep_alive
),
582 prefix
, yes_no(s
->no_delay
),
583 prefix
, yes_no(s
->free_bind
),
584 prefix
, yes_no(s
->transparent
),
585 prefix
, yes_no(s
->broadcast
),
586 prefix
, yes_no(s
->pass_cred
),
587 prefix
, yes_no(s
->pass_sec
),
588 prefix
, yes_no(s
->pass_pktinfo
),
589 prefix
, strna(s
->tcp_congestion
),
590 prefix
, yes_no(s
->remove_on_stop
),
591 prefix
, yes_no(s
->writable
),
592 prefix
, socket_fdname(s
),
593 prefix
, yes_no(s
->selinux_context_from_net
));
595 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
)
597 "%sTimestamping: %s\n",
598 prefix
, socket_timestamping_to_string(s
->timestamping
));
600 if (pidref_is_set(&s
->control_pid
))
602 "%sControl PID: "PID_FMT
"\n",
603 prefix
, s
->control_pid
.pid
);
605 if (s
->bind_to_device
)
607 "%sBindToDevice: %s\n",
608 prefix
, s
->bind_to_device
);
613 "%sNConnections: %u\n"
614 "%sMaxConnections: %u\n"
615 "%sMaxConnectionsPerSource: %u\n",
616 prefix
, s
->n_accepted
,
617 prefix
, s
->n_connections
,
618 prefix
, s
->max_connections
,
619 prefix
, s
->max_connections_per_source
);
622 "%sFlushPending: %s\n",
623 prefix
, yes_no(s
->flush_pending
));
626 if (s
->priority
>= 0)
629 prefix
, s
->priority
);
631 if (s
->receive_buffer
> 0)
633 "%sReceiveBuffer: %zu\n",
634 prefix
, s
->receive_buffer
);
636 if (s
->send_buffer
> 0)
638 "%sSendBuffer: %zu\n",
639 prefix
, s
->send_buffer
);
651 if (s
->pipe_size
> 0)
654 prefix
, s
->pipe_size
);
661 if (s
->mq_maxmsg
> 0)
663 "%sMessageQueueMaxMessages: %li\n",
664 prefix
, s
->mq_maxmsg
);
666 if (s
->mq_msgsize
> 0)
668 "%sMessageQueueMessageSize: %li\n",
669 prefix
, s
->mq_msgsize
);
674 prefix
, yes_no(s
->reuse_port
));
678 "%sSmackLabel: %s\n",
683 "%sSmackLabelIPIn: %s\n",
684 prefix
, s
->smack_ip_in
);
688 "%sSmackLabelIPOut: %s\n",
689 prefix
, s
->smack_ip_out
);
691 if (!isempty(s
->user
) || !isempty(s
->group
))
694 "%sSocketGroup: %s\n",
695 prefix
, strna(s
->user
),
696 prefix
, strna(s
->group
));
698 if (timestamp_is_set(s
->keep_alive_time
))
700 "%sKeepAliveTimeSec: %s\n",
701 prefix
, FORMAT_TIMESPAN(s
->keep_alive_time
, USEC_PER_SEC
));
703 if (s
->keep_alive_interval
> 0)
705 "%sKeepAliveIntervalSec: %s\n",
706 prefix
, FORMAT_TIMESPAN(s
->keep_alive_interval
, USEC_PER_SEC
));
708 if (s
->keep_alive_cnt
> 0)
710 "%sKeepAliveProbes: %u\n",
711 prefix
, s
->keep_alive_cnt
);
713 if (s
->defer_accept
> 0)
715 "%sDeferAcceptSec: %s\n",
716 prefix
, FORMAT_TIMESPAN(s
->defer_accept
, USEC_PER_SEC
));
718 LIST_FOREACH(port
, p
, s
->ports
) {
721 case SOCKET_SOCKET
: {
722 _cleanup_free_
char *k
= NULL
;
725 r
= socket_address_print(&p
->address
, &k
);
728 fprintf(f
, "%s%s: %m\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
));
730 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), k
);
734 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
736 case SOCKET_USB_FUNCTION
:
737 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
740 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
743 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
748 "%sTriggerLimitIntervalSec: %s\n"
749 "%sTriggerLimitBurst: %u\n"
750 "%sPollLimitIntervalSec: %s\n"
751 "%sPollLimitBurst: %u\n",
752 prefix
, FORMAT_TIMESPAN(s
->trigger_limit
.interval
, USEC_PER_SEC
),
753 prefix
, s
->trigger_limit
.burst
,
754 prefix
, FORMAT_TIMESPAN(s
->poll_limit_interval
, USEC_PER_SEC
),
755 prefix
, s
->poll_limit_burst
);
757 str
= ip_protocol_to_name(s
->socket_protocol
);
759 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
761 if (!strv_isempty(s
->symlinks
)) {
762 fprintf(f
, "%sSymlinks:", prefix
);
763 STRV_FOREACH(q
, s
->symlinks
)
764 fprintf(f
, " %s", *q
);
770 "%sTimeoutSec: %s\n",
771 prefix
, FORMAT_TIMESPAN(s
->timeout_usec
, USEC_PER_SEC
));
773 exec_context_dump(&s
->exec_context
, f
, prefix
);
774 kill_context_dump(&s
->kill_context
, f
, prefix
);
776 for (SocketExecCommand c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
777 if (!s
->exec_command
[c
])
780 fprintf(f
, "%s-> %s:\n",
781 prefix
, socket_exec_command_to_string(c
));
783 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
786 cgroup_context_dump(UNIT(s
), f
, prefix
);
789 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
792 union sockaddr_union local
, remote
;
798 if (getsockname(fd
, &local
.sa
, &l
) < 0)
802 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
805 switch (local
.sa
.sa_family
) {
809 a
= be32toh(local
.in
.sin_addr
.s_addr
),
810 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
813 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
815 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
816 be16toh(local
.in
.sin_port
),
817 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
818 be16toh(remote
.in
.sin_port
)) < 0)
825 static const unsigned char ipv4_prefix
[] = {
826 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
829 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
830 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
832 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
833 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
836 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
838 a
[0], a
[1], a
[2], a
[3],
839 be16toh(local
.in6
.sin6_port
),
840 b
[0], b
[1], b
[2], b
[3],
841 be16toh(remote
.in6
.sin6_port
)) < 0)
847 IN6_ADDR_TO_STRING(&local
.in6
.sin6_addr
),
848 be16toh(local
.in6
.sin6_port
),
849 IN6_ADDR_TO_STRING(&remote
.in6
.sin6_addr
),
850 be16toh(remote
.in6
.sin6_port
)) < 0)
861 k
= getpeercred(fd
, &ucred
);
864 "%u-"PID_FMT
"-"UID_FMT
,
865 nr
, ucred
.pid
, ucred
.uid
) < 0)
867 } else if (k
== -ENODATA
) {
868 /* This handles the case where somebody is
869 * connecting from another pid/uid namespace
870 * (e.g. from outside of our container). */
885 local
.vm
.svm_cid
, local
.vm
.svm_port
,
886 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
892 assert_not_reached();
899 static void socket_close_fds(Socket
*s
) {
902 LIST_FOREACH(port
, p
, s
->ports
) {
905 was_open
= p
->fd
>= 0;
907 p
->event_source
= sd_event_source_disable_unref(p
->event_source
);
908 p
->fd
= safe_close(p
->fd
);
909 socket_cleanup_fd_list(p
);
911 /* One little note: we should normally not delete any sockets in the file system here! After all some
912 * other process we spawned might still have a reference of this fd and wants to continue to use
913 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
914 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
915 * anyway, but only then. */
917 if (!was_open
|| !s
->remove_on_stop
)
923 (void) unlink(p
->path
);
927 (void) mq_unlink(p
->path
);
931 (void) socket_address_unlink(&p
->address
);
939 if (s
->remove_on_stop
)
940 STRV_FOREACH(i
, s
->symlinks
)
943 /* Note that we don't return NULL here, since s has not been freed. */
946 static void socket_apply_socket_options(Socket
*s
, SocketPort
*p
, int fd
) {
954 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
956 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
959 if (timestamp_is_set(s
->keep_alive_time
)) {
960 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
962 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
965 if (s
->keep_alive_interval
> 0) {
966 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
968 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
971 if (s
->keep_alive_cnt
> 0) {
972 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
974 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
977 if (s
->defer_accept
> 0) {
978 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
980 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
984 if (s
->socket_protocol
== IPPROTO_SCTP
) {
985 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
987 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
989 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
991 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
996 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
998 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1002 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1004 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1008 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1010 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1013 if (s
->pass_pktinfo
) {
1014 r
= socket_set_recvpktinfo(fd
, socket_address_family(&p
->address
), true);
1016 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable packet info socket option: %m");
1019 if (s
->timestamping
!= SOCKET_TIMESTAMPING_OFF
) {
1020 r
= setsockopt_int(fd
, SOL_SOCKET
,
1021 s
->timestamping
== SOCKET_TIMESTAMPING_NS
? SO_TIMESTAMPNS
: SO_TIMESTAMP
,
1024 log_unit_warning_errno(UNIT(s
), r
, "Failed to enable timestamping socket option, ignoring: %m");
1027 if (s
->priority
>= 0) {
1028 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1030 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1033 if (s
->receive_buffer
> 0) {
1034 r
= fd_set_rcvbuf(fd
, s
->receive_buffer
, false);
1036 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1037 "SO_RCVBUF/SO_RCVBUFFORCE failed: %m");
1040 if (s
->send_buffer
> 0) {
1041 r
= fd_set_sndbuf(fd
, s
->send_buffer
, false);
1043 log_unit_full_errno(UNIT(s
), ERRNO_IS_PRIVILEGE(r
) ? LOG_DEBUG
: LOG_WARNING
, r
,
1044 "SO_SNDBUF/SO_SNDBUFFORCE failed: %m");
1048 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1050 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1053 if (s
->ip_tos
>= 0) {
1054 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1056 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1059 if (s
->ip_ttl
>= 0) {
1060 r
= socket_set_ttl(fd
, socket_address_family(&p
->address
), s
->ip_ttl
);
1062 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1065 if (s
->tcp_congestion
)
1066 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1067 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1069 if (s
->smack_ip_in
) {
1070 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1072 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1075 if (s
->smack_ip_out
) {
1076 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1078 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1082 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1088 if (s
->pipe_size
> 0)
1089 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1090 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1093 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1095 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1099 static int fifo_address_create(
1101 mode_t directory_mode
,
1102 mode_t socket_mode
) {
1104 _cleanup_close_
int fd
= -EBADF
;
1111 (void) mkdir_parents_label(path
, directory_mode
);
1113 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1117 /* Enforce the right access mode for the fifo */
1118 old_mask
= umask(~socket_mode
);
1120 /* Include the original umask in our mask */
1121 (void) umask(~socket_mode
| old_mask
);
1123 r
= mkfifo(path
, socket_mode
);
1124 (void) umask(old_mask
);
1126 if (r
< 0 && errno
!= EEXIST
) {
1131 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1137 mac_selinux_create_file_clear();
1139 if (fstat(fd
, &st
) < 0) {
1144 if (!S_ISFIFO(st
.st_mode
) ||
1145 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1146 st
.st_uid
!= getuid() ||
1147 st
.st_gid
!= getgid()) {
1155 mac_selinux_create_file_clear();
1159 static int special_address_create(const char *path
, bool writable
) {
1160 _cleanup_close_
int fd
= -EBADF
;
1165 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1169 if (fstat(fd
, &st
) < 0)
1172 /* Check whether this is a /proc, /sys or /dev file or char device */
1173 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1179 static int usbffs_address_create(const char *path
) {
1180 _cleanup_close_
int fd
= -EBADF
;
1185 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1189 if (fstat(fd
, &st
) < 0)
1192 /* Check whether this is a regular file (ffs endpoint) */
1193 if (!S_ISREG(st
.st_mode
))
1199 static int mq_address_create(
1205 _cleanup_close_
int fd
= -EBADF
;
1208 struct mq_attr _attr
, *attr
= NULL
;
1212 if (maxmsg
> 0 && msgsize
> 0) {
1213 _attr
= (struct mq_attr
) {
1214 .mq_flags
= O_NONBLOCK
,
1215 .mq_maxmsg
= maxmsg
,
1216 .mq_msgsize
= msgsize
,
1221 /* Enforce the right access mode for the mq */
1222 old_mask
= umask(~mq_mode
);
1224 /* Include the original umask in our mask */
1225 (void) umask(~mq_mode
| old_mask
);
1226 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1227 (void) umask(old_mask
);
1232 if (fstat(fd
, &st
) < 0)
1235 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1236 st
.st_uid
!= getuid() ||
1237 st
.st_gid
!= getgid())
1243 static int socket_symlink(Socket
*s
) {
1249 p
= socket_find_symlink_target(s
);
1253 STRV_FOREACH(i
, s
->symlinks
) {
1254 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1256 r
= symlink_idempotent(p
, *i
, false);
1258 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1259 /* If there's already something where we want to create the symlink, and the destructive
1260 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1263 if (unlink(*i
) >= 0)
1264 r
= symlink_idempotent(p
, *i
, false);
1268 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s %s %s, ignoring: %m",
1269 p
, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT
), *i
);
1275 static int usbffs_write_descs(int fd
, Service
*s
) {
1278 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1281 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1285 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1288 static int usbffs_select_ep(const struct dirent
*d
) {
1289 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1292 static int usbffs_dispatch_eps(SocketPort
*p
) {
1293 _cleanup_free_
struct dirent
**ent
= NULL
;
1297 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1302 p
->auxiliary_fds
= new(int, n
);
1303 if (!p
->auxiliary_fds
) {
1308 p
->n_auxiliary_fds
= n
;
1311 for (size_t i
= 0; i
< n
; ++i
) {
1312 _cleanup_free_
char *ep
= NULL
;
1314 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1322 r
= usbffs_address_create(ep
);
1326 p
->auxiliary_fds
[k
++] = r
;
1333 close_many(p
->auxiliary_fds
, k
);
1334 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1335 p
->n_auxiliary_fds
= 0;
1338 free_many((void**) ent
, n
);
1342 int socket_load_service_unit(Socket
*s
, int cfd
, Unit
**ret
) {
1343 /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1345 * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1349 if (UNIT_ISSET(s
->service
)) {
1350 *ret
= UNIT_DEREF(s
->service
);
1357 /* Build the instance name and load the unit */
1358 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
1361 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
1366 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
1368 if (ERRNO_IS_DISCONNECT(r
))
1369 /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1370 * different errors. This connection is over, but the socket unit lives on. */
1371 return log_unit_debug_errno(UNIT(s
), r
,
1372 "Got %s on incoming socket, assuming aborted connection attempt, ignoring.",
1378 /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1379 * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1380 * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1381 r
= unit_name_build(prefix
, instance
?: "internal", ".service", &name
);
1385 return manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, ret
);
1388 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1396 const char *exec_context
;
1397 _cleanup_free_
char *path
= NULL
;
1399 r
= socket_load_service_unit(s
, -1, &service
);
1405 exec_context
= SERVICE(service
)->exec_context
.selinux_context
;
1409 con
= strdup(exec_context
);
1413 *ret
= TAKE_PTR(con
);
1417 c
= SERVICE(service
)->exec_command
[SERVICE_EXEC_START
];
1421 r
= chase(c
->path
, SERVICE(service
)->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
, NULL
);
1425 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1426 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1435 static int socket_address_listen_do(
1437 const SocketAddress
*address
,
1438 const char *label
) {
1443 return socket_address_listen(
1445 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1457 #define log_address_error_errno(u, address, error, fmt) \
1459 _cleanup_free_ char *_t = NULL; \
1461 (void) socket_address_print(address, &_t); \
1462 log_unit_error_errno(u, error, fmt, strna(_t)); \
1465 static int fork_needed(const SocketAddress
*address
, Socket
*s
) {
1471 /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1473 /* If there are any NFTSet= directives with cgroup source, we need the cgroup */
1475 CGroupContext
*c
= unit_get_cgroup_context(u
);
1477 FOREACH_ARRAY(nft_set
, c
->nft_set_context
.sets
, c
->nft_set_context
.n_sets
)
1478 if (nft_set
->source
== NFT_SET_SOURCE_CGROUP
)
1481 if (IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
)) {
1482 r
= bpf_firewall_supported();
1485 if (r
!= BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1489 return exec_needs_network_namespace(&s
->exec_context
);
1492 static int socket_address_listen_in_cgroup(
1494 const SocketAddress
*address
,
1495 const char *label
) {
1497 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
1498 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
1504 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1505 * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1506 * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1509 r
= fork_needed(address
, s
);
1513 /* Shortcut things... */
1514 fd
= socket_address_listen_do(s
, address
, label
);
1516 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1521 r
= unit_setup_exec_runtime(UNIT(s
));
1523 return log_unit_error_errno(UNIT(s
), r
, "Failed acquire runtime: %m");
1525 if (s
->exec_context
.network_namespace_path
&&
1527 s
->exec_runtime
->shared
&&
1528 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1529 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->netns_storage_socket
, s
->exec_context
.network_namespace_path
, CLONE_NEWNET
);
1531 return log_unit_error_errno(UNIT(s
), r
, "Failed to open network namespace path %s: %m", s
->exec_context
.network_namespace_path
);
1534 if (s
->exec_context
.ipc_namespace_path
&&
1536 s
->exec_runtime
->shared
&&
1537 s
->exec_runtime
->shared
->ipcns_storage_socket
[0] >= 0) {
1538 r
= open_shareable_ns_path(s
->exec_runtime
->shared
->ipcns_storage_socket
, s
->exec_context
.ipc_namespace_path
, CLONE_NEWIPC
);
1540 return log_unit_error_errno(UNIT(s
), r
, "Failed to open IPC namespace path %s: %m", s
->exec_context
.ipc_namespace_path
);
1543 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1544 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1546 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1548 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1552 pair
[0] = safe_close(pair
[0]);
1554 if (exec_needs_network_namespace(&s
->exec_context
) &&
1556 s
->exec_runtime
->shared
&&
1557 s
->exec_runtime
->shared
->netns_storage_socket
[0] >= 0) {
1559 if (ns_type_supported(NAMESPACE_NET
)) {
1560 r
= setup_shareable_ns(s
->exec_runtime
->shared
->netns_storage_socket
, CLONE_NEWNET
);
1562 log_unit_error_errno(UNIT(s
), r
, "Failed to join network namespace: %m");
1563 _exit(EXIT_NETWORK
);
1565 } else if (s
->exec_context
.network_namespace_path
) {
1566 log_unit_error(UNIT(s
), "Network namespace path configured but network namespaces not supported.");
1567 _exit(EXIT_NETWORK
);
1569 log_unit_warning(UNIT(s
), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
1572 fd
= socket_address_listen_do(s
, address
, label
);
1574 log_address_error_errno(UNIT(s
), address
, fd
, "Failed to create listening socket (%s): %m");
1575 _exit(EXIT_FAILURE
);
1578 r
= send_one_fd(pair
[1], fd
, 0);
1580 log_address_error_errno(UNIT(s
), address
, r
, "Failed to send listening socket (%s) to parent: %m");
1581 _exit(EXIT_FAILURE
);
1584 _exit(EXIT_SUCCESS
);
1587 pair
[1] = safe_close(pair
[1]);
1588 fd
= receive_one_fd(pair
[0], 0);
1590 /* We synchronously wait for the helper, as it shouldn't be slow */
1591 r
= wait_for_terminate_and_check("(sd-listen)", pid
.pid
, WAIT_LOG_ABNORMAL
);
1598 return log_address_error_errno(UNIT(s
), address
, fd
, "Failed to receive listening socket (%s): %m");
1603 DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket
*, socket_close_fds
, NULL
);
1605 static int socket_open_fds(Socket
*orig_s
) {
1606 _cleanup_(socket_close_fdsp
) Socket
*s
= orig_s
;
1607 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1608 bool know_label
= false;
1613 LIST_FOREACH(port
, p
, s
->ports
) {
1623 /* Figure out the label, if we don't it know yet. We do it once for the first
1624 * socket where we need this and remember it for the rest. */
1626 r
= socket_determine_selinux_label(s
, &label
);
1628 return log_unit_error_errno(UNIT(s
), r
, "Failed to determine SELinux label: %m");
1633 /* Apply the socket protocol */
1634 switch (p
->address
.type
) {
1637 case SOCK_SEQPACKET
:
1638 if (s
->socket_protocol
== IPPROTO_SCTP
)
1639 p
->address
.protocol
= s
->socket_protocol
;
1643 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1644 p
->address
.protocol
= s
->socket_protocol
;
1648 p
->fd
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1652 socket_apply_socket_options(s
, p
, p
->fd
);
1656 case SOCKET_SPECIAL
:
1658 p
->fd
= special_address_create(p
->path
, s
->writable
);
1660 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open special file %s: %m", p
->path
);
1665 p
->fd
= fifo_address_create(
1670 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open FIFO %s: %m", p
->path
);
1672 socket_apply_fifo_options(s
, p
->fd
);
1678 p
->fd
= mq_address_create(
1684 return log_unit_error_errno(UNIT(s
), p
->fd
, "Failed to open message queue %s: %m", p
->path
);
1687 case SOCKET_USB_FUNCTION
: {
1688 _cleanup_free_
char *ep
= NULL
;
1690 ep
= path_make_absolute("ep0", p
->path
);
1694 p
->fd
= usbffs_address_create(ep
);
1698 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1702 r
= usbffs_dispatch_eps(p
);
1709 assert_not_reached();
1717 static void socket_unwatch_fds(Socket
*s
) {
1722 LIST_FOREACH(port
, p
, s
->ports
) {
1726 if (!p
->event_source
)
1729 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1731 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1735 static int socket_watch_fds(Socket
*s
) {
1740 LIST_FOREACH(port
, p
, s
->ports
) {
1744 if (p
->event_source
) {
1745 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1749 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1753 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1756 r
= sd_event_source_set_ratelimit(p
->event_source
, s
->poll_limit_interval
, s
->poll_limit_burst
);
1758 log_unit_debug_errno(UNIT(s
), r
, "Failed to set poll limit on I/O event source, ignoring: %m");
1764 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1765 socket_unwatch_fds(s
);
1775 static int socket_check_open(Socket
*s
) {
1776 bool have_open
= false, have_closed
= false;
1780 LIST_FOREACH(port
, p
, s
->ports
) {
1786 if (have_open
&& have_closed
)
1787 return SOCKET_OPEN_SOME
;
1791 return SOCKET_OPEN_ALL
;
1793 return SOCKET_OPEN_NONE
;
1796 static void socket_set_state(Socket
*s
, SocketState state
) {
1797 SocketState old_state
;
1800 if (s
->state
!= state
)
1801 bus_unit_send_pending_change_signal(UNIT(s
), false);
1803 old_state
= s
->state
;
1811 SOCKET_STOP_PRE_SIGTERM
,
1812 SOCKET_STOP_PRE_SIGKILL
,
1814 SOCKET_FINAL_SIGTERM
,
1815 SOCKET_FINAL_SIGKILL
,
1818 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
1819 socket_unwatch_control_pid(s
);
1820 s
->control_command
= NULL
;
1821 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1824 if (state
!= SOCKET_LISTENING
)
1825 socket_unwatch_fds(s
);
1833 SOCKET_STOP_PRE_SIGTERM
,
1834 SOCKET_STOP_PRE_SIGKILL
,
1836 socket_close_fds(s
);
1838 if (state
!= old_state
)
1839 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1841 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], /* reload_success = */ true);
1844 static int socket_coldplug(Unit
*u
) {
1845 Socket
*s
= SOCKET(u
);
1849 assert(s
->state
== SOCKET_DEAD
);
1851 if (s
->deserialized_state
== s
->state
)
1854 if (pidref_is_set(&s
->control_pid
) &&
1855 pid_is_unwaited(s
->control_pid
.pid
) &&
1856 IN_SET(s
->deserialized_state
,
1861 SOCKET_STOP_PRE_SIGTERM
,
1862 SOCKET_STOP_PRE_SIGKILL
,
1864 SOCKET_FINAL_SIGTERM
,
1865 SOCKET_FINAL_SIGKILL
,
1868 r
= unit_watch_pid(UNIT(s
), s
->control_pid
.pid
, /* exclusive= */ false);
1872 r
= socket_arm_timer(s
, /* relative= */ false, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1877 if (IN_SET(s
->deserialized_state
,
1883 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1884 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN state for
1885 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1886 * and if there's a mismatch, warn loudly. */
1888 r
= socket_check_open(s
);
1889 if (r
== SOCKET_OPEN_NONE
)
1890 log_unit_warning(UNIT(s
),
1891 "Socket unit configuration has changed while unit has been running, "
1892 "no open socket file descriptor left. "
1893 "The socket unit is not functional until restarted.");
1894 else if (r
== SOCKET_OPEN_SOME
)
1895 log_unit_warning(UNIT(s
),
1896 "Socket unit configuration has changed while unit has been running, "
1897 "and some socket file descriptors have not been opened yet. "
1898 "The socket unit is not fully functional until restarted.");
1901 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1902 r
= socket_watch_fds(s
);
1907 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
, SOCKET_CLEANING
))
1908 (void) unit_setup_exec_runtime(u
);
1910 socket_set_state(s
, s
->deserialized_state
);
1914 static int socket_spawn(Socket
*s
, ExecCommand
*c
, PidRef
*ret_pid
) {
1916 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1917 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1919 .stdout_fd
= -EBADF
,
1920 .stderr_fd
= -EBADF
,
1923 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1931 r
= unit_prepare_exec(UNIT(s
));
1935 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
1939 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1943 r
= exec_spawn(UNIT(s
),
1953 r
= pidref_set_pid(&pidref
, pid
);
1957 r
= unit_watch_pid(UNIT(s
), pidref
.pid
, /* exclusive= */ true);
1961 *ret_pid
= TAKE_PIDREF(pidref
);
1965 static int socket_chown(Socket
*s
, PidRef
*ret_pid
) {
1966 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
1971 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
1975 /* We have to resolve the user names out-of-process, hence
1976 * let's fork here. It's messy, but well, what can we do? */
1978 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1982 uid_t uid
= UID_INVALID
;
1983 gid_t gid
= GID_INVALID
;
1987 if (!isempty(s
->user
)) {
1988 const char *user
= s
->user
;
1990 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1992 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1997 if (!isempty(s
->group
)) {
1998 const char *group
= s
->group
;
2000 r
= get_group_creds(&group
, &gid
, 0);
2002 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
2007 LIST_FOREACH(port
, p
, s
->ports
) {
2008 const char *path
= NULL
;
2010 if (p
->type
== SOCKET_SOCKET
)
2011 path
= socket_address_get_path(&p
->address
);
2012 else if (p
->type
== SOCKET_FIFO
)
2018 if (chown(path
, uid
, gid
) < 0) {
2019 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
2024 _exit(EXIT_SUCCESS
);
2027 r
= unit_watch_pid(UNIT(s
), pid
.pid
, /* exclusive= */ true);
2031 *ret_pid
= TAKE_PIDREF(pid
);
2035 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
2038 if (s
->result
== SOCKET_SUCCESS
)
2041 if (s
->result
== SOCKET_SUCCESS
)
2042 unit_log_success(UNIT(s
));
2044 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
2046 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_stop
);
2048 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
2050 s
->exec_runtime
= exec_runtime_destroy(s
->exec_runtime
);
2052 unit_destroy_runtime_data(UNIT(s
), &s
->exec_context
);
2054 unit_unref_uid_gid(UNIT(s
), true);
2057 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2059 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2063 if (s
->result
== SOCKET_SUCCESS
)
2066 socket_unwatch_control_pid(s
);
2067 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2068 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2070 if (s
->control_command
) {
2071 pidref_done(&s
->control_pid
);
2073 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2075 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-post' task: %m");
2076 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2080 socket_set_state(s
, SOCKET_STOP_POST
);
2082 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2085 static int state_to_kill_operation(Socket
*s
, SocketState state
) {
2086 if (state
== SOCKET_STOP_PRE_SIGTERM
&& unit_has_job_type(UNIT(s
), JOB_RESTART
))
2087 return KILL_RESTART
;
2089 if (state
== SOCKET_FINAL_SIGTERM
)
2090 return KILL_TERMINATE
;
2095 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2100 if (s
->result
== SOCKET_SUCCESS
)
2103 r
= unit_kill_context(
2106 state_to_kill_operation(s
, state
),
2107 /* main_pid= */ NULL
,
2109 /* main_pid_alien= */ false);
2111 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2116 r
= socket_arm_timer(s
, /* relative= */ true, s
->timeout_usec
);
2118 log_unit_warning_errno(UNIT(s
), r
, "Failed to install timer: %m");
2122 socket_set_state(s
, state
);
2123 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2124 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2125 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2126 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2127 else if (state
== SOCKET_FINAL_SIGTERM
)
2128 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2130 socket_enter_dead(s
, SOCKET_SUCCESS
);
2135 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2136 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2138 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2141 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2145 if (s
->result
== SOCKET_SUCCESS
)
2148 socket_unwatch_control_pid(s
);
2149 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2150 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2152 if (s
->control_command
) {
2153 pidref_done(&s
->control_pid
);
2155 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2157 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'stop-pre' task: %m");
2158 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2162 socket_set_state(s
, SOCKET_STOP_PRE
);
2164 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2167 static void socket_enter_listening(Socket
*s
) {
2171 if (!s
->accept
&& s
->flush_pending
) {
2172 log_unit_debug(UNIT(s
), "Flushing socket before listening.");
2176 r
= socket_watch_fds(s
);
2178 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2179 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2183 socket_set_state(s
, SOCKET_LISTENING
);
2186 static void socket_enter_start_post(Socket
*s
) {
2190 socket_unwatch_control_pid(s
);
2191 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2192 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2194 if (s
->control_command
) {
2195 pidref_done(&s
->control_pid
);
2197 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2199 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-post' task: %m");
2200 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2204 socket_set_state(s
, SOCKET_START_POST
);
2206 socket_enter_listening(s
);
2209 static void socket_enter_start_chown(Socket
*s
) {
2214 r
= socket_open_fds(s
);
2216 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2220 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2222 socket_unwatch_control_pid(s
);
2223 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2224 s
->control_command
= NULL
;
2226 r
= socket_chown(s
, &s
->control_pid
);
2228 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-chown' task: %m");
2232 socket_set_state(s
, SOCKET_START_CHOWN
);
2234 socket_enter_start_post(s
);
2239 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2242 static void socket_enter_start_pre(Socket
*s
) {
2246 socket_unwatch_control_pid(s
);
2248 unit_warn_leftover_processes(UNIT(s
), unit_log_leftover_process_start
);
2250 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2251 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2253 if (s
->control_command
) {
2254 pidref_done(&s
->control_pid
);
2256 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2258 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn 'start-pre' task: %m");
2259 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2263 socket_set_state(s
, SOCKET_START_PRE
);
2265 socket_enter_start_chown(s
);
2268 static void flush_ports(Socket
*s
) {
2271 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2274 LIST_FOREACH(port
, p
, s
->ports
) {
2278 (void) flush_accept(p
->fd
);
2279 (void) flush_fd(p
->fd
);
2283 static void socket_enter_running(Socket
*s
, int cfd_in
) {
2284 /* Note that this call takes possession of the connection fd passed. It either has to assign it
2285 * somewhere or close it. */
2286 _cleanup_close_
int cfd
= cfd_in
;
2288 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2293 /* We don't take connections anymore if we are supposed to shut down anyway */
2294 if (unit_stop_pending(UNIT(s
))) {
2296 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2305 if (!ratelimit_below(&s
->trigger_limit
)) {
2306 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2307 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2311 if (cfd
< 0) { /* Accept=no case */
2312 bool pending
= false;
2315 /* If there's already a start pending don't bother to do anything */
2316 UNIT_FOREACH_DEPENDENCY(other
, UNIT(s
), UNIT_ATOM_TRIGGERS
)
2317 if (unit_active_or_pending(other
)) {
2323 if (!UNIT_ISSET(s
->service
)) {
2324 r
= log_unit_warning_errno(UNIT(s
), SYNTHETIC_ERRNO(ENOENT
),
2325 "Service to activate vanished, refusing activation.");
2329 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, NULL
, &error
, NULL
);
2334 socket_set_state(s
, SOCKET_RUNNING
);
2335 } else { /* Accept=yes case */
2336 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2339 if (s
->n_connections
>= s
->max_connections
) {
2340 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2345 if (s
->max_connections_per_source
> 0) {
2346 r
= socket_acquire_peer(s
, cfd
, &p
);
2348 if (ERRNO_IS_DISCONNECT(r
))
2350 /* We didn't have enough resources to acquire peer information, let's fail. */
2353 if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2354 _cleanup_free_
char *t
= NULL
;
2356 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2358 log_unit_warning(UNIT(s
),
2359 "Too many incoming connections (%u) from source %s, dropping connection.",
2360 p
->n_ref
, strnull(t
));
2365 r
= socket_load_service_unit(s
, cfd
, &service
);
2367 if (ERRNO_IS_DISCONNECT(r
))
2370 log_unit_warning_errno(UNIT(s
), r
, "Failed to load connection service unit: %m");
2374 r
= unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, service
,
2375 false, UNIT_DEPENDENCY_IMPLICIT
);
2377 log_unit_warning_errno(UNIT(s
), r
, "Failed to add Before=/Triggers= dependencies on connection unit: %m");
2383 r
= service_set_socket_fd(SERVICE(service
), cfd
, s
, p
, s
->selinux_context_from_net
);
2385 if (ERRNO_IS_DISCONNECT(r
))
2388 log_unit_warning_errno(UNIT(s
), r
, "Failed to set socket on service: %m");
2392 TAKE_FD(cfd
); /* We passed ownership of the fd to the service now. Forget it here. */
2395 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, service
, JOB_REPLACE
, NULL
, &error
, NULL
);
2397 /* We failed to activate the new service, but it still exists. Let's make sure the
2398 * service closes and forgets the connection fd again, immediately. */
2399 service_release_socket_fd(SERVICE(service
));
2403 /* Notify clients about changed counters */
2404 unit_add_to_dbus_queue(UNIT(s
));
2414 if (ERRNO_IS_RESOURCE(r
))
2415 log_unit_warning(UNIT(s
), "Failed to queue service startup job: %s",
2416 bus_error_message(&error
, r
));
2418 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2419 cfd
>= 0 ? "template" : "non-template",
2420 bus_error_message(&error
, r
));
2423 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2426 static void socket_run_next(Socket
*s
) {
2430 assert(s
->control_command
);
2431 assert(s
->control_command
->command_next
);
2433 socket_unwatch_control_pid(s
);
2435 s
->control_command
= s
->control_command
->command_next
;
2437 pidref_done(&s
->control_pid
);
2439 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2441 log_unit_warning_errno(UNIT(s
), r
, "Failed to spawn next task: %m");
2443 if (s
->state
== SOCKET_START_POST
)
2444 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2445 else if (s
->state
== SOCKET_STOP_POST
)
2446 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2448 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2452 static int socket_start(Unit
*u
) {
2453 Socket
*s
= SOCKET(u
);
2458 /* We cannot fulfill this request right now, try again later
2460 if (IN_SET(s
->state
,
2462 SOCKET_STOP_PRE_SIGKILL
,
2463 SOCKET_STOP_PRE_SIGTERM
,
2465 SOCKET_FINAL_SIGTERM
,
2466 SOCKET_FINAL_SIGKILL
,
2470 /* Already on it! */
2471 if (IN_SET(s
->state
,
2477 /* Cannot run this without the service being around */
2478 if (UNIT_ISSET(s
->service
)) {
2481 service
= SERVICE(UNIT_DEREF(s
->service
));
2483 if (UNIT(service
)->load_state
!= UNIT_LOADED
)
2484 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(ENOENT
),
2485 "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2487 /* If the service is already active we cannot start the
2489 if (!IN_SET(service
->state
,
2490 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
2491 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
2492 return log_unit_error_errno(u
, SYNTHETIC_ERRNO(EBUSY
),
2493 "Socket service %s already active, refusing.", UNIT(service
)->id
);
2496 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2498 r
= unit_acquire_invocation_id(u
);
2502 s
->result
= SOCKET_SUCCESS
;
2503 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2505 u
->reset_accounting
= true;
2507 socket_enter_start_pre(s
);
2511 static int socket_stop(Unit
*u
) {
2512 Socket
*s
= SOCKET(u
);
2517 if (IN_SET(s
->state
,
2519 SOCKET_STOP_PRE_SIGTERM
,
2520 SOCKET_STOP_PRE_SIGKILL
,
2522 SOCKET_FINAL_SIGTERM
,
2523 SOCKET_FINAL_SIGKILL
))
2526 /* If there's already something running we go directly into
2528 if (IN_SET(s
->state
,
2531 SOCKET_START_POST
)) {
2532 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2536 /* If we are currently cleaning, then abort it, brutally. */
2537 if (s
->state
== SOCKET_CLEANING
) {
2538 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2542 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2544 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2548 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2549 Socket
*s
= SOCKET(u
);
2556 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2557 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2558 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2559 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2561 if (pidref_is_set(&s
->control_pid
))
2562 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
.pid
);
2564 if (s
->control_command_id
>= 0)
2565 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2567 LIST_FOREACH(port
, p
, s
->ports
) {
2573 copy
= fdset_put_dup(fds
, p
->fd
);
2575 return log_unit_warning_errno(u
, copy
, "Failed to serialize socket fd: %m");
2577 if (p
->type
== SOCKET_SOCKET
) {
2578 _cleanup_free_
char *t
= NULL
;
2580 r
= socket_address_print(&p
->address
, &t
);
2582 return log_unit_error_errno(u
, r
, "Failed to format socket address: %m");
2584 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2585 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2587 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2588 } else if (p
->type
== SOCKET_SPECIAL
)
2589 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2590 else if (p
->type
== SOCKET_MQUEUE
)
2591 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2592 else if (p
->type
== SOCKET_USB_FUNCTION
)
2593 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2595 assert(p
->type
== SOCKET_FIFO
);
2596 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2603 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2604 Socket
*s
= SOCKET(u
);
2611 if (streq(key
, "state")) {
2614 state
= socket_state_from_string(value
);
2616 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2618 s
->deserialized_state
= state
;
2619 } else if (streq(key
, "result")) {
2622 f
= socket_result_from_string(value
);
2624 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2625 else if (f
!= SOCKET_SUCCESS
)
2628 } else if (streq(key
, "n-accepted")) {
2631 if (safe_atou(value
, &k
) < 0)
2632 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2635 } else if (streq(key
, "n-refused")) {
2638 if (safe_atou(value
, &k
) < 0)
2639 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2642 } else if (streq(key
, "control-pid")) {
2643 pidref_done(&s
->control_pid
);
2644 r
= pidref_set_pidstr(&s
->control_pid
, value
);
2646 log_debug_errno(r
, "Failed to pin control PID '%s', ignoring: %m", value
);
2647 } else if (streq(key
, "control-command")) {
2648 SocketExecCommand id
;
2650 id
= socket_exec_command_from_string(value
);
2652 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2654 s
->control_command_id
= id
;
2655 s
->control_command
= s
->exec_command
[id
];
2657 } else if (streq(key
, "fifo")) {
2658 _cleanup_free_
char *fdv
= NULL
;
2662 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2664 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2669 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2670 log_unit_debug(u
, "Invalid fifo value: %s", fdv
);
2674 LIST_FOREACH(port
, p
, s
->ports
)
2676 p
->type
== SOCKET_FIFO
&&
2677 path_equal_or_inode_same(p
->path
, value
, 0)) {
2678 p
->fd
= fdset_remove(fds
, fd
);
2683 log_unit_debug(u
, "No matching fifo socket found: %s", value
);
2685 } else if (streq(key
, "special")) {
2686 _cleanup_free_
char *fdv
= NULL
;
2690 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2692 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2697 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2698 log_unit_debug(u
, "Invalid special value: %s", fdv
);
2702 LIST_FOREACH(port
, p
, s
->ports
)
2704 p
->type
== SOCKET_SPECIAL
&&
2705 path_equal_or_inode_same(p
->path
, value
, 0)) {
2706 p
->fd
= fdset_remove(fds
, fd
);
2711 log_unit_debug(u
, "No matching special socket found: %s", value
);
2713 } else if (streq(key
, "mqueue")) {
2714 _cleanup_free_
char *fdv
= NULL
;
2718 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2720 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2725 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2726 log_unit_debug(u
, "Invalid mqueue value: %s", fdv
);
2730 LIST_FOREACH(port
, p
, s
->ports
)
2732 p
->type
== SOCKET_MQUEUE
&&
2733 streq(p
->path
, value
)) {
2734 p
->fd
= fdset_remove(fds
, fd
);
2739 log_unit_debug(u
, "No matching mqueue socket found: %s", value
);
2741 } else if (streq(key
, "socket")) {
2742 _cleanup_free_
char *fdv
= NULL
, *typev
= NULL
;
2746 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2748 log_unit_debug(u
, "Failed to parse socket fd from value: %s", value
);
2753 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2754 log_unit_debug(u
, "Invalid socket fd: %s", fdv
);
2758 r
= extract_first_word(&value
, &typev
, NULL
, 0);
2760 log_unit_debug(u
, "Failed to parse socket type from value: %s", value
);
2764 if (safe_atoi(typev
, &type
) < 0 || type
< 0) {
2765 log_unit_debug(u
, "Invalid socket type: %s", typev
);
2769 LIST_FOREACH(port
, p
, s
->ports
)
2771 socket_address_is(&p
->address
, value
, type
)) {
2772 p
->fd
= fdset_remove(fds
, fd
);
2777 log_unit_debug(u
, "No matching %s socket found: %s",
2778 socket_address_type_to_string(type
), value
);
2780 } else if (streq(key
, "netlink")) {
2781 _cleanup_free_
char *fdv
= NULL
;
2785 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2787 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2792 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2793 log_unit_debug(u
, "Invalid socket value: %s", fdv
);
2797 LIST_FOREACH(port
, p
, s
->ports
)
2799 socket_address_is_netlink(&p
->address
, value
)) {
2800 p
->fd
= fdset_remove(fds
, fd
);
2805 log_unit_debug(u
, "No matching netlink socket found: %s", value
);
2807 } else if (streq(key
, "ffs")) {
2808 _cleanup_free_
char *fdv
= NULL
;
2812 r
= extract_first_word(&value
, &fdv
, NULL
, 0);
2814 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2819 if (fd
< 0 || !fdset_contains(fds
, fd
)) {
2820 log_unit_debug(u
, "Invalid ffs value: %s", fdv
);
2824 LIST_FOREACH(port
, p
, s
->ports
)
2826 p
->type
== SOCKET_USB_FUNCTION
&&
2827 path_equal_or_inode_same(p
->path
, value
, 0)) {
2828 p
->fd
= fdset_remove(fds
, fd
);
2833 log_unit_debug(u
, "No matching ffs socket found: %s", value
);
2836 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2841 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2842 Socket
*s
= SOCKET(u
);
2846 LIST_FOREACH(port
, p
, s
->ports
) {
2849 if (p
->type
!= SOCKET_SOCKET
)
2855 FDSET_FOREACH(fd
, fds
) {
2856 if (socket_address_matches_fd(&p
->address
, fd
)) {
2857 p
->fd
= fdset_remove(fds
, fd
);
2858 s
->deserialized_state
= SOCKET_LISTENING
;
2865 static UnitActiveState
socket_active_state(Unit
*u
) {
2868 return state_translation_table
[SOCKET(u
)->state
];
2871 static const char *socket_sub_state_to_string(Unit
*u
) {
2874 return socket_state_to_string(SOCKET(u
)->state
);
2877 const char* socket_port_type_to_string(SocketPort
*p
) {
2885 switch (p
->address
.type
) {
2893 case SOCK_SEQPACKET
:
2894 return "SequentialPacket";
2897 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2905 case SOCKET_SPECIAL
:
2909 return "MessageQueue";
2914 case SOCKET_USB_FUNCTION
:
2915 return "USBFunction";
2922 SocketType
socket_port_type_from_string(const char *s
) {
2925 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2926 return SOCKET_SOCKET
;
2927 else if (streq(s
, "Special"))
2928 return SOCKET_SPECIAL
;
2929 else if (streq(s
, "MessageQueue"))
2930 return SOCKET_MQUEUE
;
2931 else if (streq(s
, "FIFO"))
2933 else if (streq(s
, "USBFunction"))
2934 return SOCKET_USB_FUNCTION
;
2936 return _SOCKET_TYPE_INVALID
;
2939 static bool socket_may_gc(Unit
*u
) {
2940 Socket
*s
= SOCKET(u
);
2944 return s
->n_connections
== 0;
2947 static int socket_accept_do(Socket
*s
, int fd
) {
2953 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
|SOCK_CLOEXEC
);
2955 /* Convert transient network errors into clean and well-defined EAGAIN */
2956 return ERRNO_IS_ACCEPT_AGAIN(errno
) ? -EAGAIN
: -errno
;
2961 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2962 _cleanup_(pidref_done
) PidRef pid
= PIDREF_NULL
;
2963 _cleanup_close_pair_
int pair
[2] = PIPE_EBADF
;
2970 /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
2971 * connection socket is also properly associated with the cgroup. */
2973 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2976 r
= bpf_firewall_supported();
2979 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2982 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2983 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2985 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2987 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2991 pair
[0] = safe_close(pair
[0]);
2993 cfd
= socket_accept_do(s
, fd
);
2994 if (cfd
== -EAGAIN
) /* spurious accept() */
2995 _exit(EXIT_SUCCESS
);
2997 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2998 _exit(EXIT_FAILURE
);
3001 r
= send_one_fd(pair
[1], cfd
, 0);
3003 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
3004 _exit(EXIT_FAILURE
);
3007 _exit(EXIT_SUCCESS
);
3010 pair
[1] = safe_close(pair
[1]);
3011 cfd
= receive_one_fd(pair
[0], 0);
3013 /* We synchronously wait for the helper, as it shouldn't be slow */
3014 r
= wait_for_terminate_and_check("(sd-accept)", pid
.pid
, WAIT_LOG_ABNORMAL
);
3020 /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3021 * this is a spurious accept(), let's convert that back to EAGAIN here. */
3025 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
3030 cfd
= socket_accept_do(s
, fd
);
3031 if (cfd
== -EAGAIN
) /* spurious accept(), skip it silently */
3034 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
3039 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
3040 SocketPort
*p
= ASSERT_PTR(userdata
);
3045 if (p
->socket
->state
!= SOCKET_LISTENING
)
3048 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
3050 if (revents
!= EPOLLIN
) {
3051 if (revents
& EPOLLHUP
)
3052 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.");
3054 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
3058 if (p
->socket
->accept
&&
3059 p
->type
== SOCKET_SOCKET
&&
3060 socket_address_can_accept(&p
->address
)) {
3062 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
3063 if (cfd
== -EAGAIN
) /* Spurious accept() */
3068 socket_apply_socket_options(p
->socket
, p
, cfd
);
3071 socket_enter_running(p
->socket
, cfd
);
3075 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
3079 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
3080 Socket
*s
= SOCKET(u
);
3086 if (pid
!= s
->control_pid
.pid
)
3089 pidref_done(&s
->control_pid
);
3091 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
3093 else if (code
== CLD_EXITED
)
3094 f
= SOCKET_FAILURE_EXIT_CODE
;
3095 else if (code
== CLD_KILLED
)
3096 f
= SOCKET_FAILURE_SIGNAL
;
3097 else if (code
== CLD_DUMPED
)
3098 f
= SOCKET_FAILURE_CORE_DUMP
;
3100 assert_not_reached();
3102 if (s
->control_command
) {
3103 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
3105 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
3109 unit_log_process_exit(
3112 socket_exec_command_to_string(s
->control_command_id
),
3113 f
== SOCKET_SUCCESS
,
3116 if (s
->result
== SOCKET_SUCCESS
)
3119 if (s
->control_command
&&
3120 s
->control_command
->command_next
&&
3121 f
== SOCKET_SUCCESS
) {
3123 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
3126 s
->control_command
= NULL
;
3127 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3129 /* No further commands for this step, so let's figure
3130 * out what to do next */
3132 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
3136 case SOCKET_START_PRE
:
3137 if (f
== SOCKET_SUCCESS
)
3138 socket_enter_start_chown(s
);
3140 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3143 case SOCKET_START_CHOWN
:
3144 if (f
== SOCKET_SUCCESS
)
3145 socket_enter_start_post(s
);
3147 socket_enter_stop_pre(s
, f
);
3150 case SOCKET_START_POST
:
3151 if (f
== SOCKET_SUCCESS
)
3152 socket_enter_listening(s
);
3154 socket_enter_stop_pre(s
, f
);
3157 case SOCKET_STOP_PRE
:
3158 case SOCKET_STOP_PRE_SIGTERM
:
3159 case SOCKET_STOP_PRE_SIGKILL
:
3160 socket_enter_stop_post(s
, f
);
3163 case SOCKET_STOP_POST
:
3164 case SOCKET_FINAL_SIGTERM
:
3165 case SOCKET_FINAL_SIGKILL
:
3166 socket_enter_dead(s
, f
);
3169 case SOCKET_CLEANING
:
3171 if (s
->clean_result
== SOCKET_SUCCESS
)
3172 s
->clean_result
= f
;
3174 socket_enter_dead(s
, SOCKET_SUCCESS
);
3178 assert_not_reached();
3182 /* Notify clients about changed exit status */
3183 unit_add_to_dbus_queue(u
);
3186 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3187 Socket
*s
= SOCKET(userdata
);
3190 assert(s
->timer_event_source
== source
);
3194 case SOCKET_START_PRE
:
3195 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3196 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3199 case SOCKET_START_CHOWN
:
3200 case SOCKET_START_POST
:
3201 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3202 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3205 case SOCKET_STOP_PRE
:
3206 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3207 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3210 case SOCKET_STOP_PRE_SIGTERM
:
3211 if (s
->kill_context
.send_sigkill
) {
3212 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3213 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3215 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3216 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3220 case SOCKET_STOP_PRE_SIGKILL
:
3221 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3222 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3225 case SOCKET_STOP_POST
:
3226 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3227 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3230 case SOCKET_FINAL_SIGTERM
:
3231 if (s
->kill_context
.send_sigkill
) {
3232 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3233 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3235 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3236 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3240 case SOCKET_FINAL_SIGKILL
:
3241 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3242 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3245 case SOCKET_CLEANING
:
3246 log_unit_warning(UNIT(s
), "Cleaning timed out. killing.");
3248 if (s
->clean_result
== SOCKET_SUCCESS
)
3249 s
->clean_result
= SOCKET_FAILURE_TIMEOUT
;
3251 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, 0);
3255 assert_not_reached();
3261 int socket_collect_fds(Socket
*s
, int **fds
) {
3262 size_t k
= 0, n
= 0;
3268 /* Called from the service code for requesting our fds */
3270 LIST_FOREACH(port
, p
, s
->ports
) {
3273 n
+= p
->n_auxiliary_fds
;
3285 LIST_FOREACH(port
, p
, s
->ports
) {
3288 for (size_t i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3289 rfds
[k
++] = p
->auxiliary_fds
[i
];
3298 static void socket_reset_failed(Unit
*u
) {
3299 Socket
*s
= SOCKET(u
);
3303 if (s
->state
== SOCKET_FAILED
)
3304 socket_set_state(s
, SOCKET_DEAD
);
3306 s
->result
= SOCKET_SUCCESS
;
3307 s
->clean_result
= SOCKET_SUCCESS
;
3310 void socket_connection_unref(Socket
*s
) {
3313 /* The service is dead. Yay!
3315 * This is strictly for one-instance-per-connection
3318 assert(s
->n_connections
> 0);
3321 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3324 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3325 Socket
*s
= SOCKET(u
);
3330 /* Filter out invocations with bogus state */
3331 assert(UNIT_IS_LOAD_COMPLETE(other
->load_state
));
3332 assert(other
->type
== UNIT_SERVICE
);
3334 /* Don't propagate state changes from the service if we are already down */
3335 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3338 /* We don't care for the service state if we are in Accept=yes mode */
3342 /* Propagate start limit hit state */
3343 if (other
->start_limit_hit
) {
3344 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3348 /* Don't propagate anything if there's still a job queued */
3352 if (IN_SET(SERVICE(other
)->state
,
3353 SERVICE_DEAD
, SERVICE_DEAD_BEFORE_AUTO_RESTART
, SERVICE_FAILED
, SERVICE_FAILED_BEFORE_AUTO_RESTART
,
3354 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3355 SERVICE_AUTO_RESTART
, SERVICE_AUTO_RESTART_QUEUED
))
3356 socket_enter_listening(s
);
3358 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3359 socket_set_state(s
, SOCKET_RUNNING
);
3362 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3363 Socket
*s
= SOCKET(u
);
3367 if (!s
->timer_event_source
)
3370 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3373 if (t
== USEC_INFINITY
)
3380 char *socket_fdname(Socket
*s
) {
3383 /* Returns the name to use for $LISTEN_NAMES. If the user
3384 * didn't specify anything specifically, use the socket unit's
3385 * name as fallback. */
3387 return s
->fdname
?: UNIT(s
)->id
;
3390 static PidRef
*socket_control_pid(Unit
*u
) {
3391 return &ASSERT_PTR(SOCKET(u
))->control_pid
;
3394 static int socket_clean(Unit
*u
, ExecCleanMask mask
) {
3395 _cleanup_strv_free_
char **l
= NULL
;
3396 Socket
*s
= SOCKET(u
);
3402 if (s
->state
!= SOCKET_DEAD
)
3405 r
= exec_context_get_clean_directories(&s
->exec_context
, u
->manager
->prefix
, mask
, &l
);
3409 if (strv_isempty(l
))
3412 socket_unwatch_control_pid(s
);
3413 s
->clean_result
= SOCKET_SUCCESS
;
3414 s
->control_command
= NULL
;
3415 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
3417 r
= socket_arm_timer(s
, /* relative= */ true, s
->exec_context
.timeout_clean_usec
);
3419 log_unit_warning_errno(u
, r
, "Failed to install timer: %m");
3423 r
= unit_fork_and_watch_rm_rf(u
, l
, &s
->control_pid
);
3425 log_unit_warning_errno(u
, r
, "Failed to spawn cleaning task: %m");
3429 socket_set_state(s
, SOCKET_CLEANING
);
3433 s
->clean_result
= SOCKET_FAILURE_RESOURCES
;
3434 s
->timer_event_source
= sd_event_source_disable_unref(s
->timer_event_source
);
3438 static int socket_can_clean(Unit
*u
, ExecCleanMask
*ret
) {
3439 Socket
*s
= SOCKET(u
);
3443 return exec_context_get_clean_mask(&s
->exec_context
, ret
);
3446 static int socket_can_start(Unit
*u
) {
3447 Socket
*s
= SOCKET(u
);
3452 r
= unit_test_start_limit(u
);
3454 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
3461 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3462 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3463 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3464 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3465 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3466 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3469 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3471 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3472 [SOCKET_SUCCESS
] = "success",
3473 [SOCKET_FAILURE_RESOURCES
] = "resources",
3474 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3475 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3476 [SOCKET_FAILURE_SIGNAL
] = "signal",
3477 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3478 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3479 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3480 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3483 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3485 static const char* const socket_timestamping_table
[_SOCKET_TIMESTAMPING_MAX
] = {
3486 [SOCKET_TIMESTAMPING_OFF
] = "off",
3487 [SOCKET_TIMESTAMPING_US
] = "us",
3488 [SOCKET_TIMESTAMPING_NS
] = "ns",
3491 DEFINE_STRING_TABLE_LOOKUP(socket_timestamping
, SocketTimestamping
);
3493 SocketTimestamping
socket_timestamping_from_string_harder(const char *p
) {
3494 SocketTimestamping t
;
3498 return _SOCKET_TIMESTAMPING_INVALID
;
3500 t
= socket_timestamping_from_string(p
);
3504 /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3506 if (streq(p
, "nsec"))
3507 return SOCKET_TIMESTAMPING_NS
;
3508 if (STR_IN_SET(p
, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
3509 return SOCKET_TIMESTAMPING_US
;
3511 r
= parse_boolean(p
);
3513 return _SOCKET_TIMESTAMPING_INVALID
;
3515 return r
? SOCKET_TIMESTAMPING_NS
: SOCKET_TIMESTAMPING_OFF
; /* If boolean yes, default to ns accuracy */
3518 const UnitVTable socket_vtable
= {
3519 .object_size
= sizeof(Socket
),
3520 .exec_context_offset
= offsetof(Socket
, exec_context
),
3521 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3522 .kill_context_offset
= offsetof(Socket
, kill_context
),
3523 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3529 .private_section
= "Socket",
3531 .can_transient
= true,
3532 .can_trigger
= true,
3535 .init
= socket_init
,
3536 .done
= socket_done
,
3537 .load
= socket_load
,
3539 .coldplug
= socket_coldplug
,
3541 .dump
= socket_dump
,
3543 .start
= socket_start
,
3544 .stop
= socket_stop
,
3546 .clean
= socket_clean
,
3547 .can_clean
= socket_can_clean
,
3549 .get_timeout
= socket_get_timeout
,
3551 .serialize
= socket_serialize
,
3552 .deserialize_item
= socket_deserialize_item
,
3553 .distribute_fds
= socket_distribute_fds
,
3555 .active_state
= socket_active_state
,
3556 .sub_state_to_string
= socket_sub_state_to_string
,
3558 .will_restart
= unit_will_restart_default
,
3560 .may_gc
= socket_may_gc
,
3562 .sigchld_event
= socket_sigchld_event
,
3564 .trigger_notify
= socket_trigger_notify
,
3566 .reset_failed
= socket_reset_failed
,
3568 .control_pid
= socket_control_pid
,
3570 .bus_set_property
= bus_socket_set_property
,
3571 .bus_commit_properties
= bus_socket_commit_properties
,
3573 .status_message_formats
= {
3574 .finished_start_job
= {
3575 [JOB_DONE
] = "Listening on %s.",
3576 [JOB_FAILED
] = "Failed to listen on %s.",
3577 [JOB_TIMEOUT
] = "Timed out starting %s.",
3579 .finished_stop_job
= {
3580 [JOB_DONE
] = "Closed %s.",
3581 [JOB_FAILED
] = "Failed stopping %s.",
3582 [JOB_TIMEOUT
] = "Timed out stopping %s.",
3586 .can_start
= socket_can_start
,