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

systemd / systemd / 16280725298

14 Jul 2025 08:16PM UTC coverage: 72.166% (-0.006%) from 72.172%
16280725298

push

github

web-flow
Two fixlets for coverage test (#38183)

302135 of 418667 relevant lines covered (72.17%)

773261.64 hits per line

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

46.95
/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/wait.h>
6
#include <unistd.h>
7

8
#include "sd-daemon.h"
9

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

27
static char **arg_listen = NULL;
28
static bool arg_accept = false;
29
static int arg_socket_type = SOCK_STREAM;
30
static char **arg_setenv = NULL;
31
static char **arg_fdnames = NULL;
32
static bool arg_inetd = false;
33
static bool arg_now = 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) {
4✔
51
        _cleanup_close_ int epoll_fd = -EBADF;
4✔
52
        int n, r, count = 0;
4✔
53

54
        assert(ret_epoll_fd);
4✔
55

56
        n = sd_listen_fds(true);
4✔
57
        if (n < 0)
4✔
58
                return log_error_errno(n, "Failed to read listening file descriptors from environment: %m");
×
59
        if (n > 0) {
4✔
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) {
4✔
73
                _cleanup_free_ int *except = new(int, n);
8✔
74
                if (!except)
4✔
75
                        return log_oom();
×
76

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

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

84
                r = close_all_fds(except, n);
4✔
85
                if (r < 0)
4✔
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) {
9✔
93
                r = make_socket_fd(LOG_DEBUG, *address, arg_socket_type, (arg_accept * SOCK_CLOEXEC));
5✔
94
                if (r < 0)
5✔
95
                        return log_error_errno(r, "Failed to open '%s': %m", *address);
×
96

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

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

106
        if (count > 1 && !arg_accept && arg_inetd)
4✔
107
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
108
                                       "--inetd only supported with a single file descriptor, or with --accept.");
109

110
        if (arg_fdnames && !arg_inetd) {
3✔
111
                size_t n_fdnames = strv_length(arg_fdnames);
×
112

113
                if (!arg_accept && n_fdnames != (size_t) count)
×
114
                        log_warning("The number of fd names is different from the number of fds: %zu vs %i",
×
115
                                    n_fdnames, count);
116

117
                if (arg_accept && n_fdnames > 1)
×
118
                        log_warning("More than one fd name specified with --accept.");
×
119
        }
120

121
        if (!arg_now) {
3✔
122
                epoll_fd = epoll_create1(EPOLL_CLOEXEC);
1✔
123
                if (epoll_fd < 0)
1✔
124
                        return log_error_errno(errno, "Failed to create epoll object: %m");
×
125
        }
126

127
        for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + count; fd++) {
6✔
128
                _cleanup_free_ char *name = NULL;
3✔
129

130
                getsockname_pretty(fd, &name);
3✔
131
                log_info("Listening on %s as %i.", strna(name), fd);
3✔
132

133
                if (epoll_fd >= 0) {
3✔
134
                        r = add_epoll(epoll_fd, fd);
1✔
135
                        if (r < 0)
1✔
136
                                return r;
×
137
                }
138
        }
139

140
        *ret_epoll_fd = TAKE_FD(epoll_fd);
3✔
141
        return count;
3✔
142
}
143

