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