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

systemd / systemd / 23825567702

31 Mar 2026 12:42PM UTC coverage: 72.404% (+0.006%) from 72.398%
23825567702

push

github

daandemeyer
terminal-util: fix boot hang from ANSI terminal size queries

Since v257, terminal_fix_size() is called during early boot via
console_setup() → reset_dev_console_fd() to query terminal dimensions
via ANSI escape sequences. This has caused intermittent boot hangs
where the system gets stuck with a blinking cursor and requires a
keypress to continue (see systemd/systemd#35499).

The function tries CSI 18 first, then falls back to DSR if that fails.
Previously, each method independently opened a non-blocking fd, disabled
echo/icanon, ran its query, restored termios, and closed its fd. This
created two problems:

1. Echo window between CSI 18 and DSR fallback: After CSI 18 times out
   and restores termios (re-enabling ECHO and ICANON), there is a brief
   window before DSR disables them again. If the terminal's CSI 18
   response arrives during this window, it is echoed back to the
   terminal — where the terminal interprets \e[8;rows;cols t as a
   "resize text area" command — and the response bytes land in the
   canonical line buffer as stale input that can confuse the DSR
   response parser.

2. Cursor left at bottom-right on DSR timeout: The DSR method worked by
   sending two DSR queries — one to save the cursor position, then
   moving the cursor to (32766,32766) and sending another to read the
   clamped position. If neither response was received (timeout), the
   cursor restore was skipped (conditional on saved_row > 0), leaving
   the cursor at the bottom-right corner of the terminal. The
   subsequent terminal_reset_ansi_seq() then moved it to the beginning
   of the last line via \e[1G, making boot output appear at the bottom
   of the screen — giving the appearance of a hang even when the system
   was still booting.

This commit fixes both issues:

- terminal_fix_size() now opens the non-blocking fd and configures
  termios once for both query methods, so echo stays disabled for the
  entire CSI 18 → DSR fallback sequence with no gap. tcflu... (continued)

22 of 57 new or added lines in 3 files covered. (38.6%)

834 existing lines in 52 files now uncovered.

318485 of 439872 relevant lines covered (72.4%)

1162379.76 hits per line

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

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

3
#include <fcntl.h>
4
#include <linux/sctp.h>
5
#include <mqueue.h>
6
#include <netinet/tcp.h>
7
#include <sys/stat.h>
8
#include <unistd.h>
9

10
#include "sd-bus.h"
11

12
#include "alloc-util.h"
13
#include "bpf-program.h"
14
#include "bus-common-errors.h"
15
#include "bus-error.h"
16
#include "copy.h"
17
#include "dbus-socket.h"
18
#include "dbus-unit.h"
19
#include "errno-list.h"
20
#include "errno-util.h"
21
#include "exit-status.h"
22
#include "extract-word.h"
23
#include "fd-util.h"
24
#include "fdset.h"
25
#include "format-util.h"
26
#include "fs-util.h"
27
#include "glyph-util.h"
28
#include "in-addr-util.h"
29
#include "io-util.h"
30
#include "ip-protocol-list.h"
31
#include "log.h"
32
#include "manager.h"
33
#include "mkdir-label.h"
34
#include "namespace-util.h"
35
#include "parse-util.h"
36
#include "path-util.h"
37
#include "pidfd-util.h"
38
#include "process-util.h"
39
#include "recurse-dir.h"
40
#include "selinux-util.h"
41
#include "serialize.h"
42
#include "service.h"
43
#include "set.h"
44
#include "siphash24.h"
45
#include "smack-util.h"
46
#include "socket.h"
47
#include "socket-netlink.h"
48
#include "special.h"
49
#include "string-table.h"
50
#include "string-util.h"
51
#include "strv.h"
52
#include "unit.h"
53
#include "unit-name.h"
54
#include "user-util.h"
55

56
typedef struct SocketPeer {
57
        unsigned n_ref;
58

59
        Socket *socket;
60
        union sockaddr_union peer;
61
        socklen_t peer_salen;
62
        struct ucred peer_cred;
63
} SocketPeer;
64

65
static const UnitActiveState state_translation_table[_SOCKET_STATE_MAX] = {
66
        [SOCKET_DEAD]             = UNIT_INACTIVE,
67
        [SOCKET_START_PRE]        = UNIT_ACTIVATING,
68
        [SOCKET_START_OPEN]       = UNIT_ACTIVATING,
69
        [SOCKET_START_CHOWN]      = UNIT_ACTIVATING,
70
        [SOCKET_START_POST]       = UNIT_ACTIVATING,
71
        [SOCKET_LISTENING]        = UNIT_ACTIVE,
72
        [SOCKET_DEFERRED]         = UNIT_ACTIVE,
73
        [SOCKET_RUNNING]          = UNIT_ACTIVE,
74
        [SOCKET_STOP_PRE]         = UNIT_DEACTIVATING,
75
        [SOCKET_STOP_PRE_SIGTERM] = UNIT_DEACTIVATING,
76
        [SOCKET_STOP_PRE_SIGKILL] = UNIT_DEACTIVATING,
77
        [SOCKET_STOP_POST]        = UNIT_DEACTIVATING,
78
        [SOCKET_FINAL_SIGTERM]    = UNIT_DEACTIVATING,
79
        [SOCKET_FINAL_SIGKILL]    = UNIT_DEACTIVATING,
80
        [SOCKET_FAILED]           = UNIT_FAILED,
81
        [SOCKET_CLEANING]         = UNIT_MAINTENANCE,
82
};
83

84
static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata);
85
static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
86

87
static bool SOCKET_STATE_WITH_PROCESS(SocketState state) {
15,169✔
88
        return IN_SET(state,
15,169✔
89
                      SOCKET_START_PRE,
90
                      SOCKET_START_CHOWN,
91
                      SOCKET_START_POST,
92
                      SOCKET_STOP_PRE,
93
                      SOCKET_STOP_PRE_SIGTERM,
94
                      SOCKET_STOP_PRE_SIGKILL,
95
                      SOCKET_STOP_POST,
96
                      SOCKET_FINAL_SIGTERM,
97
                      SOCKET_FINAL_SIGKILL,
98
                      SOCKET_CLEANING);
99
}
100

101
static bool SOCKET_SERVICE_IS_ACTIVE(Service *s, bool allow_finalize) {
5,442✔
102
        assert(s);
5,442✔
103

104
        /* If unit_active_state() reports inactive/failed then it's all good, otherwise we need to
105
         * manually exclude SERVICE_AUTO_RESTART and SERVICE_AUTO_RESTART_QUEUED, in which cases
106
         * the start job hasn't been enqueued/run, but are only placeholders in order to allow
107
         * canceling auto restart. */
108

109
        if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(UNIT(s))))
5,442✔
110
                return false;
111

112
        if (IN_SET(s->state, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED))
1,843✔
113
                return false;
114

115
        if (allow_finalize && IN_SET(s->state, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL, SERVICE_CLEANING))
1,834✔
116
                return false;
×
117

118
        return true;
119
}
120

121
static void socket_init(Unit *u) {
7,731✔
122
        Socket *s = ASSERT_PTR(SOCKET(u));
7,731✔
123

124
        assert(u->load_state == UNIT_STUB);
7,731✔
125

126
        s->backlog = SOMAXCONN_DELUXE;
7,731✔
127
        s->timeout_usec = u->manager->defaults.timeout_start_usec;
7,731✔
128
        s->directory_mode = 0755;
7,731✔
129
        s->socket_mode = 0666;
7,731✔
130

131
        s->max_connections = 64;
7,731✔
132

133
        s->pass_rights = true; /* defaults to enabled in kernel */
7,731✔
134
        s->priority = -1;
7,731✔
135
        s->ip_tos = -1;
7,731✔
136
        s->ip_ttl = -1;
7,731✔
137
        s->mark = -1;
7,731✔
138

139
        s->exec_context.std_output = u->manager->defaults.std_output;
7,731✔
140
        s->exec_context.std_error = u->manager->defaults.std_error;
7,731✔
141

142
        s->control_pid = PIDREF_NULL;
7,731✔
143
        s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
7,731✔
144

145
        s->trigger_limit = RATELIMIT_OFF;
7,731✔
146

147
        s->poll_limit = RATELIMIT_OFF;
7,731✔
148

149
        s->defer_trigger_max_usec = USEC_INFINITY;
7,731✔
150
}
7,731✔
151

152
static void socket_unwatch_control_pid(Socket *s) {
35,867✔
153
        assert(s);
35,867✔
154
        unit_unwatch_pidref_done(UNIT(s), &s->control_pid);
35,867✔
155
}
35,867✔
156

157
static void socket_port_close_auxiliary_fds(SocketPort *p) {
10,992✔
158
        assert(p);
10,992✔
159

160
        close_many(p->auxiliary_fds, p->n_auxiliary_fds);
10,992✔
161
        p->auxiliary_fds = mfree(p->auxiliary_fds);
10,992✔
162
        p->n_auxiliary_fds = 0;
10,992✔
163
}
10,992✔
164

165
SocketPort* socket_port_free(SocketPort *p) {
7,957✔
166
        if (!p)
7,957✔
167
                return NULL;
168

169
        sd_event_source_unref(p->event_source);
7,957✔
170

171
        socket_port_close_auxiliary_fds(p);
7,957✔
172
        safe_close(p->fd);
7,957✔
173
        free(p->path);
7,957✔
174

175
        return mfree(p);
7,957✔
176
}
177

178
void socket_free_ports(Socket *s) {
7,731✔
179
        assert(s);
7,731✔
180

181
        LIST_CLEAR(port, s->ports, socket_port_free);
15,687✔
182
}
7,731✔
183

184
static void socket_done(Unit *u) {
7,731✔
185
        Socket *s = ASSERT_PTR(SOCKET(u));
7,731✔
186
        SocketPeer *p;
7,731✔
187

188
        socket_free_ports(s);
7,731✔
189

190
        while ((p = set_steal_first(s->peers_by_address)))
7,731✔
191
                p->socket = NULL;
×
192

193
        s->peers_by_address = set_free(s->peers_by_address);
7,731✔
194

195
        s->exec_runtime = exec_runtime_free(s->exec_runtime);
7,731✔
196

197
        exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
7,731✔
198
        s->control_command = NULL;
7,731✔
199

200
        socket_unwatch_control_pid(s);
7,731✔
201

202
        unit_ref_unset(&s->service);
7,731✔
203

204
        s->tcp_congestion = mfree(s->tcp_congestion);
7,731✔
205
        s->bind_to_device = mfree(s->bind_to_device);
7,731✔
206

207
        s->smack = mfree(s->smack);
7,731✔
208
        s->smack_ip_in = mfree(s->smack_ip_in);
7,731✔
209
        s->smack_ip_out = mfree(s->smack_ip_out);
7,731✔
210

211
        strv_free(s->symlinks);
7,731✔
212

213
        s->user = mfree(s->user);
7,731✔
214
        s->group = mfree(s->group);
7,731✔
215

216
        s->fdname = mfree(s->fdname);
7,731✔
217

218
        s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
7,731✔
219
}
7,731✔
220

221
static int socket_arm_timer(Socket *s, bool relative, usec_t usec) {
235✔
222
        assert(s);
235✔
223

224
        return unit_arm_timer(UNIT(s), &s->timer_event_source, relative, usec, socket_dispatch_timer);
235✔
225
}
226

227
static bool have_non_accept_socket(Socket *s) {
9,695✔
228
        assert(s);
9,695✔
229

230
        if (!s->accept)
9,695✔
231
                return true;
232

233
        LIST_FOREACH(port, p, s->ports) {
7,876✔
234

235
                if (p->type != SOCKET_SOCKET)
3,938✔
236
                        return true;
237

238
                if (!socket_address_can_accept(&p->address))
3,938✔
239
                        return true;
240
        }
241

242
        return false;
243
}
244

245
static int socket_add_mount_dependencies(Socket *s) {
7,726✔
246
        int r;
7,726✔
247

248
        assert(s);
7,726✔
249

250
        LIST_FOREACH(port, p, s->ports) {
15,682✔
251
                const char *path = NULL;
7,956✔
252

253
                if (p->type == SOCKET_SOCKET)
7,956✔
254
                        path = socket_address_get_path(&p->address);
7,706✔
255
                else if (IN_SET(p->type, SOCKET_FIFO, SOCKET_SPECIAL, SOCKET_USB_FUNCTION))
250✔
256
                        path = p->path;
250✔
257

258
                if (!path)
7,956✔
259
                        continue;
369✔
260

261
                r = unit_add_mounts_for(UNIT(s), path, UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
7,587✔
262
                if (r < 0)
7,587✔
263
                        return r;
264
        }
265

266
        return 0;
267
}
268

269
static int socket_add_device_dependencies(Socket *s) {
7,726✔
270
        char *t;
7,726✔
271

272
        assert(s);
7,726✔
273

274
        if (!s->bind_to_device || streq(s->bind_to_device, "lo"))
7,726✔
275
                return 0;
276

277
        t = strjoina("/sys/subsystem/net/devices/", s->bind_to_device);
×
278
        return unit_add_node_dependency(UNIT(s), t, UNIT_BINDS_TO, UNIT_DEPENDENCY_FILE);
×
279
}
280

281
static int socket_add_default_dependencies(Socket *s) {
7,726✔
282
        int r;
7,726✔
283

284
        assert(s);
7,726✔
285

286
        if (!UNIT(s)->default_dependencies)
7,726✔
287
                return 0;
288

289
        r = unit_add_dependency_by_name(UNIT(s), UNIT_BEFORE, SPECIAL_SOCKETS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
3,897✔
290
        if (r < 0)
3,897✔
291
                return r;
292

293
        if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
3,897✔
294
                r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
1,221✔
295
                if (r < 0)
1,221✔
296
                        return r;
297
        }
298

299
        return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
3,897✔
300
}
301

302
static bool socket_has_exec(Socket *s) {
7,726✔
303
        assert(s);
7,726✔
304

305
        FOREACH_ARRAY(i, s->exec_command, _SOCKET_EXEC_COMMAND_MAX)
45,624✔
306
                if (*i)
38,142✔
307
                        return true;
308

309
        return false;
310
}
311

312
static int socket_add_extras(Socket *s) {
7,726✔
313
        Unit *u = UNIT(ASSERT_PTR(s));
7,726✔
314
        int r;
7,726✔
315

316
        /* Pick defaults for the trigger limit, if nothing was explicitly configured. We pick a relatively high limit
317
         * in Accept=yes mode, and a lower limit for Accept=no. Reason: in Accept=yes mode we are invoking accept()
318
         * ourselves before the trigger limit can hit, thus incoming connections are taken off the socket queue quickly
319
         * and reliably. This is different for Accept=no, where the spawned service has to take the incoming traffic
320
         * off the queues, which it might not necessarily do. Moreover, while Accept=no services are supposed to
321
         * process whatever is queued in one go, and thus should normally never have to be started frequently. This is
322
         * different for Accept=yes where each connection is processed by a new service instance, and thus frequent
323
         * service starts are typical.
324
         *
325
         * For the poll limit we follow a similar rule, but use 3/4th of the trigger limit parameters, to
326
         * trigger this earlier. */
327

328
        if (s->trigger_limit.interval == USEC_INFINITY)
7,726✔
329
                s->trigger_limit.interval = 2 * USEC_PER_SEC;
7,726✔
330
        if (s->trigger_limit.burst == UINT_MAX)
7,726✔
331
                s->trigger_limit.burst = s->accept ? 200 : 20;
13,483✔
332

333
        if (s->poll_limit.interval == USEC_INFINITY)
7,726✔
334
                s->poll_limit.interval = 2 * USEC_PER_SEC;
7,576✔
335
        if (s->poll_limit.burst == UINT_MAX)
7,726✔
336
                s->poll_limit.burst = s->accept ? 150 : 15;
13,333✔
337

338
        if (have_non_accept_socket(s)) {
7,726✔
339

340
                if (!UNIT_ISSET(s->service)) {
5,757✔
341
                        Unit *x;
3,406✔
342

343
                        r = unit_load_related_unit(u, ".service", &x);
3,406✔
344
                        if (r < 0)
3,406✔
345
                                return r;
×
346

347
                        unit_ref_set(&s->service, u, x);
3,406✔
348
                }
349

350
                r = unit_add_two_dependencies(u, UNIT_BEFORE, UNIT_TRIGGERS, UNIT_DEREF(s->service), true, UNIT_DEPENDENCY_IMPLICIT);
5,757✔
351
                if (r < 0)
5,757✔
352
                        return r;
353
        }
354

355
        r = socket_add_mount_dependencies(s);
7,726✔
356
        if (r < 0)
7,726✔
357
                return r;
358

359
        r = socket_add_device_dependencies(s);
7,726✔
360
        if (r < 0)
7,726✔
361
                return r;
362

363
        r = unit_patch_contexts(u);
7,726✔
364
        if (r < 0)
7,726✔
365
                return r;
366

367
        if (socket_has_exec(s)) {
7,726✔
368
                r = unit_add_exec_dependencies(u, &s->exec_context);
244✔
369
                if (r < 0)
244✔
370
                        return r;
371
        }
372

373
        r = unit_set_default_slice(u);
7,726✔
374
        if (r < 0)
7,726✔
375
                return r;
376

377
        r = socket_add_default_dependencies(s);
7,726✔
378
        if (r < 0)
7,726✔
379
                return r;
×
380

381
        return 0;
382
}
383

384
static const char* socket_find_symlink_target(Socket *s) {
7,013✔
385
        const char *found = NULL;
7,013✔
386

387
        assert(s);
7,013✔
388

389
        LIST_FOREACH(port, p, s->ports) {
14,026✔
390
                const char *f;
7,151✔
391

392
                switch (p->type) {
7,151✔
393

394
                case SOCKET_FIFO:
145✔
395
                        f = p->path;
145✔
396
                        break;
145✔
397

398
                case SOCKET_SOCKET:
7,006✔
399
                        f = socket_address_get_path(&p->address);
7,006✔
400
                        break;
7,006✔
401

402
                default:
403
                        f = NULL;
404
                }
405

406
                if (f) {
7,151✔
407
                        if (found)
7,080✔
408
                                return NULL;
409

410
                        found = f;
411
                }
412
        }
413

414
        return found;
415
}
416

417
static int socket_verify(Socket *s) {
7,726✔
418
        assert(s);
7,726✔
419
        assert(UNIT(s)->load_state == UNIT_LOADED);
7,726✔
420

421
        if (!s->ports)
7,726✔
422
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit has no Listen setting (ListenStream=, ListenDatagram=, ListenFIFO=, ...). Refusing.");
×
423

424
        if (s->max_connections <= 0)
7,726✔
425
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "MaxConnection= setting too small. Refusing.");
×
426

427
        if (s->accept && have_non_accept_socket(s))
7,726✔
428
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit configured for accepting sockets, but sockets are non-accepting. Refusing.");
×
429

430
        if (s->accept && UNIT_ISSET(s->service))
7,726✔
431
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Explicit service configuration for accepting socket units not supported. Refusing.");
×
432

433
        if (s->accept && s->defer_trigger != SOCKET_DEFER_NO)
7,726✔
434
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Socket unit is configured to be accepting with DeferTrigger= enabled. Refusing.");
×
435

436
        if (!strv_isempty(s->symlinks) && !socket_find_symlink_target(s))
11,117✔
437
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Unit has symlinks set but none or more than one node in the file system. Refusing.");
×
438

439
        return 0;
440
}
441

