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