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

systemd / systemd / 20669300594

02 Jan 2026 09:00PM UTC coverage: 72.677% (-0.02%) from 72.697%
20669300594

push

github

web-flow
clang-tidy: Enable more warnings (#39910)

25 of 27 new or added lines in 3 files covered. (92.59%)

5655 existing lines in 111 files now uncovered.

310023 of 426578 relevant lines covered (72.68%)

1136999.43 hits per line

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

47.74
/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 "pidfd-util.h"
21
#include "pidref.h"
22
#include "pretty-print.h"
23
#include "process-util.h"
24
#include "socket-netlink.h"
25
#include "socket-util.h"
26
#include "string-util.h"
27
#include "strv.h"
28

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

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

43
        assert(epoll_fd >= 0);
1✔
44
        assert(fd >= 0);
1✔
45

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

49
        return 0;
50
}
51

52
static int open_sockets(int *ret_epoll_fd) {
3✔
53
        _cleanup_close_ int epoll_fd = -EBADF;
3✔
54
        int n, r, count = 0;
3✔
55

56
        assert(ret_epoll_fd);
3✔
57

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

64
                for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd++) {
×
65
                        r = fd_cloexec(fd, arg_accept);
×
UNCOV
66
                        if (r < 0)
×
67
                                return r;
68

UNCOV
69
                        count++;
×
70
                }
71
        }
72

73
        /* Close logging and all other descriptors */