442
static void peer_address_hash_func(const SocketPeer *s, struct siphash *state) {
270✔
443
        assert(s);
270✔
444

445
        if (s->peer.sa.sa_family == AF_INET)
270✔
446
                siphash24_compress_typesafe(s->peer.in.sin_addr, state);
×
447
        else if (s->peer.sa.sa_family == AF_INET6)
270✔
448
                siphash24_compress_typesafe(s->peer.in6.sin6_addr, state);
×
449
        else if (s->peer.sa.sa_family == AF_VSOCK)
270✔
450
                siphash24_compress_typesafe(s->peer.vm.svm_cid, state);
×
451
        else if (s->peer.sa.sa_family == AF_UNIX)
270✔
452
                siphash24_compress_typesafe(s->peer_cred.uid, state);
270✔
453
        else
454
                assert_not_reached();
×
455
}
270✔
456

457
static int peer_address_compare_func(const SocketPeer *x, const SocketPeer *y) {
106✔
458
        int r;
106✔
459

460
        r = CMP(x->peer.sa.sa_family, y->peer.sa.sa_family);
106✔
461
        if (r != 0)
106✔
462
                return r;
×
463

464
        switch (x->peer.sa.sa_family) {
106✔
465
        case AF_INET:
×
466
                return memcmp(&x->peer.in.sin_addr, &y->peer.in.sin_addr, sizeof(x->peer.in.sin_addr));
×
467
        case AF_INET6:
×
468
                return memcmp(&x->peer.in6.sin6_addr, &y->peer.in6.sin6_addr, sizeof(x->peer.in6.sin6_addr));
×
469
        case AF_VSOCK:
×
470
                return CMP(x->peer.vm.svm_cid, y->peer.vm.svm_cid);
×
471
        case AF_UNIX:
106✔
472
                return CMP(x->peer_cred.uid, y->peer_cred.uid);
106✔
473
        }
474
        assert_not_reached();
×
475
}
476

477
DEFINE_PRIVATE_HASH_OPS(peer_address_hash_ops, SocketPeer, peer_address_hash_func, peer_address_compare_func);
478

479
static int socket_load(Unit *u) {
7,732✔
480
        Socket *s = ASSERT_PTR(SOCKET(u));
7,732✔
481
        int r;
7,732✔
482

483
        assert(u->load_state == UNIT_STUB);
7,732✔
484

485
        r = unit_load_fragment_and_dropin(u, true);
7,732✔
486
        if (r < 0)
7,732✔
487
                return r;
488

489
        if (u->load_state != UNIT_LOADED)
7,726✔
490
                return 0;
491

492
        /* This is a new unit? Then let's add in some extras */
493
        r = socket_add_extras(s);
7,726✔
494
        if (r < 0)
7,726✔
495
                return r;
496

497
        return socket_verify(s);
7,726✔
498
}
499

500
static SocketPeer* socket_peer_dup(const SocketPeer *q) {
88✔
501
        SocketPeer *p;
88✔
502

503
        assert(q);
88✔
504

505
        p = new(SocketPeer, 1);
88✔
506
        if (!p)
88✔
507
                return NULL;
508

509
        *p = (SocketPeer) {
88✔
510
                .n_ref = 1,
511
                .peer = q->peer,
88✔
512
                .peer_salen = q->peer_salen,
88✔
513
                .peer_cred = q->peer_cred,
88✔
514
        };
515

516
        return p;
88✔
517
}
518

519
static SocketPeer* socket_peer_free(SocketPeer *p) {
88✔
520
        assert(p);
88✔
521

522
        if (p->socket)
88✔
523
                set_remove(p->socket->peers_by_address, p);
88✔
524

525
        return mfree(p);
88✔
526
}
527

528
DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer, socket_peer, socket_peer_free);
127✔
529

530
int socket_acquire_peer(Socket *s, int fd, SocketPeer **ret) {
106✔
531
        _cleanup_(socket_peer_unrefp) SocketPeer *remote = NULL;
106✔
532
        SocketPeer key = {
106✔
533
                .peer_salen = sizeof(union sockaddr_union),
534
                .peer_cred = UCRED_INVALID,
535
        }, *i;
536
        int r;
106✔
537

538
        assert(s);
106✔
539
        assert(fd >= 0);
106✔
540
        assert(ret);
106✔
541

542
        if (getpeername(fd, &key.peer.sa, &key.peer_salen) < 0)
106✔
543
                return log_unit_error_errno(UNIT(s), errno, "getpeername() failed: %m");
×
544

545
        switch (key.peer.sa.sa_family) {
106✔
546
        case AF_INET:
547
        case AF_INET6:
548
        case AF_VSOCK:
549
                break;
550

551
        case AF_UNIX:
106✔
552
                r = getpeercred(fd, &key.peer_cred);
106✔
553
                if (r < 0)
106✔
554
                        return log_unit_error_errno(UNIT(s), r, "Failed to get peer credentials of socket: %m");
×
555
                break;
556

557
        default:
×
558
                *ret = NULL;
×
559
                return 0;
×
560
        }
561

562
        i = set_get(s->peers_by_address, &key);
106✔
563
        if (i) {
106✔
564
                *ret = socket_peer_ref(i);
18✔
565
                return 1;
18✔
566
        }
567

568
        remote = socket_peer_dup(&key);
88✔
569
        if (!remote)
88✔
570
                return log_oom();
×
571

572
        r = set_ensure_put(&s->peers_by_address, &peer_address_hash_ops, remote);
88✔
573
        if (r < 0)
88✔
574
                return log_unit_error_errno(UNIT(s), r, "Failed to insert peer info into hash table: %m");
×
575

576
        remote->socket = s;
88✔
577

578
        *ret = TAKE_PTR(remote);
88✔
579
        return 1;
88✔
580
}
581

582
static const char* listen_lookup(int family, int type) {
44✔
583

584
        if (family == AF_NETLINK)
44✔
585
                return "ListenNetlink";
586

587
        if (type == SOCK_STREAM)
41✔
588
                return "ListenStream";
589
        else if (type == SOCK_DGRAM)
5✔
590
                return "ListenDatagram";
591
        else if (type == SOCK_SEQPACKET)
2✔
592
                return "ListenSequentialPacket";
593

594
        assert_not_reached();
×
595
}
596

597
static void socket_dump(Unit *u, FILE *f, const char *prefix) {
44✔
598
        Socket *s = ASSERT_PTR(SOCKET(u));
44✔
599
        const char *prefix2, *str;
44✔
600

601
        assert(f);
44✔
602

603
        prefix = strempty(prefix);
44✔
604
        prefix2 = strjoina(prefix, "\t");
220✔
605

606
        fprintf(f,
88✔
607
                "%sSocket State: %s\n"
608
                "%sResult: %s\n"
609
                "%sClean Result: %s\n"
610
                "%sBindIPv6Only: %s\n"
611
                "%sBacklog: %u\n"
612
                "%sSocketMode: %04o\n"
613
                "%sDirectoryMode: %04o\n"
614
                "%sKeepAlive: %s\n"
615
                "%sNoDelay: %s\n"
616
                "%sFreeBind: %s\n"
617
                "%sTransparent: %s\n"
618
                "%sBroadcast: %s\n"
619
                "%sPassCredentials: %s\n"
620
                "%sPassPIDFD: %s\n"
621
                "%sPassSecurity: %s\n"
622
                "%sPassPacketInfo: %s\n"
623
                "%sAcceptFileDescriptors: %s\n"
624
                "%sTCPCongestion: %s\n"
625
                "%sRemoveOnStop: %s\n"
626
                "%sWritable: %s\n"
627
                "%sFileDescriptorName: %s\n"
628
                "%sPassFileDescriptorsToExec: %s\n"
629
                "%sSELinuxContextFromNet: %s\n",
630
                prefix, socket_state_to_string(s->state),
631
                prefix, socket_result_to_string(s->result),
632
                prefix, socket_result_to_string(s->clean_result),
633
                prefix, socket_address_bind_ipv6_only_to_string(s->bind_ipv6_only),
634
                prefix, s->backlog,
635
                prefix, s->socket_mode,
636
                prefix, s->directory_mode,
637
                prefix, yes_no(s->keep_alive),
44✔
638
                prefix, yes_no(s->no_delay),
44✔
639
                prefix, yes_no(s->free_bind),
44✔
640
                prefix, yes_no(s->transparent),
44✔
641
                prefix, yes_no(s->broadcast),
44✔
642
                prefix, yes_no(s->pass_cred),
44✔
643
                prefix, yes_no(s->pass_pidfd),
44✔
644
                prefix, yes_no(s->pass_sec),
44✔
645
                prefix, yes_no(s->pass_pktinfo),
44✔
646
                prefix, yes_no(s->pass_rights),
44✔
647
                prefix, strna(s->tcp_congestion),
44✔
648
                prefix, yes_no(s->remove_on_stop),
44✔
649
                prefix, yes_no(s->writable),
44✔
650
                prefix, socket_fdname(s),
651
                prefix, yes_no(s->pass_fds_to_exec),
44✔
652
                prefix, yes_no(s->selinux_context_from_net));
44✔
653

654
        if (s->timestamping != SOCKET_TIMESTAMPING_OFF)
44✔
655
                fprintf(f,
2✔
656
                        "%sTimestamping: %s\n",
657
                        prefix, socket_timestamping_to_string(s->timestamping));
658

659
        if (pidref_is_set(&s->control_pid))
660
                fprintf(f,
×
661
                        "%sControl PID: "PID_FMT"\n",
662
                        prefix, s->control_pid.pid);
663

664
        if (s->bind_to_device)
44✔
665
                fprintf(f,
×
666
                        "%sBindToDevice: %s\n",
667
                        prefix, s->bind_to_device);
668

669
        if (s->accept)
44✔
670
                fprintf(f,
14✔
671
                        "%sAccepted: %u\n"
672
                        "%sNConnections: %u\n"
673
                        "%sMaxConnections: %u\n"
674
                        "%sMaxConnectionsPerSource: %u\n",
675
                        prefix, s->n_accepted,
676
                        prefix, s->n_connections,
677
                        prefix, s->max_connections,
678
                        prefix, s->max_connections_per_source);
679
        else
680
                fprintf(f,
60✔
681
                        "%sFlushPending: %s\n"
682
                        "%sDeferTrigger: %s\n"
683
                        "%sDeferTriggerMaxSec: %s\n",
684
                        prefix, yes_no(s->flush_pending),
30✔
685
                        prefix, socket_defer_trigger_to_string(s->defer_trigger),
686
                        prefix, FORMAT_TIMESPAN(s->defer_trigger_max_usec, USEC_PER_SEC));
30✔
687

688
        if (s->priority >= 0)
44✔
689
                fprintf(f,
×
690
                        "%sPriority: %i\n",
691
                        prefix, s->priority);
692

693
        if (s->receive_buffer > 0)
44✔
694
                fprintf(f,
6✔
695
                        "%sReceiveBuffer: %zu\n",
696
                        prefix, s->receive_buffer);
697

698
        if (s->send_buffer > 0)
44✔
699
                fprintf(f,
1✔
700
                        "%sSendBuffer: %zu\n",
701
                        prefix, s->send_buffer);
702

703
        if (s->ip_tos >= 0)
44✔
704
                fprintf(f,
×
705
                        "%sIPTOS: %i\n",
706
                        prefix, s->ip_tos);
707

708
        if (s->ip_ttl >= 0)
44✔
709
                fprintf(f,
×
710
                        "%sIPTTL: %i\n",
711
                        prefix, s->ip_ttl);
712

713
        if (s->pipe_size > 0)
44✔
714
                fprintf(f,
×
715
                        "%sPipeSize: %zu\n",
716
                        prefix, s->pipe_size);
717

718
        if (s->mark >= 0)
44✔
719
                fprintf(f,
×
720
                        "%sMark: %i\n",
721
                        prefix, s->mark);
722

723
        if (s->mq_maxmsg > 0)
44✔
724
                fprintf(f,
×
725
                        "%sMessageQueueMaxMessages: %li\n",
726
                        prefix, s->mq_maxmsg);
727

728
        if (s->mq_msgsize > 0)
44✔
729
                fprintf(f,
×
730
                        "%sMessageQueueMessageSize: %li\n",
731
                        prefix, s->mq_msgsize);
732

733
        if (s->reuse_port)
44✔
734
                fprintf(f,
×
735
                        "%sReusePort: %s\n",
736
                         prefix, yes_no(s->reuse_port));
737

738
        if (s->smack)
44✔
739
                fprintf(f,
×
740
                        "%sSmackLabel: %s\n",
741
                        prefix, s->smack);
742

743
        if (s->smack_ip_in)
44✔
744
                fprintf(f,
×
745
                        "%sSmackLabelIPIn: %s\n",
746
                        prefix, s->smack_ip_in);
747

748
        if (s->smack_ip_out)
44✔
749
                fprintf(f,
×
750
                        "%sSmackLabelIPOut: %s\n",
751
                        prefix, s->smack_ip_out);
752

753
        if (!isempty(s->user) || !isempty(s->group))
44✔
754
                fprintf(f,
1✔
755
                        "%sSocketUser: %s\n"
756
                        "%sSocketGroup: %s\n",
757
                        prefix, strna(s->user),
1✔
758
                        prefix, strna(s->group));
1✔
759

760
        if (timestamp_is_set(s->keep_alive_time))
44✔
761
                fprintf(f,
×
762
                        "%sKeepAliveTimeSec: %s\n",
763
                        prefix, FORMAT_TIMESPAN(s->keep_alive_time, USEC_PER_SEC));
×
764

765
        if (s->keep_alive_interval > 0)
44✔
766
                fprintf(f,
×
767
                        "%sKeepAliveIntervalSec: %s\n",
768
                        prefix, FORMAT_TIMESPAN(s->keep_alive_interval, USEC_PER_SEC));
×
769

770
        if (s->keep_alive_cnt > 0)
44✔
771
                fprintf(f,
×
772
                        "%sKeepAliveProbes: %u\n",
773
                        prefix, s->keep_alive_cnt);
774

775
        if (s->defer_accept > 0)
44✔
776
                fprintf(f,
×
777
                        "%sDeferAcceptSec: %s\n",
778
                        prefix, FORMAT_TIMESPAN(s->defer_accept, USEC_PER_SEC));
×
779

780
        LIST_FOREACH(port, p, s->ports) {
90✔
781

782
                switch (p->type) {
46✔
783
                case SOCKET_SOCKET: {
44✔
784
                        _cleanup_free_ char *k = NULL;
44✔
785
                        int r;
44✔
786

787
                        r = socket_address_print(&p->address, &k);
44✔
788
                        if (r < 0) {
44✔
789
                                errno = -r;
×
790
                                fprintf(f, "%s%s: %m\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type));
×
791
                        } else
792
                                fprintf(f, "%s%s: %s\n", prefix, listen_lookup(socket_address_family(&p->address), p->address.type), k);
44✔
793
                        break;
44✔
794
                }
795
                case SOCKET_SPECIAL:
×
796
                        fprintf(f, "%sListenSpecial: %s\n", prefix, p->path);
×
797
                        break;
798
                case SOCKET_USB_FUNCTION:
×
799
                        fprintf(f, "%sListenUSBFunction: %s\n", prefix, p->path);
×
800
                        break;
801
                case SOCKET_MQUEUE:
×
802
                        fprintf(f, "%sListenMessageQueue: %s\n", prefix, p->path);
×
803
                        break;
804
                default:
2✔
805
                        fprintf(f, "%sListenFIFO: %s\n", prefix, p->path);
2✔
806
                }
807
        }
808

809
        fprintf(f,
44✔
810
                "%sTriggerLimitIntervalSec: %s\n"
811
                "%sTriggerLimitBurst: %u\n"
812
                "%sPollLimitIntervalSec: %s\n"
813
                "%sPollLimitBurst: %u\n",
814
                prefix, FORMAT_TIMESPAN(s->trigger_limit.interval, USEC_PER_SEC),
44✔
815
                prefix, s->trigger_limit.burst,
816
                prefix, FORMAT_TIMESPAN(s->poll_limit.interval, USEC_PER_SEC),
44✔
817
                prefix, s->poll_limit.burst);
818

819
        str = ip_protocol_to_name(s->socket_protocol);
44✔
820
        if (str)
44✔
821
                fprintf(f, "%sSocketProtocol: %s\n", prefix, str);
44✔
822

823
        if (!strv_isempty(s->symlinks)) {
44✔
824
                fprintf(f, "%sSymlinks:", prefix);
22✔
825
                STRV_FOREACH(q, s->symlinks)
49✔
826
                        fprintf(f, " %s", *q);
27✔
827

828
                fprintf(f, "\n");
22✔
829
        }
830

831
        fprintf(f,
44✔
832
                "%sTimeoutSec: %s\n",
833
                prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC));
44✔
834

835
        exec_context_dump(&s->exec_context, f, prefix);
44✔
836
        kill_context_dump(&s->kill_context, f, prefix);
44✔
837

838
        for (SocketExecCommand c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
264✔
839
                if (!s->exec_command[c])
220✔
840
                        continue;
220✔
841

842
                fprintf(f, "%s%s %s:\n",
×
843
                        prefix, glyph(GLYPH_ARROW_RIGHT), socket_exec_command_to_string(c));
844

845
                exec_command_dump_list(s->exec_command[c], f, prefix2);
×
846
        }
847

848
        cgroup_context_dump(UNIT(s), f, prefix);
44✔
849
}
44✔
850

