• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

systemd / systemd / 15057632786

15 May 2025 09:01PM UTC coverage: 72.267% (+0.02%) from 72.244%
15057632786

push

github

bluca
man: document how to hook stuff into system wakeup

Fixes: #6364

298523 of 413084 relevant lines covered (72.27%)

738132.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

38.96
/src/socket-activate/socket-activate.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <getopt.h>
4
#include <sys/epoll.h>
5
#include <sys/prctl.h>
6
#include <sys/wait.h>
7
#include <unistd.h>
8

9
#include "sd-daemon.h"
10

11
#include "alloc-util.h"
12
#include "build.h"
13
#include "daemon-util.h"
14
#include "env-util.h"
15
#include "errno-util.h"
16
#include "escape.h"
17
#include "fd-util.h"
18
#include "format-util.h"
19
#include "log.h"
20
#include "main-func.h"
21
#include "pretty-print.h"
22
#include "process-util.h"
23
#include "socket-netlink.h"
24
#include "socket-util.h"
25
#include "string-util.h"
26
#include "strv.h"
27

28
static char **arg_listen = NULL;
29
static bool arg_accept = false;
30
static int arg_socket_type = SOCK_STREAM;
31
static char **arg_setenv = NULL;
32
static char **arg_fdnames = NULL;
33
static bool arg_inetd = false;
34

35
static int add_epoll(int epoll_fd, int fd) {
1✔
36
        struct epoll_event ev = {
1✔
37
                .events = EPOLLIN,
38
                .data.fd = fd,
39
        };
40

41
        assert(epoll_fd >= 0);
1✔
42
        assert(fd >= 0);
1✔
43

44
        if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0)
1✔
45
                return log_error_errno(errno, "Failed to add event on epoll fd:%d for fd:%d: %m", epoll_fd, fd);
×
46

47
        return 0;
48
}
49

50
static int open_sockets(int *ret_epoll_fd) {
1✔
51
        _cleanup_close_ int epoll_fd = -EBADF;
1✔
52
        int n, r, count = 0;
1✔
53

54
        assert(ret_epoll_fd);
1✔
55

56
        n = sd_listen_fds(true);
1✔
57
        if (n < 0)
1✔
58
                return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
×
59
        if (n > 0) {
1✔
60
                log_info("Received %i descriptors via the environment.", n);
×
61

62
                for (int 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;
66

67
                        count++;
×
68
                }
69
        }
70

71
        /* Close logging and all other descriptors */
72
        if (arg_listen) {
1✔
73
                _cleanup_free_ int *except = new(int, n);
2✔
74
                if (!except)
1✔
75
                        return log_oom();
×
76

77
                for (int i = 0; i < n; i++)
1✔
78
                        except[i] = SD_LISTEN_FDS_START + i;
×
79

80
                log_close();
1✔
81
                log_set_open_when_needed(true);
1✔
82
                log_settle_target();
1✔
83

84
                r = close_all_fds(except, n);
1✔
85
                if (r < 0)
1✔
86
                        return log_error_errno(r, "Failed to close all file descriptors: %m");
×
87
        }
88

89
        /* Note: we leak some fd's on error here. It doesn't matter much, since the program will exit
90
         * immediately anyway, but would be a pain to fix. */
91

92
        STRV_FOREACH(address, arg_listen) {
2✔
93
                r = make_socket_fd(LOG_DEBUG, *address, arg_socket_type, (arg_accept * SOCK_CLOEXEC));
1✔
94
                if (r < 0)
1✔
95
                        return log_error_errno(r, "Failed to open '%s': %m", *address);
×
96

97
                assert(r == SD_LISTEN_FDS_START + count);
1✔
98
                count++;
1✔
99
        }
100

101
        if (arg_listen) {
1✔
102
                log_open();
1✔
103
                log_set_open_when_needed(false);
1✔
104
        }
105

106
        epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1✔
107
        if (epoll_fd < 0)
1✔
108
                return log_error_errno(errno, "Failed to create epoll object: %m");
×
109

110
        for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + count; fd++) {
2✔
111
                _cleanup_free_ char *name = NULL;
1✔
112

113
                getsockname_pretty(fd, &name);
1✔
114
                log_info("Listening on %s as %i.", strna(name), fd);
1✔
115

116
                r = add_epoll(epoll_fd, fd);
1✔
117
                if (r < 0)
1✔
118
                        return r;
×
119
        }
120

121
        *ret_epoll_fd = TAKE_FD(epoll_fd);
1✔
122
        return count;
1✔
123
}
124