144
static int exec_process(char * const *argv, int start_fd, size_t n_fds) {
4✔
145
        _cleanup_strv_free_ char **envp = NULL;
×
146
        int r;
4✔
147

148
        assert(!strv_isempty(argv));
4✔
149
        assert(start_fd >= 0);
4✔
150
        assert(n_fds > 0);
4✔
151

152
        FOREACH_STRING(var, "TERM", "COLORTERM", "NO_COLOR", "PATH", "USER", "HOME") {
28✔
153
                const char *n;
24✔
154

155
                n = strv_find_prefix(environ, var);
24✔
156
                if (!n)
24✔
157
                        continue;
12✔
158

159
                r = strv_extend(&envp, n);
12✔
160
                if (r < 0)
12✔
161
                        return r;
×
162
        }
163

164
        if (arg_inetd) {
4✔
165
                assert(n_fds == 1);
1✔
166

167
                r = rearrange_stdio(start_fd, start_fd, STDERR_FILENO); /* invalidates start_fd on success + error */
1✔
168
                if (r < 0)
1✔
169
                        return log_error_errno(r, "Failed to move fd to stdin+stdout: %m");
×
170

171
        } else {
172
                if (start_fd != SD_LISTEN_FDS_START) {
3✔
173
                        assert(n_fds == 1);
×
174

175
                        if (dup2(start_fd, SD_LISTEN_FDS_START) < 0)
×
176
                                return log_error_errno(errno, "Failed to dup connection: %m");
×
177

178
                        safe_close(start_fd);
×
179
                }
180

181
                r = strv_extendf(&envp, "LISTEN_FDS=%zu", n_fds);
3✔
182
                if (r < 0)
3✔
183
                        return r;
184

185
                r = strv_extendf(&envp, "LISTEN_PID=" PID_FMT, getpid_cached());
3✔
186
                if (r < 0)
3✔
187
                        return r;
188

189
                if (arg_fdnames) {
3✔
190
                        _cleanup_free_ char *names = NULL;
×
191
                        size_t len;
×
192

193
                        len = strv_length(arg_fdnames);
×
194
                        if (len == 1)
×
195
                                for (size_t i = 1; i < n_fds; i++) {
×
196
                                        r = strv_extend(&arg_fdnames, arg_fdnames[0]);
×
197
                                        if (r < 0)
×
198
                                                return log_oom();
×
199
                                }
200

201
                        names = strv_join(arg_fdnames, ":");
×
202
                        if (!names)
×
203
                                return log_oom();
×
204

205
                        char *t = strjoin("LISTEN_FDNAMES=", names);
×
206
                        if (!t)
×
207
                                return log_oom();
×
208

209
                        r = strv_consume(&envp, t);
×
210
                        if (r < 0)
×
211
                                return r;
212
                }
213
        }
214

215
        STRV_FOREACH(s, arg_setenv) {
4✔
216
                r = strv_env_replace_strdup(&envp, *s);
×
217
                if (r < 0)
×
218
                        return r;
219
        }
220

221
        _cleanup_free_ char *joined = strv_join(argv, " ");
4✔
222
        if (!joined)
4✔
223
                return log_oom();
×
224

225
        log_info("Executing: %s", joined);
4✔
226
        execvpe(argv[0], argv, envp);
4✔
227

228
        return log_error_errno(errno, "Failed to execute '%s': %m", joined);
×
229
}
230

231
static int fork_and_exec_process(char * const *argv, int fd) {
×
232
        _cleanup_free_ char *joined = NULL;
×
233
        pid_t child_pid;
×
234
        int r;
×
235

236
        assert(!strv_isempty(argv));
×
237
        assert(fd >= 0);
×
238

239
        joined = strv_join(argv, " ");
×
240
        if (!joined)
×
241
                return log_oom();
×
242

243
        r = safe_fork("(activate)",
×
244
                      FORK_RESET_SIGNALS | FORK_DEATHSIG_SIGTERM | FORK_RLIMIT_NOFILE_SAFE | FORK_LOG,
245
                      &child_pid);
246
        if (r < 0)
1✔
247
                return r;
248
        if (r == 0) {
1✔
249
                /* In the child */
250
                (void) exec_process(argv, fd, 1);
1✔
251
                _exit(EXIT_FAILURE);
×
252
        }
253

254
        log_info("Spawned '%s' as PID " PID_FMT ".", joined, child_pid);
×
255
        return 0;
256
}
257

258
static int do_accept(char * const *argv, int fd) {
×
259
        _cleanup_free_ char *local = NULL, *peer = NULL;
×
260
        _cleanup_close_ int fd_accepted = -EBADF;
×
261

262
        fd_accepted = accept4(fd, NULL, NULL, 0);
×
263
        if (fd_accepted < 0) {
×
264
                if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
265
                        return 0;
266

267
                return log_error_errno(errno, "Failed to accept connection on fd:%d: %m", fd);
×
268
        }
269

270
        (void) getsockname_pretty(fd_accepted, &local);
×
271
        (void) getpeername_pretty(fd_accepted, true, &peer);
×
272
        log_info("Connection from %s to %s", strna(peer), strna(local));
×
273

274
        return fork_and_exec_process(argv, fd_accepted);
×
275
}
276

