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"
31 #include "parse-util.h"
32 #include "path-util.h"
33 #include "process-util.h"
34 #include "selinux-util.h"
35 #include "signal-util.h"
36 #include "smack-util.h"
38 #include "socket-protocol-list.h"
40 #include "string-table.h"
41 #include "string-util.h"
43 #include "unit-name.h"
45 #include "user-util.h"
51 union sockaddr_union peer
;
55 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
56 [SOCKET_DEAD
] = UNIT_INACTIVE
,
57 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
58 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
59 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
60 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
61 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
62 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
63 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
64 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
65 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
66 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
67 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
68 [SOCKET_FAILED
] = UNIT_FAILED
71 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
72 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
74 static void socket_init(Unit
*u
) {
75 Socket
*s
= SOCKET(u
);
78 assert(u
->load_state
== UNIT_STUB
);
80 s
->backlog
= SOMAXCONN
;
81 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
82 s
->directory_mode
= 0755;
83 s
->socket_mode
= 0666;
85 s
->max_connections
= 64;
92 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
93 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
95 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
97 s
->trigger_limit
.interval
= USEC_INFINITY
;
98 s
->trigger_limit
.burst
= (unsigned) -1;
101 static void socket_unwatch_control_pid(Socket
*s
) {
104 if (s
->control_pid
<= 0)
107 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
111 static void socket_cleanup_fd_list(SocketPort
*p
) {
114 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
115 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
116 p
->n_auxiliary_fds
= 0;
119 void socket_free_ports(Socket
*s
) {
124 while ((p
= s
->ports
)) {
125 LIST_REMOVE(port
, s
->ports
, p
);
127 sd_event_source_unref(p
->event_source
);
129 socket_cleanup_fd_list(p
);
136 static void socket_done(Unit
*u
) {
137 Socket
*s
= SOCKET(u
);
142 socket_free_ports(s
);
144 while ((p
= set_steal_first(s
->peers_by_address
)))
147 s
->peers_by_address
= set_free(s
->peers_by_address
);
149 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, false);
150 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
151 s
->control_command
= NULL
;
153 dynamic_creds_unref(&s
->dynamic_creds
);
155 socket_unwatch_control_pid(s
);
157 unit_ref_unset(&s
->service
);
159 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
160 s
->bind_to_device
= mfree(s
->bind_to_device
);
162 s
->smack
= mfree(s
->smack
);
163 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
164 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
166 strv_free(s
->symlinks
);
168 s
->user
= mfree(s
->user
);
169 s
->group
= mfree(s
->group
);
171 s
->fdname
= mfree(s
->fdname
);
173 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
176 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
181 if (s
->timer_event_source
) {
182 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
186 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
189 if (usec
== USEC_INFINITY
)
192 r
= sd_event_add_time(
193 UNIT(s
)->manager
->event
,
194 &s
->timer_event_source
,
197 socket_dispatch_timer
, s
);
201 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
206 int socket_instantiate_service(Socket
*s
) {
207 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
213 /* This fills in s->service if it isn't filled in yet. For
214 * Accept=yes sockets we create the next connection service
215 * here. For Accept=no this is mostly a NOP since the service
216 * is figured out at load time anyway. */
218 if (UNIT_DEREF(s
->service
))
224 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
228 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
231 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
235 unit_ref_set(&s
->service
, UNIT(s
), u
);
237 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false, UNIT_DEPENDENCY_IMPLICIT
);
240 static bool have_non_accept_socket(Socket
*s
) {
248 LIST_FOREACH(port
, p
, s
->ports
) {
250 if (p
->type
!= SOCKET_SOCKET
)
253 if (!socket_address_can_accept(&p
->address
))
260 static int socket_add_mount_dependencies(Socket
*s
) {
266 LIST_FOREACH(port
, p
, s
->ports
) {
267 const char *path
= NULL
;
269 if (p
->type
== SOCKET_SOCKET
)
270 path
= socket_address_get_path(&p
->address
);
271 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
277 r
= unit_require_mounts_for(UNIT(s
), path
, UNIT_DEPENDENCY_FILE
);
285 static int socket_add_device_dependencies(Socket
*s
) {
290 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
293 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
294 return unit_add_node_dependency(UNIT(s
), t
, false, UNIT_BINDS_TO
, UNIT_DEPENDENCY_FILE
);
297 static int socket_add_default_dependencies(Socket
*s
) {
301 if (!UNIT(s
)->default_dependencies
)
304 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
308 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
309 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
314 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, true, UNIT_DEPENDENCY_DEFAULT
);
317 _pure_
static bool socket_has_exec(Socket
*s
) {
321 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
322 if (s
->exec_command
[i
])
328 static int socket_add_extras(Socket
*s
) {
334 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
335 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
336 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
337 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
338 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
339 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
340 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
341 * service starts are typical. */
343 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
344 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
346 if (s
->trigger_limit
.burst
== (unsigned) -1) {
348 s
->trigger_limit
.burst
= 200;
350 s
->trigger_limit
.burst
= 20;
353 if (have_non_accept_socket(s
)) {
355 if (!UNIT_DEREF(s
->service
)) {
358 r
= unit_load_related_unit(u
, ".service", &x
);
362 unit_ref_set(&s
->service
, u
, x
);
365 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true, UNIT_DEPENDENCY_IMPLICIT
);
370 r
= socket_add_mount_dependencies(s
);
374 r
= socket_add_device_dependencies(s
);
378 r
= unit_patch_contexts(u
);
382 if (socket_has_exec(s
)) {
383 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
388 r
= unit_set_default_slice(u
);
392 r
= socket_add_default_dependencies(s
);
399 static const char *socket_find_symlink_target(Socket
*s
) {
400 const char *found
= NULL
;
403 LIST_FOREACH(port
, p
, s
->ports
) {
404 const char *f
= NULL
;
413 f
= socket_address_get_path(&p
->address
);
431 static int socket_verify(Socket
*s
) {
434 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
438 log_unit_error(UNIT(s
), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
442 if (s
->accept
&& have_non_accept_socket(s
)) {
443 log_unit_error(UNIT(s
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
447 if (s
->accept
&& s
->max_connections
<= 0) {
448 log_unit_error(UNIT(s
), "MaxConnection= setting too small. Refusing.");
452 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
453 log_unit_error(UNIT(s
), "Explicit service configuration for accepting socket units not supported. Refusing.");
457 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
458 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
462 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
463 log_unit_error(UNIT(s
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
470 static void peer_address_hash_func(const void *p
, struct siphash
*state
) {
471 const SocketPeer
*s
= p
;
475 if (s
->peer
.sa
.sa_family
== AF_INET
)
476 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
477 else if (s
->peer
.sa
.sa_family
== AF_INET6
)
478 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
479 else if (s
->peer
.sa
.sa_family
== AF_VSOCK
)
480 siphash24_compress(&s
->peer
.vm
.svm_cid
, sizeof(s
->peer
.vm
.svm_cid
), state
);
482 assert_not_reached("Unknown address family.");
485 static int peer_address_compare_func(const void *a
, const void *b
) {
486 const SocketPeer
*x
= a
, *y
= b
;
489 r
= CMP(x
->peer
.sa
.sa_family
, y
->peer
.sa
.sa_family
);
493 switch(x
->peer
.sa
.sa_family
) {
495 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
497 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
499 return CMP(x
->peer
.vm
.svm_cid
, y
->peer
.vm
.svm_cid
);
501 assert_not_reached("Black sheep in the family!");
504 const struct hash_ops peer_address_hash_ops
= {
505 .hash
= peer_address_hash_func
,
506 .compare
= peer_address_compare_func
509 static int socket_load(Unit
*u
) {
510 Socket
*s
= SOCKET(u
);
514 assert(u
->load_state
== UNIT_STUB
);
516 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
520 r
= unit_load_fragment_and_dropin(u
);
524 if (u
->load_state
== UNIT_LOADED
) {
525 /* This is a new unit? Then let's add in some extras */
526 r
= socket_add_extras(s
);
531 return socket_verify(s
);
534 static SocketPeer
*socket_peer_new(void) {
537 p
= new0(SocketPeer
, 1);
546 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
550 set_remove(p
->socket
->peers_by_address
, p
);
555 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
557 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
558 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
559 SocketPeer sa
= {}, *i
;
560 socklen_t salen
= sizeof(sa
.peer
);
566 r
= getpeername(fd
, &sa
.peer
.sa
, &salen
);
568 return log_error_errno(errno
, "getpeername failed: %m");
570 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
575 i
= set_get(s
->peers_by_address
, &sa
);
577 *p
= socket_peer_ref(i
);
581 remote
= socket_peer_new();
585 remote
->peer
= sa
.peer
;
586 remote
->peer_salen
= salen
;
588 r
= set_put(s
->peers_by_address
, remote
);
594 *p
= TAKE_PTR(remote
);
599 _const_
static const char* listen_lookup(int family
, int type
) {
601 if (family
== AF_NETLINK
)
602 return "ListenNetlink";
604 if (type
== SOCK_STREAM
)
605 return "ListenStream";
606 else if (type
== SOCK_DGRAM
)
607 return "ListenDatagram";
608 else if (type
== SOCK_SEQPACKET
)
609 return "ListenSequentialPacket";
611 assert_not_reached("Unknown socket type");
615 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
616 char time_string
[FORMAT_TIMESPAN_MAX
];
618 Socket
*s
= SOCKET(u
);
620 const char *prefix2
, *str
;
625 prefix
= strempty(prefix
);
626 prefix2
= strjoina(prefix
, "\t");
629 "%sSocket State: %s\n"
631 "%sBindIPv6Only: %s\n"
633 "%sSocketMode: %04o\n"
634 "%sDirectoryMode: %04o\n"
638 "%sTransparent: %s\n"
640 "%sPassCredentials: %s\n"
641 "%sPassSecurity: %s\n"
642 "%sTCPCongestion: %s\n"
643 "%sRemoveOnStop: %s\n"
645 "%sFileDescriptorName: %s\n"
646 "%sSELinuxContextFromNet: %s\n",
647 prefix
, socket_state_to_string(s
->state
),
648 prefix
, socket_result_to_string(s
->result
),
649 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
651 prefix
, s
->socket_mode
,
652 prefix
, s
->directory_mode
,
653 prefix
, yes_no(s
->keep_alive
),
654 prefix
, yes_no(s
->no_delay
),
655 prefix
, yes_no(s
->free_bind
),
656 prefix
, yes_no(s
->transparent
),
657 prefix
, yes_no(s
->broadcast
),
658 prefix
, yes_no(s
->pass_cred
),
659 prefix
, yes_no(s
->pass_sec
),
660 prefix
, strna(s
->tcp_congestion
),
661 prefix
, yes_no(s
->remove_on_stop
),
662 prefix
, yes_no(s
->writable
),
663 prefix
, socket_fdname(s
),
664 prefix
, yes_no(s
->selinux_context_from_net
));
666 if (s
->control_pid
> 0)
668 "%sControl PID: "PID_FMT
"\n",
669 prefix
, s
->control_pid
);
671 if (s
->bind_to_device
)
673 "%sBindToDevice: %s\n",
674 prefix
, s
->bind_to_device
);
679 "%sNConnections: %u\n"
680 "%sMaxConnections: %u\n"
681 "%sMaxConnectionsPerSource: %u\n",
682 prefix
, s
->n_accepted
,
683 prefix
, s
->n_connections
,
684 prefix
, s
->max_connections
,
685 prefix
, s
->max_connections_per_source
);
687 if (s
->priority
>= 0)
690 prefix
, s
->priority
);
692 if (s
->receive_buffer
> 0)
694 "%sReceiveBuffer: %zu\n",
695 prefix
, s
->receive_buffer
);
697 if (s
->send_buffer
> 0)
699 "%sSendBuffer: %zu\n",
700 prefix
, s
->send_buffer
);
712 if (s
->pipe_size
> 0)
715 prefix
, s
->pipe_size
);
722 if (s
->mq_maxmsg
> 0)
724 "%sMessageQueueMaxMessages: %li\n",
725 prefix
, s
->mq_maxmsg
);
727 if (s
->mq_msgsize
> 0)
729 "%sMessageQueueMessageSize: %li\n",
730 prefix
, s
->mq_msgsize
);
735 prefix
, yes_no(s
->reuse_port
));
739 "%sSmackLabel: %s\n",
744 "%sSmackLabelIPIn: %s\n",
745 prefix
, s
->smack_ip_in
);
749 "%sSmackLabelIPOut: %s\n",
750 prefix
, s
->smack_ip_out
);
752 if (!isempty(s
->user
) || !isempty(s
->group
))
755 "%sSocketGroup: %s\n",
756 prefix
, strna(s
->user
),
757 prefix
, strna(s
->group
));
759 if (s
->keep_alive_time
> 0)
761 "%sKeepAliveTimeSec: %s\n",
762 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
764 if (s
->keep_alive_interval
> 0)
766 "%sKeepAliveIntervalSec: %s\n",
767 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
769 if (s
->keep_alive_cnt
> 0)
771 "%sKeepAliveProbes: %u\n",
772 prefix
, s
->keep_alive_cnt
);
774 if (s
->defer_accept
> 0)
776 "%sDeferAcceptSec: %s\n",
777 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
779 LIST_FOREACH(port
, p
, s
->ports
) {
782 case SOCKET_SOCKET
: {
783 _cleanup_free_
char *k
= NULL
;
787 r
= socket_address_print(&p
->address
, &k
);
793 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
797 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
799 case SOCKET_USB_FUNCTION
:
800 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
803 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
806 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
811 "%sTriggerLimitIntervalSec: %s\n"
812 "%sTriggerLimitBurst: %u\n",
813 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
814 prefix
, s
->trigger_limit
.burst
);
816 str
= socket_protocol_to_name(s
->socket_protocol
);
818 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
820 if (!strv_isempty(s
->symlinks
)) {
823 fprintf(f
, "%sSymlinks:", prefix
);
824 STRV_FOREACH(q
, s
->symlinks
)
825 fprintf(f
, " %s", *q
);
831 "%sTimeoutSec: %s\n",
832 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->timeout_usec
, USEC_PER_SEC
));
834 exec_context_dump(&s
->exec_context
, f
, prefix
);
835 kill_context_dump(&s
->kill_context
, f
, prefix
);
837 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
838 if (!s
->exec_command
[c
])
841 fprintf(f
, "%s-> %s:\n",
842 prefix
, socket_exec_command_to_string(c
));
844 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
847 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
850 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
853 union sockaddr_union local
, remote
;
859 if (getsockname(fd
, &local
.sa
, &l
) < 0)
863 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
866 switch (local
.sa
.sa_family
) {
870 a
= be32toh(local
.in
.sin_addr
.s_addr
),
871 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
874 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
876 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
877 be16toh(local
.in
.sin_port
),
878 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
879 be16toh(remote
.in
.sin_port
)) < 0)
886 static const unsigned char ipv4_prefix
[] = {
887 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
890 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
891 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
893 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
894 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
897 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
899 a
[0], a
[1], a
[2], a
[3],
900 be16toh(local
.in6
.sin6_port
),
901 b
[0], b
[1], b
[2], b
[3],
902 be16toh(remote
.in6
.sin6_port
)) < 0)
905 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
910 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
911 be16toh(local
.in6
.sin6_port
),
912 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
913 be16toh(remote
.in6
.sin6_port
)) < 0)
924 k
= getpeercred(fd
, &ucred
);
927 "%u-"PID_FMT
"-"UID_FMT
,
928 nr
, ucred
.pid
, ucred
.uid
) < 0)
930 } else if (k
== -ENODATA
) {
931 /* This handles the case where somebody is
932 * connecting from another pid/uid namespace
933 * (e.g. from outside of our container). */
948 local
.vm
.svm_cid
, local
.vm
.svm_port
,
949 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
955 assert_not_reached("Unhandled socket type.");
962 static void socket_close_fds(Socket
*s
) {
968 LIST_FOREACH(port
, p
, s
->ports
) {
971 was_open
= p
->fd
>= 0;
973 p
->event_source
= sd_event_source_unref(p
->event_source
);
974 p
->fd
= safe_close(p
->fd
);
975 socket_cleanup_fd_list(p
);
977 /* One little note: we should normally not delete any sockets in the file system here! After all some
978 * other process we spawned might still have a reference of this fd and wants to continue to use
979 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
980 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
981 * anyway, but only then. */
983 if (!was_open
|| !s
->remove_on_stop
)
989 (void) unlink(p
->path
);
993 (void) mq_unlink(p
->path
);
997 (void) socket_address_unlink(&p
->address
);
1005 if (s
->remove_on_stop
)
1006 STRV_FOREACH(i
, s
->symlinks
)
1010 static void socket_apply_socket_options(Socket
*s
, int fd
) {
1016 if (s
->keep_alive
) {
1017 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_KEEPALIVE
, true);
1019 log_unit_warning_errno(UNIT(s
), r
, "SO_KEEPALIVE failed: %m");
1022 if (s
->keep_alive_time
> 0) {
1023 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPIDLE
, s
->keep_alive_time
/ USEC_PER_SEC
);
1025 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPIDLE failed: %m");
1028 if (s
->keep_alive_interval
> 0) {
1029 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPINTVL
, s
->keep_alive_interval
/ USEC_PER_SEC
);
1031 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPINTVL failed: %m");
1034 if (s
->keep_alive_cnt
> 0) {
1035 r
= setsockopt_int(fd
, SOL_TCP
, TCP_KEEPCNT
, s
->keep_alive_cnt
);
1037 log_unit_warning_errno(UNIT(s
), r
, "TCP_KEEPCNT failed: %m");
1040 if (s
->defer_accept
> 0) {
1041 r
= setsockopt_int(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, s
->defer_accept
/ USEC_PER_SEC
);
1043 log_unit_warning_errno(UNIT(s
), r
, "TCP_DEFER_ACCEPT failed: %m");
1047 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1048 r
= setsockopt_int(fd
, SOL_SCTP
, SCTP_NODELAY
, true);
1050 log_unit_warning_errno(UNIT(s
), r
, "SCTP_NODELAY failed: %m");
1052 r
= setsockopt_int(fd
, SOL_TCP
, TCP_NODELAY
, true);
1054 log_unit_warning_errno(UNIT(s
), r
, "TCP_NODELAY failed: %m");
1059 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_BROADCAST
, true);
1061 log_unit_warning_errno(UNIT(s
), r
, "SO_BROADCAST failed: %m");
1065 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSCRED
, true);
1067 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSCRED failed: %m");
1071 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PASSSEC
, true);
1073 log_unit_warning_errno(UNIT(s
), r
, "SO_PASSSEC failed: %m");
1076 if (s
->priority
>= 0) {
1077 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_PRIORITY
, s
->priority
);
1079 log_unit_warning_errno(UNIT(s
), r
, "SO_PRIORITY failed: %m");
1082 if (s
->receive_buffer
> 0) {
1083 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1084 if (setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, s
->receive_buffer
) < 0) {
1085 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_RCVBUF
, s
->receive_buffer
);
1087 log_unit_warning_errno(UNIT(s
), r
, "SO_RCVBUF failed: %m");
1091 if (s
->send_buffer
> 0) {
1092 if (setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, s
->send_buffer
) < 0) {
1093 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_SNDBUF
, s
->send_buffer
);
1095 log_unit_warning_errno(UNIT(s
), r
, "SO_SNDBUF failed: %m");
1100 r
= setsockopt_int(fd
, SOL_SOCKET
, SO_MARK
, s
->mark
);
1102 log_unit_warning_errno(UNIT(s
), r
, "SO_MARK failed: %m");
1105 if (s
->ip_tos
>= 0) {
1106 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TOS
, s
->ip_tos
);
1108 log_unit_warning_errno(UNIT(s
), r
, "IP_TOS failed: %m");
1111 if (s
->ip_ttl
>= 0) {
1114 r
= setsockopt_int(fd
, IPPROTO_IP
, IP_TTL
, s
->ip_ttl
);
1116 if (socket_ipv6_is_supported())
1117 x
= setsockopt_int(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, s
->ip_ttl
);
1122 log_unit_warning_errno(UNIT(s
), r
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1125 if (s
->tcp_congestion
)
1126 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1127 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1129 if (s
->smack_ip_in
) {
1130 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1132 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1135 if (s
->smack_ip_out
) {
1136 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1138 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1142 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1148 if (s
->pipe_size
> 0)
1149 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1150 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1153 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1155 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1159 static int fifo_address_create(
1161 mode_t directory_mode
,
1162 mode_t socket_mode
) {
1164 _cleanup_close_
int fd
= -1;
1171 (void) mkdir_parents_label(path
, directory_mode
);
1173 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1177 /* Enforce the right access mode for the fifo */
1178 old_mask
= umask(~socket_mode
);
1180 /* Include the original umask in our mask */
1181 (void) umask(~socket_mode
| old_mask
);
1183 r
= mkfifo(path
, socket_mode
);
1184 (void) umask(old_mask
);
1186 if (r
< 0 && errno
!= EEXIST
) {
1191 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1197 mac_selinux_create_file_clear();
1199 if (fstat(fd
, &st
) < 0) {
1204 if (!S_ISFIFO(st
.st_mode
) ||
1205 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1206 st
.st_uid
!= getuid() ||
1207 st
.st_gid
!= getgid()) {
1215 mac_selinux_create_file_clear();
1219 static int special_address_create(const char *path
, bool writable
) {
1220 _cleanup_close_
int fd
= -1;
1225 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1229 if (fstat(fd
, &st
) < 0)
1232 /* Check whether this is a /proc, /sys or /dev file or char device */
1233 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1239 static int usbffs_address_create(const char *path
) {
1240 _cleanup_close_
int fd
= -1;
1245 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1249 if (fstat(fd
, &st
) < 0)
1252 /* Check whether this is a regular file (ffs endpoint) */
1253 if (!S_ISREG(st
.st_mode
))
1259 static int mq_address_create(
1265 _cleanup_close_
int fd
= -1;
1268 struct mq_attr _attr
, *attr
= NULL
;
1272 if (maxmsg
> 0 && msgsize
> 0) {
1273 _attr
= (struct mq_attr
) {
1274 .mq_flags
= O_NONBLOCK
,
1275 .mq_maxmsg
= maxmsg
,
1276 .mq_msgsize
= msgsize
,
1281 /* Enforce the right access mode for the mq */
1282 old_mask
= umask(~mq_mode
);
1284 /* Include the original umask in our mask */
1285 (void) umask(~mq_mode
| old_mask
);
1286 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1287 (void) umask(old_mask
);
1292 if (fstat(fd
, &st
) < 0)
1295 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1296 st
.st_uid
!= getuid() ||
1297 st
.st_gid
!= getgid())
1303 static int socket_symlink(Socket
*s
) {
1310 p
= socket_find_symlink_target(s
);
1314 STRV_FOREACH(i
, s
->symlinks
) {
1315 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1317 r
= symlink_idempotent(p
, *i
, false);
1319 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1320 /* If there's already something where we want to create the symlink, and the destructive
1321 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1324 if (unlink(*i
) >= 0)
1325 r
= symlink_idempotent(p
, *i
, false);
1329 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s → %s, ignoring: %m", p
, *i
);
1335 static int usbffs_write_descs(int fd
, Service
*s
) {
1338 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1341 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1345 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1348 static int usbffs_select_ep(const struct dirent
*d
) {
1349 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1352 static int usbffs_dispatch_eps(SocketPort
*p
) {
1353 _cleanup_free_
struct dirent
**ent
= NULL
;
1357 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1362 p
->auxiliary_fds
= new(int, n
);
1363 if (!p
->auxiliary_fds
) {
1368 p
->n_auxiliary_fds
= n
;
1371 for (i
= 0; i
< n
; ++i
) {
1372 _cleanup_free_
char *ep
= NULL
;
1374 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1380 path_simplify(ep
, false);
1382 r
= usbffs_address_create(ep
);
1386 p
->auxiliary_fds
[k
++] = r
;
1393 close_many(p
->auxiliary_fds
, k
);
1394 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1395 p
->n_auxiliary_fds
= 0;
1398 for (i
= 0; i
< n
; ++i
)
1404 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1407 _cleanup_free_
char *path
= NULL
;
1413 if (s
->selinux_context_from_net
) {
1414 /* If this is requested, get label from the network label */
1416 r
= mac_selinux_get_our_label(ret
);
1417 if (r
== -EOPNOTSUPP
)
1421 /* Otherwise, get it from the executable we are about to start */
1422 r
= socket_instantiate_service(s
);
1426 if (!UNIT_ISSET(s
->service
))
1429 service
= SERVICE(UNIT_DEREF(s
->service
));
1430 c
= service
->exec_command
[SERVICE_EXEC_START
];
1434 r
= chase_symlinks(c
->path
, service
->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
);
1438 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1439 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1450 static int socket_address_listen_do(
1452 const SocketAddress
*address
,
1453 const char *label
) {
1458 return socket_address_listen(
1460 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1472 static int socket_address_listen_in_cgroup(
1474 const SocketAddress
*address
,
1475 const char *label
) {
1477 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1484 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1485 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1486 * unit's cgroup for the purpose of BPF filtering and such. */
1488 if (!IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
1489 goto shortcut
; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1491 r
= bpf_firewall_supported();
1494 if (r
== BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1497 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1498 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1500 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1502 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1506 pair
[0] = safe_close(pair
[0]);
1508 fd
= socket_address_listen_do(s
, address
, label
);
1510 log_unit_error_errno(UNIT(s
), fd
, "Failed to create listening socket: %m");
1511 _exit(EXIT_FAILURE
);
1514 r
= send_one_fd(pair
[1], fd
, 0);
1516 log_unit_error_errno(UNIT(s
), r
, "Failed to send listening socket to parent: %m");
1517 _exit(EXIT_FAILURE
);
1520 _exit(EXIT_SUCCESS
);
1523 pair
[1] = safe_close(pair
[1]);
1524 fd
= receive_one_fd(pair
[0], 0);
1526 /* We synchronously wait for the helper, as it shouldn't be slow */
1527 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1534 return log_unit_error_errno(UNIT(s
), fd
, "Failed to receive listening socket: %m");
1539 fd
= socket_address_listen_do(s
, address
, label
);
1541 return log_error_errno(fd
, "Failed to create listening socket: %m");
1546 static int socket_open_fds(Socket
*s
) {
1547 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1548 bool know_label
= false;
1554 LIST_FOREACH(port
, p
, s
->ports
) {
1564 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1565 * we need this and remember it for the rest. */
1567 r
= socket_determine_selinux_label(s
, &label
);
1574 /* Apply the socket protocol */
1575 switch (p
->address
.type
) {
1578 case SOCK_SEQPACKET
:
1579 if (s
->socket_protocol
== IPPROTO_SCTP
)
1580 p
->address
.protocol
= s
->socket_protocol
;
1584 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1585 p
->address
.protocol
= s
->socket_protocol
;
1589 r
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1594 socket_apply_socket_options(s
, p
->fd
);
1598 case SOCKET_SPECIAL
:
1600 p
->fd
= special_address_create(p
->path
, s
->writable
);
1609 p
->fd
= fifo_address_create(
1618 socket_apply_fifo_options(s
, p
->fd
);
1624 p
->fd
= mq_address_create(
1635 case SOCKET_USB_FUNCTION
: {
1636 _cleanup_free_
char *ep
= NULL
;
1638 ep
= path_make_absolute("ep0", p
->path
);
1640 p
->fd
= usbffs_address_create(ep
);
1646 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1650 r
= usbffs_dispatch_eps(p
);
1657 assert_not_reached("Unknown port type");
1664 socket_close_fds(s
);
1668 static void socket_unwatch_fds(Socket
*s
) {
1674 LIST_FOREACH(port
, p
, s
->ports
) {
1678 if (!p
->event_source
)
1681 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1683 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1687 static int socket_watch_fds(Socket
*s
) {
1693 LIST_FOREACH(port
, p
, s
->ports
) {
1697 if (p
->event_source
) {
1698 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1702 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1706 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1713 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1714 socket_unwatch_fds(s
);
1724 static int socket_check_open(Socket
*s
) {
1725 bool have_open
= false, have_closed
= false;
1730 LIST_FOREACH(port
, p
, s
->ports
) {
1736 if (have_open
&& have_closed
)
1737 return SOCKET_OPEN_SOME
;
1741 return SOCKET_OPEN_ALL
;
1743 return SOCKET_OPEN_NONE
;
1746 static void socket_set_state(Socket
*s
, SocketState state
) {
1747 SocketState old_state
;
1750 old_state
= s
->state
;
1758 SOCKET_STOP_PRE_SIGTERM
,
1759 SOCKET_STOP_PRE_SIGKILL
,
1761 SOCKET_FINAL_SIGTERM
,
1762 SOCKET_FINAL_SIGKILL
)) {
1764 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1765 socket_unwatch_control_pid(s
);
1766 s
->control_command
= NULL
;
1767 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1770 if (state
!= SOCKET_LISTENING
)
1771 socket_unwatch_fds(s
);
1779 SOCKET_STOP_PRE_SIGTERM
,
1780 SOCKET_STOP_PRE_SIGKILL
))
1781 socket_close_fds(s
);
1783 if (state
!= old_state
)
1784 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1786 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
1789 static int socket_coldplug(Unit
*u
) {
1790 Socket
*s
= SOCKET(u
);
1794 assert(s
->state
== SOCKET_DEAD
);
1796 if (s
->deserialized_state
== s
->state
)
1799 if (s
->control_pid
> 0 &&
1800 pid_is_unwaited(s
->control_pid
) &&
1801 IN_SET(s
->deserialized_state
,
1806 SOCKET_STOP_PRE_SIGTERM
,
1807 SOCKET_STOP_PRE_SIGKILL
,
1809 SOCKET_FINAL_SIGTERM
,
1810 SOCKET_FINAL_SIGKILL
)) {
1812 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1816 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1821 if (IN_SET(s
->deserialized_state
,
1827 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1828 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1829 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1830 * and if there's a mismatch, warn loudly. */
1832 r
= socket_check_open(s
);
1833 if (r
== SOCKET_OPEN_NONE
)
1834 log_unit_warning(UNIT(s
),
1835 "Socket unit configuration has changed while unit has been running, "
1836 "no open socket file descriptor left. "
1837 "The socket unit is not functional until restarted.");
1838 else if (r
== SOCKET_OPEN_SOME
)
1839 log_unit_warning(UNIT(s
),
1840 "Socket unit configuration has changed while unit has been running, "
1841 "and some socket file descriptors have not been opened yet. "
1842 "The socket unit is not fully functional until restarted.");
1845 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1846 r
= socket_watch_fds(s
);
1851 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
)) {
1852 (void) unit_setup_dynamic_creds(u
);
1853 (void) unit_setup_exec_runtime(u
);
1856 socket_set_state(s
, s
->deserialized_state
);
1860 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1862 ExecParameters exec_params
= {
1863 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1876 r
= unit_prepare_exec(UNIT(s
));
1880 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1884 unit_set_exec_params(UNIT(s
), &exec_params
);
1886 r
= exec_spawn(UNIT(s
),
1896 r
= unit_watch_pid(UNIT(s
), pid
);
1898 /* FIXME: we need to do something here */
1906 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1910 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1914 /* We have to resolve the user names out-of-process, hence
1915 * let's fork here. It's messy, but well, what can we do? */
1917 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1921 uid_t uid
= UID_INVALID
;
1922 gid_t gid
= GID_INVALID
;
1927 if (!isempty(s
->user
)) {
1928 const char *user
= s
->user
;
1930 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1932 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1937 if (!isempty(s
->group
)) {
1938 const char *group
= s
->group
;
1940 r
= get_group_creds(&group
, &gid
, 0);
1942 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1947 LIST_FOREACH(port
, p
, s
->ports
) {
1948 const char *path
= NULL
;
1950 if (p
->type
== SOCKET_SOCKET
)
1951 path
= socket_address_get_path(&p
->address
);
1952 else if (p
->type
== SOCKET_FIFO
)
1958 if (chown(path
, uid
, gid
) < 0) {
1959 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1964 _exit(EXIT_SUCCESS
);
1967 r
= unit_watch_pid(UNIT(s
), pid
);
1975 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1979 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1982 if (s
->result
== SOCKET_SUCCESS
)
1985 if (s
->result
!= SOCKET_SUCCESS
)
1986 log_unit_warning(UNIT(s
), "Failed with result '%s'.", socket_result_to_string(s
->result
));
1988 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1990 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
1992 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
1994 unit_unref_uid_gid(UNIT(s
), true);
1996 dynamic_creds_destroy(&s
->dynamic_creds
);
1999 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2001 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2005 if (s
->result
== SOCKET_SUCCESS
)
2008 socket_unwatch_control_pid(s
);
2009 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2010 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2012 if (s
->control_command
) {
2013 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2017 socket_set_state(s
, SOCKET_STOP_POST
);
2019 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2024 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2025 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2028 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2033 if (s
->result
== SOCKET_SUCCESS
)
2036 r
= unit_kill_context(
2039 !IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FINAL_SIGTERM
) ?
2040 KILL_KILL
: KILL_TERMINATE
,
2048 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2052 socket_set_state(s
, state
);
2053 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2054 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2055 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2056 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2057 else if (state
== SOCKET_FINAL_SIGTERM
)
2058 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2060 socket_enter_dead(s
, SOCKET_SUCCESS
);
2065 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2067 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2068 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2070 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2073 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2077 if (s
->result
== SOCKET_SUCCESS
)
2080 socket_unwatch_control_pid(s
);
2081 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2082 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2084 if (s
->control_command
) {
2085 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2089 socket_set_state(s
, SOCKET_STOP_PRE
);
2091 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2096 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2097 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2100 static void socket_enter_listening(Socket
*s
) {
2104 r
= socket_watch_fds(s
);
2106 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2110 socket_set_state(s
, SOCKET_LISTENING
);
2114 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2117 static void socket_enter_start_post(Socket
*s
) {
2121 socket_unwatch_control_pid(s
);
2122 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2123 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2125 if (s
->control_command
) {
2126 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2128 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2132 socket_set_state(s
, SOCKET_START_POST
);
2134 socket_enter_listening(s
);
2139 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2142 static void socket_enter_start_chown(Socket
*s
) {
2147 r
= socket_open_fds(s
);
2149 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2153 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2155 socket_unwatch_control_pid(s
);
2156 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2157 s
->control_command
= NULL
;
2159 r
= socket_chown(s
, &s
->control_pid
);
2161 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2165 socket_set_state(s
, SOCKET_START_CHOWN
);
2167 socket_enter_start_post(s
);
2172 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2175 static void socket_enter_start_pre(Socket
*s
) {
2179 socket_unwatch_control_pid(s
);
2181 unit_warn_leftover_processes(UNIT(s
));
2183 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2184 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2186 if (s
->control_command
) {
2187 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2189 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2193 socket_set_state(s
, SOCKET_START_PRE
);
2195 socket_enter_start_chown(s
);
2200 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2203 static void flush_ports(Socket
*s
) {
2206 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2209 LIST_FOREACH(port
, p
, s
->ports
) {
2213 (void) flush_accept(p
->fd
);
2214 (void) flush_fd(p
->fd
);
2218 static void socket_enter_running(Socket
*s
, int cfd
) {
2219 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2222 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2227 /* We don't take connections anymore if we are supposed to shut down anyway */
2228 if (unit_stop_pending(UNIT(s
))) {
2230 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2240 if (!ratelimit_below(&s
->trigger_limit
)) {
2241 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2242 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2247 bool pending
= false;
2252 /* If there's already a start pending don't bother to
2254 HASHMAP_FOREACH_KEY(v
, other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2255 if (unit_active_or_pending(other
)) {
2261 if (!UNIT_ISSET(s
->service
)) {
2262 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2267 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2272 socket_set_state(s
, SOCKET_RUNNING
);
2274 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2275 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2278 if (s
->n_connections
>= s
->max_connections
) {
2279 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2284 if (s
->max_connections_per_source
> 0) {
2285 r
= socket_acquire_peer(s
, cfd
, &p
);
2288 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2289 _cleanup_free_
char *t
= NULL
;
2291 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2293 log_unit_warning(UNIT(s
),
2294 "Too many incoming connections (%u) from source %s, dropping connection.",
2295 p
->n_ref
, strnull(t
));
2300 r
= socket_instantiate_service(s
);
2304 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2309 /* ENOTCONN is legitimate if TCP RST was received.
2310 * This connection is over, but the socket unit lives on. */
2311 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2315 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2319 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2323 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2327 service
= SERVICE(UNIT_DEREF(s
->service
));
2328 unit_ref_unset(&s
->service
);
2331 unit_choose_id(UNIT(service
), name
);
2333 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2337 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2340 service
->peer
= TAKE_PTR(p
); /* Pass ownership of the peer reference */
2342 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2344 /* We failed to activate the new service, but it still exists. Let's make sure the service
2345 * closes and forgets the connection fd again, immediately. */
2346 service_close_socket_fd(service
);
2350 /* Notify clients about changed counters */
2351 unit_add_to_dbus_queue(UNIT(s
));
2362 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2363 cfd
>= 0 ? "template" : "non-template",
2364 bus_error_message(&error
, r
));
2366 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2370 static void socket_run_next(Socket
*s
) {
2374 assert(s
->control_command
);
2375 assert(s
->control_command
->command_next
);
2377 socket_unwatch_control_pid(s
);
2379 s
->control_command
= s
->control_command
->command_next
;
2381 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2388 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2390 if (s
->state
== SOCKET_START_POST
)
2391 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2392 else if (s
->state
== SOCKET_STOP_POST
)
2393 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2395 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2398 static int socket_start(Unit
*u
) {
2399 Socket
*s
= SOCKET(u
);
2404 /* We cannot fulfill this request right now, try again later
2406 if (IN_SET(s
->state
,
2408 SOCKET_STOP_PRE_SIGKILL
,
2409 SOCKET_STOP_PRE_SIGTERM
,
2411 SOCKET_FINAL_SIGTERM
,
2412 SOCKET_FINAL_SIGKILL
))
2415 /* Already on it! */
2416 if (IN_SET(s
->state
,
2422 /* Cannot run this without the service being around */
2423 if (UNIT_ISSET(s
->service
)) {
2426 service
= SERVICE(UNIT_DEREF(s
->service
));
2428 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2429 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2433 /* If the service is already active we cannot start the
2435 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
2436 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2441 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2443 r
= unit_start_limit_test(u
);
2445 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2449 r
= unit_acquire_invocation_id(u
);
2453 s
->result
= SOCKET_SUCCESS
;
2454 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2456 u
->reset_accounting
= true;
2458 socket_enter_start_pre(s
);
2462 static int socket_stop(Unit
*u
) {
2463 Socket
*s
= SOCKET(u
);
2468 if (IN_SET(s
->state
,
2470 SOCKET_STOP_PRE_SIGTERM
,
2471 SOCKET_STOP_PRE_SIGKILL
,
2473 SOCKET_FINAL_SIGTERM
,
2474 SOCKET_FINAL_SIGKILL
))
2477 /* If there's already something running we go directly into
2479 if (IN_SET(s
->state
,
2482 SOCKET_START_POST
)) {
2483 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2487 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2489 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2493 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2494 Socket
*s
= SOCKET(u
);
2502 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2503 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2504 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2505 unit_serialize_item_format(u
, f
, "n-refused", "%u", s
->n_refused
);
2507 if (s
->control_pid
> 0)
2508 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2510 if (s
->control_command_id
>= 0)
2511 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2513 LIST_FOREACH(port
, p
, s
->ports
) {
2519 copy
= fdset_put_dup(fds
, p
->fd
);
2523 if (p
->type
== SOCKET_SOCKET
) {
2524 _cleanup_free_
char *t
= NULL
;
2526 r
= socket_address_print(&p
->address
, &t
);
2530 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2531 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2533 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2535 } else if (p
->type
== SOCKET_SPECIAL
)
2536 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2537 else if (p
->type
== SOCKET_MQUEUE
)
2538 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2539 else if (p
->type
== SOCKET_USB_FUNCTION
)
2540 unit_serialize_item_format(u
, f
, "ffs", "%i %s", copy
, p
->path
);
2542 assert(p
->type
== SOCKET_FIFO
);
2543 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2550 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2552 p
->fd
= fdset_remove(fds
, fd
);
2555 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2556 Socket
*s
= SOCKET(u
);
2562 if (streq(key
, "state")) {
2565 state
= socket_state_from_string(value
);
2567 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2569 s
->deserialized_state
= state
;
2570 } else if (streq(key
, "result")) {
2573 f
= socket_result_from_string(value
);
2575 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2576 else if (f
!= SOCKET_SUCCESS
)
2579 } else if (streq(key
, "n-accepted")) {
2582 if (safe_atou(value
, &k
) < 0)
2583 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2586 } else if (streq(key
, "n-refused")) {
2589 if (safe_atou(value
, &k
) < 0)
2590 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2593 } else if (streq(key
, "control-pid")) {
2596 if (parse_pid(value
, &pid
) < 0)
2597 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2599 s
->control_pid
= pid
;
2600 } else if (streq(key
, "control-command")) {
2601 SocketExecCommand id
;
2603 id
= socket_exec_command_from_string(value
);
2605 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2607 s
->control_command_id
= id
;
2608 s
->control_command
= s
->exec_command
[id
];
2610 } else if (streq(key
, "fifo")) {
2614 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2615 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2617 LIST_FOREACH(port
, p
, s
->ports
)
2618 if (p
->type
== SOCKET_FIFO
&&
2619 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2620 socket_port_take_fd(p
, fds
, fd
);
2624 } else if (streq(key
, "special")) {
2628 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2629 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2631 LIST_FOREACH(port
, p
, s
->ports
)
2632 if (p
->type
== SOCKET_SPECIAL
&&
2633 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2634 socket_port_take_fd(p
, fds
, fd
);
2638 } else if (streq(key
, "mqueue")) {
2642 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2643 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2645 LIST_FOREACH(port
, p
, s
->ports
)
2646 if (p
->type
== SOCKET_MQUEUE
&&
2647 streq(p
->path
, value
+skip
)) {
2648 socket_port_take_fd(p
, fds
, fd
);
2652 } else if (streq(key
, "socket")) {
2653 int fd
, type
, skip
= 0;
2656 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2657 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2659 LIST_FOREACH(port
, p
, s
->ports
)
2660 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2661 socket_port_take_fd(p
, fds
, fd
);
2665 } else if (streq(key
, "netlink")) {
2669 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2670 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2672 LIST_FOREACH(port
, p
, s
->ports
)
2673 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2674 socket_port_take_fd(p
, fds
, fd
);
2678 } else if (streq(key
, "ffs")) {
2682 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2683 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2685 LIST_FOREACH(port
, p
, s
->ports
)
2686 if (p
->type
== SOCKET_USB_FUNCTION
&&
2687 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2688 socket_port_take_fd(p
, fds
, fd
);
2693 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2698 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2699 Socket
*s
= SOCKET(u
);
2704 LIST_FOREACH(port
, p
, s
->ports
) {
2708 if (p
->type
!= SOCKET_SOCKET
)
2714 FDSET_FOREACH(fd
, fds
, i
) {
2715 if (socket_address_matches_fd(&p
->address
, fd
)) {
2716 p
->fd
= fdset_remove(fds
, fd
);
2717 s
->deserialized_state
= SOCKET_LISTENING
;
2724 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2727 return state_translation_table
[SOCKET(u
)->state
];
2730 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2733 return socket_state_to_string(SOCKET(u
)->state
);
2736 const char* socket_port_type_to_string(SocketPort
*p
) {
2744 switch (p
->address
.type
) {
2752 case SOCK_SEQPACKET
:
2753 return "SequentialPacket";
2756 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2764 case SOCKET_SPECIAL
:
2768 return "MessageQueue";
2773 case SOCKET_USB_FUNCTION
:
2774 return "USBFunction";
2781 SocketType
socket_port_type_from_string(const char *s
) {
2784 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2785 return SOCKET_SOCKET
;
2786 else if (streq(s
, "Special"))
2787 return SOCKET_SPECIAL
;
2788 else if (streq(s
, "MessageQueue"))
2789 return SOCKET_MQUEUE
;
2790 else if (streq(s
, "FIFO"))
2792 else if (streq(s
, "USBFunction"))
2793 return SOCKET_USB_FUNCTION
;
2795 return _SOCKET_TYPE_INVALID
;
2798 _pure_
static bool socket_may_gc(Unit
*u
) {
2799 Socket
*s
= SOCKET(u
);
2803 return s
->n_connections
== 0;
2806 static int socket_accept_do(Socket
*s
, int fd
) {
2813 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2827 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2828 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
2836 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2837 * connection socket is also properly associated with the cgroup. */
2839 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2842 r
= bpf_firewall_supported();
2845 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2848 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2849 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2851 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2853 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2857 pair
[0] = safe_close(pair
[0]);
2859 cfd
= socket_accept_do(s
, fd
);
2861 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2862 _exit(EXIT_FAILURE
);
2865 r
= send_one_fd(pair
[1], cfd
, 0);
2867 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
2868 _exit(EXIT_FAILURE
);
2871 _exit(EXIT_SUCCESS
);
2874 pair
[1] = safe_close(pair
[1]);
2875 cfd
= receive_one_fd(pair
[0], 0);
2877 /* We synchronously wait for the helper, as it shouldn't be slow */
2878 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
2885 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
2890 cfd
= socket_accept_do(s
, fd
);
2892 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2897 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2898 SocketPort
*p
= userdata
;
2904 if (p
->socket
->state
!= SOCKET_LISTENING
)
2907 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2909 if (revents
!= EPOLLIN
) {
2911 if (revents
& EPOLLHUP
)
2912 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.");
2914 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2918 if (p
->socket
->accept
&&
2919 p
->type
== SOCKET_SOCKET
&&
2920 socket_address_can_accept(&p
->address
)) {
2922 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
2926 socket_apply_socket_options(p
->socket
, cfd
);
2929 socket_enter_running(p
->socket
, cfd
);
2933 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2937 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2938 Socket
*s
= SOCKET(u
);
2944 if (pid
!= s
->control_pid
)
2949 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
2951 else if (code
== CLD_EXITED
)
2952 f
= SOCKET_FAILURE_EXIT_CODE
;
2953 else if (code
== CLD_KILLED
)
2954 f
= SOCKET_FAILURE_SIGNAL
;
2955 else if (code
== CLD_DUMPED
)
2956 f
= SOCKET_FAILURE_CORE_DUMP
;
2958 assert_not_reached("Unknown sigchld code");
2960 if (s
->control_command
) {
2961 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2963 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
2967 log_unit_full(u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2968 "Control process exited, code=%s status=%i",
2969 sigchld_code_to_string(code
), status
);
2971 if (s
->result
== SOCKET_SUCCESS
)
2974 if (s
->control_command
&&
2975 s
->control_command
->command_next
&&
2976 f
== SOCKET_SUCCESS
) {
2978 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2981 s
->control_command
= NULL
;
2982 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2984 /* No further commands for this step, so let's figure
2985 * out what to do next */
2987 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2991 case SOCKET_START_PRE
:
2992 if (f
== SOCKET_SUCCESS
)
2993 socket_enter_start_chown(s
);
2995 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
2998 case SOCKET_START_CHOWN
:
2999 if (f
== SOCKET_SUCCESS
)
3000 socket_enter_start_post(s
);
3002 socket_enter_stop_pre(s
, f
);
3005 case SOCKET_START_POST
:
3006 if (f
== SOCKET_SUCCESS
)
3007 socket_enter_listening(s
);
3009 socket_enter_stop_pre(s
, f
);
3012 case SOCKET_STOP_PRE
:
3013 case SOCKET_STOP_PRE_SIGTERM
:
3014 case SOCKET_STOP_PRE_SIGKILL
:
3015 socket_enter_stop_post(s
, f
);
3018 case SOCKET_STOP_POST
:
3019 case SOCKET_FINAL_SIGTERM
:
3020 case SOCKET_FINAL_SIGKILL
:
3021 socket_enter_dead(s
, f
);
3025 assert_not_reached("Uh, control process died at wrong time.");
3029 /* Notify clients about changed exit status */
3030 unit_add_to_dbus_queue(u
);
3033 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3034 Socket
*s
= SOCKET(userdata
);
3037 assert(s
->timer_event_source
== source
);
3041 case SOCKET_START_PRE
:
3042 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3043 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3046 case SOCKET_START_CHOWN
:
3047 case SOCKET_START_POST
:
3048 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3049 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3052 case SOCKET_STOP_PRE
:
3053 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3054 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3057 case SOCKET_STOP_PRE_SIGTERM
:
3058 if (s
->kill_context
.send_sigkill
) {
3059 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3060 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3062 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3063 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3067 case SOCKET_STOP_PRE_SIGKILL
:
3068 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3069 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3072 case SOCKET_STOP_POST
:
3073 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3074 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3077 case SOCKET_FINAL_SIGTERM
:
3078 if (s
->kill_context
.send_sigkill
) {
3079 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3080 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3082 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3083 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3087 case SOCKET_FINAL_SIGKILL
:
3088 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3089 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3093 assert_not_reached("Timeout at wrong time.");
3099 int socket_collect_fds(Socket
*s
, int **fds
) {
3100 size_t k
= 0, n
= 0;
3107 /* Called from the service code for requesting our fds */
3109 LIST_FOREACH(port
, p
, s
->ports
) {
3112 n
+= p
->n_auxiliary_fds
;
3124 LIST_FOREACH(port
, p
, s
->ports
) {
3129 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3130 rfds
[k
++] = p
->auxiliary_fds
[i
];
3139 static void socket_reset_failed(Unit
*u
) {
3140 Socket
*s
= SOCKET(u
);
3144 if (s
->state
== SOCKET_FAILED
)
3145 socket_set_state(s
, SOCKET_DEAD
);
3147 s
->result
= SOCKET_SUCCESS
;
3150 void socket_connection_unref(Socket
*s
) {
3153 /* The service is dead. Yay!
3155 * This is strictly for one-instance-per-connection
3158 assert(s
->n_connections
> 0);
3161 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3164 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3165 Socket
*s
= SOCKET(u
);
3170 /* Filter out invocations with bogus state */
3171 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
3174 /* Don't propagate state changes from the service if we are already down */
3175 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3178 /* We don't care for the service state if we are in Accept=yes mode */
3182 /* Propagate start limit hit state */
3183 if (other
->start_limit_hit
) {
3184 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3188 /* Don't propagate anything if there's still a job queued */
3192 if (IN_SET(SERVICE(other
)->state
,
3193 SERVICE_DEAD
, SERVICE_FAILED
,
3194 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3195 SERVICE_AUTO_RESTART
))
3196 socket_enter_listening(s
);
3198 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3199 socket_set_state(s
, SOCKET_RUNNING
);
3202 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3203 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3206 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3207 Socket
*s
= SOCKET(u
);
3211 if (!s
->timer_event_source
)
3214 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3217 if (t
== USEC_INFINITY
)
3224 char *socket_fdname(Socket
*s
) {
3227 /* Returns the name to use for $LISTEN_NAMES. If the user
3228 * didn't specify anything specifically, use the socket unit's
3229 * name as fallback. */
3231 return s
->fdname
?: UNIT(s
)->id
;
3234 static int socket_control_pid(Unit
*u
) {
3235 Socket
*s
= SOCKET(u
);
3239 return s
->control_pid
;
3242 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3243 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3244 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3245 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3246 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3247 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3250 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3252 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3253 [SOCKET_SUCCESS
] = "success",
3254 [SOCKET_FAILURE_RESOURCES
] = "resources",
3255 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3256 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3257 [SOCKET_FAILURE_SIGNAL
] = "signal",
3258 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3259 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3260 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3261 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3264 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3266 const UnitVTable socket_vtable
= {
3267 .object_size
= sizeof(Socket
),
3268 .exec_context_offset
= offsetof(Socket
, exec_context
),
3269 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3270 .kill_context_offset
= offsetof(Socket
, kill_context
),
3271 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3272 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3278 .private_section
= "Socket",
3280 .can_transient
= true,
3282 .init
= socket_init
,
3283 .done
= socket_done
,
3284 .load
= socket_load
,
3286 .coldplug
= socket_coldplug
,
3288 .dump
= socket_dump
,
3290 .start
= socket_start
,
3291 .stop
= socket_stop
,
3293 .kill
= socket_kill
,
3295 .get_timeout
= socket_get_timeout
,
3297 .serialize
= socket_serialize
,
3298 .deserialize_item
= socket_deserialize_item
,
3299 .distribute_fds
= socket_distribute_fds
,
3301 .active_state
= socket_active_state
,
3302 .sub_state_to_string
= socket_sub_state_to_string
,
3304 .may_gc
= socket_may_gc
,
3306 .sigchld_event
= socket_sigchld_event
,
3308 .trigger_notify
= socket_trigger_notify
,
3310 .reset_failed
= socket_reset_failed
,
3312 .control_pid
= socket_control_pid
,
3314 .bus_vtable
= bus_socket_vtable
,
3315 .bus_set_property
= bus_socket_set_property
,
3316 .bus_commit_properties
= bus_socket_commit_properties
,
3318 .status_message_formats
= {
3319 /*.starting_stopping = {
3320 [0] = "Starting socket %s...",
3321 [1] = "Stopping socket %s...",
3323 .finished_start_job
= {
3324 [JOB_DONE
] = "Listening on %s.",
3325 [JOB_FAILED
] = "Failed to listen on %s.",
3326 [JOB_TIMEOUT
] = "Timed out starting %s.",
3328 .finished_stop_job
= {
3329 [JOB_DONE
] = "Closed %s.",
3330 [JOB_FAILED
] = "Failed stopping %s.",
3331 [JOB_TIMEOUT
] = "Timed out stopping %s.",