chiark / gitweb /
service: don't wait for any child unless we no its pid
[elogind.git] / socket.c
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
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 "log.h"
34 #include "load-dropin.h"
35 #include "load-fragment.h"
36 #include "strv.h"
37 #include "unit-name.h"
38 #include "dbus-socket.h"
39
40 static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
41         [SOCKET_DEAD] = UNIT_INACTIVE,
42         [SOCKET_START_PRE] = UNIT_ACTIVATING,
43         [SOCKET_START_POST] = UNIT_ACTIVATING,
44         [SOCKET_LISTENING] = UNIT_ACTIVE,
45         [SOCKET_RUNNING] = UNIT_ACTIVE,
46         [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
47         [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
48         [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
49         [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
50         [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
51         [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
52         [SOCKET_MAINTAINANCE] = UNIT_INACTIVE,
53 };
54
55 static void socket_init(Unit *u) {
56         Socket *s = SOCKET(u);
57
58         assert(u);
59         assert(u->meta.load_state == UNIT_STUB);
60
61         s->timer_watch.type = WATCH_INVALID;
62         s->backlog = SOMAXCONN;
63         s->timeout_usec = DEFAULT_TIMEOUT_USEC;
64         s->directory_mode = 0755;
65         s->socket_mode = 0666;
66
67         exec_context_init(&s->exec_context);
68
69         s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
70 }
71
72 static void socket_unwatch_control_pid(Socket *s) {
73         assert(s);
74
75         if (s->control_pid <= 0)
76                 return;
77
78         unit_unwatch_pid(UNIT(s), s->control_pid);
79         s->control_pid = 0;
80 }
81
82 static void socket_done(Unit *u) {
83         Socket *s = SOCKET(u);
84         SocketPort *p;
85
86         assert(s);
87
88         while ((p = s->ports)) {
89                 LIST_REMOVE(SocketPort, port, s->ports, p);
90
91                 if (p->fd >= 0) {
92                         unit_unwatch_fd(UNIT(s), &p->fd_watch);
93                         close_nointr_nofail(p->fd);
94                 }
95
96                 free(p->path);
97                 free(p);
98         }
99
100         exec_context_done(&s->exec_context);
101         exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
102         s->control_command = NULL;
103
104         socket_unwatch_control_pid(s);
105
106         s->service = NULL;
107
108         free(s->bind_to_device);
109         s->bind_to_device = NULL;
110
111         unit_unwatch_timer(u, &s->timer_watch);
112 }
113
114 static bool have_non_accept_socket(Socket *s) {
115         SocketPort *p;
116
117         assert(s);
118
119         if (!s->accept)
120                 return true;
121
122         LIST_FOREACH(port, p, s->ports) {
123
124                 if (p->type != SOCKET_SOCKET)
125                         return true;
126
127                 if (!socket_address_can_accept(&p->address))
128                         return true;
129         }
130
131         return false;
132 }
133
134 static int socket_verify(Socket *s) {
135         assert(s);
136
137         if (UNIT(s)->meta.load_state != UNIT_LOADED)
138                 return 0;
139
140         if (!s->ports) {
141                 log_error("%s lacks Listen setting. Refusing.", UNIT(s)->meta.id);
142                 return -EINVAL;
143         }
144
145         return 0;
146 }
147
148 static int socket_load(Unit *u) {
149         Socket *s = SOCKET(u);
150         int r;
151
152         assert(u);
153         assert(u->meta.load_state == UNIT_STUB);
154
155         if ((r = unit_load_fragment_and_dropin(u)) < 0)
156                 return r;
157
158         /* This is a new unit? Then let's add in some extras */
159         if (u->meta.load_state == UNIT_LOADED) {
160
161                 if (have_non_accept_socket(s)) {
162                         if ((r = unit_load_related_unit(u, ".service", (Unit**) &s->service)))
163                                 return r;
164
165                         if ((r = unit_add_dependency(u, UNIT_BEFORE, UNIT(s->service), true)) < 0)
166                                 return r;
167                 }
168
169                 if ((r = unit_add_exec_dependencies(u, &s->exec_context)) < 0)
170                         return r;
171
172                 if ((r = unit_add_default_cgroup(u)) < 0)
173                         return r;
174         }
175
176         return socket_verify(s);
177 }
178
179 static const char* listen_lookup(int type) {
180
181         if (type == SOCK_STREAM)
182                 return "ListenStream";
183         else if (type == SOCK_DGRAM)
184                 return "ListenDatagram";
185         else if (type == SOCK_SEQPACKET)
186                 return "ListenSequentialPacket";
187
188         assert_not_reached("Unknown socket type");
189         return NULL;
190 }
191
192 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
193
194         SocketExecCommand c;
195         Socket *s = SOCKET(u);
196         SocketPort *p;
197         const char *prefix2;
198         char *p2;
199
200         assert(s);
201         assert(f);
202
203         p2 = strappend(prefix, "\t");
204         prefix2 = p2 ? p2 : prefix;
205
206         fprintf(f,
207                 "%sSocket State: %s\n"
208                 "%sBindIPv6Only: %s\n"
209                 "%sBacklog: %u\n"
210                 "%sKillMode: %s\n"
211                 "%sSocketMode: %04o\n"
212                 "%sDirectoryMode: %04o\n",
213                 prefix, socket_state_to_string(s->state),
214                 prefix, yes_no(s->bind_ipv6_only),
215                 prefix, s->backlog,
216                 prefix, kill_mode_to_string(s->kill_mode),
217                 prefix, s->socket_mode,
218                 prefix, s->directory_mode);
219
220         if (s->control_pid > 0)
221                 fprintf(f,
222                         "%sControl PID: %llu\n",
223                         prefix, (unsigned long long) s->control_pid);
224
225         if (s->bind_to_device)
226                 fprintf(f,
227                         "%sBindToDevice: %s\n",
228                         prefix, s->bind_to_device);
229
230         if (s->accept)
231                 fprintf(f,
232                         "%sAccepted: %u\n",
233                         prefix, s->n_accepted);
234
235         LIST_FOREACH(port, p, s->ports) {
236
237                 if (p->type == SOCKET_SOCKET) {
238                         const char *t;
239                         int r;
240                         char *k;
241
242                         if ((r = socket_address_print(&p->address, &k)) < 0)
243                                 t = strerror(-r);
244                         else
245                                 t = k;
246
247                         fprintf(f, "%s%s: %s\n", prefix, listen_lookup(p->address.type), k);
248                         free(k);
249                 } else
250                         fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
251         }
252
253         exec_context_dump(&s->exec_context, f, prefix);
254
255         for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
256                 if (!s->exec_command[c])
257                         continue;
258
259                 fprintf(f, "%s-> %s:\n",
260                         prefix, socket_exec_command_to_string(c));
261
262                 exec_command_dump_list(s->exec_command[c], f, prefix2);
263         }
264
265         free(p2);
266 }
267
268 static int instance_from_socket(int fd, unsigned nr, char **instance) {
269         socklen_t l;
270         char *r;
271         union {
272                 struct sockaddr sa;
273                 struct sockaddr_un un;
274                 struct sockaddr_in in;
275                 struct sockaddr_in6 in6;
276                 struct sockaddr_storage storage;
277         } local, remote;
278
279         assert(fd >= 0);
280         assert(instance);
281
282         l = sizeof(local);
283         if (getsockname(fd, &local.sa, &l) < 0)
284                 return -errno;
285
286         l = sizeof(remote);
287         if (getpeername(fd, &remote.sa, &l) < 0)
288                 return -errno;
289
290         switch (local.sa.sa_family) {
291
292         case AF_INET: {
293                 uint32_t
294                         a = ntohl(local.in.sin_addr.s_addr),
295                         b = ntohl(remote.in.sin_addr.s_addr);
296
297                 if (asprintf(&r,
298                              "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
299                              nr,
300                              a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
301                              ntohs(local.in.sin_port),
302                              b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
303                              ntohs(remote.in.sin_port)) < 0)
304                         return -ENOMEM;
305
306                 break;
307         }
308
309         case AF_INET6: {
310                 char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
311
312                 if (asprintf(&r,
313                              "%u-%s:%u-%s:%u",
314                              nr,
315                              inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
316                              ntohs(local.in6.sin6_port),
317                              inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
318                              ntohs(remote.in6.sin6_port)) < 0)
319                         return -ENOMEM;
320
321                 break;
322         }
323
324         case AF_UNIX: {
325                 struct ucred ucred;
326
327                 l = sizeof(ucred);
328                 if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &ucred, &l) < 0)
329                         return -errno;
330
331                 if (asprintf(&r,
332                              "%u-%llu-%llu",
333                              nr,
334                              (unsigned long long) ucred.pid,
335                              (unsigned long long) ucred.uid) < 0)
336                         return -ENOMEM;
337
338                 break;
339         }
340
341         default:
342                 assert_not_reached("Unhandled socket type.");
343         }
344
345         *instance = r;
346         return 0;
347 }
348
349 static void socket_close_fds(Socket *s) {
350         SocketPort *p;
351
352         assert(s);
353
354         LIST_FOREACH(port, p, s->ports) {
355                 if (p->fd < 0)
356                         continue;
357
358                 unit_unwatch_fd(UNIT(s), &p->fd_watch);
359                 close_nointr_nofail(p->fd);
360
361                 /* One little note: we should never delete any sockets
362                  * in the file system here! After all some other
363                  * process we spawned might still have a reference of
364                  * this fd and wants to continue to use it. Therefore
365                  * we delete sockets in the file system before we
366                  * create a new one, not after we stopped using
367                  * one! */
368
369                 p->fd = -1;
370         }
371 }
372
373 static int socket_open_fds(Socket *s) {
374         SocketPort *p;
375         int r;
376
377         assert(s);
378
379         LIST_FOREACH(port, p, s->ports) {
380
381                 if (p->fd >= 0)
382                         continue;
383
384                 if (p->type == SOCKET_SOCKET) {
385
386                         if ((r = socket_address_listen(
387                                              &p->address,
388                                              s->backlog,
389                                              s->bind_ipv6_only,
390                                              s->bind_to_device,
391                                              s->directory_mode,
392                                              s->socket_mode,
393                                              &p->fd)) < 0)
394                                 goto rollback;
395
396                 } else {
397                         struct stat st;
398                         assert(p->type == SOCKET_FIFO);
399
400                         mkdir_parents(p->path, s->directory_mode);
401
402                         if (mkfifo(p->path, s->socket_mode) < 0 && errno != EEXIST) {
403                                 r = -errno;
404                                 goto rollback;
405                         }
406
407                         if ((p->fd = open(p->path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
408                                 r = -errno;
409                                 goto rollback;
410                         }
411
412                         if (fstat(p->fd, &st) < 0) {
413                                 r = -errno;
414                                 goto rollback;
415                         }
416
417                         /* FIXME verify user, access mode */
418
419                         if (!S_ISFIFO(st.st_mode)) {
420                                 r = -EEXIST;
421                                 goto rollback;
422                         }
423                 }
424         }
425
426         return 0;
427
428 rollback:
429         socket_close_fds(s);
430         return r;
431 }
432
433 static void socket_unwatch_fds(Socket *s) {
434         SocketPort *p;
435
436         assert(s);
437
438         LIST_FOREACH(port, p, s->ports) {
439                 if (p->fd < 0)
440                         continue;
441
442                 unit_unwatch_fd(UNIT(s), &p->fd_watch);
443         }
444 }
445
446 static int socket_watch_fds(Socket *s) {
447         SocketPort *p;
448         int r;
449
450         assert(s);
451
452         LIST_FOREACH(port, p, s->ports) {
453                 if (p->fd < 0)
454                         continue;
455
456                 p->fd_watch.socket_accept =
457                         s->accept &&
458                         p->type == SOCKET_SOCKET &&
459                         socket_address_can_accept(&p->address);
460
461                 if ((r = unit_watch_fd(UNIT(s), p->fd, EPOLLIN, &p->fd_watch)) < 0)
462                         goto fail;
463         }
464
465         return 0;
466
467 fail:
468         socket_unwatch_fds(s);
469         return r;
470 }
471
472 static void socket_set_state(Socket *s, SocketState state) {
473         SocketState old_state;
474         assert(s);
475
476         old_state = s->state;
477         s->state = state;
478
479         if (state != SOCKET_START_PRE &&
480             state != SOCKET_START_POST &&
481             state != SOCKET_STOP_PRE &&
482             state != SOCKET_STOP_PRE_SIGTERM &&
483             state != SOCKET_STOP_PRE_SIGKILL &&
484             state != SOCKET_STOP_POST &&
485             state != SOCKET_FINAL_SIGTERM &&
486             state != SOCKET_FINAL_SIGKILL) {
487                 unit_unwatch_timer(UNIT(s), &s->timer_watch);
488                 socket_unwatch_control_pid(s);
489                 s->control_command = NULL;
490                 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
491         }
492
493         if (state != SOCKET_LISTENING)
494                 socket_unwatch_fds(s);
495
496         if (state != SOCKET_START_POST &&
497             state != SOCKET_LISTENING &&
498             state != SOCKET_RUNNING &&
499             state != SOCKET_STOP_PRE &&
500             state != SOCKET_STOP_PRE_SIGTERM &&
501             state != SOCKET_STOP_PRE_SIGKILL)
502                 socket_close_fds(s);
503
504         if (state != old_state)
505                 log_debug("%s changed %s -> %s",
506                           s->meta.id,
507                           socket_state_to_string(old_state),
508                           socket_state_to_string(state));
509
510         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state]);
511 }
512
513 static int socket_coldplug(Unit *u) {
514         Socket *s = SOCKET(u);
515         int r;
516
517         assert(s);
518         assert(s->state == SOCKET_DEAD);
519
520         if (s->deserialized_state != s->state) {
521
522                 if (s->deserialized_state == SOCKET_START_PRE ||
523                     s->deserialized_state == SOCKET_START_POST ||
524                     s->deserialized_state == SOCKET_STOP_PRE ||
525                     s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
526                     s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
527                     s->deserialized_state == SOCKET_STOP_POST ||
528                     s->deserialized_state == SOCKET_FINAL_SIGTERM ||
529                     s->deserialized_state == SOCKET_FINAL_SIGKILL) {
530
531                         if (s->control_pid <= 0)
532                                 return -EBADMSG;
533
534                         if ((r = unit_watch_pid(UNIT(s), s->control_pid)) < 0)
535                                 return r;
536
537                         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
538                                 return r;
539                 }
540
541                 if (s->deserialized_state == SOCKET_START_POST ||
542                     s->deserialized_state == SOCKET_LISTENING ||
543                     s->deserialized_state == SOCKET_RUNNING ||
544                     s->deserialized_state == SOCKET_STOP_PRE ||
545                     s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
546                     s->deserialized_state == SOCKET_STOP_PRE_SIGKILL)
547                         if ((r = socket_open_fds(s)) < 0)
548                                 return r;
549
550                 if (s->deserialized_state == SOCKET_LISTENING)
551                         if ((r = socket_watch_fds(s)) < 0)
552                                 return r;
553
554                 socket_set_state(s, s->deserialized_state);
555         }
556
557         return 0;
558 }
559
560 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
561         pid_t pid;
562         int r;
563         char **argv;
564
565         assert(s);
566         assert(c);
567         assert(_pid);
568
569         if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
570                 goto fail;
571
572         if (!(argv = unit_full_printf_strv(UNIT(s), c->argv))) {
573                 r = -ENOMEM;
574                 goto fail;
575         }
576
577         r = exec_spawn(c,
578                        argv,
579                        &s->exec_context,
580                        NULL, 0,
581                        true,
582                        true,
583                        UNIT(s)->meta.manager->confirm_spawn,
584                        UNIT(s)->meta.cgroup_bondings,
585                        &pid);
586
587         strv_free(argv);
588         if (r < 0)
589                 goto fail;
590
591         if ((r = unit_watch_pid(UNIT(s), pid)) < 0)
592                 /* FIXME: we need to do something here */
593                 goto fail;
594
595         *_pid = pid;
596
597         return 0;
598
599 fail:
600         unit_unwatch_timer(UNIT(s), &s->timer_watch);
601
602         return r;
603 }
604
605 static void socket_enter_dead(Socket *s, bool success) {
606         assert(s);
607
608         if (!success)
609                 s->failure = true;
610
611         socket_set_state(s, s->failure ? SOCKET_MAINTAINANCE : SOCKET_DEAD);
612 }
613
614 static void socket_enter_signal(Socket *s, SocketState state, bool success);
615
616 static void socket_enter_stop_post(Socket *s, bool success) {
617         int r;
618         assert(s);
619
620         if (!success)
621                 s->failure = true;
622
623         socket_unwatch_control_pid(s);
624
625         s->control_command_id = SOCKET_EXEC_STOP_POST;
626
627         if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
628                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
629                         goto fail;
630
631                 socket_set_state(s, SOCKET_STOP_POST);
632         } else
633                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, true);
634
635         return;
636
637 fail:
638         log_warning("%s failed to run stop-post executable: %s", s->meta.id, strerror(-r));
639         socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
640 }
641
642 static void socket_enter_signal(Socket *s, SocketState state, bool success) {
643         int r;
644         bool sent = false;
645
646         assert(s);
647
648         if (!success)
649                 s->failure = true;
650
651         if (s->kill_mode != KILL_NONE) {
652                 int sig = (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_FINAL_SIGTERM) ? SIGTERM : SIGKILL;
653
654                 if (s->kill_mode == KILL_CONTROL_GROUP) {
655
656                         if ((r = cgroup_bonding_kill_list(UNIT(s)->meta.cgroup_bondings, sig)) < 0) {
657                                 if (r != -EAGAIN && r != -ESRCH)
658                                         goto fail;
659                         } else
660                                 sent = true;
661                 }
662
663                 if (!sent && s->control_pid > 0)
664                         if (kill(s->kill_mode == KILL_PROCESS ? s->control_pid : -s->control_pid, sig) < 0 && errno != ESRCH) {
665                                 r = -errno;
666                                 goto fail;
667                         }
668         }
669
670         if (sent && s->control_pid > 0) {
671                 if ((r = unit_watch_timer(UNIT(s), s->timeout_usec, &s->timer_watch)) < 0)
672                         goto fail;
673
674                 socket_set_state(s, state);
675         } else if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
676                 socket_enter_stop_post(s, true);
677         else
678                 socket_enter_dead(s, true);
679
680         return;
681
682 fail:
683         log_warning("%s failed to kill processes: %s", s->meta.id, strerror(-r));
684
685         if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
686                 socket_enter_stop_post(s, false);
687         else
688                 socket_enter_dead(s, false);
689 }
690
691 static void socket_enter_stop_pre(Socket *s, bool success) {
692         int r;
693         assert(s);
694
695         if (!success)
696                 s->failure = true;
697
698         socket_unwatch_control_pid(s);
699
700         s->control_command_id = SOCKET_EXEC_STOP_PRE;
701
702         if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
703                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
704                         goto fail;
705
706                 socket_set_state(s, SOCKET_STOP_PRE);
707         } else
708                 socket_enter_stop_post(s, true);
709
710         return;
711
712 fail:
713         log_warning("%s failed to run stop-pre executable: %s", s->meta.id, strerror(-r));
714         socket_enter_stop_post(s, false);
715 }
716
717 static void socket_enter_listening(Socket *s) {
718         int r;
719         assert(s);
720
721         if ((r = socket_watch_fds(s)) < 0) {
722                 log_warning("%s failed to watch sockets: %s", s->meta.id, strerror(-r));
723                 goto fail;
724         }
725
726         socket_set_state(s, SOCKET_LISTENING);
727         return;
728
729 fail:
730         socket_enter_stop_pre(s, false);
731 }
732
733 static void socket_enter_start_post(Socket *s) {
734         int r;
735         assert(s);
736
737         if ((r = socket_open_fds(s)) < 0) {
738                 log_warning("%s failed to listen on sockets: %s", s->meta.id, strerror(-r));
739                 goto fail;
740         }
741
742         socket_unwatch_control_pid(s);
743
744         s->control_command_id = SOCKET_EXEC_START_POST;
745
746         if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
747                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0) {
748                         log_warning("%s failed to run start-post executable: %s", s->meta.id, strerror(-r));
749                         goto fail;
750                 }
751
752                 socket_set_state(s, SOCKET_START_POST);
753         } else
754                 socket_enter_listening(s);
755
756         return;
757
758 fail:
759         socket_enter_stop_pre(s, false);
760 }
761
762 static void socket_enter_start_pre(Socket *s) {
763         int r;
764         assert(s);
765
766         socket_unwatch_control_pid(s);
767
768         s->control_command_id = SOCKET_EXEC_START_PRE;
769
770         if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
771                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
772                         goto fail;
773
774                 socket_set_state(s, SOCKET_START_PRE);
775         } else
776                 socket_enter_start_post(s);
777
778         return;
779
780 fail:
781         log_warning("%s failed to run start-pre exectuable: %s", s->meta.id, strerror(-r));
782         socket_enter_dead(s, false);
783 }
784
785 static void socket_enter_running(Socket *s, int cfd) {
786         int r;
787
788         assert(s);
789
790         if (cfd < 0) {
791                 if ((r = manager_add_job(UNIT(s)->meta.manager, JOB_START, UNIT(s->service), JOB_REPLACE, true, NULL)) < 0)
792                         goto fail;
793
794                 socket_set_state(s, SOCKET_RUNNING);
795         } else {
796                 Unit *u;
797                 char *prefix, *instance, *name;
798
799                 if ((r = instance_from_socket(cfd, s->n_accepted++, &instance)))
800                         goto fail;
801
802                 if (!(prefix = unit_name_to_prefix(UNIT(s)->meta.id))) {
803                         free(instance);
804                         r = -ENOMEM;
805                         goto fail;
806                 }
807
808                 name = unit_name_build(prefix, instance, ".service");
809                 free(prefix);
810                 free(instance);
811
812                 if (!name)
813                         r = -ENOMEM;
814
815                 r = manager_load_unit(UNIT(s)->meta.manager, name, NULL, &u);
816                 free(name);
817
818                 if (r < 0)
819                         goto fail;
820
821                 if ((r = service_set_socket_fd(SERVICE(u), cfd) < 0))
822                         goto fail;
823
824                 cfd = -1;
825
826                 if ((r = manager_add_job(u->meta.manager, JOB_START, u, JOB_REPLACE, true, NULL)) < 0)
827                         goto fail;
828         }
829
830         return;
831
832 fail:
833         log_warning("%s failed to queue socket startup job: %s", s->meta.id, strerror(-r));
834         socket_enter_stop_pre(s, false);
835
836         if (cfd >= 0)
837                 close_nointr_nofail(cfd);
838 }
839
840 static void socket_run_next(Socket *s, bool success) {
841         int r;
842
843         assert(s);
844         assert(s->control_command);
845         assert(s->control_command->command_next);
846
847         if (!success)
848                 s->failure = true;
849
850         socket_unwatch_control_pid(s);
851
852         s->control_command = s->control_command->command_next;
853
854         if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
855                 goto fail;
856
857         return;
858
859 fail:
860         log_warning("%s failed to run spawn next executable: %s", s->meta.id, strerror(-r));
861
862         if (s->state == SOCKET_START_POST)
863                 socket_enter_stop_pre(s, false);
864         else if (s->state == SOCKET_STOP_POST)
865                 socket_enter_dead(s, false);
866         else
867                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
868 }
869
870 static int socket_start(Unit *u) {
871         Socket *s = SOCKET(u);
872
873         assert(s);
874
875         /* We cannot fulfill this request right now, try again later
876          * please! */
877         if (s->state == SOCKET_STOP_PRE ||
878             s->state == SOCKET_STOP_PRE_SIGKILL ||
879             s->state == SOCKET_STOP_PRE_SIGTERM ||
880             s->state == SOCKET_STOP_POST ||
881             s->state == SOCKET_FINAL_SIGTERM ||
882             s->state == SOCKET_FINAL_SIGKILL)
883                 return -EAGAIN;
884
885         if (s->state == SOCKET_START_PRE ||
886             s->state == SOCKET_START_POST)
887                 return 0;
888
889         /* Cannot run this without the service being around */
890         if (s->service) {
891                 if (s->service->meta.load_state != UNIT_LOADED)
892                         return -ENOENT;
893
894                 /* If the service is alredy actvie we cannot start the
895                  * socket */
896                 if (s->service->state != SERVICE_DEAD &&
897                     s->service->state != SERVICE_MAINTAINANCE &&
898                     s->service->state != SERVICE_AUTO_RESTART)
899                         return -EBUSY;
900         }
901
902         assert(s->state == SOCKET_DEAD || s->state == SOCKET_MAINTAINANCE);
903
904         s->failure = false;
905         socket_enter_start_pre(s);
906         return 0;
907 }
908
909 static int socket_stop(Unit *u) {
910         Socket *s = SOCKET(u);
911
912         assert(s);
913
914         /* We cannot fulfill this request right now, try again later
915          * please! */
916         if (s->state == SOCKET_START_PRE ||
917             s->state == SOCKET_START_POST)
918                 return -EAGAIN;
919
920         /* Already on it */
921         if (s->state == SOCKET_STOP_PRE ||
922             s->state == SOCKET_STOP_PRE_SIGTERM ||
923             s->state == SOCKET_STOP_PRE_SIGKILL ||
924             s->state == SOCKET_STOP_POST ||
925             s->state == SOCKET_FINAL_SIGTERM ||
926             s->state == SOCKET_FINAL_SIGTERM)
927                 return 0;
928
929         assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
930
931         socket_enter_stop_pre(s, true);
932         return 0;
933 }
934
935 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
936         Socket *s = SOCKET(u);
937         SocketPort *p;
938         int r;
939
940         assert(u);
941         assert(f);
942         assert(fds);
943
944         unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
945         unit_serialize_item(u, f, "failure", yes_no(s->failure));
946         unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
947
948         if (s->control_pid > 0)
949                 unit_serialize_item_format(u, f, "control-pid", "%u", (unsigned) s->control_pid);
950
951         if (s->control_command_id >= 0)
952                 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
953
954         LIST_FOREACH(port, p, s->ports) {
955                 int copy;
956
957                 if (p->fd < 0)
958                         continue;
959
960                 if ((copy = fdset_put_dup(fds, p->fd)) < 0)
961                         return copy;
962
963                 if (p->type == SOCKET_SOCKET) {
964                         char *t;
965
966                         if ((r = socket_address_print(&p->address, &t)) < 0)
967                                 return r;
968
969                         unit_serialize_item_format(u, f, "socket", "%i %s", copy, t);
970                         free(t);
971                 } else {
972                         assert(p->type == SOCKET_FIFO);
973                         unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
974                 }
975         }
976
977         return 0;
978 }
979
980 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
981         Socket *s = SOCKET(u);
982         int r;
983
984         assert(u);
985         assert(key);
986         assert(value);
987         assert(fds);
988
989         if (streq(key, "state")) {
990                 SocketState state;
991
992                 if ((state = socket_state_from_string(value)) < 0)
993                         log_debug("Failed to parse state value %s", value);
994                 else
995                         s->deserialized_state = state;
996         } else if (streq(key, "failure")) {
997                 int b;
998
999                 if ((b = parse_boolean(value)) < 0)
1000                         log_debug("Failed to parse failure value %s", value);
1001                 else
1002                         s->failure = b || s->failure;
1003
1004         } else if (streq(key, "n-accepted")) {
1005                 unsigned k;
1006
1007                 if ((r = safe_atou(value, &k)) < 0)
1008                         log_debug("Failed to parse n-accepted value %s", value);
1009                 else
1010                         s->n_accepted += k;
1011         } else if (streq(key, "control-pid")) {
1012                 unsigned pid;
1013
1014                 if ((r = safe_atou(value, &pid)) < 0 || pid <= 0)
1015                         log_debug("Failed to parse control-pid value %s", value);
1016                 else
1017                         s->control_pid = (pid_t) pid;
1018         } else if (streq(key, "control-command")) {
1019                 SocketExecCommand id;
1020
1021                 if ((id = socket_exec_command_from_string(value)) < 0)
1022                         log_debug("Failed to parse exec-command value %s", value);
1023                 else {
1024                         s->control_command_id = id;
1025                         s->control_command = s->exec_command[id];
1026                 }
1027         } else if (streq(key, "fifo")) {
1028                 int fd, skip = 0;
1029                 SocketPort *p;
1030
1031                 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1032                         log_debug("Failed to parse fifo value %s", value);
1033                 else {
1034
1035                         LIST_FOREACH(port, p, s->ports)
1036                                 if (streq(p->path, value+skip))
1037                                         break;
1038
1039                         if (p) {
1040                                 if (p->fd >= 0)
1041                                         close_nointr_nofail(p->fd);
1042                                 p->fd = fdset_remove(fds, fd);
1043                         }
1044                 }
1045
1046         } else if (streq(key, "socket")) {
1047                 int fd, skip = 0;
1048                 SocketPort *p;
1049
1050                 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1051                         log_debug("Failed to parse socket value %s", value);
1052                 else {
1053
1054                         LIST_FOREACH(port, p, s->ports)
1055                                 if (socket_address_is(&p->address, value+skip))
1056                                         break;
1057
1058                         if (p) {
1059                                 if (p->fd >= 0)
1060                                         close_nointr_nofail(p->fd);
1061                                 p->fd = fdset_remove(fds, fd);
1062                         }
1063                 }
1064
1065         } else
1066                 log_debug("Unknown serialization key '%s'", key);
1067
1068         return 0;
1069 }
1070
1071 static UnitActiveState socket_active_state(Unit *u) {
1072         assert(u);
1073
1074         return state_translation_table[SOCKET(u)->state];
1075 }
1076
1077 static const char *socket_sub_state_to_string(Unit *u) {
1078         assert(u);
1079
1080         return socket_state_to_string(SOCKET(u)->state);
1081 }
1082
1083 static void socket_fd_event(Unit *u, int fd, uint32_t events, Watch *w) {
1084         Socket *s = SOCKET(u);
1085         int cfd = -1;
1086
1087         assert(s);
1088         assert(fd >= 0);
1089
1090         log_debug("Incoming traffic on %s", u->meta.id);
1091
1092         if (events != EPOLLIN) {
1093                 log_error("Got invalid poll event on socket.");
1094                 goto fail;
1095         }
1096
1097         if (w->socket_accept) {
1098                 for (;;) {
1099
1100                         if ((cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK)) < 0) {
1101
1102                                 if (errno == EINTR)
1103                                         continue;
1104
1105                                 log_error("Failed to accept socket: %m");
1106                                 goto fail;
1107                         }
1108
1109                         break;
1110                 }
1111         }
1112
1113         socket_enter_running(s, cfd);
1114         return;
1115
1116 fail:
1117         socket_enter_stop_pre(s, false);
1118 }
1119
1120 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
1121         Socket *s = SOCKET(u);
1122         bool success;
1123
1124         assert(s);
1125         assert(pid >= 0);
1126
1127         success = code == CLD_EXITED && status == 0;
1128         s->failure = s->failure || !success;
1129
1130         assert(s->control_pid == pid);
1131         s->control_pid = 0;
1132
1133         if (s->control_command)
1134                 exec_status_fill(&s->control_command->exec_status, pid, code, status);
1135
1136         log_debug("%s control process exited, code=%s status=%i", u->meta.id, sigchld_code_to_string(code), status);
1137
1138         if (s->control_command && s->control_command->command_next && success) {
1139                 log_debug("%s running next command for state %s", u->meta.id, socket_state_to_string(s->state));
1140                 socket_run_next(s, success);
1141         } else {
1142                 s->control_command = NULL;
1143                 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1144
1145                 /* No further commands for this step, so let's figure
1146                  * out what to do next */
1147
1148                 log_debug("%s got final SIGCHLD for state %s", u->meta.id, socket_state_to_string(s->state));
1149
1150                 switch (s->state) {
1151
1152                 case SOCKET_START_PRE:
1153                         if (success)
1154                                 socket_enter_start_post(s);
1155                         else
1156                                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1157                         break;
1158
1159                 case SOCKET_START_POST:
1160                         if (success)
1161                                 socket_enter_listening(s);
1162                         else
1163                                 socket_enter_stop_pre(s, false);
1164                         break;
1165
1166                 case SOCKET_STOP_PRE:
1167                 case SOCKET_STOP_PRE_SIGTERM:
1168                 case SOCKET_STOP_PRE_SIGKILL:
1169                         socket_enter_stop_post(s, success);
1170                         break;
1171
1172                 case SOCKET_STOP_POST:
1173                 case SOCKET_FINAL_SIGTERM:
1174                 case SOCKET_FINAL_SIGKILL:
1175                         socket_enter_dead(s, success);
1176                         break;
1177
1178                 default:
1179                         assert_not_reached("Uh, control process died at wrong time.");
1180                 }
1181         }
1182 }
1183
1184 static void socket_timer_event(Unit *u, uint64_t elapsed, Watch *w) {
1185         Socket *s = SOCKET(u);
1186
1187         assert(s);
1188         assert(elapsed == 1);
1189         assert(w == &s->timer_watch);
1190
1191         switch (s->state) {
1192
1193         case SOCKET_START_PRE:
1194                 log_warning("%s starting timed out. Terminating.", u->meta.id);
1195                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1196
1197         case SOCKET_START_POST:
1198                 log_warning("%s starting timed out. Stopping.", u->meta.id);
1199                 socket_enter_stop_pre(s, false);
1200                 break;
1201
1202         case SOCKET_STOP_PRE:
1203                 log_warning("%s stopping timed out. Terminating.", u->meta.id);
1204                 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, false);
1205                 break;
1206
1207         case SOCKET_STOP_PRE_SIGTERM:
1208                 log_warning("%s stopping timed out. Killing.", u->meta.id);
1209                 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, false);
1210                 break;
1211
1212         case SOCKET_STOP_PRE_SIGKILL:
1213                 log_warning("%s still around after SIGKILL. Ignoring.", u->meta.id);
1214                 socket_enter_stop_post(s, false);
1215                 break;
1216
1217         case SOCKET_STOP_POST:
1218                 log_warning("%s stopping timed out (2). Terminating.", u->meta.id);
1219                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, false);
1220                 break;
1221
1222         case SOCKET_FINAL_SIGTERM:
1223                 log_warning("%s stopping timed out (2). Killing.", u->meta.id);
1224                 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, false);
1225                 break;
1226
1227         case SOCKET_FINAL_SIGKILL:
1228                 log_warning("%s still around after SIGKILL (2). Entering maintainance mode.", u->meta.id);
1229                 socket_enter_dead(s, false);
1230                 break;
1231
1232         default:
1233                 assert_not_reached("Timeout at wrong time.");
1234         }
1235 }
1236
1237 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
1238         int *rfds;
1239         unsigned rn_fds, k;
1240         SocketPort *p;
1241
1242         assert(s);
1243         assert(fds);
1244         assert(n_fds);
1245
1246         /* Called from the service code for requesting our fds */
1247
1248         rn_fds = 0;
1249         LIST_FOREACH(port, p, s->ports)
1250                 if (p->fd >= 0)
1251                         rn_fds++;
1252
1253         if (!(rfds = new(int, rn_fds)) < 0)
1254                 return -ENOMEM;
1255
1256         k = 0;
1257         LIST_FOREACH(port, p, s->ports)
1258                 if (p->fd >= 0)
1259                         rfds[k++] = p->fd;
1260
1261         assert(k == rn_fds);
1262
1263         *fds = rfds;
1264         *n_fds = rn_fds;
1265
1266         return 0;
1267 }
1268
1269 void socket_notify_service_dead(Socket *s) {
1270         assert(s);
1271
1272         /* The service is dead. Dang. */
1273
1274         if (s->state == SOCKET_RUNNING) {
1275                 log_debug("%s got notified about service death.", s->meta.id);
1276                 socket_enter_listening(s);
1277         }
1278 }
1279
1280 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
1281         [SOCKET_DEAD] = "dead",
1282         [SOCKET_START_PRE] = "start-pre",
1283         [SOCKET_START_POST] = "start-post",
1284         [SOCKET_LISTENING] = "listening",
1285         [SOCKET_RUNNING] = "running",
1286         [SOCKET_STOP_PRE] = "stop-pre",
1287         [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
1288         [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
1289         [SOCKET_STOP_POST] = "stop-post",
1290         [SOCKET_FINAL_SIGTERM] = "final-sigterm",
1291         [SOCKET_FINAL_SIGKILL] = "final-sigkill",
1292         [SOCKET_MAINTAINANCE] = "maintainance"
1293 };
1294
1295 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
1296
1297 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
1298         [SOCKET_EXEC_START_PRE] = "StartPre",
1299         [SOCKET_EXEC_START_POST] = "StartPost",
1300         [SOCKET_EXEC_STOP_PRE] = "StopPre",
1301         [SOCKET_EXEC_STOP_POST] = "StopPost"
1302 };
1303
1304 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
1305
1306 const UnitVTable socket_vtable = {
1307         .suffix = ".socket",
1308
1309         .init = socket_init,
1310         .done = socket_done,
1311         .load = socket_load,
1312
1313         .coldplug = socket_coldplug,
1314
1315         .dump = socket_dump,
1316
1317         .start = socket_start,
1318         .stop = socket_stop,
1319
1320         .serialize = socket_serialize,
1321         .deserialize_item = socket_deserialize_item,
1322
1323         .active_state = socket_active_state,
1324         .sub_state_to_string = socket_sub_state_to_string,
1325
1326         .fd_event = socket_fd_event,
1327         .sigchld_event = socket_sigchld_event,
1328         .timer_event = socket_timer_event,
1329
1330         .bus_message_handler = bus_socket_message_handler
1331 };