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