125
static int exec_process(char * const *argv, int start_fd, size_t n_fds) {
1✔
126
        _cleanup_strv_free_ char **envp = NULL;
×
127
        int r;
1✔
128

129
        assert(!strv_isempty(argv));
1✔
130
        assert(start_fd >= 0);
1✔
131
        assert(n_fds > 0);
1✔
132

133
        if (arg_inetd && n_fds != 1)
1✔
134
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
135
                                       "--inetd only supported for single file descriptors.");
136

137
        FOREACH_STRING(var, "TERM", "COLORTERM", "NO_COLOR", "PATH", "USER", "HOME") {
7✔
138
                const char *n;
6✔
139

140
                n = strv_find_prefix(environ, var);
6✔
141
                if (!n)
6✔
142
                        continue;
3✔
143

144
                r = strv_extend(&envp, n);
3✔
145
                if (r < 0)
3✔
146
                        return r;
×
147
        }
148

149
        if (arg_inetd) {
1✔
150
                assert(n_fds == 1);
×
151

152
                r = rearrange_stdio(start_fd, start_fd, STDERR_FILENO); /* invalidates start_fd on success + error */
×
153
                if (r < 0)
×
154
                        return log_error_errno(r, "Failed to move fd to stdin+stdout: %m");
×
155

156
        } else {
157
                if (start_fd != SD_LISTEN_FDS_START) {
1✔
158
                        assert(n_fds == 1);
×
159

160
                        if (dup2(start_fd, SD_LISTEN_FDS_START) < 0)
×
161
                                return log_error_errno(errno, "Failed to dup connection: %m");
×
162

163
                        safe_close(start_fd);
×
164
                }
165

166
                r = strv_extendf(&envp, "LISTEN_FDS=%zu", n_fds);
1✔
167
                if (r < 0)
1✔
168
                        return r;
169

170
                r = strv_extendf(&envp, "LISTEN_PID=" PID_FMT, getpid_cached());
1✔
171
                if (r < 0)
1✔
172
                        return r;
173

174
                if (arg_fdnames) {
1✔
175
                        _cleanup_free_ char *names = NULL;
×
176
                        size_t len;
×
177

178
                        len = strv_length(arg_fdnames);
×
179
                        if (len == 1)
×
180
                                for (size_t i = 1; i < n_fds; i++) {
×
181
                                        r = strv_extend(&arg_fdnames, arg_fdnames[0]);
×
182
                                        if (r < 0)
×
183
                                                return log_oom();
×
184
                                }
185
                        else if (len != n_fds)
×
186
                                log_warning("The number of fd names is different than number of fds: %zu vs %zu", len, n_fds);
×
187

188
                        names = strv_join(arg_fdnames, ":");
×
189
                        if (!names)
×
190
                                return log_oom();
×
191

192
                        char *t = strjoin("LISTEN_FDNAMES=", names);
×
193
                        if (!t)
×
194
                                return log_oom();
×
195

196
                        r = strv_consume(&envp, t);
×
197
                        if (r < 0)
×
198
                                return r;
199
                }
200
        }
201

202
        STRV_FOREACH(s, arg_setenv) {
1✔
203
                r = strv_env_replace_strdup(&envp, *s);
×
204
                if (r < 0)
×
205
                        return r;
206
        }
207

208
        _cleanup_free_ char *joined = strv_join(argv, " ");
1✔
209
        if (!joined)
1✔
210
                return log_oom();
×
211

212
        log_info("Executing: %s", joined);
1✔
213
        execvpe(argv[0], argv, envp);
1✔
214

215
        return log_error_errno(errno, "Failed to execute '%s': %m", joined);
×
216
}
217

218
static int fork_and_exec_process(char * const *argv, int fd) {
×
219
        _cleanup_free_ char *joined = NULL;
×
220
        pid_t child_pid;
×
221
        int r;
×
222

223
        assert(!strv_isempty(argv));
×
224
        assert(fd >= 0);
×
225

226
        joined = strv_join(argv, " ");
×
227
        if (!joined)
×
228
                return log_oom();
×
229

230
        r = safe_fork("(activate)",
×
231
                      FORK_RESET_SIGNALS | FORK_DEATHSIG_SIGTERM | FORK_RLIMIT_NOFILE_SAFE | FORK_LOG,
232
                      &child_pid);
233
        if (r < 0)
×
234
                return r;
235
        if (r == 0) {
×
236
                /* In the child */
237
                (void) exec_process(argv, fd, 1);
×
238
                _exit(EXIT_FAILURE);
×
239
        }
240

241
        log_info("Spawned '%s' as PID " PID_FMT ".", joined, child_pid);
×
242
        return 0;
243
}
244

