2 This file is part of systemd.
4 Copyright 2010 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 #include <arpa/inet.h>
24 #include <netinet/tcp.h>
26 #include <sys/epoll.h>
29 #include <linux/sctp.h>
31 #include "alloc-util.h"
32 #include "bus-error.h"
35 #include "dbus-socket.h"
37 #include "exit-status.h"
39 #include "formats-util.h"
45 #include "parse-util.h"
46 #include "path-util.h"
47 #include "process-util.h"
48 #include "selinux-util.h"
49 #include "signal-util.h"
50 #include "smack-util.h"
53 #include "string-table.h"
54 #include "string-util.h"
56 #include "unit-name.h"
57 #include "unit-printf.h"
59 #include "user-util.h"
60 #include "in-addr-util.h"
66 union sockaddr_union peer
;
69 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
70 [SOCKET_DEAD
] = UNIT_INACTIVE
,
71 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
72 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
73 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
74 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
75 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
76 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
77 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
78 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
79 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
80 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
81 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
82 [SOCKET_FAILED
] = UNIT_FAILED
85 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
86 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
88 static void socket_init(Unit
*u
) {
89 Socket
*s
= SOCKET(u
);
92 assert(u
->load_state
== UNIT_STUB
);
94 s
->backlog
= SOMAXCONN
;
95 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
96 s
->directory_mode
= 0755;
97 s
->socket_mode
= 0666;
99 s
->max_connections
= 64;
106 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
107 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
109 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
111 s
->trigger_limit
.interval
= USEC_INFINITY
;
112 s
->trigger_limit
.burst
= (unsigned) -1;
115 static void socket_unwatch_control_pid(Socket
*s
) {
118 if (s
->control_pid
<= 0)
121 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
125 static void socket_cleanup_fd_list(SocketPort
*p
) {
128 close_many(p
->auxiliary_fds
, p
->n_auxiliary_fds
);
129 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
130 p
->n_auxiliary_fds
= 0;
133 void socket_free_ports(Socket
*s
) {
138 while ((p
= s
->ports
)) {
139 LIST_REMOVE(port
, s
->ports
, p
);
141 sd_event_source_unref(p
->event_source
);
143 socket_cleanup_fd_list(p
);
150 static void socket_done(Unit
*u
) {
151 Socket
*s
= SOCKET(u
);
156 socket_free_ports(s
);
158 while ((p
= set_steal_first(s
->peers_by_address
)))
161 s
->peers_by_address
= set_free(s
->peers_by_address
);
163 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
164 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
165 s
->control_command
= NULL
;
167 dynamic_creds_unref(&s
->dynamic_creds
);
169 socket_unwatch_control_pid(s
);
171 unit_ref_unset(&s
->service
);
173 s
->tcp_congestion
= mfree(s
->tcp_congestion
);
174 s
->bind_to_device
= mfree(s
->bind_to_device
);
176 s
->smack
= mfree(s
->smack
);
177 s
->smack_ip_in
= mfree(s
->smack_ip_in
);
178 s
->smack_ip_out
= mfree(s
->smack_ip_out
);
180 strv_free(s
->symlinks
);
182 s
->user
= mfree(s
->user
);
183 s
->group
= mfree(s
->group
);
185 s
->fdname
= mfree(s
->fdname
);
187 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
190 static int socket_arm_timer(Socket
*s
, usec_t usec
) {
195 if (s
->timer_event_source
) {
196 r
= sd_event_source_set_time(s
->timer_event_source
, usec
);
200 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
203 if (usec
== USEC_INFINITY
)
206 r
= sd_event_add_time(
207 UNIT(s
)->manager
->event
,
208 &s
->timer_event_source
,
211 socket_dispatch_timer
, s
);
215 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
220 int socket_instantiate_service(Socket
*s
) {
221 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
227 /* This fills in s->service if it isn't filled in yet. For
228 * Accept=yes sockets we create the next connection service
229 * here. For Accept=no this is mostly a NOP since the service
230 * is figured out at load time anyway. */
232 if (UNIT_DEREF(s
->service
))
238 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
242 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
245 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
249 unit_ref_set(&s
->service
, u
);
251 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false);
254 static bool have_non_accept_socket(Socket
*s
) {
262 LIST_FOREACH(port
, p
, s
->ports
) {
264 if (p
->type
!= SOCKET_SOCKET
)
267 if (!socket_address_can_accept(&p
->address
))
274 static int socket_add_mount_links(Socket
*s
) {
280 LIST_FOREACH(port
, p
, s
->ports
) {
281 const char *path
= NULL
;
283 if (p
->type
== SOCKET_SOCKET
)
284 path
= socket_address_get_path(&p
->address
);
285 else if (IN_SET(p
->type
, SOCKET_FIFO
, SOCKET_SPECIAL
, SOCKET_USB_FUNCTION
))
291 r
= unit_require_mounts_for(UNIT(s
), path
);
299 static int socket_add_device_link(Socket
*s
) {
304 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
307 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
308 return unit_add_node_link(UNIT(s
), t
, false, UNIT_BINDS_TO
);
311 static int socket_add_default_dependencies(Socket
*s
) {
315 if (!UNIT(s
)->default_dependencies
)
318 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, NULL
, true);
322 if (MANAGER_IS_SYSTEM(UNIT(s
)->manager
)) {
323 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, NULL
, true);
328 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, NULL
, true);
331 _pure_
static bool socket_has_exec(Socket
*s
) {
335 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
336 if (s
->exec_command
[i
])
342 static int socket_add_extras(Socket
*s
) {
348 /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
349 * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
350 * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
351 * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
352 * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
353 * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
354 * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
355 * service starts are typical. */
357 if (s
->trigger_limit
.interval
== USEC_INFINITY
)
358 s
->trigger_limit
.interval
= 2 * USEC_PER_SEC
;
360 if (s
->trigger_limit
.burst
== (unsigned) -1) {
362 s
->trigger_limit
.burst
= 200;
364 s
->trigger_limit
.burst
= 20;
367 if (have_non_accept_socket(s
)) {
369 if (!UNIT_DEREF(s
->service
)) {
372 r
= unit_load_related_unit(u
, ".service", &x
);
376 unit_ref_set(&s
->service
, x
);
379 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true);
384 r
= socket_add_mount_links(s
);
388 r
= socket_add_device_link(s
);
392 r
= unit_patch_contexts(u
);
396 if (socket_has_exec(s
)) {
397 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
401 r
= unit_set_default_slice(u
);
406 r
= socket_add_default_dependencies(s
);
413 static const char *socket_find_symlink_target(Socket
*s
) {
414 const char *found
= NULL
;
417 LIST_FOREACH(port
, p
, s
->ports
) {
418 const char *f
= NULL
;
427 if (p
->address
.sockaddr
.un
.sun_path
[0] != 0)
428 f
= p
->address
.sockaddr
.un
.sun_path
;
446 static int socket_verify(Socket
*s
) {
449 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
453 log_unit_error(UNIT(s
), "Unit lacks Listen setting. Refusing.");
457 if (s
->accept
&& have_non_accept_socket(s
)) {
458 log_unit_error(UNIT(s
), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
462 if (s
->accept
&& s
->max_connections
<= 0) {
463 log_unit_error(UNIT(s
), "MaxConnection= setting too small. Refusing.");
467 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
468 log_unit_error(UNIT(s
), "Explicit service configuration for accepting socket units not supported. Refusing.");
472 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
473 log_unit_error(UNIT(s
), "Unit has PAM enabled. Kill mode must be set to 'control-group'. Refusing.");
477 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
478 log_unit_error(UNIT(s
), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
485 static void peer_address_hash_func(const void *p
, struct siphash
*state
) {
486 const SocketPeer
*s
= p
;
489 assert(IN_SET(s
->peer
.sa
.sa_family
, AF_INET
, AF_INET6
));
491 if (s
->peer
.sa
.sa_family
== AF_INET
)
492 siphash24_compress(&s
->peer
.in
.sin_addr
, sizeof(s
->peer
.in
.sin_addr
), state
);
494 siphash24_compress(&s
->peer
.in6
.sin6_addr
, sizeof(s
->peer
.in6
.sin6_addr
), state
);
497 static int peer_address_compare_func(const void *a
, const void *b
) {
498 const SocketPeer
*x
= a
, *y
= b
;
500 if (x
->peer
.sa
.sa_family
< y
->peer
.sa
.sa_family
)
502 if (x
->peer
.sa
.sa_family
> y
->peer
.sa
.sa_family
)
505 switch(x
->peer
.sa
.sa_family
) {
507 return memcmp(&x
->peer
.in
.sin_addr
, &y
->peer
.in
.sin_addr
, sizeof(x
->peer
.in
.sin_addr
));
509 return memcmp(&x
->peer
.in6
.sin6_addr
, &y
->peer
.in6
.sin6_addr
, sizeof(x
->peer
.in6
.sin6_addr
));
511 assert_not_reached("Black sheep in the family!");
514 const struct hash_ops peer_address_hash_ops
= {
515 .hash
= peer_address_hash_func
,
516 .compare
= peer_address_compare_func
519 static int socket_load(Unit
*u
) {
520 Socket
*s
= SOCKET(u
);
524 assert(u
->load_state
== UNIT_STUB
);
526 r
= set_ensure_allocated(&s
->peers_by_address
, &peer_address_hash_ops
);
530 r
= unit_load_fragment_and_dropin(u
);
534 if (u
->load_state
== UNIT_LOADED
) {
535 /* This is a new unit? Then let's add in some extras */
536 r
= socket_add_extras(s
);
541 return socket_verify(s
);
544 static SocketPeer
*socket_peer_new(void) {
547 p
= new0(SocketPeer
, 1);
556 SocketPeer
*socket_peer_ref(SocketPeer
*p
) {
560 assert(p
->n_ref
> 0);
566 SocketPeer
*socket_peer_unref(SocketPeer
*p
) {
570 assert(p
->n_ref
> 0);
578 set_remove(p
->socket
->peers_by_address
, p
);
583 int socket_acquire_peer(Socket
*s
, int fd
, SocketPeer
**p
) {
584 _cleanup_(socket_peer_unrefp
) SocketPeer
*remote
= NULL
;
585 SocketPeer sa
= {}, *i
;
586 socklen_t salen
= sizeof(sa
.peer
);
592 r
= getpeername(fd
, &sa
.peer
.sa
, &salen
);
594 return log_error_errno(errno
, "getpeername failed: %m");
596 if (!IN_SET(sa
.peer
.sa
.sa_family
, AF_INET
, AF_INET6
)) {
601 i
= set_get(s
->peers_by_address
, &sa
);
603 *p
= socket_peer_ref(i
);
607 remote
= socket_peer_new();
611 remote
->peer
= sa
.peer
;
613 r
= set_put(s
->peers_by_address
, remote
);
625 _const_
static const char* listen_lookup(int family
, int type
) {
627 if (family
== AF_NETLINK
)
628 return "ListenNetlink";
630 if (type
== SOCK_STREAM
)
631 return "ListenStream";
632 else if (type
== SOCK_DGRAM
)
633 return "ListenDatagram";
634 else if (type
== SOCK_SEQPACKET
)
635 return "ListenSequentialPacket";
637 assert_not_reached("Unknown socket type");
641 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
642 char time_string
[FORMAT_TIMESPAN_MAX
];
644 Socket
*s
= SOCKET(u
);
651 prefix
= strempty(prefix
);
652 prefix2
= strjoina(prefix
, "\t");
655 "%sSocket State: %s\n"
657 "%sBindIPv6Only: %s\n"
659 "%sSocketMode: %04o\n"
660 "%sDirectoryMode: %04o\n"
664 "%sTransparent: %s\n"
666 "%sPassCredentials: %s\n"
667 "%sPassSecurity: %s\n"
668 "%sTCPCongestion: %s\n"
669 "%sRemoveOnStop: %s\n"
672 "%sSELinuxContextFromNet: %s\n",
673 prefix
, socket_state_to_string(s
->state
),
674 prefix
, socket_result_to_string(s
->result
),
675 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
677 prefix
, s
->socket_mode
,
678 prefix
, s
->directory_mode
,
679 prefix
, yes_no(s
->keep_alive
),
680 prefix
, yes_no(s
->no_delay
),
681 prefix
, yes_no(s
->free_bind
),
682 prefix
, yes_no(s
->transparent
),
683 prefix
, yes_no(s
->broadcast
),
684 prefix
, yes_no(s
->pass_cred
),
685 prefix
, yes_no(s
->pass_sec
),
686 prefix
, strna(s
->tcp_congestion
),
687 prefix
, yes_no(s
->remove_on_stop
),
688 prefix
, yes_no(s
->writable
),
689 prefix
, socket_fdname(s
),
690 prefix
, yes_no(s
->selinux_context_from_net
));
692 if (s
->control_pid
> 0)
694 "%sControl PID: "PID_FMT
"\n",
695 prefix
, s
->control_pid
);
697 if (s
->bind_to_device
)
699 "%sBindToDevice: %s\n",
700 prefix
, s
->bind_to_device
);
705 "%sNConnections: %u\n"
706 "%sMaxConnections: %u\n",
707 prefix
, s
->n_accepted
,
708 prefix
, s
->n_connections
,
709 prefix
, s
->max_connections
);
711 if (s
->priority
>= 0)
714 prefix
, s
->priority
);
716 if (s
->receive_buffer
> 0)
718 "%sReceiveBuffer: %zu\n",
719 prefix
, s
->receive_buffer
);
721 if (s
->send_buffer
> 0)
723 "%sSendBuffer: %zu\n",
724 prefix
, s
->send_buffer
);
736 if (s
->pipe_size
> 0)
739 prefix
, s
->pipe_size
);
746 if (s
->mq_maxmsg
> 0)
748 "%sMessageQueueMaxMessages: %li\n",
749 prefix
, s
->mq_maxmsg
);
751 if (s
->mq_msgsize
> 0)
753 "%sMessageQueueMessageSize: %li\n",
754 prefix
, s
->mq_msgsize
);
759 prefix
, yes_no(s
->reuse_port
));
763 "%sSmackLabel: %s\n",
768 "%sSmackLabelIPIn: %s\n",
769 prefix
, s
->smack_ip_in
);
773 "%sSmackLabelIPOut: %s\n",
774 prefix
, s
->smack_ip_out
);
776 if (!isempty(s
->user
) || !isempty(s
->group
))
779 "%sSocketGroup: %s\n",
780 prefix
, strna(s
->user
),
781 prefix
, strna(s
->group
));
783 if (s
->keep_alive_time
> 0)
785 "%sKeepAliveTimeSec: %s\n",
786 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
788 if (s
->keep_alive_interval
)
790 "%sKeepAliveIntervalSec: %s\n",
791 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
793 if (s
->keep_alive_cnt
)
795 "%sKeepAliveProbes: %u\n",
796 prefix
, s
->keep_alive_cnt
);
800 "%sDeferAcceptSec: %s\n",
801 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
803 LIST_FOREACH(port
, p
, s
->ports
) {
805 if (p
->type
== SOCKET_SOCKET
) {
810 r
= socket_address_print(&p
->address
, &k
);
816 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
818 } else if (p
->type
== SOCKET_SPECIAL
)
819 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
820 else if (p
->type
== SOCKET_USB_FUNCTION
)
821 fprintf(f
, "%sListenUSBFunction: %s\n", prefix
, p
->path
);
822 else if (p
->type
== SOCKET_MQUEUE
)
823 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
825 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
829 "%sTriggerLimitIntervalSec: %s\n"
830 "%sTriggerLimitBurst: %u\n",
831 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->trigger_limit
.interval
, USEC_PER_SEC
),
832 prefix
, s
->trigger_limit
.burst
);
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
);
848 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
851 union sockaddr_union local
, remote
;
857 if (getsockname(fd
, &local
.sa
, &l
) < 0)
861 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
864 switch (local
.sa
.sa_family
) {
868 a
= be32toh(local
.in
.sin_addr
.s_addr
),
869 b
= be32toh(remote
.in
.sin_addr
.s_addr
);
872 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
874 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
875 be16toh(local
.in
.sin_port
),
876 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
877 be16toh(remote
.in
.sin_port
)) < 0)
884 static const unsigned char ipv4_prefix
[] = {
885 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
888 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
889 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
891 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
892 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
895 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
897 a
[0], a
[1], a
[2], a
[3],
898 be16toh(local
.in6
.sin6_port
),
899 b
[0], b
[1], b
[2], b
[3],
900 be16toh(remote
.in6
.sin6_port
)) < 0)
903 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
908 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
909 be16toh(local
.in6
.sin6_port
),
910 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
911 be16toh(remote
.in6
.sin6_port
)) < 0)
922 k
= getpeercred(fd
, &ucred
);
925 "%u-"PID_FMT
"-"UID_FMT
,
926 nr
, ucred
.pid
, ucred
.uid
) < 0)
928 } else if (k
== -ENODATA
) {
929 /* This handles the case where somebody is
930 * connecting from another pid/uid namespace
931 * (e.g. from outside of our container). */
943 assert_not_reached("Unhandled socket type.");
950 static void socket_close_fds(Socket
*s
) {
956 LIST_FOREACH(port
, p
, s
->ports
) {
959 was_open
= p
->fd
>= 0;
961 p
->event_source
= sd_event_source_unref(p
->event_source
);
962 p
->fd
= safe_close(p
->fd
);
963 socket_cleanup_fd_list(p
);
965 /* One little note: we should normally not delete any sockets in the file system here! After all some
966 * other process we spawned might still have a reference of this fd and wants to continue to use
967 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
968 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
969 * anyway, but only then. */
971 if (!was_open
|| !s
->remove_on_stop
)
977 (void) unlink(p
->path
);
981 (void) mq_unlink(p
->path
);
985 (void) socket_address_unlink(&p
->address
);
993 if (s
->remove_on_stop
)
994 STRV_FOREACH(i
, s
->symlinks
)
998 static void socket_apply_socket_options(Socket
*s
, int fd
) {
1004 if (s
->keep_alive
) {
1005 int b
= s
->keep_alive
;
1006 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &b
, sizeof(b
)) < 0)
1007 log_unit_warning_errno(UNIT(s
), errno
, "SO_KEEPALIVE failed: %m");
1010 if (s
->keep_alive_time
) {
1011 int value
= s
->keep_alive_time
/ USEC_PER_SEC
;
1012 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &value
, sizeof(value
)) < 0)
1013 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPIDLE failed: %m");
1016 if (s
->keep_alive_interval
) {
1017 int value
= s
->keep_alive_interval
/ USEC_PER_SEC
;
1018 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &value
, sizeof(value
)) < 0)
1019 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPINTVL failed: %m");
1022 if (s
->keep_alive_cnt
) {
1023 int value
= s
->keep_alive_cnt
;
1024 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPCNT
, &value
, sizeof(value
)) < 0)
1025 log_unit_warning_errno(UNIT(s
), errno
, "TCP_KEEPCNT failed: %m");
1028 if (s
->defer_accept
) {
1029 int value
= s
->defer_accept
/ USEC_PER_SEC
;
1030 if (setsockopt(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, &value
, sizeof(value
)) < 0)
1031 log_unit_warning_errno(UNIT(s
), errno
, "TCP_DEFER_ACCEPT failed: %m");
1035 int b
= s
->no_delay
;
1037 if (s
->socket_protocol
== IPPROTO_SCTP
) {
1038 if (setsockopt(fd
, SOL_SCTP
, SCTP_NODELAY
, &b
, sizeof(b
)) < 0)
1039 log_unit_warning_errno(UNIT(s
), errno
, "SCTP_NODELAY failed: %m");
1041 if (setsockopt(fd
, SOL_TCP
, TCP_NODELAY
, &b
, sizeof(b
)) < 0)
1042 log_unit_warning_errno(UNIT(s
), errno
, "TCP_NODELAY failed: %m");
1048 if (setsockopt(fd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof(one
)) < 0)
1049 log_unit_warning_errno(UNIT(s
), errno
, "SO_BROADCAST failed: %m");
1054 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
1055 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSCRED failed: %m");
1060 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
)) < 0)
1061 log_unit_warning_errno(UNIT(s
), errno
, "SO_PASSSEC failed: %m");
1064 if (s
->priority
>= 0)
1065 if (setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &s
->priority
, sizeof(s
->priority
)) < 0)
1066 log_unit_warning_errno(UNIT(s
), errno
, "SO_PRIORITY failed: %m");
1068 if (s
->receive_buffer
> 0) {
1069 int value
= (int) s
->receive_buffer
;
1071 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
1073 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
1074 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
1075 log_unit_warning_errno(UNIT(s
), errno
, "SO_RCVBUF failed: %m");
1078 if (s
->send_buffer
> 0) {
1079 int value
= (int) s
->send_buffer
;
1080 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
1081 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
1082 log_unit_warning_errno(UNIT(s
), errno
, "SO_SNDBUF failed: %m");
1086 if (setsockopt(fd
, SOL_SOCKET
, SO_MARK
, &s
->mark
, sizeof(s
->mark
)) < 0)
1087 log_unit_warning_errno(UNIT(s
), errno
, "SO_MARK failed: %m");
1090 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, &s
->ip_tos
, sizeof(s
->ip_tos
)) < 0)
1091 log_unit_warning_errno(UNIT(s
), errno
, "IP_TOS failed: %m");
1093 if (s
->ip_ttl
>= 0) {
1096 r
= setsockopt(fd
, IPPROTO_IP
, IP_TTL
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1098 if (socket_ipv6_is_supported())
1099 x
= setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
1102 errno
= EAFNOSUPPORT
;
1106 log_unit_warning_errno(UNIT(s
), errno
, "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
1109 if (s
->tcp_congestion
)
1110 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
1111 log_unit_warning_errno(UNIT(s
), errno
, "TCP_CONGESTION failed: %m");
1113 if (s
->smack_ip_in
) {
1114 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPIN
, s
->smack_ip_in
);
1116 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_in_fd: %m");
1119 if (s
->smack_ip_out
) {
1120 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_IPOUT
, s
->smack_ip_out
);
1122 log_unit_error_errno(UNIT(s
), r
, "mac_smack_apply_ip_out_fd: %m");
1126 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
1132 if (s
->pipe_size
> 0)
1133 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
1134 log_unit_warning_errno(UNIT(s
), errno
, "Setting pipe size failed, ignoring: %m");
1137 r
= mac_smack_apply_fd(fd
, SMACK_ATTR_ACCESS
, s
->smack
);
1139 log_unit_error_errno(UNIT(s
), r
, "SMACK relabelling failed, ignoring: %m");
1143 static int fifo_address_create(
1145 mode_t directory_mode
,
1146 mode_t socket_mode
) {
1148 _cleanup_close_
int fd
= -1;
1155 mkdir_parents_label(path
, directory_mode
);
1157 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
1161 /* Enforce the right access mode for the fifo */
1162 old_mask
= umask(~ socket_mode
);
1164 /* Include the original umask in our mask */
1165 (void) umask(~socket_mode
| old_mask
);
1167 r
= mkfifo(path
, socket_mode
);
1168 (void) umask(old_mask
);
1170 if (r
< 0 && errno
!= EEXIST
) {
1175 fd
= open(path
, O_RDWR
| O_CLOEXEC
| O_NOCTTY
| O_NONBLOCK
| O_NOFOLLOW
);
1181 mac_selinux_create_file_clear();
1183 if (fstat(fd
, &st
) < 0) {
1188 if (!S_ISFIFO(st
.st_mode
) ||
1189 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1190 st
.st_uid
!= getuid() ||
1191 st
.st_gid
!= getgid()) {
1202 mac_selinux_create_file_clear();
1206 static int special_address_create(const char *path
, bool writable
) {
1207 _cleanup_close_
int fd
= -1;
1213 fd
= open(path
, (writable
? O_RDWR
: O_RDONLY
)|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1217 if (fstat(fd
, &st
) < 0)
1220 /* Check whether this is a /proc, /sys or /dev file or char device */
1221 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
))
1230 static int usbffs_address_create(const char *path
) {
1231 _cleanup_close_
int fd
= -1;
1237 fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1241 if (fstat(fd
, &st
) < 0)
1244 /* Check whether this is a regular file (ffs endpoint)*/
1245 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
;
1268 if (maxmsg
> 0 && msgsize
> 0) {
1269 _attr
= (struct mq_attr
) {
1270 .mq_flags
= O_NONBLOCK
,
1271 .mq_maxmsg
= maxmsg
,
1272 .mq_msgsize
= msgsize
,
1277 /* Enforce the right access mode for the mq */
1278 old_mask
= umask(~ mq_mode
);
1280 /* Include the original umask in our mask */
1281 (void) umask(~mq_mode
| old_mask
);
1282 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1283 (void) umask(old_mask
);
1288 if (fstat(fd
, &st
) < 0)
1291 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1292 st
.st_uid
!= getuid() ||
1293 st
.st_gid
!= getgid())
1302 static int socket_symlink(Socket
*s
) {
1308 p
= socket_find_symlink_target(s
);
1312 STRV_FOREACH(i
, s
->symlinks
)
1313 symlink_label(p
, *i
);
1318 static int usbffs_write_descs(int fd
, Service
*s
) {
1321 if (!s
->usb_function_descriptors
|| !s
->usb_function_strings
)
1324 r
= copy_file_fd(s
->usb_function_descriptors
, fd
, false);
1328 return copy_file_fd(s
->usb_function_strings
, fd
, false);
1331 static int usbffs_select_ep(const struct dirent
*d
) {
1332 return d
->d_name
[0] != '.' && !streq(d
->d_name
, "ep0");
1335 static int usbffs_dispatch_eps(SocketPort
*p
) {
1336 _cleanup_free_
struct dirent
**ent
= NULL
;
1339 r
= scandir(p
->path
, &ent
, usbffs_select_ep
, alphasort
);
1344 p
->auxiliary_fds
= new(int, n
);
1345 if (!p
->auxiliary_fds
)
1348 p
->n_auxiliary_fds
= n
;
1351 for (i
= 0; i
< n
; ++i
) {
1352 _cleanup_free_
char *ep
= NULL
;
1354 ep
= path_make_absolute(ent
[i
]->d_name
, p
->path
);
1358 path_kill_slashes(ep
);
1360 r
= usbffs_address_create(ep
);
1364 p
->auxiliary_fds
[k
] = r
;
1373 close_many(p
->auxiliary_fds
, k
);
1374 p
->auxiliary_fds
= mfree(p
->auxiliary_fds
);
1375 p
->n_auxiliary_fds
= 0;
1380 static int socket_determine_selinux_label(Socket
*s
, char **ret
) {
1387 if (s
->selinux_context_from_net
) {
1388 /* If this is requested, get label from the network label */
1390 r
= mac_selinux_get_our_label(ret
);
1391 if (r
== -EOPNOTSUPP
)
1395 /* Otherwise, get it from the executable we are about to start */
1396 r
= socket_instantiate_service(s
);
1400 if (!UNIT_ISSET(s
->service
))
1403 c
= SERVICE(UNIT_DEREF(s
->service
))->exec_command
[SERVICE_EXEC_START
];
1407 r
= mac_selinux_get_create_label_from_exe(c
->path
, ret
);
1408 if (r
== -EPERM
|| r
== -EOPNOTSUPP
)
1419 static int socket_open_fds(Socket
*s
) {
1420 _cleanup_(mac_selinux_freep
) char *label
= NULL
;
1421 bool know_label
= false;
1427 LIST_FOREACH(port
, p
, s
->ports
) {
1437 /* Figure out label, if we don't it know yet. We do it once, for the first socket where
1438 * we need this and remember it for the rest. */
1440 r
= socket_determine_selinux_label(s
, &label
);
1447 /* Apply the socket protocol */
1448 switch (p
->address
.type
) {
1451 case SOCK_SEQPACKET
:
1452 if (s
->socket_protocol
== IPPROTO_SCTP
)
1453 p
->address
.protocol
= s
->socket_protocol
;
1457 if (s
->socket_protocol
== IPPROTO_UDPLITE
)
1458 p
->address
.protocol
= s
->socket_protocol
;
1462 r
= socket_address_listen(
1464 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1478 socket_apply_socket_options(s
, p
->fd
);
1482 case SOCKET_SPECIAL
:
1484 p
->fd
= special_address_create(p
->path
, s
->writable
);
1493 p
->fd
= fifo_address_create(
1502 socket_apply_fifo_options(s
, p
->fd
);
1508 p
->fd
= mq_address_create(
1519 case SOCKET_USB_FUNCTION
: {
1520 _cleanup_free_
char *ep
= NULL
;
1522 ep
= path_make_absolute("ep0", p
->path
);
1524 p
->fd
= usbffs_address_create(ep
);
1530 r
= usbffs_write_descs(p
->fd
, SERVICE(UNIT_DEREF(s
->service
)));
1534 r
= usbffs_dispatch_eps(p
);
1541 assert_not_reached("Unknown port type");
1548 socket_close_fds(s
);
1552 static void socket_unwatch_fds(Socket
*s
) {
1558 LIST_FOREACH(port
, p
, s
->ports
) {
1562 if (!p
->event_source
)
1565 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1567 log_unit_debug_errno(UNIT(s
), r
, "Failed to disable event source: %m");
1571 static int socket_watch_fds(Socket
*s
) {
1577 LIST_FOREACH(port
, p
, s
->ports
) {
1581 if (p
->event_source
) {
1582 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1586 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1590 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1597 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch listening fds: %m");
1598 socket_unwatch_fds(s
);
1608 static int socket_check_open(Socket
*s
) {
1609 bool have_open
= false, have_closed
= false;
1614 LIST_FOREACH(port
, p
, s
->ports
) {
1620 if (have_open
&& have_closed
)
1621 return SOCKET_OPEN_SOME
;
1625 return SOCKET_OPEN_ALL
;
1627 return SOCKET_OPEN_NONE
;
1630 static void socket_set_state(Socket
*s
, SocketState state
) {
1631 SocketState old_state
;
1634 old_state
= s
->state
;
1642 SOCKET_STOP_PRE_SIGTERM
,
1643 SOCKET_STOP_PRE_SIGKILL
,
1645 SOCKET_FINAL_SIGTERM
,
1646 SOCKET_FINAL_SIGKILL
)) {
1648 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1649 socket_unwatch_control_pid(s
);
1650 s
->control_command
= NULL
;
1651 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1654 if (state
!= SOCKET_LISTENING
)
1655 socket_unwatch_fds(s
);
1663 SOCKET_STOP_PRE_SIGTERM
,
1664 SOCKET_STOP_PRE_SIGKILL
))
1665 socket_close_fds(s
);
1667 if (state
!= old_state
)
1668 log_unit_debug(UNIT(s
), "Changed %s -> %s", socket_state_to_string(old_state
), socket_state_to_string(state
));
1670 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], true);
1673 static int socket_coldplug(Unit
*u
) {
1674 Socket
*s
= SOCKET(u
);
1678 assert(s
->state
== SOCKET_DEAD
);
1680 if (s
->deserialized_state
== s
->state
)
1683 if (s
->control_pid
> 0 &&
1684 pid_is_unwaited(s
->control_pid
) &&
1685 IN_SET(s
->deserialized_state
,
1690 SOCKET_STOP_PRE_SIGTERM
,
1691 SOCKET_STOP_PRE_SIGKILL
,
1693 SOCKET_FINAL_SIGTERM
,
1694 SOCKET_FINAL_SIGKILL
)) {
1696 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1700 r
= socket_arm_timer(s
, usec_add(u
->state_change_timestamp
.monotonic
, s
->timeout_usec
));
1705 if (IN_SET(s
->deserialized_state
,
1711 /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1712 * for. However, this is problematic, as we won't traverse throught the SOCKET_START_CHOWN state for
1713 * them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we have all fds open,
1714 * and if there's a mismatch, warn loudly. */
1716 r
= socket_check_open(s
);
1717 if (r
== SOCKET_OPEN_NONE
)
1718 log_unit_warning(UNIT(s
),
1719 "Socket unit configuration has changed while unit has been running, "
1720 "no open socket file descriptor left. "
1721 "The socket unit is not functional until restarted.");
1722 else if (r
== SOCKET_OPEN_SOME
)
1723 log_unit_warning(UNIT(s
),
1724 "Socket unit configuration has changed while unit has been running, "
1725 "and some socket file descriptors have not been opened yet. "
1726 "The socket unit is not fully functional until restarted.");
1729 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1730 r
= socket_watch_fds(s
);
1735 if (!IN_SET(s
->deserialized_state
, SOCKET_DEAD
, SOCKET_FAILED
))
1736 (void) unit_setup_dynamic_creds(u
);
1738 socket_set_state(s
, s
->deserialized_state
);
1742 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1743 _cleanup_free_
char **argv
= NULL
;
1746 ExecParameters exec_params
= {
1747 .flags
= EXEC_APPLY_PERMISSIONS
|EXEC_APPLY_CHROOT
|EXEC_APPLY_TTY_STDIN
,
1757 (void) unit_realize_cgroup(UNIT(s
));
1758 if (s
->reset_cpu_usage
) {
1759 (void) unit_reset_cpu_usage(UNIT(s
));
1760 s
->reset_cpu_usage
= false;
1763 r
= unit_setup_exec_runtime(UNIT(s
));
1767 r
= unit_setup_dynamic_creds(UNIT(s
));
1771 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1775 r
= unit_full_printf_strv(UNIT(s
), c
->argv
, &argv
);
1779 exec_params
.argv
= argv
;
1780 exec_params
.environment
= UNIT(s
)->manager
->environment
;
1781 exec_params
.flags
|= UNIT(s
)->manager
->confirm_spawn
? EXEC_CONFIRM_SPAWN
: 0;
1782 exec_params
.cgroup_supported
= UNIT(s
)->manager
->cgroup_supported
;
1783 exec_params
.cgroup_path
= UNIT(s
)->cgroup_path
;
1784 exec_params
.cgroup_delegate
= s
->cgroup_context
.delegate
;
1785 exec_params
.runtime_prefix
= manager_get_runtime_prefix(UNIT(s
)->manager
);
1787 r
= exec_spawn(UNIT(s
),
1797 r
= unit_watch_pid(UNIT(s
), pid
);
1799 /* FIXME: we need to do something here */
1806 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1810 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1814 /* We have to resolve the user names out-of-process, hence
1815 * let's fork here. It's messy, but well, what can we do? */
1823 uid_t uid
= UID_INVALID
;
1824 gid_t gid
= GID_INVALID
;
1827 (void) default_signals(SIGNALS_CRASH_HANDLER
, SIGNALS_IGNORE
, -1);
1828 (void) ignore_signals(SIGPIPE
, -1);
1831 if (!isempty(s
->user
)) {
1832 const char *user
= s
->user
;
1834 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
);
1841 if (!isempty(s
->group
)) {
1842 const char *group
= s
->group
;
1844 r
= get_group_creds(&group
, &gid
);
1851 LIST_FOREACH(port
, p
, s
->ports
) {
1852 const char *path
= NULL
;
1854 if (p
->type
== SOCKET_SOCKET
)
1855 path
= socket_address_get_path(&p
->address
);
1856 else if (p
->type
== SOCKET_FIFO
)
1862 if (chown(path
, uid
, gid
) < 0) {
1873 log_error_errno(r
, "Failed to chown socket at step %s: %m", exit_status_to_string(ret
, EXIT_STATUS_SYSTEMD
));
1878 r
= unit_watch_pid(UNIT(s
), pid
);
1886 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1890 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1893 if (s
->result
== SOCKET_SUCCESS
)
1896 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1898 exec_runtime_destroy(s
->exec_runtime
);
1899 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
1901 exec_context_destroy_runtime_directory(&s
->exec_context
, manager_get_runtime_prefix(UNIT(s
)->manager
));
1903 unit_unref_uid_gid(UNIT(s
), true);
1905 dynamic_creds_destroy(&s
->dynamic_creds
);
1908 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
1910 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
1914 if (s
->result
== SOCKET_SUCCESS
)
1917 socket_unwatch_control_pid(s
);
1918 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
1919 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
1921 if (s
->control_command
) {
1922 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1926 socket_set_state(s
, SOCKET_STOP_POST
);
1928 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
1933 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-post' task: %m");
1934 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
1937 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
1942 if (s
->result
== SOCKET_SUCCESS
)
1945 r
= unit_kill_context(
1948 (state
!= SOCKET_STOP_PRE_SIGTERM
&& state
!= SOCKET_FINAL_SIGTERM
) ?
1949 KILL_KILL
: KILL_TERMINATE
,
1957 r
= socket_arm_timer(s
, usec_add(now(CLOCK_MONOTONIC
), s
->timeout_usec
));
1961 socket_set_state(s
, state
);
1962 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
1963 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
1964 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
1965 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
1966 else if (state
== SOCKET_FINAL_SIGTERM
)
1967 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
1969 socket_enter_dead(s
, SOCKET_SUCCESS
);
1974 log_unit_warning_errno(UNIT(s
), r
, "Failed to kill processes: %m");
1976 if (state
== SOCKET_STOP_PRE_SIGTERM
|| state
== SOCKET_STOP_PRE_SIGKILL
)
1977 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
1979 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
1982 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
1986 if (s
->result
== SOCKET_SUCCESS
)
1989 socket_unwatch_control_pid(s
);
1990 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
1991 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
1993 if (s
->control_command
) {
1994 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1998 socket_set_state(s
, SOCKET_STOP_PRE
);
2000 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
2005 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'stop-pre' task: %m");
2006 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
2009 static void socket_enter_listening(Socket
*s
) {
2013 r
= socket_watch_fds(s
);
2015 log_unit_warning_errno(UNIT(s
), r
, "Failed to watch sockets: %m");
2019 socket_set_state(s
, SOCKET_LISTENING
);
2023 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2026 static void socket_enter_start_post(Socket
*s
) {
2030 socket_unwatch_control_pid(s
);
2031 s
->control_command_id
= SOCKET_EXEC_START_POST
;
2032 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
2034 if (s
->control_command
) {
2035 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2037 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-post' task: %m");
2041 socket_set_state(s
, SOCKET_START_POST
);
2043 socket_enter_listening(s
);
2048 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2051 static void socket_enter_start_chown(Socket
*s
) {
2056 r
= socket_open_fds(s
);
2058 log_unit_warning_errno(UNIT(s
), r
, "Failed to listen on sockets: %m");
2062 if (!isempty(s
->user
) || !isempty(s
->group
)) {
2064 socket_unwatch_control_pid(s
);
2065 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
2066 s
->control_command
= NULL
;
2068 r
= socket_chown(s
, &s
->control_pid
);
2070 log_unit_warning_errno(UNIT(s
), r
, "Failed to fork 'start-chown' task: %m");
2074 socket_set_state(s
, SOCKET_START_CHOWN
);
2076 socket_enter_start_post(s
);
2081 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2084 static void socket_enter_start_pre(Socket
*s
) {
2088 socket_unwatch_control_pid(s
);
2089 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
2090 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
2092 if (s
->control_command
) {
2093 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2095 log_unit_warning_errno(UNIT(s
), r
, "Failed to run 'start-pre' task: %m");
2099 socket_set_state(s
, SOCKET_START_PRE
);
2101 socket_enter_start_chown(s
);
2106 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2109 static void flush_ports(Socket
*s
) {
2112 /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2115 LIST_FOREACH(port
, p
, s
->ports
) {
2119 (void) flush_accept(p
->fd
);
2120 (void) flush_fd(p
->fd
);
2124 static void socket_enter_running(Socket
*s
, int cfd
) {
2125 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
2128 /* Note that this call takes possession of the connection fd passed. It either has to assign it somewhere or
2133 /* We don't take connections anymore if we are supposed to shut down anyway */
2134 if (unit_stop_pending(UNIT(s
))) {
2136 log_unit_debug(UNIT(s
), "Suppressing connection request since unit stop is scheduled.");
2139 cfd
= safe_close(cfd
);
2146 if (!ratelimit_test(&s
->trigger_limit
)) {
2148 log_unit_warning(UNIT(s
), "Trigger limit hit, refusing further activation.");
2149 socket_enter_stop_pre(s
, SOCKET_FAILURE_TRIGGER_LIMIT_HIT
);
2156 bool pending
= false;
2158 /* If there's already a start pending don't bother to
2160 SET_FOREACH(other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
2161 if (unit_active_or_pending(other
)) {
2167 if (!UNIT_ISSET(s
->service
)) {
2168 log_unit_error(UNIT(s
), "Service to activate vanished, refusing activation.");
2173 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, &error
, NULL
);
2178 socket_set_state(s
, SOCKET_RUNNING
);
2180 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
2181 _cleanup_(socket_peer_unrefp
) SocketPeer
*p
= NULL
;
2184 if (s
->n_connections
>= s
->max_connections
) {
2185 log_unit_warning(UNIT(s
), "Too many incoming connections (%u), dropping connection.",
2191 if (s
->max_connections_per_source
> 0) {
2192 r
= socket_acquire_peer(s
, cfd
, &p
);
2196 } else if (r
> 0 && p
->n_ref
> s
->max_connections_per_source
) {
2197 _cleanup_free_
char *t
= NULL
;
2199 sockaddr_pretty(&p
->peer
.sa
, FAMILY_ADDRESS_SIZE(p
->peer
.sa
.sa_family
), true, false, &t
);
2201 log_unit_warning(UNIT(s
),
2202 "Too many incoming connections (%u) from source %s, dropping connection.",
2203 p
->n_ref
, strnull(t
));
2209 r
= socket_instantiate_service(s
);
2213 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
2218 /* ENOTCONN is legitimate if TCP RST was received.
2219 * This connection is over, but the socket unit lives on. */
2220 log_unit_debug(UNIT(s
), "Got ENOTCONN on incoming socket, assuming aborted connection attempt, ignoring.");
2225 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
2229 r
= unit_name_build(prefix
, instance
, ".service", &name
);
2233 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
2237 service
= SERVICE(UNIT_DEREF(s
->service
));
2238 unit_ref_unset(&s
->service
);
2241 unit_choose_id(UNIT(service
), name
);
2243 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
2247 cfd
= -1; /* We passed ownership of the fd to the service now. Forget it here. */
2250 service
->peer
= p
; /* Pass ownership of the peer reference */
2253 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, &error
, NULL
);
2255 /* We failed to activate the new service, but it still exists. Let's make sure the service
2256 * closes and forgets the connection fd again, immediately. */
2257 service_close_socket_fd(service
);
2261 /* Notify clients about changed counters */
2262 unit_add_to_dbus_queue(UNIT(s
));
2268 log_unit_warning(UNIT(s
), "Failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
2269 cfd
>= 0 ? "template" : "non-template",
2270 bus_error_message(&error
, r
));
2272 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2276 static void socket_run_next(Socket
*s
) {
2280 assert(s
->control_command
);
2281 assert(s
->control_command
->command_next
);
2283 socket_unwatch_control_pid(s
);
2285 s
->control_command
= s
->control_command
->command_next
;
2287 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
2294 log_unit_warning_errno(UNIT(s
), r
, "Failed to run next task: %m");
2296 if (s
->state
== SOCKET_START_POST
)
2297 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
2298 else if (s
->state
== SOCKET_STOP_POST
)
2299 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
2301 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
2304 static int socket_start(Unit
*u
) {
2305 Socket
*s
= SOCKET(u
);
2310 /* We cannot fulfill this request right now, try again later
2312 if (IN_SET(s
->state
,
2314 SOCKET_STOP_PRE_SIGKILL
,
2315 SOCKET_STOP_PRE_SIGTERM
,
2317 SOCKET_FINAL_SIGTERM
,
2318 SOCKET_FINAL_SIGKILL
))
2321 /* Already on it! */
2322 if (IN_SET(s
->state
,
2328 /* Cannot run this without the service being around */
2329 if (UNIT_ISSET(s
->service
)) {
2332 service
= SERVICE(UNIT_DEREF(s
->service
));
2334 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
2335 log_unit_error(u
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
2339 /* If the service is already active we cannot start the
2341 if (service
->state
!= SERVICE_DEAD
&&
2342 service
->state
!= SERVICE_FAILED
&&
2343 service
->state
!= SERVICE_AUTO_RESTART
) {
2344 log_unit_error(u
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
2349 assert(s
->state
== SOCKET_DEAD
|| s
->state
== SOCKET_FAILED
);
2351 r
= unit_start_limit_test(u
);
2353 socket_enter_dead(s
, SOCKET_FAILURE_START_LIMIT_HIT
);
2357 r
= unit_acquire_invocation_id(u
);
2361 s
->result
= SOCKET_SUCCESS
;
2362 s
->reset_cpu_usage
= true;
2364 socket_enter_start_pre(s
);
2368 static int socket_stop(Unit
*u
) {
2369 Socket
*s
= SOCKET(u
);
2374 if (IN_SET(s
->state
,
2376 SOCKET_STOP_PRE_SIGTERM
,
2377 SOCKET_STOP_PRE_SIGKILL
,
2379 SOCKET_FINAL_SIGTERM
,
2380 SOCKET_FINAL_SIGKILL
))
2383 /* If there's already something running we go directly into
2385 if (IN_SET(s
->state
,
2388 SOCKET_START_POST
)) {
2389 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
2393 assert(s
->state
== SOCKET_LISTENING
|| s
->state
== SOCKET_RUNNING
);
2395 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2399 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2400 Socket
*s
= SOCKET(u
);
2408 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2409 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2410 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2412 if (s
->control_pid
> 0)
2413 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2415 if (s
->control_command_id
>= 0)
2416 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2418 LIST_FOREACH(port
, p
, s
->ports
) {
2424 copy
= fdset_put_dup(fds
, p
->fd
);
2428 if (p
->type
== SOCKET_SOCKET
) {
2429 _cleanup_free_
char *t
= NULL
;
2431 r
= socket_address_print(&p
->address
, &t
);
2435 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2436 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2438 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2440 } else if (p
->type
== SOCKET_SPECIAL
)
2441 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2442 else if (p
->type
== SOCKET_MQUEUE
)
2443 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2444 else if (p
->type
== SOCKET_USB_FUNCTION
)
2445 unit_serialize_item_format(u
, f
, "ffs", "%i %s", copy
, p
->path
);
2447 assert(p
->type
== SOCKET_FIFO
);
2448 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2455 static void socket_port_take_fd(SocketPort
*p
, FDSet
*fds
, int fd
) {
2457 p
->fd
= fdset_remove(fds
, fd
);
2460 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2461 Socket
*s
= SOCKET(u
);
2467 if (streq(key
, "state")) {
2470 state
= socket_state_from_string(value
);
2472 log_unit_debug(u
, "Failed to parse state value: %s", value
);
2474 s
->deserialized_state
= state
;
2475 } else if (streq(key
, "result")) {
2478 f
= socket_result_from_string(value
);
2480 log_unit_debug(u
, "Failed to parse result value: %s", value
);
2481 else if (f
!= SOCKET_SUCCESS
)
2484 } else if (streq(key
, "n-accepted")) {
2487 if (safe_atou(value
, &k
) < 0)
2488 log_unit_debug(u
, "Failed to parse n-accepted value: %s", value
);
2491 } else if (streq(key
, "control-pid")) {
2494 if (parse_pid(value
, &pid
) < 0)
2495 log_unit_debug(u
, "Failed to parse control-pid value: %s", value
);
2497 s
->control_pid
= pid
;
2498 } else if (streq(key
, "control-command")) {
2499 SocketExecCommand id
;
2501 id
= socket_exec_command_from_string(value
);
2503 log_unit_debug(u
, "Failed to parse exec-command value: %s", value
);
2505 s
->control_command_id
= id
;
2506 s
->control_command
= s
->exec_command
[id
];
2508 } else if (streq(key
, "fifo")) {
2512 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2513 log_unit_debug(u
, "Failed to parse fifo value: %s", value
);
2515 LIST_FOREACH(port
, p
, s
->ports
)
2516 if (p
->type
== SOCKET_FIFO
&&
2517 path_equal_or_files_same(p
->path
, value
+skip
)) {
2518 socket_port_take_fd(p
, fds
, fd
);
2522 } else if (streq(key
, "special")) {
2526 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2527 log_unit_debug(u
, "Failed to parse special value: %s", value
);
2529 LIST_FOREACH(port
, p
, s
->ports
)
2530 if (p
->type
== SOCKET_SPECIAL
&&
2531 path_equal_or_files_same(p
->path
, value
+skip
)) {
2532 socket_port_take_fd(p
, fds
, fd
);
2536 } else if (streq(key
, "mqueue")) {
2540 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2541 log_unit_debug(u
, "Failed to parse mqueue value: %s", value
);
2543 LIST_FOREACH(port
, p
, s
->ports
)
2544 if (p
->type
== SOCKET_MQUEUE
&&
2545 streq(p
->path
, value
+skip
)) {
2546 socket_port_take_fd(p
, fds
, fd
);
2550 } else if (streq(key
, "socket")) {
2551 int fd
, type
, skip
= 0;
2554 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2555 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2557 LIST_FOREACH(port
, p
, s
->ports
)
2558 if (socket_address_is(&p
->address
, value
+skip
, type
)) {
2559 socket_port_take_fd(p
, fds
, fd
);
2563 } else if (streq(key
, "netlink")) {
2567 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2568 log_unit_debug(u
, "Failed to parse socket value: %s", value
);
2570 LIST_FOREACH(port
, p
, s
->ports
)
2571 if (socket_address_is_netlink(&p
->address
, value
+skip
)) {
2572 socket_port_take_fd(p
, fds
, fd
);
2576 } else if (streq(key
, "ffs")) {
2580 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2581 log_unit_debug(u
, "Failed to parse ffs value: %s", value
);
2583 LIST_FOREACH(port
, p
, s
->ports
)
2584 if (p
->type
== SOCKET_USB_FUNCTION
&&
2585 path_equal_or_files_same(p
->path
, value
+skip
)) {
2586 socket_port_take_fd(p
, fds
, fd
);
2591 log_unit_debug(UNIT(s
), "Unknown serialization key: %s", key
);
2596 static void socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2597 Socket
*s
= SOCKET(u
);
2602 LIST_FOREACH(port
, p
, s
->ports
) {
2606 if (p
->type
!= SOCKET_SOCKET
)
2612 FDSET_FOREACH(fd
, fds
, i
) {
2613 if (socket_address_matches_fd(&p
->address
, fd
)) {
2614 p
->fd
= fdset_remove(fds
, fd
);
2615 s
->deserialized_state
= SOCKET_LISTENING
;
2622 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2625 return state_translation_table
[SOCKET(u
)->state
];
2628 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2631 return socket_state_to_string(SOCKET(u
)->state
);
2634 const char* socket_port_type_to_string(SocketPort
*p
) {
2642 switch (p
->address
.type
) {
2650 case SOCK_SEQPACKET
:
2651 return "SequentialPacket";
2654 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2661 case SOCKET_SPECIAL
:
2665 return "MessageQueue";
2670 case SOCKET_USB_FUNCTION
:
2671 return "USBFunction";
2678 _pure_
static bool socket_check_gc(Unit
*u
) {
2679 Socket
*s
= SOCKET(u
);
2683 return s
->n_connections
> 0;
2686 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2687 SocketPort
*p
= userdata
;
2693 if (p
->socket
->state
!= SOCKET_LISTENING
)
2696 log_unit_debug(UNIT(p
->socket
), "Incoming traffic");
2698 if (revents
!= EPOLLIN
) {
2700 if (revents
& EPOLLHUP
)
2701 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.");
2703 log_unit_error(UNIT(p
->socket
), "Got unexpected poll event (0x%x) on socket.", revents
);
2707 if (p
->socket
->accept
&&
2708 p
->type
== SOCKET_SOCKET
&&
2709 socket_address_can_accept(&p
->address
)) {
2713 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2719 log_unit_error_errno(UNIT(p
->socket
), errno
, "Failed to accept socket: %m");
2726 socket_apply_socket_options(p
->socket
, cfd
);
2729 socket_enter_running(p
->socket
, cfd
);
2733 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2737 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2738 Socket
*s
= SOCKET(u
);
2744 if (pid
!= s
->control_pid
)
2749 if (is_clean_exit(code
, status
, NULL
))
2751 else if (code
== CLD_EXITED
)
2752 f
= SOCKET_FAILURE_EXIT_CODE
;
2753 else if (code
== CLD_KILLED
)
2754 f
= SOCKET_FAILURE_SIGNAL
;
2755 else if (code
== CLD_DUMPED
)
2756 f
= SOCKET_FAILURE_CORE_DUMP
;
2758 assert_not_reached("Unknown sigchld code");
2760 if (s
->control_command
) {
2761 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2763 if (s
->control_command
->ignore
)
2767 log_unit_full(u
, f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
, 0,
2768 "Control process exited, code=%s status=%i",
2769 sigchld_code_to_string(code
), status
);
2771 if (s
->result
== SOCKET_SUCCESS
)
2774 if (s
->control_command
&&
2775 s
->control_command
->command_next
&&
2776 f
== SOCKET_SUCCESS
) {
2778 log_unit_debug(u
, "Running next command for state %s", socket_state_to_string(s
->state
));
2781 s
->control_command
= NULL
;
2782 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2784 /* No further commands for this step, so let's figure
2785 * out what to do next */
2787 log_unit_debug(u
, "Got final SIGCHLD for state %s", socket_state_to_string(s
->state
));
2791 case SOCKET_START_PRE
:
2792 if (f
== SOCKET_SUCCESS
)
2793 socket_enter_start_chown(s
);
2795 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
2798 case SOCKET_START_CHOWN
:
2799 if (f
== SOCKET_SUCCESS
)
2800 socket_enter_start_post(s
);
2802 socket_enter_stop_pre(s
, f
);
2805 case SOCKET_START_POST
:
2806 if (f
== SOCKET_SUCCESS
)
2807 socket_enter_listening(s
);
2809 socket_enter_stop_pre(s
, f
);
2812 case SOCKET_STOP_PRE
:
2813 case SOCKET_STOP_PRE_SIGTERM
:
2814 case SOCKET_STOP_PRE_SIGKILL
:
2815 socket_enter_stop_post(s
, f
);
2818 case SOCKET_STOP_POST
:
2819 case SOCKET_FINAL_SIGTERM
:
2820 case SOCKET_FINAL_SIGKILL
:
2821 socket_enter_dead(s
, f
);
2825 assert_not_reached("Uh, control process died at wrong time.");
2829 /* Notify clients about changed exit status */
2830 unit_add_to_dbus_queue(u
);
2833 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
2834 Socket
*s
= SOCKET(userdata
);
2837 assert(s
->timer_event_source
== source
);
2841 case SOCKET_START_PRE
:
2842 log_unit_warning(UNIT(s
), "Starting timed out. Terminating.");
2843 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2846 case SOCKET_START_CHOWN
:
2847 case SOCKET_START_POST
:
2848 log_unit_warning(UNIT(s
), "Starting timed out. Stopping.");
2849 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
2852 case SOCKET_STOP_PRE
:
2853 log_unit_warning(UNIT(s
), "Stopping timed out. Terminating.");
2854 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2857 case SOCKET_STOP_PRE_SIGTERM
:
2858 if (s
->kill_context
.send_sigkill
) {
2859 log_unit_warning(UNIT(s
), "Stopping timed out. Killing.");
2860 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
2862 log_unit_warning(UNIT(s
), "Stopping timed out. Skipping SIGKILL. Ignoring.");
2863 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
2867 case SOCKET_STOP_PRE_SIGKILL
:
2868 log_unit_warning(UNIT(s
), "Processes still around after SIGKILL. Ignoring.");
2869 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
2872 case SOCKET_STOP_POST
:
2873 log_unit_warning(UNIT(s
), "Stopping timed out (2). Terminating.");
2874 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2877 case SOCKET_FINAL_SIGTERM
:
2878 if (s
->kill_context
.send_sigkill
) {
2879 log_unit_warning(UNIT(s
), "Stopping timed out (2). Killing.");
2880 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
2882 log_unit_warning(UNIT(s
), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
2883 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
2887 case SOCKET_FINAL_SIGKILL
:
2888 log_unit_warning(UNIT(s
), "Still around after SIGKILL (2). Entering failed mode.");
2889 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
2893 assert_not_reached("Timeout at wrong time.");
2899 int socket_collect_fds(Socket
*s
, int **fds
) {
2900 int *rfds
, k
= 0, n
= 0;
2906 /* Called from the service code for requesting our fds */
2908 LIST_FOREACH(port
, p
, s
->ports
) {
2911 n
+= p
->n_auxiliary_fds
;
2923 LIST_FOREACH(port
, p
, s
->ports
) {
2928 for (i
= 0; i
< p
->n_auxiliary_fds
; ++i
)
2929 rfds
[k
++] = p
->auxiliary_fds
[i
];
2938 static void socket_reset_failed(Unit
*u
) {
2939 Socket
*s
= SOCKET(u
);
2943 if (s
->state
== SOCKET_FAILED
)
2944 socket_set_state(s
, SOCKET_DEAD
);
2946 s
->result
= SOCKET_SUCCESS
;
2949 void socket_connection_unref(Socket
*s
) {
2952 /* The service is dead. Yay!
2954 * This is strictly for one-instance-per-connection
2957 assert(s
->n_connections
> 0);
2960 log_unit_debug(UNIT(s
), "One connection closed, %u left.", s
->n_connections
);
2963 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
2964 Socket
*s
= SOCKET(u
);
2969 /* Filter out invocations with bogus state */
2970 if (other
->load_state
!= UNIT_LOADED
|| other
->type
!= UNIT_SERVICE
)
2973 /* Don't propagate state changes from the service if we are already down */
2974 if (!IN_SET(s
->state
, SOCKET_RUNNING
, SOCKET_LISTENING
))
2977 /* We don't care for the service state if we are in Accept=yes mode */
2981 /* Propagate start limit hit state */
2982 if (other
->start_limit_hit
) {
2983 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
);
2987 /* Don't propagate anything if there's still a job queued */
2991 if (IN_SET(SERVICE(other
)->state
,
2992 SERVICE_DEAD
, SERVICE_FAILED
,
2993 SERVICE_FINAL_SIGTERM
, SERVICE_FINAL_SIGKILL
,
2994 SERVICE_AUTO_RESTART
))
2995 socket_enter_listening(s
);
2997 if (SERVICE(other
)->state
== SERVICE_RUNNING
)
2998 socket_set_state(s
, SOCKET_RUNNING
);
3001 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
3002 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
3005 static int socket_get_timeout(Unit
*u
, usec_t
*timeout
) {
3006 Socket
*s
= SOCKET(u
);
3010 if (!s
->timer_event_source
)
3013 r
= sd_event_source_get_time(s
->timer_event_source
, &t
);
3016 if (t
== USEC_INFINITY
)
3023 char *socket_fdname(Socket
*s
) {
3026 /* Returns the name to use for $LISTEN_NAMES. If the user
3027 * didn't specify anything specifically, use the socket unit's
3028 * name as fallback. */
3036 static int socket_control_pid(Unit
*u
) {
3037 Socket
*s
= SOCKET(u
);
3041 return s
->control_pid
;
3044 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
3045 [SOCKET_EXEC_START_PRE
] = "StartPre",
3046 [SOCKET_EXEC_START_CHOWN
] = "StartChown",
3047 [SOCKET_EXEC_START_POST
] = "StartPost",
3048 [SOCKET_EXEC_STOP_PRE
] = "StopPre",
3049 [SOCKET_EXEC_STOP_POST
] = "StopPost"
3052 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
3054 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
3055 [SOCKET_SUCCESS
] = "success",
3056 [SOCKET_FAILURE_RESOURCES
] = "resources",
3057 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
3058 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
3059 [SOCKET_FAILURE_SIGNAL
] = "signal",
3060 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
3061 [SOCKET_FAILURE_START_LIMIT_HIT
] = "start-limit-hit",
3062 [SOCKET_FAILURE_TRIGGER_LIMIT_HIT
] = "trigger-limit-hit",
3063 [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT
] = "service-start-limit-hit"
3066 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
3068 const UnitVTable socket_vtable
= {
3069 .object_size
= sizeof(Socket
),
3070 .exec_context_offset
= offsetof(Socket
, exec_context
),
3071 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
3072 .kill_context_offset
= offsetof(Socket
, kill_context
),
3073 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
3074 .dynamic_creds_offset
= offsetof(Socket
, dynamic_creds
),
3080 .private_section
= "Socket",
3082 .init
= socket_init
,
3083 .done
= socket_done
,
3084 .load
= socket_load
,
3086 .coldplug
= socket_coldplug
,
3088 .dump
= socket_dump
,
3090 .start
= socket_start
,
3091 .stop
= socket_stop
,
3093 .kill
= socket_kill
,
3095 .get_timeout
= socket_get_timeout
,
3097 .serialize
= socket_serialize
,
3098 .deserialize_item
= socket_deserialize_item
,
3099 .distribute_fds
= socket_distribute_fds
,
3101 .active_state
= socket_active_state
,
3102 .sub_state_to_string
= socket_sub_state_to_string
,
3104 .check_gc
= socket_check_gc
,
3106 .sigchld_event
= socket_sigchld_event
,
3108 .trigger_notify
= socket_trigger_notify
,
3110 .reset_failed
= socket_reset_failed
,
3112 .control_pid
= socket_control_pid
,
3114 .bus_vtable
= bus_socket_vtable
,
3115 .bus_set_property
= bus_socket_set_property
,
3116 .bus_commit_properties
= bus_socket_commit_properties
,
3118 .status_message_formats
= {
3119 /*.starting_stopping = {
3120 [0] = "Starting socket %s...",
3121 [1] = "Stopping socket %s...",
3123 .finished_start_job
= {
3124 [JOB_DONE
] = "Listening on %s.",
3125 [JOB_FAILED
] = "Failed to listen on %s.",
3126 [JOB_TIMEOUT
] = "Timed out starting %s.",
3128 .finished_stop_job
= {
3129 [JOB_DONE
] = "Closed %s.",
3130 [JOB_FAILED
] = "Failed stopping %s.",
3131 [JOB_TIMEOUT
] = "Timed out stopping %s.",