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 if (x
->peer
.vm
.svm_cid
< y
->peer
.vm
.svm_cid
)
501 if (x
->peer
.vm
.svm_cid
> y
->peer
.vm
.svm_cid
)
505 assert_not_reached("Black sheep in the family!");
508 const struct hash_ops peer_address_hash_ops
= {
509 .hash
= peer_address_hash_func
,
510 .compare
= peer_address_compare_func
513 static int socket_load(Unit
*u
) {
514 Socket
*s
= SOCKET(u
);
518 assert(u
->load_state
== UNIT_STUB
);
520 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
524 r
= unit_load_fragment_and_dropin(u
);
528 if (u
->load_state
== UNIT_LOADED
) {
529 /* This is a new unit? Then let's add in some extras */
530 r
= socket_add_extras(s
);
535 return socket_verify(s
);
538 static SocketPeer
*socket_peer_new(void) {
541 p
= new0(SocketPeer
, 1);
550 static SocketPeer
*socket_peer_free(SocketPeer
*p
) {
554 set_remove(p
->socket
->peers_by_address
, p
);
559 DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer
, socket_peer
, socket_peer_free
);
561 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
562 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
563 SocketPeer sa
= {}, *i
;
564 socklen_t salen
= sizeof(sa
.peer
);
570 r
= getpeername(fd
, &sa
.peer
.sa
, &salen
);
572 return log_error_errno(errno
, "getpeername failed: %m");
574 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
, AF_VSOCK
)) {
579 i
= set_get(s
->peers_by_address
, &sa
);
581 *p
= socket_peer_ref(i
);
585 remote
= socket_peer_new();
589 remote
->peer
= sa
.peer
;
590 remote
->peer_salen
= salen
;
592 r
= set_put(s
->peers_by_address
, remote
);
598 *p
= TAKE_PTR(remote
);
603 _const_
static const char* listen_lookup(int family
, int type
) {
605 if (family
== AF_NETLINK
)
606 return "ListenNetlink";
608 if (type
== SOCK_STREAM
)
609 return "ListenStream";
610 else if (type
== SOCK_DGRAM
)
611 return "ListenDatagram";
612 else if (type
== SOCK_SEQPACKET
)
613 return "ListenSequentialPacket";
615 assert_not_reached("Unknown socket type");
619 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
620 char time_string
[FORMAT_TIMESPAN_MAX
];
622 Socket
*s
= SOCKET(u
);
624 const char *prefix2
, *str
;
629 prefix
= strempty(prefix
);
630 prefix2
= strjoina(prefix
, "\t");
633 "%sSocket State: %s\n"
635 "%sBindIPv6Only: %s\n"
637 "%sSocketMode: %04o\n"
638 "%sDirectoryMode: %04o\n"
642 "%sTransparent: %s\n"
644 "%sPassCredentials: %s\n"
645 "%sPassSecurity: %s\n"
646 "%sTCPCongestion: %s\n"
647 "%sRemoveOnStop: %s\n"
649 "%sFileDescriptorName: %s\n"
650 "%sSELinuxContextFromNet: %s\n",
651 prefix
, socket_state_to_string(s
->state
),
652 prefix
, socket_result_to_string(s
->result
),
653 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
655 prefix
, s
->socket_mode
,
656 prefix
, s
->directory_mode
,
657 prefix
, yes_no(s
->keep_alive
),
658 prefix
, yes_no(s
->no_delay
),
659 prefix
, yes_no(s
->free_bind
),
660 prefix
, yes_no(s
->transparent
),
661 prefix
, yes_no(s
->broadcast
),
662 prefix
, yes_no(s
->pass_cred
),
663 prefix
, yes_no(s
->pass_sec
),
664 prefix
, strna(s
->tcp_congestion
),
665 prefix
, yes_no(s
->remove_on_stop
),
666 prefix
, yes_no(s
->writable
),
667 prefix
, socket_fdname(s
),
668 prefix
, yes_no(s
->selinux_context_from_net
));
670 if (s
->control_pid
> 0)
672 "%sControl PID: "PID_FMT
"\n",
673 prefix
, s
->control_pid
);
675 if (s
->bind_to_device
)
677 "%sBindToDevice: %s\n",
678 prefix
, s
->bind_to_device
);
683 "%sNConnections: %u\n"
684 "%sMaxConnections: %u\n"
685 "%sMaxConnectionsPerSource: %u\n",
686 prefix
, s
->n_accepted
,
687 prefix
, s
->n_connections
,
688 prefix
, s
->max_connections
,
689 prefix
, s
->max_connections_per_source
);
691 if (s
->priority
>= 0)
694 prefix
, s
->priority
);
696 if (s
->receive_buffer
> 0)
698 "%sReceiveBuffer: %zu\n",
699 prefix
, s
->receive_buffer
);
701 if (s
->send_buffer
> 0)
703 "%sSendBuffer: %zu\n",
704 prefix
, s
->send_buffer
);
716 if (s
->pipe_size
> 0)
719 prefix
, s
->pipe_size
);
726 if (s
->mq_maxmsg
> 0)
728 "%sMessageQueueMaxMessages: %li\n",
729 prefix
, s
->mq_maxmsg
);
731 if (s
->mq_msgsize
> 0)
733 "%sMessageQueueMessageSize: %li\n",
734 prefix
, s
->mq_msgsize
);
739 prefix
, yes_no(s
->reuse_port
));
743 "%sSmackLabel: %s\n",
748 "%sSmackLabelIPIn: %s\n",
749 prefix
, s
->smack_ip_in
);
753 "%sSmackLabelIPOut: %s\n",
754 prefix
, s
->smack_ip_out
);
756 if (!isempty(s
->user
) || !isempty(s
->group
))
759 "%sSocketGroup: %s\n",
760 prefix
, strna(s
->user
),
761 prefix
, strna(s
->group
));
763 if (s
->keep_alive_time
> 0)
765 "%sKeepAliveTimeSec: %s\n",
766 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
768 if (s
->keep_alive_interval
> 0)
770 "%sKeepAliveIntervalSec: %s\n",
771 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
773 if (s
->keep_alive_cnt
> 0)
775 "%sKeepAliveProbes: %u\n",
776 prefix
, s
->keep_alive_cnt
);
778 if (s
->defer_accept
> 0)
780 "%sDeferAcceptSec: %s\n",
781 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
783 LIST_FOREACH(port
, p
, s
->ports
) {
786 case SOCKET_SOCKET
: {
787 _cleanup_free_
char *k
= NULL
;
791 r
= socket_address_print(&p
->address
, &k
);
797 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
801 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
803 case SOCKET_USB_FUNCTION
:
804 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
807 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
810 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
815 "%sTriggerLimitIntervalSec: %s\n"
816 "%sTriggerLimitBurst: %u\n",
817 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
818 prefix
, s
->trigger_limit
.burst
);
820 str
= socket_protocol_to_name(s
->socket_protocol
);
822 fprintf(f
, "%sSocketProtocol: %s\n", prefix
, str
);
824 if (!strv_isempty(s
->symlinks
)) {
827 fprintf(f
, "%sSymlinks:", prefix
);
828 STRV_FOREACH(q
, s
->symlinks
)
829 fprintf(f
, " %s", *q
);
835 "%sTimeoutSec: %s\n",
836 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->timeout_usec
, USEC_PER_SEC
));
838 exec_context_dump(&s
->exec_context
, f
, prefix
);
839 kill_context_dump(&s
->kill_context
, f
, prefix
);
841 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
842 if (!s
->exec_command
[c
])
845 fprintf(f
, "%s-> %s:\n",
846 prefix
, socket_exec_command_to_string(c
));
848 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
851 cgroup_context_dump(&s
->cgroup_context
, f
, prefix
);
854 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
857 union sockaddr_union local
, remote
;
863 if (getsockname(fd
, &local
.sa
, &l
) < 0)
867 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
870 switch (local
.sa
.sa_family
) {
874 a
= be32toh(local
.in
.sin_addr
.s_addr
),
875 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
878 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
880 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
881 be16toh(local
.in
.sin_port
),
882 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
883 be16toh(remote
.in
.sin_port
)) < 0)
890 static const unsigned char ipv4_prefix
[] = {
891 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
894 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
895 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
897 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
898 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
901 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
903 a
[0], a
[1], a
[2], a
[3],
904 be16toh(local
.in6
.sin6_port
),
905 b
[0], b
[1], b
[2], b
[3],
906 be16toh(remote
.in6
.sin6_port
)) < 0)
909 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
914 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
915 be16toh(local
.in6
.sin6_port
),
916 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
917 be16toh(remote
.in6
.sin6_port
)) < 0)
928 k
= getpeercred(fd
, &ucred
);
931 "%u-"PID_FMT
"-"UID_FMT
,
932 nr
, ucred
.pid
, ucred
.uid
) < 0)
934 } else if (k
== -ENODATA
) {
935 /* This handles the case where somebody is
936 * connecting from another pid/uid namespace
937 * (e.g. from outside of our container). */
952 local
.vm
.svm_cid
, local
.vm
.svm_port
,
953 remote
.vm
.svm_cid
, remote
.vm
.svm_port
) < 0)
959 assert_not_reached("Unhandled socket type.");
966 static void socket_close_fds(Socket
*s
) {
972 LIST_FOREACH(port
, p
, s
->ports
) {
975 was_open
= p
->fd
>= 0;
977 p
->event_source
= sd_event_source_unref(p
->event_source
);
978 p
->fd
= safe_close(p
->fd
);
979 socket_cleanup_fd_list(p
);
981 /* One little note: we should normally not delete any sockets in the file system here! After all some
982 * other process we spawned might still have a reference of this fd and wants to continue to use
983 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
984 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
985 * anyway, but only then. */
987 if (!was_open
|| !s
->remove_on_stop
)
993 (void) unlink(p
->path
);
997 (void) mq_unlink(p
->path
);
1001 (void) socket_address_unlink(&p
->address
);
1009 if (s
->remove_on_stop
)
1010 STRV_FOREACH(i
, s
->symlinks
)
1014 static void socket_apply_socket_options(Socket
*s
, int fd
) {
1020 if (s
->keep_alive
) {
1022 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &one
, sizeof(one
)) < 0)
1023 log_unit_warning_errno(UNIT(s
), errno
, "SO_KEEPALIVE failed: %m");
1026 if (s
->keep_alive_time
> 0) {
1027 int value
= s
->keep_alive_time
/ USEC_PER_SEC
;
1028 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &value
, sizeof(value
)) < 0)
1029 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPIDLE failed: %m");
1032 if (s
->keep_alive_interval
> 0) {
1033 int value
= s
->keep_alive_interval
/ USEC_PER_SEC
;
1034 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &value
, sizeof(value
)) < 0)
1035 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPINTVL failed: %m");
1038 if (s
->keep_alive_cnt
> 0) {
1039 int value
= s
->keep_alive_cnt
;
1040 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPCNT
, &value
, sizeof(value
)) < 0)
1041 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPCNT failed: %m");
1044 if (s
->defer_accept
> 0) {
1045 int value
= s
->defer_accept
/ USEC_PER_SEC
;
1046 if (setsockopt(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, &value
, sizeof(value
)) < 0)
1047 log_unit_warning_errno(UNIT(s
), errno
, "TCP_DEFER_ACCEPT failed: %m");
1053 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1054 if (setsockopt(fd
, SOL_SCTP
, SCTP_NODELAY
, &one
, sizeof(one
)) < 0)
1055 log_unit_warning_errno(UNIT(s
), errno
, "SCTP_NODELAY failed: %m");
1057 if (setsockopt(fd
, SOL_TCP
, TCP_NODELAY
, &one
, sizeof(one
)) < 0)
1058 log_unit_warning_errno(UNIT(s
), errno
, "TCP_NODELAY failed: %m");
1064 if (setsockopt(fd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof(one
)) < 0)
1065 log_unit_warning_errno(UNIT(s
), errno
, "SO_BROADCAST failed: %m");
1070 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
1071 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSCRED failed: %m");
1076 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
)) < 0)
1077 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSSEC failed: %m");
1080 if (s
->priority
>= 0)
1081 if (setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &s
->priority
, sizeof(s
->priority
)) < 0)
1082 log_unit_warning_errno(UNIT(s
), errno
, "SO_PRIORITY failed: %m");
1084 if (s
->receive_buffer
> 0) {
1085 int value
= (int) s
->receive_buffer
;
1087 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1088 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
1089 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
1090 log_unit_warning_errno(UNIT(s
), errno
, "SO_RCVBUF failed: %m");
1093 if (s
->send_buffer
> 0) {
1094 int value
= (int) s
->send_buffer
;
1095 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
1096 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
1097 log_unit_warning_errno(UNIT(s
), errno
, "SO_SNDBUF failed: %m");
1101 if (setsockopt(fd
, SOL_SOCKET
, SO_MARK
, &s
->mark
, sizeof(s
->mark
)) < 0)
1102 log_unit_warning_errno(UNIT(s
), errno
, "SO_MARK failed: %m");
1105 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, &s
->ip_tos
, sizeof(s
->ip_tos
)) < 0)
1106 log_unit_warning_errno(UNIT(s
), errno
, "IP_TOS failed: %m");
1108 if (s
->ip_ttl
>= 0) {
1111 r
= setsockopt(fd
, IPPROTO_IP
, IP_TTL
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1113 if (socket_ipv6_is_supported())
1114 x
= setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1117 errno
= EAFNOSUPPORT
;
1121 log_unit_warning_errno(UNIT(s
), errno
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1124 if (s
->tcp_congestion
)
1125 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1126 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1128 if (s
->smack_ip_in
) {
1129 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1131 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1134 if (s
->smack_ip_out
) {
1135 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1137 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1141 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1147 if (s
->pipe_size
> 0)
1148 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1149 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1152 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1154 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1158 static int fifo_address_create(
1160 mode_t directory_mode
,
1161 mode_t socket_mode
) {
1163 _cleanup_close_
int fd
= -1;
1170 (void) mkdir_parents_label(path
, directory_mode
);
1172 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1176 /* Enforce the right access mode for the fifo */
1177 old_mask
= umask(~socket_mode
);
1179 /* Include the original umask in our mask */
1180 (void) umask(~socket_mode
| old_mask
);
1182 r
= mkfifo(path
, socket_mode
);
1183 (void) umask(old_mask
);
1185 if (r
< 0 && errno
!= EEXIST
) {
1190 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1196 mac_selinux_create_file_clear();
1198 if (fstat(fd
, &st
) < 0) {
1203 if (!S_ISFIFO(st
.st_mode
) ||
1204 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1205 st
.st_uid
!= getuid() ||
1206 st
.st_gid
!= getgid()) {
1214 mac_selinux_create_file_clear();
1218 static int special_address_create(const char *path
, bool writable
) {
1219 _cleanup_close_
int fd
= -1;
1224 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1228 if (fstat(fd
, &st
) < 0)
1231 /* Check whether this is a /proc, /sys or /dev file or char device */
1232 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1238 static int usbffs_address_create(const char *path
) {
1239 _cleanup_close_
int fd
= -1;
1244 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1248 if (fstat(fd
, &st
) < 0)
1251 /* Check whether this is a regular file (ffs endpoint) */
1252 if (!S_ISREG(st
.st_mode
))
1258 static int mq_address_create(
1264 _cleanup_close_
int fd
= -1;
1267 struct mq_attr _attr
, *attr
= NULL
;
1271 if (maxmsg
> 0 && msgsize
> 0) {
1272 _attr
= (struct mq_attr
) {
1273 .mq_flags
= O_NONBLOCK
,
1274 .mq_maxmsg
= maxmsg
,
1275 .mq_msgsize
= msgsize
,
1280 /* Enforce the right access mode for the mq */
1281 old_mask
= umask(~mq_mode
);
1283 /* Include the original umask in our mask */
1284 (void) umask(~mq_mode
| old_mask
);
1285 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1286 (void) umask(old_mask
);
1291 if (fstat(fd
, &st
) < 0)
1294 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1295 st
.st_uid
!= getuid() ||
1296 st
.st_gid
!= getgid())
1302 static int socket_symlink(Socket
*s
) {
1309 p
= socket_find_symlink_target(s
);
1313 STRV_FOREACH(i
, s
->symlinks
) {
1314 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1316 r
= symlink_idempotent(p
, *i
, false);
1318 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1319 /* If there's already something where we want to create the symlink, and the destructive
1320 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1323 if (unlink(*i
) >= 0)
1324 r
= symlink_idempotent(p
, *i
, false);
1328 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s → %s, ignoring: %m", p
, *i
);
1334 static int usbffs_write_descs(int fd
, Service
*s
) {
1337 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1340 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1344 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1347 static int usbffs_select_ep(const struct dirent
*d
) {
1348 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1351 static int usbffs_dispatch_eps(SocketPort
*p
) {
1352 _cleanup_free_
struct dirent
**ent
= NULL
;
1356 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1361 p
->auxiliary_fds
= new(int, n
);
1362 if (!p
->auxiliary_fds
) {
1367 p
->n_auxiliary_fds
= n
;
1370 for (i
= 0; i
< n
; ++i
) {
1371 _cleanup_free_
char *ep
= NULL
;
1373 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1379 path_simplify(ep
, false);
1381 r
= usbffs_address_create(ep
);
1385 p
->auxiliary_fds
[k
++] = r
;
1392 close_many(p
->auxiliary_fds
, k
);
1393 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1394 p
->n_auxiliary_fds
= 0;
1397 for (i
= 0; i
< n
; ++i
)
1403 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1406 _cleanup_free_
char *path
= NULL
;
1412 if (s
->selinux_context_from_net
) {
1413 /* If this is requested, get label from the network label */
1415 r
= mac_selinux_get_our_label(ret
);
1416 if (r
== -EOPNOTSUPP
)
1420 /* Otherwise, get it from the executable we are about to start */
1421 r
= socket_instantiate_service(s
);
1425 if (!UNIT_ISSET(s
->service
))
1428 service
= SERVICE(UNIT_DEREF(s
->service
));
1429 c
= service
->exec_command
[SERVICE_EXEC_START
];
1433 r
= chase_symlinks(c
->path
, service
->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
);
1437 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1438 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1449 static int socket_address_listen_do(
1451 const SocketAddress
*address
,
1452 const char *label
) {
1457 return socket_address_listen(
1459 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1471 static int socket_address_listen_in_cgroup(
1473 const SocketAddress
*address
,
1474 const char *label
) {
1476 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1483 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1484 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1485 * unit's cgroup for the purpose of BPF filtering and such. */
1487 if (!IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
1488 goto shortcut
; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1490 r
= bpf_firewall_supported();
1493 if (r
== BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1496 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1497 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1499 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1501 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1505 pair
[0] = safe_close(pair
[0]);
1507 fd
= socket_address_listen_do(s
, address
, label
);
1509 log_unit_error_errno(UNIT(s
), fd
, "Failed to create listening socket: %m");
1510 _exit(EXIT_FAILURE
);
1513 r
= send_one_fd(pair
[1], fd
, 0);
1515 log_unit_error_errno(UNIT(s
), r
, "Failed to send listening socket to parent: %m");
1516 _exit(EXIT_FAILURE
);
1519 _exit(EXIT_SUCCESS
);
1522 pair
[1] = safe_close(pair
[1]);
1523 fd
= receive_one_fd(pair
[0], 0);
1525 /* We synchronously wait for the helper, as it shouldn't be slow */
1526 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1533 return log_unit_error_errno(UNIT(s
), fd
, "Failed to receive listening socket: %m");
1538 fd
= socket_address_listen_do(s
, address
, label
);
1540 return log_error_errno(fd
, "Failed to create listening socket: %m");
1545 static int socket_open_fds(Socket
*s
) {
1546 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1547 bool know_label
= false;
1553 LIST_FOREACH(port
, p
, s
->ports
) {
1563 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1564 * we need this and remember it for the rest. */
1566 r
= socket_determine_selinux_label(s
, &label
);
1573 /* Apply the socket protocol */
1574 switch (p
->address
.type
) {
1577 case SOCK_SEQPACKET
:
1578 if (s
->socket_protocol
== IPPROTO_SCTP
)
1579 p
->address
.protocol
= s
->socket_protocol
;
1583 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1584 p
->address
.protocol
= s
->socket_protocol
;
1588 r
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1593 socket_apply_socket_options(s
, p
->fd
);
1597 case SOCKET_SPECIAL
:
1599 p
->fd
= special_address_create(p
->path
, s
->writable
);
1608 p
->fd
= fifo_address_create(
1617 socket_apply_fifo_options(s
, p
->fd
);
1623 p
->fd
= mq_address_create(
1634 case SOCKET_USB_FUNCTION
: {
1635 _cleanup_free_
char *ep
= NULL
;
1637 ep
= path_make_absolute("ep0", p
->path
);
1639 p
->fd
= usbffs_address_create(ep
);
1645 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1649 r
= usbffs_dispatch_eps(p
);
1656 assert_not_reached("Unknown port type");
1663 socket_close_fds(s
);
1667 static void socket_unwatch_fds(Socket
*s
) {
1673 LIST_FOREACH(port
, p
, s
->ports
) {
1677 if (!p
->event_source
)
1680 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1682 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1686 static int socket_watch_fds(Socket
*s
) {
1692 LIST_FOREACH(port
, p
, s
->ports
) {
1696 if (p
->event_source
) {
1697 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1701 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1705 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1712 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1713 socket_unwatch_fds(s
);
1723 static int socket_check_open(Socket
*s
) {
1724 bool have_open
= false, have_closed
= false;
1729 LIST_FOREACH(port
, p
, s
->ports
) {
1735 if (have_open
&& have_closed
)
1736 return SOCKET_OPEN_SOME
;
1740 return SOCKET_OPEN_ALL
;
1742 return SOCKET_OPEN_NONE
;
1745 static void socket_set_state(Socket
*s
, SocketState state
) {
1746 SocketState old_state
;
1749 old_state
= s
->state
;
1757 SOCKET_STOP_PRE_SIGTERM
,
1758 SOCKET_STOP_PRE_SIGKILL
,
1760 SOCKET_FINAL_SIGTERM
,
1761 SOCKET_FINAL_SIGKILL
)) {
1763 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1764 socket_unwatch_control_pid(s
);
1765 s
->control_command
= NULL
;
1766 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1769 if (state
!= SOCKET_LISTENING
)
1770 socket_unwatch_fds(s
);
1778 SOCKET_STOP_PRE_SIGTERM
,
1779 SOCKET_STOP_PRE_SIGKILL
))
1780 socket_close_fds(s
);
1782 if (state
!= old_state
)
1783 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1785 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
1788 static int socket_coldplug(Unit
*u
) {
1789 Socket
*s
= SOCKET(u
);
1793 assert(s
->state
== SOCKET_DEAD
);
1795 if (s
->deserialized_state
== s
->state
)
1798 if (s
->control_pid
> 0 &&
1799 pid_is_unwaited(s
->control_pid
) &&
1800 IN_SET(s
->deserialized_state
,
1805 SOCKET_STOP_PRE_SIGTERM
,
1806 SOCKET_STOP_PRE_SIGKILL
,
1808 SOCKET_FINAL_SIGTERM
,
1809 SOCKET_FINAL_SIGKILL
)) {
1811 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1815 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1820 if (IN_SET(s
->deserialized_state
,
1826 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1827 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1828 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1829 * and if there's a mismatch, warn loudly. */
1831 r
= socket_check_open(s
);
1832 if (r
== SOCKET_OPEN_NONE
)
1833 log_unit_warning(UNIT(s
),
1834 "Socket unit configuration has changed while unit has been running, "
1835 "no open socket file descriptor left. "
1836 "The socket unit is not functional until restarted.");
1837 else if (r
== SOCKET_OPEN_SOME
)
1838 log_unit_warning(UNIT(s
),
1839 "Socket unit configuration has changed while unit has been running, "
1840 "and some socket file descriptors have not been opened yet. "
1841 "The socket unit is not fully functional until restarted.");
1844 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1845 r
= socket_watch_fds(s
);
1850 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
)) {
1851 (void) unit_setup_dynamic_creds(u
);
1852 (void) unit_setup_exec_runtime(u
);
1855 socket_set_state(s
, s
->deserialized_state
);
1859 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1861 ExecParameters exec_params
= {
1862 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1875 r
= unit_prepare_exec(UNIT(s
));
1879 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1883 unit_set_exec_params(UNIT(s
), &exec_params
);
1885 r
= exec_spawn(UNIT(s
),
1895 r
= unit_watch_pid(UNIT(s
), pid
);
1897 /* FIXME: we need to do something here */
1905 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1909 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1913 /* We have to resolve the user names out-of-process, hence
1914 * let's fork here. It's messy, but well, what can we do? */
1916 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1920 uid_t uid
= UID_INVALID
;
1921 gid_t gid
= GID_INVALID
;
1926 if (!isempty(s
->user
)) {
1927 const char *user
= s
->user
;
1929 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1931 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1936 if (!isempty(s
->group
)) {
1937 const char *group
= s
->group
;
1939 r
= get_group_creds(&group
, &gid
, 0);
1941 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1946 LIST_FOREACH(port
, p
, s
->ports
) {
1947 const char *path
= NULL
;
1949 if (p
->type
== SOCKET_SOCKET
)
1950 path
= socket_address_get_path(&p
->address
);
1951 else if (p
->type
== SOCKET_FIFO
)
1957 if (chown(path
, uid
, gid
) < 0) {
1958 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1963 _exit(EXIT_SUCCESS
);
1966 r
= unit_watch_pid(UNIT(s
), pid
);
1974 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1978 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1981 if (s
->result
== SOCKET_SUCCESS
)
1984 if (s
->result
!= SOCKET_SUCCESS
)
1985 log_unit_warning(UNIT(s
), "Failed with result '%s'.", socket_result_to_string(s
->result
));
1987 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1989 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
1991 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
1993 unit_unref_uid_gid(UNIT(s
), true);
1995 dynamic_creds_destroy(&s
->dynamic_creds
);
1998 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
2000 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2004 if (s
->result
== SOCKET_SUCCESS
)
2007 socket_unwatch_control_pid(s
);
2008 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2009 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2011 if (s
->control_command
) {
2012 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2016 socket_set_state(s
, SOCKET_STOP_POST
);
2018 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2023 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2024 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2027 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2032 if (s
->result
== SOCKET_SUCCESS
)
2035 r
= unit_kill_context(
2038 !IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FINAL_SIGTERM
) ?
2039 KILL_KILL
: KILL_TERMINATE
,
2047 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2051 socket_set_state(s
, state
);
2052 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2053 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2054 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2055 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2056 else if (state
== SOCKET_FINAL_SIGTERM
)
2057 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2059 socket_enter_dead(s
, SOCKET_SUCCESS
);
2064 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2066 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2067 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2069 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2072 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2076 if (s
->result
== SOCKET_SUCCESS
)
2079 socket_unwatch_control_pid(s
);
2080 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2081 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2083 if (s
->control_command
) {
2084 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2088 socket_set_state(s
, SOCKET_STOP_PRE
);
2090 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2095 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2096 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2099 static void socket_enter_listening(Socket
*s
) {
2103 r
= socket_watch_fds(s
);
2105 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2109 socket_set_state(s
, SOCKET_LISTENING
);
2113 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2116 static void socket_enter_start_post(Socket
*s
) {
2120 socket_unwatch_control_pid(s
);
2121 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2122 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2124 if (s
->control_command
) {
2125 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2127 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2131 socket_set_state(s
, SOCKET_START_POST
);
2133 socket_enter_listening(s
);
2138 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2141 static void socket_enter_start_chown(Socket
*s
) {
2146 r
= socket_open_fds(s
);
2148 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2152 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2154 socket_unwatch_control_pid(s
);
2155 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2156 s
->control_command
= NULL
;
2158 r
= socket_chown(s
, &s
->control_pid
);
2160 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2164 socket_set_state(s
, SOCKET_START_CHOWN
);
2166 socket_enter_start_post(s
);
2171 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2174 static void socket_enter_start_pre(Socket
*s
) {
2178 socket_unwatch_control_pid(s
);
2180 unit_warn_leftover_processes(UNIT(s
));
2182 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2183 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2185 if (s
->control_command
) {
2186 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2188 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2192 socket_set_state(s
, SOCKET_START_PRE
);
2194 socket_enter_start_chown(s
);
2199 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2202 static void flush_ports(Socket
*s
) {
2205 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2208 LIST_FOREACH(port
, p
, s
->ports
) {
2212 (void) flush_accept(p
->fd
);
2213 (void) flush_fd(p
->fd
);
2217 static void socket_enter_running(Socket
*s
, int cfd
) {
2218 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2221 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2226 /* We don't take connections anymore if we are supposed to shut down anyway */
2227 if (unit_stop_pending(UNIT(s
))) {
2229 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2239 if (!ratelimit_below(&s
->trigger_limit
)) {
2240 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2241 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2246 bool pending
= false;
2251 /* If there's already a start pending don't bother to
2253 HASHMAP_FOREACH_KEY(v
, other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2254 if (unit_active_or_pending(other
)) {
2260 if (!UNIT_ISSET(s
->service
)) {
2261 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2266 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2271 socket_set_state(s
, SOCKET_RUNNING
);
2273 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2274 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2277 if (s
->n_connections
>= s
->max_connections
) {
2278 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2283 if (s
->max_connections_per_source
> 0) {
2284 r
= socket_acquire_peer(s
, cfd
, &p
);
2287 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2288 _cleanup_free_
char *t
= NULL
;
2290 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2292 log_unit_warning(UNIT(s
),
2293 "Too many incoming connections (%u) from source %s, dropping connection.",
2294 p
->n_ref
, strnull(t
));
2299 r
= socket_instantiate_service(s
);
2303 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2308 /* ENOTCONN is legitimate if TCP RST was received.
2309 * This connection is over, but the socket unit lives on. */
2310 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2314 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2318 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2322 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2326 service
= SERVICE(UNIT_DEREF(s
->service
));
2327 unit_ref_unset(&s
->service
);
2330 unit_choose_id(UNIT(service
), name
);
2332 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2336 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2339 service
->peer
= TAKE_PTR(p
); /* Pass ownership of the peer reference */
2341 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2343 /* We failed to activate the new service, but it still exists. Let's make sure the service
2344 * closes and forgets the connection fd again, immediately. */
2345 service_close_socket_fd(service
);
2349 /* Notify clients about changed counters */
2350 unit_add_to_dbus_queue(UNIT(s
));
2361 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2362 cfd
>= 0 ? "template" : "non-template",
2363 bus_error_message(&error
, r
));
2365 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2369 static void socket_run_next(Socket
*s
) {
2373 assert(s
->control_command
);
2374 assert(s
->control_command
->command_next
);
2376 socket_unwatch_control_pid(s
);
2378 s
->control_command
= s
->control_command
->command_next
;
2380 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2387 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2389 if (s
->state
== SOCKET_START_POST
)
2390 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2391 else if (s
->state
== SOCKET_STOP_POST
)
2392 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2394 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2397 static int socket_start(Unit
*u
) {
2398 Socket
*s
= SOCKET(u
);
2403 /* We cannot fulfill this request right now, try again later
2405 if (IN_SET(s
->state
,
2407 SOCKET_STOP_PRE_SIGKILL
,
2408 SOCKET_STOP_PRE_SIGTERM
,
2410 SOCKET_FINAL_SIGTERM
,
2411 SOCKET_FINAL_SIGKILL
))
2414 /* Already on it! */
2415 if (IN_SET(s
->state
,
2421 /* Cannot run this without the service being around */
2422 if (UNIT_ISSET(s
->service
)) {
2425 service
= SERVICE(UNIT_DEREF(s
->service
));
2427 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2428 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2432 /* If the service is already active we cannot start the
2434 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
2435 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2440 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2442 r
= unit_start_limit_test(u
);
2444 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2448 r
= unit_acquire_invocation_id(u
);
2452 s
->result
= SOCKET_SUCCESS
;
2453 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2455 u
->reset_accounting
= true;
2457 socket_enter_start_pre(s
);
2461 static int socket_stop(Unit
*u
) {
2462 Socket
*s
= SOCKET(u
);
2467 if (IN_SET(s
->state
,
2469 SOCKET_STOP_PRE_SIGTERM
,
2470 SOCKET_STOP_PRE_SIGKILL
,
2472 SOCKET_FINAL_SIGTERM
,
2473 SOCKET_FINAL_SIGKILL
))
2476 /* If there's already something running we go directly into
2478 if (IN_SET(s
->state
,
2481 SOCKET_START_POST
)) {
2482 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2486 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2488 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2492 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2493 Socket
*s
= SOCKET(u
);
2501 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2502 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2503 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2504 unit_serialize_item_format(u
, f
, "n-refused", "%u", s
->n_refused
);
2506 if (s
->control_pid
> 0)
2507 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2509 if (s
->control_command_id
>= 0)
2510 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2512 LIST_FOREACH(port
, p
, s
->ports
) {
2518 copy
= fdset_put_dup(fds
, p
->fd
);
2522 if (p
->type
== SOCKET_SOCKET
) {
2523 _cleanup_free_
char *t
= NULL
;
2525 r
= socket_address_print(&p
->address
, &t
);
2529 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2530 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2532 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2534 } else if (p
->type
== SOCKET_SPECIAL
)
2535 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2536 else if (p
->type
== SOCKET_MQUEUE
)
2537 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2538 else if (p
->type
== SOCKET_USB_FUNCTION
)
2539 unit_serialize_item_format(u
, f
, "ffs", "%i %s", copy
, p
->path
);
2541 assert(p
->type
== SOCKET_FIFO
);
2542 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2549 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2551 p
->fd
= fdset_remove(fds
, fd
);
2554 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2555 Socket
*s
= SOCKET(u
);
2561 if (streq(key
, "state")) {
2564 state
= socket_state_from_string(value
);
2566 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2568 s
->deserialized_state
= state
;
2569 } else if (streq(key
, "result")) {
2572 f
= socket_result_from_string(value
);
2574 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2575 else if (f
!= SOCKET_SUCCESS
)
2578 } else if (streq(key
, "n-accepted")) {
2581 if (safe_atou(value
, &k
) < 0)
2582 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2585 } else if (streq(key
, "n-refused")) {
2588 if (safe_atou(value
, &k
) < 0)
2589 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2592 } else if (streq(key
, "control-pid")) {
2595 if (parse_pid(value
, &pid
) < 0)
2596 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2598 s
->control_pid
= pid
;
2599 } else if (streq(key
, "control-command")) {
2600 SocketExecCommand id
;
2602 id
= socket_exec_command_from_string(value
);
2604 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2606 s
->control_command_id
= id
;
2607 s
->control_command
= s
->exec_command
[id
];
2609 } else if (streq(key
, "fifo")) {
2613 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2614 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2616 LIST_FOREACH(port
, p
, s
->ports
)
2617 if (p
->type
== SOCKET_FIFO
&&
2618 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2619 socket_port_take_fd(p
, fds
, fd
);
2623 } else if (streq(key
, "special")) {
2627 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2628 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2630 LIST_FOREACH(port
, p
, s
->ports
)
2631 if (p
->type
== SOCKET_SPECIAL
&&
2632 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2633 socket_port_take_fd(p
, fds
, fd
);
2637 } else if (streq(key
, "mqueue")) {
2641 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2642 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2644 LIST_FOREACH(port
, p
, s
->ports
)
2645 if (p
->type
== SOCKET_MQUEUE
&&
2646 streq(p
->path
, value
+skip
)) {
2647 socket_port_take_fd(p
, fds
, fd
);
2651 } else if (streq(key
, "socket")) {
2652 int fd
, type
, skip
= 0;
2655 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2656 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2658 LIST_FOREACH(port
, p
, s
->ports
)
2659 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2660 socket_port_take_fd(p
, fds
, fd
);
2664 } else if (streq(key
, "netlink")) {
2668 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2669 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2671 LIST_FOREACH(port
, p
, s
->ports
)
2672 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2673 socket_port_take_fd(p
, fds
, fd
);
2677 } else if (streq(key
, "ffs")) {
2681 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2682 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2684 LIST_FOREACH(port
, p
, s
->ports
)
2685 if (p
->type
== SOCKET_USB_FUNCTION
&&
2686 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2687 socket_port_take_fd(p
, fds
, fd
);
2692 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2697 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2698 Socket
*s
= SOCKET(u
);
2703 LIST_FOREACH(port
, p
, s
->ports
) {
2707 if (p
->type
!= SOCKET_SOCKET
)
2713 FDSET_FOREACH(fd
, fds
, i
) {
2714 if (socket_address_matches_fd(&p
->address
, fd
)) {
2715 p
->fd
= fdset_remove(fds
, fd
);
2716 s
->deserialized_state
= SOCKET_LISTENING
;
2723 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2726 return state_translation_table
[SOCKET(u
)->state
];
2729 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2732 return socket_state_to_string(SOCKET(u
)->state
);
2735 const char* socket_port_type_to_string(SocketPort
*p
) {
2743 switch (p
->address
.type
) {
2751 case SOCK_SEQPACKET
:
2752 return "SequentialPacket";
2755 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2763 case SOCKET_SPECIAL
:
2767 return "MessageQueue";
2772 case SOCKET_USB_FUNCTION
:
2773 return "USBFunction";
2780 SocketType
socket_port_type_from_string(const char *s
) {
2783 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2784 return SOCKET_SOCKET
;
2785 else if (streq(s
, "Special"))
2786 return SOCKET_SPECIAL
;
2787 else if (streq(s
, "MessageQueue"))
2788 return SOCKET_MQUEUE
;
2789 else if (streq(s
, "FIFO"))
2791 else if (streq(s
, "USBFunction"))
2792 return SOCKET_USB_FUNCTION
;
2794 return _SOCKET_TYPE_INVALID
;
2797 _pure_
static bool socket_may_gc(Unit
*u
) {
2798 Socket
*s
= SOCKET(u
);
2802 return s
->n_connections
== 0;
2805 static int socket_accept_do(Socket
*s
, int fd
) {
2812 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2826 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2827 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
2835 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2836 * connection socket is also properly associated with the cgroup. */
2838 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2841 r
= bpf_firewall_supported();
2844 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2847 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2848 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2850 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2852 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2856 pair
[0] = safe_close(pair
[0]);
2858 cfd
= socket_accept_do(s
, fd
);
2860 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2861 _exit(EXIT_FAILURE
);
2864 r
= send_one_fd(pair
[1], cfd
, 0);
2866 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
2867 _exit(EXIT_FAILURE
);
2870 _exit(EXIT_SUCCESS
);
2873 pair
[1] = safe_close(pair
[1]);
2874 cfd
= receive_one_fd(pair
[0], 0);
2876 /* We synchronously wait for the helper, as it shouldn't be slow */
2877 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
2884 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
2889 cfd
= socket_accept_do(s
, fd
);
2891 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2896 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2897 SocketPort
*p
= userdata
;
2903 if (p
->socket
->state
!= SOCKET_LISTENING
)
2906 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2908 if (revents
!= EPOLLIN
) {
2910 if (revents
& EPOLLHUP
)
2911 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.");
2913 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2917 if (p
->socket
->accept
&&
2918 p
->type
== SOCKET_SOCKET
&&
2919 socket_address_can_accept(&p
->address
)) {
2921 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
2925 socket_apply_socket_options(p
->socket
, cfd
);
2928 socket_enter_running(p
->socket
, cfd
);
2932 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2936 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2937 Socket
*s
= SOCKET(u
);
2943 if (pid
!= s
->control_pid
)
2948 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
2950 else if (code
== CLD_EXITED
)
2951 f
= SOCKET_FAILURE_EXIT_CODE
;
2952 else if (code
== CLD_KILLED
)
2953 f
= SOCKET_FAILURE_SIGNAL
;
2954 else if (code
== CLD_DUMPED
)
2955 f
= SOCKET_FAILURE_CORE_DUMP
;
2957 assert_not_reached("Unknown sigchld code");
2959 if (s
->control_command
) {
2960 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2962 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
2966 log_unit_full(u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2967 "Control process exited, code=%s status=%i",
2968 sigchld_code_to_string(code
), status
);
2970 if (s
->result
== SOCKET_SUCCESS
)
2973 if (s
->control_command
&&
2974 s
->control_command
->command_next
&&
2975 f
== SOCKET_SUCCESS
) {
2977 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2980 s
->control_command
= NULL
;
2981 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2983 /* No further commands for this step, so let's figure
2984 * out what to do next */
2986 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2990 case SOCKET_START_PRE
:
2991 if (f
== SOCKET_SUCCESS
)
2992 socket_enter_start_chown(s
);
2994 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
2997 case SOCKET_START_CHOWN
:
2998 if (f
== SOCKET_SUCCESS
)
2999 socket_enter_start_post(s
);
3001 socket_enter_stop_pre(s
, f
);
3004 case SOCKET_START_POST
:
3005 if (f
== SOCKET_SUCCESS
)
3006 socket_enter_listening(s
);
3008 socket_enter_stop_pre(s
, f
);
3011 case SOCKET_STOP_PRE
:
3012 case SOCKET_STOP_PRE_SIGTERM
:
3013 case SOCKET_STOP_PRE_SIGKILL
:
3014 socket_enter_stop_post(s
, f
);
3017 case SOCKET_STOP_POST
:
3018 case SOCKET_FINAL_SIGTERM
:
3019 case SOCKET_FINAL_SIGKILL
:
3020 socket_enter_dead(s
, f
);
3024 assert_not_reached("Uh, control process died at wrong time.");
3028 /* Notify clients about changed exit status */
3029 unit_add_to_dbus_queue(u
);
3032 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3033 Socket
*s
= SOCKET(userdata
);
3036 assert(s
->timer_event_source
== source
);
3040 case SOCKET_START_PRE
:
3041 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3042 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3045 case SOCKET_START_CHOWN
:
3046 case SOCKET_START_POST
:
3047 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3048 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3051 case SOCKET_STOP_PRE
:
3052 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3053 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3056 case SOCKET_STOP_PRE_SIGTERM
:
3057 if (s
->kill_context
.send_sigkill
) {
3058 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3059 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3061 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3062 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3066 case SOCKET_STOP_PRE_SIGKILL
:
3067 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3068 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3071 case SOCKET_STOP_POST
:
3072 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3073 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3076 case SOCKET_FINAL_SIGTERM
:
3077 if (s
->kill_context
.send_sigkill
) {
3078 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3079 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3081 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3082 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3086 case SOCKET_FINAL_SIGKILL
:
3087 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3088 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3092 assert_not_reached("Timeout at wrong time.");
3098 int socket_collect_fds(Socket
*s
, int **fds
) {
3099 size_t k
= 0, n
= 0;
3106 /* Called from the service code for requesting our fds */
3108 LIST_FOREACH(port
, p
, s
->ports
) {
3111 n
+= p
->n_auxiliary_fds
;
3123 LIST_FOREACH(port
, p
, s
->ports
) {
3128 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3129 rfds
[k
++] = p
->auxiliary_fds
[i
];
3138 static void socket_reset_failed(Unit
*u
) {
3139 Socket
*s
= SOCKET(u
);
3143 if (s
->state
== SOCKET_FAILED
)
3144 socket_set_state(s
, SOCKET_DEAD
);
3146 s
->result
= SOCKET_SUCCESS
;
3149 void socket_connection_unref(Socket
*s
) {
3152 /* The service is dead. Yay!
3154 * This is strictly for one-instance-per-connection
3157 assert(s
->n_connections
> 0);
3160 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3163 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3164 Socket
*s
= SOCKET(u
);
3169 /* Filter out invocations with bogus state */
3170 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
3173 /* Don't propagate state changes from the service if we are already down */
3174 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3177 /* We don't care for the service state if we are in Accept=yes mode */
3181 /* Propagate start limit hit state */
3182 if (other
->start_limit_hit
) {
3183 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3187 /* Don't propagate anything if there's still a job queued */
3191 if (IN_SET(SERVICE(other
)->state
,
3192 SERVICE_DEAD
, SERVICE_FAILED
,
3193 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3194 SERVICE_AUTO_RESTART
))
3195 socket_enter_listening(s
);
3197 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3198 socket_set_state(s
, SOCKET_RUNNING
);
3201 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3202 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3205 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3206 Socket
*s
= SOCKET(u
);
3210 if (!s
->timer_event_source
)
3213 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3216 if (t
== USEC_INFINITY
)
3223 char *socket_fdname(Socket
*s
) {
3226 /* Returns the name to use for $LISTEN_NAMES. If the user
3227 * didn't specify anything specifically, use the socket unit's
3228 * name as fallback. */
3230 return s
->fdname
?: UNIT(s
)->id
;
3233 static int socket_control_pid(Unit
*u
) {
3234 Socket
*s
= SOCKET(u
);
3238 return s
->control_pid
;
3241 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3242 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3243 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3244 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3245 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3246 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3249 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3251 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3252 [SOCKET_SUCCESS
] = "success",
3253 [SOCKET_FAILURE_RESOURCES
] = "resources",
3254 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3255 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3256 [SOCKET_FAILURE_SIGNAL
] = "signal",
3257 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3258 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3259 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3260 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3263 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3265 const UnitVTable socket_vtable
= {
3266 .object_size
= sizeof(Socket
),
3267 .exec_context_offset
= offsetof(Socket
, exec_context
),
3268 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3269 .kill_context_offset
= offsetof(Socket
, kill_context
),
3270 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3271 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3277 .private_section
= "Socket",
3279 .can_transient
= true,
3281 .init
= socket_init
,
3282 .done
= socket_done
,
3283 .load
= socket_load
,
3285 .coldplug
= socket_coldplug
,
3287 .dump
= socket_dump
,
3289 .start
= socket_start
,
3290 .stop
= socket_stop
,
3292 .kill
= socket_kill
,
3294 .get_timeout
= socket_get_timeout
,
3296 .serialize
= socket_serialize
,
3297 .deserialize_item
= socket_deserialize_item
,
3298 .distribute_fds
= socket_distribute_fds
,
3300 .active_state
= socket_active_state
,
3301 .sub_state_to_string
= socket_sub_state_to_string
,
3303 .may_gc
= socket_may_gc
,
3305 .sigchld_event
= socket_sigchld_event
,
3307 .trigger_notify
= socket_trigger_notify
,
3309 .reset_failed
= socket_reset_failed
,
3311 .control_pid
= socket_control_pid
,
3313 .bus_vtable
= bus_socket_vtable
,
3314 .bus_set_property
= bus_socket_set_property
,
3315 .bus_commit_properties
= bus_socket_commit_properties
,
3317 .status_message_formats
= {
3318 /*.starting_stopping = {
3319 [0] = "Starting socket %s...",
3320 [1] = "Stopping socket %s...",
3322 .finished_start_job
= {
3323 [JOB_DONE
] = "Listening on %s.",
3324 [JOB_FAILED
] = "Failed to listen on %s.",
3325 [JOB_TIMEOUT
] = "Timed out starting %s.",
3327 .finished_stop_job
= {
3328 [JOB_DONE
] = "Closed %s.",
3329 [JOB_FAILED
] = "Failed stopping %s.",
3330 [JOB_TIMEOUT
] = "Timed out stopping %s.",