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