74
        if (arg_listen) {
3✔
75
                _cleanup_free_ int *except = new(int, n);
6✔
76
                if (!except)
3✔
UNCOV
77
                        return log_oom();
×
78

79
                for (int i = 0; i < n; i++)
3✔
UNCOV
80
                        except[i] = SD_LISTEN_FDS_START + i;
×
81

82
                log_close();
3✔
83
                log_set_open_when_needed(true);
3✔
84
                log_settle_target();
3✔
85

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

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

94
        STRV_FOREACH(address, arg_listen) {
7✔
95
                r = make_socket_fd(LOG_DEBUG, *address, arg_socket_type, (arg_accept * SOCK_CLOEXEC));
4✔
96
                if (r < 0)
4✔
UNCOV
97
                        return log_error_errno(r, "Failed to open '%s': %m", *address);
×
98

99
                assert(r == SD_LISTEN_FDS_START + count);
4✔
100
                count++;
4✔
101
        }
102

103
        if (arg_listen) {
3✔
104
                log_open();
3✔
105
                log_set_open_when_needed(false);
3✔
106
        }
107

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

112
        if (arg_fdnames && !arg_inetd) {
2✔
UNCOV
113
                size_t n_fdnames = strv_length(arg_fdnames);
×
114

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

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

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

129
        for (int fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + count; fd++) {
4✔
130
                _cleanup_free_ char *name = NULL;
2✔
131

132
                getsockname_pretty(fd, &name);
2✔
133
                log_info("Listening on %s as %i.", strna(name), fd);
2✔
134

135
                if (epoll_fd >= 0) {
2✔
136
                        r = add_epoll(epoll_fd, fd);
1✔
137
                        if (r < 0)
1✔
UNCOV
138
                                return r;
×
139
                }
140
        }
141

142
        *ret_epoll_fd = TAKE_FD(epoll_fd);
2✔
143
        return count;
2✔
144
}
145

146
static int exec_process(char * const *argv, int start_fd, size_t n_fds) {
3✔
UNCOV
147
        _cleanup_strv_free_ char **envp = NULL;
×
148
        int r;
3✔
149

150
        assert(!strv_isempty(argv));
3✔
151
        assert(start_fd >= 0);
3✔
152
        assert(n_fds > 0);
3✔
153

154
        FOREACH_STRING(var, "TERM", "COLORTERM", "NO_COLOR", "PATH", "USER", "HOME") {
21✔
155
                const char *n;
18✔
156

157
                n = strv_find_prefix(environ, var);
18✔
158
                if (!n)
18✔
159
                        continue;
12✔
160

161
                r = strv_extend(&envp, n);
6✔
162
                if (r < 0)
6✔
UNCOV
163
                        return r;
×
164
        }
165

166
        if (arg_inetd) {
3✔
167
                assert(n_fds == 1);
1✔
168

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

173
        } else {
174
                if (start_fd != SD_LISTEN_FDS_START) {
2✔
UNCOV
175
                        assert(n_fds == 1);
×
176

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

UNCOV
180
                        safe_close(start_fd);
×
181
                }
182

183
                r = strv_extendf(&envp, "LISTEN_FDS=%zu", n_fds);
2✔
184
                if (r < 0)
2✔
185
                        return r;
186

187
                r = strv_extendf(&envp, "LISTEN_PID=" PID_FMT, getpid_cached());
2✔
188
                if (r < 0)
2✔
189
                        return r;
190

191
                uint64_t pidfdid;
2✔
192
                if (pidfd_get_inode_id_self_cached(&pidfdid) >= 0) {
2✔
193
                        r = strv_extendf(&envp, "LISTEN_PIDFDID=%" PRIu64, pidfdid);
2✔
194
                        if (r < 0)
2✔
195
                                return r;
196
                }
197

198
                if (arg_fdnames) {
2✔
199
                        _cleanup_free_ char *names = NULL;
×
UNCOV
200
                        size_t len;
×
201

202
                        len = strv_length(arg_fdnames);
×
203
                        if (len == 1)
×
204
                                for (size_t i = 1; i < n_fds; i++) {
×
205
                                        r = strv_extend(&arg_fdnames, arg_fdnames[0]);
×
206
                                        if (r < 0)
×
UNCOV
207
                                                return log_oom();
×
208
                                }
209

210
                        names = strv_join(arg_fdnames, ":");
×
211
                        if (!names)
×
UNCOV
212
                                return log_oom();
×
213

214
                        char *t = strjoin("LISTEN_FDNAMES=", names);
×
215
                        if (!t)
×
UNCOV
216
                                return log_oom();
×
217

218
                        r = strv_consume(&envp, t);
×
UNCOV
219
                        if (r < 0)
×
220
                                return r;
221
                }
222
        }
223

224
        STRV_FOREACH(s, arg_setenv) {
3✔
225
                r = strv_env_replace_strdup(&envp, *s);
×
UNCOV
226
                if (r < 0)
×
227
                        return r;
228
        }
229

230
        _cleanup_free_ char *joined = strv_join(argv, " ");
3✔
231
        if (!joined)
3✔
UNCOV
232
                return log_oom();
×
233

234
        log_info("Executing: %s", joined);
3✔
235
        execvpe(argv[0], argv, envp);
3✔
236

UNCOV
237
        return log_error_errno(errno, "Failed to execute '%s': %m", joined);
×
238
}
239

240
static int fork_and_exec_process(char * const *argv, int fd) {
×
241
        _cleanup_free_ char *joined = NULL;
×
242
        int r;
×
243

244
        assert(!strv_isempty(argv));
×
245
        assert(fd >= 0);
×
246

247
        joined = strv_join(argv, " ");
×
248
        if (!joined)
×
249
                return log_oom();
×
250

251
        _cleanup_(pidref_done) PidRef child_pidref = PIDREF_NULL;
×
UNCOV
252
        r = pidref_safe_fork(
×
253
                        "(activate)",
254
                        FORK_RESET_SIGNALS|FORK_DEATHSIG_SIGTERM|FORK_RLIMIT_NOFILE_SAFE|FORK_LOG,
255
                        &child_pidref);
256
        if (r < 0)
1✔
257
                return r;
258
        if (r == 0) {
1✔
259
                /* In the child */
260
                (void) exec_process(argv, fd, 1);
1✔
UNCOV
261
                _exit(EXIT_FAILURE);
×
262
        }
263

UNCOV
264
        log_info("Spawned '%s' as PID " PID_FMT ".", joined, child_pidref.pid);
×
265
        return 0;
266
}
267

268
static int do_accept(char * const *argv, int fd) {
×
UNCOV
269
        _cleanup_free_ char *local = NULL, *peer = NULL;
×
270
        _cleanup_close_ int fd_accepted = -EBADF;
×
271

272
        fd_accepted = accept4(fd, NULL, NULL, 0);
×
UNCOV
273
        if (fd_accepted < 0) {
×
UNCOV
274
                if (ERRNO_IS_ACCEPT_AGAIN(errno))
×
275
                        return 0;
276

UNCOV
277
                return log_error_errno(errno, "Failed to accept connection on fd:%d: %m", fd);
×
278
        }
279

280
        (void) getsockname_pretty(fd_accepted, &local);
×
UNCOV
281
        (void) getpeername_pretty(fd_accepted, true, &peer);
×
282
        log_info("Connection from %s to %s", strna(peer), strna(local));
×
283

UNCOV
284
        return fork_and_exec_process(argv, fd_accepted);
×
285
}
286

287
/* SIGCHLD handler. */
UNCOV
288
static void sigchld_hdl(int sig) {
×
289
        int r;
×
290

291
        PROTECT_ERRNO;
×
292

UNCOV
293
        for (;;) {
×
294
                siginfo_t si = {};
×
295

296
                r = waitid(P_ALL, 0, &si, WEXITED | WNOHANG);
×
297
                if (r < 0) {
×
298
                        if (errno != ECHILD)
×
UNCOV
299
                                log_error_errno(errno, "Failed to reap children: %m");
×
300
                        return;
×
301
                }
UNCOV
302
                if (si.si_pid == 0)
×
303
                        return;
304

UNCOV
305
                log_info("Child %d died with code %d", si.si_pid, si.si_status);
×
306
        }
307
}
308

UNCOV
309
static int install_chld_handler(void) {
×
UNCOV
310
        static const struct sigaction act = {
×
311
                .sa_flags = SA_NOCLDSTOP | SA_RESTART,
312
                .sa_handler = sigchld_hdl,
313
        };
314

UNCOV
315
        if (sigaction(SIGCHLD, &act, NULL) < 0)
×
UNCOV
316
                return log_error_errno(errno, "Failed to install SIGCHLD handler: %m");
×
317

318
        return 0;
319
}
320

321
static int help(void) {
×
UNCOV
322
        _cleanup_free_ char *link = NULL;
×
323
        int r;
×
324

325
        r = terminal_urlify_man("systemd-socket-activate", "1", &link);
×
UNCOV
326
        if (r < 0)
×
327
                return log_oom();
×
328

UNCOV
329
        printf("%s [OPTIONS...] COMMAND ...\n"
×
330
               "\n%sListen on sockets and launch child on connection.%s\n"
331
               "\nOptions:\n"
332
               "  -h --help                  Show this help and exit\n"
333
               "     --version               Print version string and exit\n"
334
               "  -l --listen=ADDR           Listen for raw connections at ADDR\n"
335
               "  -d --datagram              Listen on datagram instead of stream socket\n"
336
               "     --seqpacket             Listen on SOCK_SEQPACKET instead of stream socket\n"
337
               "  -a --accept                Spawn separate child for each connection\n"
338
               "  -E --setenv=NAME[=VALUE]   Pass an environment variable to children\n"
339
               "     --fdname=NAME[:NAME...] Specify names for file descriptors\n"
340
               "     --inetd                 Enable inetd file descriptor passing protocol\n"
341
               "     --now                   Start instantly instead of waiting for connection\n"
342
               "\nNote: file descriptors from sd_listen_fds() will be passed through.\n"
343
               "\nSee the %s for details.\n",
344
               program_invocation_short_name,
345
               ansi_highlight(),
346
               ansi_normal(),
347
               link);
348

349
        return 0;
350
}
351

352
static int parse_argv(int argc, char *argv[]) {
4✔
353
        enum {
4✔
354
                ARG_VERSION = 0x100,
355
                ARG_FDNAME,
356
                ARG_SEQPACKET,
357
                ARG_INETD,
358
                ARG_NOW,
359
        };
360

361
        static const struct option options[] = {
4✔
362
                { "help",        no_argument,       NULL, 'h'           },
363
                { "version",     no_argument,       NULL, ARG_VERSION   },
364
                { "datagram",    no_argument,       NULL, 'd'           },
365
                { "seqpacket",   no_argument,       NULL, ARG_SEQPACKET },
366
                { "listen",      required_argument, NULL, 'l'           },
367
                { "accept",      no_argument,       NULL, 'a'           },
368
                { "setenv",      required_argument, NULL, 'E'           },
369
                { "environment", required_argument, NULL, 'E'           }, /* legacy alias */
370
                { "fdname",      required_argument, NULL, ARG_FDNAME    },
371
                { "inetd",       no_argument,       NULL, ARG_INETD     },
372
                { "now",         no_argument,       NULL, ARG_NOW       },
373
                {}
374
        };
375

376
        int c, r;
4✔
377

378
        assert(argc >= 0);
4✔
379
        assert(argv);
4✔
380

381
        /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
382
         * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
383
        optind = 0;
4✔
384
        while ((c = getopt_long(argc, argv, "+hl:aE:d", options, NULL)) >= 0)
13✔
385
                switch (c) {
9✔
UNCOV
386
                case 'h':
×
387
                        return help();
×
388

UNCOV
389
                case ARG_VERSION:
×
UNCOV
390
                        return version();
×
391

392
                case 'l':
5✔
393
                        r = strv_extend(&arg_listen, optarg);
5✔
394
                        if (r < 0)
5✔
UNCOV
395
                                return log_oom();
×
396

397
                        break;
398

399
                case 'd':
×
UNCOV
400
                        if (arg_socket_type == SOCK_SEQPACKET)
×
UNCOV
401
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
402
                                                       "--datagram may not be combined with --seqpacket.");
403

UNCOV
404
                        arg_socket_type = SOCK_DGRAM;
×
405
                        break;
×
406

407
                case ARG_SEQPACKET:
×
UNCOV
408
                        if (arg_socket_type == SOCK_DGRAM)
×
UNCOV
409
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
410
                                                       "--seqpacket may not be combined with --datagram.");
411

UNCOV
412
                        arg_socket_type = SOCK_SEQPACKET;
×
UNCOV
413
                        break;
×
414

415
                case 'a':
1✔
416
                        arg_accept = true;
1✔
417
                        break;
1✔
418

419
                case 'E':
×
420
                        r = strv_env_replace_strdup_passthrough(&arg_setenv, optarg);
×
UNCOV
421
                        if (r < 0)
×
UNCOV
422
                                return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
×
423
                        break;
424

UNCOV
425
                case ARG_FDNAME: {
×
426
                        _cleanup_strv_free_ char **names = NULL;
×
427

428
                        names = strv_split(optarg, ":");
×
UNCOV
429
                        if (!names)
×
430
                                return log_oom();
×
431

432
                        STRV_FOREACH(s, names)
×
UNCOV
433
                                if (!fdname_is_valid(*s)) {
×
434
                                        _cleanup_free_ char *esc = NULL;
×
435

UNCOV
436
                                        esc = cescape(*s);
×
UNCOV
437
                                        log_warning("File descriptor name \"%s\" is not valid.", esc);
×
438
                                }
439

440
                        /* Empty optargs means one empty name */
UNCOV
441
                        r = strv_extend_strv(&arg_fdnames,
×
442
                                             strv_isempty(names) ? STRV_MAKE("") : names,
×
443
                                             false);
444
                        if (r < 0)
×
UNCOV
445
                                return log_error_errno(r, "strv_extend_strv: %m");
×
UNCOV
446
                        break;
×
447
                }
448

449
                case ARG_INETD:
1✔
450
                        arg_inetd = true;
1✔
451
                        break;
1✔
452

453
                case ARG_NOW:
2✔
454
                        arg_now = true;
2✔
455
                        break;
2✔
456

457
                case '?':
458
                        return -EINVAL;
459

UNCOV
460
                default:
×
UNCOV
461
                        assert_not_reached();
×
462
                }