851
static int instance_from_socket(
109✔
852
                int fd,
853
                unsigned nr,
854
                char **ret) {
855

856
        union sockaddr_union local, remote;
109✔
857
        socklen_t l;
109✔
858
        int r;
109✔
859

860
        assert(fd >= 0);
109✔
861
        assert(ret);
109✔
862

863
        l = sizeof(local);
109✔
864
        if (getsockname(fd, &local.sa, &l) < 0)
109✔
865
                return -errno;
109✔
866

867
        l = sizeof(remote);
109✔
868
        if (getpeername(fd, &remote.sa, &l) < 0)
109✔
869
                return -errno;
×
870

871
        uint64_t cookie;
109✔
872
        r = socket_get_cookie(fd, &cookie);
109✔
873
        if (r < 0)
109✔
874
                return r;
875

876
        char *s;
109✔
877

878
        switch (local.sa.sa_family) {
109✔
879

880
        case AF_INET: {
×
881
                uint32_t
×
882
                        a = be32toh(local.in.sin_addr.s_addr),
×
883
                        b = be32toh(remote.in.sin_addr.s_addr);
×
884

885
                s = asprintf_safe(
×
886
                                "%u-%" PRIu64 "-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
887
                                nr,
888
                                cookie,
889
                                a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
890
                                be16toh(local.in.sin_port),
×
891
                                b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
892
                                be16toh(remote.in.sin_port));
×
893
                break;
894
        }
895

896
        case AF_INET6: {
×
897
                static const unsigned char ipv4_prefix[] = {
×
898
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
899
                };
900

901
                if (memcmp(&local.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0 &&
×
902
                    memcmp(&remote.in6.sin6_addr, ipv4_prefix, sizeof(ipv4_prefix)) == 0) {
×
903
                        const uint8_t
×
904
                                *a = local.in6.sin6_addr.s6_addr+12,
×
905
                                *b = remote.in6.sin6_addr.s6_addr+12;
×
906

907
                        s = asprintf_safe(
×
908
                                        "%u-%" PRIu64 "-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
909
                                        nr,
910
                                        cookie,
911
                                        a[0], a[1], a[2], a[3],
×
912
                                        be16toh(local.in6.sin6_port),
×
913
                                        b[0], b[1], b[2], b[3],
×
914
                                        be16toh(remote.in6.sin6_port));
×
915
                } else
916
                        s = asprintf_safe(
×
917
                                        "%u-%" PRIu64 "-%s:%u-%s:%u",
918
                                        nr,
919
                                        cookie,
920
                                        IN6_ADDR_TO_STRING(&local.in6.sin6_addr),
×
921
                                        be16toh(local.in6.sin6_port),
×
922
                                        IN6_ADDR_TO_STRING(&remote.in6.sin6_addr),
×
923
                                        be16toh(remote.in6.sin6_port));
×
924
                break;
925
        }
926

927
        case AF_UNIX: {
109✔
928
                struct ucred ucred;
109✔
929

930
                r = getpeercred(fd, &ucred);
109✔
931
                if (r >= 0) {
109✔
932
                        _cleanup_close_ int pidfd = getpeerpidfd(fd);
218✔
933
                        uint64_t pidfd_id;
109✔
934

935
                        if (pidfd >= 0 && pidfd_get_inode_id(pidfd, &pidfd_id) >= 0)
109✔
936
                                s = asprintf_safe(
109✔
937
                                                "%u-%" PRIu64 "-" PID_FMT "_%" PRIu64 "-" UID_FMT,
938
                                                nr, cookie, ucred.pid, pidfd_id, ucred.uid);
939
                        else
940
                                s = asprintf_safe(
×
941
                                                "%u-%" PRIu64 "-" PID_FMT "-" UID_FMT,
942
                                                nr, cookie, ucred.pid, ucred.uid);
943
                } else if (r == -ENODATA)
×
944
                        /* This handles the case where somebody is connecting from another pid/uid namespace
945
                         * (e.g. from outside of our container). */
946
                        s = asprintf_safe("%u-%" PRIu64 "-unknown", nr, cookie);
×
947
                else
948
                        return r;
×
949
                break;
109✔
950
        }
951

952
        case AF_VSOCK:
×
953
                s = asprintf_safe(
×
954
                                "%u-%" PRIu64 "-%u:%u-%u:%u",
955
                                nr,
956
                                cookie,
957
                                local.vm.svm_cid, local.vm.svm_port,
958
                                remote.vm.svm_cid, remote.vm.svm_port);
959
                break;
960

961
        default:
×
962
                assert_not_reached();
×
963
        }
964

965
        if (!s)
109✔
966
                return -ENOMEM;
967

968
        *ret = s;
109✔
969
        return 0;
109✔
970
}
971

972
static void socket_close_fds(Socket *s) {
3,024✔
973
        assert(s);
3,024✔
974

975
        LIST_FOREACH(port, p, s->ports) {
6,059✔
976
                bool was_open = p->fd >= 0;
3,035✔
977

978
                p->event_source = sd_event_source_disable_unref(p->event_source);
3,035✔
979
                p->fd = safe_close(p->fd);
3,035✔
980
                socket_port_close_auxiliary_fds(p);
3,035✔
981

982
                /* One little note: we should normally not delete any sockets in the file system here! After all some
983
                 * other process we spawned might still have a reference of this fd and wants to continue to use
984
                 * it. Therefore we normally delete sockets in the file system before we create a new one, not after we
985
                 * stopped using one! That all said, if the user explicitly requested this, we'll delete them here
986
                 * anyway, but only then. */
987

988
                if (!was_open || !s->remove_on_stop)
3,035✔
989
                        continue;
2,746✔
990

991
                switch (p->type) {
289✔
992

993
                case SOCKET_FIFO:
22✔
994
                        (void) unlink(p->path);
22✔
995
                        break;
22✔
996

997
                case SOCKET_MQUEUE:
×
998
                        (void) mq_unlink(p->path);
×
999
                        break;
×
1000

1001
                case SOCKET_SOCKET:
267✔
1002
                        (void) socket_address_unlink(&p->address);
267✔
1003
                        break;
267✔
1004

1005
                default:
1006
                        ;
1007
                }
1008
        }
1009

1010
        if (s->remove_on_stop)
3,024✔
1011
                STRV_FOREACH(i, s->symlinks)
293✔
1012
                        (void) unlink(*i);
15✔
1013

1014
        /* Note that we don't return NULL here, since s has not been freed. */
1015
}
3,024✔
1016

1017
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket*, socket_close_fds, NULL);
×
1018

1019
#define log_socket_option_errno(s, e, option)                                          \
1020
        ({                                                                             \
1021
                int _e_ = (e);                                                         \
1022
                log_unit_full_errno(                                                   \
1023
                                UNIT(s),                                               \
1024
                                ERRNO_IS_NOT_SUPPORTED(_e_) ||                         \
1025
                                ERRNO_IS_PRIVILEGE(_e_) ? LOG_DEBUG : LOG_WARNING,     \
1026
                                _e_,                                                   \
1027
                                "Failed to set %s socket option, ignoring: %m",        \
1028
                                option);                                               \
1029
        })
1030

1031
static void socket_apply_socket_options(Socket *s, SocketPort *p, int fd) {
3,658✔
1032
        int r;
3,658✔
1033

1034
        assert(s);
3,658✔
1035
        assert(p);
3,658✔
1036
        assert(fd >= 0);
3,658✔
1037

1038
        if (s->keep_alive) {
3,658✔
1039
                r = setsockopt_int(fd, SOL_SOCKET, SO_KEEPALIVE, true);
×
1040
                if (r < 0)
×
1041
                        log_socket_option_errno(s, r, "SO_KEEPALIVE");
×
1042
        }
1043

1044
        if (timestamp_is_set(s->keep_alive_time)) {
3,658✔
1045
                r = setsockopt_int(fd, SOL_TCP, TCP_KEEPIDLE, s->keep_alive_time / USEC_PER_SEC);
×
1046
                if (r < 0)
×
1047
                        log_socket_option_errno(s, r, "TCP_KEEPIDLE");
×
1048
        }
1049

1050
        if (s->keep_alive_interval > 0) {
3,658✔
1051
                r = setsockopt_int(fd, SOL_TCP, TCP_KEEPINTVL, s->keep_alive_interval / USEC_PER_SEC);
×
1052
                if (r < 0)
×
1053
                        log_socket_option_errno(s, r, "TCP_KEEPINTVL");
×
1054
        }
1055

1056
        if (s->keep_alive_cnt > 0) {
3,658✔
1057
                r = setsockopt_int(fd, SOL_TCP, TCP_KEEPCNT, s->keep_alive_cnt);
×
1058
                if (r < 0)
×
1059
                        log_socket_option_errno(s, r, "TCP_KEEPCNT");
×
1060
        }
1061

1062
        if (s->defer_accept > 0) {
3,658✔
1063
                r = setsockopt_int(fd, SOL_TCP, TCP_DEFER_ACCEPT, s->defer_accept / USEC_PER_SEC);
×
1064
                if (r < 0)
×
1065
                        log_socket_option_errno(s, r, "TCP_DEFER_ACCEPT");
×
1066
        }
1067

1068
        if (s->no_delay) {
3,658✔
1069
                if (s->socket_protocol == IPPROTO_SCTP) {
×
1070
                        r = setsockopt_int(fd, SOL_SCTP, SCTP_NODELAY, true);
×
1071
                        if (r < 0)
×
1072
                                log_socket_option_errno(s, r, "SCTP_NODELAY");
×
1073
                } else {
1074
                        r = setsockopt_int(fd, SOL_TCP, TCP_NODELAY, true);
×
1075
                        if (r < 0)
×
1076
                                log_socket_option_errno(s, r, "TCP_NODELAY");
×
1077
                }
1078
        }
1079

1080
        if (s->broadcast) {
3,658✔
1081
                r = setsockopt_int(fd, SOL_SOCKET, SO_BROADCAST, true);
×
1082
                if (r < 0)
×
1083
                        log_socket_option_errno(s, r, "SO_BROADCAST");
×
1084
        }
1085

1086
        if (s->pass_cred) {
3,658✔
1087
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
144✔
1088
                if (r < 0)
144✔
1089
                        log_socket_option_errno(s, r, "SO_PASSCRED");
×
1090
        }
1091

1092
        if (s->pass_pidfd) {
3,658✔
1093
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSPIDFD, true);
×
1094
                if (r < 0)
×
1095
                        log_socket_option_errno(s, r, "SO_PASSPIDFD");
×
1096
        }
1097

1098
        if (s->pass_sec) {
3,658✔
1099
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSSEC, true);
99✔
1100
                if (r < 0)
99✔
1101
                        log_socket_option_errno(s, r, "SO_PASSSEC");
×
1102
        }
1103

1104
        if (s->pass_pktinfo) {
3,658✔
1105
                r = socket_set_recvpktinfo(fd, socket_address_family(&p->address), true);
36✔
1106
                if (r < 0)
36✔
1107
                        log_socket_option_errno(s, r, "packet info");
×
1108
        }
1109

1110
        if (!s->pass_rights) {
3,658✔
1111
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSRIGHTS, false);
×
1112
                if (r < 0)
×
1113
                        log_socket_option_errno(s, r, "SO_PASSRIGHTS");
×
1114
        }
1115

1116
        if (s->timestamping != SOCKET_TIMESTAMPING_OFF) {
3,658✔
1117
                r = setsockopt_int(fd, SOL_SOCKET,
198✔
1118
                                   s->timestamping == SOCKET_TIMESTAMPING_NS ? SO_TIMESTAMPNS : SO_TIMESTAMP,
1119
                                   true);
1120
                if (r < 0)
99✔
1121
                        log_socket_option_errno(s, r, "timestamping");
×
1122
        }
1123

1124
        if (s->priority >= 0) {
3,658✔
1125
                r = setsockopt_int(fd, SOL_SOCKET, SO_PRIORITY, s->priority);
190✔
1126
                if (r < 0)
190✔
1127
                        log_socket_option_errno(s, r, "SO_PRIORITY");
×
1128
        }
1129

1130
        if (s->receive_buffer > 0) {
3,658✔
1131
                r = fd_set_rcvbuf(fd, s->receive_buffer, false);
163✔
1132
                if (r < 0)
163✔
1133
                        log_socket_option_errno(s, r, "SO_RCVBUF/SO_RCVBUFFORCE");
×
1134
        }
1135

1136
        if (s->send_buffer > 0) {
3,658✔
1137
                r = fd_set_sndbuf(fd, s->send_buffer, false);
33✔
1138
                if (r < 0)
33✔
1139
                        log_socket_option_errno(s, r, "SO_SNDBUF/SO_SNDBUFFORCE");
×
1140
        }
1141

1142
        if (s->mark >= 0) {
3,658✔
1143
                r = setsockopt_int(fd, SOL_SOCKET, SO_MARK, s->mark);
×
1144
                if (r < 0)
×
1145
                        log_socket_option_errno(s, r, "SO_MARK");
×
1146
        }
1147

1148
        if (s->ip_tos >= 0) {
3,658✔
1149
                r = setsockopt_int(fd, IPPROTO_IP, IP_TOS, s->ip_tos);
×
1150
                if (r < 0)
×
1151
                        log_socket_option_errno(s, r, "IP_TOS");
×
1152
        }
1153

1154
        if (s->ip_ttl >= 0) {
3,658✔
1155
                r = socket_set_ttl(fd, socket_address_family(&p->address), s->ip_ttl);
×
1156
                if (r < 0)
×
1157
                        log_socket_option_errno(s, r, "IP_TTL/IPV6_UNICAST_HOPS");
×
1158
        }
1159

1160
        if (s->tcp_congestion)
3,658✔
1161
                if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
×
1162
                        log_socket_option_errno(s, errno, "TCP_CONGESTION");
×
1163

1164
        if (s->smack_ip_in) {
3,658✔
1165
                r = mac_smack_apply_fd(fd, SMACK_ATTR_IPIN, s->smack_ip_in);
×
1166
                if (r < 0)
×
1167
                        log_unit_warning_errno(UNIT(s), r, "Failed to apply SMACK label for IP input, ignoring: %m");
×
1168
        }
1169

1170
        if (s->smack_ip_out) {
3,658✔
1171
                r = mac_smack_apply_fd(fd, SMACK_ATTR_IPOUT, s->smack_ip_out);
×
1172
                if (r < 0)
×
1173
                        log_unit_warning_errno(UNIT(s), r, "Failed to apply SMACK label for IP output, ignoring: %m");
×
1174
        }
1175
}
3,658✔
1176

1177
static void socket_apply_fifo_options(Socket *s, int fd) {
73✔
1178
        int r;
73✔
1179

1180
        assert(s);
73✔
1181
        assert(fd >= 0);
73✔
1182

1183
        if (s->pipe_size > 0)
73✔
1184
                if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
×
1185
                        log_unit_warning_errno(UNIT(s), errno, "Setting pipe size failed, ignoring: %m");
×
1186

1187
        if (s->smack) {
73✔
1188
                r = mac_smack_apply_fd(fd, SMACK_ATTR_ACCESS, s->smack);
×
1189
                if (r < 0)
×
1190
                        log_unit_error_errno(UNIT(s), r, "SMACK relabelling failed, ignoring: %m");
×
1191
        }
1192
}
73✔
1193

1194
static int fifo_address_create(
73✔
1195
                const char *path,
1196
                mode_t directory_mode,
1197
                mode_t socket_mode) {
1198

1199
        _cleanup_close_ int fd = -EBADF;
73✔
1200
        mode_t old_mask;
73✔
1201
        struct stat st;
73✔
1202
        int r;
73✔
1203

1204
        assert(path);
73✔
1205

1206
        (void) mkdir_parents_label(path, directory_mode);
73✔
1207

1208
        r = mac_selinux_create_file_prepare(path, S_IFIFO);
73✔
1209
        if (r < 0)
73✔
1210
                return r;
1211

1212
        /* Enforce the right access mode for the fifo */
1213
        old_mask = umask(~socket_mode);
73✔
1214

1215
        /* Include the original umask in our mask */
1216
        (void) umask(~socket_mode | old_mask);
73✔
1217

1218
        r = mkfifo(path, socket_mode);
73✔
1219
        (void) umask(old_mask);
73✔
1220

1221
        if (r < 0 && errno != EEXIST) {
73✔
1222
                r = -errno;
×
1223
                goto fail;
×
1224
        }
1225

1226
        fd = open(path, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW);
73✔
1227
        if (fd < 0) {
73✔
1228
                r = -errno;
×
1229
                goto fail;
×
1230
        }
1231

1232
        mac_selinux_create_file_clear();
73✔
1233

1234
        if (fstat(fd, &st) < 0) {
73✔
1235
                r = -errno;
×
1236
                goto fail;
×
1237
        }
1238

1239
        if (!S_ISFIFO(st.st_mode) ||
73✔
1240
            (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
146✔
1241
            st.st_uid != getuid() ||
146✔
1242
            st.st_gid != getgid()) {
73✔
1243
                r = -EEXIST;
×
1244
                goto fail;
×
1245
        }
1246

1247
        return TAKE_FD(fd);
1248

1249
fail:
×
1250
        mac_selinux_create_file_clear();
×
1251
        return r;
1252
}
1253

1254
static int special_address_create(const char *path, bool writable) {
6✔
1255
        _cleanup_close_ int fd = -EBADF;
6✔
1256
        struct stat st;
6✔
1257

1258
        assert(path);
6✔
1259

1260
        fd = open(path, (writable ? O_RDWR : O_RDONLY)|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
6✔
1261
        if (fd < 0)
6✔
1262
                return -errno;
×
1263

1264
        if (fstat(fd, &st) < 0)
6✔
1265
                return -errno;
×
1266

1267
        /* Check whether this is a /proc, /sys or /dev file or char device */
1268
        if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode))
6✔
1269
                return -EEXIST;
×
1270

1271
        return TAKE_FD(fd);
1272
}
1273

1274
static int usbffs_address_create_at(int dfd, const char *name) {
×
1275
        _cleanup_close_ int fd = -EBADF;
×
1276
        struct stat st;
×
1277

1278
        assert(dfd >= 0);
×
1279
        assert(name);
×
1280

1281
        fd = openat(dfd, name, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
×
1282
        if (fd < 0)
×
1283
                return -errno;
×
1284

1285
        if (fstat(fd, &st) < 0)
×
1286
                return -errno;
×
1287

1288
        /* Check whether this is a regular file (ffs endpoint) */
1289
        if (!S_ISREG(st.st_mode))
×
1290
                return -EEXIST;
×
1291

1292
        return TAKE_FD(fd);
1293
}
1294

1295
static int mq_address_create(
×
1296
                const char *path,
1297
                mode_t mq_mode,
1298
                long maxmsg,
1299
                long msgsize) {
1300

1301
        _cleanup_close_ int fd = -EBADF;
×
1302
        struct stat st;
×
1303
        mode_t old_mask;
×
1304
        struct mq_attr _attr, *attr = NULL;
×
1305

1306
        assert(path);
×
1307

1308
        if (maxmsg > 0 && msgsize > 0) {
×
1309
                _attr = (struct mq_attr) {
×
1310
                        .mq_flags = O_NONBLOCK,
1311
                        .mq_maxmsg = maxmsg,
1312
                        .mq_msgsize = msgsize,
1313
                };
1314
                attr = &_attr;
×
1315
        }
1316

1317
        /* Enforce the right access mode for the mq */
1318
        old_mask = umask(~mq_mode);
×
1319

1320
        /* Include the original umask in our mask */
1321
        (void) umask(~mq_mode | old_mask);
×
1322
        fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
×
1323
        (void) umask(old_mask);
×
1324

1325
        if (fd < 0)
×
1326
                return -errno;
×
1327

1328
        if (fstat(fd, &st) < 0)
×
1329
                return -errno;
×
1330

1331
        if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
×
1332
            st.st_uid != getuid() ||
×
1333
            st.st_gid != getgid())
×
1334
                return -EEXIST;
×
1335

1336
        return TAKE_FD(fd);
1337
}
1338

1339
static int socket_symlink(Socket *s) {
3,622✔
1340
        int r;
3,622✔
1341

1342
        assert(s);
3,622✔
1343

1344
        const char *target = socket_find_symlink_target(s);
3,622✔
1345
        if (!target)
3,622✔
1346
                return 0;
1347

1348
        STRV_FOREACH(linkpath, s->symlinks) {
5,389✔
1349
                (void) mkdir_parents_label(*linkpath, s->directory_mode);
1,976✔
1350

1351
                r = symlink_idempotent(target, *linkpath, false);
1,976✔
1352
                if (r == -EEXIST && s->remove_on_stop) {
1,976✔
1353
                        /* If there's already something where we want to create the symlink, and the
1354
                         * destructive RemoveOnStop= mode is set, then we might as well try to remove what
1355
                         * already exists and try again. */
1356

1357
                        if (unlink(*linkpath) >= 0)
×
1358
                                r = symlink_idempotent(target, *linkpath, false);
×
1359
                }
1360
                if (r < 0)
1,976✔
1361
                        log_unit_warning_errno(UNIT(s), r, "Failed to create symlink %s %s %s, ignoring: %m",
×
1362
                                               *linkpath, glyph(GLYPH_ARROW_RIGHT), target);
1363
        }
1364

1365
        return 0;
1366
}
1367

1368
static int usbffs_write_descs(int fd, Service *s) {
×
1369
        int r;
×
1370

1371
        assert(fd >= 0);
×
1372
        assert(s);
×
1373

1374
        if (!s->usb_function_descriptors || !s->usb_function_strings)
×
1375
                return -EINVAL;
1376

1377
        r = copy_file_fd(s->usb_function_descriptors, fd, 0);
×
1378
        if (r < 0)
×
1379
                return r;
1380

1381
        return copy_file_fd(s->usb_function_strings, fd, 0);
×
1382
}
1383

