]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/activate/activate.c
tree-wide: make use of getpid_cached() wherever we can
[thirdparty/systemd.git] / src / activate / activate.c
CommitLineData
2ca0435b
ZJS
1/***
2 This file is part of systemd.
3
4 Copyright 2013 Zbigniew Jędrzejewski-Szmek
5
6 systemd is free software; you can redistribute it and/or modify it
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
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
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18***/
19
3f6fd1ba 20#include <getopt.h>
2ca0435b
ZJS
21#include <sys/epoll.h>
22#include <sys/prctl.h>
23#include <sys/socket.h>
24#include <sys/wait.h>
3f6fd1ba 25#include <unistd.h>
2ca0435b 26
8dd4c05b 27#include "sd-daemon.h"
2ca0435b 28
b5efdb8a 29#include "alloc-util.h"
cf98937c 30#include "escape.h"
b5efdb8a 31#include "fd-util.h"
2ca0435b 32#include "log.h"
2ca0435b 33#include "macro.h"
df0ff127 34#include "process-util.h"
ce30c8dc 35#include "signal-util.h"
3f6fd1ba 36#include "socket-util.h"
07630cea 37#include "string-util.h"
3f6fd1ba 38#include "strv.h"
2ca0435b
ZJS
39
40static char** arg_listen = NULL;
41static bool arg_accept = false;
d31e430f 42static int arg_socket_type = SOCK_STREAM;
2ca0435b 43static char** arg_args = NULL;
892213bf 44static char** arg_setenv = NULL;
cf98937c 45static char **arg_fdnames = NULL;
eef0a274 46static bool arg_inetd = false;
2ca0435b
ZJS
47
48static int add_epoll(int epoll_fd, int fd) {
30374ebe
LP
49 struct epoll_event ev = {
50 .events = EPOLLIN
51 };
2ca0435b 52 int r;
2ca0435b
ZJS
53
54 assert(epoll_fd >= 0);
55 assert(fd >= 0);
56
30374ebe 57 ev.data.fd = fd;
2ca0435b 58 r = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
4a62c710
MS
59 if (r < 0)
60 return log_error_errno(errno, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd, fd);
603938e0
LP
61
62 return 0;
2ca0435b
ZJS
63}
64
65static int open_sockets(int *epoll_fd, bool accept) {
30374ebe 66 char **address;
29a5ca9b 67 int n, fd, r;
2ca0435b 68 int count = 0;
2ca0435b
ZJS
69
70 n = sd_listen_fds(true);
eb56eb9b
MS
71 if (n < 0)
72 return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
30374ebe
LP
73 if (n > 0) {
74 log_info("Received %i descriptors via the environment.", n);
2ca0435b 75
30374ebe
LP
76 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
77 r = fd_cloexec(fd, arg_accept);
78 if (r < 0)
79 return r;
2ca0435b 80
313cefa1 81 count++;
30374ebe 82 }
2ca0435b
ZJS
83 }
84
c0997164
ZJS
85 /* Close logging and all other descriptors */
86 if (arg_listen) {
87 int except[3 + n];
88
89 for (fd = 0; fd < SD_LISTEN_FDS_START + n; fd++)
90 except[fd] = fd;
91
92 log_close();
93 close_all_fds(except, 3 + n);
94 }
95
fff40a51
ZJS
96 /** Note: we leak some fd's on error here. I doesn't matter
97 * much, since the program will exit immediately anyway, but
98 * would be a pain to fix.
99 */
100
2ca0435b 101 STRV_FOREACH(address, arg_listen) {
d31e430f 102 fd = make_socket_fd(LOG_DEBUG, *address, arg_socket_type, (arg_accept*SOCK_CLOEXEC));
2ca0435b 103 if (fd < 0) {
c0997164 104 log_open();
23bbb0de 105 return log_error_errno(fd, "Failed to open '%s': %m", *address);
2ca0435b
ZJS
106 }
107
175a3d25 108 assert(fd == SD_LISTEN_FDS_START + count);
313cefa1 109 count++;
2ca0435b
ZJS
110 }
111
c0997164
ZJS
112 if (arg_listen)
113 log_open();
114
2ca0435b 115 *epoll_fd = epoll_create1(EPOLL_CLOEXEC);
4a62c710
MS
116 if (*epoll_fd < 0)
117 return log_error_errno(errno, "Failed to create epoll object: %m");
2ca0435b
ZJS
118
119 for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + count; fd++) {
30374ebe
LP
120 _cleanup_free_ char *name = NULL;
121
122 getsockname_pretty(fd, &name);
2c408cb6 123 log_info("Listening on %s as %i.", strna(name), fd);
30374ebe 124
29a5ca9b 125 r = add_epoll(*epoll_fd, fd);
2ca0435b
ZJS
126 if (r < 0)
127 return r;
128 }
129
130 return count;
131}
132
eef0a274 133static int exec_process(const char* name, char **argv, char **env, int start_fd, int n_fds) {
30374ebe 134
30374ebe 135 _cleanup_strv_free_ char **envp = NULL;
eef0a274 136 _cleanup_free_ char *joined = NULL;
30374ebe 137 unsigned n_env = 0, length;
eef0a274 138 const char *tocopy;
eef0a274
LP
139 char **s;
140 int r;
141
142 if (arg_inetd && n_fds != 1) {
143 log_error("--inetd only supported for single file descriptors.");
144 return -EINVAL;
145 }
2ca0435b 146
892213bf 147 length = strv_length(arg_setenv);
30374ebe 148
8dd4c05b
LP
149 /* PATH, TERM, HOME, USER, LISTEN_FDS, LISTEN_PID, LISTEN_FDNAMES, NULL */
150 envp = new0(char *, length + 8);
30374ebe
LP
151 if (!envp)
152 return log_oom();
5e65c93a 153
892213bf 154 STRV_FOREACH(s, arg_setenv) {
eef0a274 155
fa994f91
LP
156 if (strchr(*s, '=')) {
157 char *k;
158
159 k = strdup(*s);
160 if (!k)
161 return log_oom();
162
163 envp[n_env++] = k;
164 } else {
8dd4c05b 165 _cleanup_free_ char *p;
fa994f91 166 const char *n;
8dd4c05b
LP
167
168 p = strappend(*s, "=");
5e65c93a
ZJS
169 if (!p)
170 return log_oom();
fa994f91
LP
171
172 n = strv_find_prefix(env, p);
173 if (!n)
174 continue;
175
176 envp[n_env] = strdup(n);
177 if (!envp[n_env])
178 return log_oom();
eef0a274 179
313cefa1 180 n_env++;
5e65c93a
ZJS
181 }
182 }
183
eef0a274 184 FOREACH_STRING(tocopy, "TERM=", "PATH=", "USER=", "HOME=") {
fa994f91
LP
185 const char *n;
186
eef0a274 187 n = strv_find_prefix(env, tocopy);
fa994f91
LP
188 if (!n)
189 continue;
190
191 envp[n_env] = strdup(n);
192 if (!envp[n_env])
193 return log_oom();
194
313cefa1 195 n_env++;
2ca0435b
ZJS
196 }
197
eef0a274
LP
198 if (arg_inetd) {
199 assert(n_fds == 1);
2ca0435b 200
eef0a274
LP
201 r = dup2(start_fd, STDIN_FILENO);
202 if (r < 0)
203 return log_error_errno(errno, "Failed to dup connection to stdin: %m");
8dd4c05b 204
eef0a274
LP
205 r = dup2(start_fd, STDOUT_FILENO);
206 if (r < 0)
207 return log_error_errno(errno, "Failed to dup connection to stdout: %m");
208
209 start_fd = safe_close(start_fd);
210 } else {
211 if (start_fd != SD_LISTEN_FDS_START) {
212 assert(n_fds == 1);
213
214 r = dup2(start_fd, SD_LISTEN_FDS_START);
215 if (r < 0)
216 return log_error_errno(errno, "Failed to dup connection: %m");
217
218 safe_close(start_fd);
219 start_fd = SD_LISTEN_FDS_START;
220 }
221
222 if (asprintf((char**)(envp + n_env++), "LISTEN_FDS=%i", n_fds) < 0)
8dd4c05b
LP
223 return log_oom();
224
df0ff127 225 if (asprintf((char**)(envp + n_env++), "LISTEN_PID=" PID_FMT, getpid_cached()) < 0)
eef0a274 226 return log_oom();
8dd4c05b 227
cf98937c
ZJS
228 if (arg_fdnames) {
229 _cleanup_free_ char *names = NULL;
230 size_t len;
eef0a274 231 char *e;
cf98937c
ZJS
232 int i;
233
234 len = strv_length(arg_fdnames);
235 if (len == 1)
236 for (i = 1; i < n_fds; i++) {
237 r = strv_extend(&arg_fdnames, arg_fdnames[0]);
238 if (r < 0)
239 return log_error_errno(r, "Failed to extend strv: %m");
240 }
241 else if (len != (unsigned) n_fds)
242 log_warning("The number of fd names is different than number of fds: %zu vs %d",
243 len, n_fds);
eef0a274 244
cf98937c
ZJS
245 names = strv_join(arg_fdnames, ":");
246 if (!names)
8dd4c05b 247 return log_oom();
eef0a274 248
cf98937c
ZJS
249 e = strappend("LISTEN_FDNAMES=", names);
250 if (!e)
251 return log_oom();
8dd4c05b 252
eef0a274 253 envp[n_env++] = e;
8dd4c05b 254 }
8dd4c05b
LP
255 }
256
eef0a274
LP
257 joined = strv_join(argv, " ");
258 if (!joined)
2ca0435b
ZJS
259 return log_oom();
260
eef0a274 261 log_info("Execing %s (%s)", name, joined);
2ca0435b 262 execvpe(name, argv, envp);
30374ebe 263
eef0a274 264 return log_error_errno(errno, "Failed to execp %s (%s): %m", name, joined);
2ca0435b
ZJS
265}
266
eef0a274
LP
267static int fork_and_exec_process(const char* child, char** argv, char **env, int fd) {
268 _cleanup_free_ char *joined = NULL;
2ca0435b 269 pid_t parent_pid, child_pid;
2ca0435b 270
eef0a274
LP
271 joined = strv_join(argv, " ");
272 if (!joined)
2ca0435b
ZJS
273 return log_oom();
274
df0ff127 275 parent_pid = getpid_cached();
2ca0435b
ZJS
276
277 child_pid = fork();
4a62c710
MS
278 if (child_pid < 0)
279 return log_error_errno(errno, "Failed to fork: %m");
2ca0435b
ZJS
280
281 /* In the child */
282 if (child_pid == 0) {
ce30c8dc
LP
283
284 (void) reset_all_signal_handlers();
285 (void) reset_signal_mask();
286
2ca0435b
ZJS
287 /* Make sure the child goes away when the parent dies */
288 if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
289 _exit(EXIT_FAILURE);
290
291 /* Check whether our parent died before we were able
292 * to set the death signal */
293 if (getppid() != parent_pid)
294 _exit(EXIT_SUCCESS);
295
eef0a274 296 exec_process(child, argv, env, fd, 1);
2ca0435b
ZJS
297 _exit(EXIT_FAILURE);
298 }
299
eef0a274 300 log_info("Spawned %s (%s) as PID %d", child, joined, child_pid);
2ca0435b
ZJS
301 return 0;
302}
303
304static int do_accept(const char* name, char **argv, char **envp, int fd) {
30374ebe 305 _cleanup_free_ char *local = NULL, *peer = NULL;
eef0a274 306 _cleanup_close_ int fd_accepted = -1;
2ca0435b 307
eef0a274
LP
308 fd_accepted = accept4(fd, NULL, NULL, 0);
309 if (fd_accepted < 0)
08719b64 310 return log_error_errno(errno, "Failed to accept connection on fd:%d: %m", fd);
2ca0435b 311
eef0a274
LP
312 getsockname_pretty(fd_accepted, &local);
313 getpeername_pretty(fd_accepted, true, &peer);
30374ebe 314 log_info("Connection from %s to %s", strna(peer), strna(local));
2ca0435b 315
eef0a274 316 return fork_and_exec_process(name, argv, envp, fd_accepted);
2ca0435b
ZJS
317}
318
319/* SIGCHLD handler. */
5488e52d 320static void sigchld_hdl(int sig) {
9d458c09
LP
321 PROTECT_ERRNO;
322
5488e52d
EV
323 for (;;) {
324 siginfo_t si;
325 int r;
08719b64 326
5488e52d
EV
327 si.si_pid = 0;
328 r = waitid(P_ALL, 0, &si, WEXITED|WNOHANG);
329 if (r < 0) {
330 if (errno != ECHILD)
331 log_error_errno(errno, "Failed to reap children: %m");
332 return;
333 }
334 if (si.si_pid == 0)
335 return;
336
337 log_info("Child %d died with code %d", si.si_pid, si.si_status);
338 }
2ca0435b
ZJS
339}
340
341static int install_chld_handler(void) {
08719b64 342 static const struct sigaction act = {
e28c7cd0 343 .sa_flags = SA_NOCLDSTOP|SA_RESTART,
5488e52d 344 .sa_handler = sigchld_hdl,
c0997164 345 };
2ca0435b 346
08719b64
LP
347 int r;
348
2ca0435b
ZJS
349 r = sigaction(SIGCHLD, &act, 0);
350 if (r < 0)
08719b64
LP
351 return log_error_errno(errno, "Failed to install SIGCHLD handler: %m");
352
353 return 0;
2ca0435b
ZJS
354}
355
601185b4 356static void help(void) {
2ca0435b
ZJS
357 printf("%s [OPTIONS...]\n\n"
358 "Listen on sockets and launch child on connection.\n\n"
359 "Options:\n"
cf98937c
ZJS
360 " -h --help Show this help and exit\n"
361 " --version Print version string and exit\n"
362 " -l --listen=ADDR Listen for raw connections at ADDR\n"
363 " -d --datagram Listen on datagram instead of stream socket\n"
364 " --seqpacket Listen on SOCK_SEQPACKET instead of stream socket\n"
365 " -a --accept Spawn separate child for each connection\n"
366 " -E --setenv=NAME[=VALUE] Pass an environment variable to children\n"
367 " --fdname=NAME[:NAME...] Specify names for file descriptors\n"
368 " --inetd Enable inetd file descriptor passing protocol\n"
2ca0435b
ZJS
369 "\n"
370 "Note: file descriptors from sd_listen_fds() will be passed through.\n"
601185b4 371 , program_invocation_short_name);
2ca0435b
ZJS
372}
373
374static int parse_argv(int argc, char *argv[]) {
375 enum {
376 ARG_VERSION = 0x100,
8dd4c05b 377 ARG_FDNAME,
d31e430f 378 ARG_SEQPACKET,
eef0a274 379 ARG_INETD,
2ca0435b
ZJS
380 };
381
382 static const struct option options[] = {
892213bf
ZJS
383 { "help", no_argument, NULL, 'h' },
384 { "version", no_argument, NULL, ARG_VERSION },
7b7afdfc 385 { "datagram", no_argument, NULL, 'd' },
d31e430f 386 { "seqpacket", no_argument, NULL, ARG_SEQPACKET },
892213bf
ZJS
387 { "listen", required_argument, NULL, 'l' },
388 { "accept", no_argument, NULL, 'a' },
389 { "setenv", required_argument, NULL, 'E' },
8dd4c05b
LP
390 { "environment", required_argument, NULL, 'E' }, /* legacy alias */
391 { "fdname", required_argument, NULL, ARG_FDNAME },
eef0a274 392 { "inetd", no_argument, NULL, ARG_INETD },
eb9da376 393 {}
2ca0435b
ZJS
394 };
395
8dd4c05b 396 int c, r;
2ca0435b
ZJS
397
398 assert(argc >= 0);
399 assert(argv);
400
b722348d 401 while ((c = getopt_long(argc, argv, "+hl:aE:d", options, NULL)) >= 0)
2ca0435b
ZJS
402 switch(c) {
403 case 'h':
601185b4
ZJS
404 help();
405 return 0;
2ca0435b
ZJS
406
407 case ARG_VERSION:
3f6fd1ba 408 return version();
2ca0435b 409
8dd4c05b
LP
410 case 'l':
411 r = strv_extend(&arg_listen, optarg);
2ca0435b 412 if (r < 0)
8dd4c05b 413 return log_oom();
2ca0435b
ZJS
414
415 break;
2ca0435b 416
7b7afdfc 417 case 'd':
d31e430f
LP
418 if (arg_socket_type == SOCK_SEQPACKET) {
419 log_error("--datagram may not be combined with --seqpacket.");
420 return -EINVAL;
421 }
422
423 arg_socket_type = SOCK_DGRAM;
424 break;
425
426 case ARG_SEQPACKET:
427 if (arg_socket_type == SOCK_DGRAM) {
428 log_error("--seqpacket may not be combined with --datagram.");
429 return -EINVAL;
430 }
431
432 arg_socket_type = SOCK_SEQPACKET;
7b7afdfc
SS
433 break;
434
2ca0435b
ZJS
435 case 'a':
436 arg_accept = true;
437 break;
438
8dd4c05b
LP
439 case 'E':
440 r = strv_extend(&arg_setenv, optarg);
5e65c93a 441 if (r < 0)
8dd4c05b 442 return log_oom();
5e65c93a
ZJS
443
444 break;
8dd4c05b 445
cf98937c
ZJS
446 case ARG_FDNAME: {
447 _cleanup_strv_free_ char **names;
448 char **s;
449
450 names = strv_split(optarg, ":");
451 if (!names)
452 return log_oom();
453
454 STRV_FOREACH(s, names)
455 if (!fdname_is_valid(*s)) {
456 _cleanup_free_ char *esc;
163c76c9 457
cf98937c
ZJS
458 esc = cescape(*s);
459 log_warning("File descriptor name \"%s\" is not valid.", esc);
460 }
461
462 /* Empty optargs means one empty name */
463 r = strv_extend_strv(&arg_fdnames,
464 strv_isempty(names) ? STRV_MAKE("") : names,
465 false);
466 if (r < 0)
467 return log_error_errno(r, "strv_extend_strv: %m");
8dd4c05b 468 break;
cf98937c 469 }
5e65c93a 470
eef0a274
LP
471 case ARG_INETD:
472 arg_inetd = true;
473 break;
474
2ca0435b
ZJS
475 case '?':
476 return -EINVAL;
477
478 default:
eb9da376 479 assert_not_reached("Unhandled option");
2ca0435b
ZJS
480 }
481
482 if (optind == argc) {
601185b4 483 log_error("%s: command to execute is missing.",
2ca0435b
ZJS
484 program_invocation_short_name);
485 return -EINVAL;
486 }
487
d31e430f 488 if (arg_socket_type == SOCK_DGRAM && arg_accept) {
7b7afdfc
SS
489 log_error("Datagram sockets do not accept connections. "
490 "The --datagram and --accept options may not be combined.");
491 return -EINVAL;
492 }
493
2ca0435b
ZJS
494 arg_args = argv + optind;
495
496 return 1 /* work to do */;
497}
498
499int main(int argc, char **argv, char **envp) {
500 int r, n;
501 int epoll_fd = -1;
502
2ca0435b 503 log_parse_environment();
eceb8483 504 log_open();
2ca0435b
ZJS
505
506 r = parse_argv(argc, argv);
507 if (r <= 0)
508 return r == 0 ? EXIT_SUCCESS : EXIT_FAILURE;
509
510 r = install_chld_handler();
511 if (r < 0)
512 return EXIT_FAILURE;
513
514 n = open_sockets(&epoll_fd, arg_accept);
515 if (n < 0)
516 return EXIT_FAILURE;
2c408cb6
LP
517 if (n == 0) {
518 log_error("No sockets to listen on specified or passed in.");
519 return EXIT_FAILURE;
520 }
2ca0435b 521
eceb8483 522 for (;;) {
2ca0435b
ZJS
523 struct epoll_event event;
524
525 r = epoll_wait(epoll_fd, &event, 1, -1);
526 if (r < 0) {
527 if (errno == EINTR)
528 continue;
529
56f64d95 530 log_error_errno(errno, "epoll_wait() failed: %m");
2ca0435b
ZJS
531 return EXIT_FAILURE;
532 }
533
2c408cb6 534 log_info("Communication attempt on fd %i.", event.data.fd);
2ca0435b 535 if (arg_accept) {
d31e430f 536 r = do_accept(argv[optind], argv + optind, envp, event.data.fd);
2ca0435b
ZJS
537 if (r < 0)
538 return EXIT_FAILURE;
539 } else
540 break;
541 }
542
eef0a274 543 exec_process(argv[optind], argv + optind, envp, SD_LISTEN_FDS_START, n);
2ca0435b
ZJS
544
545 return EXIT_SUCCESS;
546}