chiark / gitweb /
socket: don't crash if the .service unit for a .socket unit is not found
[elogind.git] / src / socket.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2010 Lennart Poettering
7
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.
12
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.
17
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/>.
20 ***/
21
22 #include <sys/types.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <sys/epoll.h>
28 #include <signal.h>
29 #include <arpa/inet.h>
30
31 #include "unit.h"
32 #include "socket.h"
33 #include "netinet/tcp.h"
34 #include "log.h"
35 #include "load-dropin.h"
36 #include "load-fragment.h"
37 #include "strv.h"
38 #include "unit-name.h"
39 #include "dbus-socket.h"
40 #include "missing.h"
41 #include "special.h"
42 #include "bus-errors.h"
43 #include "label.h"
44 #include "exit-status.h"
45
46 static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
47         [SOCKET_DEAD] = UNIT_INACTIVE,
48         [SOCKET_START_PRE] = UNIT_ACTIVATING,
49         [SOCKET_START_POST] = UNIT_ACTIVATING,
50         [SOCKET_LISTENING] = UNIT_ACTIVE,
51         [SOCKET_RUNNING] = UNIT_ACTIVE,
52         [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
53         [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
54         [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
55         [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
56         [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
57         [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
58         [SOCKET_FAILED] = UNIT_FAILED
59 };
60
61 static void socket_init(Unit *u) {
62         Socket *s = SOCKET(u);
63
64         assert(u);
65         assert(u->meta.load_state == UNIT_STUB);
66
67         s->backlog = SOMAXCONN;
68         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
69         s->directory_mode = 0755;
70         s->socket_mode = 0666;
71
72         s->max_connections = 64;
73
74         s->priority = -1;
75         s->ip_tos = -1;
76         s->ip_ttl = -1;
77         s->mark = -1;
78
79         exec_context_init(&s->exec_context);
80
81         s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
82 }
83
84 static void socket_unwatch_control_pid(Socket *s) {
85         assert(s);
86
87         if (s->control_pid <= 0)
88                 return;
89
90         unit_unwatch_pid(UNIT(s), s->control_pid);
91         s->control_pid = 0;
92 }
93
94 static void socket_done(Unit *u) {
95         Socket *s = SOCKET(u);
96         SocketPort *p;
97         Meta *i;
98
99         assert(s);
100
101         while ((p = s->ports)) {
102                 LIST_REMOVE(SocketPort, port, s->ports, p);
103
104                 if (p->fd >= 0) {
105                         unit_unwatch_fd(UNIT(s), &p->fd_watch);
106                         close_nointr_nofail(p->fd);
107                 }
108
109                 free(p->path);
110                 free(p);
111         }
112
113         exec_context_done(&s->exec_context);
114         exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
115         s->control_command = NULL;
116
117         socket_unwatch_control_pid(s);
118
119         s->service = NULL;
120
121         free(s->tcp_congestion);
122         s->tcp_congestion = NULL;
123
124         free(s->bind_to_device);
125         s->bind_to_device = NULL;
126
127         unit_unwatch_timer(u, &s->timer_watch);
128
129         /* Make sure no service instance refers to us anymore. */
130         LIST_FOREACH(units_per_type, i, u->meta.manager->units_per_type[UNIT_SERVICE]) {
131                 Service *service = (Service *) i;
132
133                 if (service->accept_socket == s)
134                         service->accept_socket = NULL;
135
136                 set_remove(service->configured_sockets, s);
137         }
138 }
139
140 static int socket_instantiate_service(Socket *s) {
141         char *prefix, *name;
142         int r;
143         Unit *u;
144
145         assert(s);
146
147         /* This fills in s->service if it isn't filled in yet. For
148          * Accept=yes sockets we create the next connection service
149          * here. For Accept=no this is mostly a NOP since the service
150          * is figured out at load time anyway. */
151
152         if (s->service)
153                 return 0;
154
155         assert(s->accept);
156
157         if (!(prefix = unit_name_to_prefix(s->meta.id)))
158                 return -ENOMEM;
159
160         r = asprintf(&name, "%s@%u.service", prefix, s->n_accepted);
161         free(prefix);
162
163         if (r < 0)
164                 return -ENOMEM;
165
166         r = manager_load_unit(s->meta.manager, name, NULL, NULL, &u);
167         free(name);
168
169         if (r < 0)
170                 return r;
171
172         u->meta.no_gc = true;
173         s->service = SERVICE(u);
174         return 0;
175 }
176
177 static bool have_non_accept_socket(Socket *s) {
178         SocketPort *p;
179
180         assert(s);
181
182         if (!s->accept)
183                 return true;
184
185         LIST_FOREACH(port, p, s->ports) {
186
187                 if (p->type != SOCKET_SOCKET)
188                         return true;
189
190                 if (!socket_address_can_accept(&p->address))
191                         return true;
192         }
193
194         return false;
195 }
196
197 static int socket_verify(Socket *s) {
198         assert(s);
199
200         if (s->meta.load_state != UNIT_LOADED)
201                 return 0;
202
203         if (!s->ports) {
204                 log_error("%s lacks Listen setting. Refusing.", s->meta.id);
205                 return -EINVAL;
206         }
207
208         if (s->accept && have_non_accept_socket(s)) {
209                 log_error("%s configured for accepting sockets, but sockets are non-accepting. Refusing.", s->meta.id);
210                 return -EINVAL;
211         }
212
213         if (s->accept && s->max_connections <= 0) {
214                 log_error("%s's MaxConnection setting too small. Refusing.", s->meta.id);
215                 return -EINVAL;
216         }
217
218         if (s->accept && s->service) {
219                 log_error("Explicit service configuration for accepting sockets not supported on %s. Refusing.", s->meta.id);
220                 return -EINVAL;
221         }
222
223         if (s->exec_context.pam_name && s->exec_context.kill_mode != KILL_CONTROL_GROUP) {
224                 log_error("%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", s->meta.id);
225                 return -EINVAL;
226         }
227
228         return 0;
229 }
230
231 static bool socket_needs_mount(Socket *s, const char *prefix) {
232         SocketPort *p;
233
234         assert(s);
235
236         LIST_FOREACH(port, p, s->ports) {
237
238                 if (p->type == SOCKET_SOCKET) {
239                         if (socket_address_needs_mount(&p->address, prefix))
240                                 return true;
241                 } else {
242                         assert(p->type == SOCKET_FIFO);
243                         if (path_startswith(p->path, prefix))
244                                 return true;
245                 }
246         }
247
248         return false;
249 }
250
251 int socket_add_one_mount_link(Socket *s, Mount *m) {
252         int r;
253
254         assert(s);
255         assert(m);
256
257         if (s->meta.load_state != UNIT_LOADED ||
258             m->meta.load_state != UNIT_LOADED)
259                 return 0;
260
261         if (!socket_needs_mount(s, m->where))
262                 return 0;
263
264         if ((r = unit_add_two_dependencies(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, UNIT(m), true)) < 0)
265                 return r;
266
267         return 0;
268 }
269
270 static int socket_add_mount_links(Socket *s) {
271         Meta *other;
272         int r;
273
274         assert(s);
275
276         LIST_FOREACH(units_per_type, other, s->meta.manager->units_per_type[UNIT_MOUNT])
277                 if ((r = socket_add_one_mount_link(s, (Mount*) other)) < 0)
278                         return r;
279
280         return 0;
281 }
282
283 static int socket_add_device_link(Socket *s) {
284         char *t;
285         int r;
286
287         assert(s);
288
289         if (!s->bind_to_device)
290                 return 0;
291
292         if (asprintf(&t, "/sys/subsystem/net/devices/%s", s->bind_to_device) < 0)
293                 return -ENOMEM;
294
295         r = unit_add_node_link(UNIT(s), t, false);
296         free(t);
297
298         return r;
299 }
300
301 static int socket_add_default_dependencies(Socket *s) {
302         int r;
303         assert(s);
304
305         if (s->meta.manager->running_as == MANAGER_SYSTEM) {
306                 if ((r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true)) < 0)
307                         return r;
308
309                 if ((r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true)) < 0)
310                         return r;
311         }
312
313         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
314 }
315
316 static int socket_load(Unit *u) {
317         Socket *s = SOCKET(u);
318         int r;
319
320         assert(u);
321         assert(u->meta.load_state == UNIT_STUB);
322
323         if ((r = unit_load_fragment_and_dropin(u)) < 0)
324                 return r;
325
326         /* This is a new unit? Then let's add in some extras */
327         if (u->meta.load_state == UNIT_LOADED) {
328
329                 if (have_non_accept_socket(s)) {
330
331                         if (!s->service)
332                                 if ((r = unit_load_related_unit(u, ".service", (Unit**) &s->service)) < 0)
333                                         return r;
334
335                         if ((r = unit_add_dependency(u, UNIT_BEFORE, UNIT(s->service), true)) < 0)
336                                 return r;
337                 }
338
339                 if ((r = socket_add_mount_links(s)) < 0)
340                         return r;
341
342                 if ((r = socket_add_device_link(s)) < 0)
343                         return r;
344
345                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
346                         return r;
347
348                 if ((r = unit_add_default_cgroups(u)) < 0)
349                         return r;
350
351                 if (s->meta.default_dependencies)
352                         if ((r = socket_add_default_dependencies(s)) < 0)
353                                 return r;
354         }
355
356         return socket_verify(s);
357 }
358
359 static const char* listen_lookup(int type) {
360
361         if (type == SOCK_STREAM)
362                 return "ListenStream";
363         else if (type == SOCK_DGRAM)
364                 return "ListenDatagram";
365         else if (type == SOCK_SEQPACKET)
366                 return "ListenSequentialPacket";
367
368         assert_not_reached("Unknown socket type");
369         return NULL;
370 }
371
372 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
373
374         SocketExecCommand c;
375         Socket *s = SOCKET(u);
376         SocketPort *p;
377         const char *prefix2;
378         char *p2;
379
380         assert(s);
381         assert(f);
382
383         p2 = strappend(prefix, "\t");
384         prefix2 = p2 ? p2 : prefix;
385
386         fprintf(f,
387                 "%sSocket State: %s\n"
388                 "%sBindIPv6Only: %s\n"
389                 "%sBacklog: %u\n"
390                 "%sSocketMode: %04o\n"
391                 "%sDirectoryMode: %04o\n"
392                 "%sKeepAlive: %s\n"
393                 "%sFreeBind: %s\n"
394                 "%sTCPCongestion: %s\n",
395                 prefix, socket_state_to_string(s->state),
396                 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
397                 prefix, s->backlog,
398                 prefix, s->socket_mode,
399                 prefix, s->directory_mode,
400                 prefix, yes_no(s->keep_alive),
401                 prefix, yes_no(s->free_bind),
402                 prefix, strna(s->tcp_congestion));
403
404         if (s->control_pid > 0)
405                 fprintf(f,
406                         "%sControl PID: %lu\n",
407                         prefix, (unsigned long) s->control_pid);
408
409         if (s->bind_to_device)
410                 fprintf(f,
411                         "%sBindToDevice: %s\n",
412                         prefix, s->bind_to_device);
413
414         if (s->accept)
415                 fprintf(f,
416                         "%sAccepted: %u\n"
417                         "%sNConnections: %u\n"
418                         "%sMaxConnections: %u\n",
419                         prefix, s->n_accepted,
420                         prefix, s->n_connections,
421                         prefix, s->max_connections);
422
423         if (s->priority >= 0)
424                 fprintf(f,
425                         "%sPriority: %i\n",
426                         prefix, s->priority);
427
428         if (s->receive_buffer > 0)
429                 fprintf(f,
430                         "%sReceiveBuffer: %zu\n",
431                         prefix, s->receive_buffer);
432
433         if (s->send_buffer > 0)
434                 fprintf(f,
435                         "%sSendBuffer: %zu\n",
436                         prefix, s->send_buffer);
437
438         if (s->ip_tos >= 0)
439                 fprintf(f,
440                         "%sIPTOS: %i\n",
441                         prefix, s->ip_tos);
442
443         if (s->ip_ttl >= 0)
444                 fprintf(f,
445                         "%sIPTTL: %i\n",
446                         prefix, s->ip_ttl);
447
448         if (s->pipe_size > 0)
449                 fprintf(f,
450                         "%sPipeSize: %zu\n",
451                         prefix, s->pipe_size);
452
453         if (s->mark >= 0)
454                 fprintf(f,
455                         "%sMark: %i\n",
456                         prefix, s->mark);
457
458         LIST_FOREACH(port, p, s->ports) {
459
460                 if (p->type == SOCKET_SOCKET) {
461                         const char *t;
462                         int r;
463                         char *k = NULL;
464
465                         if ((r = socket_address_print(&p->address, &k)) < 0)
466                                 t = strerror(-r);
467                         else
468                                 t = k;
469
470                         fprintf(f, "%s%s: %s\n", prefix, listen_lookup(p->address.type), t);
471                         free(k);
472                 } else
473                         fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
474         }
475
476         exec_context_dump(&s->exec_context, f, prefix);
477
478         for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
479                 if (!s->exec_command[c])
480                         continue;
481
482                 fprintf(f, "%s-> %s:\n",
483                         prefix, socket_exec_command_to_string(c));
484
485                 exec_command_dump_list(s->exec_command[c], f, prefix2);
486         }
487
488         free(p2);
489 }
490
491 static int instance_from_socket(int fd, unsigned nr, char **instance) {
492         socklen_t l;
493         char *r;
494         union {
495                 struct sockaddr sa;
496                 struct sockaddr_un un;
497                 struct sockaddr_in in;
498                 struct sockaddr_in6 in6;
499                 struct sockaddr_storage storage;
500         } local, remote;
501
502         assert(fd >= 0);
503         assert(instance);
504
505         l = sizeof(local);
506         if (getsockname(fd, &local.sa, &l) < 0)
507                 return -errno;
508
509         l = sizeof(remote);
510         if (getpeername(fd, &remote.sa, &l) < 0)
511                 return -errno;
512
513         switch (local.sa.sa_family) {
514
515         case AF_INET: {
516                 uint32_t
517                         a = ntohl(local.in.sin_addr.s_addr),
518                         b = ntohl(remote.in.sin_addr.s_addr);
519
520                 if (asprintf(&r,
521                              "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
522                              a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
523                              ntohs(local.in.sin_port),
524                              b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
525                              ntohs(remote.in.sin_port)) < 0)
526                         return -ENOMEM;
527
528                 break;
529         }
530
531         case AF_INET6: {
532                 static const char ipv4_prefix[] = {
533                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
534                 };
535
536                 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
537                     memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
538                         const uint8_t
539                                 *a = local.in6.sin6_addr.s6_addr+12,
540                                 *b = remote.in6.sin6_addr.s6_addr+12;
541
542                         if (asprintf(&r,
543                                      "%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
544                                      a[0], a[1], a[2], a[3],
545                                      ntohs(local.in6.sin6_port),
546                                      b[0], b[1], b[2], b[3],
547                                      ntohs(remote.in6.sin6_port)) < 0)
548                                 return -ENOMEM;
549                 } else {
550                         char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
551
552                         if (asprintf(&r,
553                                      "%s:%u-%s:%u",
554                                      inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
555                                      ntohs(local.in6.sin6_port),
556                                      inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
557                                      ntohs(remote.in6.sin6_port)) < 0)
558                                 return -ENOMEM;
559                 }
560
561                 break;
562         }
563
564         case AF_UNIX: {
565                 struct ucred ucred;
566
567                 l = sizeof(ucred);
568                 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
569                         return -errno;
570
571                 if (asprintf(&r,
572                              "%u-%lu-%lu",
573                              nr,
574                              (unsigned long) ucred.pid,
575                              (unsigned long) ucred.uid) < 0)
576                         return -ENOMEM;
577
578                 break;
579         }
580
581         default:
582                 assert_not_reached("Unhandled socket type.");
583         }
584
585         *instance = r;
586         return 0;
587 }
588
589 static void socket_close_fds(Socket *s) {
590         SocketPort *p;
591
592         assert(s);
593
594         LIST_FOREACH(port, p, s->ports) {
595                 if (p->fd < 0)
596                         continue;
597
598                 unit_unwatch_fd(UNIT(s), &p->fd_watch);
599                 close_nointr_nofail(p->fd);
600
601                 /* One little note: we should never delete any sockets
602                  * in the file system here! After all some other
603                  * process we spawned might still have a reference of
604                  * this fd and wants to continue to use it. Therefore
605                  * we delete sockets in the file system before we
606                  * create a new one, not after we stopped using
607                  * one! */
608
609                 p->fd = -1;
610         }
611 }
612
613 static void socket_apply_socket_options(Socket *s, int fd) {
614         assert(s);
615         assert(fd >= 0);
616
617         if (s->keep_alive) {
618                 int b = s->keep_alive;
619                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
620                         log_warning("SO_KEEPALIVE failed: %m");
621         }
622
623         if (s->priority >= 0)
624                 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
625                         log_warning("SO_PRIORITY failed: %m");
626
627         if (s->receive_buffer > 0) {
628                 int value = (int) s->receive_buffer;
629                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
630                         log_warning("SO_RCVBUF failed: %m");
631         }
632
633         if (s->send_buffer > 0) {
634                 int value = (int) s->send_buffer;
635                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
636                         log_warning("SO_SNDBUF failed: %m");
637         }
638
639         if (s->mark >= 0)
640                 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
641                         log_warning("SO_MARK failed: %m");
642
643         if (s->ip_tos >= 0)
644                 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
645                         log_warning("IP_TOS failed: %m");
646
647         if (s->ip_ttl >= 0) {
648                 int r, x;
649
650                 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
651
652                 if (socket_ipv6_is_supported())
653                         x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
654                 else {
655                         x = -1;
656                         errno = EAFNOSUPPORT;
657                 }
658
659                 if (r < 0 && x < 0)
660                         log_warning("IP_TTL/IPV6_UNICAST_HOPS failed: %m");
661         }
662
663         if (s->tcp_congestion)
664                 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
665                         log_warning("TCP_CONGESTION failed: %m");
666 }
667
668 static void socket_apply_fifo_options(Socket *s, int fd) {
669         assert(s);
670         assert(fd >= 0);
671
672         if (s->pipe_size > 0)
673                 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
674                         log_warning("F_SETPIPE_SZ: %m");
675 }
676
677
678 static int fifo_address_create(
679                 const char *path,
680                 mode_t directory_mode,
681                 mode_t socket_mode,
682                 int *_fd) {
683
684         int fd = -1, r = 0;
685         struct stat st;
686         mode_t old_mask;
687
688         assert(path);
689         assert(_fd);
690
691         mkdir_parents(path, directory_mode);
692
693         if ((r = label_fifofile_set(path)) < 0)
694                 goto fail;
695
696         /* Enforce the right access mode for the fifo */
697         old_mask = umask(~ socket_mode);
698
699         /* Include the original umask in our mask */
700         umask(~socket_mode | old_mask);
701
702         r = mkfifo(path, socket_mode);
703         umask(old_mask);
704
705         if (r < 0) {
706                 r = -errno;
707                 goto fail;
708         }
709
710         if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
711                 r = -errno;
712                 goto fail;
713         }
714
715         label_file_clear();
716
717         if (fstat(fd, &st) < 0) {
718                 r = -errno;
719                 goto fail;
720         }
721
722         if (!S_ISFIFO(st.st_mode) ||
723             (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
724             st.st_uid != getuid() ||
725             st.st_gid != getgid()) {
726
727                 r = -EEXIST;
728                 goto fail;
729         }
730
731         *_fd = fd;
732         return 0;
733
734 fail:
735         label_file_clear();
736
737         if (fd >= 0)
738                 close_nointr_nofail(fd);
739
740         return r;
741 }
742
743 static int socket_open_fds(Socket *s) {
744         SocketPort *p;
745         int r;
746         char *label = NULL;
747         bool know_label = false;
748
749         assert(s);
750
751         LIST_FOREACH(port, p, s->ports) {
752
753                 if (p->fd >= 0)
754                         continue;
755
756                 if (p->type == SOCKET_SOCKET) {
757
758                         if (!know_label) {
759
760                                 if ((r = socket_instantiate_service(s)) < 0)
761                                         return r;
762
763                                 if (s->service && s->service->exec_command[SERVICE_EXEC_START])
764                                         if ((r = label_get_socket_label_from_exe(s->service->exec_command[SERVICE_EXEC_START]->path, &label)) < 0)
765                                                 return r;
766
767                                 know_label = true;
768                         }
769
770                         if ((r = socket_address_listen(
771                                              &p->address,
772                                              s->backlog,
773                                              s->bind_ipv6_only,
774                                              s->bind_to_device,
775                                              s->free_bind,
776                                              s->directory_mode,
777                                              s->socket_mode,
778                                              label,
779                                              &p->fd)) < 0)
780                                 goto rollback;
781
782                         socket_apply_socket_options(s, p->fd);
783
784                 } else  if (p->type == SOCKET_FIFO) {
785
786                         if ((r = fifo_address_create(
787                                              p->path,
788                                              s->directory_mode,
789                                              s->socket_mode,
790                                              &p->fd)) < 0)
791                                 goto rollback;
792
793                         socket_apply_fifo_options(s, p->fd);
794
795                 } else
796                         assert_not_reached("Unknown port type");
797         }
798
799         label_free(label);
800         return 0;
801
802 rollback:
803         socket_close_fds(s);
804         label_free(label);
805         return r;
806 }
807
808 static void socket_unwatch_fds(Socket *s) {
809         SocketPort *p;
810
811         assert(s);
812
813         LIST_FOREACH(port, p, s->ports) {
814                 if (p->fd < 0)
815                         continue;
816
817                 unit_unwatch_fd(UNIT(s), &p->fd_watch);
818         }
819 }
820
821 static int socket_watch_fds(Socket *s) {
822         SocketPort *p;
823         int r;
824
825         assert(s);
826
827         LIST_FOREACH(port, p, s->ports) {
828                 if (p->fd < 0)
829                         continue;
830
831                 p->fd_watch.socket_accept =
832                         s->accept &&
833                         p->type == SOCKET_SOCKET &&
834                         socket_address_can_accept(&p->address);
835
836                 if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
837                         goto fail;
838         }
839
840         return 0;
841
842 fail:
843         socket_unwatch_fds(s);
844         return r;
845 }
846
847 static void socket_set_state(Socket *s, SocketState state) {
848         SocketState old_state;
849         assert(s);
850
851         old_state = s->state;
852         s->state = state;
853
854         if (state != SOCKET_START_PRE &&
855             state != SOCKET_START_POST &&
856             state != SOCKET_STOP_PRE &&
857             state != SOCKET_STOP_PRE_SIGTERM &&
858             state != SOCKET_STOP_PRE_SIGKILL &&
859             state != SOCKET_STOP_POST &&
860             state != SOCKET_FINAL_SIGTERM &&
861             state != SOCKET_FINAL_SIGKILL) {
862                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
863                 socket_unwatch_control_pid(s);
864                 s->control_command = NULL;
865                 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
866         }
867
868         if (state != SOCKET_LISTENING)
869                 socket_unwatch_fds(s);
870
871         if (state != SOCKET_START_POST &&
872             state != SOCKET_LISTENING &&
873             state != SOCKET_RUNNING &&
874             state != SOCKET_STOP_PRE &&
875             state != SOCKET_STOP_PRE_SIGTERM &&
876             state != SOCKET_STOP_PRE_SIGKILL)
877                 socket_close_fds(s);
878
879         if (state != old_state)
880                 log_debug("%s changed %s -> %s",
881                           s->meta.id,
882                           socket_state_to_string(old_state),
883                           socket_state_to_string(state));
884
885         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
886 }
887
888 static int socket_coldplug(Unit *u) {
889         Socket *s = SOCKET(u);
890         int r;
891
892         assert(s);
893         assert(s->state == SOCKET_DEAD);
894
895         if (s->deserialized_state != s->state) {
896
897                 if (s->deserialized_state == SOCKET_START_PRE ||
898                     s->deserialized_state == SOCKET_START_POST ||
899                     s->deserialized_state == SOCKET_STOP_PRE ||
900                     s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
901                     s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
902                     s->deserialized_state == SOCKET_STOP_POST ||
903                     s->deserialized_state == SOCKET_FINAL_SIGTERM ||
904                     s->deserialized_state == SOCKET_FINAL_SIGKILL) {
905
906                         if (s->control_pid <= 0)
907                                 return -EBADMSG;
908
909                         if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
910                                 return r;
911
912                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
913                                 return r;
914                 }
915
916                 if (s->deserialized_state == SOCKET_START_POST ||
917                     s->deserialized_state == SOCKET_LISTENING ||
918                     s->deserialized_state == SOCKET_RUNNING ||
919                     s->deserialized_state == SOCKET_STOP_PRE ||
920                     s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
921                     s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
922                         if ((r = socket_open_fds(s)) < 0)
923                                 return r;
924
925                 if (s->deserialized_state == SOCKET_LISTENING)
926                         if ((r = socket_watch_fds(s)) < 0)
927                                 return r;
928
929                 socket_set_state(s, s->deserialized_state);
930         }
931
932         return 0;
933 }
934
935 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
936         pid_t pid;
937         int r;
938         char **argv;
939
940         assert(s);
941         assert(c);
942         assert(_pid);
943
944         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
945                 goto fail;
946
947         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
948                 r = -ENOMEM;
949                 goto fail;
950         }
951
952         r = exec_spawn(c,
953                        argv,
954                        &s->exec_context,
955                        NULL, 0,
956                        s->meta.manager->environment,
957                        true,
958                        true,
959                        true,
960                        s->meta.manager->confirm_spawn,
961                        s->meta.cgroup_bondings,
962                        &pid);
963
964         strv_free(argv);
965         if (r < 0)
966                 goto fail;
967
968         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
969                 /* FIXME: we need to do something here */
970                 goto fail;
971
972         *_pid = pid;
973
974         return 0;
975
976 fail:
977         unit_unwatch_timer(UNIT(s), &s->timer_watch);
978
979         return r;
980 }
981
982 static void socket_enter_dead(Socket *s, bool success) {
983         assert(s);
984
985         if (!success)
986                 s->failure = true;
987
988         socket_set_state(s, s->failure ? SOCKET_FAILED : SOCKET_DEAD);
989 }
990
991 static void socket_enter_signal(Socket *s, SocketState state, bool success);
992
993 static void socket_enter_stop_post(Socket *s, bool success) {
994         int r;
995         assert(s);
996
997         if (!success)
998                 s->failure = true;
999
1000         socket_unwatch_control_pid(s);
1001
1002         s->control_command_id = SOCKET_EXEC_STOP_POST;
1003
1004         if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
1005                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1006                         goto fail;
1007
1008                 socket_set_state(s, SOCKET_STOP_POST);
1009         } else
1010                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, true);
1011
1012         return;
1013
1014 fail:
1015         log_warning("%s failed to run 'stop-post' task: %s", s->meta.id, strerror(-r));
1016         socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1017 }
1018
1019 static void socket_enter_signal(Socket *s, SocketState state, bool success) {
1020         int r;
1021         Set *pid_set = NULL;
1022         bool wait_for_exit = false;
1023
1024         assert(s);
1025
1026         if (!success)
1027                 s->failure = true;
1028
1029         if (s->exec_context.kill_mode != KILL_NONE) {
1030                 int sig = (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_FINAL_SIGTERM) ? s->exec_context.kill_signal : SIGKILL;
1031
1032                 if (s->control_pid > 0) {
1033                         if (kill(s->exec_context.kill_mode == KILL_PROCESS_GROUP ?
1034                                  -s->control_pid :
1035                                  s->control_pid, sig) < 0 && errno != ESRCH)
1036
1037                                 log_warning("Failed to kill control process %li: %m", (long) s->control_pid);
1038                         else
1039                                 wait_for_exit = true;
1040                 }
1041
1042                 if (s->exec_context.kill_mode == KILL_CONTROL_GROUP) {
1043
1044                         if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func))) {
1045                                 r = -ENOMEM;
1046                                 goto fail;
1047                         }
1048
1049                         /* Exclude the control pid from being killed via the cgroup */
1050                         if (s->control_pid > 0)
1051                                 if ((r = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0)
1052                                         goto fail;
1053
1054                         if ((r = cgroup_bonding_kill_list(s->meta.cgroup_bondings, sig, pid_set)) < 0) {
1055                                 if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1056                                         log_warning("Failed to kill control group: %s", strerror(-r));
1057                         } else if (r > 0)
1058                                 wait_for_exit = true;
1059
1060                         set_free(pid_set);
1061                 }
1062         }
1063
1064         if (wait_for_exit) {
1065                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
1066                         goto fail;
1067
1068                 socket_set_state(s, state);
1069         } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1070                 socket_enter_stop_post(s, true);
1071         else
1072                 socket_enter_dead(s, true);
1073
1074         return;
1075
1076 fail:
1077         log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
1078
1079         if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1080                 socket_enter_stop_post(s, false);
1081         else
1082                 socket_enter_dead(s, false);
1083
1084         if (pid_set)
1085                 set_free(pid_set);
1086 }
1087
1088 static void socket_enter_stop_pre(Socket *s, bool success) {
1089         int r;
1090         assert(s);
1091
1092         if (!success)
1093                 s->failure = true;
1094
1095         socket_unwatch_control_pid(s);
1096
1097         s->control_command_id = SOCKET_EXEC_STOP_PRE;
1098
1099         if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
1100                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1101                         goto fail;
1102
1103                 socket_set_state(s, SOCKET_STOP_PRE);
1104         } else
1105                 socket_enter_stop_post(s, true);
1106
1107         return;
1108
1109 fail:
1110         log_warning("%s failed to run 'stop-pre' task: %s", s->meta.id, strerror(-r));
1111         socket_enter_stop_post(s, false);
1112 }
1113
1114 static void socket_enter_listening(Socket *s) {
1115         int r;
1116         assert(s);
1117
1118         if ((r = socket_watch_fds(s)) < 0) {
1119                 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1120                 goto fail;
1121         }
1122
1123         socket_set_state(s, SOCKET_LISTENING);
1124         return;
1125
1126 fail:
1127         socket_enter_stop_pre(s, false);
1128 }
1129
1130 static void socket_enter_start_post(Socket *s) {
1131         int r;
1132         assert(s);
1133
1134         if ((r = socket_open_fds(s)) < 0) {
1135                 log_warning("%s failed to listen on sockets: %s", s->meta.id, strerror(-r));
1136                 goto fail;
1137         }
1138
1139         socket_unwatch_control_pid(s);
1140
1141         s->control_command_id = SOCKET_EXEC_START_POST;
1142
1143         if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
1144                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0) {
1145                         log_warning("%s failed to run 'start-post' task: %s", s->meta.id, strerror(-r));
1146                         goto fail;
1147                 }
1148
1149                 socket_set_state(s, SOCKET_START_POST);
1150         } else
1151                 socket_enter_listening(s);
1152
1153         return;
1154
1155 fail:
1156         socket_enter_stop_pre(s, false);
1157 }
1158
1159 static void socket_enter_start_pre(Socket *s) {
1160         int r;
1161         assert(s);
1162
1163         socket_unwatch_control_pid(s);
1164
1165         s->control_command_id = SOCKET_EXEC_START_PRE;
1166
1167         if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
1168                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1169                         goto fail;
1170
1171                 socket_set_state(s, SOCKET_START_PRE);
1172         } else
1173                 socket_enter_start_post(s);
1174
1175         return;
1176
1177 fail:
1178         log_warning("%s failed to run 'start-pre' task: %s", s->meta.id, strerror(-r));
1179         socket_enter_dead(s, false);
1180 }
1181
1182 static void socket_enter_running(Socket *s, int cfd) {
1183         int r;
1184         DBusError error;
1185
1186         assert(s);
1187         dbus_error_init(&error);
1188
1189         /* We don't take connections anymore if we are supposed to
1190          * shut down anyway */
1191         if (unit_pending_inactive(UNIT(s))) {
1192                 if (cfd >= 0)
1193                         close_nointr_nofail(cfd);
1194                 else  {
1195                         /* Flush all sockets by closing and reopening them */
1196                         socket_close_fds(s);
1197
1198                         if ((r = socket_watch_fds(s)) < 0) {
1199                                 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
1200                                 socket_enter_stop_pre(s, false);
1201                         }
1202                 }
1203
1204                 return;
1205         }
1206
1207         if (cfd < 0) {
1208                 bool pending = false;
1209                 Meta *i;
1210
1211                 /* If there's already a start pending don't bother to
1212                  * do anything */
1213                 LIST_FOREACH(units_per_type, i, s->meta.manager->units_per_type[UNIT_SERVICE]) {
1214                         Service *service = (Service *) i;
1215
1216                         if (!set_get(service->configured_sockets, s))
1217                                 continue;
1218
1219                         if (!unit_pending_active(UNIT(service)))
1220                                 continue;
1221
1222                         pending = true;
1223                         break;
1224                 }
1225
1226                 if (!pending)
1227                         if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(s->service), JOB_REPLACE, true, &error, NULL)) < 0)
1228                                 goto fail;
1229
1230                 socket_set_state(s, SOCKET_RUNNING);
1231         } else {
1232                 char *prefix, *instance = NULL, *name;
1233                 Service *service;
1234
1235                 if (s->n_connections >= s->max_connections) {
1236                         log_warning("Too many incoming connections (%u)", s->n_connections);
1237                         close_nointr_nofail(cfd);
1238                         return;
1239                 }
1240
1241                 if ((r = socket_instantiate_service(s)) < 0)
1242                         goto fail;
1243
1244                 if ((r = instance_from_socket(cfd, s->n_accepted, &instance)) < 0)
1245                         goto fail;
1246
1247                 if (!(prefix = unit_name_to_prefix(s->meta.id))) {
1248                         free(instance);
1249                         r = -ENOMEM;
1250                         goto fail;
1251                 }
1252
1253                 name = unit_name_build(prefix, instance, ".service");
1254                 free(prefix);
1255                 free(instance);
1256
1257                 if (!name) {
1258                         r = -ENOMEM;
1259                         goto fail;
1260                 }
1261
1262                 if ((r = unit_add_name(UNIT(s->service), name)) < 0) {
1263                         free(name);
1264                         goto fail;
1265                 }
1266
1267                 service = s->service;
1268                 s->service = NULL;
1269                 s->n_accepted ++;
1270
1271                 service->meta.no_gc = false;
1272
1273                 unit_choose_id(UNIT(service), name);
1274                 free(name);
1275
1276                 if ((r = service_set_socket_fd(service, cfd, s)) < 0)
1277                         goto fail;
1278
1279                 cfd = -1;
1280                 s->n_connections ++;
1281
1282                 if ((r = manager_add_job(s->meta.manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL)) < 0)
1283                         goto fail;
1284
1285                 /* Notify clients about changed counters */
1286                 unit_add_to_dbus_queue(UNIT(s));
1287         }
1288
1289         return;
1290
1291 fail:
1292         log_warning("%s failed to queue socket startup job: %s", s->meta.id, bus_error(&error, r));
1293         socket_enter_stop_pre(s, false);
1294
1295         if (cfd >= 0)
1296                 close_nointr_nofail(cfd);
1297
1298         dbus_error_free(&error);
1299 }
1300
1301 static void socket_run_next(Socket *s, bool success) {
1302         int r;
1303
1304         assert(s);
1305         assert(s->control_command);
1306         assert(s->control_command->command_next);
1307
1308         if (!success)
1309                 s->failure = true;
1310
1311         socket_unwatch_control_pid(s);
1312
1313         s->control_command = s->control_command->command_next;
1314
1315         if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1316                 goto fail;
1317
1318         return;
1319
1320 fail:
1321         log_warning("%s failed to run next task: %s", s->meta.id, strerror(-r));
1322
1323         if (s->state == SOCKET_START_POST)
1324                 socket_enter_stop_pre(s, false);
1325         else if (s->state == SOCKET_STOP_POST)
1326                 socket_enter_dead(s, false);
1327         else
1328                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1329 }
1330
1331 static int socket_start(Unit *u) {
1332         Socket *s = SOCKET(u);
1333
1334         assert(s);
1335
1336         /* We cannot fulfill this request right now, try again later
1337          * please! */
1338         if (s->state == SOCKET_STOP_PRE ||
1339             s->state == SOCKET_STOP_PRE_SIGKILL ||
1340             s->state == SOCKET_STOP_PRE_SIGTERM ||
1341             s->state == SOCKET_STOP_POST ||
1342             s->state == SOCKET_FINAL_SIGTERM ||
1343             s->state == SOCKET_FINAL_SIGKILL)
1344                 return -EAGAIN;
1345
1346         if (s->state == SOCKET_START_PRE ||
1347             s->state == SOCKET_START_POST)
1348                 return 0;
1349
1350         /* Cannot run this without the service being around */
1351         if (s->service) {
1352                 if (s->service->meta.load_state != UNIT_LOADED)
1353                         return -ENOENT;
1354
1355                 /* If the service is alredy actvie we cannot start the
1356                  * socket */
1357                 if (s->service->state != SERVICE_DEAD &&
1358                     s->service->state != SERVICE_FAILED &&
1359                     s->service->state != SERVICE_AUTO_RESTART)
1360                         return -EBUSY;
1361         }
1362
1363         assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1364
1365         s->failure = false;
1366         socket_enter_start_pre(s);
1367         return 0;
1368 }
1369
1370 static int socket_stop(Unit *u) {
1371         Socket *s = SOCKET(u);
1372
1373         assert(s);
1374
1375         /* Already on it */
1376         if (s->state == SOCKET_STOP_PRE ||
1377             s->state == SOCKET_STOP_PRE_SIGTERM ||
1378             s->state == SOCKET_STOP_PRE_SIGKILL ||
1379             s->state == SOCKET_STOP_POST ||
1380             s->state == SOCKET_FINAL_SIGTERM ||
1381             s->state == SOCKET_FINAL_SIGKILL)
1382                 return 0;
1383
1384         /* If there's already something running we go directly into
1385          * kill mode. */
1386         if (s->state == SOCKET_START_PRE ||
1387             s->state == SOCKET_START_POST) {
1388                 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, true);
1389                 return -EAGAIN;
1390         }
1391
1392         assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1393
1394         socket_enter_stop_pre(s, true);
1395         return 0;
1396 }
1397
1398 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1399         Socket *s = SOCKET(u);
1400         SocketPort *p;
1401         int r;
1402
1403         assert(u);
1404         assert(f);
1405         assert(fds);
1406
1407         unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1408         unit_serialize_item(u, f, "failure", yes_no(s->failure));
1409         unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1410
1411         if (s->control_pid > 0)
1412                 unit_serialize_item_format(u, f, "control-pid", "%lu", (unsigned long) s->control_pid);
1413
1414         if (s->control_command_id >= 0)
1415                 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1416
1417         LIST_FOREACH(port, p, s->ports) {
1418                 int copy;
1419
1420                 if (p->fd < 0)
1421                         continue;
1422
1423                 if ((copy = fdset_put_dup(fds, p->fd)) < 0)
1424                         return copy;
1425
1426                 if (p->type == SOCKET_SOCKET) {
1427                         char *t;
1428
1429                         if ((r = socket_address_print(&p->address, &t)) < 0)
1430                                 return r;
1431
1432                         unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1433                         free(t);
1434                 } else {
1435                         assert(p->type == SOCKET_FIFO);
1436                         unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1437                 }
1438         }
1439
1440         return 0;
1441 }
1442
1443 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1444         Socket *s = SOCKET(u);
1445
1446         assert(u);
1447         assert(key);
1448         assert(value);
1449         assert(fds);
1450
1451         if (streq(key, "state")) {
1452                 SocketState state;
1453
1454                 if ((state = socket_state_from_string(value)) < 0)
1455                         log_debug("Failed to parse state value %s", value);
1456                 else
1457                         s->deserialized_state = state;
1458         } else if (streq(key, "failure")) {
1459                 int b;
1460
1461                 if ((b = parse_boolean(value)) < 0)
1462                         log_debug("Failed to parse failure value %s", value);
1463                 else
1464                         s->failure = b || s->failure;
1465
1466         } else if (streq(key, "n-accepted")) {
1467                 unsigned k;
1468
1469                 if (safe_atou(value, &k) < 0)
1470                         log_debug("Failed to parse n-accepted value %s", value);
1471                 else
1472                         s->n_accepted += k;
1473         } else if (streq(key, "control-pid")) {
1474                 pid_t pid;
1475
1476                 if (parse_pid(value, &pid) < 0)
1477                         log_debug("Failed to parse control-pid value %s", value);
1478                 else
1479                         s->control_pid = pid;
1480         } else if (streq(key, "control-command")) {
1481                 SocketExecCommand id;
1482
1483                 if ((id = socket_exec_command_from_string(value)) < 0)
1484                         log_debug("Failed to parse exec-command value %s", value);
1485                 else {
1486                         s->control_command_id = id;
1487                         s->control_command = s->exec_command[id];
1488                 }
1489         } else if (streq(key, "fifo")) {
1490                 int fd, skip = 0;
1491                 SocketPort *p;
1492
1493                 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1494                         log_debug("Failed to parse fifo value %s", value);
1495                 else {
1496
1497                         LIST_FOREACH(port, p, s->ports)
1498                                 if (streq(p->path, value+skip))
1499                                         break;
1500
1501                         if (p) {
1502                                 if (p->fd >= 0)
1503                                         close_nointr_nofail(p->fd);
1504                                 p->fd = fdset_remove(fds, fd);
1505                         }
1506                 }
1507
1508         } else if (streq(key, "socket")) {
1509                 int fd, type, skip = 0;
1510                 SocketPort *p;
1511
1512                 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
1513                         log_debug("Failed to parse socket value %s", value);
1514                 else {
1515
1516                         LIST_FOREACH(port, p, s->ports)
1517                                 if (socket_address_is(&p->address, value+skip, type))
1518                                         break;
1519
1520                         if (p) {
1521                                 if (p->fd >= 0)
1522                                         close_nointr_nofail(p->fd);
1523                                 p->fd = fdset_remove(fds, fd);
1524                         }
1525                 }
1526
1527         } else
1528                 log_debug("Unknown serialization key '%s'", key);
1529
1530         return 0;
1531 }
1532
1533 static UnitActiveState socket_active_state(Unit *u) {
1534         assert(u);
1535
1536         return state_translation_table[SOCKET(u)->state];
1537 }
1538
1539 static const char *socket_sub_state_to_string(Unit *u) {
1540         assert(u);
1541
1542         return socket_state_to_string(SOCKET(u)->state);
1543 }
1544
1545 static bool socket_check_gc(Unit *u) {
1546         Socket *s = SOCKET(u);
1547
1548         assert(u);
1549
1550         return s->n_connections > 0;
1551 }
1552
1553 static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
1554         Socket *s = SOCKET(u);
1555         int cfd = -1;
1556
1557         assert(s);
1558         assert(fd >= 0);
1559
1560         if (s->state != SOCKET_LISTENING)
1561                 return;
1562
1563         log_debug("Incoming traffic on %s", u->meta.id);
1564
1565         if (events != EPOLLIN) {
1566                 log_error("Got invalid poll event on socket.");
1567                 goto fail;
1568         }
1569
1570         if (w->socket_accept) {
1571                 for (;;) {
1572
1573                         if ((cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK)) < 0) {
1574
1575                                 if (errno == EINTR)
1576                                         continue;
1577
1578                                 log_error("Failed to accept socket: %m");
1579                                 goto fail;
1580                         }
1581
1582                         break;
1583                 }
1584
1585                 socket_apply_socket_options(s, cfd);
1586         }
1587
1588         socket_enter_running(s, cfd);
1589         return;
1590
1591 fail:
1592         socket_enter_stop_pre(s, false);
1593 }
1594
1595 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1596         Socket *s = SOCKET(u);
1597         bool success;
1598
1599         assert(s);
1600         assert(pid >= 0);
1601
1602         if (pid != s->control_pid)
1603                 return;
1604
1605         s->control_pid = 0;
1606
1607         success = is_clean_exit(code, status);
1608
1609         if (s->control_command) {
1610                 exec_status_exit(&s->control_command->exec_status, pid, code, status, s->exec_context.utmp_id);
1611
1612                 if (s->control_command->ignore)
1613                         success = true;
1614         }
1615
1616         log_full(success ? LOG_DEBUG : LOG_NOTICE,
1617                  "%s control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1618         s->failure = s->failure || !success;
1619
1620         if (s->control_command && s->control_command->command_next && success) {
1621                 log_debug("%s running next command for state %s", u->meta.id, socket_state_to_string(s->state));
1622                 socket_run_next(s, success);
1623         } else {
1624                 s->control_command = NULL;
1625                 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1626
1627                 /* No further commands for this step, so let's figure
1628                  * out what to do next */
1629
1630                 log_debug("%s got final SIGCHLD for state %s", u->meta.id, socket_state_to_string(s->state));
1631
1632                 switch (s->state) {
1633
1634                 case SOCKET_START_PRE:
1635                         if (success)
1636                                 socket_enter_start_post(s);
1637                         else
1638                                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1639                         break;
1640
1641                 case SOCKET_START_POST:
1642                         if (success)
1643                                 socket_enter_listening(s);
1644                         else
1645                                 socket_enter_stop_pre(s, false);
1646                         break;
1647
1648                 case SOCKET_STOP_PRE:
1649                 case SOCKET_STOP_PRE_SIGTERM:
1650                 case SOCKET_STOP_PRE_SIGKILL:
1651                         socket_enter_stop_post(s, success);
1652                         break;
1653
1654                 case SOCKET_STOP_POST:
1655                 case SOCKET_FINAL_SIGTERM:
1656                 case SOCKET_FINAL_SIGKILL:
1657                         socket_enter_dead(s, success);
1658                         break;
1659
1660                 default:
1661                         assert_not_reached("Uh, control process died at wrong time.");
1662                 }
1663         }
1664
1665         /* Notify clients about changed exit status */
1666         unit_add_to_dbus_queue(u);
1667 }
1668
1669 static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
1670         Socket *s = SOCKET(u);
1671
1672         assert(s);
1673         assert(elapsed == 1);
1674         assert(w == &s->timer_watch);
1675
1676         switch (s->state) {
1677
1678         case SOCKET_START_PRE:
1679                 log_warning("%s starting timed out. Terminating.", u->meta.id);
1680                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1681
1682         case SOCKET_START_POST:
1683                 log_warning("%s starting timed out. Stopping.", u->meta.id);
1684                 socket_enter_stop_pre(s, false);
1685                 break;
1686
1687         case SOCKET_STOP_PRE:
1688                 log_warning("%s stopping timed out. Terminating.", u->meta.id);
1689                 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, false);
1690                 break;
1691
1692         case SOCKET_STOP_PRE_SIGTERM:
1693                 if (s->exec_context.send_sigkill) {
1694                         log_warning("%s stopping timed out. Killing.", u->meta.id);
1695                         socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, false);
1696                 } else {
1697                         log_warning("%s stopping timed out. Skipping SIGKILL. Ignoring.", u->meta.id);
1698                         socket_enter_stop_post(s, false);
1699                 }
1700                 break;
1701
1702         case SOCKET_STOP_PRE_SIGKILL:
1703                 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
1704                 socket_enter_stop_post(s, false);
1705                 break;
1706
1707         case SOCKET_STOP_POST:
1708                 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
1709                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1710                 break;
1711
1712         case SOCKET_FINAL_SIGTERM:
1713                 if (s->exec_context.send_sigkill) {
1714                         log_warning("%s stopping timed out (2). Killing.", u->meta.id);
1715                         socket_enter_signal(s, SOCKET_FINAL_SIGKILL, false);
1716                 } else {
1717                         log_warning("%s stopping timed out (2). Skipping SIGKILL. Ignoring.", u->meta.id);
1718                         socket_enter_dead(s, false);
1719                 }
1720                 break;
1721
1722         case SOCKET_FINAL_SIGKILL:
1723                 log_warning("%s still around after SIGKILL (2). Entering failed mode.", u->meta.id);
1724                 socket_enter_dead(s, false);
1725                 break;
1726
1727         default:
1728                 assert_not_reached("Timeout at wrong time.");
1729         }
1730 }
1731
1732 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
1733         int *rfds;
1734         unsigned rn_fds, k;
1735         SocketPort *p;
1736
1737         assert(s);
1738         assert(fds);
1739         assert(n_fds);
1740
1741         /* Called from the service code for requesting our fds */
1742
1743         rn_fds = 0;
1744         LIST_FOREACH(port, p, s->ports)
1745                 if (p->fd >= 0)
1746                         rn_fds++;
1747
1748         if (!(rfds = new(int, rn_fds)))
1749                 return -ENOMEM;
1750
1751         k = 0;
1752         LIST_FOREACH(port, p, s->ports)
1753                 if (p->fd >= 0)
1754                         rfds[k++] = p->fd;
1755
1756         assert(k == rn_fds);
1757
1758         *fds = rfds;
1759         *n_fds = rn_fds;
1760
1761         return 0;
1762 }
1763
1764 void socket_notify_service_dead(Socket *s) {
1765         assert(s);
1766
1767         /* The service is dead. Dang!
1768          *
1769          * This is strictly for one-instance-for-all-connections
1770          * services. */
1771
1772         if (s->state == SOCKET_RUNNING) {
1773                 log_debug("%s got notified about service death.", s->meta.id);
1774                 socket_enter_listening(s);
1775         }
1776 }
1777
1778 void socket_connection_unref(Socket *s) {
1779         assert(s);
1780
1781         /* The service is dead. Yay!
1782          *
1783          * This is strictly for one-onstance-per-connection
1784          * services. */
1785
1786         assert(s->n_connections > 0);
1787         s->n_connections--;
1788
1789         log_debug("%s: One connection closed, %u left.", s->meta.id, s->n_connections);
1790 }
1791
1792 static void socket_reset_failed(Unit *u) {
1793         Socket *s = SOCKET(u);
1794
1795         assert(s);
1796
1797         if (s->state == SOCKET_FAILED)
1798                 socket_set_state(s, SOCKET_DEAD);
1799
1800         s->failure = false;
1801 }
1802
1803 static int socket_kill(Unit *u, KillWho who, KillMode mode, int signo, DBusError *error) {
1804         Socket *s = SOCKET(u);
1805         int r = 0;
1806         Set *pid_set = NULL;
1807
1808         assert(s);
1809
1810         if (who == KILL_MAIN) {
1811                 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "Socket units have no main processes");
1812                 return -EINVAL;
1813         }
1814
1815         if (s->control_pid <= 0 && who == KILL_CONTROL) {
1816                 dbus_set_error(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
1817                 return -ENOENT;
1818         }
1819
1820         if (s->control_pid > 0)
1821                 if (kill(mode == KILL_PROCESS_GROUP ? -s->control_pid : s->control_pid, signo) < 0)
1822                         r = -errno;
1823
1824         if (mode == KILL_CONTROL_GROUP) {
1825                 int q;
1826
1827                 if (!(pid_set = set_new(trivial_hash_func, trivial_compare_func)))
1828                         return -ENOMEM;
1829
1830                 /* Exclude the control pid from being killed via the cgroup */
1831                 if (s->control_pid > 0)
1832                         if ((q = set_put(pid_set, LONG_TO_PTR(s->control_pid))) < 0) {
1833                                 r = q;
1834                                 goto finish;
1835                         }
1836
1837                 if ((q = cgroup_bonding_kill_list(s->meta.cgroup_bondings, signo, pid_set)) < 0)
1838                         if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
1839                                 r = q;
1840         }
1841
1842 finish:
1843         if (pid_set)
1844                 set_free(pid_set);
1845
1846         return r;
1847 }
1848
1849 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
1850         [SOCKET_DEAD] = "dead",
1851         [SOCKET_START_PRE] = "start-pre",
1852         [SOCKET_START_POST] = "start-post",
1853         [SOCKET_LISTENING] = "listening",
1854         [SOCKET_RUNNING] = "running",
1855         [SOCKET_STOP_PRE] = "stop-pre",
1856         [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
1857         [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
1858         [SOCKET_STOP_POST] = "stop-post",
1859         [SOCKET_FINAL_SIGTERM] = "final-sigterm",
1860         [SOCKET_FINAL_SIGKILL] = "final-sigkill",
1861         [SOCKET_FAILED] = "failed"
1862 };
1863
1864 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
1865
1866 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
1867         [SOCKET_EXEC_START_PRE] = "StartPre",
1868         [SOCKET_EXEC_START_POST] = "StartPost",
1869         [SOCKET_EXEC_STOP_PRE] = "StopPre",
1870         [SOCKET_EXEC_STOP_POST] = "StopPost"
1871 };
1872
1873 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
1874
1875 const UnitVTable socket_vtable = {
1876         .suffix = ".socket",
1877
1878         .init = socket_init,
1879         .done = socket_done,
1880         .load = socket_load,
1881
1882         .kill = socket_kill,
1883
1884         .coldplug = socket_coldplug,
1885
1886         .dump = socket_dump,
1887
1888         .start = socket_start,
1889         .stop = socket_stop,
1890
1891         .serialize = socket_serialize,
1892         .deserialize_item = socket_deserialize_item,
1893
1894         .active_state = socket_active_state,
1895         .sub_state_to_string = socket_sub_state_to_string,
1896
1897         .check_gc = socket_check_gc,
1898
1899         .fd_event = socket_fd_event,
1900         .sigchld_event = socket_sigchld_event,
1901         .timer_event = socket_timer_event,
1902
1903         .reset_failed = socket_reset_failed,
1904
1905         .bus_interface = "org.freedesktop.systemd1.Socket",
1906         .bus_message_handler = bus_socket_message_handler,
1907         .bus_invalidating_properties =  bus_socket_invalidating_properties
1908 };