1384
static int usbffs_dispatch_eps(SocketPort *p, int dfd) {
×
1385
        _cleanup_free_ DirectoryEntries *des = NULL;
×
1386
        int r;
×
1387

1388
        assert(p);
×
1389
        assert(dfd >= 0);
×
1390

1391
        r = readdir_all(dfd, RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT, &des);
×
1392
        if (r < 0)
×
1393
                return r;
1394

1395
        p->auxiliary_fds = new(int, des->n_entries);
×
1396
        if (!p->auxiliary_fds)
×
1397
                return -ENOMEM;
1398

1399
        FOREACH_ARRAY(i, des->entries, des->n_entries) {
×
1400
                const struct dirent *de = *i;
×
1401

1402
                if (streq(de->d_name, "ep0"))
×
1403
                        continue;
×
1404

1405
                r = usbffs_address_create_at(dfd, de->d_name);
×
1406
                if (r < 0)
×
1407
                        goto fail;
×
1408

1409
                p->auxiliary_fds[p->n_auxiliary_fds++] = r;
×
1410
        }
1411

1412
        assert(p->n_auxiliary_fds < des->n_entries);
×
1413

1414
        return 0;
1415

1416
fail:
×
1417
        socket_port_close_auxiliary_fds(p);
×
1418
        return r;
1419
}
1420

1421
int socket_load_service_unit(Socket *s, int cfd, Unit **ret) {
3,687✔
1422
        int r;
3,687✔
1423

1424
        /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1425
         *
1426
         * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1427
         * instance name.
1428
         */
1429

1430
        assert(s);
3,687✔
1431
        assert(ret);
3,687✔
1432

1433
        if (UNIT_ISSET(s->service)) {
3,687✔
1434
                *ret = UNIT_DEREF(s->service);
2,753✔
1435
                return 0;
3,687✔
1436
        }
1437

1438
        if (!s->accept)
934✔
1439
                return -ENODATA;
1440

1441
        /* Build the instance name and load the unit */
1442
        _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
934✔
1443

1444
        r = unit_name_to_prefix(UNIT(s)->id, &prefix);
934✔
1445
        if (r < 0)
934✔
1446
                return r;
1447

1448
        if (cfd >= 0) {
934✔
1449
                r = instance_from_socket(cfd, s->n_accepted, &instance);
109✔
1450
                if (ERRNO_IS_NEG_DISCONNECT(r))
109✔
1451
                        /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1452
                         * different errors. This connection is over, but the socket unit lives on. */
1453
                        return log_unit_debug_errno(UNIT(s), r,
×
1454
                                                    "Got error %s on incoming socket, assuming aborted connection attempt, ignoring.",
1455
                                                    ERRNO_NAME(r));
1456
                if (r < 0)
109✔
1457
                        return r;
1458
        }
1459

1460
        /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1461
         * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1462
         * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1463
        r = unit_name_build(prefix, instance ?: "internal", ".service", &name);
1,759✔
1464
        if (r < 0)
934✔
1465
                return r;
1466

1467
        return manager_load_unit(UNIT(s)->manager, name, NULL, NULL, ret);
934✔
1468
}
1469

1470
static int socket_determine_selinux_label(Socket *s, char **ret) {
3,516✔
1471
        Unit *service;
3,516✔
1472
        int r;
3,516✔
1473

1474
        assert(s);
3,516✔
1475
        assert(ret);
3,516✔
1476

1477
        r = socket_load_service_unit(s, /* cfd= */ -EBADF, &service);
3,516✔
1478
        if (r == -ENODATA) {
3,516✔
1479
                *ret = NULL;
×
1480
                return 0;
×
1481
        }
1482
        if (r < 0)
3,516✔
1483
                return r;
1484

1485
        r = service_determine_exec_selinux_label(SERVICE(service), ret);
7,032✔
1486
        if (r == -ENODATA) {
3,516✔
1487
                *ret = NULL;
3,516✔
1488
                return 0;
3,516✔
1489
        }
1490
        return r;
1491
}
1492

1493
static int socket_address_listen_do(
3,564✔
1494
                Socket *s,
1495
                const SocketAddress *address,
1496
                const char *selinux_label) {
1497

1498
        assert(s);
3,564✔
1499
        assert(address);
3,564✔
1500

1501
        return socket_address_listen(
7,128✔
1502
                        address,
1503
                        SOCK_CLOEXEC|SOCK_NONBLOCK,
1504
                        s->backlog,
3,564✔
1505
                        s->bind_ipv6_only,
1506
                        s->bind_to_device,
3,564✔
1507
                        s->reuse_port,
3,564✔
1508
                        s->free_bind,
3,564✔
1509
                        s->transparent,
3,564✔
1510
                        s->directory_mode,
1511
                        s->socket_mode,
1512
                        selinux_label,
1513
                        s->smack);
3,564✔
1514
}
1515

1516
#define log_address_error_errno(u, address, error, fmt)          \
1517
        ({                                                       \
1518
                _cleanup_free_ char *_t = NULL;                  \
1519
                                                                 \
1520
                (void) socket_address_print(address, &_t);       \
1521
                log_unit_error_errno(u, error, fmt, strna(_t));  \
1522
        })
1523

1524
static bool fork_needed(const SocketAddress *address, Socket *s) {
3,549✔
1525
        assert(address);
3,549✔
1526
        assert(s);
3,549✔
1527

1528
        /* Check if we need to do the cgroup or netns stuff. If not we can do things much simpler. */
1529

1530
        /* If there are any NFTSet= directives with cgroup source, we need the cgroup */
1531
        Unit *u = UNIT(s);
3,549✔
1532
        CGroupContext *c = unit_get_cgroup_context(u);
3,549✔
1533
        if (c)
3,549✔
1534
                FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets)
3,549✔
1535
                        if (nft_set->source == NFT_SET_SOURCE_CGROUP)
×
1536
                                return true;
1537

1538
        if (IN_SET(address->sockaddr.sa.sa_family, AF_INET, AF_INET6) &&
3,550✔
1539
            bpf_program_supported() > 0) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
1✔
1540
                return true;
1541

1542
        return exec_needs_network_namespace(&s->exec_context);
3,548✔
1543
}
1544

1545
static int socket_address_listen_in_cgroup(
3,549✔
1546
                Socket *s,
1547
                const SocketAddress *address,
1548
                const char *label) {
1549

1550
        int r;
3,549✔
1551

1552
        assert(s);
3,549✔
1553
        assert(address);
3,549✔
1554

1555
        /* This is a wrapper around socket_address_listen(), that forks off a helper process inside the
1556
         * socket's cgroup and network namespace in which the socket is actually created. This way we ensure
1557
         * the socket is actually properly attached to the unit's cgroup for the purpose of BPF filtering and
1558
         * such. */
1559

1560
        if (!fork_needed(address, s)) {
3,549✔
1561
                /* Shortcut things... */
1562
                r = socket_address_listen_do(s, address, label);
3,548✔
1563
                if (r < 0)
3,548✔
1564
                        return log_address_error_errno(UNIT(s), address, r, "Failed to create listening socket (%s): %m");
3,549✔
1565

1566
                return r;
1567
        }
1568

1569
        r = unit_setup_exec_runtime(UNIT(s));
1✔
1570
        if (r < 0)
1✔
1571
                return log_unit_error_errno(UNIT(s), r, "Failed to acquire runtime: %m");
×
1572

1573
        if (s->exec_runtime && s->exec_runtime->shared) {
1✔
1574
                if (s->exec_context.user_namespace_path &&
×
1575
                    s->exec_runtime->shared->userns_storage_socket[0] >= 0) {
×
1576
                        r = open_shareable_ns_path(s->exec_runtime->shared->userns_storage_socket, s->exec_context.user_namespace_path, CLONE_NEWUSER);
×
1577
                        if (r < 0)
×
1578
                                return log_unit_error_errno(UNIT(s), r, "Failed to open user namespace path %s: %m", s->exec_context.user_namespace_path);
×
1579
                }
1580

1581
                if (s->exec_context.network_namespace_path &&
×
1582
                    s->exec_runtime->shared->netns_storage_socket[0] >= 0) {
×
1583
                        r = open_shareable_ns_path(s->exec_runtime->shared->netns_storage_socket, s->exec_context.network_namespace_path, CLONE_NEWNET);
×
1584
                        if (r < 0)
×
1585
                                return log_unit_error_errno(UNIT(s), r, "Failed to open network namespace path %s: %m", s->exec_context.network_namespace_path);
×
1586
                }
1587

1588
                if (s->exec_context.ipc_namespace_path &&
×
1589
                    s->exec_runtime->shared->ipcns_storage_socket[0] >= 0) {
×
1590
                        r = open_shareable_ns_path(s->exec_runtime->shared->ipcns_storage_socket, s->exec_context.ipc_namespace_path, CLONE_NEWIPC);
×
1591
                        if (r < 0)
×
1592
                                return log_unit_error_errno(UNIT(s), r, "Failed to open IPC namespace path %s: %m", s->exec_context.ipc_namespace_path);
×
1593
                }
1594
        }
1595

1596
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
×
1597
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
1✔
1598
        _cleanup_close_ int fd = -EBADF;
1✔
1599

1600
        if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pair) < 0)
1✔
1601
                return log_unit_error_errno(UNIT(s), errno, "Failed to create communication channel: %m");
×
1602

1603
        r = unit_fork_helper_process(UNIT(s), "(sd-listen)", /* into_cgroup= */ true, &pid);
1✔
1604
        if (r < 0)
17✔
1605
                return log_unit_error_errno(UNIT(s), r, "Failed to fork off listener stub process: %m");
×
1606
        if (r == 0) {
17✔
1607
                /* Child */
1608

1609
                pair[0] = safe_close(pair[0]);
16✔
1610

1611
                if (exec_needs_network_namespace(&s->exec_context) &&
16✔
1612
                    s->exec_runtime &&
×
1613
                    s->exec_runtime->shared &&
×
1614
                    s->exec_runtime->shared->netns_storage_socket[0] >= 0) {
×
1615

1616
                        if (namespace_type_supported(NAMESPACE_NET)) {
×
1617
                                r = setup_shareable_ns(s->exec_runtime->shared->netns_storage_socket, CLONE_NEWNET);
×
1618
                                if (r < 0) {
×
1619
                                        log_unit_error_errno(UNIT(s), r, "Failed to join network namespace: %m");
×
1620
                                        _exit(EXIT_NETWORK);
×
1621
                                }
1622
                        } else if (s->exec_context.network_namespace_path) {
×
1623
                                log_unit_error(UNIT(s), "Network namespace path configured but network namespaces not supported.");
×
1624
                                _exit(EXIT_NETWORK);
×
1625
                        } else
1626
                                log_unit_warning(UNIT(s), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
×
1627
                }
1628

1629
                fd = socket_address_listen_do(s, address, label);
16✔
1630
                if (fd < 0) {
16✔
1631
                        log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
×
1632
                        _exit(EXIT_FAILURE);
×
1633
                }
1634

1635
                r = send_one_fd(pair[1], fd, 0);
16✔
1636
                if (r < 0) {
16✔
1637
                        log_address_error_errno(UNIT(s), address, r, "Failed to send listening socket (%s) to parent: %m");
×
1638
                        _exit(EXIT_FAILURE);
×
1639
                }
1640

1641
                _exit(EXIT_SUCCESS);
16✔
1642
        }
1643

1644
        pair[1] = safe_close(pair[1]);
1✔
1645
        fd = receive_one_fd(pair[0], 0);
1✔
1646

1647
        /* We synchronously wait for the helper, as it shouldn't be slow */
1648
        r = pidref_wait_for_terminate_and_check("(sd-listen)", &pid, WAIT_LOG_ABNORMAL);
1✔
1649
        if (r < 0)
1✔
1650
                return r;
1651

1652
        if (fd < 0)
1✔
1653
                return log_address_error_errno(UNIT(s), address, fd, "Failed to receive listening socket (%s): %m");
×
1654

1655
        return TAKE_FD(fd);
1656
}
1657

1658
static int socket_open_fds(Socket *orig_s) {
3,559✔
1659
        _cleanup_(socket_close_fdsp) Socket *s = orig_s;
3,559✔
1660
        _cleanup_freecon_ char *label = NULL;
3,559✔
1661
        bool know_label = false;
3,559✔
1662
        int r;
3,559✔
1663

1664
        assert(s);
3,559✔
1665

1666
        LIST_FOREACH(port, p, s->ports) {
3,559✔
1667

1668
                if (p->fd >= 0)
3,628✔
1669
                        continue;
×
1670

1671
                switch (p->type) {
3,628✔
1672

1673
                case SOCKET_SOCKET:
3,549✔
1674

1675
                        if (!know_label) {
3,549✔
1676
                                /* Figure out the label, if we don't it know yet. We do it once for the first
1677
                                 * socket where we need this and remember it for the rest. */
1678

1679
                                r = socket_determine_selinux_label(s, &label);
3,516✔
1680
                                if (r < 0)
3,516✔
1681
                                        return log_unit_error_errno(UNIT(s), r, "Failed to determine SELinux label: %m");
×
1682

1683
                                know_label = true;
1684
                        }
1685

1686
                        /* Apply the socket protocol */
1687
                        switch (p->address.type) {
3,549✔
1688

1689
                        case SOCK_STREAM:
3,366✔
1690
                                if (IN_SET(s->socket_protocol, IPPROTO_SCTP, IPPROTO_MPTCP))
3,366✔
1691
                                        p->address.protocol = s->socket_protocol;
×
1692
                                break;
1693

1694
                        case SOCK_SEQPACKET:
53✔
1695
                                if (s->socket_protocol == IPPROTO_SCTP)
53✔
1696
                                        p->address.protocol = s->socket_protocol;
×
1697
                                break;
1698

1699
                        case SOCK_DGRAM:
66✔
1700
                                if (s->socket_protocol == IPPROTO_UDPLITE)
66✔
1701
                                        p->address.protocol = s->socket_protocol;
×
1702
                                break;
1703
                        }
1704

1705
                        p->fd = socket_address_listen_in_cgroup(s, &p->address, label);
3,549✔
1706
                        if (p->fd < 0)
3,549✔
1707
                                return p->fd;
1708

1709
                        socket_apply_socket_options(s, p, p->fd);
3,549✔
1710
                        socket_symlink(s);
3,549✔
1711
                        break;
1712

1713
                case SOCKET_SPECIAL:
6✔
1714

1715
                        p->fd = special_address_create(p->path, s->writable);
6✔
1716
                        if (p->fd < 0)
6✔
1717
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open special file '%s': %m", p->path);
×
1718
                        break;
1719

1720
                case SOCKET_FIFO:
73✔
1721

1722
                        p->fd = fifo_address_create(
146✔
1723
                                        p->path,
73✔
1724
                                        s->directory_mode,
1725
                                        s->socket_mode);
1726
                        if (p->fd < 0)
73✔
1727
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open FIFO '%s': %m", p->path);
×
1728

1729
                        socket_apply_fifo_options(s, p->fd);
73✔
1730
                        socket_symlink(s);
73✔
1731
                        break;
1732

1733
                case SOCKET_MQUEUE:
×
1734

1735
                        p->fd = mq_address_create(
×
1736
                                        p->path,
×
1737
                                        s->socket_mode,
1738
                                        s->mq_maxmsg,
1739
                                        s->mq_msgsize);
1740
                        if (p->fd < 0)
×
1741
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open message queue '%s': %m", p->path);
×
1742
                        break;
1743

1744
                case SOCKET_USB_FUNCTION: {
×
1745
                        _cleanup_close_ int dfd = -EBADF;
7,187✔
1746

1747
                        dfd = open(p->path, O_DIRECTORY|O_CLOEXEC);
×
1748
                        if (dfd < 0)
×
1749
                                return log_unit_error_errno(UNIT(s), errno,
×
1750
                                                            "Failed to open USB FunctionFS dir '%s': %m", p->path);
1751

1752
                        p->fd = usbffs_address_create_at(dfd, "ep0");
×
1753
                        if (p->fd < 0)
×
1754
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open USB FunctionFS ep0: %m");
×
1755

1756
                        r = usbffs_write_descs(p->fd, SERVICE(UNIT_DEREF(s->service)));
×
1757
                        if (r < 0)
×
1758
                                return log_unit_error_errno(UNIT(s), r, "Failed to write to USB FunctionFS ep0: %m");
×
1759

1760
                        r = usbffs_dispatch_eps(p, dfd);
×
1761
                        if (r < 0)
×
1762
                                return log_unit_error_errno(UNIT(s), r, "Failed to dispatch USB FunctionFS eps: %m");
×
1763

1764
                        break;
×
1765
                }
1766

1767
                default:
×
1768
                        assert_not_reached();
×
1769
                }
1770
        }
1771

1772
        TAKE_PTR(s);
1773
        return 0;
1774
}
1775

1776
static void socket_unwatch_fds(Socket *s) {
9,486✔
1777
        int r;
9,486✔
1778

1779
        assert(s);
9,486✔
1780

1781
        LIST_FOREACH(port, p, s->ports) {
19,219✔
1782
                if (p->fd < 0)
9,733✔
1783
                        continue;
3,628✔
1784

1785
                r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
6,105✔
1786
                if (r < 0)
6,105✔
1787
                        log_unit_debug_errno(UNIT(s), r, "Failed to disable event source: %m");
×
1788
        }
1789
}
9,486✔
1790

1791
static int socket_watch_fds(Socket *s) {
5,683✔
1792
        int r;
5,683✔
1793

1794
        assert(s);
5,683✔
1795

1796
        LIST_FOREACH(port, p, s->ports) {
11,491✔
1797
                if (p->fd < 0)
5,808✔
1798
                        continue;
×
1799

1800
                if (p->event_source) {
5,808✔
1801
                        r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
827✔
1802
                        if (r < 0)
827✔
1803
                                goto fail;
×
1804
                } else {
1805
                        r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
4,981✔
1806
                        if (r < 0)
4,981✔
1807
                                goto fail;
×
1808

1809
                        (void) sd_event_source_set_description(p->event_source, "socket-port-io");
4,981✔
1810
                }
1811

1812
                r = sd_event_source_set_ratelimit(p->event_source, s->poll_limit.interval, s->poll_limit.burst);
5,808✔
1813
                if (r < 0)
5,808✔
1814
                        log_unit_debug_errno(UNIT(s), r, "Failed to set poll limit on I/O event source, ignoring: %m");
×
1815
        }
1816

1817
        return 0;
1818

1819
fail:
×
1820
        log_unit_warning_errno(UNIT(s), r, "Failed to watch listening fds: %m");
×
1821
        socket_unwatch_fds(s);
×
1822
        return r;
×
1823
}
1824

1825
enum {
1826
        SOCKET_OPEN_NONE,
1827
        SOCKET_OPEN_SOME,
1828
        SOCKET_OPEN_ALL,
1829
};
1830

1831
static int socket_check_open(Socket *s) {
2,016✔
1832
        bool have_open = false, have_closed = false;
2,016✔
1833

1834
        assert(s);
2,016✔
1835

1836
        LIST_FOREACH(port, p, s->ports) {
4,135✔
1837
                if (p->fd < 0)
2,119✔
1838
                        have_closed = true;
1839
                else
1840
                        have_open = true;
2,119✔
1841

1842
                if (have_open && have_closed)
2,119✔
1843
                        return SOCKET_OPEN_SOME;
1844
        }
1845

1846
        if (have_open)
2,016✔
1847
                return SOCKET_OPEN_ALL;
2,016✔
1848

1849
        return SOCKET_OPEN_NONE;
1850
}
1851