245
static int do_accept(char * const *argv, int fd) {
×
246
        _cleanup_free_ char *local = NULL, *peer = NULL;
×
247
        _cleanup_close_ int fd_accepted = -EBADF;
×
248

249
        fd_accepted = accept4(fd, NULL, NULL, 0);
×
250
        if (fd_accepted < 0) {
×
251
                if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
252
                        return 0;
253

254
                return log_error_errno(errno, "Failed to accept connection on fd:%d: %m", fd);
×
255
        }
256

257
        (void) getsockname_pretty(fd_accepted, &local);
×
258
        (void) getpeername_pretty(fd_accepted, true, &peer);
×
259
        log_info("Connection from %s to %s", strna(peer), strna(local));
×
260

261
        return fork_and_exec_process(argv, fd_accepted);
×
262
}
263

264
/* SIGCHLD handler. */
265
static void sigchld_hdl(int sig) {
×
266
        int r;
×
267

268
        PROTECT_ERRNO;
×
269

270
        for (;;) {
×
271
                siginfo_t si = {};
×
272

273
                r = waitid(P_ALL, 0, &si, WEXITED | WNOHANG);
×
274
                if (r < 0) {
×
275
                        if (errno != ECHILD)
×
276
                                log_error_errno(errno, "Failed to reap children: %m");
×
277
                        return;
×
278
                }
279
                if (si.si_pid == 0)
×
280
                        return;
281

282
                log_info("Child %d died with code %d", si.si_pid, si.si_status);
×
283
        }
284
}
285

286
static int install_chld_handler(void) {
×
287
        static const struct sigaction act = {
×
288
                .sa_flags = SA_NOCLDSTOP | SA_RESTART,
289
                .sa_handler = sigchld_hdl,
290
        };
291

292
        if (sigaction(SIGCHLD, &act, NULL) < 0)
×
293
                return log_error_errno(errno, "Failed to install SIGCHLD handler: %m");
×
294

295
        return 0;
296
}
297

298
static int help(void) {
×
299
        _cleanup_free_ char *link = NULL;
×
300
        int r;
×
301

302
        r = terminal_urlify_man("systemd-socket-activate", "1", &link);
×
303
        if (r < 0)
×
304
                return log_oom();
×
305

306
        printf("%s [OPTIONS...]\n"
×
307
               "\n%sListen on sockets and launch child on connection.%s\n"
308
               "\nOptions:\n"
309
               "  -h --help                  Show this help and exit\n"
310
               "     --version               Print version string and exit\n"
311
               "  -l --listen=ADDR           Listen for raw connections at ADDR\n"
312
               "  -d --datagram              Listen on datagram instead of stream socket\n"
313
               "     --seqpacket             Listen on SOCK_SEQPACKET instead of stream socket\n"
314
               "  -a --accept                Spawn separate child for each connection\n"
315
               "  -E --setenv=NAME[=VALUE]   Pass an environment variable to children\n"
316
               "     --fdname=NAME[:NAME...] Specify names for file descriptors\n"
317
               "     --inetd                 Enable inetd file descriptor passing protocol\n"
318
               "\nNote: file descriptors from sd_listen_fds() will be passed through.\n"
319
               "\nSee the %s for details.\n",
320
               program_invocation_short_name,
321
               ansi_highlight(),
322
               ansi_normal(),
323
               link);
324

325
        return 0;
326
}
327

328
static int parse_argv(int argc, char *argv[]) {
1✔
329
        enum {
1✔
330
                ARG_VERSION = 0x100,
331
                ARG_FDNAME,
332
                ARG_SEQPACKET,
333
                ARG_INETD,
334
        };
335

336
        static const struct option options[] = {
1✔
337
                { "help",        no_argument,       NULL, 'h'           },
338
                { "version",     no_argument,       NULL, ARG_VERSION   },
339
                { "datagram",    no_argument,       NULL, 'd'           },
340
                { "seqpacket",   no_argument,       NULL, ARG_SEQPACKET },
341
                { "listen",      required_argument, NULL, 'l'           },
342
                { "accept",      no_argument,       NULL, 'a'           },
343
                { "setenv",      required_argument, NULL, 'E'           },
344
                { "environment", required_argument, NULL, 'E'           }, /* legacy alias */
345
                { "fdname",      required_argument, NULL, ARG_FDNAME    },
346
                { "inetd",       no_argument,       NULL, ARG_INETD     },
347
                {}
348
        };
349

350
        int c, r;
1✔
351

352
        assert(argc >= 0);
1✔
353
        assert(argv);
1✔
354

355
        /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
356
         * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
357
        optind = 0;
1✔
358
        while ((c = getopt_long(argc, argv, "+hl:aE:d", options, NULL)) >= 0)
2✔
359
                switch (c) {
1✔
360
                case 'h':
×
361
                        return help();
×
362

363
                case ARG_VERSION:
×
364
                        return version();
×
365

366
                case 'l':
1✔
367
                        r = strv_extend(&arg_listen, optarg);
1✔
368
                        if (r < 0)
1✔
369
                                return log_oom();
×
370

371
                        break;
372

373
                case 'd':
×
374
                        if (arg_socket_type == SOCK_SEQPACKET)
×
375
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
376
                                                       "--datagram may not be combined with --seqpacket.");
377

378
                        arg_socket_type = SOCK_DGRAM;
×
379
                        break;
×
380

381
                case ARG_SEQPACKET:
×
382
                        if (arg_socket_type == SOCK_DGRAM)
×
383
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
384
                                                       "--seqpacket may not be combined with --datagram.");