277
/* SIGCHLD handler. */
278
static void sigchld_hdl(int sig) {
×
279
        int r;
×
280

281
        PROTECT_ERRNO;
×
282

283
        for (;;) {
×
284
                siginfo_t si = {};
×
285

286
                r = waitid(P_ALL, 0, &si, WEXITED | WNOHANG);
×
287
                if (r < 0) {
×
288
                        if (errno != ECHILD)
×
289
                                log_error_errno(errno, "Failed to reap children: %m");
×
290
                        return;
×
291
                }
292
                if (si.si_pid == 0)
×
293
                        return;
294

295
                log_info("Child %d died with code %d", si.si_pid, si.si_status);
×
296
        }
297
}
298

299
static int install_chld_handler(void) {
×
300
        static const struct sigaction act = {
×
301
                .sa_flags = SA_NOCLDSTOP | SA_RESTART,
302
                .sa_handler = sigchld_hdl,
303
        };
304

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

308
        return 0;
309
}
310

311
static int help(void) {
×
312
        _cleanup_free_ char *link = NULL;
×
313
        int r;
×
314

315
        r = terminal_urlify_man("systemd-socket-activate", "1", &link);
×
316
        if (r < 0)
×
317
                return log_oom();
×
318

319
        printf("%s [OPTIONS...] COMMAND ...\n"
×
320
               "\n%sListen on sockets and launch child on connection.%s\n"
321
               "\nOptions:\n"
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"
331
               "     --now                   Start instantly instead of waiting for connection\n"
332
               "\nNote: file descriptors from sd_listen_fds() will be passed through.\n"
333
               "\nSee the %s for details.\n",
334
               program_invocation_short_name,
335
               ansi_highlight(),
336
               ansi_normal(),
337
               link);
338

339
        return 0;
340
}
341

342
static int parse_argv(int argc, char *argv[]) {
5✔
343
        enum {
5✔
344
                ARG_VERSION = 0x100,
345
                ARG_FDNAME,
346
                ARG_SEQPACKET,
347
                ARG_INETD,
348
                ARG_NOW,
349
        };
350

351
        static const struct option options[] = {
5✔
352
                { "help",        no_argument,       NULL, 'h'           },
353
                { "version",     no_argument,       NULL, ARG_VERSION   },
354
                { "datagram",    no_argument,       NULL, 'd'           },
355
                { "seqpacket",   no_argument,       NULL, ARG_SEQPACKET },
356
                { "listen",      required_argument, NULL, 'l'           },
357
                { "accept",      no_argument,       NULL, 'a'           },
358
                { "setenv",      required_argument, NULL, 'E'           },
359
                { "environment", required_argument, NULL, 'E'           }, /* legacy alias */
360
                { "fdname",      required_argument, NULL, ARG_FDNAME    },
361
                { "inetd",       no_argument,       NULL, ARG_INETD     },
362
                { "now",         no_argument,       NULL, ARG_NOW       },
363
                {}
364
        };
365

366
        int c, r;
5✔
367

368
        assert(argc >= 0);
5✔
369
        assert(argv);
5✔
370

371
        /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
372
         * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
373
        optind = 0;
5✔
374
        while ((c = getopt_long(argc, argv, "+hl:aE:d", options, NULL)) >= 0)
16✔
375
                switch (c) {
11✔
376
                case 'h':
×
377
                        return help();
×
378

379
                case ARG_VERSION:
×
380
                        return version();
×
381

382
                case 'l':
6✔
383
                        r = strv_extend(&arg_listen, optarg);
6✔
384
                        if (r < 0)
6✔
385
                                return log_oom();
×
386

387
                        break;
388

389
                case 'd':
×
390
                        if (arg_socket_type == SOCK_SEQPACKET)
×
391
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
392
                                                       "--datagram may not be combined with --seqpacket.");
393

394
                        arg_socket_type = SOCK_DGRAM;
×
395
                        break;
×
396

397
                case ARG_SEQPACKET:
×
398
                        if (arg_socket_type == SOCK_DGRAM)
×
399
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
400
                                                       "--seqpacket may not be combined with --datagram.");
401

402
                        arg_socket_type = SOCK_SEQPACKET;
×
403
                        break;
×
404

405
                case 'a':
1✔
406
                        arg_accept = true;
1✔
407
                        break;
1✔
408

409
                case 'E':