1852
static void socket_set_state(Socket *s, SocketState state) {
15,169✔
1853
        SocketState old_state;
15,169✔
1854

1855
        assert(s);
15,169✔
1856

1857
        if (s->state != state)
15,169✔
1858
                bus_unit_send_pending_change_signal(UNIT(s), false);
13,466✔
1859

1860
        old_state = s->state;
15,169✔
1861
        s->state = state;
15,169✔
1862

1863
        if (!SOCKET_STATE_WITH_PROCESS(state) && state != SOCKET_DEFERRED)
15,169✔
1864
                s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
14,934✔
1865

1866
        if (!SOCKET_STATE_WITH_PROCESS(state)) {
15,169✔
1867
                socket_unwatch_control_pid(s);
14,934✔
1868
                s->control_command = NULL;
14,934✔
1869
                s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
14,934✔
1870
        }
1871

1872
        if (state != SOCKET_LISTENING)
15,169✔
1873
                socket_unwatch_fds(s);
9,486✔
1874

1875
        if (!IN_SET(state,
9,486✔
1876
                    SOCKET_START_OPEN,
1877
                    SOCKET_START_CHOWN,
1878
                    SOCKET_START_POST,
1879
                    SOCKET_LISTENING,
1880
                    SOCKET_DEFERRED,
1881
                    SOCKET_RUNNING,
1882
                    SOCKET_STOP_PRE,
1883
                    SOCKET_STOP_PRE_SIGTERM,
1884
                    SOCKET_STOP_PRE_SIGKILL))
1885
                socket_close_fds(s);
3,024✔
1886

1887
        if (state != SOCKET_DEFERRED)
15,169✔
1888
                unit_remove_from_stop_notify_queue(UNIT(s));
15,169✔
1889

1890
        if (state != old_state)
15,169✔
1891
                log_unit_debug(UNIT(s), "Changed %s -> %s", socket_state_to_string(old_state), socket_state_to_string(state));
13,466✔
1892

1893
        unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], /* reload_success= */ true);
15,169✔
1894
}
15,169✔
1895

1896
static int socket_coldplug(Unit *u) {
4,049✔
1897
        Socket *s = ASSERT_PTR(SOCKET(u));
4,049✔
1898
        int r;
4,049✔
1899

1900
        assert(s->state == SOCKET_DEAD);
4,049✔
1901

1902
        if (s->deserialized_state == s->state)
4,049✔
1903
                return 0;
1904

1905
        /* Patch "deferred" back to "listening" and let socket_enter_running() figure out what to do.
1906
         * This saves us the trouble of handling flipping of DeferTrigger= vs Accept= during reload. */
1907
        if (s->deserialized_state == SOCKET_DEFERRED)
2,016✔
1908
                s->deserialized_state = SOCKET_LISTENING;
×
1909

1910
        if (pidref_is_set(&s->control_pid) &&
2,016✔
1911
            pidref_is_unwaited(&s->control_pid) > 0 &&
×
1912
            SOCKET_STATE_WITH_PROCESS(s->deserialized_state)) {
×
1913

1914
                r = unit_watch_pidref(UNIT(s), &s->control_pid, /* exclusive= */ false);
×
1915
                if (r < 0)
×
1916
                        return r;
1917

1918
                r = socket_arm_timer(s, /* relative= */ false, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec));
×
1919
                if (r < 0)
×
1920
                        return r;
1921
        }
1922

1923
        if (IN_SET(s->deserialized_state,
2,016✔
1924
                   SOCKET_START_OPEN,
1925
                   SOCKET_START_CHOWN,
1926
                   SOCKET_START_POST,
1927
                   SOCKET_LISTENING,
1928
                   SOCKET_RUNNING)) {
1929

1930
                /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1931
                 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN
1932
                 * state for them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we
1933
                 * have all fds open, and if there's a mismatch, warn loudly.
1934
                 *
1935
                 * Note that SOCKET_START_OPEN requires no special treatment, as it's only intermediate
1936
                 * between SOCKET_START_PRE and SOCKET_START_CHOWN and shall otherwise not be observed.
1937
                 * It's listed only for consistency. */
1938

1939
                r = socket_check_open(s);
2,016✔
1940
                if (r == SOCKET_OPEN_NONE)
2,016✔
1941
                        log_unit_warning(UNIT(s),
×
1942
                                         "Unit configuration changed while unit was running, "
1943
                                         "and no socket file descriptors are open. "
1944
                                         "Unit not functional until restarted.");
1945
                else if (r == SOCKET_OPEN_SOME)
2,016✔
1946
                        log_unit_warning(UNIT(s),
×
1947
                                         "Unit configuration changed while unit was running, "
1948
                                         "and some socket file descriptors have not been opened yet. "
1949
                                         "Unit not fully functional until restarted.");
1950
        }
1951

1952
        if (s->deserialized_state == SOCKET_LISTENING) {
2,016✔
1953
                r = socket_watch_fds(s);
1,275✔
1954
                if (r < 0)
1,275✔
1955
                        return r;
1956
        }
1957

1958
        if (!IN_SET(s->deserialized_state, SOCKET_DEAD, SOCKET_FAILED, SOCKET_CLEANING))
2,016✔
1959
                (void) unit_setup_exec_runtime(u);
2,016✔
1960

1961
        socket_set_state(s, s->deserialized_state);
2,016✔
1962
        return 0;
2,016✔
1963
}
1964

1965
static int socket_spawn(Socket *s, ExecCommand *c, PidRef *ret_pid) {
199✔
1966
        _cleanup_(exec_params_shallow_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(
199✔
1967
                        EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN);
1968
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
199✔
1969
        int r;
199✔
1970

1971
        assert(s);
199✔
1972
        assert(c);
199✔
1973
        assert(ret_pid);
199✔
1974

1975
        r = unit_prepare_exec(UNIT(s));
199✔
1976
        if (r < 0)
199✔
1977
                return r;
1978

1979
        r = socket_arm_timer(s, /* relative= */ true, s->timeout_usec);
199✔
1980
        if (r < 0)
199✔
1981
                return r;
1982

1983
        r = unit_set_exec_params(UNIT(s), &exec_params);
199✔
1984
        if (r < 0)
199✔
1985
                return r;
1986

1987
        /* Note that ExecStartPre= command doesn't inherit any FDs. It runs before we open listen FDs. */
1988
        if (s->pass_fds_to_exec) {
199✔
1989
                _cleanup_strv_free_ char **fd_names = NULL;
×
1990
                _cleanup_free_ int *fds = NULL;
×
1991
                int n_fds;
×
1992

1993
                n_fds = socket_collect_fds(s, &fds);
×
1994
                if (n_fds < 0)
×
1995
                        return n_fds;
1996

1997
                r = strv_extend_n(&fd_names, socket_fdname(s), n_fds);
×
1998
                if (r < 0)
×
1999
                        return r;
2000

2001
                exec_params.fds = TAKE_PTR(fds);
×
2002
                exec_params.fd_names = TAKE_PTR(fd_names);
×
2003
                exec_params.n_socket_fds = n_fds;
×
2004
        }
2005

2006
        r = exec_spawn(UNIT(s),
199✔
2007
                       c,
2008
                       &s->exec_context,
199✔
2009
                       &exec_params,
2010
                       s->exec_runtime,
2011
                       &s->cgroup_context,
199✔
2012
                       &pidref);
2013
        if (r < 0)
199✔
2014
                return r;
2015

2016
        r = unit_watch_pidref(UNIT(s), &pidref, /* exclusive= */ true);
199✔
2017
        if (r < 0)
199✔
2018
                return r;
2019

2020
        *ret_pid = TAKE_PIDREF(pidref);
199✔
2021
        return 0;
199✔
2022
}
2023

2024
static int socket_chown(Socket *s, PidRef *ret_pid) {
36✔
2025
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
36✔
2026
        int r;
36✔
2027

2028
        assert(s);
36✔
2029

2030
        r = socket_arm_timer(s, /* relative= */ true, s->timeout_usec);
36✔
2031
        if (r < 0)
36✔
2032
                return r;
2033

2034
        /* We have to resolve the user names out-of-process, hence
2035
         * let's fork here. It's messy, but well, what can we do? */
2036

2037
        r = unit_fork_helper_process(UNIT(s), "(sd-chown)", /* into_cgroup= */ true, &pid);
36✔
2038
        if (r < 0)
157✔
2039
                return r;
2040
        if (r == 0) {
157✔
2041
                uid_t uid = UID_INVALID;
121✔
2042
                gid_t gid = GID_INVALID;
121✔
2043

2044
                /* Child */
2045

2046
                if (!isempty(s->user)) {
121✔
2047
                        const char *user = s->user;
1✔
2048

2049
                        r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
1✔
2050
                        if (r < 0) {
1✔
2051
                                log_unit_error_errno(UNIT(s), r,
×
2052
                                                     "Failed to resolve user '%s': %s",
2053
                                                     user, STRERROR_USER(r));
2054
                                _exit(EXIT_USER);
×
2055
                        }
2056
                }
2057

2058
                if (!isempty(s->group)) {
121✔
2059
                        const char *group = s->group;
121✔
2060

2061
                        r = get_group_creds(&group, &gid, 0);
121✔
2062
                        if (r < 0) {
121✔
2063
                                log_unit_error_errno(UNIT(s), r,
×
2064
                                                     "Failed to resolve group '%s': %s",
2065
                                                     group, STRERROR_GROUP(r));
2066
                                _exit(EXIT_GROUP);
×
2067
                        }
2068
                }
2069

2070
                LIST_FOREACH(port, p, s->ports) {
242✔
2071
                        const char *path = NULL;
121✔
2072

2073
                        if (p->type == SOCKET_SOCKET)
121✔
2074
                                path = socket_address_get_path(&p->address);
120✔
2075
                        else if (p->type == SOCKET_FIFO)
1✔
2076
                                path = p->path;
×
2077
                        else if (p->type == SOCKET_MQUEUE) {
1✔
2078
                                /* Use fchown on the fd since /dev/mqueue might not be mounted. */
2079
                                if (fchown(p->fd, uid, gid) < 0) {
1✔
2080
                                        log_unit_error_errno(UNIT(s), errno, "Failed to fchown(): %m");
×
2081
                                        _exit(EXIT_CHOWN);
×
2082
                                }
2083
                                continue;
1✔
2084
                        }
2085

2086
                        if (!path)
120✔
2087
                                continue;
×
2088

2089
                        if (chown(path, uid, gid) < 0) {
120✔
2090
                                log_unit_error_errno(UNIT(s), errno, "Failed to chown(): %m");
×
2091
                                _exit(EXIT_CHOWN);
×
2092
                        }
2093
                }
2094

2095
                _exit(EXIT_SUCCESS);
121✔
2096
        }
2097

2098
        r = unit_watch_pidref(UNIT(s), &pid, /* exclusive= */ true);
36✔
2099
        if (r < 0)
36✔
2100
                return r;
2101

2102
        *ret_pid = TAKE_PIDREF(pid);
36✔
2103
        return 0;
36✔
2104
}
2105

2106
static void socket_enter_dead(Socket *s, SocketResult f) {
3,024✔
2107
        assert(s);
3,024✔
2108

2109
        if (s->result == SOCKET_SUCCESS || IN_SET(f, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT, SOCKET_FAILURE_START_LIMIT_HIT))
3,024✔
2110
                s->result = f;
3,024✔
2111

2112
        if (s->result == SOCKET_SUCCESS)
3,024✔
2113
                unit_log_success(UNIT(s));
3,024✔
2114
        else
2115
                unit_log_failure(UNIT(s), socket_result_to_string(s->result));
×
2116

2117
        unit_warn_leftover_processes(UNIT(s), /* start= */ false);
3,024✔
2118

2119
        socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
6,048✔
2120

2121
        s->exec_runtime = exec_runtime_destroy(s->exec_runtime);
3,024✔
2122

2123
        unit_destroy_runtime_data(UNIT(s), &s->exec_context, /* destroy_runtime_dir= */ true);
3,024✔
2124

2125
        unit_unref_uid_gid(UNIT(s), true);
3,024✔
2126
}
3,024✔
2127

2128
static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
2129

2130
static void socket_enter_stop_post(Socket *s, SocketResult f) {
3,024✔
2131
        int r;
3,024✔
2132

2133
        assert(s);
3,024✔
2134

2135
        if (s->result == SOCKET_SUCCESS)
3,024✔
2136
                s->result = f;
3,024✔
2137

2138
        socket_unwatch_control_pid(s);
3,024✔
2139
        s->control_command_id = SOCKET_EXEC_STOP_POST;
3,024✔
2140
        s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
3,024✔
2141

2142
        if (s->control_command) {
3,024✔
2143
                r = socket_spawn(s, s->control_command, &s->control_pid);
×
2144
                if (r < 0) {
×
2145
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop-post' task: %m");
×
2146
                        socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
×
2147
                        return;
×
2148
                }
2149

2150
                socket_set_state(s, SOCKET_STOP_POST);
×
2151
        } else
2152
                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
3,024✔
2153
}
2154

2155
static int state_to_kill_operation(Socket *s, SocketState state) {
6,048✔
2156
        assert(s);
6,048✔
2157

2158
        if (state == SOCKET_STOP_PRE_SIGTERM)
6,048✔
UNCOV
2159
                return unit_has_job_type(UNIT(s), JOB_RESTART) ? KILL_RESTART : KILL_TERMINATE;
×
2160

2161
        if (state == SOCKET_FINAL_SIGTERM)
6,048✔
2162
                return KILL_TERMINATE;
3,024✔
2163

2164
        return KILL_KILL;
2165
}
2166

2167
static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
6,048✔
2168
        int r;
6,048✔
2169

2170
        assert(s);
6,048✔
2171

2172
        if (s->result == SOCKET_SUCCESS)
6,048✔
2173
                s->result = f;
6,048✔
2174

2175
        r = unit_kill_context(UNIT(s), state_to_kill_operation(s, state));
6,048✔
2176
        if (r < 0) {
6,048✔
2177
                log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
×
2178
                goto fail;
×
2179
        }
2180
        if (r > 0) {
6,048✔
UNCOV
2181
                r = socket_arm_timer(s, /* relative= */ true, s->timeout_usec);
×
UNCOV
2182
                if (r < 0) {
×
2183
                        log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
2184
                        goto fail;
×
2185
                }
2186

UNCOV
2187
                socket_set_state(s, state);
×
2188
        } else if (state == SOCKET_STOP_PRE_SIGTERM)
6,048✔
2189
                socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
×
2190
        else if (state == SOCKET_STOP_PRE_SIGKILL)
6,048✔
2191
                socket_enter_stop_post(s, SOCKET_SUCCESS);
×
2192
        else if (state == SOCKET_FINAL_SIGTERM)
6,048✔
2193
                socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
3,024✔
2194
        else
2195
                socket_enter_dead(s, SOCKET_SUCCESS);
3,024✔
2196

2197
        return;
2198

2199
fail:
×
2200
        if (IN_SET(state, SOCKET_STOP_PRE_SIGTERM, SOCKET_STOP_PRE_SIGKILL))
×
2201
                socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
×
2202
        else
2203
                socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
×
2204
}
2205

2206
static void socket_enter_stop_pre(Socket *s, SocketResult f) {
3,024✔
2207
        int r;
3,024✔
2208

2209
        assert(s);
3,024✔
2210

2211
        if (s->result == SOCKET_SUCCESS)
3,024✔
2212
                s->result = f;
3,024✔
2213

2214
        socket_unwatch_control_pid(s);
3,024✔
2215
        s->control_command_id = SOCKET_EXEC_STOP_PRE;
3,024✔
2216
        s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
3,024✔
2217

2218
        if (s->control_command) {
3,024✔
2219
                r = socket_spawn(s, s->control_command, &s->control_pid);
3✔
2220
                if (r < 0) {
3✔
2221
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop-pre' task: %m");
×
2222
                        socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
×
2223
                        return;
×
2224
                }
2225

2226
                socket_set_state(s, SOCKET_STOP_PRE);
3✔
2227
        } else
2228
                socket_enter_stop_post(s, SOCKET_SUCCESS);
3,021✔
2229
}
2230

2231
static void flush_ports(Socket *s) {
×
2232
        assert(s);
×
2233

2234
        /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2235
         * anymore */
2236

2237
        LIST_FOREACH(port, p, s->ports) {
×
2238
                if (p->fd < 0)
×
2239
                        continue;
×
2240

2241
                if (p->type == SOCKET_MQUEUE)
×
2242
                        (void) flush_mqueue(p->fd);
×
2243
                else {
2244
                        (void) flush_accept(p->fd);
×
2245
                        (void) flush_fd(p->fd);
×
2246
                }
2247
        }
2248
}
×
2249

2250
static void socket_enter_listening(Socket *s) {
4,408✔
2251
        int r;
4,408✔
2252

2253
        assert(s);
4,408✔
2254

2255
        if (!s->accept && s->flush_pending) {
4,408✔
2256
                log_unit_debug(UNIT(s), "Flushing socket before listening.");
×
2257
                flush_ports(s);
×
2258
        }
2259

2260
        r = socket_watch_fds(s);
4,408✔
2261
        if (r < 0) {
4,408✔
2262
                log_unit_warning_errno(UNIT(s), r, "Failed to watch sockets: %m");
×
2263
                socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2264
                return;
×
2265
        }
2266

2267
        socket_set_state(s, SOCKET_LISTENING);
4,408✔
2268
}
2269

2270
static void socket_enter_start_post(Socket *s) {
3,559✔
2271
        int r;
3,559✔
2272

2273
        assert(s);
3,559✔
2274

2275
        socket_unwatch_control_pid(s);
3,559✔
2276
        s->control_command_id = SOCKET_EXEC_START_POST;
3,559✔
2277
        s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
3,559✔
2278

2279
        if (s->control_command) {
3,559✔
2280
                r = socket_spawn(s, s->control_command, &s->control_pid);
196✔
2281
                if (r < 0) {
196✔
2282
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-post' task: %m");
×
2283
                        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2284
                        return;
×
2285
                }
2286

2287
                socket_set_state(s, SOCKET_START_POST);
196✔
2288
        } else
2289
                socket_enter_listening(s);
3,363✔
2290
}
2291

2292
static void socket_enter_start_chown(Socket *s) {
3,559✔
2293
        int r;
3,559✔
2294

2295
        assert(s);
3,559✔
2296
        assert(s->state == SOCKET_START_OPEN);
3,559✔
2297

2298
        if (!isempty(s->user) || !isempty(s->group)) {
3,559✔
2299

2300
                socket_unwatch_control_pid(s);
36✔
2301
                s->control_command_id = SOCKET_EXEC_START_CHOWN;
36✔
2302
                s->control_command = NULL;
36✔
2303

2304
                r = socket_chown(s, &s->control_pid);
36✔
2305
                if (r < 0) {
36✔
2306
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-chown' task: %m");
×
2307
                        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2308
                        return;
×
2309
                }
2310

2311
                socket_set_state(s, SOCKET_START_CHOWN);
36✔
2312
        } else
2313
                socket_enter_start_post(s);
3,523✔
2314
}
2315

2316
static void socket_enter_start_open(Socket *s) {
3,559✔
2317
        int r;
3,559✔
2318

2319
        assert(s);
3,559✔
2320
        assert(IN_SET(s->state, SOCKET_DEAD, SOCKET_FAILED, SOCKET_START_PRE));
3,559✔
2321

2322
        /* We force a state transition here even though we're not spawning any process (i.e. the state is purely
2323
         * intermediate), so that failure of socket_open_fds() always causes a state change in unit_notify().
2324
         * Otherwise, if no Exec*= is defined, we might go from previous SOCKET_FAILED to SOCKET_FAILED,
2325
         * meaning the OnFailure= deps are unexpectedly skipped (#35635). */
2326

2327
        socket_set_state(s, SOCKET_START_OPEN);
3,559✔
2328

2329
        r = socket_open_fds(s);
3,559✔
2330
        if (r < 0) {
3,559✔
2331
                log_unit_error_errno(UNIT(s), r, "Failed to listen on sockets: %m");
×
2332
                socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2333
                return;
×
2334
        }
2335

2336
        socket_enter_start_chown(s);
3,559✔
2337
}
2338

