1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2010 Lennart Poettering
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
26 #include <sys/epoll.h>
28 #include <arpa/inet.h>
29 #include <netinet/tcp.h>
36 #include "path-util.h"
37 #include "unit-name.h"
38 #include "unit-printf.h"
42 #include "exit-status.h"
44 #include "smack-util.h"
46 #include "bus-error.h"
47 #include "selinux-util.h"
48 #include "dbus-socket.h"
51 #include "formats-util.h"
53 static const UnitActiveState state_translation_table
[_SOCKET_STATE_MAX
] = {
54 [SOCKET_DEAD
] = UNIT_INACTIVE
,
55 [SOCKET_START_PRE
] = UNIT_ACTIVATING
,
56 [SOCKET_START_CHOWN
] = UNIT_ACTIVATING
,
57 [SOCKET_START_POST
] = UNIT_ACTIVATING
,
58 [SOCKET_LISTENING
] = UNIT_ACTIVE
,
59 [SOCKET_RUNNING
] = UNIT_ACTIVE
,
60 [SOCKET_STOP_PRE
] = UNIT_DEACTIVATING
,
61 [SOCKET_STOP_PRE_SIGTERM
] = UNIT_DEACTIVATING
,
62 [SOCKET_STOP_PRE_SIGKILL
] = UNIT_DEACTIVATING
,
63 [SOCKET_STOP_POST
] = UNIT_DEACTIVATING
,
64 [SOCKET_FINAL_SIGTERM
] = UNIT_DEACTIVATING
,
65 [SOCKET_FINAL_SIGKILL
] = UNIT_DEACTIVATING
,
66 [SOCKET_FAILED
] = UNIT_FAILED
69 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
);
70 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
);
72 static void socket_init(Unit
*u
) {
73 Socket
*s
= SOCKET(u
);
76 assert(u
->load_state
== UNIT_STUB
);
78 s
->backlog
= SOMAXCONN
;
79 s
->timeout_usec
= u
->manager
->default_timeout_start_usec
;
80 s
->directory_mode
= 0755;
81 s
->socket_mode
= 0666;
83 s
->max_connections
= 64;
90 s
->exec_context
.std_output
= u
->manager
->default_std_output
;
91 s
->exec_context
.std_error
= u
->manager
->default_std_error
;
93 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
96 static void socket_unwatch_control_pid(Socket
*s
) {
99 if (s
->control_pid
<= 0)
102 unit_unwatch_pid(UNIT(s
), s
->control_pid
);
106 void socket_free_ports(Socket
*s
) {
111 while ((p
= s
->ports
)) {
112 LIST_REMOVE(port
, s
->ports
, p
);
114 sd_event_source_unref(p
->event_source
);
122 static void socket_done(Unit
*u
) {
123 Socket
*s
= SOCKET(u
);
127 socket_free_ports(s
);
129 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
130 exec_command_free_array(s
->exec_command
, _SOCKET_EXEC_COMMAND_MAX
);
131 s
->control_command
= NULL
;
133 socket_unwatch_control_pid(s
);
135 unit_ref_unset(&s
->service
);
137 free(s
->tcp_congestion
);
138 s
->tcp_congestion
= NULL
;
140 free(s
->bind_to_device
);
141 s
->bind_to_device
= NULL
;
144 free(s
->smack_ip_in
);
145 free(s
->smack_ip_out
);
147 strv_free(s
->symlinks
);
152 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
155 static int socket_arm_timer(Socket
*s
) {
160 if (s
->timeout_usec
<= 0) {
161 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
165 if (s
->timer_event_source
) {
166 r
= sd_event_source_set_time(s
->timer_event_source
, now(CLOCK_MONOTONIC
) + s
->timeout_usec
);
170 return sd_event_source_set_enabled(s
->timer_event_source
, SD_EVENT_ONESHOT
);
173 r
= sd_event_add_time(
174 UNIT(s
)->manager
->event
,
175 &s
->timer_event_source
,
177 now(CLOCK_MONOTONIC
) + s
->timeout_usec
, 0,
178 socket_dispatch_timer
, s
);
182 (void) sd_event_source_set_description(s
->timer_event_source
, "socket-timer");
187 int socket_instantiate_service(Socket
*s
) {
188 _cleanup_free_
char *prefix
= NULL
, *name
= NULL
;
194 /* This fills in s->service if it isn't filled in yet. For
195 * Accept=yes sockets we create the next connection service
196 * here. For Accept=no this is mostly a NOP since the service
197 * is figured out at load time anyway. */
199 if (UNIT_DEREF(s
->service
))
205 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
209 if (asprintf(&name
, "%s@%u.service", prefix
, s
->n_accepted
) < 0)
212 r
= manager_load_unit(UNIT(s
)->manager
, name
, NULL
, NULL
, &u
);
217 unit_ref_set(&s
->service
, u
);
219 return unit_add_two_dependencies(UNIT(s
), UNIT_BEFORE
, UNIT_TRIGGERS
, u
, false);
222 static bool have_non_accept_socket(Socket
*s
) {
230 LIST_FOREACH(port
, p
, s
->ports
) {
232 if (p
->type
!= SOCKET_SOCKET
)
235 if (!socket_address_can_accept(&p
->address
))
242 static int socket_add_mount_links(Socket
*s
) {
248 LIST_FOREACH(port
, p
, s
->ports
) {
249 const char *path
= NULL
;
251 if (p
->type
== SOCKET_SOCKET
)
252 path
= socket_address_get_path(&p
->address
);
253 else if (p
->type
== SOCKET_FIFO
|| p
->type
== SOCKET_SPECIAL
)
259 r
= unit_require_mounts_for(UNIT(s
), path
);
267 static int socket_add_device_link(Socket
*s
) {
272 if (!s
->bind_to_device
|| streq(s
->bind_to_device
, "lo"))
275 t
= strjoina("/sys/subsystem/net/devices/", s
->bind_to_device
);
276 return unit_add_node_link(UNIT(s
), t
, false);
279 static int socket_add_default_dependencies(Socket
*s
) {
283 r
= unit_add_dependency_by_name(UNIT(s
), UNIT_BEFORE
, SPECIAL_SOCKETS_TARGET
, NULL
, true);
287 if (UNIT(s
)->manager
->running_as
== SYSTEMD_SYSTEM
) {
288 r
= unit_add_two_dependencies_by_name(UNIT(s
), UNIT_AFTER
, UNIT_REQUIRES
, SPECIAL_SYSINIT_TARGET
, NULL
, true);
293 return unit_add_two_dependencies_by_name(UNIT(s
), UNIT_BEFORE
, UNIT_CONFLICTS
, SPECIAL_SHUTDOWN_TARGET
, NULL
, true);
296 _pure_
static bool socket_has_exec(Socket
*s
) {
300 for (i
= 0; i
< _SOCKET_EXEC_COMMAND_MAX
; i
++)
301 if (s
->exec_command
[i
])
307 static int socket_add_extras(Socket
*s
) {
313 if (have_non_accept_socket(s
)) {
315 if (!UNIT_DEREF(s
->service
)) {
318 r
= unit_load_related_unit(u
, ".service", &x
);
322 unit_ref_set(&s
->service
, x
);
325 r
= unit_add_two_dependencies(u
, UNIT_BEFORE
, UNIT_TRIGGERS
, UNIT_DEREF(s
->service
), true);
330 r
= socket_add_mount_links(s
);
334 r
= socket_add_device_link(s
);
338 r
= unit_patch_contexts(u
);
342 if (socket_has_exec(s
)) {
343 r
= unit_add_exec_dependencies(u
, &s
->exec_context
);
347 r
= unit_add_default_slice(u
, &s
->cgroup_context
);
352 if (u
->default_dependencies
) {
353 r
= socket_add_default_dependencies(s
);
361 static const char *socket_find_symlink_target(Socket
*s
) {
362 const char *found
= NULL
;
365 LIST_FOREACH(port
, p
, s
->ports
) {
366 const char *f
= NULL
;
375 if (p
->address
.sockaddr
.un
.sun_path
[0] != 0)
376 f
= p
->address
.sockaddr
.un
.sun_path
;
394 static int socket_verify(Socket
*s
) {
397 if (UNIT(s
)->load_state
!= UNIT_LOADED
)
401 log_unit_error(UNIT(s
)->id
, "%s lacks Listen setting. Refusing.", UNIT(s
)->id
);
405 if (s
->accept
&& have_non_accept_socket(s
)) {
406 log_unit_error(UNIT(s
)->id
, "%s configured for accepting sockets, but sockets are non-accepting. Refusing.",
411 if (s
->accept
&& s
->max_connections
<= 0) {
412 log_unit_error(UNIT(s
)->id
, "%s's MaxConnection setting too small. Refusing.", UNIT(s
)->id
);
416 if (s
->accept
&& UNIT_DEREF(s
->service
)) {
417 log_unit_error(UNIT(s
)->id
, "Explicit service configuration for accepting sockets not supported on %s. Refusing.", UNIT(s
)->id
);
421 if (s
->exec_context
.pam_name
&& s
->kill_context
.kill_mode
!= KILL_CONTROL_GROUP
) {
422 log_unit_error(UNIT(s
)->id
, "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s
)->id
);
426 if (!strv_isempty(s
->symlinks
) && !socket_find_symlink_target(s
)) {
427 log_unit_error(UNIT(s
)->id
, "%s has symlinks set but none or more than one node in the file system. Refusing.", UNIT(s
)->id
);
434 static int socket_load(Unit
*u
) {
435 Socket
*s
= SOCKET(u
);
439 assert(u
->load_state
== UNIT_STUB
);
441 r
= unit_load_fragment_and_dropin(u
);
445 if (u
->load_state
== UNIT_LOADED
) {
446 /* This is a new unit? Then let's add in some extras */
447 r
= socket_add_extras(s
);
452 return socket_verify(s
);
455 _const_
static const char* listen_lookup(int family
, int type
) {
457 if (family
== AF_NETLINK
)
458 return "ListenNetlink";
460 if (type
== SOCK_STREAM
)
461 return "ListenStream";
462 else if (type
== SOCK_DGRAM
)
463 return "ListenDatagram";
464 else if (type
== SOCK_SEQPACKET
)
465 return "ListenSequentialPacket";
467 assert_not_reached("Unknown socket type");
471 static void socket_dump(Unit
*u
, FILE *f
, const char *prefix
) {
472 char time_string
[FORMAT_TIMESPAN_MAX
];
474 Socket
*s
= SOCKET(u
);
481 prefix
= strempty(prefix
);
482 prefix2
= strjoina(prefix
, "\t");
485 "%sSocket State: %s\n"
487 "%sBindIPv6Only: %s\n"
489 "%sSocketMode: %04o\n"
490 "%sDirectoryMode: %04o\n"
494 "%sTransparent: %s\n"
496 "%sPassCredentials: %s\n"
497 "%sPassSecurity: %s\n"
498 "%sTCPCongestion: %s\n"
499 "%sRemoveOnStop: %s\n"
500 "%sSELinuxContextFromNet: %s\n",
501 prefix
, socket_state_to_string(s
->state
),
502 prefix
, socket_result_to_string(s
->result
),
503 prefix
, socket_address_bind_ipv6_only_to_string(s
->bind_ipv6_only
),
505 prefix
, s
->socket_mode
,
506 prefix
, s
->directory_mode
,
507 prefix
, yes_no(s
->keep_alive
),
508 prefix
, yes_no(s
->no_delay
),
509 prefix
, yes_no(s
->free_bind
),
510 prefix
, yes_no(s
->transparent
),
511 prefix
, yes_no(s
->broadcast
),
512 prefix
, yes_no(s
->pass_cred
),
513 prefix
, yes_no(s
->pass_sec
),
514 prefix
, strna(s
->tcp_congestion
),
515 prefix
, yes_no(s
->remove_on_stop
),
516 prefix
, yes_no(s
->selinux_context_from_net
));
518 if (s
->control_pid
> 0)
520 "%sControl PID: "PID_FMT
"\n",
521 prefix
, s
->control_pid
);
523 if (s
->bind_to_device
)
525 "%sBindToDevice: %s\n",
526 prefix
, s
->bind_to_device
);
531 "%sNConnections: %u\n"
532 "%sMaxConnections: %u\n",
533 prefix
, s
->n_accepted
,
534 prefix
, s
->n_connections
,
535 prefix
, s
->max_connections
);
537 if (s
->priority
>= 0)
540 prefix
, s
->priority
);
542 if (s
->receive_buffer
> 0)
544 "%sReceiveBuffer: %zu\n",
545 prefix
, s
->receive_buffer
);
547 if (s
->send_buffer
> 0)
549 "%sSendBuffer: %zu\n",
550 prefix
, s
->send_buffer
);
562 if (s
->pipe_size
> 0)
565 prefix
, s
->pipe_size
);
572 if (s
->mq_maxmsg
> 0)
574 "%sMessageQueueMaxMessages: %li\n",
575 prefix
, s
->mq_maxmsg
);
577 if (s
->mq_msgsize
> 0)
579 "%sMessageQueueMessageSize: %li\n",
580 prefix
, s
->mq_msgsize
);
585 prefix
, yes_no(s
->reuse_port
));
589 "%sSmackLabel: %s\n",
594 "%sSmackLabelIPIn: %s\n",
595 prefix
, s
->smack_ip_in
);
599 "%sSmackLabelIPOut: %s\n",
600 prefix
, s
->smack_ip_out
);
602 if (!isempty(s
->user
) || !isempty(s
->group
))
605 "%sOwnerGroup: %s\n",
606 prefix
, strna(s
->user
),
607 prefix
, strna(s
->group
));
609 if (s
->keep_alive_time
> 0)
611 "%sKeepAliveTimeSec: %s\n",
612 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_time
, USEC_PER_SEC
));
614 if (s
->keep_alive_interval
)
616 "%sKeepAliveIntervalSec: %s\n",
617 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->keep_alive_interval
, USEC_PER_SEC
));
619 if (s
->keep_alive_cnt
)
621 "%sKeepAliveProbes: %u\n",
622 prefix
, s
->keep_alive_cnt
);
626 "%sDeferAcceptSec: %s\n",
627 prefix
, format_timespan(time_string
, FORMAT_TIMESPAN_MAX
, s
->defer_accept
, USEC_PER_SEC
));
629 LIST_FOREACH(port
, p
, s
->ports
) {
631 if (p
->type
== SOCKET_SOCKET
) {
636 if ((r
= socket_address_print(&p
->address
, &k
)) < 0)
641 fprintf(f
, "%s%s: %s\n", prefix
, listen_lookup(socket_address_family(&p
->address
), p
->address
.type
), t
);
643 } else if (p
->type
== SOCKET_SPECIAL
)
644 fprintf(f
, "%sListenSpecial: %s\n", prefix
, p
->path
);
645 else if (p
->type
== SOCKET_MQUEUE
)
646 fprintf(f
, "%sListenMessageQueue: %s\n", prefix
, p
->path
);
648 fprintf(f
, "%sListenFIFO: %s\n", prefix
, p
->path
);
651 exec_context_dump(&s
->exec_context
, f
, prefix
);
652 kill_context_dump(&s
->kill_context
, f
, prefix
);
654 for (c
= 0; c
< _SOCKET_EXEC_COMMAND_MAX
; c
++) {
655 if (!s
->exec_command
[c
])
658 fprintf(f
, "%s-> %s:\n",
659 prefix
, socket_exec_command_to_string(c
));
661 exec_command_dump_list(s
->exec_command
[c
], f
, prefix2
);
665 static int instance_from_socket(int fd
, unsigned nr
, char **instance
) {
668 union sockaddr_union local
, remote
;
674 if (getsockname(fd
, &local
.sa
, &l
) < 0)
678 if (getpeername(fd
, &remote
.sa
, &l
) < 0)
681 switch (local
.sa
.sa_family
) {
685 a
= ntohl(local
.in
.sin_addr
.s_addr
),
686 b
= ntohl(remote
.in
.sin_addr
.s_addr
);
689 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
691 a
>> 24, (a
>> 16) & 0xFF, (a
>> 8) & 0xFF, a
& 0xFF,
692 ntohs(local
.in
.sin_port
),
693 b
>> 24, (b
>> 16) & 0xFF, (b
>> 8) & 0xFF, b
& 0xFF,
694 ntohs(remote
.in
.sin_port
)) < 0)
701 static const unsigned char ipv4_prefix
[] = {
702 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
705 if (memcmp(&local
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0 &&
706 memcmp(&remote
.in6
.sin6_addr
, ipv4_prefix
, sizeof(ipv4_prefix
)) == 0) {
708 *a
= local
.in6
.sin6_addr
.s6_addr
+12,
709 *b
= remote
.in6
.sin6_addr
.s6_addr
+12;
712 "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
714 a
[0], a
[1], a
[2], a
[3],
715 ntohs(local
.in6
.sin6_port
),
716 b
[0], b
[1], b
[2], b
[3],
717 ntohs(remote
.in6
.sin6_port
)) < 0)
720 char a
[INET6_ADDRSTRLEN
], b
[INET6_ADDRSTRLEN
];
725 inet_ntop(AF_INET6
, &local
.in6
.sin6_addr
, a
, sizeof(a
)),
726 ntohs(local
.in6
.sin6_port
),
727 inet_ntop(AF_INET6
, &remote
.in6
.sin6_addr
, b
, sizeof(b
)),
728 ntohs(remote
.in6
.sin6_port
)) < 0)
739 k
= getpeercred(fd
, &ucred
);
742 "%u-"PID_FMT
"-"UID_FMT
,
743 nr
, ucred
.pid
, ucred
.uid
) < 0)
745 } else if (k
== -ENODATA
) {
746 /* This handles the case where somebody is
747 * connecting from another pid/uid namespace
748 * (e.g. from outside of our container). */
760 assert_not_reached("Unhandled socket type.");
767 static void socket_close_fds(Socket
*s
) {
773 LIST_FOREACH(port
, p
, s
->ports
) {
775 p
->event_source
= sd_event_source_unref(p
->event_source
);
780 p
->fd
= safe_close(p
->fd
);
782 /* One little note: we should normally not delete any
783 * sockets in the file system here! After all some
784 * other process we spawned might still have a
785 * reference of this fd and wants to continue to use
786 * it. Therefore we delete sockets in the file system
787 * before we create a new one, not after we stopped
790 if (s
->remove_on_stop
) {
802 socket_address_unlink(&p
->address
);
811 if (s
->remove_on_stop
)
812 STRV_FOREACH(i
, s
->symlinks
)
816 static void socket_apply_socket_options(Socket
*s
, int fd
) {
823 int b
= s
->keep_alive
;
824 if (setsockopt(fd
, SOL_SOCKET
, SO_KEEPALIVE
, &b
, sizeof(b
)) < 0)
825 log_unit_warning(UNIT(s
)->id
, "SO_KEEPALIVE failed: %m");
828 if (s
->keep_alive_time
) {
829 int value
= s
->keep_alive_time
/ USEC_PER_SEC
;
830 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPIDLE
, &value
, sizeof(value
)) < 0)
831 log_unit_warning(UNIT(s
)->id
, "TCP_KEEPIDLE failed: %m");
834 if (s
->keep_alive_interval
) {
835 int value
= s
->keep_alive_interval
/ USEC_PER_SEC
;
836 if (setsockopt(fd
, SOL_TCP
, TCP_KEEPINTVL
, &value
, sizeof(value
)) < 0)
837 log_unit_warning(UNIT(s
)->id
, "TCP_KEEPINTVL failed: %m");
840 if (s
->keep_alive_cnt
) {
841 int value
= s
->keep_alive_cnt
;
842 if (setsockopt(fd
, SOL_SOCKET
, TCP_KEEPCNT
, &value
, sizeof(value
)) < 0)
843 log_unit_warning(UNIT(s
)->id
, "TCP_KEEPCNT failed: %m");
846 if (s
->defer_accept
) {
847 int value
= s
->defer_accept
/ USEC_PER_SEC
;
848 if (setsockopt(fd
, SOL_TCP
, TCP_DEFER_ACCEPT
, &value
, sizeof(value
)) < 0)
849 log_unit_warning(UNIT(s
)->id
, "TCP_DEFER_ACCEPT failed: %m");
854 if (setsockopt(fd
, SOL_TCP
, TCP_NODELAY
, &b
, sizeof(b
)) < 0)
855 log_unit_warning(UNIT(s
)->id
, "TCP_NODELAY failed: %m");
860 if (setsockopt(fd
, SOL_SOCKET
, SO_BROADCAST
, &one
, sizeof(one
)) < 0)
861 log_unit_warning(UNIT(s
)->id
, "SO_BROADCAST failed: %m");
866 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSCRED
, &one
, sizeof(one
)) < 0)
867 log_unit_warning(UNIT(s
)->id
, "SO_PASSCRED failed: %m");
872 if (setsockopt(fd
, SOL_SOCKET
, SO_PASSSEC
, &one
, sizeof(one
)) < 0)
873 log_unit_warning(UNIT(s
)->id
, "SO_PASSSEC failed: %m");
876 if (s
->priority
>= 0)
877 if (setsockopt(fd
, SOL_SOCKET
, SO_PRIORITY
, &s
->priority
, sizeof(s
->priority
)) < 0)
878 log_unit_warning(UNIT(s
)->id
, "SO_PRIORITY failed: %m");
880 if (s
->receive_buffer
> 0) {
881 int value
= (int) s
->receive_buffer
;
883 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
885 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUFFORCE
, &value
, sizeof(value
)) < 0)
886 if (setsockopt(fd
, SOL_SOCKET
, SO_RCVBUF
, &value
, sizeof(value
)) < 0)
887 log_unit_warning(UNIT(s
)->id
, "SO_RCVBUF failed: %m");
890 if (s
->send_buffer
> 0) {
891 int value
= (int) s
->send_buffer
;
892 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUFFORCE
, &value
, sizeof(value
)) < 0)
893 if (setsockopt(fd
, SOL_SOCKET
, SO_SNDBUF
, &value
, sizeof(value
)) < 0)
894 log_unit_warning(UNIT(s
)->id
, "SO_SNDBUF failed: %m");
898 if (setsockopt(fd
, SOL_SOCKET
, SO_MARK
, &s
->mark
, sizeof(s
->mark
)) < 0)
899 log_unit_warning(UNIT(s
)->id
, "SO_MARK failed: %m");
902 if (setsockopt(fd
, IPPROTO_IP
, IP_TOS
, &s
->ip_tos
, sizeof(s
->ip_tos
)) < 0)
903 log_unit_warning(UNIT(s
)->id
, "IP_TOS failed: %m");
905 if (s
->ip_ttl
>= 0) {
908 r
= setsockopt(fd
, IPPROTO_IP
, IP_TTL
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
910 if (socket_ipv6_is_supported())
911 x
= setsockopt(fd
, IPPROTO_IPV6
, IPV6_UNICAST_HOPS
, &s
->ip_ttl
, sizeof(s
->ip_ttl
));
914 errno
= EAFNOSUPPORT
;
918 log_unit_warning(UNIT(s
)->id
,
919 "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
922 if (s
->tcp_congestion
)
923 if (setsockopt(fd
, SOL_TCP
, TCP_CONGESTION
, s
->tcp_congestion
, strlen(s
->tcp_congestion
)+1) < 0)
924 log_unit_warning(UNIT(s
)->id
, "TCP_CONGESTION failed: %m");
927 int b
= s
->reuse_port
;
928 if (setsockopt(fd
, SOL_SOCKET
, SO_REUSEPORT
, &b
, sizeof(b
)) < 0)
929 log_unit_warning(UNIT(s
)->id
, "SO_REUSEPORT failed: %m");
932 if (s
->smack_ip_in
) {
933 r
= mac_smack_apply_ip_in_fd(fd
, s
->smack_ip_in
);
935 log_unit_error_errno(UNIT(s
)->id
, r
, "mac_smack_apply_ip_in_fd: %m");
938 if (s
->smack_ip_out
) {
939 r
= mac_smack_apply_ip_out_fd(fd
, s
->smack_ip_out
);
941 log_unit_error_errno(UNIT(s
)->id
, r
, "mac_smack_apply_ip_out_fd: %m");
945 static void socket_apply_fifo_options(Socket
*s
, int fd
) {
951 if (s
->pipe_size
> 0)
952 if (fcntl(fd
, F_SETPIPE_SZ
, s
->pipe_size
) < 0)
953 log_unit_warning(UNIT(s
)->id
, "F_SETPIPE_SZ: %m");
956 r
= mac_smack_apply_fd(fd
, s
->smack
);
958 log_unit_error_errno(UNIT(s
)->id
, r
, "mac_smack_apply_fd: %m");
962 static int fifo_address_create(
964 mode_t directory_mode
,
975 mkdir_parents_label(path
, directory_mode
);
977 r
= mac_selinux_create_file_prepare(path
, S_IFIFO
);
981 /* Enforce the right access mode for the fifo */
982 old_mask
= umask(~ socket_mode
);
984 /* Include the original umask in our mask */
985 umask(~socket_mode
| old_mask
);
987 r
= mkfifo(path
, socket_mode
);
990 if (r
< 0 && errno
!= EEXIST
) {
995 if ((fd
= open(path
, O_RDWR
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
)) < 0) {
1000 mac_selinux_create_file_clear();
1002 if (fstat(fd
, &st
) < 0) {
1007 if (!S_ISFIFO(st
.st_mode
) ||
1008 (st
.st_mode
& 0777) != (socket_mode
& ~old_mask
) ||
1009 st
.st_uid
!= getuid() ||
1010 st
.st_gid
!= getgid()) {
1020 mac_selinux_create_file_clear();
1026 static int special_address_create(
1036 fd
= open(path
, O_RDONLY
|O_CLOEXEC
|O_NOCTTY
|O_NONBLOCK
|O_NOFOLLOW
);
1042 if (fstat(fd
, &st
) < 0) {
1047 /* Check whether this is a /proc, /sys or /dev file or char device */
1048 if (!S_ISREG(st
.st_mode
) && !S_ISCHR(st
.st_mode
)) {
1062 static int mq_address_create(
1072 struct mq_attr _attr
, *attr
= NULL
;
1077 if (maxmsg
> 0 && msgsize
> 0) {
1079 _attr
.mq_flags
= O_NONBLOCK
;
1080 _attr
.mq_maxmsg
= maxmsg
;
1081 _attr
.mq_msgsize
= msgsize
;
1085 /* Enforce the right access mode for the mq */
1086 old_mask
= umask(~ mq_mode
);
1088 /* Include the original umask in our mask */
1089 umask(~mq_mode
| old_mask
);
1090 fd
= mq_open(path
, O_RDONLY
|O_CLOEXEC
|O_NONBLOCK
|O_CREAT
, mq_mode
, attr
);
1098 if (fstat(fd
, &st
) < 0) {
1103 if ((st
.st_mode
& 0777) != (mq_mode
& ~old_mask
) ||
1104 st
.st_uid
!= getuid() ||
1105 st
.st_gid
!= getgid()) {
1119 static int socket_symlink(Socket
*s
) {
1125 p
= socket_find_symlink_target(s
);
1129 STRV_FOREACH(i
, s
->symlinks
)
1130 symlink_label(p
, *i
);
1135 static int socket_open_fds(Socket
*s
) {
1139 bool know_label
= false;
1143 LIST_FOREACH(port
, p
, s
->ports
) {
1148 if (p
->type
== SOCKET_SOCKET
) {
1151 /* Figure out label, if we don't it know
1152 * yet. We do it once, for the first
1153 * socket where we need this and
1154 * remember it for the rest. */
1156 if (s
->selinux_context_from_net
) {
1157 /* Get it from the network label */
1159 r
= mac_selinux_get_our_label(&label
);
1160 if (r
< 0 && r
!= -EOPNOTSUPP
)
1164 /* Get it from the executable we are about to start */
1166 r
= socket_instantiate_service(s
);
1170 if (UNIT_ISSET(s
->service
) &&
1171 SERVICE(UNIT_DEREF(s
->service
))->exec_command
[SERVICE_EXEC_START
]) {
1172 r
= mac_selinux_get_create_label_from_exe(SERVICE(UNIT_DEREF(s
->service
))->exec_command
[SERVICE_EXEC_START
]->path
, &label
);
1173 if (r
< 0 && r
!= -EPERM
&& r
!= -EOPNOTSUPP
)
1181 r
= socket_address_listen(
1183 SOCK_CLOEXEC
|SOCK_NONBLOCK
,
1196 socket_apply_socket_options(s
, p
->fd
);
1199 } else if (p
->type
== SOCKET_SPECIAL
) {
1201 r
= special_address_create(
1207 } else if (p
->type
== SOCKET_FIFO
) {
1209 r
= fifo_address_create(
1217 socket_apply_fifo_options(s
, p
->fd
);
1220 } else if (p
->type
== SOCKET_MQUEUE
) {
1222 r
= mq_address_create(
1231 assert_not_reached("Unknown port type");
1234 mac_selinux_free(label
);
1238 socket_close_fds(s
);
1239 mac_selinux_free(label
);
1244 static void socket_unwatch_fds(Socket
*s
) {
1250 LIST_FOREACH(port
, p
, s
->ports
) {
1254 if (!p
->event_source
)
1257 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_OFF
);
1259 log_unit_debug(UNIT(s
)->id
, "Failed to disable event source.");
1263 static int socket_watch_fds(Socket
*s
) {
1269 LIST_FOREACH(port
, p
, s
->ports
) {
1273 if (p
->event_source
)
1274 r
= sd_event_source_set_enabled(p
->event_source
, SD_EVENT_ON
);
1276 r
= sd_event_add_io(UNIT(s
)->manager
->event
, &p
->event_source
, p
->fd
, EPOLLIN
, socket_dispatch_io
, p
);
1279 log_unit_warning_errno(UNIT(s
)->id
, r
, "Failed to watch listening fds: %m");
1283 (void) sd_event_source_set_description(p
->event_source
, "socket-port-io");
1289 socket_unwatch_fds(s
);
1293 static void socket_set_state(Socket
*s
, SocketState state
) {
1294 SocketState old_state
;
1297 old_state
= s
->state
;
1305 SOCKET_STOP_PRE_SIGTERM
,
1306 SOCKET_STOP_PRE_SIGKILL
,
1308 SOCKET_FINAL_SIGTERM
,
1309 SOCKET_FINAL_SIGKILL
)) {
1311 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1312 socket_unwatch_control_pid(s
);
1313 s
->control_command
= NULL
;
1314 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
1317 if (state
!= SOCKET_LISTENING
)
1318 socket_unwatch_fds(s
);
1326 SOCKET_STOP_PRE_SIGTERM
,
1327 SOCKET_STOP_PRE_SIGKILL
))
1328 socket_close_fds(s
);
1330 if (state
!= old_state
)
1331 log_unit_debug(UNIT(s
)->id
, "%s changed %s -> %s",
1332 UNIT(s
)->id
, socket_state_to_string(old_state
), socket_state_to_string(state
));
1334 unit_notify(UNIT(s
), state_translation_table
[old_state
], state_translation_table
[state
], true);
1337 static int socket_coldplug(Unit
*u
) {
1338 Socket
*s
= SOCKET(u
);
1342 assert(s
->state
== SOCKET_DEAD
);
1344 if (s
->deserialized_state
== s
->state
)
1347 if (IN_SET(s
->deserialized_state
,
1352 SOCKET_STOP_PRE_SIGTERM
,
1353 SOCKET_STOP_PRE_SIGKILL
,
1355 SOCKET_FINAL_SIGTERM
,
1356 SOCKET_FINAL_SIGKILL
)) {
1358 if (s
->control_pid
<= 0)
1361 r
= unit_watch_pid(UNIT(s
), s
->control_pid
);
1365 r
= socket_arm_timer(s
);
1370 if (IN_SET(s
->deserialized_state
,
1376 SOCKET_STOP_PRE_SIGTERM
,
1377 SOCKET_STOP_PRE_SIGKILL
)) {
1378 r
= socket_open_fds(s
);
1383 if (s
->deserialized_state
== SOCKET_LISTENING
) {
1384 r
= socket_watch_fds(s
);
1389 socket_set_state(s
, s
->deserialized_state
);
1393 static int socket_spawn(Socket
*s
, ExecCommand
*c
, pid_t
*_pid
) {
1394 _cleanup_free_
char **argv
= NULL
;
1397 ExecParameters exec_params
= {
1398 .apply_permissions
= true,
1399 .apply_chroot
= true,
1400 .apply_tty_stdin
= true,
1407 (void) unit_realize_cgroup(UNIT(s
));
1408 if (s
->reset_cpu_usage
) {
1409 (void) unit_reset_cpu_usage(UNIT(s
));
1410 s
->reset_cpu_usage
= false;
1413 r
= unit_setup_exec_runtime(UNIT(s
));
1417 r
= socket_arm_timer(s
);
1421 r
= unit_full_printf_strv(UNIT(s
), c
->argv
, &argv
);
1425 exec_params
.argv
= argv
;
1426 exec_params
.environment
= UNIT(s
)->manager
->environment
;
1427 exec_params
.confirm_spawn
= UNIT(s
)->manager
->confirm_spawn
;
1428 exec_params
.cgroup_supported
= UNIT(s
)->manager
->cgroup_supported
;
1429 exec_params
.cgroup_path
= UNIT(s
)->cgroup_path
;
1430 exec_params
.cgroup_delegate
= s
->cgroup_context
.delegate
;
1431 exec_params
.runtime_prefix
= manager_get_runtime_prefix(UNIT(s
)->manager
);
1432 exec_params
.unit_id
= UNIT(s
)->id
;
1442 r
= unit_watch_pid(UNIT(s
), pid
);
1444 /* FIXME: we need to do something here */
1451 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1455 static int socket_chown(Socket
*s
, pid_t
*_pid
) {
1459 r
= socket_arm_timer(s
);
1463 /* We have to resolve the user names out-of-process, hence
1464 * let's fork here. It's messy, but well, what can we do? */
1472 uid_t uid
= UID_INVALID
;
1473 gid_t gid
= GID_INVALID
;
1476 default_signals(SIGNALS_CRASH_HANDLER
, SIGNALS_IGNORE
, -1);
1477 ignore_signals(SIGPIPE
, -1);
1480 if (!isempty(s
->user
)) {
1481 const char *user
= s
->user
;
1483 r
= get_user_creds(&user
, &uid
, &gid
, NULL
, NULL
);
1490 if (!isempty(s
->group
)) {
1491 const char *group
= s
->group
;
1493 r
= get_group_creds(&group
, &gid
);
1500 LIST_FOREACH(port
, p
, s
->ports
) {
1501 const char *path
= NULL
;
1503 if (p
->type
== SOCKET_SOCKET
)
1504 path
= socket_address_get_path(&p
->address
);
1505 else if (p
->type
== SOCKET_FIFO
)
1511 if (chown(path
, uid
, gid
) < 0) {
1522 log_error_errno(r
, "Failed to chown socket at step %s: %m", exit_status_to_string(ret
, EXIT_STATUS_SYSTEMD
));
1527 r
= unit_watch_pid(UNIT(s
), pid
);
1535 s
->timer_event_source
= sd_event_source_unref(s
->timer_event_source
);
1539 static void socket_enter_dead(Socket
*s
, SocketResult f
) {
1542 if (f
!= SOCKET_SUCCESS
)
1545 exec_runtime_destroy(s
->exec_runtime
);
1546 s
->exec_runtime
= exec_runtime_unref(s
->exec_runtime
);
1548 exec_context_destroy_runtime_directory(&s
->exec_context
, manager_get_runtime_prefix(UNIT(s
)->manager
));
1550 socket_set_state(s
, s
->result
!= SOCKET_SUCCESS
? SOCKET_FAILED
: SOCKET_DEAD
);
1553 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
);
1555 static void socket_enter_stop_post(Socket
*s
, SocketResult f
) {
1559 if (f
!= SOCKET_SUCCESS
)
1562 socket_unwatch_control_pid(s
);
1563 s
->control_command_id
= SOCKET_EXEC_STOP_POST
;
1564 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_POST
];
1566 if (s
->control_command
) {
1567 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1571 socket_set_state(s
, SOCKET_STOP_POST
);
1573 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_SUCCESS
);
1578 log_unit_warning(UNIT(s
)->id
,
1579 "%s failed to run 'stop-post' task: %s",
1580 UNIT(s
)->id
, strerror(-r
));
1581 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
1584 static void socket_enter_signal(Socket
*s
, SocketState state
, SocketResult f
) {
1589 if (f
!= SOCKET_SUCCESS
)
1592 r
= unit_kill_context(
1595 (state
!= SOCKET_STOP_PRE_SIGTERM
&& state
!= SOCKET_FINAL_SIGTERM
) ?
1596 KILL_KILL
: KILL_TERMINATE
,
1604 r
= socket_arm_timer(s
);
1608 socket_set_state(s
, state
);
1609 } else if (state
== SOCKET_STOP_PRE_SIGTERM
)
1610 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_SUCCESS
);
1611 else if (state
== SOCKET_STOP_PRE_SIGKILL
)
1612 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
1613 else if (state
== SOCKET_FINAL_SIGTERM
)
1614 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_SUCCESS
);
1616 socket_enter_dead(s
, SOCKET_SUCCESS
);
1621 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to kill processes: %m", UNIT(s
)->id
);
1623 if (state
== SOCKET_STOP_PRE_SIGTERM
|| state
== SOCKET_STOP_PRE_SIGKILL
)
1624 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
1626 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
1629 static void socket_enter_stop_pre(Socket
*s
, SocketResult f
) {
1633 if (f
!= SOCKET_SUCCESS
)
1636 socket_unwatch_control_pid(s
);
1637 s
->control_command_id
= SOCKET_EXEC_STOP_PRE
;
1638 s
->control_command
= s
->exec_command
[SOCKET_EXEC_STOP_PRE
];
1640 if (s
->control_command
) {
1641 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1645 socket_set_state(s
, SOCKET_STOP_PRE
);
1647 socket_enter_stop_post(s
, SOCKET_SUCCESS
);
1652 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to run 'stop-pre' task: %m", UNIT(s
)->id
);
1653 socket_enter_stop_post(s
, SOCKET_FAILURE_RESOURCES
);
1656 static void socket_enter_listening(Socket
*s
) {
1660 r
= socket_watch_fds(s
);
1662 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to watch sockets: %m", UNIT(s
)->id
);
1666 socket_set_state(s
, SOCKET_LISTENING
);
1670 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1673 static void socket_enter_start_post(Socket
*s
) {
1677 socket_unwatch_control_pid(s
);
1678 s
->control_command_id
= SOCKET_EXEC_START_POST
;
1679 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_POST
];
1681 if (s
->control_command
) {
1682 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1684 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to run 'start-post' task: %m", UNIT(s
)->id
);
1688 socket_set_state(s
, SOCKET_START_POST
);
1690 socket_enter_listening(s
);
1695 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1698 static void socket_enter_start_chown(Socket
*s
) {
1703 r
= socket_open_fds(s
);
1705 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to listen on sockets: %m", UNIT(s
)->id
);
1709 if (!isempty(s
->user
) || !isempty(s
->group
)) {
1711 socket_unwatch_control_pid(s
);
1712 s
->control_command_id
= SOCKET_EXEC_START_CHOWN
;
1713 s
->control_command
= NULL
;
1715 r
= socket_chown(s
, &s
->control_pid
);
1717 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to fork 'start-chown' task: %m", UNIT(s
)->id
);
1721 socket_set_state(s
, SOCKET_START_CHOWN
);
1723 socket_enter_start_post(s
);
1728 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1731 static void socket_enter_start_pre(Socket
*s
) {
1735 socket_unwatch_control_pid(s
);
1736 s
->control_command_id
= SOCKET_EXEC_START_PRE
;
1737 s
->control_command
= s
->exec_command
[SOCKET_EXEC_START_PRE
];
1739 if (s
->control_command
) {
1740 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1742 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to run 'start-pre' task: %m", UNIT(s
)->id
);
1746 socket_set_state(s
, SOCKET_START_PRE
);
1748 socket_enter_start_chown(s
);
1753 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
1756 static void socket_enter_running(Socket
*s
, int cfd
) {
1757 _cleanup_bus_error_free_ sd_bus_error error
= SD_BUS_ERROR_NULL
;
1762 /* We don't take connections anymore if we are supposed to
1763 * shut down anyway */
1764 if (unit_stop_pending(UNIT(s
))) {
1766 log_unit_debug(UNIT(s
)->id
, "Suppressing connection request on %s since unit stop is scheduled.", UNIT(s
)->id
);
1771 /* Flush all sockets by closing and reopening them */
1772 socket_close_fds(s
);
1774 r
= socket_open_fds(s
);
1776 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to listen on sockets: %m", UNIT(s
)->id
);
1777 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1781 r
= socket_watch_fds(s
);
1783 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to watch sockets: %m", UNIT(s
)->id
);
1784 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1794 bool pending
= false;
1796 /* If there's already a start pending don't bother to
1798 SET_FOREACH(other
, UNIT(s
)->dependencies
[UNIT_TRIGGERS
], i
)
1799 if (unit_active_or_pending(other
)) {
1805 if (!UNIT_ISSET(s
->service
)) {
1806 log_unit_error(UNIT(s
)->id
, "%s: service to activate vanished, refusing activation.", UNIT(s
)->id
);
1811 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT_DEREF(s
->service
), JOB_REPLACE
, true, &error
, NULL
);
1816 socket_set_state(s
, SOCKET_RUNNING
);
1818 _cleanup_free_
char *prefix
= NULL
, *instance
= NULL
, *name
= NULL
;
1821 if (s
->n_connections
>= s
->max_connections
) {
1822 log_unit_warning(UNIT(s
)->id
, "%s: Too many incoming connections (%u)", UNIT(s
)->id
, s
->n_connections
);
1827 r
= socket_instantiate_service(s
);
1831 r
= instance_from_socket(cfd
, s
->n_accepted
, &instance
);
1836 /* ENOTCONN is legitimate if TCP RST was received.
1837 * This connection is over, but the socket unit lives on. */
1842 r
= unit_name_to_prefix(UNIT(s
)->id
, &prefix
);
1846 r
= unit_name_build(prefix
, instance
, ".service", &name
);
1850 r
= unit_add_name(UNIT_DEREF(s
->service
), name
);
1854 service
= SERVICE(UNIT_DEREF(s
->service
));
1855 unit_ref_unset(&s
->service
);
1858 UNIT(service
)->no_gc
= false;
1860 unit_choose_id(UNIT(service
), name
);
1862 r
= service_set_socket_fd(service
, cfd
, s
, s
->selinux_context_from_net
);
1867 s
->n_connections
++;
1869 r
= manager_add_job(UNIT(s
)->manager
, JOB_START
, UNIT(service
), JOB_REPLACE
, true, &error
, NULL
);
1873 /* Notify clients about changed counters */
1874 unit_add_to_dbus_queue(UNIT(s
));
1880 log_unit_warning(UNIT(s
)->id
, "%s failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
1881 UNIT(s
)->id
, cfd
>= 0 ? "template" : "non-template",
1882 bus_error_message(&error
, r
));
1884 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1888 static void socket_run_next(Socket
*s
) {
1892 assert(s
->control_command
);
1893 assert(s
->control_command
->command_next
);
1895 socket_unwatch_control_pid(s
);
1897 s
->control_command
= s
->control_command
->command_next
;
1899 r
= socket_spawn(s
, s
->control_command
, &s
->control_pid
);
1906 log_unit_warning_errno(UNIT(s
)->id
, r
, "%s failed to run next task: %m", UNIT(s
)->id
);
1908 if (s
->state
== SOCKET_START_POST
)
1909 socket_enter_stop_pre(s
, SOCKET_FAILURE_RESOURCES
);
1910 else if (s
->state
== SOCKET_STOP_POST
)
1911 socket_enter_dead(s
, SOCKET_FAILURE_RESOURCES
);
1913 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_RESOURCES
);
1916 static int socket_start(Unit
*u
) {
1917 Socket
*s
= SOCKET(u
);
1921 /* We cannot fulfill this request right now, try again later
1923 if (IN_SET(s
->state
,
1925 SOCKET_STOP_PRE_SIGKILL
,
1926 SOCKET_STOP_PRE_SIGTERM
,
1928 SOCKET_FINAL_SIGTERM
,
1929 SOCKET_FINAL_SIGKILL
))
1932 /* Already on it! */
1933 if (IN_SET(s
->state
,
1939 /* Cannot run this without the service being around */
1940 if (UNIT_ISSET(s
->service
)) {
1943 service
= SERVICE(UNIT_DEREF(s
->service
));
1945 if (UNIT(service
)->load_state
!= UNIT_LOADED
) {
1946 log_unit_error(u
->id
, "Socket service %s not loaded, refusing.", UNIT(service
)->id
);
1950 /* If the service is already active we cannot start the
1952 if (service
->state
!= SERVICE_DEAD
&&
1953 service
->state
!= SERVICE_FAILED
&&
1954 service
->state
!= SERVICE_AUTO_RESTART
) {
1955 log_unit_error(u
->id
, "Socket service %s already active, refusing.", UNIT(service
)->id
);
1960 assert(s
->state
== SOCKET_DEAD
|| s
->state
== SOCKET_FAILED
);
1962 s
->result
= SOCKET_SUCCESS
;
1963 s
->reset_cpu_usage
= true;
1965 socket_enter_start_pre(s
);
1970 static int socket_stop(Unit
*u
) {
1971 Socket
*s
= SOCKET(u
);
1976 if (IN_SET(s
->state
,
1978 SOCKET_STOP_PRE_SIGTERM
,
1979 SOCKET_STOP_PRE_SIGKILL
,
1981 SOCKET_FINAL_SIGTERM
,
1982 SOCKET_FINAL_SIGKILL
))
1985 /* If there's already something running we go directly into
1987 if (IN_SET(s
->state
,
1990 SOCKET_START_POST
)) {
1991 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_SUCCESS
);
1995 assert(s
->state
== SOCKET_LISTENING
|| s
->state
== SOCKET_RUNNING
);
1997 socket_enter_stop_pre(s
, SOCKET_SUCCESS
);
2001 static int socket_serialize(Unit
*u
, FILE *f
, FDSet
*fds
) {
2002 Socket
*s
= SOCKET(u
);
2010 unit_serialize_item(u
, f
, "state", socket_state_to_string(s
->state
));
2011 unit_serialize_item(u
, f
, "result", socket_result_to_string(s
->result
));
2012 unit_serialize_item_format(u
, f
, "n-accepted", "%u", s
->n_accepted
);
2014 if (s
->control_pid
> 0)
2015 unit_serialize_item_format(u
, f
, "control-pid", PID_FMT
, s
->control_pid
);
2017 if (s
->control_command_id
>= 0)
2018 unit_serialize_item(u
, f
, "control-command", socket_exec_command_to_string(s
->control_command_id
));
2020 LIST_FOREACH(port
, p
, s
->ports
) {
2026 copy
= fdset_put_dup(fds
, p
->fd
);
2030 if (p
->type
== SOCKET_SOCKET
) {
2031 _cleanup_free_
char *t
= NULL
;
2033 r
= socket_address_print(&p
->address
, &t
);
2037 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2038 unit_serialize_item_format(u
, f
, "netlink", "%i %s", copy
, t
);
2040 unit_serialize_item_format(u
, f
, "socket", "%i %i %s", copy
, p
->address
.type
, t
);
2042 } else if (p
->type
== SOCKET_SPECIAL
)
2043 unit_serialize_item_format(u
, f
, "special", "%i %s", copy
, p
->path
);
2044 else if (p
->type
== SOCKET_MQUEUE
)
2045 unit_serialize_item_format(u
, f
, "mqueue", "%i %s", copy
, p
->path
);
2047 assert(p
->type
== SOCKET_FIFO
);
2048 unit_serialize_item_format(u
, f
, "fifo", "%i %s", copy
, p
->path
);
2055 static int socket_deserialize_item(Unit
*u
, const char *key
, const char *value
, FDSet
*fds
) {
2056 Socket
*s
= SOCKET(u
);
2062 if (streq(key
, "state")) {
2065 state
= socket_state_from_string(value
);
2067 log_unit_debug(u
->id
, "Failed to parse state value %s", value
);
2069 s
->deserialized_state
= state
;
2070 } else if (streq(key
, "result")) {
2073 f
= socket_result_from_string(value
);
2075 log_unit_debug(u
->id
, "Failed to parse result value %s", value
);
2076 else if (f
!= SOCKET_SUCCESS
)
2079 } else if (streq(key
, "n-accepted")) {
2082 if (safe_atou(value
, &k
) < 0)
2083 log_unit_debug(u
->id
, "Failed to parse n-accepted value %s", value
);
2086 } else if (streq(key
, "control-pid")) {
2089 if (parse_pid(value
, &pid
) < 0)
2090 log_unit_debug(u
->id
, "Failed to parse control-pid value %s", value
);
2092 s
->control_pid
= pid
;
2093 } else if (streq(key
, "control-command")) {
2094 SocketExecCommand id
;
2096 id
= socket_exec_command_from_string(value
);
2098 log_unit_debug(u
->id
, "Failed to parse exec-command value %s", value
);
2100 s
->control_command_id
= id
;
2101 s
->control_command
= s
->exec_command
[id
];
2103 } else if (streq(key
, "fifo")) {
2107 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2108 log_unit_debug(u
->id
, "Failed to parse fifo value %s", value
);
2111 LIST_FOREACH(port
, p
, s
->ports
)
2112 if (p
->type
== SOCKET_FIFO
&&
2113 path_equal_or_files_same(p
->path
, value
+skip
))
2118 p
->fd
= fdset_remove(fds
, fd
);
2122 } else if (streq(key
, "special")) {
2126 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2127 log_unit_debug(u
->id
, "Failed to parse special value %s", value
);
2130 LIST_FOREACH(port
, p
, s
->ports
)
2131 if (p
->type
== SOCKET_SPECIAL
&&
2132 path_equal_or_files_same(p
->path
, value
+skip
))
2137 p
->fd
= fdset_remove(fds
, fd
);
2141 } else if (streq(key
, "mqueue")) {
2145 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2146 log_unit_debug(u
->id
, "Failed to parse mqueue value %s", value
);
2149 LIST_FOREACH(port
, p
, s
->ports
)
2150 if (p
->type
== SOCKET_MQUEUE
&&
2151 streq(p
->path
, value
+skip
))
2156 p
->fd
= fdset_remove(fds
, fd
);
2160 } else if (streq(key
, "socket")) {
2161 int fd
, type
, skip
= 0;
2164 if (sscanf(value
, "%i %i %n", &fd
, &type
, &skip
) < 2 || fd
< 0 || type
< 0 || !fdset_contains(fds
, fd
))
2165 log_unit_debug(u
->id
, "Failed to parse socket value %s", value
);
2168 LIST_FOREACH(port
, p
, s
->ports
)
2169 if (socket_address_is(&p
->address
, value
+skip
, type
))
2174 p
->fd
= fdset_remove(fds
, fd
);
2178 } else if (streq(key
, "netlink")) {
2182 if (sscanf(value
, "%i %n", &fd
, &skip
) < 1 || fd
< 0 || !fdset_contains(fds
, fd
))
2183 log_unit_debug(u
->id
, "Failed to parse socket value %s", value
);
2186 LIST_FOREACH(port
, p
, s
->ports
)
2187 if (socket_address_is_netlink(&p
->address
, value
+skip
))
2192 p
->fd
= fdset_remove(fds
, fd
);
2196 log_unit_debug(UNIT(s
)->id
, "Unknown serialization key '%s'", key
);
2201 static int socket_distribute_fds(Unit
*u
, FDSet
*fds
) {
2202 Socket
*s
= SOCKET(u
);
2207 LIST_FOREACH(port
, p
, s
->ports
) {
2211 if (p
->type
!= SOCKET_SOCKET
)
2217 FDSET_FOREACH(fd
, fds
, i
) {
2218 if (socket_address_matches_fd(&p
->address
, fd
)) {
2219 p
->fd
= fdset_remove(fds
, fd
);
2220 s
->deserialized_state
= SOCKET_LISTENING
;
2229 _pure_
static UnitActiveState
socket_active_state(Unit
*u
) {
2232 return state_translation_table
[SOCKET(u
)->state
];
2235 _pure_
static const char *socket_sub_state_to_string(Unit
*u
) {
2238 return socket_state_to_string(SOCKET(u
)->state
);
2241 const char* socket_port_type_to_string(SocketPort
*p
) {
2249 switch (p
->address
.type
) {
2257 case SOCK_SEQPACKET
:
2258 return "SequentialPacket";
2261 if (socket_address_family(&p
->address
) == AF_NETLINK
)
2268 case SOCKET_SPECIAL
:
2272 return "MessageQueue";
2282 _pure_
static bool socket_check_gc(Unit
*u
) {
2283 Socket
*s
= SOCKET(u
);
2287 return s
->n_connections
> 0;
2290 static int socket_dispatch_io(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
2291 SocketPort
*p
= userdata
;
2297 if (p
->socket
->state
!= SOCKET_LISTENING
)
2300 log_unit_debug(UNIT(p
->socket
)->id
, "Incoming traffic on %s", UNIT(p
->socket
)->id
);
2302 if (revents
!= EPOLLIN
) {
2304 if (revents
& EPOLLHUP
)
2305 log_unit_error(UNIT(p
->socket
)->id
, "%s: Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.",
2306 UNIT(p
->socket
)->id
);
2308 log_unit_error(UNIT(p
->socket
)->id
, "%s: Got unexpected poll event (0x%x) on socket.",
2309 UNIT(p
->socket
)->id
, revents
);
2314 if (p
->socket
->accept
&&
2315 p
->type
== SOCKET_SOCKET
&&
2316 socket_address_can_accept(&p
->address
)) {
2320 cfd
= accept4(fd
, NULL
, NULL
, SOCK_NONBLOCK
);
2326 log_unit_error(UNIT(p
->socket
)->id
, "Failed to accept socket: %m");
2333 socket_apply_socket_options(p
->socket
, cfd
);
2336 socket_enter_running(p
->socket
, cfd
);
2340 socket_enter_stop_pre(p
->socket
, SOCKET_FAILURE_RESOURCES
);
2344 static void socket_sigchld_event(Unit
*u
, pid_t pid
, int code
, int status
) {
2345 Socket
*s
= SOCKET(u
);
2351 if (pid
!= s
->control_pid
)
2356 if (is_clean_exit(code
, status
, NULL
))
2358 else if (code
== CLD_EXITED
)
2359 f
= SOCKET_FAILURE_EXIT_CODE
;
2360 else if (code
== CLD_KILLED
)
2361 f
= SOCKET_FAILURE_SIGNAL
;
2362 else if (code
== CLD_DUMPED
)
2363 f
= SOCKET_FAILURE_CORE_DUMP
;
2365 assert_not_reached("Unknown sigchld code");
2367 if (s
->control_command
) {
2368 exec_status_exit(&s
->control_command
->exec_status
, &s
->exec_context
, pid
, code
, status
);
2370 if (s
->control_command
->ignore
)
2374 log_unit_full(u
->id
,
2375 f
== SOCKET_SUCCESS
? LOG_DEBUG
: LOG_NOTICE
,
2376 "%s control process exited, code=%s status=%i",
2377 u
->id
, sigchld_code_to_string(code
), status
);
2379 if (f
!= SOCKET_SUCCESS
)
2382 if (s
->control_command
&&
2383 s
->control_command
->command_next
&&
2384 f
== SOCKET_SUCCESS
) {
2386 log_unit_debug(u
->id
,
2387 "%s running next command for state %s",
2388 u
->id
, socket_state_to_string(s
->state
));
2391 s
->control_command
= NULL
;
2392 s
->control_command_id
= _SOCKET_EXEC_COMMAND_INVALID
;
2394 /* No further commands for this step, so let's figure
2395 * out what to do next */
2397 log_unit_debug(u
->id
,
2398 "%s got final SIGCHLD for state %s",
2399 u
->id
, socket_state_to_string(s
->state
));
2403 case SOCKET_START_PRE
:
2404 if (f
== SOCKET_SUCCESS
)
2405 socket_enter_start_chown(s
);
2407 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, f
);
2410 case SOCKET_START_CHOWN
:
2411 if (f
== SOCKET_SUCCESS
)
2412 socket_enter_start_post(s
);
2414 socket_enter_stop_pre(s
, f
);
2417 case SOCKET_START_POST
:
2418 if (f
== SOCKET_SUCCESS
)
2419 socket_enter_listening(s
);
2421 socket_enter_stop_pre(s
, f
);
2424 case SOCKET_STOP_PRE
:
2425 case SOCKET_STOP_PRE_SIGTERM
:
2426 case SOCKET_STOP_PRE_SIGKILL
:
2427 socket_enter_stop_post(s
, f
);
2430 case SOCKET_STOP_POST
:
2431 case SOCKET_FINAL_SIGTERM
:
2432 case SOCKET_FINAL_SIGKILL
:
2433 socket_enter_dead(s
, f
);
2437 assert_not_reached("Uh, control process died at wrong time.");
2441 /* Notify clients about changed exit status */
2442 unit_add_to_dbus_queue(u
);
2445 static int socket_dispatch_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
2446 Socket
*s
= SOCKET(userdata
);
2449 assert(s
->timer_event_source
== source
);
2453 case SOCKET_START_PRE
:
2454 log_unit_warning(UNIT(s
)->id
, "%s starting timed out. Terminating.", UNIT(s
)->id
);
2455 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2458 case SOCKET_START_CHOWN
:
2459 case SOCKET_START_POST
:
2460 log_unit_warning(UNIT(s
)->id
, "%s starting timed out. Stopping.", UNIT(s
)->id
);
2461 socket_enter_stop_pre(s
, SOCKET_FAILURE_TIMEOUT
);
2464 case SOCKET_STOP_PRE
:
2465 log_unit_warning(UNIT(s
)->id
, "%s stopping timed out. Terminating.", UNIT(s
)->id
);
2466 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2469 case SOCKET_STOP_PRE_SIGTERM
:
2470 if (s
->kill_context
.send_sigkill
) {
2471 log_unit_warning(UNIT(s
)->id
, "%s stopping timed out. Killing.", UNIT(s
)->id
);
2472 socket_enter_signal(s
, SOCKET_STOP_PRE_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
2474 log_unit_warning(UNIT(s
)->id
, "%s stopping timed out. Skipping SIGKILL. Ignoring.", UNIT(s
)->id
);
2475 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
2479 case SOCKET_STOP_PRE_SIGKILL
:
2480 log_unit_warning(UNIT(s
)->id
, "%s still around after SIGKILL. Ignoring.", UNIT(s
)->id
);
2481 socket_enter_stop_post(s
, SOCKET_FAILURE_TIMEOUT
);
2484 case SOCKET_STOP_POST
:
2485 log_unit_warning(UNIT(s
)->id
, "%s stopping timed out (2). Terminating.", UNIT(s
)->id
);
2486 socket_enter_signal(s
, SOCKET_FINAL_SIGTERM
, SOCKET_FAILURE_TIMEOUT
);
2489 case SOCKET_FINAL_SIGTERM
:
2490 if (s
->kill_context
.send_sigkill
) {
2491 log_unit_warning(UNIT(s
)->id
, "%s stopping timed out (2). Killing.", UNIT(s
)->id
);
2492 socket_enter_signal(s
, SOCKET_FINAL_SIGKILL
, SOCKET_FAILURE_TIMEOUT
);
2494 log_unit_warning(UNIT(s
)->id
, "%s stopping timed out (2). Skipping SIGKILL. Ignoring.", UNIT(s
)->id
);
2495 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
2499 case SOCKET_FINAL_SIGKILL
:
2500 log_unit_warning(UNIT(s
)->id
, "%s still around after SIGKILL (2). Entering failed mode.", UNIT(s
)->id
);
2501 socket_enter_dead(s
, SOCKET_FAILURE_TIMEOUT
);
2505 assert_not_reached("Timeout at wrong time.");
2511 int socket_collect_fds(Socket
*s
, int **fds
, unsigned *n_fds
) {
2520 /* Called from the service code for requesting our fds */
2523 LIST_FOREACH(port
, p
, s
->ports
)
2533 rfds
= new(int, rn_fds
);
2538 LIST_FOREACH(port
, p
, s
->ports
)
2542 assert(k
== rn_fds
);
2550 static void socket_reset_failed(Unit
*u
) {
2551 Socket
*s
= SOCKET(u
);
2555 if (s
->state
== SOCKET_FAILED
)
2556 socket_set_state(s
, SOCKET_DEAD
);
2558 s
->result
= SOCKET_SUCCESS
;
2561 static void socket_notify_service_dead(Socket
*s
, bool failed_permanent
) {
2564 /* The service is dead. Dang!
2566 * This is strictly for one-instance-for-all-connections
2569 if (s
->state
== SOCKET_RUNNING
) {
2570 log_unit_debug(UNIT(s
)->id
, "%s got notified about service death (failed permanently: %s)", UNIT(s
)->id
, yes_no(failed_permanent
));
2571 if (failed_permanent
)
2572 socket_enter_stop_pre(s
, SOCKET_FAILURE_SERVICE_FAILED_PERMANENT
);
2574 socket_enter_listening(s
);
2578 void socket_connection_unref(Socket
*s
) {
2581 /* The service is dead. Yay!
2583 * This is strictly for one-instance-per-connection
2586 assert(s
->n_connections
> 0);
2589 log_unit_debug(UNIT(s
)->id
, "%s: One connection closed, %u left.", UNIT(s
)->id
, s
->n_connections
);
2592 static void socket_trigger_notify(Unit
*u
, Unit
*other
) {
2593 Socket
*s
= SOCKET(u
);
2599 /* Don't propagate state changes from the service if we are
2600 already down or accepting connections */
2601 if ((s
->state
!= SOCKET_RUNNING
&&
2602 s
->state
!= SOCKET_LISTENING
) ||
2606 if (other
->load_state
!= UNIT_LOADED
||
2607 other
->type
!= UNIT_SERVICE
)
2610 se
= SERVICE(other
);
2612 if (se
->state
== SERVICE_FAILED
)
2613 socket_notify_service_dead(s
, se
->result
== SERVICE_FAILURE_START_LIMIT
);
2615 if (se
->state
== SERVICE_DEAD
||
2616 se
->state
== SERVICE_FINAL_SIGTERM
||
2617 se
->state
== SERVICE_FINAL_SIGKILL
||
2618 se
->state
== SERVICE_AUTO_RESTART
)
2619 socket_notify_service_dead(s
, false);
2621 if (se
->state
== SERVICE_RUNNING
)
2622 socket_set_state(s
, SOCKET_RUNNING
);
2625 static int socket_kill(Unit
*u
, KillWho who
, int signo
, sd_bus_error
*error
) {
2626 return unit_kill_common(u
, who
, signo
, -1, SOCKET(u
)->control_pid
, error
);
2629 static int socket_get_timeout(Unit
*u
, uint64_t *timeout
) {
2630 Socket
*s
= SOCKET(u
);
2633 if (!s
->timer_event_source
)
2636 r
= sd_event_source_get_time(s
->timer_event_source
, timeout
);
2643 static const char* const socket_state_table
[_SOCKET_STATE_MAX
] = {
2644 [SOCKET_DEAD
] = "dead",
2645 [SOCKET_START_PRE
] = "start-pre",
2646 [SOCKET_START_CHOWN
] = "start-chown",
2647 [SOCKET_START_POST
] = "start-post",
2648 [SOCKET_LISTENING
] = "listening",
2649 [SOCKET_RUNNING
] = "running",
2650 [SOCKET_STOP_PRE
] = "stop-pre",
2651 [SOCKET_STOP_PRE_SIGTERM
] = "stop-pre-sigterm",
2652 [SOCKET_STOP_PRE_SIGKILL
] = "stop-pre-sigkill",
2653 [SOCKET_STOP_POST
] = "stop-post",
2654 [SOCKET_FINAL_SIGTERM
] = "final-sigterm",
2655 [SOCKET_FINAL_SIGKILL
] = "final-sigkill",
2656 [SOCKET_FAILED
] = "failed"
2659 DEFINE_STRING_TABLE_LOOKUP(socket_state
, SocketState
);
2661 static const char* const socket_exec_command_table
[_SOCKET_EXEC_COMMAND_MAX
] = {
2662 [SOCKET_EXEC_START_PRE
] = "StartPre",
2663 [SOCKET_EXEC_START_CHOWN
] = "StartChown",
2664 [SOCKET_EXEC_START_POST
] = "StartPost",
2665 [SOCKET_EXEC_STOP_PRE
] = "StopPre",
2666 [SOCKET_EXEC_STOP_POST
] = "StopPost"
2669 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command
, SocketExecCommand
);
2671 static const char* const socket_result_table
[_SOCKET_RESULT_MAX
] = {
2672 [SOCKET_SUCCESS
] = "success",
2673 [SOCKET_FAILURE_RESOURCES
] = "resources",
2674 [SOCKET_FAILURE_TIMEOUT
] = "timeout",
2675 [SOCKET_FAILURE_EXIT_CODE
] = "exit-code",
2676 [SOCKET_FAILURE_SIGNAL
] = "signal",
2677 [SOCKET_FAILURE_CORE_DUMP
] = "core-dump",
2678 [SOCKET_FAILURE_SERVICE_FAILED_PERMANENT
] = "service-failed-permanent"
2681 DEFINE_STRING_TABLE_LOOKUP(socket_result
, SocketResult
);
2683 const UnitVTable socket_vtable
= {
2684 .object_size
= sizeof(Socket
),
2685 .exec_context_offset
= offsetof(Socket
, exec_context
),
2686 .cgroup_context_offset
= offsetof(Socket
, cgroup_context
),
2687 .kill_context_offset
= offsetof(Socket
, kill_context
),
2688 .exec_runtime_offset
= offsetof(Socket
, exec_runtime
),
2694 .private_section
= "Socket",
2696 .init
= socket_init
,
2697 .done
= socket_done
,
2698 .load
= socket_load
,
2700 .coldplug
= socket_coldplug
,
2702 .dump
= socket_dump
,
2704 .start
= socket_start
,
2705 .stop
= socket_stop
,
2707 .kill
= socket_kill
,
2709 .get_timeout
= socket_get_timeout
,
2711 .serialize
= socket_serialize
,
2712 .deserialize_item
= socket_deserialize_item
,
2713 .distribute_fds
= socket_distribute_fds
,
2715 .active_state
= socket_active_state
,
2716 .sub_state_to_string
= socket_sub_state_to_string
,
2718 .check_gc
= socket_check_gc
,
2720 .sigchld_event
= socket_sigchld_event
,
2722 .trigger_notify
= socket_trigger_notify
,
2724 .reset_failed
= socket_reset_failed
,
2726 .bus_interface
= "org.freedesktop.systemd1.Socket",
2727 .bus_vtable
= bus_socket_vtable
,
2728 .bus_set_property
= bus_socket_set_property
,
2729 .bus_commit_properties
= bus_socket_commit_properties
,
2731 .status_message_formats
= {
2732 /*.starting_stopping = {
2733 [0] = "Starting socket %s...",
2734 [1] = "Stopping socket %s...",
2736 .finished_start_job
= {
2737 [JOB_DONE
] = "Listening on %s.",
2738 [JOB_FAILED
] = "Failed to listen on %s.",
2739 [JOB_DEPENDENCY
] = "Dependency failed for %s.",
2740 [JOB_TIMEOUT
] = "Timed out starting %s.",
2742 .finished_stop_job
= {
2743 [JOB_DONE
] = "Closed %s.",
2744 [JOB_FAILED
] = "Failed stopping %s.",
2745 [JOB_TIMEOUT
] = "Timed out stopping %s.",