385

386
                        arg_socket_type = SOCK_SEQPACKET;
×
387
                        break;
×
388

389
                case 'a':
×
390
                        arg_accept = true;
×
391
                        break;
×
392

393
                case 'E':
×
394
                        r = strv_env_replace_strdup_passthrough(&arg_setenv, optarg);
×
395
                        if (r < 0)
×
396
                                return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
×
397
                        break;
398

399
                case ARG_FDNAME: {
×
400
                        _cleanup_strv_free_ char **names = NULL;
×
401

402
                        names = strv_split(optarg, ":");
×
403
                        if (!names)
×
404
                                return log_oom();
×
405

406
                        STRV_FOREACH(s, names)
×
407
                                if (!fdname_is_valid(*s)) {
×
408
                                        _cleanup_free_ char *esc = NULL;
×
409

410
                                        esc = cescape(*s);
×
411
                                        log_warning("File descriptor name \"%s\" is not valid.", esc);
×
412
                                }
413

414
                        /* Empty optargs means one empty name */
415
                        r = strv_extend_strv(&arg_fdnames,
×
416
                                             strv_isempty(names) ? STRV_MAKE("") : names,
×
417
                                             false);
418
                        if (r < 0)
×
419
                                return log_error_errno(r, "strv_extend_strv: %m");
×
420
                        break;
×
421
                }
422

423
                case ARG_INETD:
×
424
                        arg_inetd = true;
×
425
                        break;
×
426

427
                case '?':
428
                        return -EINVAL;
429

430
                default:
×
431
                        assert_not_reached();
×
432
                }
433

434
        if (optind == argc)
1✔
435
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
436
                                       "%s: command to execute is missing.",
437
                                       program_invocation_short_name);
438

439
        if (arg_socket_type == SOCK_DGRAM && arg_accept)
1✔
440
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
441
                                       "Datagram sockets do not accept connections. "
442
                                       "The --datagram and --accept options may not be combined.");
443

444
        return 1 /* work to do */;
445
}
446

447
static int run(int argc, char **argv) {
1✔
448
        _cleanup_close_ int epoll_fd = -EBADF;
×
449
        _cleanup_strv_free_ char **exec_argv = NULL;
×
450
        int r, n;
1✔
451

452
        log_setup();
1✔
453

454
        r = parse_argv(argc, argv);
1✔
455
        if (r <= 0)
1✔
456
                return r;
457

458
        exec_argv = strv_copy(argv + optind);
1✔
459
        if (!exec_argv)
1✔
460
                return log_oom();
×
461

462
        assert(!strv_isempty(exec_argv));
1✔
463

464
        n = open_sockets(&epoll_fd);
1✔
465
        if (n < 0)
1✔
466
                return n;
467
        if (n == 0)
1✔
468
                return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No sockets to listen on specified or passed in.");
×
469

470
        /* Notify the caller that all sockets are open now. We only do this in --accept mode however,
471
         * since otherwise our process will be replaced and it's better to leave the readiness notify
472
         * to the actual payload. */
473
        _unused_ _cleanup_(notify_on_cleanup) const char *notify = NULL;
×
474
        if (arg_accept) {
1✔
475
                r = install_chld_handler();
×
476
                if (r < 0)
×
477
                        return r;
478

479
                notify = notify_start(NOTIFY_READY_MESSAGE, NOTIFY_STOPPING_MESSAGE);
×
480
        }
481

482
        for (;;) {
1✔
483
                struct epoll_event event;
1✔
484

485
                if (epoll_wait(epoll_fd, &event, 1, -1) < 0) {
1✔
486
                        if (errno == EINTR)
×
487
                                continue;
×
488

489
                        return log_error_errno(errno, "epoll_wait() failed: %m");
×
490
                }
491

492
                log_info("Communication attempt on fd %i.", event.data.fd);
1✔
493

494
                if (!arg_accept)
1✔
495
                        return exec_process(exec_argv, SD_LISTEN_FDS_START, (size_t) n);
1✔
496

497
                r = do_accept(exec_argv, event.data.fd);
×
498
                if (r < 0)
×
499
                        return r;
500
        }
501
}
502

503
DEFINE_MAIN_FUNCTION(run);
1✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc