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 int value
= s
->keep_alive_time
/ USEC_PER_SEC
;
1024 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &value
, sizeof(value
)) < 0)
1025 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPIDLE failed: %m");
1028 if (s
->keep_alive_interval
> 0) {
1029 int value
= s
->keep_alive_interval
/ USEC_PER_SEC
;
1030 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &value
, sizeof(value
)) < 0)
1031 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPINTVL failed: %m");
1034 if (s
->keep_alive_cnt
> 0) {
1035 int value
= s
->keep_alive_cnt
;
1036 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPCNT
, &value
, sizeof(value
)) < 0)
1037 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPCNT failed: %m");
1040 if (s
->defer_accept
> 0) {
1041 int value
= s
->defer_accept
/ USEC_PER_SEC
;
1042 if (setsockopt(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, &value
, sizeof(value
)) < 0)
1043 log_unit_warning_errno(UNIT(s
), errno
, "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 if (setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &s
->priority
, sizeof(s
->priority
)) < 0)
1078 log_unit_warning_errno(UNIT(s
), errno
, "SO_PRIORITY failed: %m");
1080 if (s
->receive_buffer
> 0) {
1081 int value
= (int) s
->receive_buffer
;
1083 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1084 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
1085 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
1086 log_unit_warning_errno(UNIT(s
), errno
, "SO_RCVBUF failed: %m");
1089 if (s
->send_buffer
> 0) {
1090 int value
= (int) s
->send_buffer
;
1091 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
1092 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
1093 log_unit_warning_errno(UNIT(s
), errno
, "SO_SNDBUF failed: %m");
1097 if (setsockopt(fd
, SOL_SOCKET
, SO_MARK
, &s
->mark
, sizeof(s
->mark
)) < 0)
1098 log_unit_warning_errno(UNIT(s
), errno
, "SO_MARK failed: %m");
1101 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, &s
->ip_tos
, sizeof(s
->ip_tos
)) < 0)
1102 log_unit_warning_errno(UNIT(s
), errno
, "IP_TOS failed: %m");
1104 if (s
->ip_ttl
>= 0) {
1107 r
= setsockopt(fd
, IPPROTO_IP
, IP_TTL
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1109 if (socket_ipv6_is_supported())
1110 x
= setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1113 errno
= EAFNOSUPPORT
;
1117 log_unit_warning_errno(UNIT(s
), errno
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1120 if (s
->tcp_congestion
)
1121 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1122 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1124 if (s
->smack_ip_in
) {
1125 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1127 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1130 if (s
->smack_ip_out
) {
1131 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1133 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1137 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1143 if (s
->pipe_size
> 0)
1144 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1145 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1148 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1150 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1154 static int fifo_address_create(
1156 mode_t directory_mode
,
1157 mode_t socket_mode
) {
1159 _cleanup_close_
int fd
= -1;
1166 (void) mkdir_parents_label(path
, directory_mode
);
1168 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1172 /* Enforce the right access mode for the fifo */
1173 old_mask
= umask(~socket_mode
);
1175 /* Include the original umask in our mask */
1176 (void) umask(~socket_mode
| old_mask
);
1178 r
= mkfifo(path
, socket_mode
);
1179 (void) umask(old_mask
);
1181 if (r
< 0 && errno
!= EEXIST
) {
1186 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1192 mac_selinux_create_file_clear();
1194 if (fstat(fd
, &st
) < 0) {
1199 if (!S_ISFIFO(st
.st_mode
) ||
1200 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1201 st
.st_uid
!= getuid() ||
1202 st
.st_gid
!= getgid()) {
1210 mac_selinux_create_file_clear();
1214 static int special_address_create(const char *path
, bool writable
) {
1215 _cleanup_close_
int fd
= -1;
1220 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1224 if (fstat(fd
, &st
) < 0)
1227 /* Check whether this is a /proc, /sys or /dev file or char device */
1228 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1234 static int usbffs_address_create(const char *path
) {
1235 _cleanup_close_
int fd
= -1;
1240 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1244 if (fstat(fd
, &st
) < 0)
1247 /* Check whether this is a regular file (ffs endpoint) */
1248 if (!S_ISREG(st
.st_mode
))
1254 static int mq_address_create(
1260 _cleanup_close_
int fd
= -1;
1263 struct mq_attr _attr
, *attr
= NULL
;
1267 if (maxmsg
> 0 && msgsize
> 0) {
1268 _attr
= (struct mq_attr
) {
1269 .mq_flags
= O_NONBLOCK
,
1270 .mq_maxmsg
= maxmsg
,
1271 .mq_msgsize
= msgsize
,
1276 /* Enforce the right access mode for the mq */
1277 old_mask
= umask(~mq_mode
);
1279 /* Include the original umask in our mask */
1280 (void) umask(~mq_mode
| old_mask
);
1281 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1282 (void) umask(old_mask
);
1287 if (fstat(fd
, &st
) < 0)
1290 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1291 st
.st_uid
!= getuid() ||
1292 st
.st_gid
!= getgid())
1298 static int socket_symlink(Socket
*s
) {
1305 p
= socket_find_symlink_target(s
);
1309 STRV_FOREACH(i
, s
->symlinks
) {
1310 (void) mkdir_parents_label(*i
, s
->directory_mode
);
1312 r
= symlink_idempotent(p
, *i
, false);
1314 if (r
== -EEXIST
&& s
->remove_on_stop
) {
1315 /* If there's already something where we want to create the symlink, and the destructive
1316 * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1319 if (unlink(*i
) >= 0)
1320 r
= symlink_idempotent(p
, *i
, false);
1324 log_unit_warning_errno(UNIT(s
), r
, "Failed to create symlink %s → %s, ignoring: %m", p
, *i
);
1330 static int usbffs_write_descs(int fd
, Service
*s
) {
1333 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1336 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, 0);
1340 return copy_file_fd(s
->usb_function_strings
, fd
, 0);
1343 static int usbffs_select_ep(const struct dirent
*d
) {
1344 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1347 static int usbffs_dispatch_eps(SocketPort
*p
) {
1348 _cleanup_free_
struct dirent
**ent
= NULL
;
1352 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1357 p
->auxiliary_fds
= new(int, n
);
1358 if (!p
->auxiliary_fds
) {
1363 p
->n_auxiliary_fds
= n
;
1366 for (i
= 0; i
< n
; ++i
) {
1367 _cleanup_free_
char *ep
= NULL
;
1369 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1375 path_simplify(ep
, false);
1377 r
= usbffs_address_create(ep
);
1381 p
->auxiliary_fds
[k
++] = r
;
1388 close_many(p
->auxiliary_fds
, k
);
1389 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1390 p
->n_auxiliary_fds
= 0;
1393 for (i
= 0; i
< n
; ++i
)
1399 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1402 _cleanup_free_
char *path
= NULL
;
1408 if (s
->selinux_context_from_net
) {
1409 /* If this is requested, get label from the network label */
1411 r
= mac_selinux_get_our_label(ret
);
1412 if (r
== -EOPNOTSUPP
)
1416 /* Otherwise, get it from the executable we are about to start */
1417 r
= socket_instantiate_service(s
);
1421 if (!UNIT_ISSET(s
->service
))
1424 service
= SERVICE(UNIT_DEREF(s
->service
));
1425 c
= service
->exec_command
[SERVICE_EXEC_START
];
1429 r
= chase_symlinks(c
->path
, service
->exec_context
.root_directory
, CHASE_PREFIX_ROOT
, &path
);
1433 r
= mac_selinux_get_create_label_from_exe(path
, ret
);
1434 if (IN_SET(r
, -EPERM
, -EOPNOTSUPP
))
1445 static int socket_address_listen_do(
1447 const SocketAddress
*address
,
1448 const char *label
) {
1453 return socket_address_listen(
1455 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1467 static int socket_address_listen_in_cgroup(
1469 const SocketAddress
*address
,
1470 const char *label
) {
1472 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
1479 /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the socket's cgroup
1480 * in which the socket is actually created. This way we ensure the socket is actually properly attached to the
1481 * unit's cgroup for the purpose of BPF filtering and such. */
1483 if (!IN_SET(address
->sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
1484 goto shortcut
; /* BPF filtering only applies to IPv4 + IPv6, shortcut things for other protocols */
1486 r
= bpf_firewall_supported();
1489 if (r
== BPF_FIREWALL_UNSUPPORTED
) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1492 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
1493 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
1495 r
= unit_fork_helper_process(UNIT(s
), "(sd-listen)", &pid
);
1497 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off listener stub process: %m");
1501 pair
[0] = safe_close(pair
[0]);
1503 fd
= socket_address_listen_do(s
, address
, label
);
1505 log_unit_error_errno(UNIT(s
), fd
, "Failed to create listening socket: %m");
1506 _exit(EXIT_FAILURE
);
1509 r
= send_one_fd(pair
[1], fd
, 0);
1511 log_unit_error_errno(UNIT(s
), r
, "Failed to send listening socket to parent: %m");
1512 _exit(EXIT_FAILURE
);
1515 _exit(EXIT_SUCCESS
);
1518 pair
[1] = safe_close(pair
[1]);
1519 fd
= receive_one_fd(pair
[0], 0);
1521 /* We synchronously wait for the helper, as it shouldn't be slow */
1522 r
= wait_for_terminate_and_check("(sd-listen)", pid
, WAIT_LOG_ABNORMAL
);
1529 return log_unit_error_errno(UNIT(s
), fd
, "Failed to receive listening socket: %m");
1534 fd
= socket_address_listen_do(s
, address
, label
);
1536 return log_error_errno(fd
, "Failed to create listening socket: %m");
1541 static int socket_open_fds(Socket
*s
) {
1542 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1543 bool know_label
= false;
1549 LIST_FOREACH(port
, p
, s
->ports
) {
1559 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1560 * we need this and remember it for the rest. */
1562 r
= socket_determine_selinux_label(s
, &label
);
1569 /* Apply the socket protocol */
1570 switch (p
->address
.type
) {
1573 case SOCK_SEQPACKET
:
1574 if (s
->socket_protocol
== IPPROTO_SCTP
)
1575 p
->address
.protocol
= s
->socket_protocol
;
1579 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1580 p
->address
.protocol
= s
->socket_protocol
;
1584 r
= socket_address_listen_in_cgroup(s
, &p
->address
, label
);
1589 socket_apply_socket_options(s
, p
->fd
);
1593 case SOCKET_SPECIAL
:
1595 p
->fd
= special_address_create(p
->path
, s
->writable
);
1604 p
->fd
= fifo_address_create(
1613 socket_apply_fifo_options(s
, p
->fd
);
1619 p
->fd
= mq_address_create(
1630 case SOCKET_USB_FUNCTION
: {
1631 _cleanup_free_
char *ep
= NULL
;
1633 ep
= path_make_absolute("ep0", p
->path
);
1635 p
->fd
= usbffs_address_create(ep
);
1641 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1645 r
= usbffs_dispatch_eps(p
);
1652 assert_not_reached("Unknown port type");
1659 socket_close_fds(s
);
1663 static void socket_unwatch_fds(Socket
*s
) {
1669 LIST_FOREACH(port
, p
, s
->ports
) {
1673 if (!p
->event_source
)
1676 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1678 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1682 static int socket_watch_fds(Socket
*s
) {
1688 LIST_FOREACH(port
, p
, s
->ports
) {
1692 if (p
->event_source
) {
1693 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1697 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1701 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1708 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1709 socket_unwatch_fds(s
);
1719 static int socket_check_open(Socket
*s
) {
1720 bool have_open
= false, have_closed
= false;
1725 LIST_FOREACH(port
, p
, s
->ports
) {
1731 if (have_open
&& have_closed
)
1732 return SOCKET_OPEN_SOME
;
1736 return SOCKET_OPEN_ALL
;
1738 return SOCKET_OPEN_NONE
;
1741 static void socket_set_state(Socket
*s
, SocketState state
) {
1742 SocketState old_state
;
1745 old_state
= s
->state
;
1753 SOCKET_STOP_PRE_SIGTERM
,
1754 SOCKET_STOP_PRE_SIGKILL
,
1756 SOCKET_FINAL_SIGTERM
,
1757 SOCKET_FINAL_SIGKILL
)) {
1759 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1760 socket_unwatch_control_pid(s
);
1761 s
->control_command
= NULL
;
1762 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1765 if (state
!= SOCKET_LISTENING
)
1766 socket_unwatch_fds(s
);
1774 SOCKET_STOP_PRE_SIGTERM
,
1775 SOCKET_STOP_PRE_SIGKILL
))
1776 socket_close_fds(s
);
1778 if (state
!= old_state
)
1779 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1781 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], 0);
1784 static int socket_coldplug(Unit
*u
) {
1785 Socket
*s
= SOCKET(u
);
1789 assert(s
->state
== SOCKET_DEAD
);
1791 if (s
->deserialized_state
== s
->state
)
1794 if (s
->control_pid
> 0 &&
1795 pid_is_unwaited(s
->control_pid
) &&
1796 IN_SET(s
->deserialized_state
,
1801 SOCKET_STOP_PRE_SIGTERM
,
1802 SOCKET_STOP_PRE_SIGKILL
,
1804 SOCKET_FINAL_SIGTERM
,
1805 SOCKET_FINAL_SIGKILL
)) {
1807 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1811 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1816 if (IN_SET(s
->deserialized_state
,
1822 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1823 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1824 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1825 * and if there's a mismatch, warn loudly. */
1827 r
= socket_check_open(s
);
1828 if (r
== SOCKET_OPEN_NONE
)
1829 log_unit_warning(UNIT(s
),
1830 "Socket unit configuration has changed while unit has been running, "
1831 "no open socket file descriptor left. "
1832 "The socket unit is not functional until restarted.");
1833 else if (r
== SOCKET_OPEN_SOME
)
1834 log_unit_warning(UNIT(s
),
1835 "Socket unit configuration has changed while unit has been running, "
1836 "and some socket file descriptors have not been opened yet. "
1837 "The socket unit is not fully functional until restarted.");
1840 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1841 r
= socket_watch_fds(s
);
1846 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
)) {
1847 (void) unit_setup_dynamic_creds(u
);
1848 (void) unit_setup_exec_runtime(u
);
1851 socket_set_state(s
, s
->deserialized_state
);
1855 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1857 ExecParameters exec_params
= {
1858 .flags
= EXEC_APPLY_SANDBOXING
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1871 r
= unit_prepare_exec(UNIT(s
));
1875 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1879 unit_set_exec_params(UNIT(s
), &exec_params
);
1881 r
= exec_spawn(UNIT(s
),
1891 r
= unit_watch_pid(UNIT(s
), pid
);
1893 /* FIXME: we need to do something here */
1901 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1905 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1909 /* We have to resolve the user names out-of-process, hence
1910 * let's fork here. It's messy, but well, what can we do? */
1912 r
= unit_fork_helper_process(UNIT(s
), "(sd-chown)", &pid
);
1916 uid_t uid
= UID_INVALID
;
1917 gid_t gid
= GID_INVALID
;
1922 if (!isempty(s
->user
)) {
1923 const char *user
= s
->user
;
1925 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
, 0);
1927 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve user %s: %m", user
);
1932 if (!isempty(s
->group
)) {
1933 const char *group
= s
->group
;
1935 r
= get_group_creds(&group
, &gid
, 0);
1937 log_unit_error_errno(UNIT(s
), r
, "Failed to resolve group %s: %m", group
);
1942 LIST_FOREACH(port
, p
, s
->ports
) {
1943 const char *path
= NULL
;
1945 if (p
->type
== SOCKET_SOCKET
)
1946 path
= socket_address_get_path(&p
->address
);
1947 else if (p
->type
== SOCKET_FIFO
)
1953 if (chown(path
, uid
, gid
) < 0) {
1954 log_unit_error_errno(UNIT(s
), errno
, "Failed to chown(): %m");
1959 _exit(EXIT_SUCCESS
);
1962 r
= unit_watch_pid(UNIT(s
), pid
);
1970 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1974 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1977 if (s
->result
== SOCKET_SUCCESS
)
1980 if (s
->result
!= SOCKET_SUCCESS
)
1981 log_unit_warning(UNIT(s
), "Failed with result '%s'.", socket_result_to_string(s
->result
));
1983 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1985 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
, true);
1987 exec_context_destroy_runtime_directory(&s
->exec_context
, UNIT(s
)->manager
->prefix
[EXEC_DIRECTORY_RUNTIME
]);
1989 unit_unref_uid_gid(UNIT(s
), true);
1991 dynamic_creds_destroy(&s
->dynamic_creds
);
1994 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
1996 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
2000 if (s
->result
== SOCKET_SUCCESS
)
2003 socket_unwatch_control_pid(s
);
2004 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
2005 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
2007 if (s
->control_command
) {
2008 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2012 socket_set_state(s
, SOCKET_STOP_POST
);
2014 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
2019 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
2020 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2023 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
2028 if (s
->result
== SOCKET_SUCCESS
)
2031 r
= unit_kill_context(
2034 !IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FINAL_SIGTERM
) ?
2035 KILL_KILL
: KILL_TERMINATE
,
2043 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
2047 socket_set_state(s
, state
);
2048 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
2049 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
2050 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
2051 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2052 else if (state
== SOCKET_FINAL_SIGTERM
)
2053 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
2055 socket_enter_dead(s
, SOCKET_SUCCESS
);
2060 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
2062 if (IN_SET(state
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_STOP_PRE_SIGKILL
))
2063 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2065 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2068 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
2072 if (s
->result
== SOCKET_SUCCESS
)
2075 socket_unwatch_control_pid(s
);
2076 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
2077 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
2079 if (s
->control_command
) {
2080 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2084 socket_set_state(s
, SOCKET_STOP_PRE
);
2086 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2091 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2092 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2095 static void socket_enter_listening(Socket
*s
) {
2099 r
= socket_watch_fds(s
);
2101 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2105 socket_set_state(s
, SOCKET_LISTENING
);
2109 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2112 static void socket_enter_start_post(Socket
*s
) {
2116 socket_unwatch_control_pid(s
);
2117 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2118 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2120 if (s
->control_command
) {
2121 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2123 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2127 socket_set_state(s
, SOCKET_START_POST
);
2129 socket_enter_listening(s
);
2134 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2137 static void socket_enter_start_chown(Socket
*s
) {
2142 r
= socket_open_fds(s
);
2144 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2148 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2150 socket_unwatch_control_pid(s
);
2151 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2152 s
->control_command
= NULL
;
2154 r
= socket_chown(s
, &s
->control_pid
);
2156 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2160 socket_set_state(s
, SOCKET_START_CHOWN
);
2162 socket_enter_start_post(s
);
2167 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2170 static void socket_enter_start_pre(Socket
*s
) {
2174 socket_unwatch_control_pid(s
);
2176 unit_warn_leftover_processes(UNIT(s
));
2178 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2179 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2181 if (s
->control_command
) {
2182 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2184 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2188 socket_set_state(s
, SOCKET_START_PRE
);
2190 socket_enter_start_chown(s
);
2195 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2198 static void flush_ports(Socket
*s
) {
2201 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2204 LIST_FOREACH(port
, p
, s
->ports
) {
2208 (void) flush_accept(p
->fd
);
2209 (void) flush_fd(p
->fd
);
2213 static void socket_enter_running(Socket
*s
, int cfd
) {
2214 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2217 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2222 /* We don't take connections anymore if we are supposed to shut down anyway */
2223 if (unit_stop_pending(UNIT(s
))) {
2225 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2235 if (!ratelimit_below(&s
->trigger_limit
)) {
2236 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2237 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2242 bool pending
= false;
2247 /* If there's already a start pending don't bother to
2249 HASHMAP_FOREACH_KEY(v
, other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2250 if (unit_active_or_pending(other
)) {
2256 if (!UNIT_ISSET(s
->service
)) {
2257 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2262 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2267 socket_set_state(s
, SOCKET_RUNNING
);
2269 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2270 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2273 if (s
->n_connections
>= s
->max_connections
) {
2274 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2279 if (s
->max_connections_per_source
> 0) {
2280 r
= socket_acquire_peer(s
, cfd
, &p
);
2283 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2284 _cleanup_free_
char *t
= NULL
;
2286 (void) sockaddr_pretty(&p
->peer
.sa
, p
->peer_salen
, true, false, &t
);
2288 log_unit_warning(UNIT(s
),
2289 "Too many incoming connections (%u) from source %s, dropping connection.",
2290 p
->n_ref
, strnull(t
));
2295 r
= socket_instantiate_service(s
);
2299 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2304 /* ENOTCONN is legitimate if TCP RST was received.
2305 * This connection is over, but the socket unit lives on. */
2306 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2310 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2314 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2318 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2322 service
= SERVICE(UNIT_DEREF(s
->service
));
2323 unit_ref_unset(&s
->service
);
2326 unit_choose_id(UNIT(service
), name
);
2328 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2332 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2335 service
->peer
= TAKE_PTR(p
); /* Pass ownership of the peer reference */
2337 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2339 /* We failed to activate the new service, but it still exists. Let's make sure the service
2340 * closes and forgets the connection fd again, immediately. */
2341 service_close_socket_fd(service
);
2345 /* Notify clients about changed counters */
2346 unit_add_to_dbus_queue(UNIT(s
));
2357 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2358 cfd
>= 0 ? "template" : "non-template",
2359 bus_error_message(&error
, r
));
2361 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2365 static void socket_run_next(Socket
*s
) {
2369 assert(s
->control_command
);
2370 assert(s
->control_command
->command_next
);
2372 socket_unwatch_control_pid(s
);
2374 s
->control_command
= s
->control_command
->command_next
;
2376 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2383 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2385 if (s
->state
== SOCKET_START_POST
)
2386 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2387 else if (s
->state
== SOCKET_STOP_POST
)
2388 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2390 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2393 static int socket_start(Unit
*u
) {
2394 Socket
*s
= SOCKET(u
);
2399 /* We cannot fulfill this request right now, try again later
2401 if (IN_SET(s
->state
,
2403 SOCKET_STOP_PRE_SIGKILL
,
2404 SOCKET_STOP_PRE_SIGTERM
,
2406 SOCKET_FINAL_SIGTERM
,
2407 SOCKET_FINAL_SIGKILL
))
2410 /* Already on it! */
2411 if (IN_SET(s
->state
,
2417 /* Cannot run this without the service being around */
2418 if (UNIT_ISSET(s
->service
)) {
2421 service
= SERVICE(UNIT_DEREF(s
->service
));
2423 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2424 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2428 /* If the service is already active we cannot start the
2430 if (!IN_SET(service
->state
, SERVICE_DEAD
, SERVICE_FAILED
, SERVICE_AUTO_RESTART
)) {
2431 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2436 assert(IN_SET(s
->state
, SOCKET_DEAD
, SOCKET_FAILED
));
2438 r
= unit_start_limit_test(u
);
2440 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2444 r
= unit_acquire_invocation_id(u
);
2448 s
->result
= SOCKET_SUCCESS
;
2449 exec_command_reset_status_list_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
2451 u
->reset_accounting
= true;
2453 socket_enter_start_pre(s
);
2457 static int socket_stop(Unit
*u
) {
2458 Socket
*s
= SOCKET(u
);
2463 if (IN_SET(s
->state
,
2465 SOCKET_STOP_PRE_SIGTERM
,
2466 SOCKET_STOP_PRE_SIGKILL
,
2468 SOCKET_FINAL_SIGTERM
,
2469 SOCKET_FINAL_SIGKILL
))
2472 /* If there's already something running we go directly into
2474 if (IN_SET(s
->state
,
2477 SOCKET_START_POST
)) {
2478 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2482 assert(IN_SET(s
->state
, SOCKET_LISTENING
, SOCKET_RUNNING
));
2484 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2488 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2489 Socket
*s
= SOCKET(u
);
2497 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2498 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2499 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2500 unit_serialize_item_format(u
, f
, "n-refused", "%u", s
->n_refused
);
2502 if (s
->control_pid
> 0)
2503 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2505 if (s
->control_command_id
>= 0)
2506 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2508 LIST_FOREACH(port
, p
, s
->ports
) {
2514 copy
= fdset_put_dup(fds
, p
->fd
);
2518 if (p
->type
== SOCKET_SOCKET
) {
2519 _cleanup_free_
char *t
= NULL
;
2521 r
= socket_address_print(&p
->address
, &t
);
2525 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2526 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2528 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2530 } else if (p
->type
== SOCKET_SPECIAL
)
2531 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2532 else if (p
->type
== SOCKET_MQUEUE
)
2533 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2534 else if (p
->type
== SOCKET_USB_FUNCTION
)
2535 unit_serialize_item_format(u
, f
, "ffs", "%i %s", copy
, p
->path
);
2537 assert(p
->type
== SOCKET_FIFO
);
2538 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2545 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2547 p
->fd
= fdset_remove(fds
, fd
);
2550 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2551 Socket
*s
= SOCKET(u
);
2557 if (streq(key
, "state")) {
2560 state
= socket_state_from_string(value
);
2562 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2564 s
->deserialized_state
= state
;
2565 } else if (streq(key
, "result")) {
2568 f
= socket_result_from_string(value
);
2570 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2571 else if (f
!= SOCKET_SUCCESS
)
2574 } else if (streq(key
, "n-accepted")) {
2577 if (safe_atou(value
, &k
) < 0)
2578 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2581 } else if (streq(key
, "n-refused")) {
2584 if (safe_atou(value
, &k
) < 0)
2585 log_unit_debug(u
, "Failed to parse n-refused value: %s", value
);
2588 } else if (streq(key
, "control-pid")) {
2591 if (parse_pid(value
, &pid
) < 0)
2592 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2594 s
->control_pid
= pid
;
2595 } else if (streq(key
, "control-command")) {
2596 SocketExecCommand id
;
2598 id
= socket_exec_command_from_string(value
);
2600 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2602 s
->control_command_id
= id
;
2603 s
->control_command
= s
->exec_command
[id
];
2605 } else if (streq(key
, "fifo")) {
2609 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2610 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2612 LIST_FOREACH(port
, p
, s
->ports
)
2613 if (p
->type
== SOCKET_FIFO
&&
2614 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2615 socket_port_take_fd(p
, fds
, fd
);
2619 } else if (streq(key
, "special")) {
2623 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2624 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2626 LIST_FOREACH(port
, p
, s
->ports
)
2627 if (p
->type
== SOCKET_SPECIAL
&&
2628 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2629 socket_port_take_fd(p
, fds
, fd
);
2633 } else if (streq(key
, "mqueue")) {
2637 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2638 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2640 LIST_FOREACH(port
, p
, s
->ports
)
2641 if (p
->type
== SOCKET_MQUEUE
&&
2642 streq(p
->path
, value
+skip
)) {
2643 socket_port_take_fd(p
, fds
, fd
);
2647 } else if (streq(key
, "socket")) {
2648 int fd
, type
, skip
= 0;
2651 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2652 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2654 LIST_FOREACH(port
, p
, s
->ports
)
2655 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2656 socket_port_take_fd(p
, fds
, fd
);
2660 } else if (streq(key
, "netlink")) {
2664 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2665 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2667 LIST_FOREACH(port
, p
, s
->ports
)
2668 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2669 socket_port_take_fd(p
, fds
, fd
);
2673 } else if (streq(key
, "ffs")) {
2677 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2678 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2680 LIST_FOREACH(port
, p
, s
->ports
)
2681 if (p
->type
== SOCKET_USB_FUNCTION
&&
2682 path_equal_or_files_same(p
->path
, value
+skip
, 0)) {
2683 socket_port_take_fd(p
, fds
, fd
);
2688 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2693 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2694 Socket
*s
= SOCKET(u
);
2699 LIST_FOREACH(port
, p
, s
->ports
) {
2703 if (p
->type
!= SOCKET_SOCKET
)
2709 FDSET_FOREACH(fd
, fds
, i
) {
2710 if (socket_address_matches_fd(&p
->address
, fd
)) {
2711 p
->fd
= fdset_remove(fds
, fd
);
2712 s
->deserialized_state
= SOCKET_LISTENING
;
2719 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2722 return state_translation_table
[SOCKET(u
)->state
];
2725 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2728 return socket_state_to_string(SOCKET(u
)->state
);
2731 const char* socket_port_type_to_string(SocketPort
*p
) {
2739 switch (p
->address
.type
) {
2747 case SOCK_SEQPACKET
:
2748 return "SequentialPacket";
2751 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2759 case SOCKET_SPECIAL
:
2763 return "MessageQueue";
2768 case SOCKET_USB_FUNCTION
:
2769 return "USBFunction";
2776 SocketType
socket_port_type_from_string(const char *s
) {
2779 if (STR_IN_SET(s
, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2780 return SOCKET_SOCKET
;
2781 else if (streq(s
, "Special"))
2782 return SOCKET_SPECIAL
;
2783 else if (streq(s
, "MessageQueue"))
2784 return SOCKET_MQUEUE
;
2785 else if (streq(s
, "FIFO"))
2787 else if (streq(s
, "USBFunction"))
2788 return SOCKET_USB_FUNCTION
;
2790 return _SOCKET_TYPE_INVALID
;
2793 _pure_
static bool socket_may_gc(Unit
*u
) {
2794 Socket
*s
= SOCKET(u
);
2798 return s
->n_connections
== 0;
2801 static int socket_accept_do(Socket
*s
, int fd
) {
2808 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2822 static int socket_accept_in_cgroup(Socket
*s
, SocketPort
*p
, int fd
) {
2823 _cleanup_close_pair_
int pair
[2] = { -1, -1 };
2831 /* Similar to socket_address_listen_in_cgroup(), but for accept() rathern than socket(): make sure that any
2832 * connection socket is also properly associated with the cgroup. */
2834 if (!IN_SET(p
->address
.sockaddr
.sa
.sa_family
, AF_INET
, AF_INET6
))
2837 r
= bpf_firewall_supported();
2840 if (r
== BPF_FIREWALL_UNSUPPORTED
)
2843 if (socketpair(AF_UNIX
, SOCK_SEQPACKET
|SOCK_CLOEXEC
, 0, pair
) < 0)
2844 return log_unit_error_errno(UNIT(s
), errno
, "Failed to create communication channel: %m");
2846 r
= unit_fork_helper_process(UNIT(s
), "(sd-accept)", &pid
);
2848 return log_unit_error_errno(UNIT(s
), r
, "Failed to fork off accept stub process: %m");
2852 pair
[0] = safe_close(pair
[0]);
2854 cfd
= socket_accept_do(s
, fd
);
2856 log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2857 _exit(EXIT_FAILURE
);
2860 r
= send_one_fd(pair
[1], cfd
, 0);
2862 log_unit_error_errno(UNIT(s
), r
, "Failed to send connection socket to parent: %m");
2863 _exit(EXIT_FAILURE
);
2866 _exit(EXIT_SUCCESS
);
2869 pair
[1] = safe_close(pair
[1]);
2870 cfd
= receive_one_fd(pair
[0], 0);
2872 /* We synchronously wait for the helper, as it shouldn't be slow */
2873 r
= wait_for_terminate_and_check("(sd-accept)", pid
, WAIT_LOG_ABNORMAL
);
2880 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to receive connection socket: %m");
2885 cfd
= socket_accept_do(s
, fd
);
2887 return log_unit_error_errno(UNIT(s
), cfd
, "Failed to accept connection socket: %m");
2892 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2893 SocketPort
*p
= userdata
;
2899 if (p
->socket
->state
!= SOCKET_LISTENING
)
2902 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2904 if (revents
!= EPOLLIN
) {
2906 if (revents
& EPOLLHUP
)
2907 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.");
2909 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2913 if (p
->socket
->accept
&&
2914 p
->type
== SOCKET_SOCKET
&&
2915 socket_address_can_accept(&p
->address
)) {
2917 cfd
= socket_accept_in_cgroup(p
->socket
, p
, fd
);
2921 socket_apply_socket_options(p
->socket
, cfd
);
2924 socket_enter_running(p
->socket
, cfd
);
2928 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2932 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2933 Socket
*s
= SOCKET(u
);
2939 if (pid
!= s
->control_pid
)
2944 if (is_clean_exit(code
, status
, EXIT_CLEAN_COMMAND
, NULL
))
2946 else if (code
== CLD_EXITED
)
2947 f
= SOCKET_FAILURE_EXIT_CODE
;
2948 else if (code
== CLD_KILLED
)
2949 f
= SOCKET_FAILURE_SIGNAL
;
2950 else if (code
== CLD_DUMPED
)
2951 f
= SOCKET_FAILURE_CORE_DUMP
;
2953 assert_not_reached("Unknown sigchld code");
2955 if (s
->control_command
) {
2956 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2958 if (s
->control_command
->flags
& EXEC_COMMAND_IGNORE_FAILURE
)
2962 log_unit_full(u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2963 "Control process exited, code=%s status=%i",
2964 sigchld_code_to_string(code
), status
);
2966 if (s
->result
== SOCKET_SUCCESS
)
2969 if (s
->control_command
&&
2970 s
->control_command
->command_next
&&
2971 f
== SOCKET_SUCCESS
) {
2973 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2976 s
->control_command
= NULL
;
2977 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2979 /* No further commands for this step, so let's figure
2980 * out what to do next */
2982 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2986 case SOCKET_START_PRE
:
2987 if (f
== SOCKET_SUCCESS
)
2988 socket_enter_start_chown(s
);
2990 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
2993 case SOCKET_START_CHOWN
:
2994 if (f
== SOCKET_SUCCESS
)
2995 socket_enter_start_post(s
);
2997 socket_enter_stop_pre(s
, f
);
3000 case SOCKET_START_POST
:
3001 if (f
== SOCKET_SUCCESS
)
3002 socket_enter_listening(s
);
3004 socket_enter_stop_pre(s
, f
);
3007 case SOCKET_STOP_PRE
:
3008 case SOCKET_STOP_PRE_SIGTERM
:
3009 case SOCKET_STOP_PRE_SIGKILL
:
3010 socket_enter_stop_post(s
, f
);
3013 case SOCKET_STOP_POST
:
3014 case SOCKET_FINAL_SIGTERM
:
3015 case SOCKET_FINAL_SIGKILL
:
3016 socket_enter_dead(s
, f
);
3020 assert_not_reached("Uh, control process died at wrong time.");
3024 /* Notify clients about changed exit status */
3025 unit_add_to_dbus_queue(u
);
3028 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
3029 Socket
*s
= SOCKET(userdata
);
3032 assert(s
->timer_event_source
== source
);
3036 case SOCKET_START_PRE
:
3037 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
3038 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3041 case SOCKET_START_CHOWN
:
3042 case SOCKET_START_POST
:
3043 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
3044 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
3047 case SOCKET_STOP_PRE
:
3048 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
3049 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3052 case SOCKET_STOP_PRE_SIGTERM
:
3053 if (s
->kill_context
.send_sigkill
) {
3054 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
3055 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3057 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
3058 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3062 case SOCKET_STOP_PRE_SIGKILL
:
3063 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
3064 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
3067 case SOCKET_STOP_POST
:
3068 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
3069 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
3072 case SOCKET_FINAL_SIGTERM
:
3073 if (s
->kill_context
.send_sigkill
) {
3074 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
3075 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
3077 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
3078 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3082 case SOCKET_FINAL_SIGKILL
:
3083 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
3084 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
3088 assert_not_reached("Timeout at wrong time.");
3094 int socket_collect_fds(Socket
*s
, int **fds
) {
3095 size_t k
= 0, n
= 0;
3102 /* Called from the service code for requesting our fds */
3104 LIST_FOREACH(port
, p
, s
->ports
) {
3107 n
+= p
->n_auxiliary_fds
;
3119 LIST_FOREACH(port
, p
, s
->ports
) {
3124 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
3125 rfds
[k
++] = p
->auxiliary_fds
[i
];
3134 static void socket_reset_failed(Unit
*u
) {
3135 Socket
*s
= SOCKET(u
);
3139 if (s
->state
== SOCKET_FAILED
)
3140 socket_set_state(s
, SOCKET_DEAD
);
3142 s
->result
= SOCKET_SUCCESS
;
3145 void socket_connection_unref(Socket
*s
) {
3148 /* The service is dead. Yay!
3150 * This is strictly for one-instance-per-connection
3153 assert(s
->n_connections
> 0);
3156 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
3159 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
3160 Socket
*s
= SOCKET(u
);
3165 /* Filter out invocations with bogus state */
3166 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
3169 /* Don't propagate state changes from the service if we are already down */
3170 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
3173 /* We don't care for the service state if we are in Accept=yes mode */
3177 /* Propagate start limit hit state */
3178 if (other
->start_limit_hit
) {
3179 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
3183 /* Don't propagate anything if there's still a job queued */
3187 if (IN_SET(SERVICE(other
)->state
,
3188 SERVICE_DEAD
, SERVICE_FAILED
,
3189 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
3190 SERVICE_AUTO_RESTART
))
3191 socket_enter_listening(s
);
3193 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
3194 socket_set_state(s
, SOCKET_RUNNING
);
3197 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3198 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3201 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3202 Socket
*s
= SOCKET(u
);
3206 if (!s
->timer_event_source
)
3209 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3212 if (t
== USEC_INFINITY
)
3219 char *socket_fdname(Socket
*s
) {
3222 /* Returns the name to use for $LISTEN_NAMES. If the user
3223 * didn't specify anything specifically, use the socket unit's
3224 * name as fallback. */
3226 return s
->fdname
?: UNIT(s
)->id
;
3229 static int socket_control_pid(Unit
*u
) {
3230 Socket
*s
= SOCKET(u
);
3234 return s
->control_pid
;
3237 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3238 [SOCKET_EXEC_START_PRE
] = "ExecStartPre",
3239 [SOCKET_EXEC_START_CHOWN
] = "ExecStartChown",
3240 [SOCKET_EXEC_START_POST
] = "ExecStartPost",
3241 [SOCKET_EXEC_STOP_PRE
] = "ExecStopPre",
3242 [SOCKET_EXEC_STOP_POST
] = "ExecStopPost"
3245 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3247 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3248 [SOCKET_SUCCESS
] = "success",
3249 [SOCKET_FAILURE_RESOURCES
] = "resources",
3250 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3251 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3252 [SOCKET_FAILURE_SIGNAL
] = "signal",
3253 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3254 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3255 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3256 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3259 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3261 const UnitVTable socket_vtable
= {
3262 .object_size
= sizeof(Socket
),
3263 .exec_context_offset
= offsetof(Socket
, exec_context
),
3264 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3265 .kill_context_offset
= offsetof(Socket
, kill_context
),
3266 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3267 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3273 .private_section
= "Socket",
3275 .can_transient
= true,
3277 .init
= socket_init
,
3278 .done
= socket_done
,
3279 .load
= socket_load
,
3281 .coldplug
= socket_coldplug
,
3283 .dump
= socket_dump
,
3285 .start
= socket_start
,
3286 .stop
= socket_stop
,
3288 .kill
= socket_kill
,
3290 .get_timeout
= socket_get_timeout
,
3292 .serialize
= socket_serialize
,
3293 .deserialize_item
= socket_deserialize_item
,
3294 .distribute_fds
= socket_distribute_fds
,
3296 .active_state
= socket_active_state
,
3297 .sub_state_to_string
= socket_sub_state_to_string
,
3299 .may_gc
= socket_may_gc
,
3301 .sigchld_event
= socket_sigchld_event
,
3303 .trigger_notify
= socket_trigger_notify
,
3305 .reset_failed
= socket_reset_failed
,
3307 .control_pid
= socket_control_pid
,
3309 .bus_vtable
= bus_socket_vtable
,
3310 .bus_set_property
= bus_socket_set_property
,
3311 .bus_commit_properties
= bus_socket_commit_properties
,
3313 .status_message_formats
= {
3314 /*.starting_stopping = {
3315 [0] = "Starting socket %s...",
3316 [1] = "Stopping socket %s...",
3318 .finished_start_job
= {
3319 [JOB_DONE
] = "Listening on %s.",
3320 [JOB_FAILED
] = "Failed to listen on %s.",
3321 [JOB_TIMEOUT
] = "Timed out starting %s.",
3323 .finished_stop_job
= {
3324 [JOB_DONE
] = "Closed %s.",
3325 [JOB_FAILED
] = "Failed stopping %s.",
3326 [JOB_TIMEOUT
] = "Timed out stopping %s.",