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