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

systemd / systemd / 18765396043

23 Oct 2025 01:51PM UTC coverage: 72.284% (-0.01%) from 72.295%
18765396043

push

github

YHNdnzj
core: increment start limit counter only when we can start the unit

Otherwise, e.g. requesting to start a unit that is under stopping may
enter the failed state.

This makes
- rename .can_start() -> .test_startable(), and make it allow to return
  boolean and refuse to start units when it returns false,
- refuse earlier to start units that are in the deactivating state, so
  several redundant conditions in .start() can be dropped,
- move checks for unit states mapped to UNIT_ACTIVATING from .start() to
  .test_startable().

Fixes #39247.

13 of 15 new or added lines in 8 files covered. (86.67%)

6946 existing lines in 72 files now uncovered.

304970 of 421905 relevant lines covered (72.28%)

1105466.04 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 "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
static bool arg_now = false;
35

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

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

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

48
        return 0;
49
}
50

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

55
        assert(ret_epoll_fd);
3✔
56

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

UNCOV
179
                        safe_close(start_fd);
×
180
                }
181

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

262
        log_info("Spawned '%s' as PID " PID_FMT ".", joined, child_pid);
×
263
        return 0;
264
}
265

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

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

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

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

UNCOV
282
        return fork_and_exec_process(argv, fd_accepted);
×
283
}
284

285
/* SIGCHLD handler. */
286
static void sigchld_hdl(int sig) {
×
287
        int r;
×
288

289
        PROTECT_ERRNO;
×
290

UNCOV
291
        for (;;) {
×
292
                siginfo_t si = {};
×
293

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

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

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

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

316
        return 0;
317
}
318

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

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

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

347
        return 0;
348
}
349

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

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

374
        int c, r;
4✔
375

376
        assert(argc >= 0);
4✔
377
        assert(argv);
4✔
378

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

UNCOV
387
                case ARG_VERSION:
×
UNCOV
388
                        return version();
×
389

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

395
                        break;
396

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

402
                        arg_socket_type = SOCK_DGRAM;
×
403
                        break;
×
404

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

410
                        arg_socket_type = SOCK_SEQPACKET;
×
411
                        break;
×
412

413
                case 'a':
1✔
414
                        arg_accept = true;
1✔
415
                        break;
1✔
416

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

423
                case ARG_FDNAME: {
×
424
                        _cleanup_strv_free_ char **names = NULL;
×
425

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

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

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

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

447
                case ARG_INETD:
1✔
448
                        arg_inetd = true;
1✔
449
                        break;
1✔
450

451
                case ARG_NOW:
2✔
452
                        arg_now = true;
2✔
453
                        break;
2✔
454

455
                case '?':
456
                        return -EINVAL;
457

UNCOV
458
                default:
×
UNCOV
459
                        assert_not_reached();
×
460
                }
461

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

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

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

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

479
        return 1 /* work to do */;
480
}
481

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

487
        log_setup();
4✔
488

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

493
        exec_argv = strv_copy(argv + optind);
3✔
494
        if (!exec_argv)
3✔
495
                return log_oom();
×
496

497
        assert(!strv_isempty(exec_argv));
3✔
498

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

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

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

514
        for (;;) {
2✔
515
                struct epoll_event event;
2✔
516

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

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

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

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

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

537
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