2339
static void socket_enter_start_pre(Socket *s) {
3,559✔
2340
        int r;
3,559✔
2341

2342
        assert(s);
3,559✔
2343

2344
        socket_unwatch_control_pid(s);
3,559✔
2345

2346
        unit_warn_leftover_processes(UNIT(s), /* start= */ true);
3,559✔
2347

2348
        s->control_command_id = SOCKET_EXEC_START_PRE;
3,559✔
2349
        s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
3,559✔
2350

2351
        if (s->control_command) {
3,559✔
2352
                r = socket_spawn(s, s->control_command, &s->control_pid);
×
2353
                if (r < 0) {
×
2354
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-pre' task: %m");
×
2355
                        socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
×
2356
                        return;
×
2357
                }
2358

2359
                socket_set_state(s, SOCKET_START_PRE);
×
2360
        } else
2361
                socket_enter_start_open(s);
3,559✔
2362
}
2363

UNCOV
2364
static bool socket_may_defer(Socket *s) {
×
UNCOV
2365
        assert(s);
×
2366

UNCOV
2367
        switch (s->defer_trigger) {
×
2368

2369
        case SOCKET_DEFER_NO:
2370
                return false;
2371

2372
        case SOCKET_DEFER_YES:
UNCOV
2373
                return !hashmap_isempty(UNIT(s)->manager->jobs);
×
2374

2375
        case SOCKET_DEFER_PATIENT:
×
2376
                assert(s->defer_trigger_max_usec > 0);
×
2377
                return true;
2378

2379
        default:
×
2380
                assert_not_reached();
×
2381
        }
2382
}
2383

UNCOV
2384
static bool socket_stop_notify(Unit *u) {
×
UNCOV
2385
        Socket *s = ASSERT_PTR(SOCKET(u));
×
UNCOV
2386
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
UNCOV
2387
        int r;
×
2388

UNCOV
2389
        assert(s->state == SOCKET_DEFERRED);
×
2390

UNCOV
2391
        r = manager_add_job(u->manager, JOB_START, UNIT_DEREF(s->service), JOB_LENIENT, &error, /* ret= */ NULL);
×
UNCOV
2392
        if (r >= 0) { /* Yay! */
×
2393
                socket_set_state(s, SOCKET_RUNNING);
×
2394
                return true; /* changed */
2395
        }
UNCOV
2396
        if (sd_bus_error_has_name(&error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE)) {
×
UNCOV
2397
                if (s->defer_trigger == SOCKET_DEFER_PATIENT || !hashmap_isempty(u->manager->jobs))
×
2398
                        /* Wait for some more */
2399
                        return false;
2400

2401
                log_unit_warning_errno(u, r, "Service conflicts with active units even after all jobs have completed, giving up.");
×
2402
        } else
2403
                log_unit_warning_errno(u, r, "Failed to queue service startup job: %s", bus_error_message(&error, r));
×
2404

2405
        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2406
        return true; /* changed */
2407
}
2408

UNCOV
2409
static void socket_enter_deferred(Socket *s) {
×
UNCOV
2410
        int r;
×
2411

UNCOV
2412
        assert(s);
×
UNCOV
2413
        assert(socket_may_defer(s));
×
2414

2415
        /* So here's the thing: if there're currently units conflicting with the service we shall be
2416
         * triggering, and the previous transaction is still running (job pool is not empty), let's
2417
         * defer the activation a bit, and recheck upon any unit stop. IOW, the trigger in question
2418
         * becomes bound to the conflicting dependency, and not the socket IO because we never process them.
2419
         * Put a safety net around all this though, i.e. give up if the service still can't be started
2420
         * even after all existing jobs have completed, or DeferTriggerMaxSec= is reached. */
2421

UNCOV
2422
        r = socket_arm_timer(s, /* relative= */ true, s->defer_trigger_max_usec);
×
UNCOV
2423
        if (r < 0) {
×
2424
                log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
2425
                return socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2426
        }
2427

UNCOV
2428
        unit_add_to_stop_notify_queue(UNIT(s));
×
2429

2430
        /* Disable IO event sources */
UNCOV
2431
        socket_set_state(s, SOCKET_DEFERRED);
×
2432
}
2433

2434
static void socket_enter_running(Socket *s, int cfd_in) {
295✔
2435
        /* Note that this call takes possession of the connection fd passed. It either has to assign it
2436
         * somewhere or close it. */
2437
        _cleanup_close_ int cfd = cfd_in;
295✔
2438
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
295✔
2439
        int r;
295✔
2440

2441
        assert(s);
295✔
2442

2443
        /* We don't take connections anymore if we are supposed to shut down anyway */
2444
        if (unit_stop_pending(UNIT(s))) {
295✔
2445

2446
                log_unit_debug(UNIT(s), "Suppressing connection request since unit stop is scheduled.");
×
2447

2448
                if (cfd >= 0)
×
2449
                        goto refuse;
×
2450

2451
                flush_ports(s);
×
2452
                return;
2453
        }
2454

2455
        if (s->state == SOCKET_DEFERRED) {
295✔
2456
                assert(cfd < 0);
×
2457
                return;
2458
        }
2459

2460
        if (!ratelimit_below(&s->trigger_limit)) {
295✔
2461
                log_unit_warning(UNIT(s), "Trigger limit hit, refusing further activation.");
×
2462
                socket_enter_stop_pre(s, SOCKET_FAILURE_TRIGGER_LIMIT_HIT);
×
2463
                goto refuse;
×
2464
        }
2465

2466
        if (cfd < 0) { /* Accept=no case */
295✔
2467
                bool pending = false;
186✔
2468
                Unit *other;
186✔
2469

2470
                /* If there's already a start pending don't bother to do anything */
2471
                UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_TRIGGERS)
648✔
2472
                        if (unit_active_or_pending(other)) {
186✔
2473
                                pending = true;
2474
                                break;
2475
                        }
2476

2477
                if (!pending) {
186✔
2478
                        if (!UNIT_ISSET(s->service)) {
90✔
2479
                                log_unit_warning(UNIT(s),
×
2480
                                                 "Service to activate vanished, refusing activation.");
2481
                                goto fail;
×
2482
                        }
2483

2484
                        if (s->defer_trigger != SOCKET_DEFER_NO) {
90✔
UNCOV
2485
                                r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_LENIENT, &error, /* ret= */ NULL);
×
UNCOV
2486
                                if (r < 0 && sd_bus_error_has_name(&error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE) && socket_may_defer(s))
×
2487
                                        /* We only check BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE here, not
2488
                                         * BUS_ERROR_TRANSACTION_JOBS_CONFLICTING or BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC,
2489
                                         * since those are errors in a single transaction, which are most likely
2490
                                         * caused by dependency issues in the unit configuration.
2491
                                         * Deferring activation probably won't help. */
UNCOV
2492
                                        return socket_enter_deferred(s);
×
2493
                        } else
2494
                                r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, &error, /* ret= */ NULL);
90✔
2495
                        if (r < 0)
90✔
2496
                                goto queue_error;
×
2497
                }
2498

2499
                socket_set_state(s, SOCKET_RUNNING);
186✔
2500
        } else { /* Accept=yes case */
2501
                _cleanup_(socket_peer_unrefp) SocketPeer *p = NULL;
109✔
2502
                Unit *service;
109✔
2503

2504
                if (s->n_connections >= s->max_connections) {
109✔
2505
                        log_unit_warning(UNIT(s), "Too many incoming connections (%u), dropping connection.",
×
2506
                                         s->n_connections);
2507
                        goto refuse;
×
2508
                }
2509

2510
                if (s->max_connections_per_source > 0) {
109✔
2511
                        r = socket_acquire_peer(s, cfd, &p);
106✔
2512
                        if (ERRNO_IS_NEG_DISCONNECT(r))
106✔
2513
                                return;
2514
                        if (r < 0)
106✔
2515
                                /* We didn't have enough resources to acquire peer information, let's fail. */
2516
                                goto fail;
×
2517
                        if (r > 0 && p->n_ref > s->max_connections_per_source) {
106✔
2518
                                _cleanup_free_ char *t = NULL;
×
2519

2520
                                if (p->peer.sa.sa_family == AF_UNIX)
×
2521
                                        (void) asprintf(&t, "UID " UID_FMT, p->peer_cred.uid);
×
2522
                                else
2523
                                        (void) sockaddr_pretty(&p->peer.sa, p->peer_salen, /* translate_ipv6= */ true, /* include_port= */ false, &t);
×
2524

2525
                                log_unit_warning(UNIT(s),
×
2526
                                                 "Too many incoming connections (%u) from source %s, dropping connection.",
2527
                                                 p->n_ref, strnull(t));
2528
                                goto refuse;
×
2529
                        }
2530
                }
2531

2532
                r = socket_load_service_unit(s, cfd, &service);
109✔
2533
                if (ERRNO_IS_NEG_DISCONNECT(r))
109✔
2534
                        return;
2535
                if (r < 0 || UNIT_IS_LOAD_ERROR(service->load_state)) {
109✔
2536
                        log_unit_warning_errno(UNIT(s), r < 0 ? r : service->load_error,
×
2537
                                               "Failed to load connection service unit: %m");
2538
                        goto fail;
×
2539
                }
2540
                if (service->load_state == UNIT_MASKED) {
109✔
2541
                        log_unit_warning(UNIT(s), "Connection service unit is masked, refusing.");
×
2542
                        goto fail;
×
2543
                }
2544

2545
                s->n_accepted++;
109✔
2546

2547
                r = service_set_socket_fd(SERVICE(service), cfd, s, p, s->selinux_context_from_net);
218✔
2548
                if (ERRNO_IS_NEG_DISCONNECT(r))
109✔
2549
                        return;
2550
                if (r < 0) {
109✔
2551
                        log_unit_warning_errno(UNIT(s), r, "Failed to set socket on service: %m");
×
2552
                        goto fail;
×
2553
                }
2554

2555
                /* We passed ownership of the fd and socket peer to the service now. */
2556
                TAKE_FD(cfd);
109✔
2557
                TAKE_PTR(p);
109✔
2558

2559
                s->n_connections++;
109✔
2560

2561
                r = manager_add_job(UNIT(s)->manager, JOB_START, service, JOB_REPLACE, &error, /* ret= */ NULL);
109✔
2562
                if (r < 0) {
109✔
2563
                        /* We failed to activate the new service, but it still exists. Let's make sure the
2564
                         * service closes and forgets the connection fd again, immediately. */
2565
                        service_release_socket_fd(SERVICE(service));
×
2566
                        goto queue_error;
×
2567
                }
2568

2569
                /* Notify clients about changed counters */
2570
                unit_add_to_dbus_queue(UNIT(s));
109✔
2571
        }
2572

2573
        return;
2574

2575
refuse:
×
2576
        s->n_refused++;
×
2577
        return;
×
2578

2579
queue_error:
×
2580
        log_unit_warning_errno(UNIT(s), r, "Failed to queue service startup job%s: %s",
×
2581
                               cfd >= 0 && !ERRNO_IS_RESOURCE(r) ? " (Maybe the service is missing or is a template unit?)" : "",
2582
                               bus_error_message(&error, r));
2583

2584
fail:
×
2585
        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2586
}
2587

2588
static void socket_run_next(Socket *s) {
×
2589
        int r;
×
2590

2591
        assert(s);
×
2592
        assert(s->control_command);
×
2593
        assert(s->control_command->command_next);
×
2594

2595
        socket_unwatch_control_pid(s);
×
2596

2597
        s->control_command = s->control_command->command_next;
×
2598

2599
        r = socket_spawn(s, s->control_command, &s->control_pid);
×
2600
        if (r < 0) {
×
2601
                log_unit_warning_errno(UNIT(s), r, "Failed to spawn next task: %m");
×
2602

2603
                if (s->state == SOCKET_START_POST)
×
2604
                        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2605
                else if (s->state == SOCKET_STOP_POST)
×
2606
                        socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
×
2607
                else
2608
                        socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
×
2609
        }
2610
}
×
2611

2612
static int socket_start(Unit *u) {
3,559✔
2613
        Socket *s = ASSERT_PTR(SOCKET(u));
3,559✔
2614
        int r;
3,559✔
2615

2616
        assert(IN_SET(s->state, SOCKET_DEAD, SOCKET_FAILED));
3,559✔
2617

2618
        r = unit_acquire_invocation_id(u);
3,559✔
2619
        if (r < 0)
3,559✔
2620
                return r;
2621

2622
        s->result = SOCKET_SUCCESS;
3,559✔
2623
        exec_command_reset_status_list_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
3,559✔
2624

2625
        if (s->cgroup_runtime)
3,559✔
2626
                s->cgroup_runtime->reset_accounting = true;
3✔
2627

2628
        socket_enter_start_pre(s);
3,559✔
2629
        return 1;
3,559✔
2630
}
2631

2632
static int socket_stop(Unit *u) {
3,024✔
2633
        Socket *s = ASSERT_PTR(SOCKET(u));
3,024✔
2634

2635
        /* Already on it */
2636
        if (IN_SET(s->state,
3,024✔
2637
                   SOCKET_STOP_PRE,
2638
                   SOCKET_STOP_PRE_SIGTERM,
2639
                   SOCKET_STOP_PRE_SIGKILL,
2640
                   SOCKET_STOP_POST,
2641
                   SOCKET_FINAL_SIGTERM,
2642
                   SOCKET_FINAL_SIGKILL))
2643
                return 0;
2644

2645
        /* If there's already something running we go directly into
2646
         * kill mode. */
2647
        if (IN_SET(s->state,
3,024✔
2648
                   SOCKET_START_PRE,
2649
                   SOCKET_START_OPEN,
2650
                   SOCKET_START_CHOWN,
2651
                   SOCKET_START_POST)) {
UNCOV
2652
                socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
×
UNCOV
2653
                return -EAGAIN;
×
2654
        }
2655

2656
        /* If we are currently cleaning, then abort it, brutally. */
2657
        if (s->state == SOCKET_CLEANING) {
3,024✔
2658
                socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
×
2659
                return 0;
×
2660
        }
2661

2662
        assert(IN_SET(s->state, SOCKET_LISTENING, SOCKET_DEFERRED, SOCKET_RUNNING));
3,024✔
2663

2664
        socket_enter_stop_pre(s, SOCKET_SUCCESS);
3,024✔
2665
        return 1;
3,024✔
2666
}
2667

2668
static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
3,461✔
2669
        Socket *s = ASSERT_PTR(SOCKET(u));
3,461✔
2670
        int r;
3,461✔
2671

2672
        assert(f);
3,461✔
2673
        assert(fds);
3,461✔
2674

2675
        (void) serialize_item(f, "state", socket_state_to_string(s->state));
3,461✔
2676
        (void) serialize_item(f, "result", socket_result_to_string(s->result));
3,461✔
2677
        (void) serialize_item_format(f, "n-accepted", "%u", s->n_accepted);
3,461✔
2678
        (void) serialize_item_format(f, "n-refused", "%u", s->n_refused);
3,461✔
2679
        (void) serialize_pidref(f, fds, "control-pid", &s->control_pid);
3,461✔
2680

2681
        if (s->control_command_id >= 0)
3,461✔
2682
                (void) serialize_item(f, "control-command", socket_exec_command_to_string(s->control_command_id));
×
2683

2684
        LIST_FOREACH(port, p, s->ports) {
7,066✔
2685
                int copy;
3,605✔
2686

2687
                if (p->fd < 0)
3,605✔
2688
                        continue;
1,079✔
2689

2690
                copy = fdset_put_dup(fds, p->fd);
2,526✔
2691
                if (copy < 0)
2,526✔
2692
                        return log_unit_warning_errno(u, copy, "Failed to serialize socket fd: %m");
×
2693

2694
                if (p->type == SOCKET_SOCKET) {
2,526✔
2695
                        _cleanup_free_ char *t = NULL;
2,386✔
2696

2697
                        r = socket_address_print(&p->address, &t);
2,386✔
2698
                        if (r < 0)
2,386✔
2699
                                return log_unit_error_errno(u, r, "Failed to format socket address: %m");
×
2700

2701
                        if (socket_address_family(&p->address) == AF_NETLINK)
2,386✔
2702
                                (void) serialize_item_format(f, "netlink", "%i %s", copy, t);
119✔
2703
                        else
2704
                                (void) serialize_item_format(f, "socket", "%i %i %s", copy, p->address.type, t);
2,267✔
2705
                } else if (p->type == SOCKET_SPECIAL)
140✔
2706
                        (void) serialize_item_format(f, "special", "%i %s", copy, p->path);
18✔
2707
                else if (p->type == SOCKET_MQUEUE)
122✔
2708
                        (void) serialize_item_format(f, "mqueue", "%i %s", copy, p->path);
×
2709
                else if (p->type == SOCKET_USB_FUNCTION)
122✔
2710
                        (void) serialize_item_format(f, "ffs", "%i %s", copy, p->path);
×
2711
                else {
2712
                        assert(p->type == SOCKET_FIFO);
122✔
2713
                        (void) serialize_item_format(f, "fifo", "%i %s", copy, p->path);
122✔
2714
                }
2715
        }
2716

2717
        (void) serialize_ratelimit(f, "trigger-ratelimit", &s->trigger_limit);
3,461✔
2718

2719
        return 0;
3,461✔
2720
}
2721

2722
static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
15,789✔
2723
        Socket *s = ASSERT_PTR(SOCKET(u));
15,789✔
2724
        int r;
15,789✔
2725

2726
        assert(key);
15,789✔
2727
        assert(value);
15,789✔
2728

