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