×
410
                        r = strv_env_replace_strdup_passthrough(&arg_setenv, optarg);
×
411
                        if (r < 0)
×
412
                                return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
×
413
                        break;
414

415
                case ARG_FDNAME: {
×
416
                        _cleanup_strv_free_ char **names = NULL;
×
417

418
                        names = strv_split(optarg, ":");
×
419
                        if (!names)
×
420
                                return log_oom();
×
421

422
                        STRV_FOREACH(s, names)
×
423
                                if (!fdname_is_valid(*s)) {
×
424
                                        _cleanup_free_ char *esc = NULL;
×
425

426
                                        esc = cescape(*s);
×
427
                                        log_warning("File descriptor name \"%s\" is not valid.", esc);
×
428
                                }
429

430
                        /* Empty optargs means one empty name */
431
                        r = strv_extend_strv(&arg_fdnames,
×
432
                                             strv_isempty(names) ? STRV_MAKE("") : names,
×
433
                                             false);
434
                        if (r < 0)
×
435
                                return log_error_errno(r, "strv_extend_strv: %m");
×
436
                        break;
×
437
                }
438

439
                case ARG_INETD:
1✔
440
                        arg_inetd = true;
1✔
441
                        break;
1✔
442

443
                case ARG_NOW:
3✔
444
                        arg_now = true;
3✔
445
                        break;
3✔
446

447
                case '?':
448
                        return -EINVAL;
449

450
                default:
×
451
                        assert_not_reached();
×
452
                }
453

454
        if (optind == argc)
5✔
455
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
456
                                       "%s: command to execute is missing.",
457
                                       program_invocation_short_name);
458

459
        if (arg_socket_type == SOCK_DGRAM && arg_accept)
5✔
460
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
461
                                       "Datagram sockets do not accept connections. "
462
                                       "The --datagram and --accept options may not be combined.");
463

464
        if (arg_accept && arg_now)
5✔
465
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
466
                                       "--now cannot be used in conjunction with --accept.");
467

468
        if (arg_fdnames && arg_inetd)
4✔
469
                log_warning("--fdname= has no effect with --inetd present.");
×
470

471
        return 1 /* work to do */;
472
}
473

474
static int run(int argc, char **argv) {
5✔
475
        _cleanup_close_ int epoll_fd = -EBADF;
2✔
476
        _cleanup_strv_free_ char **exec_argv = NULL;
2✔
477
        int r, n;
5✔
478

479
        log_setup();
5✔
480

481
        r = parse_argv(argc, argv);
5✔
482
        if (r <= 0)
5✔
483
                return r;
484

485
        exec_argv = strv_copy(argv + optind);
4✔
486
        if (!exec_argv)
4✔
487
                return log_oom();
×
488

489
        assert(!strv_isempty(exec_argv));
4✔
490

491
        n = open_sockets(&epoll_fd);
4✔
492
        if (n < 0)
4✔
493
                return n;
494
        if (n == 0)
3✔
495
                return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No sockets to listen on specified or passed in.");
×
496

497
        if (arg_accept) {
3✔
498
                r = install_chld_handler();
×
499
                if (r < 0)
×
500
                        return r;
501
        }
502

503
        /* Notify the caller that all sockets are open now. */
504
        _unused_ _cleanup_(notify_on_cleanup) const char *notify = notify_start(NOTIFY_READY_MESSAGE, NOTIFY_STOPPING_MESSAGE);
3✔
505

506
        for (;;) {
3✔
507
                struct epoll_event event;
3✔
508

509
                if (epoll_fd >= 0) {
3✔
510
                        if (epoll_wait(epoll_fd, &event, 1, -1) < 0) {
1✔
511
                                if (errno == EINTR)
×
512
                                        continue;
×
513

514
                                return log_error_errno(errno, "epoll_wait() failed: %m");
×
515
                        }
516

517
                        log_info("Communication attempt on fd %i.", event.data.fd);
1✔
518
                }
519

520
                if (!arg_accept)
3✔
521
                        return exec_process(exec_argv, SD_LISTEN_FDS_START, (size_t) n);
3✔
522

523
                r = do_accept(exec_argv, event.data.fd);
×
524
                if (r < 0)
×
525
                        return r;
526
        }
527
}
528

529
DEFINE_MAIN_FUNCTION(run);
5✔
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