2729
        if (streq(key, "state")) {
15,789✔
2730
                SocketState state;
2,734✔
2731

2732
                state = socket_state_from_string(value);
2,734✔
2733
                if (state < 0)
2,734✔
2734
                        log_unit_debug(u, "Failed to parse state value: %s", value);
×
2735
                else
2736
                        s->deserialized_state = state;
2,734✔
2737
        } else if (streq(key, "result")) {
13,055✔
2738
                SocketResult f;
2,734✔
2739

2740
                f = socket_result_from_string(value);
2,734✔
2741
                if (f < 0)
2,734✔
2742
                        log_unit_debug(u, "Failed to parse result value: %s", value);
×
2743
                else if (f != SOCKET_SUCCESS)
2,734✔
2744
                        s->result = f;
×
2745

2746
        } else if (streq(key, "n-accepted")) {
10,321✔
2747
                unsigned k;
2,734✔
2748

2749
                if (safe_atou(value, &k) < 0)
2,734✔
2750
                        log_unit_debug(u, "Failed to parse n-accepted value: %s", value);
×
2751
                else
2752
                        s->n_accepted += k;
2,734✔
2753
        } else if (streq(key, "n-refused")) {
7,587✔
2754
                unsigned k;
2,734✔
2755

2756
                if (safe_atou(value, &k) < 0)
2,734✔
2757
                        log_unit_debug(u, "Failed to parse n-refused value: %s", value);
×
2758
                else
2759
                        s->n_refused += k;
2,734✔
2760
        } else if (streq(key, "control-pid")) {
4,853✔
2761

2762
                if (!pidref_is_set(&s->control_pid))
15,789✔
2763
                        (void) deserialize_pidref(fds, value, &s->control_pid);
×
2764

2765
        } else if (streq(key, "control-command")) {
4,853✔
2766
                SocketExecCommand id;
×
2767

2768
                id = socket_exec_command_from_string(value);
×
2769
                if (id < 0)
×
2770
                        log_unit_debug(u, "Failed to parse exec-command value: %s", value);
×
2771
                else {
2772
                        s->control_command_id = id;
×
2773
                        s->control_command = s->exec_command[id];
×
2774
                }
2775
        } else if (streq(key, "fifo")) {
4,853✔
2776
                _cleanup_free_ char *fdv = NULL;
100✔
2777
                bool found = false;
100✔
2778
                int fd;
100✔
2779

2780
                r = extract_first_word(&value, &fdv, NULL, 0);
100✔
2781
                if (r <= 0) {
100✔
2782
                        log_unit_debug(u, "Failed to parse fifo value: %s", value);
×
2783
                        return 0;
×
2784
                }
2785

2786
                fd = parse_fd(fdv);
100✔
2787
                if (fd < 0 || !fdset_contains(fds, fd)) {
100✔
2788
                        log_unit_debug(u, "Invalid fifo value: %s", fdv);
×
2789
                        return 0;
×
2790
                }
2791

2792
                LIST_FOREACH(port, p, s->ports)
150✔
2793
                        if (p->fd < 0 &&
150✔
2794
                            p->type == SOCKET_FIFO &&
100✔
2795
                            path_equal_or_inode_same(p->path, value, 0)) {
100✔
2796
                                p->fd = fdset_remove(fds, fd);
100✔
2797
                                found = true;
100✔
2798
                                break;
100✔
2799
                        }
2800
                if (!found)
100✔
2801
                        log_unit_debug(u, "No matching fifo socket found: %s", value);
×
2802

2803
        } else if (streq(key, "special")) {
4,753✔
2804
                _cleanup_free_ char *fdv = NULL;
15✔
2805
                bool found = false;
15✔
2806
                int fd;
15✔
2807

2808
                r = extract_first_word(&value, &fdv, NULL, 0);
15✔
2809
                if (r <= 0) {
15✔
2810
                        log_unit_debug(u, "Failed to parse special value: %s", value);
×
2811
                        return 0;
×
2812
                }
2813

2814
                fd = parse_fd(fdv);
15✔
2815
                if (fd < 0 || !fdset_contains(fds, fd)) {
15✔
2816
                        log_unit_debug(u, "Invalid special value: %s", fdv);
×
2817
                        return 0;
×
2818
                }
2819

2820
                LIST_FOREACH(port, p, s->ports)
15✔
2821
                        if (p->fd < 0 &&
15✔
2822
                            p->type == SOCKET_SPECIAL &&
15✔
2823
                            path_equal_or_inode_same(p->path, value, 0)) {
15✔
2824
                                p->fd = fdset_remove(fds, fd);
15✔
2825
                                found = true;
15✔
2826
                                break;
15✔
2827
                        }
2828
                if (!found)
15✔
2829
                        log_unit_debug(u, "No matching special socket found: %s", value);
×
2830

2831
        } else if (streq(key, "mqueue")) {
4,738✔
2832
                _cleanup_free_ char *fdv = NULL;
×
2833
                bool found = false;
×
2834
                int fd;
×
2835

2836
                r = extract_first_word(&value, &fdv, NULL, 0);
×
2837
                if (r <= 0) {
×
2838
                        log_unit_debug(u, "Failed to parse mqueue value: %s", value);
×
2839
                        return 0;
×
2840
                }
2841

2842
                fd = parse_fd(fdv);
×
2843
                if (fd < 0 || !fdset_contains(fds, fd)) {
×
2844
                        log_unit_debug(u, "Invalid mqueue value: %s", fdv);
×
2845
                        return 0;
×
2846
                }
2847

2848
                LIST_FOREACH(port, p, s->ports)
×
2849
                        if (p->fd < 0 &&
×
2850
                            p->type == SOCKET_MQUEUE &&
×
2851
                            streq(p->path, value)) {
×
2852
                                p->fd = fdset_remove(fds, fd);
×
2853
                                found = true;
×
2854
                                break;
×
2855
                        }
2856
                if (!found)
×
2857
                        log_unit_debug(u, "No matching mqueue socket found: %s", value);
×
2858

2859
        } else if (streq(key, "socket")) {
4,738✔
2860
                _cleanup_free_ char *fdv = NULL, *typev = NULL;
1,918✔
2861
                bool found = false;
1,918✔
2862
                int fd, type;
1,918✔
2863

2864
                r = extract_first_word(&value, &fdv, NULL, 0);
1,918✔
2865
                if (r <= 0) {
1,918✔
2866
                        log_unit_debug(u, "Failed to parse socket fd from value: %s", value);
×
2867
                        return 0;
×
2868
                }
2869

2870
                fd = parse_fd(fdv);
1,918✔
2871
                if (fd < 0 || !fdset_contains(fds, fd)) {
1,918✔
2872
                        log_unit_debug(u, "Invalid socket fd: %s", fdv);
×
2873
                        return 0;
×
2874
                }
2875

2876
                r = extract_first_word(&value, &typev, NULL, 0);
1,918✔
2877
                if (r <= 0) {
1,918✔
2878
                        log_unit_debug(u, "Failed to parse socket type from value: %s", value);
×
2879
                        return 0;
×
2880
                }
2881

2882
                if (safe_atoi(typev, &type) < 0 || type < 0) {
1,918✔
2883
                        log_unit_debug(u, "Invalid socket type: %s", typev);
×
2884
                        return 0;
×
2885
                }
2886

2887
                LIST_FOREACH(port, p, s->ports)
1,971✔
2888
                        if (p->fd < 0 &&
3,889✔
2889
                            socket_address_is(&p->address, value, type)) {
1,918✔
2890
                                p->fd = fdset_remove(fds, fd);
1,918✔
2891
                                found = true;
1,918✔
2892
                                break;
1,918✔
2893
                        }
2894
                if (!found)
1,918✔
2895
                        log_unit_debug(u, "No matching %s socket found: %s",
×
2896
                                       socket_address_type_to_string(type), value);
2897

2898
        } else if (streq(key, "netlink")) {
2,820✔
2899
                _cleanup_free_ char *fdv = NULL;
86✔
2900
                bool found = false;
86✔
2901
                int fd;
86✔
2902

2903
                r = extract_first_word(&value, &fdv, NULL, 0);
86✔
2904
                if (r <= 0) {
86✔
2905
                        log_unit_debug(u, "Failed to parse socket value: %s", value);
×
2906
                        return 0;
×
2907
                }
2908

2909
                fd = parse_fd(fdv);
86✔
2910
                if (fd < 0 || !fdset_contains(fds, fd)) {
86✔
2911
                        log_unit_debug(u, "Invalid socket value: %s", fdv);
×
2912
                        return 0;
×
2913
                }
2914

2915
                LIST_FOREACH(port, p, s->ports)
86✔
2916
                        if (p->fd < 0 &&
172✔
2917
                            socket_address_is_netlink(&p->address, value)) {
86✔
2918
                                p->fd = fdset_remove(fds, fd);
86✔
2919
                                found = true;
86✔
2920
                                break;
86✔
2921
                        }
2922
                if (!found)
86✔
2923
                        log_unit_debug(u, "No matching netlink socket found: %s", value);
×
2924

2925
        } else if (streq(key, "ffs")) {
2,734✔
2926
                _cleanup_free_ char *fdv = NULL;
×
2927
                bool found = false;
×
2928
                int fd;
×
2929

2930
                r = extract_first_word(&value, &fdv, NULL, 0);
×
2931
                if (r <= 0) {
×
2932
                        log_unit_debug(u, "Failed to parse ffs value: %s", value);
×
2933
                        return 0;
×
2934
                }
2935

2936
                fd = parse_fd(fdv);
×
2937
                if (fd < 0 || !fdset_contains(fds, fd)) {
×
2938
                        log_unit_debug(u, "Invalid ffs value: %s", fdv);
×
2939
                        return 0;
×
2940
                }
2941

2942
                LIST_FOREACH(port, p, s->ports)
×
2943
                        if (p->fd < 0 &&
×
2944
                            p->type == SOCKET_USB_FUNCTION &&
×
2945
                            path_equal_or_inode_same(p->path, value, 0)) {
×
2946
                                p->fd = fdset_remove(fds, fd);
×
2947
                                found = true;
×
2948
                                break;
×
2949
                        }
2950
                if (!found)
×
2951
                        log_unit_debug(u, "No matching ffs socket found: %s", value);
×
2952

2953
        } else if (streq(key, "trigger-ratelimit"))
2,734✔
2954
                deserialize_ratelimit(&s->trigger_limit, key, value);
2,734✔
2955
        else
2956
                log_unit_debug(UNIT(s), "Unknown serialization key: %s", key);
×
2957

2958
        return 0;
2959
}
2960

2961
static void socket_distribute_fds(Unit *u, FDSet *fds) {
851✔
2962
        Socket *s = ASSERT_PTR(SOCKET(u));
851✔
2963

2964
        LIST_FOREACH(port, p, s->ports) {
1,740✔
2965
                int fd;
889✔
2966

2967
                if (p->type != SOCKET_SOCKET)
889✔
2968
                        continue;
43✔
2969

2970
                if (p->fd >= 0)
846✔
2971
                        continue;
528✔
2972

2973
                FDSET_FOREACH(fd, fds) {
840✔
2974
                        if (socket_address_matches_fd(&p->address, fd)) {
522✔
2975
                                p->fd = fdset_remove(fds, fd);
×
2976
                                s->deserialized_state = SOCKET_LISTENING;
×
2977
                                break;
×
2978
                        }
2979
                }
2980
        }
2981
}
851✔
2982

2983
static UnitActiveState socket_active_state(Unit *u) {
608,862✔
2984
        Socket *s = ASSERT_PTR(SOCKET(u));
608,862✔
2985

2986
        return state_translation_table[s->state];
608,862✔
2987
}
2988

2989
static const char *socket_sub_state_to_string(Unit *u) {
5,101✔
2990
        Socket *s = ASSERT_PTR(SOCKET(u));
5,101✔
2991

2992
        return socket_state_to_string(s->state);
5,101✔
2993
}
2994

2995
int socket_port_to_address(const SocketPort *p, char **ret) {
92✔
2996
        _cleanup_free_ char *address = NULL;
92✔
2997
        int r;
92✔
2998

2999
        assert(p);
92✔
3000
        assert(ret);
92✔
3001

3002
        switch (p->type) {
92✔
3003
                case SOCKET_SOCKET: {
88✔
3004
                        r = socket_address_print(&p->address, &address);
88✔
3005
                        if (r < 0)
88✔
3006
                                return r;
3007

3008
                        break;
3009
                }
3010

3011
                case SOCKET_SPECIAL:
4✔
3012
                case SOCKET_MQUEUE:
3013
                case SOCKET_FIFO:
3014
                case SOCKET_USB_FUNCTION:
3015
                        address = strdup(p->path);
4✔
3016
                        if (!address)
4✔
3017
                                return -ENOMEM;
3018
                        break;
3019

3020
                default:
×
3021
                        assert_not_reached();
×
3022
        }
3023

3024
        *ret = TAKE_PTR(address);
92✔
3025

3026
        return 0;
92✔
3027
}
3028

3029
const char* socket_port_type_to_string(SocketPort *p) {
92✔
3030
        assert(p);
92✔
3031

3032
        switch (p->type) {
92✔
3033

3034
        case SOCKET_SOCKET:
88✔
3035

3036
                switch (p->address.type) {
88✔
3037

3038
                case SOCK_STREAM:
3039
                        return "Stream";
3040

3041
                case SOCK_DGRAM:
6✔
3042
                        return "Datagram";
6✔
3043

3044
                case SOCK_SEQPACKET:
4✔
3045
                        return "SequentialPacket";
4✔
3046

3047
                case SOCK_RAW:
6✔
3048
                        if (socket_address_family(&p->address) == AF_NETLINK)
6✔
3049
                                return "Netlink";
3050

3051
                        _fallthrough_;
×
3052
                default:
3053
                        return NULL;
×
3054
                }
3055

3056
        case SOCKET_SPECIAL:
3057
                return "Special";
3058

3059
        case SOCKET_MQUEUE:
×
3060
                return "MessageQueue";
×
3061

3062
        case SOCKET_FIFO:
4✔
3063
                return "FIFO";
4✔
3064

3065
        case SOCKET_USB_FUNCTION:
×
3066
                return "USBFunction";
×
3067

3068
        default:
×
3069
                return NULL;
×
3070
        }
3071
}
3072

3073
SocketType socket_port_type_from_string(const char *s) {
2✔
3074
        assert(s);
2✔
3075

3076
        if (STR_IN_SET(s, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2✔
3077
                return SOCKET_SOCKET;
2✔
3078
        else if (streq(s, "Special"))
2✔
3079
                return SOCKET_SPECIAL;
3080
        else if (streq(s, "MessageQueue"))
2✔
3081
                return SOCKET_MQUEUE;
3082
        else if (streq(s, "FIFO"))
2✔
3083
                return SOCKET_FIFO;
3084
        else if (streq(s, "USBFunction"))
×
3085
                return SOCKET_USB_FUNCTION;
3086
        else
3087
                return _SOCKET_TYPE_INVALID;
×
3088
}
3089

3090
static bool socket_may_gc(Unit *u) {
16,501✔
3091
        Socket *s = ASSERT_PTR(SOCKET(u));
16,501✔
3092

3093
        return s->n_connections == 0;
16,501✔
3094
}
3095

3096
static int socket_accept_do(Socket *s, int fd) {
111✔
3097
        int cfd;
111✔
3098

3099
        assert(s);
111✔
3100
        assert(fd >= 0);
111✔
3101

3102
        cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
111✔
3103
        if (cfd < 0)
111✔
3104
                /* Convert transient network errors into clean and well-defined EAGAIN */
3105
                return ERRNO_IS_ACCEPT_AGAIN(errno) ? -EAGAIN : -errno;
×
3106

3107
        return cfd;
3108
}
3109

3110
static int socket_accept_in_cgroup(Socket *s, SocketPort *p, int fd) {
109✔
3111
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
×
3112
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
109✔
3113
        int cfd, r;
109✔
3114

3115
        assert(s);
109✔
3116
        assert(p);
109✔
3117
        assert(fd >= 0);
109✔
3118

3119
        /* Similar to socket_address_listen_in_cgroup(), but for accept() rather than socket(): make sure that any
3120
         * connection socket is also properly associated with the cgroup. */
3121

3122
        if (!IN_SET(p->address.sockaddr.sa.sa_family, AF_INET, AF_INET6))
109✔
3123
                goto shortcut;
109✔
3124

3125
        if (bpf_program_supported() <= 0)
×
3126
                goto shortcut;
×
3127

3128
        if (socketpair(AF_UNIX, SOCK_SEQPACKET|SOCK_CLOEXEC, 0, pair) < 0)
×
3129
                return log_unit_error_errno(UNIT(s), errno, "Failed to create communication channel: %m");
×
3130

3131
        r = unit_fork_helper_process(UNIT(s), "(sd-accept)", /* into_cgroup= */ true, &pid);
×
3132
        if (r < 0)
2✔
3133
                return log_unit_error_errno(UNIT(s), r, "Failed to fork off accept stub process: %m");
×
3134
        if (r == 0) {
2✔
3135
                /* Child */
3136

3137
                pair[0] = safe_close(pair[0]);
2✔
3138

3139
                cfd = socket_accept_do(s, fd);
2✔
3140
                if (cfd == -EAGAIN) /* spurious accept() */
2✔
3141
                        _exit(EXIT_SUCCESS);
×
3142
                if (cfd < 0) {
2✔
3143
                        log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
×
3144
                        _exit(EXIT_FAILURE);
×
3145
                }
3146

3147
                r = send_one_fd(pair[1], cfd, 0);
2✔
3148
                if (r < 0) {
2✔
3149
                        log_unit_error_errno(UNIT(s), r, "Failed to send connection socket to parent: %m");
×
3150
                        _exit(EXIT_FAILURE);
×
3151
                }
3152

3153
                _exit(EXIT_SUCCESS);
2✔
3154
        }
3155

3156
        pair[1] = safe_close(pair[1]);
×
3157
        cfd = receive_one_fd(pair[0], 0);
×
3158

3159
        /* We synchronously wait for the helper, as it shouldn't be slow */
3160
        r = pidref_wait_for_terminate_and_check("(sd-accept)", &pid, WAIT_LOG_ABNORMAL);
×
3161
        if (r < 0) {
×
3162
                safe_close(cfd);
×
3163
                return r;
3164
        }
3165

3166
        /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3167
         * this is a spurious accept(), let's convert that back to EAGAIN here. */
3168
        if (cfd == -EIO && r == EXIT_SUCCESS)
×
3169
                return -EAGAIN;
3170
        if (cfd < 0)
×
3171
                return log_unit_error_errno(UNIT(s), cfd, "Failed to receive connection socket: %m");
×
3172

3173
        return cfd;
3174

3175
shortcut:
109✔
3176
        cfd = socket_accept_do(s, fd);
109✔
3177
        if (cfd == -EAGAIN) /* spurious accept(), skip it silently */
109✔
3178
                return -EAGAIN;
3179
        if (cfd < 0)
109✔
3180
                return log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
×
3181

3182
        return cfd;
3183
}
3184

3185
static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
295✔
3186
        SocketPort *p = ASSERT_PTR(userdata);
295✔
3187
        int cfd = -EBADF;
295✔
3188

3189
        assert(fd >= 0);
295✔
3190

3191
        if (p->socket->state != SOCKET_LISTENING)
295✔
3192
                return 0;
3193

3194
        log_unit_debug(UNIT(p->socket), "Incoming traffic");
295✔
3195

3196
        if (revents != EPOLLIN) {
295✔
3197
                if (revents & EPOLLHUP)
×
3198
                        log_unit_error(UNIT(p->socket), "Got POLLHUP on a listening socket. The service probably invoked shutdown() on it, and should better not do that.");
×
3199
                else
3200
                        log_unit_error(UNIT(p->socket), "Got unexpected poll event (0x%x) on socket.", revents);
×
3201
                goto fail;
×
3202
        }
3203

3204
        if (p->socket->accept &&
295✔
3205
            p->type == SOCKET_SOCKET &&
218✔
3206
            socket_address_can_accept(&p->address)) {
109✔
3207

3208
                cfd = socket_accept_in_cgroup(p->socket, p, fd);
109✔
3209
                if (cfd == -EAGAIN) /* Spurious accept() */
109✔
3210
                        return 0;
3211
                if (cfd < 0)
109✔
3212
                        goto fail;
×
3213

3214
                socket_apply_socket_options(p->socket, p, cfd);
109✔
3215
        }
3216

3217
        socket_enter_running(p->socket, cfd);
295✔
3218
        return 0;
295✔
3219

3220
fail:
×
3221
        socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
×
3222
        return 0;
×
3223
}
3224

3225
static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
235✔
3226
        Socket *s = ASSERT_PTR(SOCKET(u));
235✔
3227
        SocketResult f;
235✔
3228

3229
        assert(pid >= 0);
235✔
3230

3231
        if (pid != s->control_pid.pid)
235✔
3232
                return;
3233

3234
        pidref_done(&s->control_pid);
235✔
3235

3236
        if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
235✔
3237
                f = SOCKET_SUCCESS;
UNCOV
3238
        else if (code == CLD_EXITED)
×
3239
                f = SOCKET_FAILURE_EXIT_CODE;
UNCOV
3240
        else if (code == CLD_KILLED)
×
3241
                f = SOCKET_FAILURE_SIGNAL;
3242
        else if (code == CLD_DUMPED)
×
3243
                f = SOCKET_FAILURE_CORE_DUMP;
3244
        else
3245
                assert_not_reached();
×
3246

3247
        if (s->control_command) {
235✔
3248
                exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
199✔
3249

3250
                if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
199✔
3251
                        f = SOCKET_SUCCESS;
199✔
3252
        }
3253

3254
        unit_log_process_exit(
235✔
3255
                        u,
3256
                        "Control process",
3257
                        socket_exec_command_to_string(s->control_command_id),
3258
                        f == SOCKET_SUCCESS,
3259
                        code, status);
3260

3261
        if (s->result == SOCKET_SUCCESS)
235✔
3262
                s->result = f;
235✔
3263

3264
        if (s->control_command &&
235✔
3265
            s->control_command->command_next &&
199✔
3266
            f == SOCKET_SUCCESS) {
3267

3268
                log_unit_debug(u, "Running next command for state %s", socket_state_to_string(s->state));
×
3269
                socket_run_next(s);
×
3270
        } else {
3271
                s->control_command = NULL;
235✔
3272
                s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
235✔
3273

3274
                /* No further commands for this step, so let's figure
3275
                 * out what to do next */
3276

3277
                log_unit_debug(u, "Got final SIGCHLD for state %s", socket_state_to_string(s->state));
235✔
3278

3279
                switch (s->state) {
235✔
3280

3281
                case SOCKET_START_PRE:
×
3282
                        if (f == SOCKET_SUCCESS)
×
3283
                                socket_enter_start_open(s);
×
3284
                        else
3285
                                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
×
3286
                        break;
3287

3288
                case SOCKET_START_CHOWN:
36✔
3289
                        if (f == SOCKET_SUCCESS)
36✔
3290
                                socket_enter_start_post(s);
36✔
3291
                        else
3292
                                socket_enter_stop_pre(s, f);
×
3293
                        break;
3294

3295
                case SOCKET_START_POST:
196✔
3296
                        if (f == SOCKET_SUCCESS)
196✔
3297
                                socket_enter_listening(s);
196✔
3298
                        else
3299
                                socket_enter_stop_pre(s, f);
×
3300
                        break;
3301

3302
                case SOCKET_STOP_PRE:
3✔
3303
                case SOCKET_STOP_PRE_SIGTERM:
3304
                case SOCKET_STOP_PRE_SIGKILL:
3305
                        socket_enter_stop_post(s, f);
3✔
3306
                        break;
3✔
3307

3308
                case SOCKET_STOP_POST:
×
3309
                case SOCKET_FINAL_SIGTERM:
3310
                case SOCKET_FINAL_SIGKILL:
3311
                        socket_enter_dead(s, f);
×
3312
                        break;
×
3313

3314
                case SOCKET_CLEANING:
×
3315

3316
                        if (s->clean_result == SOCKET_SUCCESS)
×
3317
                                s->clean_result = f;
×
3318

3319
                        socket_enter_dead(s, SOCKET_SUCCESS);
×
3320
                        break;
×
3321

3322
                default:
×
3323
                        assert_not_reached();
×
3324
                }
3325
        }
3326

3327
        /* Notify clients about changed exit status */
3328
        unit_add_to_dbus_queue(u);
235✔
3329
}
3330

