1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 General Public License as published by
10 the Free Software Foundation; either version 2 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 General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
22 #include <sys/types.h>
27 #include <sys/epoll.h>
29 #include <arpa/inet.h>
30 #include <selinux/selinux.h>
35 #include "load-dropin.h"
36 #include "load-fragment.h"
38 #include "unit-name.h"
39 #include "dbus-socket.h"
42 #include "bus-errors.h"
44 static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
45 [SOCKET_DEAD] = UNIT_INACTIVE,
46 [SOCKET_START_PRE] = UNIT_ACTIVATING,
47 [SOCKET_START_POST] = UNIT_ACTIVATING,
48 [SOCKET_LISTENING] = UNIT_ACTIVE,
49 [SOCKET_RUNNING] = UNIT_ACTIVE,
50 [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
51 [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
52 [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
53 [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
54 [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
55 [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
56 [SOCKET_MAINTENANCE] = UNIT_MAINTENANCE
59 static void socket_init(Unit *u) {
60 Socket *s = SOCKET(u);
63 assert(u->meta.load_state == UNIT_STUB);
65 s->backlog = SOMAXCONN;
66 s->timeout_usec = DEFAULT_TIMEOUT_USEC;
67 s->directory_mode = 0755;
68 s->socket_mode = 0666;
70 s->max_connections = 64;
77 exec_context_init(&s->exec_context);
79 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
82 static void socket_unwatch_control_pid(Socket *s) {
85 if (s->control_pid <= 0)
88 unit_unwatch_pid(UNIT(s), s->control_pid);
92 static void socket_done(Unit *u) {
93 Socket *s = SOCKET(u);
99 while ((p = s->ports)) {
100 LIST_REMOVE(SocketPort, port, s->ports, p);
103 unit_unwatch_fd(UNIT(s), &p->fd_watch);
104 close_nointr_nofail(p->fd);
111 exec_context_done(&s->exec_context);
112 exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
113 s->control_command = NULL;
115 socket_unwatch_control_pid(s);
119 free(s->bind_to_device);
120 s->bind_to_device = NULL;
122 unit_unwatch_timer(u, &s->timer_watch);
124 /* Make sure no service instance refers to us anymore. */
125 LIST_FOREACH(units_per_type, i, u->meta.manager->units_per_type[UNIT_SERVICE]) {
126 Service *service = (Service *) i;
128 if (service->socket == s)
129 service->socket = NULL;
133 static int socket_instantiate_service(Socket *s) {
140 /* This fills in s->service if it isn't filled in yet. For
141 * Accept=yes sockets we create the next connection service
142 * here. For Accept=no this is mostly a NOP since the service
143 * is figured out at load time anyway. */
150 if (!(prefix = unit_name_to_prefix(s->meta.id)))
153 r = asprintf(&name, "%s@%u.service", prefix, s->n_accepted);
159 r = manager_load_unit(s->meta.manager, name, NULL, NULL, &u);
165 s->service = SERVICE(u);
169 static bool have_non_accept_socket(Socket *s) {
177 LIST_FOREACH(port, p, s->ports) {
179 if (p->type != SOCKET_SOCKET)
182 if (!socket_address_can_accept(&p->address))
189 static int socket_verify(Socket *s) {
192 if (s->meta.load_state != UNIT_LOADED)
196 log_error("%s lacks Listen setting. Refusing.", s->meta.id);
200 if (s->accept && have_non_accept_socket(s)) {
201 log_error("%s configured for accepting sockets, but sockets are non-accepting. Refusing.", s->meta.id);
205 if (s->accept && s->max_connections <= 0) {
206 log_error("%s's MaxConnection setting too small. Refusing.", s->meta.id);
210 if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
211 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
218 static bool socket_needs_mount(Socket *s, const char *prefix) {
223 LIST_FOREACH(port, p, s->ports) {
225 if (p->type == SOCKET_SOCKET) {
226 if (socket_address_needs_mount(&p->address, prefix))
229 assert(p->type == SOCKET_FIFO);
230 if (path_startswith(p->path, prefix))
238 int socket_add_one_mount_link(Socket *s, Mount *m) {
244 if (s->meta.load_state != UNIT_LOADED ||
245 m->meta.load_state != UNIT_LOADED)
248 if (!socket_needs_mount(s, m->where))
251 if ((r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
257 static int socket_add_mount_links(Socket *s) {
263 LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_MOUNT])
264 if ((r = socket_add_one_mount_link(s, (Mount*) other)) < 0)
270 static int socket_add_device_link(Socket *s) {
276 if (!s->bind_to_device)
279 if (asprintf(&t, "/sys/subsystem/net/devices/%s", s->bind_to_device) < 0)
282 r = unit_add_node_link(UNIT(s), t, false);
288 static int socket_add_default_dependencies(Socket *s) {
292 if (s->meta.manager->running_as == MANAGER_SYSTEM)
293 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 0)
296 return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
299 static int socket_load(Unit *u) {
300 Socket *s = SOCKET(u);
304 assert(u->meta.load_state == UNIT_STUB);
306 if ((r = unit_load_fragment_and_dropin(u)) < 0)
309 /* This is a new unit? Then let's add in some extras */
310 if (u->meta.load_state == UNIT_LOADED) {
312 if (have_non_accept_socket(s)) {
313 if ((r = unit_load_related_unit(u, ".service", (Unit**) &s->service)) < 0)
316 if ((r = unit_add_dependency(u, UNIT_BEFORE, UNIT(s->service), true)) < 0)
320 if ((r = socket_add_mount_links(s)) < 0)
323 if ((r = socket_add_device_link(s)) < 0)
326 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
329 if ((r = unit_add_default_cgroup(u)) < 0)
332 if (s->meta.default_dependencies)
333 if ((r = socket_add_default_dependencies(s)) < 0)
337 return socket_verify(s);
340 static const char* listen_lookup(int type) {
342 if (type == SOCK_STREAM)
343 return "ListenStream";
344 else if (type == SOCK_DGRAM)
345 return "ListenDatagram";
346 else if (type == SOCK_SEQPACKET)
347 return "ListenSequentialPacket";
349 assert_not_reached("Unknown socket type");
353 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
356 Socket *s = SOCKET(u);
364 p2 = strappend(prefix, "\t");
365 prefix2 = p2 ? p2 : prefix;
368 "%sSocket State: %s\n"
369 "%sBindIPv6Only: %s\n"
371 "%sSocketMode: %04o\n"
372 "%sDirectoryMode: %04o\n"
375 prefix, socket_state_to_string(s->state),
376 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
378 prefix, s->socket_mode,
379 prefix, s->directory_mode,
380 prefix, yes_no(s->keep_alive),
381 prefix, yes_no(s->free_bind));
383 if (s->control_pid > 0)
385 "%sControl PID: %lu\n",
386 prefix, (unsigned long) s->control_pid);
388 if (s->bind_to_device)
390 "%sBindToDevice: %s\n",
391 prefix, s->bind_to_device);
396 "%sNConnections: %u\n"
397 "%sMaxConnections: %u\n",
398 prefix, s->n_accepted,
399 prefix, s->n_connections,
400 prefix, s->max_connections);
402 if (s->priority >= 0)
405 prefix, s->priority);
407 if (s->receive_buffer > 0)
409 "%sReceiveBuffer: %zu\n",
410 prefix, s->receive_buffer);
412 if (s->send_buffer > 0)
414 "%sSendBuffer: %zu\n",
415 prefix, s->send_buffer);
427 if (s->pipe_size > 0)
430 prefix, s->pipe_size);
437 LIST_FOREACH(port, p, s->ports) {
439 if (p->type == SOCKET_SOCKET) {
444 if ((r = socket_address_print(&p->address, &k)) < 0)
449 fprintf(f, "%s%s: %s\n", prefix, listen_lookup(p->address.type), k);
452 fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
455 exec_context_dump(&s->exec_context, f, prefix);
457 for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
458 if (!s->exec_command[c])
461 fprintf(f, "%s-> %s:\n",
462 prefix, socket_exec_command_to_string(c));
464 exec_command_dump_list(s->exec_command[c], f, prefix2);
470 static int instance_from_socket(int fd, unsigned nr, char **instance) {
475 struct sockaddr_un un;
476 struct sockaddr_in in;
477 struct sockaddr_in6 in6;
478 struct sockaddr_storage storage;
485 if (getsockname(fd, &local.sa, &l) < 0)
489 if (getpeername(fd, &remote.sa, &l) < 0)
492 switch (local.sa.sa_family) {
496 a = ntohl(local.in.sin_addr.s_addr),
497 b = ntohl(remote.in.sin_addr.s_addr);
500 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
501 a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
502 ntohs(local.in.sin_port),
503 b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
504 ntohs(remote.in.sin_port)) < 0)
511 static const char ipv4_prefix[] = {
512 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
515 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
516 memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
518 *a = local.in6.sin6_addr.s6_addr+12,
519 *b = remote.in6.sin6_addr.s6_addr+12;
522 "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
523 a[0], a[1], a[2], a[3],
524 ntohs(local.in6.sin6_port),
525 b[0], b[1], b[2], b[3],
526 ntohs(remote.in6.sin6_port)) < 0)
529 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
533 inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
534 ntohs(local.in6.sin6_port),
535 inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
536 ntohs(remote.in6.sin6_port)) < 0)
547 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
553 (unsigned long) ucred.pid,
554 (unsigned long) ucred.uid) < 0)
561 assert_not_reached("Unhandled socket type.");
568 static void socket_close_fds(Socket *s) {
573 LIST_FOREACH(port, p, s->ports) {
577 unit_unwatch_fd(UNIT(s), &p->fd_watch);
578 close_nointr_nofail(p->fd);
580 /* One little note: we should never delete any sockets
581 * in the file system here! After all some other
582 * process we spawned might still have a reference of
583 * this fd and wants to continue to use it. Therefore
584 * we delete sockets in the file system before we
585 * create a new one, not after we stopped using
592 static void socket_apply_socket_options(Socket *s, int fd) {
597 int b = s->keep_alive;
598 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
599 log_warning("SO_KEEPALIVE failed: %m");
602 if (s->priority >= 0)
603 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
604 log_warning("SO_PRIORITY failed: %m");
606 if (s->receive_buffer > 0) {
607 int value = (int) s->receive_buffer;
608 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
609 log_warning("SO_RCVBUF failed: %m");
612 if (s->send_buffer > 0) {
613 int value = (int) s->send_buffer;
614 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
615 log_warning("SO_SNDBUF failed: %m");
619 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
620 log_warning("SO_MARK failed: %m");
623 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
624 log_warning("IP_TOS failed: %m");
626 if (s->ip_ttl >= 0) {
629 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
630 x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
633 log_warning("IP_TTL/IPV6_UNICAST_HOPS failed: %m");
637 static void socket_apply_fifo_options(Socket *s, int fd) {
641 if (s->pipe_size > 0)
642 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
643 log_warning("F_SETPIPE_SZ: %m");
646 static int selinux_getconfromexe(
648 security_context_t *newcon) {
650 security_context_t mycon = NULL, fcon = NULL;
651 security_class_t sclass;
658 r = getfilecon(exe, &fcon);
662 sclass = string_to_security_class("process");
663 r = security_compute_create(mycon, fcon, sclass, newcon);
674 static int selinux_getfileconfrompath(
675 const security_context_t scon,
678 security_context_t *fcon) {
680 security_context_t dir_con = NULL;
681 security_class_t sclass;
684 r = getfilecon(path, &dir_con);
687 if ((sclass = string_to_security_class(class)) != 0)
688 r = security_compute_create(scon, dir_con, sclass, fcon);
697 static int fifo_address_create(
699 mode_t directory_mode,
701 security_context_t scon,
707 security_context_t filecon = NULL;
712 mkdir_parents(path, directory_mode);
715 if (scon && ((r = selinux_getfileconfrompath(scon, path, "fifo_file", &filecon)) == 0)) {
716 r = setfscreatecon(filecon);
719 log_error("Failed to set SELinux file context (%s) on %s: %m", scon, path);
726 if (r < 0 && security_getenforce() == 1)
730 /* Enforce the right access mode for the fifo */
731 old_mask = umask(~ socket_mode);
733 /* Include the original umask in our mask */
734 umask(~socket_mode | old_mask);
736 r = mkfifo(path, socket_mode);
744 if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
749 setfscreatecon(NULL);
751 if (fstat(fd, &st) < 0) {
756 if (!S_ISFIFO(st.st_mode) ||
757 (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
758 st.st_uid != getuid() ||
759 st.st_gid != getgid()) {
769 setfscreatecon(NULL);
771 close_nointr_nofail(fd);
776 static int socket_open_fds(Socket *s) {
779 security_context_t scon = NULL;
783 if ((r = socket_instantiate_service(s)) < 0)
786 if (selinux_getconfromexe(s->service->exec_command[SERVICE_EXEC_START]->path, &scon) < 0) {
787 log_error("Failed to get SELinux exec context for %s \n", s->service->exec_command[SERVICE_EXEC_START]->path);
788 if (security_getenforce() == 1)
792 log_debug("SELinux Socket context for %s set to %s\n", s->service->exec_command[SERVICE_EXEC_START]->path, scon);
793 LIST_FOREACH(port, p, s->ports) {
798 if (p->type == SOCKET_SOCKET) {
800 if ((r = socket_address_listen(
812 socket_apply_socket_options(s, p->fd);
814 } else if (p->type == SOCKET_FIFO) {
816 if ((r = fifo_address_create(
824 socket_apply_fifo_options(s, p->fd);
827 assert_not_reached("Unknown port type");
839 static void socket_unwatch_fds(Socket *s) {
844 LIST_FOREACH(port, p, s->ports) {
848 unit_unwatch_fd(UNIT(s), &p->fd_watch);
852 static int socket_watch_fds(Socket *s) {
858 LIST_FOREACH(port, p, s->ports) {
862 p->fd_watch.socket_accept =
864 p->type == SOCKET_SOCKET &&
865 socket_address_can_accept(&p->address);
867 if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
874 socket_unwatch_fds(s);
878 static void socket_set_state(Socket *s, SocketState state) {
879 SocketState old_state;
882 old_state = s->state;
885 if (state != SOCKET_START_PRE &&
886 state != SOCKET_START_POST &&
887 state != SOCKET_STOP_PRE &&
888 state != SOCKET_STOP_PRE_SIGTERM &&
889 state != SOCKET_STOP_PRE_SIGKILL &&
890 state != SOCKET_STOP_POST &&
891 state != SOCKET_FINAL_SIGTERM &&
892 state != SOCKET_FINAL_SIGKILL) {
893 unit_unwatch_timer(UNIT(s), &s->timer_watch);
894 socket_unwatch_control_pid(s);
895 s->control_command = NULL;
896 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
899 if (state != SOCKET_LISTENING)
900 socket_unwatch_fds(s);
902 if (state != SOCKET_START_POST &&
903 state != SOCKET_LISTENING &&
904 state != SOCKET_RUNNING &&
905 state != SOCKET_STOP_PRE &&
906 state != SOCKET_STOP_PRE_SIGTERM &&
907 state != SOCKET_STOP_PRE_SIGKILL)
910 if (state != old_state)
911 log_debug("%s changed %s -> %s",
913 socket_state_to_string(old_state),
914 socket_state_to_string(state));
916 unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
919 static int socket_coldplug(Unit *u) {
920 Socket *s = SOCKET(u);
924 assert(s->state == SOCKET_DEAD);
926 if (s->deserialized_state != s->state) {
928 if (s->deserialized_state == SOCKET_START_PRE ||
929 s->deserialized_state == SOCKET_START_POST ||
930 s->deserialized_state == SOCKET_STOP_PRE ||
931 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
932 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
933 s->deserialized_state == SOCKET_STOP_POST ||
934 s->deserialized_state == SOCKET_FINAL_SIGTERM ||
935 s->deserialized_state == SOCKET_FINAL_SIGKILL) {
937 if (s->control_pid <= 0)
940 if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
943 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
947 if (s->deserialized_state == SOCKET_START_POST ||
948 s->deserialized_state == SOCKET_LISTENING ||
949 s->deserialized_state == SOCKET_RUNNING ||
950 s->deserialized_state == SOCKET_STOP_PRE ||
951 s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
952 s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
953 if ((r = socket_open_fds(s)) < 0)
956 if (s->deserialized_state == SOCKET_LISTENING)
957 if ((r = socket_watch_fds(s)) < 0)
960 socket_set_state(s, s->deserialized_state);
966 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
975 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
978 if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
987 s->meta.manager->environment,
991 s->meta.manager->confirm_spawn,
992 s->meta.cgroup_bondings,
999 if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
1000 /* FIXME: we need to do something here */
1008 unit_unwatch_timer(UNIT(s), &s->timer_watch);
1013 static void socket_enter_dead(Socket *s, bool success) {
1019 socket_set_state(s, s->failure ? SOCKET_MAINTENANCE : SOCKET_DEAD);
1022 static void socket_enter_signal(Socket *s, SocketState state, bool success);
1024 static void socket_enter_stop_post(Socket *s, bool success) {
1031 socket_unwatch_control_pid(s);
1033 s->control_command_id = SOCKET_EXEC_STOP_POST;
1035 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
1036 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1039 socket_set_state(s, SOCKET_STOP_POST);
1041 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, true);
1046 log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1047 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1050 static void socket_enter_signal(Socket *s, SocketState state, bool success) {
1059 if (s->exec_context.kill_mode != KILL_NONE) {
1060 int sig = (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1062 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1064 if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig)) < 0) {
1065 if (r != -EAGAIN && r != -ESRCH)
1071 if (!sent && s->control_pid > 0)
1072 if (kill(s->exec_context.kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH) {
1078 if (sent && s->control_pid > 0) {
1079 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1082 socket_set_state(s, state);
1083 } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1084 socket_enter_stop_post(s, true);
1086 socket_enter_dead(s, true);
1091 log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1093 if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1094 socket_enter_stop_post(s, false);
1096 socket_enter_dead(s, false);
1099 static void socket_enter_stop_pre(Socket *s, bool success) {
1106 socket_unwatch_control_pid(s);
1108 s->control_command_id = SOCKET_EXEC_STOP_PRE;
1110 if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
1111 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1114 socket_set_state(s, SOCKET_STOP_PRE);
1116 socket_enter_stop_post(s, true);
1121 log_warning("%s failed to run 'stop-pre' task: %s", s->meta.id, strerror(-r));
1122 socket_enter_stop_post(s, false);
1125 static void socket_enter_listening(Socket *s) {
1129 if ((r = socket_watch_fds(s)) < 0) {
1130 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1134 socket_set_state(s, SOCKET_LISTENING);
1138 socket_enter_stop_pre(s, false);
1141 static void socket_enter_start_post(Socket *s) {
1145 if ((r = socket_open_fds(s)) < 0) {
1146 log_warning("%s failed to listen on sockets: %s", s->meta.id, strerror(-r));
1150 socket_unwatch_control_pid(s);
1152 s->control_command_id = SOCKET_EXEC_START_POST;
1154 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
1155 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0) {
1156 log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1160 socket_set_state(s, SOCKET_START_POST);
1162 socket_enter_listening(s);
1167 socket_enter_stop_pre(s, false);
1170 static void socket_enter_start_pre(Socket *s) {
1174 socket_unwatch_control_pid(s);
1176 s->control_command_id = SOCKET_EXEC_START_PRE;
1178 if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
1179 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1182 socket_set_state(s, SOCKET_START_PRE);
1184 socket_enter_start_post(s);
1189 log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1190 socket_enter_dead(s, false);
1193 static void socket_enter_running(Socket *s, int cfd) {
1198 dbus_error_init(&error);
1200 /* We don't take connections anymore if we are supposed to
1201 * shut down anyway */
1202 if (s->meta.job && s->meta.job->type == JOB_STOP) {
1204 close_nointr_nofail(cfd);
1206 /* Flush all sockets by closing and reopening them */
1207 socket_close_fds(s);
1209 if ((r = socket_watch_fds(s)) < 0) {
1210 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1211 socket_enter_stop_pre(s, false);
1219 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s->service), JOB_REPLACE, true, &error, NULL)) < 0)
1222 socket_set_state(s, SOCKET_RUNNING);
1224 char *prefix, *instance = NULL, *name;
1227 if (s->n_connections >= s->max_connections) {
1228 log_warning("Too many incoming connections (%u)", s->n_connections);
1229 close_nointr_nofail(cfd);
1233 if ((r = socket_instantiate_service(s)) < 0)
1236 if ((r = instance_from_socket(cfd, s->n_accepted, &instance)) < 0)
1239 if (!(prefix = unit_name_to_prefix(s->meta.id))) {
1245 name = unit_name_build(prefix, instance, ".service");
1254 if ((r = unit_add_name(UNIT(s->service), name)) < 0) {
1259 service = s->service;
1263 unit_choose_id(UNIT(service), name);
1266 if ((r = service_set_socket_fd(service, cfd, s)) < 0)
1270 s->n_connections ++;
1272 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL)) < 0)
1279 log_warning("%s failed to queue socket startup job: %s", s->meta.id, bus_error(&error, r));
1280 socket_enter_stop_pre(s, false);
1283 close_nointr_nofail(cfd);
1285 dbus_error_free(&error);
1288 static void socket_run_next(Socket *s, bool success) {
1292 assert(s->control_command);
1293 assert(s->control_command->command_next);
1298 socket_unwatch_control_pid(s);
1300 s->control_command = s->control_command->command_next;
1302 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1308 log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1310 if (s->state == SOCKET_START_POST)
1311 socket_enter_stop_pre(s, false);
1312 else if (s->state == SOCKET_STOP_POST)
1313 socket_enter_dead(s, false);
1315 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1318 static int socket_start(Unit *u) {
1319 Socket *s = SOCKET(u);
1323 /* We cannot fulfill this request right now, try again later
1325 if (s->state == SOCKET_STOP_PRE ||
1326 s->state == SOCKET_STOP_PRE_SIGKILL ||
1327 s->state == SOCKET_STOP_PRE_SIGTERM ||
1328 s->state == SOCKET_STOP_POST ||
1329 s->state == SOCKET_FINAL_SIGTERM ||
1330 s->state == SOCKET_FINAL_SIGKILL)
1333 if (s->state == SOCKET_START_PRE ||
1334 s->state == SOCKET_START_POST)
1337 /* Cannot run this without the service being around */
1339 if (s->service->meta.load_state != UNIT_LOADED)
1342 /* If the service is alredy actvie we cannot start the
1344 if (s->service->state != SERVICE_DEAD &&
1345 s->service->state != SERVICE_MAINTENANCE &&
1346 s->service->state != SERVICE_AUTO_RESTART)
1350 assert(s->state == SOCKET_DEAD || s->state == SOCKET_MAINTENANCE);
1353 socket_enter_start_pre(s);
1357 static int socket_stop(Unit *u) {
1358 Socket *s = SOCKET(u);
1363 if (s->state == SOCKET_STOP_PRE ||
1364 s->state == SOCKET_STOP_PRE_SIGTERM ||
1365 s->state == SOCKET_STOP_PRE_SIGKILL ||
1366 s->state == SOCKET_STOP_POST ||
1367 s->state == SOCKET_FINAL_SIGTERM ||
1368 s->state == SOCKET_FINAL_SIGKILL)
1371 /* If there's already something running we go directly into
1373 if (s->state == SOCKET_START_PRE ||
1374 s->state == SOCKET_START_POST) {
1375 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, true);
1379 assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1381 socket_enter_stop_pre(s, true);
1385 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1386 Socket *s = SOCKET(u);
1394 unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1395 unit_serialize_item(u, f, "failure", yes_no(s->failure));
1396 unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1398 if (s->control_pid > 0)
1399 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1401 if (s->control_command_id >= 0)
1402 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1404 LIST_FOREACH(port, p, s->ports) {
1410 if ((copy = fdset_put_dup(fds, p->fd)) < 0)
1413 if (p->type == SOCKET_SOCKET) {
1416 if ((r = socket_address_print(&p->address, &t)) < 0)
1419 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1422 assert(p->type == SOCKET_FIFO);
1423 unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1430 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1431 Socket *s = SOCKET(u);
1439 if (streq(key, "state")) {
1442 if ((state = socket_state_from_string(value)) < 0)
1443 log_debug("Failed to parse state value %s", value);
1445 s->deserialized_state = state;
1446 } else if (streq(key, "failure")) {
1449 if ((b = parse_boolean(value)) < 0)
1450 log_debug("Failed to parse failure value %s", value);
1452 s->failure = b || s->failure;
1454 } else if (streq(key, "n-accepted")) {
1457 if ((r = safe_atou(value, &k)) < 0)
1458 log_debug("Failed to parse n-accepted value %s", value);
1461 } else if (streq(key, "control-pid")) {
1464 if ((r = parse_pid(value, &pid)) < 0)
1465 log_debug("Failed to parse control-pid value %s", value);
1467 s->control_pid = pid;
1468 } else if (streq(key, "control-command")) {
1469 SocketExecCommand id;
1471 if ((id = socket_exec_command_from_string(value)) < 0)
1472 log_debug("Failed to parse exec-command value %s", value);
1474 s->control_command_id = id;
1475 s->control_command = s->exec_command[id];
1477 } else if (streq(key, "fifo")) {
1481 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1482 log_debug("Failed to parse fifo value %s", value);
1485 LIST_FOREACH(port, p, s->ports)
1486 if (streq(p->path, value+skip))
1491 close_nointr_nofail(p->fd);
1492 p->fd = fdset_remove(fds, fd);
1496 } else if (streq(key, "socket")) {
1497 int fd, type, skip = 0;
1500 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
1501 log_debug("Failed to parse socket value %s", value);
1504 LIST_FOREACH(port, p, s->ports)
1505 if (socket_address_is(&p->address, value+skip, type))
1510 close_nointr_nofail(p->fd);
1511 p->fd = fdset_remove(fds, fd);
1516 log_debug("Unknown serialization key '%s'", key);
1521 static UnitActiveState socket_active_state(Unit *u) {
1524 return state_translation_table[SOCKET(u)->state];
1527 static const char *socket_sub_state_to_string(Unit *u) {
1530 return socket_state_to_string(SOCKET(u)->state);
1533 static bool socket_check_gc(Unit *u) {
1534 Socket *s = SOCKET(u);
1538 return s->n_connections > 0;
1541 static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
1542 Socket *s = SOCKET(u);
1548 if (s->state != SOCKET_LISTENING)
1551 log_debug("Incoming traffic on %s", u->meta.id);
1553 if (events != EPOLLIN) {
1554 log_error("Got invalid poll event on socket.");
1558 if (w->socket_accept) {
1561 if ((cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK)) < 0) {
1566 log_error("Failed to accept socket: %m");
1573 socket_apply_socket_options(s, cfd);
1576 socket_enter_running(s, cfd);
1580 socket_enter_stop_pre(s, false);
1583 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1584 Socket *s = SOCKET(u);
1590 if (pid != s->control_pid)
1595 success = is_clean_exit(code, status);
1597 if (s->control_command) {
1598 exec_status_exit(&s->control_command->exec_status, pid, code, status);
1600 if (s->control_command->ignore)
1604 log_full(success ? LOG_DEBUG : LOG_NOTICE,
1605 "%s control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1606 s->failure = s->failure || !success;
1608 if (s->control_command && s->control_command->command_next && success) {
1609 log_debug("%s running next command for state %s", u->meta.id, socket_state_to_string(s->state));
1610 socket_run_next(s, success);
1612 s->control_command = NULL;
1613 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1615 /* No further commands for this step, so let's figure
1616 * out what to do next */
1618 log_debug("%s got final SIGCHLD for state %s", u->meta.id, socket_state_to_string(s->state));
1622 case SOCKET_START_PRE:
1624 socket_enter_start_post(s);
1626 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1629 case SOCKET_START_POST:
1631 socket_enter_listening(s);
1633 socket_enter_stop_pre(s, false);
1636 case SOCKET_STOP_PRE:
1637 case SOCKET_STOP_PRE_SIGTERM:
1638 case SOCKET_STOP_PRE_SIGKILL:
1639 socket_enter_stop_post(s, success);
1642 case SOCKET_STOP_POST:
1643 case SOCKET_FINAL_SIGTERM:
1644 case SOCKET_FINAL_SIGKILL:
1645 socket_enter_dead(s, success);
1649 assert_not_reached("Uh, control process died at wrong time.");
1654 static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
1655 Socket *s = SOCKET(u);
1658 assert(elapsed == 1);
1659 assert(w == &s->timer_watch);
1663 case SOCKET_START_PRE:
1664 log_warning("%s starting timed out. Terminating.", u->meta.id);
1665 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1667 case SOCKET_START_POST:
1668 log_warning("%s starting timed out. Stopping.", u->meta.id);
1669 socket_enter_stop_pre(s, false);
1672 case SOCKET_STOP_PRE:
1673 log_warning("%s stopping timed out. Terminating.", u->meta.id);
1674 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, false);
1677 case SOCKET_STOP_PRE_SIGTERM:
1678 log_warning("%s stopping timed out. Killing.", u->meta.id);
1679 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, false);
1682 case SOCKET_STOP_PRE_SIGKILL:
1683 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
1684 socket_enter_stop_post(s, false);
1687 case SOCKET_STOP_POST:
1688 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
1689 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1692 case SOCKET_FINAL_SIGTERM:
1693 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
1694 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, false);
1697 case SOCKET_FINAL_SIGKILL:
1698 log_warning("%s still around after SIGKILL (2). Entering maintenance mode.", u->meta.id);
1699 socket_enter_dead(s, false);
1703 assert_not_reached("Timeout at wrong time.");
1707 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
1716 /* Called from the service code for requesting our fds */
1719 LIST_FOREACH(port, p, s->ports)
1723 if (!(rfds = new(int, rn_fds)) < 0)
1727 LIST_FOREACH(port, p, s->ports)
1731 assert(k == rn_fds);
1739 void socket_notify_service_dead(Socket *s) {
1742 /* The service is dead. Dang!
1744 * This is strictly for one-instance-for-all-connections
1747 if (s->state == SOCKET_RUNNING) {
1748 log_debug("%s got notified about service death.", s->meta.id);
1749 socket_enter_listening(s);
1753 void socket_connection_unref(Socket *s) {
1756 /* The service is dead. Yay!
1758 * This is strictly for one-onstance-per-connection
1761 assert(s->n_connections > 0);
1764 log_debug("%s: One connection closed, %u left.", s->meta.id, s->n_connections);
1767 static void socket_reset_maintenance(Unit *u) {
1768 Socket *s = SOCKET(u);
1772 if (s->state == SOCKET_MAINTENANCE)
1773 socket_set_state(s, SOCKET_DEAD);
1778 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
1779 [SOCKET_DEAD] = "dead",
1780 [SOCKET_START_PRE] = "start-pre",
1781 [SOCKET_START_POST] = "start-post",
1782 [SOCKET_LISTENING] = "listening",
1783 [SOCKET_RUNNING] = "running",
1784 [SOCKET_STOP_PRE] = "stop-pre",
1785 [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
1786 [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
1787 [SOCKET_STOP_POST] = "stop-post",
1788 [SOCKET_FINAL_SIGTERM] = "final-sigterm",
1789 [SOCKET_FINAL_SIGKILL] = "final-sigkill",
1790 [SOCKET_MAINTENANCE] = "maintenance"
1793 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
1795 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
1796 [SOCKET_EXEC_START_PRE] = "StartPre",
1797 [SOCKET_EXEC_START_POST] = "StartPost",
1798 [SOCKET_EXEC_STOP_PRE] = "StopPre",
1799 [SOCKET_EXEC_STOP_POST] = "StopPost"
1802 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
1804 const UnitVTable socket_vtable = {
1805 .suffix = ".socket",
1807 .init = socket_init,
1808 .done = socket_done,
1809 .load = socket_load,
1811 .coldplug = socket_coldplug,
1813 .dump = socket_dump,
1815 .start = socket_start,
1816 .stop = socket_stop,
1818 .serialize = socket_serialize,
1819 .deserialize_item = socket_deserialize_item,
1821 .active_state = socket_active_state,
1822 .sub_state_to_string = socket_sub_state_to_string,
1824 .check_gc = socket_check_gc,
1826 .fd_event = socket_fd_event,
1827 .sigchld_event = socket_sigchld_event,
1828 .timer_event = socket_timer_event,
1830 .reset_maintenance = socket_reset_maintenance,
1832 .bus_message_handler = bus_socket_message_handler