chiark / gitweb /
Make sure that keys are properly removed from hashmap
[elogind.git] / src / core / 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 Lesser General Public License as published by
10   the Free Software Foundation; either version 2.1 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   Lesser General Public License for more details.
17
18   You should have received a copy of the GNU Lesser 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 #include <netinet/tcp.h>
31 #include <mqueue.h>
32 #ifdef HAVE_XATTR
33 #include <attr/xattr.h>
34 #endif
35
36 #include "sd-event.h"
37 #include "log.h"
38 #include "load-dropin.h"
39 #include "load-fragment.h"
40 #include "strv.h"
41 #include "mkdir.h"
42 #include "path-util.h"
43 #include "unit-name.h"
44 #include "unit-printf.h"
45 #include "missing.h"
46 #include "special.h"
47 #include "label.h"
48 #include "exit-status.h"
49 #include "def.h"
50 #include "smack-util.h"
51 #include "bus-util.h"
52 #include "bus-error.h"
53 #include "dbus-socket.h"
54 #include "unit.h"
55 #include "socket.h"
56
57 static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
58         [SOCKET_DEAD] = UNIT_INACTIVE,
59         [SOCKET_START_PRE] = UNIT_ACTIVATING,
60         [SOCKET_START_POST] = UNIT_ACTIVATING,
61         [SOCKET_LISTENING] = UNIT_ACTIVE,
62         [SOCKET_RUNNING] = UNIT_ACTIVE,
63         [SOCKET_STOP_PRE] = UNIT_DEACTIVATING,
64         [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
65         [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
66         [SOCKET_STOP_POST] = UNIT_DEACTIVATING,
67         [SOCKET_FINAL_SIGTERM] = UNIT_DEACTIVATING,
68         [SOCKET_FINAL_SIGKILL] = UNIT_DEACTIVATING,
69         [SOCKET_FAILED] = UNIT_FAILED
70 };
71
72 static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
73 static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
74
75 static void socket_init(Unit *u) {
76         Socket *s = SOCKET(u);
77
78         assert(u);
79         assert(u->load_state == UNIT_STUB);
80
81         s->backlog = SOMAXCONN;
82         s->timeout_usec = u->manager->default_timeout_start_usec;
83         s->directory_mode = 0755;
84         s->socket_mode = 0666;
85
86         s->max_connections = 64;
87
88         s->priority = -1;
89         s->ip_tos = -1;
90         s->ip_ttl = -1;
91         s->mark = -1;
92
93         s->exec_context.std_output = u->manager->default_std_output;
94         s->exec_context.std_error = u->manager->default_std_error;
95
96         s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
97 }
98
99 static void socket_unwatch_control_pid(Socket *s) {
100         assert(s);
101
102         if (s->control_pid <= 0)
103                 return;
104
105         unit_unwatch_pid(UNIT(s), s->control_pid);
106         s->control_pid = 0;
107 }
108
109 void socket_free_ports(Socket *s) {
110         SocketPort *p;
111
112         assert(s);
113
114         while ((p = s->ports)) {
115                 LIST_REMOVE(port, s->ports, p);
116
117                 sd_event_source_unref(p->event_source);
118
119                 safe_close(p->fd);
120                 free(p->path);
121                 free(p);
122         }
123 }
124
125 static void socket_done(Unit *u) {
126         Socket *s = SOCKET(u);
127
128         assert(s);
129
130         socket_free_ports(s);
131
132         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
133         exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
134         s->control_command = NULL;
135
136         socket_unwatch_control_pid(s);
137
138         unit_ref_unset(&s->service);
139
140         free(s->tcp_congestion);
141         s->tcp_congestion = NULL;
142
143         free(s->bind_to_device);
144         s->bind_to_device = NULL;
145
146         free(s->smack);
147         free(s->smack_ip_in);
148         free(s->smack_ip_out);
149
150         s->timer_event_source = sd_event_source_unref(s->timer_event_source);
151 }
152
153 static int socket_arm_timer(Socket *s) {
154         int r;
155
156         assert(s);
157
158         if (s->timeout_usec <= 0) {
159                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
160                 return 0;
161         }
162
163         if (s->timer_event_source) {
164                 r = sd_event_source_set_time(s->timer_event_source, now(CLOCK_MONOTONIC) + s->timeout_usec);
165                 if (r < 0)
166                         return r;
167
168                 return sd_event_source_set_enabled(s->timer_event_source, SD_EVENT_ONESHOT);
169         }
170
171         return sd_event_add_time(
172                         UNIT(s)->manager->event,
173                         &s->timer_event_source,
174                         CLOCK_MONOTONIC,
175                         now(CLOCK_MONOTONIC) + s->timeout_usec, 0,
176                         socket_dispatch_timer, s);
177 }
178
179 static int socket_instantiate_service(Socket *s) {
180         _cleanup_free_ char *prefix = NULL;
181         _cleanup_free_ char *name = NULL;
182         int r;
183         Unit *u;
184
185         assert(s);
186
187         /* This fills in s->service if it isn't filled in yet. For
188          * Accept=yes sockets we create the next connection service
189          * here. For Accept=no this is mostly a NOP since the service
190          * is figured out at load time anyway. */
191
192         if (UNIT_DEREF(s->service))
193                 return 0;
194
195         assert(s->accept);
196
197         prefix = unit_name_to_prefix(UNIT(s)->id);
198         if (!prefix)
199                 return -ENOMEM;
200
201         if (asprintf(&name, "%s@%u.service", prefix, s->n_accepted) < 0)
202                 return -ENOMEM;
203
204         r = manager_load_unit(UNIT(s)->manager, name, NULL, NULL, &u);
205         if (r < 0)
206                 return r;
207
208 #ifdef HAVE_SYSV_COMPAT
209         if (SERVICE(u)->is_sysv) {
210                 log_error("Using SysV services for socket activation is not supported. Refusing.");
211                 return -ENOENT;
212         }
213 #endif
214
215         u->no_gc = true;
216         unit_ref_set(&s->service, u);
217
218         return unit_add_two_dependencies(UNIT(s), UNIT_BEFORE, UNIT_TRIGGERS, u, false);
219 }
220
221 static bool have_non_accept_socket(Socket *s) {
222         SocketPort *p;
223
224         assert(s);
225
226         if (!s->accept)
227                 return true;
228
229         LIST_FOREACH(port, p, s->ports) {
230
231                 if (p->type != SOCKET_SOCKET)
232                         return true;
233
234                 if (!socket_address_can_accept(&p->address))
235                         return true;
236         }
237
238         return false;
239 }
240
241 static int socket_add_mount_links(Socket *s) {
242         SocketPort *p;
243         int r;
244
245         assert(s);
246
247         LIST_FOREACH(port, p, s->ports) {
248                 const char *path = NULL;
249
250                 if (p->type == SOCKET_SOCKET)
251                         path = socket_address_get_path(&p->address);
252                 else if (p->type == SOCKET_FIFO || p->type == SOCKET_SPECIAL)
253                         path = p->path;
254
255                 if (!path)
256                         continue;
257
258                 r = unit_require_mounts_for(UNIT(s), path);
259                 if (r < 0)
260                         return r;
261         }
262
263         return 0;
264 }
265
266 static int socket_add_device_link(Socket *s) {
267         char *t;
268
269         assert(s);
270
271         if (!s->bind_to_device || streq(s->bind_to_device, "lo"))
272                 return 0;
273
274         t = strappenda("/sys/subsystem/net/devices/", s->bind_to_device);
275         return unit_add_node_link(UNIT(s), t, false);
276 }
277
278 static int socket_add_default_dependencies(Socket *s) {
279         int r;
280         assert(s);
281
282         r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, NULL, true);
283         if (r < 0)
284                 return r;
285
286         if (UNIT(s)->manager->running_as == SYSTEMD_SYSTEM) {
287                 r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, NULL, true);
288                 if (r < 0)
289                         return r;
290         }
291
292         return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, NULL, true);
293 }
294
295 _pure_ static bool socket_has_exec(Socket *s) {
296         unsigned i;
297         assert(s);
298
299         for (i = 0; i < _SOCKET_EXEC_COMMAND_MAX; i++)
300                 if (s->exec_command[i])
301                         return true;
302
303         return false;
304 }
305
306 static int socket_add_extras(Socket *s) {
307         Unit *u = UNIT(s);
308         int r;
309
310         assert(s);
311
312         if (have_non_accept_socket(s)) {
313
314                 if (!UNIT_DEREF(s->service)) {
315                         Unit *x;
316
317                         r = unit_load_related_unit(u, ".service", &x);
318                         if (r < 0)
319                                 return r;
320
321                         unit_ref_set(&s->service, x);
322                 }
323
324                 r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, UNIT_DEREF(s->service), true);
325                 if (r < 0)
326                         return r;
327         }
328
329         r = socket_add_mount_links(s);
330         if (r < 0)
331                 return r;
332
333         r = socket_add_device_link(s);
334         if (r < 0)
335                 return r;
336
337         r = unit_patch_contexts(u);
338         if (r < 0)
339                 return r;
340
341         if (socket_has_exec(s)) {
342                 r = unit_add_exec_dependencies(u, &s->exec_context);
343                 if (r < 0)
344                         return r;
345
346                 r = unit_add_default_slice(u, &s->cgroup_context);
347                 if (r < 0)
348                         return r;
349         }
350
351         if (u->default_dependencies) {
352                 r = socket_add_default_dependencies(s);
353                 if (r < 0)
354                         return r;
355         }
356
357         return 0;
358 }
359
360 static int socket_verify(Socket *s) {
361         assert(s);
362
363         if (UNIT(s)->load_state != UNIT_LOADED)
364                 return 0;
365
366         if (!s->ports) {
367                 log_error_unit(UNIT(s)->id, "%s lacks Listen setting. Refusing.", UNIT(s)->id);
368                 return -EINVAL;
369         }
370
371         if (s->accept && have_non_accept_socket(s)) {
372                 log_error_unit(UNIT(s)->id, "%s configured for accepting sockets, but sockets are non-accepting. Refusing.",
373                                UNIT(s)->id);
374                 return -EINVAL;
375         }
376
377         if (s->accept && s->max_connections <= 0) {
378                 log_error_unit(UNIT(s)->id, "%s's MaxConnection setting too small. Refusing.", UNIT(s)->id);
379                 return -EINVAL;
380         }
381
382         if (s->accept && UNIT_DEREF(s->service)) {
383                 log_error_unit(UNIT(s)->id, "Explicit service configuration for accepting sockets not supported on %s. Refusing.", UNIT(s)->id);
384                 return -EINVAL;
385         }
386
387         if (s->exec_context.pam_name && s->kill_context.kill_mode != KILL_CONTROL_GROUP) {
388                 log_error_unit(UNIT(s)->id, "%s has PAM enabled. Kill mode must be set to 'control-group'. Refusing.", UNIT(s)->id);
389                 return -EINVAL;
390         }
391
392         return 0;
393 }
394
395 static int socket_load(Unit *u) {
396         Socket *s = SOCKET(u);
397         int r;
398
399         assert(u);
400         assert(u->load_state == UNIT_STUB);
401
402         r = unit_load_fragment_and_dropin(u);
403         if (r < 0)
404                 return r;
405
406         if (u->load_state == UNIT_LOADED) {
407                 /* This is a new unit? Then let's add in some extras */
408                 r = socket_add_extras(s);
409                 if (r < 0)
410                         return r;
411         }
412
413         return socket_verify(s);
414 }
415
416 _const_ static const char* listen_lookup(int family, int type) {
417
418         if (family == AF_NETLINK)
419                 return "ListenNetlink";
420
421         if (type == SOCK_STREAM)
422                 return "ListenStream";
423         else if (type == SOCK_DGRAM)
424                 return "ListenDatagram";
425         else if (type == SOCK_SEQPACKET)
426                 return "ListenSequentialPacket";
427
428         assert_not_reached("Unknown socket type");
429         return NULL;
430 }
431
432 static void socket_dump(Unit *u, FILE *f, const char *prefix) {
433         SocketExecCommand c;
434         Socket *s = SOCKET(u);
435         SocketPort *p;
436         const char *prefix2;
437
438         assert(s);
439         assert(f);
440
441         prefix2 = strappenda(prefix, "\t");
442
443         fprintf(f,
444                 "%sSocket State: %s\n"
445                 "%sResult: %s\n"
446                 "%sBindIPv6Only: %s\n"
447                 "%sBacklog: %u\n"
448                 "%sSocketMode: %04o\n"
449                 "%sDirectoryMode: %04o\n"
450                 "%sKeepAlive: %s\n"
451                 "%sFreeBind: %s\n"
452                 "%sTransparent: %s\n"
453                 "%sBroadcast: %s\n"
454                 "%sPassCredentials: %s\n"
455                 "%sPassSecurity: %s\n"
456                 "%sTCPCongestion: %s\n",
457                 prefix, socket_state_to_string(s->state),
458                 prefix, socket_result_to_string(s->result),
459                 prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
460                 prefix, s->backlog,
461                 prefix, s->socket_mode,
462                 prefix, s->directory_mode,
463                 prefix, yes_no(s->keep_alive),
464                 prefix, yes_no(s->free_bind),
465                 prefix, yes_no(s->transparent),
466                 prefix, yes_no(s->broadcast),
467                 prefix, yes_no(s->pass_cred),
468                 prefix, yes_no(s->pass_sec),
469                 prefix, strna(s->tcp_congestion));
470
471         if (s->control_pid > 0)
472                 fprintf(f,
473                         "%sControl PID: "PID_FMT"\n",
474                         prefix, s->control_pid);
475
476         if (s->bind_to_device)
477                 fprintf(f,
478                         "%sBindToDevice: %s\n",
479                         prefix, s->bind_to_device);
480
481         if (s->accept)
482                 fprintf(f,
483                         "%sAccepted: %u\n"
484                         "%sNConnections: %u\n"
485                         "%sMaxConnections: %u\n",
486                         prefix, s->n_accepted,
487                         prefix, s->n_connections,
488                         prefix, s->max_connections);
489
490         if (s->priority >= 0)
491                 fprintf(f,
492                         "%sPriority: %i\n",
493                         prefix, s->priority);
494
495         if (s->receive_buffer > 0)
496                 fprintf(f,
497                         "%sReceiveBuffer: %zu\n",
498                         prefix, s->receive_buffer);
499
500         if (s->send_buffer > 0)
501                 fprintf(f,
502                         "%sSendBuffer: %zu\n",
503                         prefix, s->send_buffer);
504
505         if (s->ip_tos >= 0)
506                 fprintf(f,
507                         "%sIPTOS: %i\n",
508                         prefix, s->ip_tos);
509
510         if (s->ip_ttl >= 0)
511                 fprintf(f,
512                         "%sIPTTL: %i\n",
513                         prefix, s->ip_ttl);
514
515         if (s->pipe_size > 0)
516                 fprintf(f,
517                         "%sPipeSize: %zu\n",
518                         prefix, s->pipe_size);
519
520         if (s->mark >= 0)
521                 fprintf(f,
522                         "%sMark: %i\n",
523                         prefix, s->mark);
524
525         if (s->mq_maxmsg > 0)
526                 fprintf(f,
527                         "%sMessageQueueMaxMessages: %li\n",
528                         prefix, s->mq_maxmsg);
529
530         if (s->mq_msgsize > 0)
531                 fprintf(f,
532                         "%sMessageQueueMessageSize: %li\n",
533                         prefix, s->mq_msgsize);
534
535         if (s->reuse_port)
536                 fprintf(f,
537                         "%sReusePort: %s\n",
538                          prefix, yes_no(s->reuse_port));
539
540         if (s->smack)
541                 fprintf(f,
542                         "%sSmackLabel: %s\n",
543                         prefix, s->smack);
544
545         if (s->smack_ip_in)
546                 fprintf(f,
547                         "%sSmackLabelIPIn: %s\n",
548                         prefix, s->smack_ip_in);
549
550         if (s->smack_ip_out)
551                 fprintf(f,
552                         "%sSmackLabelIPOut: %s\n",
553                         prefix, s->smack_ip_out);
554
555         LIST_FOREACH(port, p, s->ports) {
556
557                 if (p->type == SOCKET_SOCKET) {
558                         const char *t;
559                         int r;
560                         char *k = NULL;
561
562                         if ((r = socket_address_print(&p->address, &k)) < 0)
563                                 t = strerror(-r);
564                         else
565                                 t = k;
566
567                         fprintf(f, "%s%s: %s\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type), t);
568                         free(k);
569                 } else if (p->type == SOCKET_SPECIAL)
570                         fprintf(f, "%sListenSpecial: %s\n", prefix, p->path);
571                 else if (p->type == SOCKET_MQUEUE)
572                         fprintf(f, "%sListenMessageQueue: %s\n", prefix, p->path);
573                 else
574                         fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
575         }
576
577         exec_context_dump(&s->exec_context, f, prefix);
578         kill_context_dump(&s->kill_context, f, prefix);
579
580         for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
581                 if (!s->exec_command[c])
582                         continue;
583
584                 fprintf(f, "%s-> %s:\n",
585                         prefix, socket_exec_command_to_string(c));
586
587                 exec_command_dump_list(s->exec_command[c], f, prefix2);
588         }
589 }
590
591 static int instance_from_socket(int fd, unsigned nr, char **instance) {
592         socklen_t l;
593         char *r;
594         union sockaddr_union local, remote;
595
596         assert(fd >= 0);
597         assert(instance);
598
599         l = sizeof(local);
600         if (getsockname(fd, &local.sa, &l) < 0)
601                 return -errno;
602
603         l = sizeof(remote);
604         if (getpeername(fd, &remote.sa, &l) < 0)
605                 return -errno;
606
607         switch (local.sa.sa_family) {
608
609         case AF_INET: {
610                 uint32_t
611                         a = ntohl(local.in.sin_addr.s_addr),
612                         b = ntohl(remote.in.sin_addr.s_addr);
613
614                 if (asprintf(&r,
615                              "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
616                              nr,
617                              a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
618                              ntohs(local.in.sin_port),
619                              b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
620                              ntohs(remote.in.sin_port)) < 0)
621                         return -ENOMEM;
622
623                 break;
624         }
625
626         case AF_INET6: {
627                 static const unsigned char ipv4_prefix[] = {
628                         0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
629                 };
630
631                 if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
632                     memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
633                         const uint8_t
634                                 *a = local.in6.sin6_addr.s6_addr+12,
635                                 *b = remote.in6.sin6_addr.s6_addr+12;
636
637                         if (asprintf(&r,
638                                      "%u-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
639                                      nr,
640                                      a[0], a[1], a[2], a[3],
641                                      ntohs(local.in6.sin6_port),
642                                      b[0], b[1], b[2], b[3],
643                                      ntohs(remote.in6.sin6_port)) < 0)
644                                 return -ENOMEM;
645                 } else {
646                         char a[INET6_ADDRSTRLEN], b[INET6_ADDRSTRLEN];
647
648                         if (asprintf(&r,
649                                      "%u-%s:%u-%s:%u",
650                                      nr,
651                                      inet_ntop(AF_INET6, &local.in6.sin6_addr, a, sizeof(a)),
652                                      ntohs(local.in6.sin6_port),
653                                      inet_ntop(AF_INET6, &remote.in6.sin6_addr, b, sizeof(b)),
654                                      ntohs(remote.in6.sin6_port)) < 0)
655                                 return -ENOMEM;
656                 }
657
658                 break;
659         }
660
661         case AF_UNIX: {
662                 struct ucred ucred;
663                 int k;
664
665                 k = getpeercred(fd, &ucred);
666                 if (k >= 0) {
667                         if (asprintf(&r,
668                                      "%u-"PID_FMT"-"UID_FMT,
669                                      nr, ucred.pid, ucred.uid) < 0)
670                                 return -ENOMEM;
671                 } else if (k == -ENODATA) {
672                         /* This handles the case where somebody is
673                          * connecting from another pid/uid namespace
674                          * (e.g. from outside of our container). */
675                         if (asprintf(&r,
676                                      "%u-unknown",
677                                      nr) < 0)
678                                 return -ENOMEM;
679                 } else
680                         return k;
681
682                 break;
683         }
684
685         default:
686                 assert_not_reached("Unhandled socket type.");
687         }
688
689         *instance = r;
690         return 0;
691 }
692
693 static void socket_close_fds(Socket *s) {
694         SocketPort *p;
695
696         assert(s);
697
698         LIST_FOREACH(port, p, s->ports) {
699
700                 p->event_source = sd_event_source_unref(p->event_source);
701
702                 if (p->fd < 0)
703                         continue;
704
705                 p->fd = safe_close(p->fd);
706
707                 /* One little note: we should never delete any sockets
708                  * in the file system here! After all some other
709                  * process we spawned might still have a reference of
710                  * this fd and wants to continue to use it. Therefore
711                  * we delete sockets in the file system before we
712                  * create a new one, not after we stopped using
713                  * one! */
714         }
715 }
716
717 static void socket_apply_socket_options(Socket *s, int fd) {
718         assert(s);
719         assert(fd >= 0);
720
721         if (s->keep_alive) {
722                 int b = s->keep_alive;
723                 if (setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &b, sizeof(b)) < 0)
724                         log_warning_unit(UNIT(s)->id, "SO_KEEPALIVE failed: %m");
725         }
726
727         if (s->broadcast) {
728                 int one = 1;
729                 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &one, sizeof(one)) < 0)
730                         log_warning_unit(UNIT(s)->id, "SO_BROADCAST failed: %m");
731         }
732
733         if (s->pass_cred) {
734                 int one = 1;
735                 if (setsockopt(fd, SOL_SOCKET, SO_PASSCRED, &one, sizeof(one)) < 0)
736                         log_warning_unit(UNIT(s)->id, "SO_PASSCRED failed: %m");
737         }
738
739         if (s->pass_sec) {
740                 int one = 1;
741                 if (setsockopt(fd, SOL_SOCKET, SO_PASSSEC, &one, sizeof(one)) < 0)
742                         log_warning_unit(UNIT(s)->id, "SO_PASSSEC failed: %m");
743         }
744
745         if (s->priority >= 0)
746                 if (setsockopt(fd, SOL_SOCKET, SO_PRIORITY, &s->priority, sizeof(s->priority)) < 0)
747                         log_warning_unit(UNIT(s)->id, "SO_PRIORITY failed: %m");
748
749         if (s->receive_buffer > 0) {
750                 int value = (int) s->receive_buffer;
751
752                 /* We first try with SO_RCVBUFFORCE, in case we have the perms for that */
753
754                 if (setsockopt(fd, SOL_SOCKET, SO_RCVBUFFORCE, &value, sizeof(value)) < 0)
755                         if (setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &value, sizeof(value)) < 0)
756                                 log_warning_unit(UNIT(s)->id, "SO_RCVBUF failed: %m");
757         }
758
759         if (s->send_buffer > 0) {
760                 int value = (int) s->send_buffer;
761                 if (setsockopt(fd, SOL_SOCKET, SO_SNDBUFFORCE, &value, sizeof(value)) < 0)
762                         if (setsockopt(fd, SOL_SOCKET, SO_SNDBUF, &value, sizeof(value)) < 0)
763                                 log_warning_unit(UNIT(s)->id, "SO_SNDBUF failed: %m");
764         }
765
766         if (s->mark >= 0)
767                 if (setsockopt(fd, SOL_SOCKET, SO_MARK, &s->mark, sizeof(s->mark)) < 0)
768                         log_warning_unit(UNIT(s)->id, "SO_MARK failed: %m");
769
770         if (s->ip_tos >= 0)
771                 if (setsockopt(fd, IPPROTO_IP, IP_TOS, &s->ip_tos, sizeof(s->ip_tos)) < 0)
772                         log_warning_unit(UNIT(s)->id, "IP_TOS failed: %m");
773
774         if (s->ip_ttl >= 0) {
775                 int r, x;
776
777                 r = setsockopt(fd, IPPROTO_IP, IP_TTL, &s->ip_ttl, sizeof(s->ip_ttl));
778
779                 if (socket_ipv6_is_supported())
780                         x = setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &s->ip_ttl, sizeof(s->ip_ttl));
781                 else {
782                         x = -1;
783                         errno = EAFNOSUPPORT;
784                 }
785
786                 if (r < 0 && x < 0)
787                         log_warning_unit(UNIT(s)->id,
788                                          "IP_TTL/IPV6_UNICAST_HOPS failed: %m");
789         }
790
791         if (s->tcp_congestion)
792                 if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
793                         log_warning_unit(UNIT(s)->id, "TCP_CONGESTION failed: %m");
794
795         if (s->reuse_port) {
796                 int b = s->reuse_port;
797                 if (setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &b, sizeof(b)) < 0)
798                         log_warning_unit(UNIT(s)->id, "SO_REUSEPORT failed: %m");
799         }
800
801         if (s->smack_ip_in)
802                 if (smack_label_ip_in_fd(fd, s->smack_ip_in) < 0)
803                         log_error_unit(UNIT(s)->id, "smack_label_ip_in_fd: %m");
804
805         if (s->smack_ip_out)
806                 if (smack_label_ip_out_fd(fd, s->smack_ip_out) < 0)
807                         log_error_unit(UNIT(s)->id, "smack_label_ip_out_fd: %m");
808 }
809
810 static void socket_apply_fifo_options(Socket *s, int fd) {
811         assert(s);
812         assert(fd >= 0);
813
814         if (s->pipe_size > 0)
815                 if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
816                         log_warning_unit(UNIT(s)->id,
817                                          "F_SETPIPE_SZ: %m");
818
819         if (s->smack)
820                 if (smack_label_fd(fd, s->smack) < 0)
821                         log_error_unit(UNIT(s)->id, "smack_label_fd: %m");
822 }
823
824 static int fifo_address_create(
825                 const char *path,
826                 mode_t directory_mode,
827                 mode_t socket_mode,
828                 int *_fd) {
829
830         int fd = -1, r = 0;
831         struct stat st;
832         mode_t old_mask;
833
834         assert(path);
835         assert(_fd);
836
837         mkdir_parents_label(path, directory_mode);
838
839         r = label_context_set(path, S_IFIFO);
840         if (r < 0)
841                 goto fail;
842
843         /* Enforce the right access mode for the fifo */
844         old_mask = umask(~ socket_mode);
845
846         /* Include the original umask in our mask */
847         umask(~socket_mode | old_mask);
848
849         r = mkfifo(path, socket_mode);
850         umask(old_mask);
851
852         if (r < 0 && errno != EEXIST) {
853                 r = -errno;
854                 goto fail;
855         }
856
857         if ((fd = open(path, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
858                 r = -errno;
859                 goto fail;
860         }
861
862         label_context_clear();
863
864         if (fstat(fd, &st) < 0) {
865                 r = -errno;
866                 goto fail;
867         }
868
869         if (!S_ISFIFO(st.st_mode) ||
870             (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
871             st.st_uid != getuid() ||
872             st.st_gid != getgid()) {
873
874                 r = -EEXIST;
875                 goto fail;
876         }
877
878         *_fd = fd;
879         return 0;
880
881 fail:
882         label_context_clear();
883         safe_close(fd);
884
885         return r;
886 }
887
888 static int special_address_create(
889                 const char *path,
890                 int *_fd) {
891
892         int fd = -1, r = 0;
893         struct stat st;
894
895         assert(path);
896         assert(_fd);
897
898         if ((fd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW)) < 0) {
899                 r = -errno;
900                 goto fail;
901         }
902
903         if (fstat(fd, &st) < 0) {
904                 r = -errno;
905                 goto fail;
906         }
907
908         /* Check whether this is a /proc, /sys or /dev file or char device */
909         if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode)) {
910                 r = -EEXIST;
911                 goto fail;
912         }
913
914         *_fd = fd;
915         return 0;
916
917 fail:
918         safe_close(fd);
919
920         return r;
921 }
922
923 static int mq_address_create(
924                 const char *path,
925                 mode_t mq_mode,
926                 long maxmsg,
927                 long msgsize,
928                 int *_fd) {
929
930         int fd = -1, r = 0;
931         struct stat st;
932         mode_t old_mask;
933         struct mq_attr _attr, *attr = NULL;
934
935         assert(path);
936         assert(_fd);
937
938         if (maxmsg > 0 && msgsize > 0) {
939                 zero(_attr);
940                 _attr.mq_flags = O_NONBLOCK;
941                 _attr.mq_maxmsg = maxmsg;
942                 _attr.mq_msgsize = msgsize;
943                 attr = &_attr;
944         }
945
946         /* Enforce the right access mode for the mq */
947         old_mask = umask(~ mq_mode);
948
949         /* Include the original umask in our mask */
950         umask(~mq_mode | old_mask);
951
952         fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
953         umask(old_mask);
954
955         if (fd < 0) {
956                 r = -errno;
957                 goto fail;
958         }
959
960         if (fstat(fd, &st) < 0) {
961                 r = -errno;
962                 goto fail;
963         }
964
965         if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
966             st.st_uid != getuid() ||
967             st.st_gid != getgid()) {
968
969                 r = -EEXIST;
970                 goto fail;
971         }
972
973         *_fd = fd;
974         return 0;
975
976 fail:
977         safe_close(fd);
978         return r;
979 }
980
981 static int socket_open_fds(Socket *s) {
982         SocketPort *p;
983         int r;
984         char *label = NULL;
985         bool know_label = false;
986
987         assert(s);
988
989         LIST_FOREACH(port, p, s->ports) {
990
991                 if (p->fd >= 0)
992                         continue;
993
994                 if (p->type == SOCKET_SOCKET) {
995
996                         if (!know_label) {
997
998                                 if ((r = socket_instantiate_service(s)) < 0)
999                                         return r;
1000
1001                                 if (UNIT_ISSET(s->service) &&
1002                                     SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]) {
1003                                         r = label_get_create_label_from_exe(SERVICE(UNIT_DEREF(s->service))->exec_command[SERVICE_EXEC_START]->path, &label);
1004
1005                                         if (r < 0) {
1006                                                 if (r != -EPERM)
1007                                                         return r;
1008                                         }
1009                                 }
1010
1011                                 know_label = true;
1012                         }
1013
1014                         r = socket_address_listen(
1015                                         &p->address,
1016                                         SOCK_CLOEXEC|SOCK_NONBLOCK,
1017                                         s->backlog,
1018                                         s->bind_ipv6_only,
1019                                         s->bind_to_device,
1020                                         s->free_bind,
1021                                         s->transparent,
1022                                         s->directory_mode,
1023                                         s->socket_mode,
1024                                         label);
1025                         if (r < 0)
1026                                 goto rollback;
1027
1028                         p->fd = r;
1029                         socket_apply_socket_options(s, p->fd);
1030
1031                 } else  if (p->type == SOCKET_SPECIAL) {
1032
1033                         r = special_address_create(
1034                                         p->path,
1035                                         &p->fd);
1036                         if (r < 0)
1037                                 goto rollback;
1038
1039                 } else  if (p->type == SOCKET_FIFO) {
1040
1041                         r = fifo_address_create(
1042                                         p->path,
1043                                         s->directory_mode,
1044                                         s->socket_mode,
1045                                         &p->fd);
1046                         if (r < 0)
1047                                 goto rollback;
1048
1049                         socket_apply_fifo_options(s, p->fd);
1050                 } else if (p->type == SOCKET_MQUEUE) {
1051
1052                         r = mq_address_create(
1053                                         p->path,
1054                                         s->socket_mode,
1055                                         s->mq_maxmsg,
1056                                         s->mq_msgsize,
1057                                         &p->fd);
1058                         if (r < 0)
1059                                 goto rollback;
1060                 } else
1061                         assert_not_reached("Unknown port type");
1062         }
1063
1064         label_free(label);
1065         return 0;
1066
1067 rollback:
1068         socket_close_fds(s);
1069         label_free(label);
1070         return r;
1071 }
1072
1073 static void socket_unwatch_fds(Socket *s) {
1074         SocketPort *p;
1075         int r;
1076
1077         assert(s);
1078
1079         LIST_FOREACH(port, p, s->ports) {
1080                 if (p->fd < 0)
1081                         continue;
1082
1083                 if (p->event_source) {
1084                         r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
1085                         if (r < 0)
1086                                 log_debug_unit(UNIT(s)->id, "Failed to disable event source.");
1087                 }
1088         }
1089 }
1090
1091 static int socket_watch_fds(Socket *s) {
1092         SocketPort *p;
1093         int r;
1094
1095         assert(s);
1096
1097         LIST_FOREACH(port, p, s->ports) {
1098                 if (p->fd < 0)
1099                         continue;
1100
1101                 if (p->event_source)
1102                         r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
1103                 else
1104                         r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
1105
1106                 if (r < 0) {
1107                         log_warning_unit(UNIT(s)->id, "Failed to watch listening fds: %s", strerror(-r));
1108                         goto fail;
1109                 }
1110         }
1111
1112         return 0;
1113
1114 fail:
1115         socket_unwatch_fds(s);
1116         return r;
1117 }
1118
1119 static void socket_set_state(Socket *s, SocketState state) {
1120         SocketState old_state;
1121         assert(s);
1122
1123         old_state = s->state;
1124         s->state = state;
1125
1126         if (state != SOCKET_START_PRE &&
1127             state != SOCKET_START_POST &&
1128             state != SOCKET_STOP_PRE &&
1129             state != SOCKET_STOP_PRE_SIGTERM &&
1130             state != SOCKET_STOP_PRE_SIGKILL &&
1131             state != SOCKET_STOP_POST &&
1132             state != SOCKET_FINAL_SIGTERM &&
1133             state != SOCKET_FINAL_SIGKILL) {
1134
1135                 s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1136                 socket_unwatch_control_pid(s);
1137                 s->control_command = NULL;
1138                 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
1139         }
1140
1141         if (state != SOCKET_LISTENING)
1142                 socket_unwatch_fds(s);
1143
1144         if (state != SOCKET_START_POST &&
1145             state != SOCKET_LISTENING &&
1146             state != SOCKET_RUNNING &&
1147             state != SOCKET_STOP_PRE &&
1148             state != SOCKET_STOP_PRE_SIGTERM &&
1149             state != SOCKET_STOP_PRE_SIGKILL)
1150                 socket_close_fds(s);
1151
1152         if (state != old_state)
1153                 log_debug_unit(UNIT(s)->id, "%s changed %s -> %s",
1154                                UNIT(s)->id, socket_state_to_string(old_state), socket_state_to_string(state));
1155
1156         unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], true);
1157 }
1158
1159 static int socket_coldplug(Unit *u) {
1160         Socket *s = SOCKET(u);
1161         int r;
1162
1163         assert(s);
1164         assert(s->state == SOCKET_DEAD);
1165
1166         if (s->deserialized_state == s->state)
1167                 return 0;
1168
1169         if (s->deserialized_state == SOCKET_START_PRE ||
1170             s->deserialized_state == SOCKET_START_POST ||
1171             s->deserialized_state == SOCKET_STOP_PRE ||
1172             s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
1173             s->deserialized_state == SOCKET_STOP_PRE_SIGKILL ||
1174             s->deserialized_state == SOCKET_STOP_POST ||
1175             s->deserialized_state == SOCKET_FINAL_SIGTERM ||
1176             s->deserialized_state == SOCKET_FINAL_SIGKILL) {
1177
1178                 if (s->control_pid <= 0)
1179                         return -EBADMSG;
1180
1181                 r = unit_watch_pid(UNIT(s), s->control_pid);
1182                 if (r < 0)
1183                         return r;
1184
1185                 r = socket_arm_timer(s);
1186                 if (r < 0)
1187                         return r;
1188         }
1189
1190         if (s->deserialized_state == SOCKET_START_POST ||
1191             s->deserialized_state == SOCKET_LISTENING ||
1192             s->deserialized_state == SOCKET_RUNNING ||
1193             s->deserialized_state == SOCKET_STOP_PRE ||
1194             s->deserialized_state == SOCKET_STOP_PRE_SIGTERM ||
1195             s->deserialized_state == SOCKET_STOP_PRE_SIGKILL) {
1196                 r = socket_open_fds(s);
1197                 if (r < 0)
1198                         return r;
1199         }
1200
1201         if (s->deserialized_state == SOCKET_LISTENING) {
1202                 r = socket_watch_fds(s);
1203                 if (r < 0)
1204                         return r;
1205         }
1206
1207         socket_set_state(s, s->deserialized_state);
1208         return 0;
1209 }
1210
1211 static int socket_spawn(Socket *s, ExecCommand *c, pid_t *_pid) {
1212         pid_t pid;
1213         int r;
1214         char **argv;
1215
1216         assert(s);
1217         assert(c);
1218         assert(_pid);
1219
1220         unit_realize_cgroup(UNIT(s));
1221
1222         r = unit_setup_exec_runtime(UNIT(s));
1223         if (r < 0)
1224                 goto fail;
1225
1226         r = socket_arm_timer(s);
1227         if (r < 0)
1228                 goto fail;
1229
1230         r = unit_full_printf_strv(UNIT(s), c->argv, &argv);
1231         if (r < 0)
1232                 goto fail;
1233
1234         r = exec_spawn(c,
1235                        argv,
1236                        &s->exec_context,
1237                        NULL, 0,
1238                        UNIT(s)->manager->environment,
1239                        true,
1240                        true,
1241                        true,
1242                        UNIT(s)->manager->confirm_spawn,
1243                        UNIT(s)->manager->cgroup_supported,
1244                        UNIT(s)->cgroup_path,
1245                        manager_get_runtime_prefix(UNIT(s)->manager),
1246                        UNIT(s)->id,
1247                        0,
1248                        NULL,
1249                        s->exec_runtime,
1250                        &pid);
1251
1252         strv_free(argv);
1253         if (r < 0)
1254                 goto fail;
1255
1256         r = unit_watch_pid(UNIT(s), pid);
1257         if (r < 0)
1258                 /* FIXME: we need to do something here */
1259                 goto fail;
1260
1261         *_pid = pid;
1262
1263         return 0;
1264
1265 fail:
1266         s->timer_event_source = sd_event_source_unref(s->timer_event_source);
1267
1268         return r;
1269 }
1270
1271 static void socket_enter_dead(Socket *s, SocketResult f) {
1272         assert(s);
1273
1274         if (f != SOCKET_SUCCESS)
1275                 s->result = f;
1276
1277         exec_runtime_destroy(s->exec_runtime);
1278         s->exec_runtime = exec_runtime_unref(s->exec_runtime);
1279
1280         exec_context_destroy_runtime_directory(&s->exec_context, manager_get_runtime_prefix(UNIT(s)->manager));
1281
1282         socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
1283 }
1284
1285 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
1286
1287 static void socket_enter_stop_post(Socket *s, SocketResult f) {
1288         int r;
1289         assert(s);
1290
1291         if (f != SOCKET_SUCCESS)
1292                 s->result = f;
1293
1294         socket_unwatch_control_pid(s);
1295
1296         s->control_command_id = SOCKET_EXEC_STOP_POST;
1297
1298         if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST])) {
1299                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1300                         goto fail;
1301
1302                 socket_set_state(s, SOCKET_STOP_POST);
1303         } else
1304                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
1305
1306         return;
1307
1308 fail:
1309         log_warning_unit(UNIT(s)->id,
1310                          "%s failed to run 'stop-post' task: %s",
1311                          UNIT(s)->id, strerror(-r));
1312         socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1313 }
1314
1315 static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
1316         int r;
1317
1318         assert(s);
1319
1320         if (f != SOCKET_SUCCESS)
1321                 s->result = f;
1322
1323         r = unit_kill_context(
1324                         UNIT(s),
1325                         &s->kill_context,
1326                         state != SOCKET_STOP_PRE_SIGTERM && state != SOCKET_FINAL_SIGTERM,
1327                         -1,
1328                         s->control_pid,
1329                         false);
1330         if (r < 0)
1331                 goto fail;
1332
1333         if (r > 0) {
1334                 r = socket_arm_timer(s);
1335                 if (r < 0)
1336                         goto fail;
1337
1338                 socket_set_state(s, state);
1339         } else if (state == SOCKET_STOP_PRE_SIGTERM)
1340                 socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
1341         else if (state == SOCKET_STOP_PRE_SIGKILL)
1342                 socket_enter_stop_post(s, SOCKET_SUCCESS);
1343         else if (state == SOCKET_FINAL_SIGTERM)
1344                 socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
1345         else
1346                 socket_enter_dead(s, SOCKET_SUCCESS);
1347
1348         return;
1349
1350 fail:
1351         log_warning_unit(UNIT(s)->id, "%s failed to kill processes: %s", UNIT(s)->id, strerror(-r));
1352
1353         if (state == SOCKET_STOP_PRE_SIGTERM || state == SOCKET_STOP_PRE_SIGKILL)
1354                 socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1355         else
1356                 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1357 }
1358
1359 static void socket_enter_stop_pre(Socket *s, SocketResult f) {
1360         int r;
1361         assert(s);
1362
1363         if (f != SOCKET_SUCCESS)
1364                 s->result = f;
1365
1366         socket_unwatch_control_pid(s);
1367
1368         s->control_command_id = SOCKET_EXEC_STOP_PRE;
1369
1370         if ((s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE])) {
1371                 if ((r = socket_spawn(s, s->control_command, &s->control_pid)) < 0)
1372                         goto fail;
1373
1374                 socket_set_state(s, SOCKET_STOP_PRE);
1375         } else
1376                 socket_enter_stop_post(s, SOCKET_SUCCESS);
1377
1378         return;
1379
1380 fail:
1381         log_warning_unit(UNIT(s)->id, "%s failed to run 'stop-pre' task: %s", UNIT(s)->id, strerror(-r));
1382         socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
1383 }
1384
1385 static void socket_enter_listening(Socket *s) {
1386         int r;
1387         assert(s);
1388
1389         r = socket_watch_fds(s);
1390         if (r < 0) {
1391                 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1392                 goto fail;
1393         }
1394
1395         socket_set_state(s, SOCKET_LISTENING);
1396         return;
1397
1398 fail:
1399         socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1400 }
1401
1402 static void socket_enter_start_post(Socket *s) {
1403         int r;
1404         assert(s);
1405
1406         r = socket_open_fds(s);
1407         if (r < 0) {
1408                 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1409                 goto fail;
1410         }
1411
1412         socket_unwatch_control_pid(s);
1413
1414         s->control_command_id = SOCKET_EXEC_START_POST;
1415
1416         if ((s->control_command = s->exec_command[SOCKET_EXEC_START_POST])) {
1417                 r = socket_spawn(s, s->control_command, &s->control_pid);
1418                 if (r < 0) {
1419                         log_warning_unit(UNIT(s)->id, "%s failed to run 'start-post' task: %s", UNIT(s)->id, strerror(-r));
1420                         goto fail;
1421                 }
1422
1423                 socket_set_state(s, SOCKET_START_POST);
1424         } else
1425                 socket_enter_listening(s);
1426
1427         return;
1428
1429 fail:
1430         socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1431 }
1432
1433 static void socket_enter_start_pre(Socket *s) {
1434         int r;
1435         assert(s);
1436
1437         socket_unwatch_control_pid(s);
1438
1439         s->control_command_id = SOCKET_EXEC_START_PRE;
1440
1441         if ((s->control_command = s->exec_command[SOCKET_EXEC_START_PRE])) {
1442                 r = socket_spawn(s, s->control_command, &s->control_pid);
1443                 if (r < 0)
1444                         goto fail;
1445
1446                 socket_set_state(s, SOCKET_START_PRE);
1447         } else
1448                 socket_enter_start_post(s);
1449
1450         return;
1451
1452 fail:
1453         log_warning_unit(UNIT(s)->id, "%s failed to run 'start-pre' task: %s", UNIT(s)->id, strerror(-r));
1454         socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1455 }
1456
1457 static void socket_enter_running(Socket *s, int cfd) {
1458         _cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
1459         int r;
1460
1461         assert(s);
1462
1463         /* We don't take connections anymore if we are supposed to
1464          * shut down anyway */
1465         if (unit_stop_pending(UNIT(s))) {
1466
1467                 log_debug_unit(UNIT(s)->id, "Suppressing connection request on %s since unit stop is scheduled.", UNIT(s)->id);
1468
1469                 if (cfd >= 0)
1470                         safe_close(cfd);
1471                 else  {
1472                         /* Flush all sockets by closing and reopening them */
1473                         socket_close_fds(s);
1474
1475                         r = socket_open_fds(s);
1476                         if (r < 0) {
1477                                 log_warning_unit(UNIT(s)->id, "%s failed to listen on sockets: %s", UNIT(s)->id, strerror(-r));
1478                                 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1479                                 return;
1480                         }
1481
1482                         r = socket_watch_fds(s);
1483                         if (r < 0) {
1484                                 log_warning_unit(UNIT(s)->id, "%s failed to watch sockets: %s", UNIT(s)->id, strerror(-r));
1485                                 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1486                         }
1487                 }
1488
1489                 return;
1490         }
1491
1492         if (cfd < 0) {
1493                 Iterator i;
1494                 Unit *other;
1495                 bool pending = false;
1496
1497                 /* If there's already a start pending don't bother to
1498                  * do anything */
1499                 SET_FOREACH(other, UNIT(s)->dependencies[UNIT_TRIGGERS], i)
1500                         if (unit_active_or_pending(other)) {
1501                                 pending = true;
1502                                 break;
1503                         }
1504
1505                 if (!pending) {
1506                         r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, true, &error, NULL);
1507                         if (r < 0)
1508                                 goto fail;
1509                 }
1510
1511                 socket_set_state(s, SOCKET_RUNNING);
1512         } else {
1513                 _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
1514                 Service *service;
1515
1516                 if (s->n_connections >= s->max_connections) {
1517                         log_warning_unit(UNIT(s)->id, "%s: Too many incoming connections (%u)", UNIT(s)->id, s->n_connections);
1518                         safe_close(cfd);
1519                         return;
1520                 }
1521
1522                 r = socket_instantiate_service(s);
1523                 if (r < 0)
1524                         goto fail;
1525
1526                 r = instance_from_socket(cfd, s->n_accepted, &instance);
1527                 if (r < 0) {
1528                         if (r != -ENOTCONN)
1529                                 goto fail;
1530
1531                         /* ENOTCONN is legitimate if TCP RST was received.
1532                          * This connection is over, but the socket unit lives on. */
1533                         safe_close(cfd);
1534                         return;
1535                 }
1536
1537                 prefix = unit_name_to_prefix(UNIT(s)->id);
1538                 if (!prefix) {
1539                         r = -ENOMEM;
1540                         goto fail;
1541                 }
1542
1543                 name = unit_name_build(prefix, instance, ".service");
1544                 if (!name) {
1545                         r = -ENOMEM;
1546                         goto fail;
1547                 }
1548
1549                 r = unit_add_name(UNIT_DEREF(s->service), name);
1550                 if (r < 0)
1551                         goto fail;
1552
1553                 service = SERVICE(UNIT_DEREF(s->service));
1554                 unit_ref_unset(&s->service);
1555                 s->n_accepted ++;
1556
1557                 UNIT(service)->no_gc = false;
1558
1559                 unit_choose_id(UNIT(service), name);
1560
1561                 r = service_set_socket_fd(service, cfd, s);
1562                 if (r < 0)
1563                         goto fail;
1564
1565                 cfd = -1;
1566                 s->n_connections ++;
1567
1568                 r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT(service), JOB_REPLACE, true, &error, NULL);
1569                 if (r < 0)
1570                         goto fail;
1571
1572                 /* Notify clients about changed counters */
1573                 unit_add_to_dbus_queue(UNIT(s));
1574         }
1575
1576         return;
1577
1578 fail:
1579         log_warning_unit(UNIT(s)->id, "%s failed to queue service startup job (Maybe the service file is missing or not a %s unit?): %s",
1580                          UNIT(s)->id, cfd >= 0 ? "template" : "non-template",
1581                          bus_error_message(&error, r));
1582
1583         socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1584         safe_close(cfd);
1585 }
1586
1587 static void socket_run_next(Socket *s) {
1588         int r;
1589
1590         assert(s);
1591         assert(s->control_command);
1592         assert(s->control_command->command_next);
1593
1594         socket_unwatch_control_pid(s);
1595
1596         s->control_command = s->control_command->command_next;
1597
1598         r = socket_spawn(s, s->control_command, &s->control_pid);
1599         if (r < 0)
1600                 goto fail;
1601
1602         return;
1603
1604 fail:
1605         log_warning_unit(UNIT(s)->id, "%s failed to run next task: %s", UNIT(s)->id, strerror(-r));
1606
1607         if (s->state == SOCKET_START_POST)
1608                 socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
1609         else if (s->state == SOCKET_STOP_POST)
1610                 socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
1611         else
1612                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
1613 }
1614
1615 static int socket_start(Unit *u) {
1616         Socket *s = SOCKET(u);
1617
1618         assert(s);
1619
1620         /* We cannot fulfill this request right now, try again later
1621          * please! */
1622         if (s->state == SOCKET_STOP_PRE ||
1623             s->state == SOCKET_STOP_PRE_SIGKILL ||
1624             s->state == SOCKET_STOP_PRE_SIGTERM ||
1625             s->state == SOCKET_STOP_POST ||
1626             s->state == SOCKET_FINAL_SIGTERM ||
1627             s->state == SOCKET_FINAL_SIGKILL)
1628                 return -EAGAIN;
1629
1630         if (s->state == SOCKET_START_PRE ||
1631             s->state == SOCKET_START_POST)
1632                 return 0;
1633
1634         /* Cannot run this without the service being around */
1635         if (UNIT_ISSET(s->service)) {
1636                 Service *service;
1637
1638                 service = SERVICE(UNIT_DEREF(s->service));
1639
1640                 if (UNIT(service)->load_state != UNIT_LOADED) {
1641                         log_error_unit(u->id, "Socket service %s not loaded, refusing.", UNIT(service)->id);
1642                         return -ENOENT;
1643                 }
1644
1645                 /* If the service is already active we cannot start the
1646                  * socket */
1647                 if (service->state != SERVICE_DEAD &&
1648                     service->state != SERVICE_FAILED &&
1649                     service->state != SERVICE_AUTO_RESTART) {
1650                         log_error_unit(u->id, "Socket service %s already active, refusing.", UNIT(service)->id);
1651                         return -EBUSY;
1652                 }
1653
1654 #ifdef HAVE_SYSV_COMPAT
1655                 if (service->is_sysv) {
1656                         log_error_unit(u->id,
1657                                        "Using SysV services for socket activation is not supported. Refusing.");
1658                         return -ENOENT;
1659                 }
1660 #endif
1661         }
1662
1663         assert(s->state == SOCKET_DEAD || s->state == SOCKET_FAILED);
1664
1665         s->result = SOCKET_SUCCESS;
1666         socket_enter_start_pre(s);
1667
1668         return 0;
1669 }
1670
1671 static int socket_stop(Unit *u) {
1672         Socket *s = SOCKET(u);
1673
1674         assert(s);
1675
1676         /* Already on it */
1677         if (s->state == SOCKET_STOP_PRE ||
1678             s->state == SOCKET_STOP_PRE_SIGTERM ||
1679             s->state == SOCKET_STOP_PRE_SIGKILL ||
1680             s->state == SOCKET_STOP_POST ||
1681             s->state == SOCKET_FINAL_SIGTERM ||
1682             s->state == SOCKET_FINAL_SIGKILL)
1683                 return 0;
1684
1685         /* If there's already something running we go directly into
1686          * kill mode. */
1687         if (s->state == SOCKET_START_PRE ||
1688             s->state == SOCKET_START_POST) {
1689                 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
1690                 return -EAGAIN;
1691         }
1692
1693         assert(s->state == SOCKET_LISTENING || s->state == SOCKET_RUNNING);
1694
1695         socket_enter_stop_pre(s, SOCKET_SUCCESS);
1696         return 0;
1697 }
1698
1699 static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
1700         Socket *s = SOCKET(u);
1701         SocketPort *p;
1702         int r;
1703
1704         assert(u);
1705         assert(f);
1706         assert(fds);
1707
1708         unit_serialize_item(u, f, "state", socket_state_to_string(s->state));
1709         unit_serialize_item(u, f, "result", socket_result_to_string(s->result));
1710         unit_serialize_item_format(u, f, "n-accepted", "%u", s->n_accepted);
1711
1712         if (s->control_pid > 0)
1713                 unit_serialize_item_format(u, f, "control-pid", PID_FMT, s->control_pid);
1714
1715         if (s->control_command_id >= 0)
1716                 unit_serialize_item(u, f, "control-command", socket_exec_command_to_string(s->control_command_id));
1717
1718         LIST_FOREACH(port, p, s->ports) {
1719                 int copy;
1720
1721                 if (p->fd < 0)
1722                         continue;
1723
1724                 copy = fdset_put_dup(fds, p->fd);
1725                 if (copy < 0)
1726                         return copy;
1727
1728                 if (p->type == SOCKET_SOCKET) {
1729                         _cleanup_free_ char *t = NULL;
1730
1731                         r = socket_address_print(&p->address, &t);
1732                         if (r < 0)
1733                                 return r;
1734
1735                         if (socket_address_family(&p->address) == AF_NETLINK)
1736                                 unit_serialize_item_format(u, f, "netlink", "%i %s", copy, t);
1737                         else
1738                                 unit_serialize_item_format(u, f, "socket", "%i %i %s", copy, p->address.type, t);
1739
1740                 } else if (p->type == SOCKET_SPECIAL)
1741                         unit_serialize_item_format(u, f, "special", "%i %s", copy, p->path);
1742                 else if (p->type == SOCKET_MQUEUE)
1743                         unit_serialize_item_format(u, f, "mqueue", "%i %s", copy, p->path);
1744                 else {
1745                         assert(p->type == SOCKET_FIFO);
1746                         unit_serialize_item_format(u, f, "fifo", "%i %s", copy, p->path);
1747                 }
1748         }
1749
1750         return 0;
1751 }
1752
1753 static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
1754         Socket *s = SOCKET(u);
1755
1756         assert(u);
1757         assert(key);
1758         assert(value);
1759
1760         if (streq(key, "state")) {
1761                 SocketState state;
1762
1763                 state = socket_state_from_string(value);
1764                 if (state < 0)
1765                         log_debug_unit(u->id, "Failed to parse state value %s", value);
1766                 else
1767                         s->deserialized_state = state;
1768         } else if (streq(key, "result")) {
1769                 SocketResult f;
1770
1771                 f = socket_result_from_string(value);
1772                 if (f < 0)
1773                         log_debug_unit(u->id, "Failed to parse result value %s", value);
1774                 else if (f != SOCKET_SUCCESS)
1775                         s->result = f;
1776
1777         } else if (streq(key, "n-accepted")) {
1778                 unsigned k;
1779
1780                 if (safe_atou(value, &k) < 0)
1781                         log_debug_unit(u->id, "Failed to parse n-accepted value %s", value);
1782                 else
1783                         s->n_accepted += k;
1784         } else if (streq(key, "control-pid")) {
1785                 pid_t pid;
1786
1787                 if (parse_pid(value, &pid) < 0)
1788                         log_debug_unit(u->id, "Failed to parse control-pid value %s", value);
1789                 else
1790                         s->control_pid = pid;
1791         } else if (streq(key, "control-command")) {
1792                 SocketExecCommand id;
1793
1794                 id = socket_exec_command_from_string(value);
1795                 if (id < 0)
1796                         log_debug_unit(u->id, "Failed to parse exec-command value %s", value);
1797                 else {
1798                         s->control_command_id = id;
1799                         s->control_command = s->exec_command[id];
1800                 }
1801         } else if (streq(key, "fifo")) {
1802                 int fd, skip = 0;
1803                 SocketPort *p;
1804
1805                 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1806                         log_debug_unit(u->id, "Failed to parse fifo value %s", value);
1807                 else {
1808
1809                         LIST_FOREACH(port, p, s->ports)
1810                                 if (p->type == SOCKET_FIFO &&
1811                                     streq_ptr(p->path, value+skip))
1812                                         break;
1813
1814                         if (p) {
1815                                 safe_close(p->fd);
1816                                 p->fd = fdset_remove(fds, fd);
1817                         }
1818                 }
1819
1820         } else if (streq(key, "special")) {
1821                 int fd, skip = 0;
1822                 SocketPort *p;
1823
1824                 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1825                         log_debug_unit(u->id, "Failed to parse special value %s", value);
1826                 else {
1827
1828                         LIST_FOREACH(port, p, s->ports)
1829                                 if (p->type == SOCKET_SPECIAL &&
1830                                     streq_ptr(p->path, value+skip))
1831                                         break;
1832
1833                         if (p) {
1834                                 safe_close(p->fd);
1835                                 p->fd = fdset_remove(fds, fd);
1836                         }
1837                 }
1838
1839         } else if (streq(key, "mqueue")) {
1840                 int fd, skip = 0;
1841                 SocketPort *p;
1842
1843                 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1844                         log_debug_unit(u->id, "Failed to parse mqueue value %s", value);
1845                 else {
1846
1847                         LIST_FOREACH(port, p, s->ports)
1848                                 if (p->type == SOCKET_MQUEUE &&
1849                                     streq_ptr(p->path, value+skip))
1850                                         break;
1851
1852                         if (p) {
1853                                 safe_close(p->fd);
1854                                 p->fd = fdset_remove(fds, fd);
1855                         }
1856                 }
1857
1858         } else if (streq(key, "socket")) {
1859                 int fd, type, skip = 0;
1860                 SocketPort *p;
1861
1862                 if (sscanf(value, "%i %i %n", &fd, &type, &skip) < 2 || fd < 0 || type < 0 || !fdset_contains(fds, fd))
1863                         log_debug_unit(u->id, "Failed to parse socket value %s", value);
1864                 else {
1865
1866                         LIST_FOREACH(port, p, s->ports)
1867                                 if (socket_address_is(&p->address, value+skip, type))
1868                                         break;
1869
1870                         if (p) {
1871                                 safe_close(p->fd);
1872                                 p->fd = fdset_remove(fds, fd);
1873                         }
1874                 }
1875
1876         } else if (streq(key, "netlink")) {
1877                 int fd, skip = 0;
1878                 SocketPort *p;
1879
1880                 if (sscanf(value, "%i %n", &fd, &skip) < 1 || fd < 0 || !fdset_contains(fds, fd))
1881                         log_debug_unit(u->id, "Failed to parse socket value %s", value);
1882                 else {
1883
1884                         LIST_FOREACH(port, p, s->ports)
1885                                 if (socket_address_is_netlink(&p->address, value+skip))
1886                                         break;
1887
1888                         if (p) {
1889                                 safe_close(p->fd);
1890                                 p->fd = fdset_remove(fds, fd);
1891                         }
1892                 }
1893         } else
1894                 log_debug_unit(UNIT(s)->id, "Unknown serialization key '%s'", key);
1895
1896         return 0;
1897 }
1898
1899 static int socket_distribute_fds(Unit *u, FDSet *fds) {
1900         Socket *s = SOCKET(u);
1901         SocketPort *p;
1902
1903         assert(u);
1904
1905         LIST_FOREACH(port, p, s->ports) {
1906                 Iterator i;
1907                 int fd;
1908
1909                 if (p->type != SOCKET_SOCKET)
1910                         continue;
1911
1912                 if (p->fd >= 0)
1913                         continue;
1914
1915                 FDSET_FOREACH(fd, fds, i) {
1916                         if (socket_address_matches_fd(&p->address, fd)) {
1917                                 p->fd = fdset_remove(fds, fd);
1918                                 s->deserialized_state = SOCKET_LISTENING;
1919                                 break;
1920                         }
1921                 }
1922         }
1923
1924         return 0;
1925 }
1926
1927 _pure_ static UnitActiveState socket_active_state(Unit *u) {
1928         assert(u);
1929
1930         return state_translation_table[SOCKET(u)->state];
1931 }
1932
1933 _pure_ static const char *socket_sub_state_to_string(Unit *u) {
1934         assert(u);
1935
1936         return socket_state_to_string(SOCKET(u)->state);
1937 }
1938
1939 const char* socket_port_type_to_string(SocketPort *p) {
1940
1941         assert(p);
1942
1943         switch (p->type) {
1944
1945         case SOCKET_SOCKET:
1946
1947                 switch (p->address.type) {
1948
1949                 case SOCK_STREAM:
1950                         return "Stream";
1951
1952                 case SOCK_DGRAM:
1953                         return "Datagram";
1954
1955                 case SOCK_SEQPACKET:
1956                         return "SequentialPacket";
1957
1958                 case SOCK_RAW:
1959                         if (socket_address_family(&p->address) == AF_NETLINK)
1960                                 return "Netlink";
1961
1962                 default:
1963                         return NULL;
1964                 }
1965
1966         case SOCKET_SPECIAL:
1967                 return "Special";
1968
1969         case SOCKET_MQUEUE:
1970                 return "MessageQueue";
1971
1972         case SOCKET_FIFO:
1973                 return "FIFO";
1974
1975         default:
1976                 return NULL;
1977         }
1978 }
1979
1980 _pure_ static bool socket_check_gc(Unit *u) {
1981         Socket *s = SOCKET(u);
1982
1983         assert(u);
1984
1985         return s->n_connections > 0;
1986 }
1987
1988 static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
1989         SocketPort *p = userdata;
1990         int cfd = -1;
1991
1992         assert(p);
1993         assert(fd >= 0);
1994
1995         if (p->socket->state != SOCKET_LISTENING)
1996                 return 0;
1997
1998         log_debug_unit(UNIT(p->socket)->id, "Incoming traffic on %s", UNIT(p->socket)->id);
1999
2000         if (revents != EPOLLIN) {
2001
2002                 if (revents & EPOLLHUP)
2003                         log_error_unit(UNIT(p->socket)->id, "%s: Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.",
2004                                        UNIT(p->socket)->id);
2005                 else
2006                         log_error_unit(UNIT(p->socket)->id, "%s: Got unexpected poll event (0x%x) on socket.",
2007                                        UNIT(p->socket)->id, revents);
2008
2009                 goto fail;
2010         }
2011
2012         if (p->socket->accept &&
2013             p->type == SOCKET_SOCKET &&
2014             socket_address_can_accept(&p->address)) {
2015
2016                 for (;;) {
2017
2018                         cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK);
2019                         if (cfd < 0) {
2020
2021                                 if (errno == EINTR)
2022                                         continue;
2023
2024                                 log_error_unit(UNIT(p->socket)->id,
2025                                                "Failed to accept socket: %m");
2026                                 goto fail;
2027                         }
2028
2029                         break;
2030                 }
2031
2032                 socket_apply_socket_options(p->socket, cfd);
2033         }
2034
2035         socket_enter_running(p->socket, cfd);
2036         return 0;
2037
2038 fail:
2039         socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
2040         return 0;
2041 }
2042
2043 static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
2044         Socket *s = SOCKET(u);
2045         SocketResult f;
2046
2047         assert(s);
2048         assert(pid >= 0);
2049
2050         if (pid != s->control_pid)
2051                 return;
2052
2053         s->control_pid = 0;
2054
2055         if (is_clean_exit(code, status, NULL))
2056                 f = SOCKET_SUCCESS;
2057         else if (code == CLD_EXITED)
2058                 f = SOCKET_FAILURE_EXIT_CODE;
2059         else if (code == CLD_KILLED)
2060                 f = SOCKET_FAILURE_SIGNAL;
2061         else if (code == CLD_DUMPED)
2062                 f = SOCKET_FAILURE_CORE_DUMP;
2063         else
2064                 assert_not_reached("Unknown code");
2065
2066         if (s->control_command) {
2067                 exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
2068
2069                 if (s->control_command->ignore)
2070                         f = SOCKET_SUCCESS;
2071         }
2072
2073         log_full_unit(f == SOCKET_SUCCESS ? LOG_DEBUG : LOG_NOTICE,
2074                       u->id,
2075                       "%s control process exited, code=%s status=%i",
2076                       u->id, sigchld_code_to_string(code), status);
2077
2078         if (f != SOCKET_SUCCESS)
2079                 s->result = f;
2080
2081         if (s->control_command &&
2082             s->control_command->command_next &&
2083             f == SOCKET_SUCCESS) {
2084
2085                 log_debug_unit(u->id,
2086                                "%s running next command for state %s",
2087                                u->id, socket_state_to_string(s->state));
2088                 socket_run_next(s);
2089         } else {
2090                 s->control_command = NULL;
2091                 s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
2092
2093                 /* No further commands for this step, so let's figure
2094                  * out what to do next */
2095
2096                 log_debug_unit(u->id,
2097                                "%s got final SIGCHLD for state %s",
2098                                u->id, socket_state_to_string(s->state));
2099
2100                 switch (s->state) {
2101
2102                 case SOCKET_START_PRE:
2103                         if (f == SOCKET_SUCCESS)
2104                                 socket_enter_start_post(s);
2105                         else
2106                                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
2107                         break;
2108
2109                 case SOCKET_START_POST:
2110                         if (f == SOCKET_SUCCESS)
2111                                 socket_enter_listening(s);
2112                         else
2113                                 socket_enter_stop_pre(s, f);
2114                         break;
2115
2116                 case SOCKET_STOP_PRE:
2117                 case SOCKET_STOP_PRE_SIGTERM:
2118                 case SOCKET_STOP_PRE_SIGKILL:
2119                         socket_enter_stop_post(s, f);
2120                         break;
2121
2122                 case SOCKET_STOP_POST:
2123                 case SOCKET_FINAL_SIGTERM:
2124                 case SOCKET_FINAL_SIGKILL:
2125                         socket_enter_dead(s, f);
2126                         break;
2127
2128                 default:
2129                         assert_not_reached("Uh, control process died at wrong time.");
2130                 }
2131         }
2132
2133         /* Notify clients about changed exit status */
2134         unit_add_to_dbus_queue(u);
2135 }
2136
2137 static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
2138         Socket *s = SOCKET(userdata);
2139
2140         assert(s);
2141         assert(s->timer_event_source == source);
2142
2143         switch (s->state) {
2144
2145         case SOCKET_START_PRE:
2146                 log_warning_unit(UNIT(s)->id,
2147                                  "%s starting timed out. Terminating.", UNIT(s)->id);
2148                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2149                 break;
2150
2151         case SOCKET_START_POST:
2152                 log_warning_unit(UNIT(s)->id,
2153                                  "%s starting timed out. Stopping.", UNIT(s)->id);
2154                 socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
2155                 break;
2156
2157         case SOCKET_STOP_PRE:
2158                 log_warning_unit(UNIT(s)->id,
2159                                  "%s stopping timed out. Terminating.", UNIT(s)->id);
2160                 socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2161                 break;
2162
2163         case SOCKET_STOP_PRE_SIGTERM:
2164                 if (s->kill_context.send_sigkill) {
2165                         log_warning_unit(UNIT(s)->id,
2166                                          "%s stopping timed out. Killing.", UNIT(s)->id);
2167                         socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2168                 } else {
2169                         log_warning_unit(UNIT(s)->id,
2170                                          "%s stopping timed out. Skipping SIGKILL. Ignoring.",
2171                                          UNIT(s)->id);
2172                         socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2173                 }
2174                 break;
2175
2176         case SOCKET_STOP_PRE_SIGKILL:
2177                 log_warning_unit(UNIT(s)->id,
2178                                  "%s still around after SIGKILL. Ignoring.", UNIT(s)->id);
2179                 socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
2180                 break;
2181
2182         case SOCKET_STOP_POST:
2183                 log_warning_unit(UNIT(s)->id,
2184                                  "%s stopping timed out (2). Terminating.", UNIT(s)->id);
2185                 socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
2186                 break;
2187
2188         case SOCKET_FINAL_SIGTERM:
2189                 if (s->kill_context.send_sigkill) {
2190                         log_warning_unit(UNIT(s)->id,
2191                                          "%s stopping timed out (2). Killing.", UNIT(s)->id);
2192                         socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
2193                 } else {
2194                         log_warning_unit(UNIT(s)->id,
2195                                          "%s stopping timed out (2). Skipping SIGKILL. Ignoring.",
2196                                          UNIT(s)->id);
2197                         socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2198                 }
2199                 break;
2200
2201         case SOCKET_FINAL_SIGKILL:
2202                 log_warning_unit(UNIT(s)->id,
2203                                  "%s still around after SIGKILL (2). Entering failed mode.",
2204                                  UNIT(s)->id);
2205                 socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
2206                 break;
2207
2208         default:
2209                 assert_not_reached("Timeout at wrong time.");
2210         }
2211
2212         return 0;
2213 }
2214
2215 int socket_collect_fds(Socket *s, int **fds, unsigned *n_fds) {
2216         int *rfds;
2217         unsigned rn_fds, k;
2218         SocketPort *p;
2219
2220         assert(s);
2221         assert(fds);
2222         assert(n_fds);
2223
2224         /* Called from the service code for requesting our fds */
2225
2226         rn_fds = 0;
2227         LIST_FOREACH(port, p, s->ports)
2228                 if (p->fd >= 0)
2229                         rn_fds++;
2230
2231         if (rn_fds <= 0) {
2232                 *fds = NULL;
2233                 *n_fds = 0;
2234                 return 0;
2235         }
2236
2237         if (!(rfds = new(int, rn_fds)))
2238                 return -ENOMEM;
2239
2240         k = 0;
2241         LIST_FOREACH(port, p, s->ports)
2242                 if (p->fd >= 0)
2243                         rfds[k++] = p->fd;
2244
2245         assert(k == rn_fds);
2246
2247         *fds = rfds;
2248         *n_fds = rn_fds;
2249
2250         return 0;
2251 }
2252
2253 static void socket_reset_failed(Unit *u) {
2254         Socket *s = SOCKET(u);
2255
2256         assert(s);
2257
2258         if (s->state == SOCKET_FAILED)
2259                 socket_set_state(s, SOCKET_DEAD);
2260
2261         s->result = SOCKET_SUCCESS;
2262 }
2263
2264 static void socket_notify_service_dead(Socket *s, bool failed_permanent) {
2265         assert(s);
2266
2267         /* The service is dead. Dang!
2268          *
2269          * This is strictly for one-instance-for-all-connections
2270          * services. */
2271
2272         if (s->state == SOCKET_RUNNING) {
2273                 log_debug_unit(UNIT(s)->id, "%s got notified about service death (failed permanently: %s)", UNIT(s)->id, yes_no(failed_permanent));
2274                 if (failed_permanent)
2275                         socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_FAILED_PERMANENT);
2276                 else
2277                         socket_enter_listening(s);
2278         }
2279 }
2280
2281 void socket_connection_unref(Socket *s) {
2282         assert(s);
2283
2284         /* The service is dead. Yay!
2285          *
2286          * This is strictly for one-instance-per-connection
2287          * services. */
2288
2289         assert(s->n_connections > 0);
2290         s->n_connections--;
2291
2292         log_debug_unit(UNIT(s)->id, "%s: One connection closed, %u left.", UNIT(s)->id, s->n_connections);
2293 }
2294
2295 static void socket_trigger_notify(Unit *u, Unit *other) {
2296         Socket *s = SOCKET(u);
2297         Service *se;
2298
2299         assert(u);
2300         assert(other);
2301
2302         /* Don't propagate state changes from the service if we are
2303            already down or accepting connections */
2304         if ((s->state !=  SOCKET_RUNNING &&
2305             s->state != SOCKET_LISTENING) ||
2306             s->accept)
2307                 return;
2308
2309         if (other->load_state != UNIT_LOADED ||
2310             other->type != UNIT_SERVICE)
2311                 return;
2312
2313         se = SERVICE(other);
2314
2315         if (se->state == SERVICE_FAILED)
2316                 socket_notify_service_dead(s, se->result == SERVICE_FAILURE_START_LIMIT);
2317
2318         if (se->state == SERVICE_DEAD ||
2319             se->state == SERVICE_STOP ||
2320             se->state == SERVICE_STOP_SIGTERM ||
2321             se->state == SERVICE_STOP_SIGKILL ||
2322             se->state == SERVICE_STOP_POST ||
2323             se->state == SERVICE_FINAL_SIGTERM ||
2324             se->state == SERVICE_FINAL_SIGKILL ||
2325             se->state == SERVICE_AUTO_RESTART)
2326                 socket_notify_service_dead(s, false);
2327
2328         if (se->state == SERVICE_RUNNING)
2329                 socket_set_state(s, SOCKET_RUNNING);
2330 }
2331
2332 static int socket_kill(Unit *u, KillWho who, int signo, sd_bus_error *error) {
2333         return unit_kill_common(u, who, signo, -1, SOCKET(u)->control_pid, error);
2334 }
2335
2336 static int socket_get_timeout(Unit *u, uint64_t *timeout) {
2337         Socket *s = SOCKET(u);
2338         int r;
2339
2340         if (!s->timer_event_source)
2341                 return 0;
2342
2343         r = sd_event_source_get_time(s->timer_event_source, timeout);
2344         if (r < 0)
2345                 return r;
2346
2347         return 1;
2348 }
2349
2350 static const char* const socket_state_table[_SOCKET_STATE_MAX] = {
2351         [SOCKET_DEAD] = "dead",
2352         [SOCKET_START_PRE] = "start-pre",
2353         [SOCKET_START_POST] = "start-post",
2354         [SOCKET_LISTENING] = "listening",
2355         [SOCKET_RUNNING] = "running",
2356         [SOCKET_STOP_PRE] = "stop-pre",
2357         [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm",
2358         [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill",
2359         [SOCKET_STOP_POST] = "stop-post",
2360         [SOCKET_FINAL_SIGTERM] = "final-sigterm",
2361         [SOCKET_FINAL_SIGKILL] = "final-sigkill",
2362         [SOCKET_FAILED] = "failed"
2363 };
2364
2365 DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState);
2366
2367 static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
2368         [SOCKET_EXEC_START_PRE] = "StartPre",
2369         [SOCKET_EXEC_START_POST] = "StartPost",
2370         [SOCKET_EXEC_STOP_PRE] = "StopPre",
2371         [SOCKET_EXEC_STOP_POST] = "StopPost"
2372 };
2373
2374 DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
2375
2376 static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
2377         [SOCKET_SUCCESS] = "success",
2378         [SOCKET_FAILURE_RESOURCES] = "resources",
2379         [SOCKET_FAILURE_TIMEOUT] = "timeout",
2380         [SOCKET_FAILURE_EXIT_CODE] = "exit-code",
2381         [SOCKET_FAILURE_SIGNAL] = "signal",
2382         [SOCKET_FAILURE_CORE_DUMP] = "core-dump",
2383         [SOCKET_FAILURE_SERVICE_FAILED_PERMANENT] = "service-failed-permanent"
2384 };
2385
2386 DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
2387
2388 const UnitVTable socket_vtable = {
2389         .object_size = sizeof(Socket),
2390         .exec_context_offset = offsetof(Socket, exec_context),
2391         .cgroup_context_offset = offsetof(Socket, cgroup_context),
2392         .kill_context_offset = offsetof(Socket, kill_context),
2393         .exec_runtime_offset = offsetof(Socket, exec_runtime),
2394
2395         .sections =
2396                 "Unit\0"
2397                 "Socket\0"
2398                 "Install\0",
2399         .private_section = "Socket",
2400
2401         .init = socket_init,
2402         .done = socket_done,
2403         .load = socket_load,
2404
2405         .coldplug = socket_coldplug,
2406
2407         .dump = socket_dump,
2408
2409         .start = socket_start,
2410         .stop = socket_stop,
2411
2412         .kill = socket_kill,
2413
2414         .get_timeout = socket_get_timeout,
2415
2416         .serialize = socket_serialize,
2417         .deserialize_item = socket_deserialize_item,
2418         .distribute_fds = socket_distribute_fds,
2419
2420         .active_state = socket_active_state,
2421         .sub_state_to_string = socket_sub_state_to_string,
2422
2423         .check_gc = socket_check_gc,
2424
2425         .sigchld_event = socket_sigchld_event,
2426
2427         .trigger_notify = socket_trigger_notify,
2428
2429         .reset_failed = socket_reset_failed,
2430
2431         .bus_interface = "org.freedesktop.systemd1.Socket",
2432         .bus_vtable = bus_socket_vtable,
2433         .bus_set_property = bus_socket_set_property,
2434         .bus_commit_properties = bus_socket_commit_properties,
2435
2436         .status_message_formats = {
2437                 /*.starting_stopping = {
2438                         [0] = "Starting socket %s...",
2439                         [1] = "Stopping socket %s...",
2440                 },*/
2441                 .finished_start_job = {
2442                         [JOB_DONE]       = "Listening on %s.",
2443                         [JOB_FAILED]     = "Failed to listen on %s.",
2444                         [JOB_DEPENDENCY] = "Dependency failed for %s.",
2445                         [JOB_TIMEOUT]    = "Timed out starting %s.",
2446                 },
2447                 .finished_stop_job = {
2448                         [JOB_DONE]       = "Closed %s.",
2449                         [JOB_FAILED]     = "Failed stopping %s.",
2450                         [JOB_TIMEOUT]    = "Timed out stopping %s.",
2451                 },
2452         },
2453 };