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