463

464
        if (optind == argc)
4✔
UNCOV
465
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
466
                                       "%s: command to execute is missing.",
467
                                       program_invocation_short_name);
468

469
        if (arg_socket_type == SOCK_DGRAM && arg_accept)
4✔
UNCOV
470
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
471
                                       "Datagram sockets do not accept connections. "
472
                                       "The --datagram and --accept options may not be combined.");
473

474
        if (arg_accept && arg_now)
4✔
475
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
476
                                       "--now cannot be used in conjunction with --accept.");
477

478
        if (arg_fdnames && arg_inetd)
3✔
UNCOV
479
                log_warning("--fdname= has no effect with --inetd present.");
×
480

481
        return 1 /* work to do */;
482
}
483

484
static int run(int argc, char **argv) {
4✔
485
        _cleanup_close_ int epoll_fd = -EBADF;
2✔
486
        _cleanup_strv_free_ char **exec_argv = NULL;
2✔
487
        int r, n;
4✔
488

489
        log_setup();
4✔
490

491
        r = parse_argv(argc, argv);
4✔
492
        if (r <= 0)
4✔
493
                return r;
494

495
        exec_argv = strv_copy(argv + optind);
3✔
496
        if (!exec_argv)
3✔
UNCOV
497
                return log_oom();
×
498

499
        assert(!strv_isempty(exec_argv));
3✔
500

501
        n = open_sockets(&epoll_fd);
3✔
502
        if (n < 0)
3✔
503
                return n;
504
        if (n == 0)
2✔
UNCOV
505
                return log_error_errno(SYNTHETIC_ERRNO(ENOENT), "No sockets to listen on specified or passed in.");
×
506

507
        if (arg_accept) {
2✔
UNCOV
508
                r = install_chld_handler();
×
UNCOV
509
                if (r < 0)
×
510
                        return r;
511
        }
512

513
        /* Notify the caller that all sockets are open now. */
514
        _unused_ _cleanup_(notify_on_cleanup) const char *notify = notify_start(NOTIFY_READY_MESSAGE, NOTIFY_STOPPING_MESSAGE);
2✔
515

516
        for (;;) {
2✔
517
                struct epoll_event event;
2✔
518

519
                if (epoll_fd >= 0) {
2✔
520
                        if (epoll_wait(epoll_fd, &event, 1, -1) < 0) {
1✔
UNCOV
521
                                if (errno == EINTR)
×
522
                                        continue;
×
523

UNCOV
524
                                return log_error_errno(errno, "epoll_wait() failed: %m");
×
525
                        }
526

527
                        log_info("Communication attempt on fd %i.", event.data.fd);
1✔
528
                }
529

530
                if (!arg_accept)
2✔
531
                        return exec_process(exec_argv, SD_LISTEN_FDS_START, (size_t) n);
2✔
532

UNCOV
533
                r = do_accept(exec_argv, event.data.fd);
×
UNCOV
534
                if (r < 0)
×
535
                        return r;
536
        }
537
}
538

539
DEFINE_MAIN_FUNCTION(run);
4✔
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