3331
static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
×
3332
        Socket *s = ASSERT_PTR(SOCKET(userdata));
×
3333

3334
        assert(s->timer_event_source == source);
×
3335

3336
        switch (s->state) {
×
3337

3338
        case SOCKET_START_PRE:
3339
                log_unit_warning(UNIT(s), "Starting timed out. Terminating.");
×
3340
                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
×
3341
                break;
×
3342

3343
        case SOCKET_START_CHOWN:
3344
        case SOCKET_START_POST:
3345
                log_unit_warning(UNIT(s), "Starting timed out. Stopping.");
×
3346
                socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
×
3347
                break;
×
3348

3349
        case SOCKET_DEFERRED:
3350
                log_unit_warning(UNIT(s), "DeferTriggerMaxSec= elapsed. Stopping.");
×
3351
                socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
×
3352
                break;
×
3353

3354
        case SOCKET_STOP_PRE:
3355
                log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
×
3356
                socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
×
3357
                break;
×
3358

3359
        case SOCKET_STOP_PRE_SIGTERM:
×
3360
                if (s->kill_context.send_sigkill) {
×
3361
                        log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
×
3362
                        socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
×
3363
                } else {
3364
                        log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL. Ignoring.");
×
3365
                        socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
×
3366
                }
3367
                break;
3368

3369
        case SOCKET_STOP_PRE_SIGKILL:
3370
                log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
×
3371
                socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
×
3372
                break;
×
3373

3374
        case SOCKET_STOP_POST:
3375
                log_unit_warning(UNIT(s), "Stopping timed out (2). Terminating.");
×
3376
                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
×
3377
                break;
×
3378

3379
        case SOCKET_FINAL_SIGTERM:
×
3380
                if (s->kill_context.send_sigkill) {
×
3381
                        log_unit_warning(UNIT(s), "Stopping timed out (2). Killing.");
×
3382
                        socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
×
3383
                } else {
3384
                        log_unit_warning(UNIT(s), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
×
3385
                        socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
×
3386
                }
3387
                break;
3388

3389
        case SOCKET_FINAL_SIGKILL:
3390
                log_unit_warning(UNIT(s), "Still around after SIGKILL (2). Entering failed mode.");
×
3391
                socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
×
3392
                break;
×
3393

3394
        case SOCKET_CLEANING:
3395
                log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
×
3396

3397
                if (s->clean_result == SOCKET_SUCCESS)
×
3398
                        s->clean_result = SOCKET_FAILURE_TIMEOUT;
×
3399

3400
                socket_enter_signal(s, SOCKET_FINAL_SIGKILL, 0);
×
3401
                break;
×
3402

3403
        default:
×
3404
                assert_not_reached();
×
3405
        }
3406

3407
        return 0;
×
3408
}
3409

3410
int socket_collect_fds(Socket *s, int **ret) {
669✔
3411
        size_t n = 0, k = 0;
669✔
3412

3413
        assert(s);
669✔
3414
        assert(ret);
669✔
3415

3416
        /* Called from the service code for requesting our fds */
3417

3418
        LIST_FOREACH(port, p, s->ports) {
1,374✔
3419
                if (p->fd >= 0)
705✔
3420
                        n++;
686✔
3421
                n += p->n_auxiliary_fds;
705✔
3422
        }
3423

3424
        if (n == 0) {
669✔
3425
                *ret = NULL;
19✔
3426
                return 0;
19✔
3427
        }
3428

3429
        int *fds = new(int, n);
650✔
3430
        if (!fds)
650✔
3431
                return -ENOMEM;
3432

3433
        LIST_FOREACH(port, p, s->ports) {
1,336✔
3434
                if (p->fd >= 0)
686✔
3435
                        fds[k++] = p->fd;
686✔
3436
                FOREACH_ARRAY(i, p->auxiliary_fds, p->n_auxiliary_fds)
686✔
3437
                        fds[k++] = *i;
×
3438
        }
3439

3440
        assert(k == n);
650✔
3441

3442
        *ret = fds;
650✔
3443
        return (int) n;
650✔
3444
}
3445

3446
static void socket_reset_failed(Unit *u) {
44✔
3447
        Socket *s = SOCKET(u);
44✔
3448

3449
        assert(s);
×
3450

3451
        if (s->state == SOCKET_FAILED)
44✔
3452
                socket_set_state(s, SOCKET_DEAD);
×
3453

3454
        s->result = SOCKET_SUCCESS;
44✔
3455
        s->clean_result = SOCKET_SUCCESS;
44✔
3456
}
44✔
3457

3458
void socket_connection_unref(Socket *s) {
109✔
3459
        assert(s);
109✔
3460

3461
        /* The service is dead. Yay!
3462
         *
3463
         * This is strictly for one-instance-per-connection
3464
         * services. */
3465

3466
        assert(s->n_connections > 0);
109✔
3467
        s->n_connections--;
109✔
3468

3469
        log_unit_debug(UNIT(s), "One connection closed, %u left.", s->n_connections);
109✔
3470
}
109✔
3471

3472
static void socket_trigger_notify(Unit *u, Unit *other) {
4,475✔
3473
        Socket *s = ASSERT_PTR(SOCKET(u));
4,475✔
3474

3475
        assert(other);
4,475✔
3476

3477
        /* Filter out invocations with bogus state */
3478
        assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
4,475✔
3479

3480
        Service *service = ASSERT_PTR(SERVICE(other));
4,475✔
3481

3482
        /* Don't propagate state changes from the service if we are already down */
3483
        if (!IN_SET(s->state, SOCKET_RUNNING, SOCKET_LISTENING, SOCKET_DEFERRED))
4,475✔
3484
                return;
3485

3486
        /* We don't care for the service state if we are in Accept=yes mode */
3487
        if (s->accept)
3,914✔
3488
                return;
3489

3490
        /* Propagate start limit hit state */
3491
        if (other->start_limit_hit) {
3,574✔
3492
                socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT);
×
3493
                return;
×
3494
        }
3495

3496
        /* Don't propagate anything if there's still a job queued */
3497
        if (other->job)
3,574✔
3498
                return;
3499

3500
        if (!SOCKET_SERVICE_IS_ACTIVE(service, /* allow_finalize= */ true))
2,683✔
3501
                socket_enter_listening(s);
849✔
3502

3503
        if (SERVICE(other)->state == SERVICE_RUNNING)
2,683✔
3504
                socket_set_state(s, SOCKET_RUNNING);
1,741✔
3505
}
3506

3507
static void socket_handoff_timestamp(
398✔
3508
                Unit *u,
3509
                const struct ucred *ucred,
3510
                const dual_timestamp *ts) {
3511

3512
        Socket *s = ASSERT_PTR(SOCKET(u));
398✔
3513

3514
        assert(ucred);
398✔
3515
        assert(ts);
398✔
3516

3517
        if (s->control_pid.pid == ucred->pid && s->control_command) {
398✔
3518
                exec_status_handoff(&s->control_command->exec_status, ucred, ts);
398✔
3519
                unit_add_to_dbus_queue(u);
398✔
3520
        }
3521
}
398✔
3522

3523
static int socket_get_timeout(Unit *u, usec_t *timeout) {
×
3524
        Socket *s = ASSERT_PTR(SOCKET(u));
×
3525
        usec_t t;
×
3526
        int r;
×
3527

3528
        assert(timeout);
×
3529

3530
        if (!s->timer_event_source)
×
3531
                return 0;
×
3532

3533
        r = sd_event_source_get_time(s->timer_event_source, &t);
×
3534
        if (r < 0)
×
3535
                return r;
3536
        if (t == USEC_INFINITY)
×
3537
                return 0;
3538

3539
        *timeout = t;
×
3540
        return 1;
×
3541
}
3542

3543
const char* socket_fdname(Socket *s) {
891✔
3544
        assert(s);
891✔
3545

3546
        /* Returns the name to use for $LISTEN_FDNAMES. If the user didn't specify anything specifically,
3547
         * use the socket unit's name as fallback for Accept=no sockets, "connection" otherwise. */
3548

3549
        if (s->fdname)
891✔
3550
                return s->fdname;
3551

3552
        if (s->accept)
420✔
3553
                return "connection";
3554

3555
        return UNIT(s)->id;
403✔
3556
}
3557

3558
static PidRef* socket_control_pid(Unit *u) {
6,458✔
3559
        return &ASSERT_PTR(SOCKET(u))->control_pid;
12,916✔
3560
}
3561

3562
static int socket_clean(Unit *u, ExecCleanMask mask) {
×
3563
        Socket *s = ASSERT_PTR(SOCKET(u));
×
3564
        _cleanup_strv_free_ char **l = NULL;
×
3565
        int r;
×
3566

3567
        assert(mask != 0);
×
3568

3569
        if (s->state != SOCKET_DEAD)
×
3570
                return -EBUSY;
3571

3572
        r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
×
3573
        if (r < 0)
×
3574
                return r;
3575

3576
        if (strv_isempty(l))
×
3577
                return -EUNATCH;
3578

3579
        socket_unwatch_control_pid(s);
×
3580
        s->clean_result = SOCKET_SUCCESS;
×
3581
        s->control_command = NULL;
×
3582
        s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
×
3583

3584
        r = socket_arm_timer(s, /* relative= */ true, s->exec_context.timeout_clean_usec);
×
3585
        if (r < 0) {
×
3586
                log_unit_warning_errno(u, r, "Failed to install timer: %m");
×
3587
                goto fail;
×
3588
        }
3589

3590
        r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
×
3591
        if (r < 0) {
×
3592
                log_unit_warning_errno(u, r, "Failed to spawn cleaning task: %m");
×
3593
                goto fail;
×
3594
        }
3595

3596
        socket_set_state(s, SOCKET_CLEANING);
×
3597
        return 0;
3598

3599
fail:
×
3600
        s->clean_result = SOCKET_FAILURE_RESOURCES;
×
3601
        s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
×
3602
        return r;
×
3603
}
3604

3605
static int socket_can_clean(Unit *u, ExecCleanMask *ret) {
101✔
3606
        Socket *s = ASSERT_PTR(SOCKET(u));
101✔
3607

3608
        return exec_context_get_clean_mask(&s->exec_context, ret);
101✔
3609
}
3610

3611
static int socket_test_startable(Unit *u) {
3,559✔
3612
        Socket *s = ASSERT_PTR(SOCKET(u));
3,559✔
3613
        int r;
3,559✔
3614

3615
        /* It is already being started. */
3616
        if (IN_SET(s->state,
3,559✔
3617
                   SOCKET_START_PRE,
3618
                   SOCKET_START_OPEN,
3619
                   SOCKET_START_CHOWN,
3620
                   SOCKET_START_POST))
3621
                return false;
3622

3623
        /* Cannot run this without the service being around */
3624
        if (UNIT_ISSET(s->service)) {
3,559✔
3625
                Service *service = ASSERT_PTR(SERVICE(UNIT_DEREF(s->service)));
2,759✔
3626

3627
                if (UNIT(service)->load_state != UNIT_LOADED)
2,759✔
3628
                        return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
×
3629
                                                    "Socket service %s not loaded, refusing.", UNIT(service)->id);
3630

3631
                /* If the service is already active we cannot start the socket */
3632
                if (SOCKET_SERVICE_IS_ACTIVE(service, /* allow_finalize= */ false))
2,759✔
3633
                        return log_unit_error_errno(u, SYNTHETIC_ERRNO(EBUSY),
×
3634
                                                    "Socket service %s already active, refusing.", UNIT(service)->id);
3635
        }
3636

3637
        r = unit_test_start_limit(u);
3,559✔
3638
        if (r < 0) {
3,559✔
3639
                socket_enter_dead(s, SOCKET_FAILURE_START_LIMIT_HIT);
×
3640
                return r;
×
3641
        }
3642

3643
        return true;
3644
}
3645

3646
static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
3647
        [SOCKET_EXEC_START_PRE]   = "ExecStartPre",
3648
        [SOCKET_EXEC_START_CHOWN] = "ExecStartChown",
3649
        [SOCKET_EXEC_START_POST]  = "ExecStartPost",
3650
        [SOCKET_EXEC_STOP_PRE]    = "ExecStopPre",
3651
        [SOCKET_EXEC_STOP_POST]   = "ExecStopPost",
3652
};
3653

3654
DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
295✔
3655

3656
static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
3657
        [SOCKET_SUCCESS]                         = "success",
3658
        [SOCKET_FAILURE_RESOURCES]               = "resources",
3659
        [SOCKET_FAILURE_TIMEOUT]                 = "timeout",
3660
        [SOCKET_FAILURE_EXIT_CODE]               = "exit-code",
3661
        [SOCKET_FAILURE_SIGNAL]                  = "signal",
3662
        [SOCKET_FAILURE_CORE_DUMP]               = "core-dump",
3663
        [SOCKET_FAILURE_START_LIMIT_HIT]         = "start-limit-hit",
3664
        [SOCKET_FAILURE_TRIGGER_LIMIT_HIT]       = "trigger-limit-hit",
3665
        [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT] = "service-start-limit-hit",
3666
};
3667

3668
DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
10,832✔
3669

3670
static const char* const socket_timestamping_table[_SOCKET_TIMESTAMPING_MAX] = {
3671
        [SOCKET_TIMESTAMPING_OFF] = "off",
3672
        [SOCKET_TIMESTAMPING_US]  = "us",
3673
        [SOCKET_TIMESTAMPING_NS]  = "ns",
3674
};
3675

3676
DEFINE_STRING_TABLE_LOOKUP(socket_timestamping, SocketTimestamping);
321✔
3677

3678
SocketTimestamping socket_timestamping_from_string_harder(const char *s) {
231✔
3679
        SocketTimestamping t;
231✔
3680
        int r;
231✔
3681

3682
        if (!s)
231✔
3683
                return _SOCKET_TIMESTAMPING_INVALID;
3684

3685
        t = socket_timestamping_from_string(s);
231✔
3686
        if (t >= 0)
231✔
3687
                return t;
3688

3689
        /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3690
         * too. */
3691
        if (streq(s, "nsec"))
×
3692
                return SOCKET_TIMESTAMPING_NS;
3693
        if (STR_IN_SET(s, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
×
3694
                return SOCKET_TIMESTAMPING_US;
×
3695

3696
        r = parse_boolean(s);
×
3697
        if (r < 0)
×
3698
                return _SOCKET_TIMESTAMPING_INVALID;
3699

3700
        return r ? SOCKET_TIMESTAMPING_NS : SOCKET_TIMESTAMPING_OFF; /* If boolean yes, default to ns accuracy */
×
3701
}
3702

3703
static const char* const socket_defer_trigger_table[_SOCKET_DEFER_MAX] = {
3704
        [SOCKET_DEFER_NO]      = "no",
3705
        [SOCKET_DEFER_YES]     = "yes",
3706
        [SOCKET_DEFER_PATIENT] = "patient",
3707
};
3708

3709
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(socket_defer_trigger, SocketDeferTrigger, SOCKET_DEFER_YES);
807✔
3710

3711
const UnitVTable socket_vtable = {
3712
        .object_size = sizeof(Socket),
3713
        .exec_context_offset = offsetof(Socket, exec_context),
3714
        .cgroup_context_offset = offsetof(Socket, cgroup_context),
3715
        .kill_context_offset = offsetof(Socket, kill_context),
3716
        .exec_runtime_offset = offsetof(Socket, exec_runtime),
3717
        .cgroup_runtime_offset = offsetof(Socket, cgroup_runtime),
3718

3719
        .sections =
3720
                "Unit\0"
3721
                "Socket\0"
3722
                "Install\0",
3723
        .private_section = "Socket",
3724

3725
        .can_transient = true,
3726
        .can_trigger = true,
3727
        .can_fail = true,
3728

3729
        .init = socket_init,
3730
        .done = socket_done,
3731
        .load = socket_load,
3732

3733
        .coldplug = socket_coldplug,
3734

3735
        .dump = socket_dump,
3736

3737
        .start = socket_start,
3738
        .stop = socket_stop,
3739

3740
        .clean = socket_clean,
3741
        .can_clean = socket_can_clean,
3742

3743
        .get_timeout = socket_get_timeout,
3744

3745
        .serialize = socket_serialize,
3746
        .deserialize_item = socket_deserialize_item,
3747
        .distribute_fds = socket_distribute_fds,
3748

3749
        .active_state = socket_active_state,
3750
        .sub_state_to_string = socket_sub_state_to_string,
3751

3752
        .will_restart = unit_will_restart_default,
3753

3754
        .may_gc = socket_may_gc,
3755

3756
        .sigchld_event = socket_sigchld_event,
3757

3758
        .trigger_notify = socket_trigger_notify,
3759

3760
        .stop_notify = socket_stop_notify,
3761

3762
        .reset_failed = socket_reset_failed,
3763

3764
        .notify_handoff_timestamp = socket_handoff_timestamp,
3765

3766
        .control_pid = socket_control_pid,
3767

3768
        .bus_set_property = bus_socket_set_property,
3769
        .bus_commit_properties = bus_socket_commit_properties,
3770

3771
        .status_message_formats = {
3772
                .finished_start_job = {
3773
                        [JOB_DONE]       = "Listening on %s.",
3774
                        [JOB_FAILED]     = "Failed to listen on %s.",
3775
                        [JOB_TIMEOUT]    = "Timed out starting %s.",
3776
                },
3777
                .finished_stop_job = {
3778
                        [JOB_DONE]       = "Closed %s.",
3779
                        [JOB_FAILED]     = "Failed stopping %s.",
3780
                        [JOB_TIMEOUT]    = "Timed out stopping %s.",
3781
                },
3782
        },
3783

3784
        .test_startable = socket_test_startable,
3785
};
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