1 /* SPDX-License-Identifier: LGPL-2.1+ */
7 #include <netinet/tcp.h>
12 #include <linux/sctp.h>
14 #include "alloc-util.h"
15 #include "bpf-firewall.h"
16 #include "bus-error.h"
19 #include "dbus-socket.h"
21 #include "exit-status.h"
23 #include "format-util.h"
25 #include "in-addr-util.h"
27 #include "ip-protocol-list.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"
37 #include "signal-util.h"
38 #include "smack-util.h"
41 #include "string-table.h"
42 #include "string-util.h"
44 #include "unit-name.h"
46 #include "user-util.h"
52 union sockaddr_union peer
;
56 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
57 [SOCKET_DEAD
] = UNIT_INACTIVE
,
58 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
59 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
60 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
61 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
62 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
63 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
64 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
65 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
66 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
67 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
68 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
69 [SOCKET_FAILED
] = UNIT_FAILED
72 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
73 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
75 static void socket_init(Unit
*u
) {
76 Socket
*s
= SOCKET(u
);
79 assert(u
->load_state
== UNIT_STUB
);
81 s
->backlog
= SOMAXCONN
;
82 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
83 s
->directory_mode
= 0755;
84 s
->socket_mode
= 0666;
86 s
->max_connections
= 64;
93 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
94 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
96 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
98 s
->trigger_limit
.interval
= USEC_INFINITY
;
99 s
->trigger_limit
.burst
= (unsigned) -1;
102 static void socket_unwatch_control_pid(Socket
*s
) {
105 if (s
->control_pid
<= 0)
108 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
112 static void socket_cleanup_fd_list(SocketPort
*p
) {
115 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
116 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
117 p
->n_auxiliary_fds
= 0;
120 void socket_free_ports(Socket
*s
) {
125 while ((p
= s
->ports
)) {
126 LIST_REMOVE(port
, s
->ports
, p
);
128 sd_event_source_unref(p
->event_source
);
130 socket_cleanup_fd_list(p
);
137 static void socket_done(Unit
*u
) {
138 Socket
*s
= SOCKET(u
);
143 socket_free_ports(s
);
145 while ((p
= set_steal_first(s
->peers_by_address
)))
148 s
->peers_by_address
= set_free(s
->peers_by_address
);
150 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
151 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
152 s
->control_command
= NULL
;
154 dynamic_creds_unref(&s
->dynamic_creds
);
156 socket_unwatch_control_pid(s
);
158 unit_ref_unset(&s
->service
);
160 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
161 s
->bind_to_device
= mfree(s
->bind_to_device
);
163 s
->smack
= mfree(s
->smack
);
164 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
165 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
167 strv_free(s
->symlinks
);
169 s
->user
= mfree(s
->user
);
170 s
->group
= mfree(s
->group
);
172 s
->fdname
= mfree(s
->fdname
);
174 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
177 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
182 if (s
->timer_event_source
) {
183 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
187 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
190 if (usec
== USEC_INFINITY
)
193 r
= sd_event_add_time(
194 UNIT(s
)->manager
->event
,
195 &s
->timer_event_source
,
198 socket_dispatch_timer
, s
);
202 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
207 int socket_instantiate_service(Socket
*s
) {
208 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
214 /* This fills in s->service if it isn't filled in yet. For
215 * Accept=yes sockets we create the next connection service
216 * here. For Accept=no this is mostly a NOP since the service
217 * is figured out at load time anyway. */
219 if (UNIT_DEREF(s
->service
))
225 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
229 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
232 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
236 unit_ref_set(&s
->service
, UNIT(s
), u
);
238 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false, UNIT_DEPENDENCY_IMPLICIT
);
241 static bool have_non_accept_socket(Socket
*s
) {
249 LIST_FOREACH(port
, p
, s
->ports
) {
251 if (p
->type
!= SOCKET_SOCKET
)
254 if (!socket_address_can_accept(&p
->address
))
261 static int socket_add_mount_dependencies(Socket
*s
) {
267 LIST_FOREACH(port
, p
, s
->ports
) {
268 const char *path
= NULL
;
270 if (p
->type
== SOCKET_SOCKET
)
271 path
= socket_address_get_path(&p
->address
);
272 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
278 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
286 static int socket_add_device_dependencies(Socket
*s
) {
291 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
294 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
295 return unit_add_node_dependency(UNIT(s
), t
, false, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
298 static int socket_add_default_dependencies(Socket
*s
) {
302 if (!UNIT(s
)->default_dependencies
)
305 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
309 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
310 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
315 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
318 _pure_
static bool socket_has_exec(Socket
*s
) {
322 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
323 if (s
->exec_command
[i
])
329 static int socket_add_extras(Socket
*s
) {
335 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
336 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
337 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
338 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
339 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
340 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
341 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
342 * service starts are typical. */
344 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
345 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
347 if (s
->trigger_limit
.burst
== (unsigned) -1) {
349 s
->trigger_limit
.burst
= 200;
351 s
->trigger_limit
.burst
= 20;
354 if (have_non_accept_socket(s
)) {
356 if (!UNIT_DEREF(s
->service
)) {
359 r
= unit_load_related_unit(u
, ".service", &x
);
363 unit_ref_set(&s
->service
, u
, x
);
366 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
371 r
= socket_add_mount_dependencies(s
);
375 r
= socket_add_device_dependencies(s
);
379 r
= unit_patch_contexts(u
);
383 if (socket_has_exec(s
)) {
384 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
389 r
= unit_set_default_slice(u
);
393 r
= socket_add_default_dependencies(s
);
400 static const char *socket_find_symlink_target(Socket
*s
) {
401 const char *found
= NULL
;
404 LIST_FOREACH(port
, p
, s
->ports
) {
405 const char *f
= NULL
;
414 f
= socket_address_get_path(&p
->address
);
432 static int socket_verify(Socket
*s
) {
435 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
439 log_unit_error(UNIT(s
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
443 if (s
->accept
&& have_non_accept_socket(s
)) {
444 log_unit_error(UNIT(s
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
448 if (s
->accept
&& s
->max_connections
<= 0) {
449 log_unit_error(UNIT(s
), "MaxConnection= setting too small. Refusing.");
453 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
454 log_unit_error(UNIT(s
), "Explicit service configuration for accepting socket units not supported. Refusing.");
458 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
459 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
463 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
464 log_unit_error(UNIT(s
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
471 static void peer_address_hash_func(const void *p
, struct siphash
*state
) {
472 const SocketPeer
*s
= p
;
476 if (s
->peer
.sa
.sa_family
== AF_INET
)
477 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
478 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
479 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
480 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
481 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
483 assert_not_reached("Unknown address family.");
486 static int peer_address_compare_func(const void *a
, const void *b
) {
487 const SocketPeer
*x
= a
, *y
= b
;
490 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
494 switch(x
->peer
.sa
.sa_family
) {
496 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
498 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
500 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
502 assert_not_reached("Black sheep in the family!");
505 const struct hash_ops peer_address_hash_ops
= {
506 .hash
= peer_address_hash_func
,
507 .compare
= peer_address_compare_func
510 static int socket_load(Unit
*u
) {
511 Socket
*s
= SOCKET(u
);
515 assert(u
->load_state
== UNIT_STUB
);
517 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
521 r
= unit_load_fragment_and_dropin(u
);
525 if (u
->load_state
== UNIT_LOADED
) {
526 /* This is a new unit? Then let's add in some extras */
527 r
= socket_add_extras(s
);
532 return socket_verify(s
);
535 static SocketPeer
*socket_peer_new(void) {
538 p
= new0(SocketPeer
, 1);
547 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
551 set_remove(p
->socket
->peers_by_address
, p
);
556 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
558 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
559 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
560 SocketPeer sa
= {}, *i
;
561 socklen_t salen
= sizeof(sa
.peer
);
567 r
= getpeername(fd
, &sa
.peer
.sa
, &salen
);
569 return log_error_errno(errno
, "getpeername failed: %m");
571 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
576 i
= set_get(s
->peers_by_address
, &sa
);
578 *p
= socket_peer_ref(i
);
582 remote
= socket_peer_new();
586 remote
->peer
= sa
.peer
;
587 remote
->peer_salen
= salen
;
589 r
= set_put(s
->peers_by_address
, remote
);
595 *p
= TAKE_PTR(remote
);
600 _const_
static const char* listen_lookup(int family
, int type
) {
602 if (family
== AF_NETLINK
)
603 return "ListenNetlink";
605 if (type
== SOCK_STREAM
)
606 return "ListenStream";
607 else if (type
== SOCK_DGRAM
)
608 return "ListenDatagram";
609 else if (type
== SOCK_SEQPACKET
)
610 return "ListenSequentialPacket";
612 assert_not_reached("Unknown socket type");
616 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
617 char time_string
[FORMAT_TIMESPAN_MAX
];
619 Socket
*s
= SOCKET(u
);
621 const char *prefix2
, *str
;
626 prefix
= strempty(prefix
);
627 prefix2
= strjoina(prefix
, "\t");
630 "%sSocket State: %s\n"
632 "%sBindIPv6Only: %s\n"
634 "%sSocketMode: %04o\n"
635 "%sDirectoryMode: %04o\n"
639 "%sTransparent: %s\n"
641 "%sPassCredentials: %s\n"
642 "%sPassSecurity: %s\n"
643 "%sTCPCongestion: %s\n"
644 "%sRemoveOnStop: %s\n"
646 "%sFileDescriptorName: %s\n"
647 "%sSELinuxContextFromNet: %s\n",
648 prefix
, socket_state_to_string(s
->state
),
649 prefix
, socket_result_to_string(s
->result
),
650 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
652 prefix
, s
->socket_mode
,
653 prefix
, s
->directory_mode
,
654 prefix
, yes_no(s
->keep_alive
),
655 prefix
, yes_no(s
->no_delay
),
656 prefix
, yes_no(s
->free_bind
),
657 prefix
, yes_no(s
->transparent
),
658 prefix
, yes_no(s
->broadcast
),
659 prefix
, yes_no(s
->pass_cred
),
660 prefix
, yes_no(s
->pass_sec
),
661 prefix
, strna(s
->tcp_congestion
),
662 prefix
, yes_no(s
->remove_on_stop
),
663 prefix
, yes_no(s
->writable
),
664 prefix
, socket_fdname(s
),
665 prefix
, yes_no(s
->selinux_context_from_net
));
667 if (s
->control_pid
> 0)
669 "%sControl PID: "PID_FMT
"\n",
670 prefix
, s
->control_pid
);
672 if (s
->bind_to_device
)
674 "%sBindToDevice: %s\n",
675 prefix
, s
->bind_to_device
);
680 "%sNConnections: %u\n"
681 "%sMaxConnections: %u\n"
682 "%sMaxConnectionsPerSource: %u\n",
683 prefix
, s
->n_accepted
,
684 prefix
, s
->n_connections
,
685 prefix
, s
->max_connections
,
686 prefix
, s
->max_connections_per_source
);
688 if (s
->priority
>= 0)
691 prefix
, s
->priority
);
693 if (s
->receive_buffer
> 0)
695 "%sReceiveBuffer: %zu\n",
696 prefix
, s
->receive_buffer
);
698 if (s
->send_buffer
> 0)
700 "%sSendBuffer: %zu\n",
701 prefix
, s
->send_buffer
);
713 if (s
->pipe_size
> 0)
716 prefix
, s
->pipe_size
);
723 if (s
->mq_maxmsg
> 0)
725 "%sMessageQueueMaxMessages: %li\n",
726 prefix
, s
->mq_maxmsg
);
728 if (s
->mq_msgsize
> 0)
730 "%sMessageQueueMessageSize: %li\n",
731 prefix
, s
->mq_msgsize
);
736 prefix
, yes_no(s
->reuse_port
));
740 "%sSmackLabel: %s\n",
745 "%sSmackLabelIPIn: %s\n",
746 prefix
, s
->smack_ip_in
);
750 "%sSmackLabelIPOut: %s\n",
751 prefix
, s
->smack_ip_out
);
753 if (!isempty(s
->user
) || !isempty(s
->group
))
756 "%sSocketGroup: %s\n",
757 prefix
, strna(s
->user
),
758 prefix
, strna(s
->group
));
760 if (s
->keep_alive_time
> 0)
762 "%sKeepAliveTimeSec: %s\n",
763 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
765 if (s
->keep_alive_interval
> 0)
767 "%sKeepAliveIntervalSec: %s\n",
768 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
770 if (s
->keep_alive_cnt
> 0)
772 "%sKeepAliveProbes: %u\n",
773 prefix
, s
->keep_alive_cnt
);
775 if (s
->defer_accept
> 0)
777 "%sDeferAcceptSec: %s\n",
778 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
780 LIST_FOREACH(port
, p
, s
->ports
) {
783 case SOCKET_SOCKET
: {
784 _cleanup_free_
char *k
= NULL
;
788 r
= socket_address_print(&p
->address
, &k
);
794 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
798 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
800 case SOCKET_USB_FUNCTION
:
801 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
804 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
807 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
812 "%sTriggerLimitIntervalSec: %s\n"
813 "%sTriggerLimitBurst: %u\n",
814 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
815 prefix
, s
->trigger_limit
.burst
);
817 str
= ip_protocol_to_name(s
->socket_protocol
);
819 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
821 if (!strv_isempty(s
->symlinks
)) {
824 fprintf(f
, "%sSymlinks:", prefix
);
825 STRV_FOREACH(q
, s
->symlinks
)
826 fprintf(f
, " %s", *q
);
832 "%sTimeoutSec: %s\n",
833 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->timeout_usec
, USEC_PER_SEC
));
835 exec_context_dump(&s
->exec_context
, f
, prefix
);
836 kill_context_dump(&s
->kill_context
, f
, prefix
);
838 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
839 if (!s
->exec_command
[c
])
842 fprintf(f
, "%s-> %s:\n",
843 prefix
, socket_exec_command_to_string(c
));
845 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
848 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
851 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
854 union sockaddr_union local
, remote
;
860 if (getsockname(fd
, &local
.sa
, &l
) < 0)
864 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
867 switch (local
.sa
.sa_family
) {
871 a
= be32toh(local
.in
.sin_addr
.s_addr
),
872 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
875 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
877 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
878 be16toh(local
.in
.sin_port
),
879 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
880 be16toh(remote
.in
.sin_port
)) < 0)
887 static const unsigned char ipv4_prefix
[] = {
888 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
891 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
892 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
894 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
895 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
898 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
900 a
[0], a
[1], a
[2], a
[3],
901 be16toh(local
.in6
.sin6_port
),
902 b
[0], b
[1], b
[2], b
[3],
903 be16toh(remote
.in6
.sin6_port
)) < 0)
906 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
911 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
912 be16toh(local
.in6
.sin6_port
),
913 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
914 be16toh(remote
.in6
.sin6_port
)) < 0)
925 k
= getpeercred(fd
, &ucred
);
928 "%u-"PID_FMT
"-"UID_FMT
,
929 nr
, ucred
.pid
, ucred
.uid
) < 0)
931 } else if (k
== -ENODATA
) {
932 /* This handles the case where somebody is
933 * connecting from another pid/uid namespace
934 * (e.g. from outside of our container). */
949 local
.vm
.svm_cid
, local
.vm
.svm_port
,
950 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
956 assert_not_reached("Unhandled socket type.");
963 static void socket_close_fds(Socket
*s
) {
969 LIST_FOREACH(port
, p
, s
->ports
) {
972 was_open
= p
->fd
>= 0;
974 p
->event_source
= sd_event_source_unref(p
->event_source
);
975 p
->fd
= safe_close(p
->fd
);
976 socket_cleanup_fd_list(p
);
978 /* One little note: we should normally not delete any sockets in the file system here! After all some
979 * other process we spawned might still have a reference of this fd and wants to continue to use
980 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
981 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
982 * anyway, but only then. */
984 if (!was_open
|| !s
->remove_on_stop
)
990 (void) unlink(p
->path
);
994 (void) mq_unlink(p
->path
);
998 (void) socket_address_unlink(&p
->address
);
1006 if (s
->remove_on_stop
)
1007 STRV_FOREACH(i
, s
->symlinks
)
1011 static void socket_apply_socket_options(Socket
*s
, int fd
) {
1017 if (s
->keep_alive
) {
1018 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
1020 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
1023 if (s
->keep_alive_time
> 0) {
1024 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
1026 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
1029 if (s
->keep_alive_interval
> 0) {
1030 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
1032 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
1035 if (s
->keep_alive_cnt
> 0) {
1036 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
1038 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
1041 if (s
->defer_accept
> 0) {
1042 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
1044 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
1048 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1049 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1051 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1053 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1055 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1060 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1062 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1066 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1068 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1072 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1074 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1077 if (s
->priority
>= 0) {
1078 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1080 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1083 if (s
->receive_buffer
> 0) {
1084 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1085 if (setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, s
->receive_buffer
) < 0) {
1086 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, s
->receive_buffer
);
1088 log_unit_warning_errno(UNIT(s
), r
, "SO_RCVBUF failed: %m");
1092 if (s
->send_buffer
> 0) {
1093 if (setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, s
->send_buffer
) < 0) {
1094 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, s
->send_buffer
);
1096 log_unit_warning_errno(UNIT(s
), r
, "SO_SNDBUF failed: %m");
1101 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1103 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1106 if (s
->ip_tos
>= 0) {
1107 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1109 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1112 if (s
->ip_ttl
>= 0) {
1115 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TTL
, s
->ip_ttl
);
1117 if (socket_ipv6_is_supported())
1118 x
= setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, s
->ip_ttl
);
1123 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1126 if (s
->tcp_congestion
)
1127 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1128 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1130 if (s
->smack_ip_in
) {
1131 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1133 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1136 if (s
->smack_ip_out
) {
1137 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1139 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1143 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1149 if (s
->pipe_size
> 0)
1150 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1151 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1154 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1156 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1160 static int fifo_address_create(
1162 mode_t directory_mode
,
1163 mode_t socket_mode
) {
1165 _cleanup_close_
int fd
= -1;
1172 (void) mkdir_parents_label(path
, directory_mode
);
1174 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1178 /* Enforce the right access mode for the fifo */
1179 old_mask
= umask(~socket_mode
);
1181 /* Include the original umask in our mask */
1182 (void) umask(~socket_mode
| old_mask
);
1184 r
= mkfifo(path
, socket_mode
);
1185 (void) umask(old_mask
);
1187 if (r
< 0 && errno
!= EEXIST
) {
1192 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1198 mac_selinux_create_file_clear();
1200 if (fstat(fd
, &st
) < 0) {
1205 if (!S_ISFIFO(st
.st_mode
) ||
1206 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1207 st
.st_uid
!= getuid() ||
1208 st
.st_gid
!= getgid()) {
1216 mac_selinux_create_file_clear();
1220 static int special_address_create(const char *path
, bool writable
) {
1221 _cleanup_close_
int fd
= -1;
1226 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1230 if (fstat(fd
, &st
) < 0)
1233 /* Check whether this is a /proc, /sys or /dev file or char device */
1234 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1240 static int usbffs_address_create(const char *path
) {
1241 _cleanup_close_
int fd
= -1;
1246 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1250 if (fstat(fd
, &st
) < 0)
1253 /* Check whether this is a regular file (ffs endpoint) */
1254 if (!S_ISREG(st
.st_mode
))
1260 static int mq_address_create(
1266 _cleanup_close_
int fd
= -1;
1269 struct mq_attr _attr
, *attr
= NULL
;
1273 if (maxmsg
> 0 && msgsize
> 0) {
1274 _attr
= (struct mq_attr
) {
1275 .mq_flags
= O_NONBLOCK
,
1276 .mq_maxmsg
= maxmsg
,
1277 .mq_msgsize
= msgsize
,
1282 /* Enforce the right access mode for the mq */
1283 old_mask
= umask(~mq_mode
);
1285 /* Include the original umask in our mask */
1286 (void) umask(~mq_mode
| old_mask
);
1287 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1288 (void) umask(old_mask
);
1293 if (fstat(fd
, &st
) < 0)
1296 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1297 st
.st_uid
!= getuid() ||
1298 st
.st_gid
!= getgid())
1304 static int socket_symlink(Socket
*s
) {
1311 p
= socket_find_symlink_target(s
);
1315 STRV_FOREACH(i
, s
->symlinks
) {
1316 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1318 r
= symlink_idempotent(p
, *i
, false);
1320 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1321 /* If there's already something where we want to create the symlink, and the destructive
1322 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1325 if (unlink(*i
) >= 0)
1326 r
= symlink_idempotent(p
, *i
, false);
1330 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s → %s, ignoring: %m", p
, *i
);
1336 static int usbffs_write_descs(int fd
, Service
*s
) {
1339 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1342 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1346 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1349 static int usbffs_select_ep(const struct dirent
*d
) {
1350 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1353 static int usbffs_dispatch_eps(SocketPort
*p
) {
1354 _cleanup_free_
struct dirent
**ent
= NULL
;
1358 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1363 p
->auxiliary_fds
= new(int, n
);
1364 if (!p
->auxiliary_fds
) {
1369 p
->n_auxiliary_fds
= n
;
1372 for (i
= 0; i
< n
; ++i
) {
1373 _cleanup_free_
char *ep
= NULL
;
1375 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1381 path_simplify(ep
, false);
1383 r
= usbffs_address_create(ep
);
1387 p
->auxiliary_fds
[k
++] = r
;
1394 close_many(p
->auxiliary_fds
, k
);
1395 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1396 p
->n_auxiliary_fds
= 0;
1399 for (i
= 0; i
< n
; ++i
)
1405 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1408 _cleanup_free_
char *path
= NULL
;
1414 if (s
->selinux_context_from_net
) {
1415 /* If this is requested, get label from the network label */
1417 r
= mac_selinux_get_our_label(ret
);
1418 if (r
== -EOPNOTSUPP
)
1422 /* Otherwise, get it from the executable we are about to start */
1423 r
= socket_instantiate_service(s
);
1427 if (!UNIT_ISSET(s
->service
))
1430 service
= SERVICE(UNIT_DEREF(s
->service
));
1431 c
= service
->exec_command
[SERVICE_EXEC_START
];
1435 r
= chase_symlinks(c
->path
, service
->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
);
1439 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1440 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1451 static int socket_address_listen_do(
1453 const SocketAddress
*address
,
1454 const char *label
) {
1459 return socket_address_listen(
1461 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1473 static int socket_address_listen_in_cgroup(
1475 const SocketAddress
*address
,
1476 const char *label
) {
1478 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1485 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1486 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1487 * unit's cgroup for the purpose of BPF filtering and such. */
1489 if (!IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
1490 goto shortcut
; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1492 r
= bpf_firewall_supported();
1495 if (r
== BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1498 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1499 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1501 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1503 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1507 pair
[0] = safe_close(pair
[0]);
1509 fd
= socket_address_listen_do(s
, address
, label
);
1511 log_unit_error_errno(UNIT(s
), fd
, "Failed to create listening socket: %m");
1512 _exit(EXIT_FAILURE
);
1515 r
= send_one_fd(pair
[1], fd
, 0);
1517 log_unit_error_errno(UNIT(s
), r
, "Failed to send listening socket to parent: %m");
1518 _exit(EXIT_FAILURE
);
1521 _exit(EXIT_SUCCESS
);
1524 pair
[1] = safe_close(pair
[1]);
1525 fd
= receive_one_fd(pair
[0], 0);
1527 /* We synchronously wait for the helper, as it shouldn't be slow */
1528 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1535 return log_unit_error_errno(UNIT(s
), fd
, "Failed to receive listening socket: %m");
1540 fd
= socket_address_listen_do(s
, address
, label
);
1542 return log_error_errno(fd
, "Failed to create listening socket: %m");
1547 static int socket_open_fds(Socket
*s
) {
1548 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1549 bool know_label
= false;
1555 LIST_FOREACH(port
, p
, s
->ports
) {
1565 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1566 * we need this and remember it for the rest. */
1568 r
= socket_determine_selinux_label(s
, &label
);
1575 /* Apply the socket protocol */
1576 switch (p
->address
.type
) {
1579 case SOCK_SEQPACKET
:
1580 if (s
->socket_protocol
== IPPROTO_SCTP
)
1581 p
->address
.protocol
= s
->socket_protocol
;
1585 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1586 p
->address
.protocol
= s
->socket_protocol
;
1590 r
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1595 socket_apply_socket_options(s
, p
->fd
);
1599 case SOCKET_SPECIAL
:
1601 p
->fd
= special_address_create(p
->path
, s
->writable
);
1610 p
->fd
= fifo_address_create(
1619 socket_apply_fifo_options(s
, p
->fd
);
1625 p
->fd
= mq_address_create(
1636 case SOCKET_USB_FUNCTION
: {
1637 _cleanup_free_
char *ep
= NULL
;
1639 ep
= path_make_absolute("ep0", p
->path
);
1641 p
->fd
= usbffs_address_create(ep
);
1647 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1651 r
= usbffs_dispatch_eps(p
);
1658 assert_not_reached("Unknown port type");
1665 socket_close_fds(s
);
1669 static void socket_unwatch_fds(Socket
*s
) {
1675 LIST_FOREACH(port
, p
, s
->ports
) {
1679 if (!p
->event_source
)
1682 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1684 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1688 static int socket_watch_fds(Socket
*s
) {
1694 LIST_FOREACH(port
, p
, s
->ports
) {
1698 if (p
->event_source
) {
1699 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1703 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1707 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1714 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1715 socket_unwatch_fds(s
);
1725 static int socket_check_open(Socket
*s
) {
1726 bool have_open
= false, have_closed
= false;
1731 LIST_FOREACH(port
, p
, s
->ports
) {
1737 if (have_open
&& have_closed
)
1738 return SOCKET_OPEN_SOME
;
1742 return SOCKET_OPEN_ALL
;
1744 return SOCKET_OPEN_NONE
;
1747 static void socket_set_state(Socket
*s
, SocketState state
) {
1748 SocketState old_state
;
1751 old_state
= s
->state
;
1759 SOCKET_STOP_PRE_SIGTERM
,
1760 SOCKET_STOP_PRE_SIGKILL
,
1762 SOCKET_FINAL_SIGTERM
,
1763 SOCKET_FINAL_SIGKILL
)) {
1765 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1766 socket_unwatch_control_pid(s
);
1767 s
->control_command
= NULL
;
1768 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1771 if (state
!= SOCKET_LISTENING
)
1772 socket_unwatch_fds(s
);
1780 SOCKET_STOP_PRE_SIGTERM
,
1781 SOCKET_STOP_PRE_SIGKILL
))
1782 socket_close_fds(s
);
1784 if (state
!= old_state
)
1785 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1787 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
1790 static int socket_coldplug(Unit
*u
) {
1791 Socket
*s
= SOCKET(u
);
1795 assert(s
->state
== SOCKET_DEAD
);
1797 if (s
->deserialized_state
== s
->state
)
1800 if (s
->control_pid
> 0 &&
1801 pid_is_unwaited(s
->control_pid
) &&
1802 IN_SET(s
->deserialized_state
,
1807 SOCKET_STOP_PRE_SIGTERM
,
1808 SOCKET_STOP_PRE_SIGKILL
,
1810 SOCKET_FINAL_SIGTERM
,
1811 SOCKET_FINAL_SIGKILL
)) {
1813 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1817 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1822 if (IN_SET(s
->deserialized_state
,
1828 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1829 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1830 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1831 * and if there's a mismatch, warn loudly. */
1833 r
= socket_check_open(s
);
1834 if (r
== SOCKET_OPEN_NONE
)
1835 log_unit_warning(UNIT(s
),
1836 "Socket unit configuration has changed while unit has been running, "
1837 "no open socket file descriptor left. "
1838 "The socket unit is not functional until restarted.");
1839 else if (r
== SOCKET_OPEN_SOME
)
1840 log_unit_warning(UNIT(s
),
1841 "Socket unit configuration has changed while unit has been running, "
1842 "and some socket file descriptors have not been opened yet. "
1843 "The socket unit is not fully functional until restarted.");
1846 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1847 r
= socket_watch_fds(s
);
1852 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
)) {
1853 (void) unit_setup_dynamic_creds(u
);
1854 (void) unit_setup_exec_runtime(u
);
1857 socket_set_state(s
, s
->deserialized_state
);
1861 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1863 _cleanup_(exec_params_clear
) ExecParameters exec_params
= {
1864 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1877 r
= unit_prepare_exec(UNIT(s
));
1881 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1885 r
= unit_set_exec_params(UNIT(s
), &exec_params
);
1889 r
= exec_spawn(UNIT(s
),
1899 r
= unit_watch_pid(UNIT(s
), pid
);
1901 /* FIXME: we need to do something here */
1909 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1913 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1917 /* We have to resolve the user names out-of-process, hence
1918 * let's fork here. It's messy, but well, what can we do? */
1920 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1924 uid_t uid
= UID_INVALID
;
1925 gid_t gid
= GID_INVALID
;
1930 if (!isempty(s
->user
)) {
1931 const char *user
= s
->user
;
1933 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1935 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1940 if (!isempty(s
->group
)) {
1941 const char *group
= s
->group
;
1943 r
= get_group_creds(&group
, &gid
, 0);
1945 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1950 LIST_FOREACH(port
, p
, s
->ports
) {
1951 const char *path
= NULL
;
1953 if (p
->type
== SOCKET_SOCKET
)
1954 path
= socket_address_get_path(&p
->address
);
1955 else if (p
->type
== SOCKET_FIFO
)
1961 if (chown(path
, uid
, gid
) < 0) {
1962 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1967 _exit(EXIT_SUCCESS
);
1970 r
= unit_watch_pid(UNIT(s
), pid
);
1978 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1982 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1985 if (s
->result
== SOCKET_SUCCESS
)
1988 if (s
->result
== SOCKET_SUCCESS
)
1989 unit_log_success(UNIT(s
));
1991 unit_log_failure(UNIT(s
), socket_result_to_string(s
->result
));
1993 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1995 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
1997 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
1999 unit_unref_uid_gid(UNIT(s
), true);
2001 dynamic_creds_destroy(&s
->dynamic_creds
);
2004 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2006 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2010 if (s
->result
== SOCKET_SUCCESS
)
2013 socket_unwatch_control_pid(s
);
2014 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2015 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2017 if (s
->control_command
) {
2018 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2022 socket_set_state(s
, SOCKET_STOP_POST
);
2024 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2029 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2030 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2033 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2038 if (s
->result
== SOCKET_SUCCESS
)
2041 r
= unit_kill_context(
2044 !IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FINAL_SIGTERM
) ?
2045 KILL_KILL
: KILL_TERMINATE
,
2053 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2057 socket_set_state(s
, state
);
2058 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2059 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2060 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2061 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2062 else if (state
== SOCKET_FINAL_SIGTERM
)
2063 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2065 socket_enter_dead(s
, SOCKET_SUCCESS
);
2070 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2072 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2073 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2075 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2078 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2082 if (s
->result
== SOCKET_SUCCESS
)
2085 socket_unwatch_control_pid(s
);
2086 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2087 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2089 if (s
->control_command
) {
2090 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2094 socket_set_state(s
, SOCKET_STOP_PRE
);
2096 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2101 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2102 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2105 static void socket_enter_listening(Socket
*s
) {
2109 r
= socket_watch_fds(s
);
2111 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2115 socket_set_state(s
, SOCKET_LISTENING
);
2119 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2122 static void socket_enter_start_post(Socket
*s
) {
2126 socket_unwatch_control_pid(s
);
2127 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2128 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2130 if (s
->control_command
) {
2131 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2133 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2137 socket_set_state(s
, SOCKET_START_POST
);
2139 socket_enter_listening(s
);
2144 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2147 static void socket_enter_start_chown(Socket
*s
) {
2152 r
= socket_open_fds(s
);
2154 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2158 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2160 socket_unwatch_control_pid(s
);
2161 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2162 s
->control_command
= NULL
;
2164 r
= socket_chown(s
, &s
->control_pid
);
2166 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2170 socket_set_state(s
, SOCKET_START_CHOWN
);
2172 socket_enter_start_post(s
);
2177 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2180 static void socket_enter_start_pre(Socket
*s
) {
2184 socket_unwatch_control_pid(s
);
2186 unit_warn_leftover_processes(UNIT(s
));
2188 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2189 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2191 if (s
->control_command
) {
2192 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2194 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2198 socket_set_state(s
, SOCKET_START_PRE
);
2200 socket_enter_start_chown(s
);
2205 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2208 static void flush_ports(Socket
*s
) {
2211 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2214 LIST_FOREACH(port
, p
, s
->ports
) {
2218 (void) flush_accept(p
->fd
);
2219 (void) flush_fd(p
->fd
);
2223 static void socket_enter_running(Socket
*s
, int cfd
) {
2224 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2227 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2232 /* We don't take connections anymore if we are supposed to shut down anyway */
2233 if (unit_stop_pending(UNIT(s
))) {
2235 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2245 if (!ratelimit_below(&s
->trigger_limit
)) {
2246 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2247 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2252 bool pending
= false;
2257 /* If there's already a start pending don't bother to
2259 HASHMAP_FOREACH_KEY(v
, other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2260 if (unit_active_or_pending(other
)) {
2266 if (!UNIT_ISSET(s
->service
)) {
2267 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2272 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2277 socket_set_state(s
, SOCKET_RUNNING
);
2279 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2280 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2283 if (s
->n_connections
>= s
->max_connections
) {
2284 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2289 if (s
->max_connections_per_source
> 0) {
2290 r
= socket_acquire_peer(s
, cfd
, &p
);
2293 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2294 _cleanup_free_
char *t
= NULL
;
2296 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2298 log_unit_warning(UNIT(s
),
2299 "Too many incoming connections (%u) from source %s, dropping connection.",
2300 p
->n_ref
, strnull(t
));
2305 r
= socket_instantiate_service(s
);
2309 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2314 /* ENOTCONN is legitimate if TCP RST was received.
2315 * This connection is over, but the socket unit lives on. */
2316 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2320 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2324 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2328 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2332 service
= SERVICE(UNIT_DEREF(s
->service
));
2333 unit_ref_unset(&s
->service
);
2336 unit_choose_id(UNIT(service
), name
);
2338 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2342 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2345 service
->peer
= TAKE_PTR(p
); /* Pass ownership of the peer reference */
2347 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2349 /* We failed to activate the new service, but it still exists. Let's make sure the service
2350 * closes and forgets the connection fd again, immediately. */
2351 service_close_socket_fd(service
);
2355 /* Notify clients about changed counters */
2356 unit_add_to_dbus_queue(UNIT(s
));
2367 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2368 cfd
>= 0 ? "template" : "non-template",
2369 bus_error_message(&error
, r
));
2371 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2375 static void socket_run_next(Socket
*s
) {
2379 assert(s
->control_command
);
2380 assert(s
->control_command
->command_next
);
2382 socket_unwatch_control_pid(s
);
2384 s
->control_command
= s
->control_command
->command_next
;
2386 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2393 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2395 if (s
->state
== SOCKET_START_POST
)
2396 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2397 else if (s
->state
== SOCKET_STOP_POST
)
2398 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2400 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2403 static int socket_start(Unit
*u
) {
2404 Socket
*s
= SOCKET(u
);
2409 /* We cannot fulfill this request right now, try again later
2411 if (IN_SET(s
->state
,
2413 SOCKET_STOP_PRE_SIGKILL
,
2414 SOCKET_STOP_PRE_SIGTERM
,
2416 SOCKET_FINAL_SIGTERM
,
2417 SOCKET_FINAL_SIGKILL
))
2420 /* Already on it! */
2421 if (IN_SET(s
->state
,
2427 /* Cannot run this without the service being around */
2428 if (UNIT_ISSET(s
->service
)) {
2431 service
= SERVICE(UNIT_DEREF(s
->service
));
2433 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2434 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2438 /* If the service is already active we cannot start the
2440 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
2441 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2446 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2448 r
= unit_start_limit_test(u
);
2450 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2454 r
= unit_acquire_invocation_id(u
);
2458 s
->result
= SOCKET_SUCCESS
;
2459 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2461 u
->reset_accounting
= true;
2463 socket_enter_start_pre(s
);
2467 static int socket_stop(Unit
*u
) {
2468 Socket
*s
= SOCKET(u
);
2473 if (IN_SET(s
->state
,
2475 SOCKET_STOP_PRE_SIGTERM
,
2476 SOCKET_STOP_PRE_SIGKILL
,
2478 SOCKET_FINAL_SIGTERM
,
2479 SOCKET_FINAL_SIGKILL
))
2482 /* If there's already something running we go directly into
2484 if (IN_SET(s
->state
,
2487 SOCKET_START_POST
)) {
2488 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2492 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2494 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2498 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2499 Socket
*s
= SOCKET(u
);
2507 (void) serialize_item(f
, "state", socket_state_to_string(s
->state
));
2508 (void) serialize_item(f
, "result", socket_result_to_string(s
->result
));
2509 (void) serialize_item_format(f
, "n-accepted", "%u", s
->n_accepted
);
2510 (void) serialize_item_format(f
, "n-refused", "%u", s
->n_refused
);
2512 if (s
->control_pid
> 0)
2513 (void) serialize_item_format(f
, "control-pid", PID_FMT
, s
->control_pid
);
2515 if (s
->control_command_id
>= 0)
2516 (void) serialize_item(f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2518 LIST_FOREACH(port
, p
, s
->ports
) {
2524 copy
= fdset_put_dup(fds
, p
->fd
);
2526 return log_warning_errno(copy
, "Failed to serialize socket fd: %m");
2528 if (p
->type
== SOCKET_SOCKET
) {
2529 _cleanup_free_
char *t
= NULL
;
2531 r
= socket_address_print(&p
->address
, &t
);
2533 return log_error_errno(r
, "Failed to format socket address: %m");
2535 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2536 (void) serialize_item_format(f
, "netlink", "%i %s", copy
, t
);
2538 (void) serialize_item_format(f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2539 } else if (p
->type
== SOCKET_SPECIAL
)
2540 (void) serialize_item_format(f
, "special", "%i %s", copy
, p
->path
);
2541 else if (p
->type
== SOCKET_MQUEUE
)
2542 (void) serialize_item_format(f
, "mqueue", "%i %s", copy
, p
->path
);
2543 else if (p
->type
== SOCKET_USB_FUNCTION
)
2544 (void) serialize_item_format(f
, "ffs", "%i %s", copy
, p
->path
);
2546 assert(p
->type
== SOCKET_FIFO
);
2547 (void) serialize_item_format(f
, "fifo", "%i %s", copy
, p
->path
);
2554 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2558 p
->fd
= fdset_remove(fds
, fd
);
2561 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2562 Socket
*s
= SOCKET(u
);
2568 if (streq(key
, "state")) {
2571 state
= socket_state_from_string(value
);
2573 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2575 s
->deserialized_state
= state
;
2576 } else if (streq(key
, "result")) {
2579 f
= socket_result_from_string(value
);
2581 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2582 else if (f
!= SOCKET_SUCCESS
)
2585 } else if (streq(key
, "n-accepted")) {
2588 if (safe_atou(value
, &k
) < 0)
2589 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2592 } else if (streq(key
, "n-refused")) {
2595 if (safe_atou(value
, &k
) < 0)
2596 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2599 } else if (streq(key
, "control-pid")) {
2602 if (parse_pid(value
, &pid
) < 0)
2603 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2605 s
->control_pid
= pid
;
2606 } else if (streq(key
, "control-command")) {
2607 SocketExecCommand id
;
2609 id
= socket_exec_command_from_string(value
);
2611 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2613 s
->control_command_id
= id
;
2614 s
->control_command
= s
->exec_command
[id
];
2616 } else if (streq(key
, "fifo")) {
2620 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2621 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2623 LIST_FOREACH(port
, p
, s
->ports
)
2624 if (p
->type
== SOCKET_FIFO
&&
2625 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2626 socket_port_take_fd(p
, fds
, fd
);
2630 } else if (streq(key
, "special")) {
2634 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2635 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2637 LIST_FOREACH(port
, p
, s
->ports
)
2638 if (p
->type
== SOCKET_SPECIAL
&&
2639 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2640 socket_port_take_fd(p
, fds
, fd
);
2644 } else if (streq(key
, "mqueue")) {
2648 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2649 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2651 LIST_FOREACH(port
, p
, s
->ports
)
2652 if (p
->type
== SOCKET_MQUEUE
&&
2653 streq(p
->path
, value
+skip
)) {
2654 socket_port_take_fd(p
, fds
, fd
);
2658 } else if (streq(key
, "socket")) {
2659 int fd
, type
, skip
= 0;
2662 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2663 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2665 LIST_FOREACH(port
, p
, s
->ports
)
2666 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2667 socket_port_take_fd(p
, fds
, fd
);
2671 } else if (streq(key
, "netlink")) {
2675 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2676 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2678 LIST_FOREACH(port
, p
, s
->ports
)
2679 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2680 socket_port_take_fd(p
, fds
, fd
);
2684 } else if (streq(key
, "ffs")) {
2688 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2689 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2691 LIST_FOREACH(port
, p
, s
->ports
)
2692 if (p
->type
== SOCKET_USB_FUNCTION
&&
2693 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2694 socket_port_take_fd(p
, fds
, fd
);
2699 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2704 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2705 Socket
*s
= SOCKET(u
);
2710 LIST_FOREACH(port
, p
, s
->ports
) {
2714 if (p
->type
!= SOCKET_SOCKET
)
2720 FDSET_FOREACH(fd
, fds
, i
) {
2721 if (socket_address_matches_fd(&p
->address
, fd
)) {
2722 p
->fd
= fdset_remove(fds
, fd
);
2723 s
->deserialized_state
= SOCKET_LISTENING
;
2730 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2733 return state_translation_table
[SOCKET(u
)->state
];
2736 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2739 return socket_state_to_string(SOCKET(u
)->state
);
2742 const char* socket_port_type_to_string(SocketPort
*p
) {
2750 switch (p
->address
.type
) {
2758 case SOCK_SEQPACKET
:
2759 return "SequentialPacket";
2762 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2770 case SOCKET_SPECIAL
:
2774 return "MessageQueue";
2779 case SOCKET_USB_FUNCTION
:
2780 return "USBFunction";
2787 SocketType
socket_port_type_from_string(const char *s
) {
2790 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2791 return SOCKET_SOCKET
;
2792 else if (streq(s
, "Special"))
2793 return SOCKET_SPECIAL
;
2794 else if (streq(s
, "MessageQueue"))
2795 return SOCKET_MQUEUE
;
2796 else if (streq(s
, "FIFO"))
2798 else if (streq(s
, "USBFunction"))
2799 return SOCKET_USB_FUNCTION
;
2801 return _SOCKET_TYPE_INVALID
;
2804 _pure_
static bool socket_may_gc(Unit
*u
) {
2805 Socket
*s
= SOCKET(u
);
2809 return s
->n_connections
== 0;
2812 static int socket_accept_do(Socket
*s
, int fd
) {
2819 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2833 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2834 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
2842 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2843 * connection socket is also properly associated with the cgroup. */
2845 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2848 r
= bpf_firewall_supported();
2851 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2854 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2855 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2857 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2859 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2863 pair
[0] = safe_close(pair
[0]);
2865 cfd
= socket_accept_do(s
, fd
);
2867 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2868 _exit(EXIT_FAILURE
);
2871 r
= send_one_fd(pair
[1], cfd
, 0);
2873 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
2874 _exit(EXIT_FAILURE
);
2877 _exit(EXIT_SUCCESS
);
2880 pair
[1] = safe_close(pair
[1]);
2881 cfd
= receive_one_fd(pair
[0], 0);
2883 /* We synchronously wait for the helper, as it shouldn't be slow */
2884 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
2891 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
2896 cfd
= socket_accept_do(s
, fd
);
2898 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2903 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2904 SocketPort
*p
= userdata
;
2910 if (p
->socket
->state
!= SOCKET_LISTENING
)
2913 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2915 if (revents
!= EPOLLIN
) {
2917 if (revents
& EPOLLHUP
)
2918 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.");
2920 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2924 if (p
->socket
->accept
&&
2925 p
->type
== SOCKET_SOCKET
&&
2926 socket_address_can_accept(&p
->address
)) {
2928 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
2932 socket_apply_socket_options(p
->socket
, cfd
);
2935 socket_enter_running(p
->socket
, cfd
);
2939 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2943 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2944 Socket
*s
= SOCKET(u
);
2950 if (pid
!= s
->control_pid
)
2955 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
2957 else if (code
== CLD_EXITED
)
2958 f
= SOCKET_FAILURE_EXIT_CODE
;
2959 else if (code
== CLD_KILLED
)
2960 f
= SOCKET_FAILURE_SIGNAL
;
2961 else if (code
== CLD_DUMPED
)
2962 f
= SOCKET_FAILURE_CORE_DUMP
;
2964 assert_not_reached("Unknown sigchld code");
2966 if (s
->control_command
) {
2967 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2969 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
2973 unit_log_process_exit(
2974 u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
,
2976 socket_exec_command_to_string(s
->control_command_id
),
2979 if (s
->result
== SOCKET_SUCCESS
)
2982 if (s
->control_command
&&
2983 s
->control_command
->command_next
&&
2984 f
== SOCKET_SUCCESS
) {
2986 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2989 s
->control_command
= NULL
;
2990 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2992 /* No further commands for this step, so let's figure
2993 * out what to do next */
2995 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2999 case SOCKET_START_PRE
:
3000 if (f
== SOCKET_SUCCESS
)
3001 socket_enter_start_chown(s
);
3003 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
3006 case SOCKET_START_CHOWN
:
3007 if (f
== SOCKET_SUCCESS
)
3008 socket_enter_start_post(s
);
3010 socket_enter_stop_pre(s
, f
);
3013 case SOCKET_START_POST
:
3014 if (f
== SOCKET_SUCCESS
)
3015 socket_enter_listening(s
);
3017 socket_enter_stop_pre(s
, f
);
3020 case SOCKET_STOP_PRE
:
3021 case SOCKET_STOP_PRE_SIGTERM
:
3022 case SOCKET_STOP_PRE_SIGKILL
:
3023 socket_enter_stop_post(s
, f
);
3026 case SOCKET_STOP_POST
:
3027 case SOCKET_FINAL_SIGTERM
:
3028 case SOCKET_FINAL_SIGKILL
:
3029 socket_enter_dead(s
, f
);
3033 assert_not_reached("Uh, control process died at wrong time.");
3037 /* Notify clients about changed exit status */
3038 unit_add_to_dbus_queue(u
);
3041 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3042 Socket
*s
= SOCKET(userdata
);
3045 assert(s
->timer_event_source
== source
);
3049 case SOCKET_START_PRE
:
3050 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3051 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3054 case SOCKET_START_CHOWN
:
3055 case SOCKET_START_POST
:
3056 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3057 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3060 case SOCKET_STOP_PRE
:
3061 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3062 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3065 case SOCKET_STOP_PRE_SIGTERM
:
3066 if (s
->kill_context
.send_sigkill
) {
3067 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3068 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3070 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3071 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3075 case SOCKET_STOP_PRE_SIGKILL
:
3076 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3077 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3080 case SOCKET_STOP_POST
:
3081 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3082 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3085 case SOCKET_FINAL_SIGTERM
:
3086 if (s
->kill_context
.send_sigkill
) {
3087 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3088 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3090 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3091 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3095 case SOCKET_FINAL_SIGKILL
:
3096 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3097 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3101 assert_not_reached("Timeout at wrong time.");
3107 int socket_collect_fds(Socket
*s
, int **fds
) {
3108 size_t k
= 0, n
= 0;
3115 /* Called from the service code for requesting our fds */
3117 LIST_FOREACH(port
, p
, s
->ports
) {
3120 n
+= p
->n_auxiliary_fds
;
3132 LIST_FOREACH(port
, p
, s
->ports
) {
3137 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3138 rfds
[k
++] = p
->auxiliary_fds
[i
];
3147 static void socket_reset_failed(Unit
*u
) {
3148 Socket
*s
= SOCKET(u
);
3152 if (s
->state
== SOCKET_FAILED
)
3153 socket_set_state(s
, SOCKET_DEAD
);
3155 s
->result
= SOCKET_SUCCESS
;
3158 void socket_connection_unref(Socket
*s
) {
3161 /* The service is dead. Yay!
3163 * This is strictly for one-instance-per-connection
3166 assert(s
->n_connections
> 0);
3169 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3172 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3173 Socket
*s
= SOCKET(u
);
3178 /* Filter out invocations with bogus state */
3179 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
3182 /* Don't propagate state changes from the service if we are already down */
3183 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3186 /* We don't care for the service state if we are in Accept=yes mode */
3190 /* Propagate start limit hit state */
3191 if (other
->start_limit_hit
) {
3192 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3196 /* Don't propagate anything if there's still a job queued */
3200 if (IN_SET(SERVICE(other
)->state
,
3201 SERVICE_DEAD
, SERVICE_FAILED
,
3202 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3203 SERVICE_AUTO_RESTART
))
3204 socket_enter_listening(s
);
3206 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3207 socket_set_state(s
, SOCKET_RUNNING
);
3210 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3211 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3214 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3215 Socket
*s
= SOCKET(u
);
3219 if (!s
->timer_event_source
)
3222 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3225 if (t
== USEC_INFINITY
)
3232 char *socket_fdname(Socket
*s
) {
3235 /* Returns the name to use for $LISTEN_NAMES. If the user
3236 * didn't specify anything specifically, use the socket unit's
3237 * name as fallback. */
3239 return s
->fdname
?: UNIT(s
)->id
;
3242 static int socket_control_pid(Unit
*u
) {
3243 Socket
*s
= SOCKET(u
);
3247 return s
->control_pid
;
3250 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3251 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3252 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3253 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3254 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3255 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3258 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3260 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3261 [SOCKET_SUCCESS
] = "success",
3262 [SOCKET_FAILURE_RESOURCES
] = "resources",
3263 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3264 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3265 [SOCKET_FAILURE_SIGNAL
] = "signal",
3266 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3267 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3268 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3269 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3272 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3274 const UnitVTable socket_vtable
= {
3275 .object_size
= sizeof(Socket
),
3276 .exec_context_offset
= offsetof(Socket
, exec_context
),
3277 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3278 .kill_context_offset
= offsetof(Socket
, kill_context
),
3279 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3280 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3286 .private_section
= "Socket",
3288 .can_transient
= true,
3290 .init
= socket_init
,
3291 .done
= socket_done
,
3292 .load
= socket_load
,
3294 .coldplug
= socket_coldplug
,
3296 .dump
= socket_dump
,
3298 .start
= socket_start
,
3299 .stop
= socket_stop
,
3301 .kill
= socket_kill
,
3303 .get_timeout
= socket_get_timeout
,
3305 .serialize
= socket_serialize
,
3306 .deserialize_item
= socket_deserialize_item
,
3307 .distribute_fds
= socket_distribute_fds
,
3309 .active_state
= socket_active_state
,
3310 .sub_state_to_string
= socket_sub_state_to_string
,
3312 .may_gc
= socket_may_gc
,
3314 .sigchld_event
= socket_sigchld_event
,
3316 .trigger_notify
= socket_trigger_notify
,
3318 .reset_failed
= socket_reset_failed
,
3320 .control_pid
= socket_control_pid
,
3322 .bus_vtable
= bus_socket_vtable
,
3323 .bus_set_property
= bus_socket_set_property
,
3324 .bus_commit_properties
= bus_socket_commit_properties
,
3326 .status_message_formats
= {
3327 /*.starting_stopping = {
3328 [0] = "Starting socket %s...",
3329 [1] = "Stopping socket %s...",
3331 .finished_start_job
= {
3332 [JOB_DONE
] = "Listening on %s.",
3333 [JOB_FAILED
] = "Failed to listen on %s.",
3334 [JOB_TIMEOUT
] = "Timed out starting %s.",
3336 .finished_stop_job
= {
3337 [JOB_DONE
] = "Closed %s.",
3338 [JOB_FAILED
] = "Failed stopping %s.",
3339 [JOB_TIMEOUT
] = "Timed out stopping %s.",