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

systemd / systemd / 19520565317

19 Nov 2025 11:19PM UTC coverage: 72.548% (+0.1%) from 72.449%
19520565317

push

github

web-flow
core: Verify inherited FDs are writable for stdout/stderr (#39674)

When inheriting file descriptors for stdout/stderr (either from stdin or
when making stderr inherit from stdout), we previously just assumed they
would be writable and dup'd them. This could lead to broken setups if
the inherited FD was actually opened read-only.

Before dup'ing any inherited FDs to stdout/stderr, verify they are
actually writable using the new fd_is_writable() helper. If not, fall
back to /dev/null (or reopen the terminal in the TTY case) with a
warning, rather than silently creating a broken setup where output
operations would fail.

31 of 44 new or added lines in 3 files covered. (70.45%)

813 existing lines in 43 files now uncovered.

308541 of 425291 relevant lines covered (72.55%)

1188151.68 hits per line

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

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

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

11
#include "sd-bus.h"
12

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

57
typedef struct SocketPeer {
58
        unsigned n_ref;
59

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

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

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

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

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

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

110
        if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(UNIT(s))))
5,263✔
111
                return false;
112

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

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

119
        return true;
120
}
121

122
static void socket_init(Unit *u) {
6,556✔
123
        Socket *s = ASSERT_PTR(SOCKET(u));
6,556✔
124

125
        assert(u->load_state == UNIT_STUB);
6,556✔
126

127
        s->backlog = SOMAXCONN_DELUXE;
6,556✔
128
        s->timeout_usec = u->manager->defaults.timeout_start_usec;
6,556✔
129
        s->directory_mode = 0755;
6,556✔
130
        s->socket_mode = 0666;
6,556✔
131

132
        s->max_connections = 64;
6,556✔
133

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

140
        s->exec_context.std_output = u->manager->defaults.std_output;
6,556✔
141
        s->exec_context.std_error = u->manager->defaults.std_error;
6,556✔
142

143
        s->control_pid = PIDREF_NULL;
6,556✔
144
        s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
6,556✔
145

146
        s->trigger_limit = RATELIMIT_OFF;
6,556✔
147

148
        s->poll_limit = RATELIMIT_OFF;
6,556✔
149

150
        s->defer_trigger_max_usec = USEC_INFINITY;
6,556✔
151
}
6,556✔
152

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

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

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

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

170
        sd_event_source_unref(p->event_source);
7,072✔
171

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

176
        return mfree(p);
7,072✔
177
}
178

179
void socket_free_ports(Socket *s) {
6,556✔
180
        assert(s);
6,556✔
181

182
        LIST_CLEAR(port, s->ports, socket_port_free);
13,627✔
183
}
6,556✔
184

185
static void socket_done(Unit *u) {
6,556✔
186
        Socket *s = ASSERT_PTR(SOCKET(u));
6,556✔
187
        SocketPeer *p;
6,556✔
188

189
        socket_free_ports(s);
6,556✔
190

191
        while ((p = set_steal_first(s->peers_by_address)))
6,557✔
192
                p->socket = NULL;
1✔
193

194
        s->peers_by_address = set_free(s->peers_by_address);
6,556✔
195

196
        s->exec_runtime = exec_runtime_free(s->exec_runtime);
6,556✔
197

198
        exec_command_free_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
6,556✔
199
        s->control_command = NULL;
6,556✔
200

201
        socket_unwatch_control_pid(s);
6,556✔
202

203
        unit_ref_unset(&s->service);
6,556✔
204

205
        s->tcp_congestion = mfree(s->tcp_congestion);
6,556✔
206
        s->bind_to_device = mfree(s->bind_to_device);
6,556✔
207

208
        s->smack = mfree(s->smack);
6,556✔
209
        s->smack_ip_in = mfree(s->smack_ip_in);
6,556✔
210
        s->smack_ip_out = mfree(s->smack_ip_out);
6,556✔
211

212
        strv_free(s->symlinks);
6,556✔
213

214
        s->user = mfree(s->user);
6,556✔
215
        s->group = mfree(s->group);
6,556✔
216

217
        s->fdname = mfree(s->fdname);
6,556✔
218

219
        s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
6,556✔
220
}
6,556✔
221

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

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

228
static bool have_non_accept_socket(Socket *s) {
7,981✔
229
        assert(s);
7,981✔
230

231
        if (!s->accept)
7,981✔
232
                return true;
233

234
        LIST_FOREACH(port, p, s->ports) {
5,720✔
235

236
                if (p->type != SOCKET_SOCKET)
2,860✔
237
                        return true;
238

239
                if (!socket_address_can_accept(&p->address))
2,860✔
240
                        return true;
241
        }
242

243
        return false;
244
}
245

246
static int socket_add_mount_dependencies(Socket *s) {
6,551✔
247
        int r;
6,551✔
248

249
        assert(s);
6,551✔
250

251
        LIST_FOREACH(port, p, s->ports) {
13,622✔
252
                const char *path = NULL;
7,071✔
253

254
                if (p->type == SOCKET_SOCKET)
7,071✔
255
                        path = socket_address_get_path(&p->address);
6,831✔
256
                else if (IN_SET(p->type, SOCKET_FIFO, SOCKET_SPECIAL, SOCKET_USB_FUNCTION))
240✔
257
                        path = p->path;
240✔
258

259
                if (!path)
7,071✔
260
                        continue;
351✔
261

262
                r = unit_add_mounts_for(UNIT(s), path, UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
6,720✔
263
                if (r < 0)
6,720✔
264
                        return r;
265
        }
266

267
        return 0;
268
}
269

270
static int socket_add_device_dependencies(Socket *s) {
6,551✔
271
        char *t;
6,551✔
272

273
        assert(s);
6,551✔
274

275
        if (!s->bind_to_device || streq(s->bind_to_device, "lo"))
6,551✔
276
                return 0;
277

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

282
static int socket_add_default_dependencies(Socket *s) {
6,551✔
283
        int r;
6,551✔
284

285
        assert(s);
6,551✔
286

287
        if (!UNIT(s)->default_dependencies)
6,551✔
288
                return 0;
289

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

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

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

303
static bool socket_has_exec(Socket *s) {
6,551✔
304
        assert(s);
6,551✔
305

306
        FOREACH_ARRAY(i, s->exec_command, _SOCKET_EXEC_COMMAND_MAX)
38,676✔
307
                if (*i)
32,335✔
308
                        return true;
309

310
        return false;
311
}
312

313
static int socket_add_extras(Socket *s) {
6,551✔
314
        Unit *u = UNIT(ASSERT_PTR(s));
6,551✔
315
        int r;
6,551✔
316

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

329
        if (s->trigger_limit.interval == USEC_INFINITY)
6,551✔
330
                s->trigger_limit.interval = 2 * USEC_PER_SEC;
6,551✔
331
        if (s->trigger_limit.burst == UINT_MAX)
6,551✔
332
                s->trigger_limit.burst = s->accept ? 200 : 20;
11,672✔
333

334
        if (s->poll_limit.interval == USEC_INFINITY)
6,551✔
335
                s->poll_limit.interval = 2 * USEC_PER_SEC;
6,411✔
336
        if (s->poll_limit.burst == UINT_MAX)
6,551✔
337
                s->poll_limit.burst = s->accept ? 150 : 15;
11,532✔
338

339
        if (have_non_accept_socket(s)) {
6,551✔
340

341
                if (!UNIT_ISSET(s->service)) {
5,121✔
342
                        Unit *x;
3,056✔
343

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

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

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

356
        r = socket_add_mount_dependencies(s);
6,551✔
357
        if (r < 0)
6,551✔
358
                return r;
359

360
        r = socket_add_device_dependencies(s);
6,551✔
361
        if (r < 0)
6,551✔
362
                return r;
363

364
        r = unit_patch_contexts(u);
6,551✔
365
        if (r < 0)
6,551✔
366
                return r;
367

368
        if (socket_has_exec(s)) {
6,551✔
369
                r = unit_add_exec_dependencies(u, &s->exec_context);
210✔
370
                if (r < 0)
210✔
371
                        return r;
372
        }
373

374
        r = unit_set_default_slice(u);
6,551✔
375
        if (r < 0)
6,551✔
376
                return r;
377

378
        r = socket_add_default_dependencies(s);
6,551✔
379
        if (r < 0)
6,551✔
380
                return r;
×
381

382
        return 0;
383
}
384

385
static const char* socket_find_symlink_target(Socket *s) {
3,813✔
386
        const char *found = NULL;
3,813✔
387

388
        assert(s);
3,813✔
389

390
        LIST_FOREACH(port, p, s->ports) {
7,626✔
391
                const char *f;
4,395✔
392

393
                switch (p->type) {
4,395✔
394

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

399
                case SOCKET_SOCKET:
4,250✔
400
                        f = socket_address_get_path(&p->address);
4,250✔
401
                        break;
4,250✔
402

403
                default:
404
                        f = NULL;
405
                }
406

407
                if (f) {
4,395✔
408
                        if (found)
4,325✔
409
                                return NULL;
410

411
                        found = f;
412
                }
413
        }
414

415
        return found;
416
}
417

418
static int socket_verify(Socket *s) {
6,551✔
419
        assert(s);
6,551✔
420
        assert(UNIT(s)->load_state == UNIT_LOADED);
6,551✔
421

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

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

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

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

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

437
        if (!strv_isempty(s->symlinks) && !socket_find_symlink_target(s))
6,857✔
438
                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.");
×
439

440
        return 0;
441
}
442

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

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

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

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

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

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

480
static int socket_load(Unit *u) {
6,557✔
481
        Socket *s = ASSERT_PTR(SOCKET(u));
6,557✔
482
        int r;
6,557✔
483

484
        assert(u->load_state == UNIT_STUB);
6,557✔
485

486
        r = unit_load_fragment_and_dropin(u, true);
6,557✔
487
        if (r < 0)
6,557✔
488
                return r;
489

490
        if (u->load_state != UNIT_LOADED)
6,551✔
491
                return 0;
492

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

498
        return socket_verify(s);
6,551✔
499
}
500

501
static SocketPeer* socket_peer_dup(const SocketPeer *q) {
70✔
502
        SocketPeer *p;
70✔
503

504
        assert(q);
70✔
505

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

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

517
        return p;
70✔
518
}
519

520
static SocketPeer* socket_peer_free(SocketPeer *p) {
70✔
521
        assert(p);
70✔
522

523
        if (p->socket)
70✔
524
                set_remove(p->socket->peers_by_address, p);
69✔
525

526
        return mfree(p);
70✔
527
}
528

529
DEFINE_TRIVIAL_REF_UNREF_FUNC(SocketPeer, socket_peer, socket_peer_free);
114✔
530

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

539
        assert(s);
90✔
540
        assert(fd >= 0);
90✔
541
        assert(ret);
90✔
542

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

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

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

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

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

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

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

577
        remote->socket = s;
70✔
578

579
        *ret = TAKE_PTR(remote);
70✔
580
        return 1;
70✔
581
}
582

583
static const char* listen_lookup(int family, int type) {
42✔
584

585
        if (family == AF_NETLINK)
42✔
586
                return "ListenNetlink";
587

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

595
        assert_not_reached();
×
596
}
597

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

602
        assert(f);
41✔
603

604
        prefix = strempty(prefix);
41✔
605
        prefix2 = strjoina(prefix, "\t");
205✔
606

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

781
        LIST_FOREACH(port, p, s->ports) {
85✔
782

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

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

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

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

824
        if (!strv_isempty(s->symlinks)) {
41✔
825
                fprintf(f, "%sSymlinks:", prefix);
3✔
826
                STRV_FOREACH(q, s->symlinks)
7✔
827
                        fprintf(f, " %s", *q);
4✔
828

829
                fprintf(f, "\n");
3✔
830
        }
831

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

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

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

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

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

849
        cgroup_context_dump(UNIT(s), f, prefix);
41✔
850
}
41✔
851

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

857
        union sockaddr_union local, remote;
92✔
858
        socklen_t l;
92✔
859
        int r;
92✔
860

861
        assert(fd >= 0);
92✔
862
        assert(ret);
92✔
863

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

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

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

877
        char *s;
92✔
878

879
        switch (local.sa.sa_family) {
92✔
880

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

886
                if (asprintf(&s,
×
887
                             "%u-%" PRIu64 "-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
888
                             nr,
889
                             cookie,
890
                             a >> 24, (a >> 16) & 0xFF, (a >> 8) & 0xFF, a & 0xFF,
891
                             be16toh(local.in.sin_port),
×
892
                             b >> 24, (b >> 16) & 0xFF, (b >> 8) & 0xFF, b & 0xFF,
893
                             be16toh(remote.in.sin_port)) < 0)
×
894
                        return -ENOMEM;
895

896
                break;
897
        }
898

899
        case AF_INET6: {
×
900
                static const unsigned char ipv4_prefix[] = {
×
901
                        0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF
902
                };
903

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

910
                        if (asprintf(&s,
×
911
                                     "%u-%" PRIu64 "-%u.%u.%u.%u:%u-%u.%u.%u.%u:%u",
912
                                     nr,
913
                                     cookie,
914
                                     a[0], a[1], a[2], a[3],
×
915
                                     be16toh(local.in6.sin6_port),
×
916
                                     b[0], b[1], b[2], b[3],
×
917
                                     be16toh(remote.in6.sin6_port)) < 0)
×
918
                                return -ENOMEM;
919
                } else {
920
                        if (asprintf(&s,
×
921
                                     "%u-%" PRIu64 "-%s:%u-%s:%u",
922
                                     nr,
923
                                     cookie,
924
                                     IN6_ADDR_TO_STRING(&local.in6.sin6_addr),
×
925
                                     be16toh(local.in6.sin6_port),
×
926
                                     IN6_ADDR_TO_STRING(&remote.in6.sin6_addr),
×
927
                                     be16toh(remote.in6.sin6_port)) < 0)
×
928
                                return -ENOMEM;
×
929
                }
930

931
                break;
932
        }
933

934
        case AF_UNIX: {
92✔
935
                struct ucred ucred;
92✔
936

937
                r = getpeercred(fd, &ucred);
92✔
938
                if (r >= 0) {
92✔
939
                        _cleanup_close_ int pidfd = getpeerpidfd(fd);
184✔
940
                        uint64_t pidfd_id;
92✔
941

942
                        if (pidfd >= 0 && pidfd_get_inode_id(pidfd, &pidfd_id) >= 0)
92✔
943
                                r = asprintf(&s, "%u-%" PRIu64 "-" PID_FMT "_%" PRIu64 "-" UID_FMT,
90✔
944
                                             nr, cookie, ucred.pid, pidfd_id, ucred.uid);
945
                        else
946
                                r = asprintf(&s, "%u-%" PRIu64 "-" PID_FMT "-" UID_FMT,
2✔
947
                                             nr, cookie, ucred.pid, ucred.uid);
948
                        if (r < 0)
92✔
949
                                return -ENOMEM;
×
950
                } else if (r == -ENODATA) {
×
951
                        /* This handles the case where somebody is connecting from another pid/uid namespace
952
                         * (e.g. from outside of our container). */
953
                        if (asprintf(&s,
×
954
                                     "%u-%" PRIu64 "-unknown",
955
                                     nr,
956
                                     cookie) < 0)
957
                                return -ENOMEM;
958
                } else
959
                        return r;
960

961
                break;
92✔
962
        }
963

964
        case AF_VSOCK:
×
965
                if (asprintf(&s,
×
966
                             "%u-%" PRIu64 "-%u:%u-%u:%u",
967
                             nr,
968
                             cookie,
969
                             local.vm.svm_cid, local.vm.svm_port,
970
                             remote.vm.svm_cid, remote.vm.svm_port) < 0)
971
                        return -ENOMEM;
972

973
                break;
974

975
        default:
×
976
                assert_not_reached();
×
977
        }
978

979
        *ret = s;
92✔
980
        return 0;
92✔
981
}
982

983
static void socket_close_fds(Socket *s) {
2,734✔
984
        assert(s);
2,734✔
985

986
        LIST_FOREACH(port, p, s->ports) {
5,690✔
987
                bool was_open = p->fd >= 0;
2,956✔
988

989
                p->event_source = sd_event_source_disable_unref(p->event_source);
2,956✔
990
                p->fd = safe_close(p->fd);
2,956✔
991
                socket_port_close_auxiliary_fds(p);
2,956✔
992

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

999
                if (!was_open || !s->remove_on_stop)
2,956✔
1000
                        continue;
2,686✔
1001

1002
                switch (p->type) {
270✔
1003

1004
                case SOCKET_FIFO:
22✔
1005
                        (void) unlink(p->path);
22✔
1006
                        break;
22✔
1007

1008
                case SOCKET_MQUEUE:
×
1009
                        (void) mq_unlink(p->path);
×
1010
                        break;
×
1011

1012
                case SOCKET_SOCKET:
248✔
1013
                        (void) socket_address_unlink(&p->address);
248✔
1014
                        break;
248✔
1015

1016
                default:
1017
                        ;
1018
                }
1019
        }
1020

1021
        if (s->remove_on_stop)
2,734✔
1022
                STRV_FOREACH(i, s->symlinks)
261✔
1023
                        (void) unlink(*i);
2✔
1024

1025
        /* Note that we don't return NULL here, since s has not been freed. */
1026
}
2,734✔
1027

1028
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(Socket*, socket_close_fds, NULL);
×
1029

1030
#define log_socket_option_errno(s, e, option)                                          \
1031
        ({                                                                             \
1032
                int _e_ = (e);                                                         \
1033
                log_unit_full_errno(                                                   \
1034
                                UNIT(s),                                               \
1035
                                ERRNO_IS_NOT_SUPPORTED(_e_) ? LOG_DEBUG : LOG_WARNING, \
1036
                                _e_,                                                   \
1037
                                "Failed to set %s socket option, ignoring: %m",        \
1038
                                option);                                               \
1039
        })
1040

1041
static void socket_apply_socket_options(Socket *s, SocketPort *p, int fd) {
3,526✔
1042
        int r;
3,526✔
1043

1044
        assert(s);
3,526✔
1045
        assert(p);
3,526✔
1046
        assert(fd >= 0);
3,526✔
1047

1048
        if (s->keep_alive) {
3,526✔
1049
                r = setsockopt_int(fd, SOL_SOCKET, SO_KEEPALIVE, true);
×
1050
                if (r < 0)
×
UNCOV
1051
                        log_socket_option_errno(s, r, "SO_KEEPALIVE");
×
1052
        }
1053

1054
        if (timestamp_is_set(s->keep_alive_time)) {
3,526✔
1055
                r = setsockopt_int(fd, SOL_TCP, TCP_KEEPIDLE, s->keep_alive_time / USEC_PER_SEC);
×
1056
                if (r < 0)
×
UNCOV
1057
                        log_socket_option_errno(s, r, "TCP_KEEPIDLE");
×
1058
        }
1059

1060
        if (s->keep_alive_interval > 0) {
3,526✔
1061
                r = setsockopt_int(fd, SOL_TCP, TCP_KEEPINTVL, s->keep_alive_interval / USEC_PER_SEC);
×
1062
                if (r < 0)
×
UNCOV
1063
                        log_socket_option_errno(s, r, "TCP_KEEPINTVL");
×
1064
        }
1065

1066
        if (s->keep_alive_cnt > 0) {
3,526✔
1067
                r = setsockopt_int(fd, SOL_TCP, TCP_KEEPCNT, s->keep_alive_cnt);
×
1068
                if (r < 0)
×
UNCOV
1069
                        log_socket_option_errno(s, r, "TCP_KEEPCNT");
×
1070
        }
1071

1072
        if (s->defer_accept > 0) {
3,526✔
1073
                r = setsockopt_int(fd, SOL_TCP, TCP_DEFER_ACCEPT, s->defer_accept / USEC_PER_SEC);
×
1074
                if (r < 0)
×
1075
                        log_socket_option_errno(s, r, "TCP_DEFER_ACCEPT");
×
1076
        }
1077

1078
        if (s->no_delay) {
3,526✔
1079
                if (s->socket_protocol == IPPROTO_SCTP) {
×
UNCOV
1080
                        r = setsockopt_int(fd, SOL_SCTP, SCTP_NODELAY, true);
×
UNCOV
1081
                        if (r < 0)
×
UNCOV
1082
                                log_socket_option_errno(s, r, "SCTP_NODELAY");
×
1083
                } else {
1084
                        r = setsockopt_int(fd, SOL_TCP, TCP_NODELAY, true);
×
1085
                        if (r < 0)
×
1086
                                log_socket_option_errno(s, r, "TCP_NODELAY");
×
1087
                }
1088
        }
1089

1090
        if (s->broadcast) {
3,526✔
UNCOV
1091
                r = setsockopt_int(fd, SOL_SOCKET, SO_BROADCAST, true);
×
1092
                if (r < 0)
×
UNCOV
1093
                        log_socket_option_errno(s, r, "SO_BROADCAST");
×
1094
        }
1095

1096
        if (s->pass_cred) {
3,526✔
1097
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSCRED, true);
144✔
1098
                if (r < 0)
144✔
UNCOV
1099
                        log_socket_option_errno(s, r, "SO_PASSCRED");
×
1100
        }
1101

1102
        if (s->pass_pidfd) {
3,526✔
UNCOV
1103
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSPIDFD, true);
×
UNCOV
1104
                if (r < 0)
×
1105
                        log_socket_option_errno(s, r, "SO_PASSPIDFD");
×
1106
        }
1107

1108
        if (s->pass_sec) {
3,526✔
1109
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSSEC, true);
99✔
1110
                if (r < 0)
99✔
UNCOV
1111
                        log_socket_option_errno(s, r, "SO_PASSSEC");
×
1112
        }
1113

1114
        if (s->pass_pktinfo) {
3,526✔
1115
                r = socket_set_recvpktinfo(fd, socket_address_family(&p->address), true);
36✔
1116
                if (r < 0)
36✔
1117
                        log_socket_option_errno(s, r, "packet info");
×
1118
        }
1119

1120
        if (!s->pass_rights) {
3,526✔
UNCOV
1121
                r = setsockopt_int(fd, SOL_SOCKET, SO_PASSRIGHTS, false);
×
UNCOV
1122
                if (r < 0)
×
UNCOV
1123
                        log_socket_option_errno(s, r, "SO_PASSRIGHTS");
×
1124
        }
1125

1126
        if (s->timestamping != SOCKET_TIMESTAMPING_OFF) {
3,526✔
1127
                r = setsockopt_int(fd, SOL_SOCKET,
198✔
1128
                                   s->timestamping == SOCKET_TIMESTAMPING_NS ? SO_TIMESTAMPNS : SO_TIMESTAMP,
1129
                                   true);
1130
                if (r < 0)
99✔
UNCOV
1131
                        log_socket_option_errno(s, r, "timestamping");
×
1132
        }
1133

1134
        if (s->priority >= 0) {
3,526✔
1135
                r = setsockopt_int(fd, SOL_SOCKET, SO_PRIORITY, s->priority);
186✔
1136
                if (r < 0)
186✔
UNCOV
1137
                        log_socket_option_errno(s, r, "SO_PRIORITY");
×
1138
        }
1139

1140
        if (s->receive_buffer > 0) {
3,526✔
1141
                r = fd_set_rcvbuf(fd, s->receive_buffer, false);
163✔
1142
                if (r < 0)
163✔
UNCOV
1143
                        log_socket_option_errno(s, r, "SO_RCVBUF/SO_RCVBUFFORCE");
×
1144
        }
1145

1146
        if (s->send_buffer > 0) {
3,526✔
1147
                r = fd_set_sndbuf(fd, s->send_buffer, false);
33✔
1148
                if (r < 0)
33✔
UNCOV
1149
                        log_socket_option_errno(s, r, "SO_SNDBUF/SO_SNDBUFFORCE");
×
1150
        }
1151

1152
        if (s->mark >= 0) {
3,526✔
1153
                r = setsockopt_int(fd, SOL_SOCKET, SO_MARK, s->mark);
×
UNCOV
1154
                if (r < 0)
×
UNCOV
1155
                        log_socket_option_errno(s, r, "SO_MARK");
×
1156
        }
1157

1158
        if (s->ip_tos >= 0) {
3,526✔
1159
                r = setsockopt_int(fd, IPPROTO_IP, IP_TOS, s->ip_tos);
×
UNCOV
1160
                if (r < 0)
×
UNCOV
1161
                        log_socket_option_errno(s, r, "IP_TOS");
×
1162
        }
1163

1164
        if (s->ip_ttl >= 0) {
3,526✔
1165
                r = socket_set_ttl(fd, socket_address_family(&p->address), s->ip_ttl);
×
UNCOV
1166
                if (r < 0)
×
UNCOV
1167
                        log_socket_option_errno(s, r, "IP_TTL/IPV6_UNICAST_HOPS");
×
1168
        }
1169

1170
        if (s->tcp_congestion)
3,526✔
UNCOV
1171
                if (setsockopt(fd, SOL_TCP, TCP_CONGESTION, s->tcp_congestion, strlen(s->tcp_congestion)+1) < 0)
×
UNCOV
1172
                        log_socket_option_errno(s, errno, "TCP_CONGESTION");
×
1173

1174
        if (s->smack_ip_in) {
3,526✔
1175
                r = mac_smack_apply_fd(fd, SMACK_ATTR_IPIN, s->smack_ip_in);
×
UNCOV
1176
                if (r < 0)
×
UNCOV
1177
                        log_unit_warning_errno(UNIT(s), r, "Failed to apply SMACK label for IP input, ignoring: %m");
×
1178
        }
1179

1180
        if (s->smack_ip_out) {
3,526✔
1181
                r = mac_smack_apply_fd(fd, SMACK_ATTR_IPOUT, s->smack_ip_out);
×
UNCOV
1182
                if (r < 0)
×
UNCOV
1183
                        log_unit_warning_errno(UNIT(s), r, "Failed to apply SMACK label for IP output, ignoring: %m");
×
1184
        }
1185
}
3,526✔
1186

1187
static void socket_apply_fifo_options(Socket *s, int fd) {
73✔
1188
        int r;
73✔
1189

1190
        assert(s);
73✔
1191
        assert(fd >= 0);
73✔
1192

1193
        if (s->pipe_size > 0)
73✔
UNCOV
1194
                if (fcntl(fd, F_SETPIPE_SZ, s->pipe_size) < 0)
×
UNCOV
1195
                        log_unit_warning_errno(UNIT(s), errno, "Setting pipe size failed, ignoring: %m");
×
1196

1197
        if (s->smack) {
73✔
1198
                r = mac_smack_apply_fd(fd, SMACK_ATTR_ACCESS, s->smack);
×
UNCOV
1199
                if (r < 0)
×
UNCOV
1200
                        log_unit_error_errno(UNIT(s), r, "SMACK relabelling failed, ignoring: %m");
×
1201
        }
1202
}
73✔
1203

1204
static int fifo_address_create(
73✔
1205
                const char *path,
1206
                mode_t directory_mode,
1207
                mode_t socket_mode) {
1208

1209
        _cleanup_close_ int fd = -EBADF;
73✔
1210
        mode_t old_mask;
73✔
1211
        struct stat st;
73✔
1212
        int r;
73✔
1213

1214
        assert(path);
73✔
1215

1216
        (void) mkdir_parents_label(path, directory_mode);
73✔
1217

1218
        r = mac_selinux_create_file_prepare(path, S_IFIFO);
73✔
1219
        if (r < 0)
73✔
1220
                return r;
1221

1222
        /* Enforce the right access mode for the fifo */
1223
        old_mask = umask(~socket_mode);
73✔
1224

1225
        /* Include the original umask in our mask */
1226
        (void) umask(~socket_mode | old_mask);
73✔
1227

1228
        r = mkfifo(path, socket_mode);
73✔
1229
        (void) umask(old_mask);
73✔
1230

1231
        if (r < 0 && errno != EEXIST) {
73✔
UNCOV
1232
                r = -errno;
×
UNCOV
1233
                goto fail;
×
1234
        }
1235

1236
        fd = open(path, O_RDWR | O_CLOEXEC | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW);
73✔
1237
        if (fd < 0) {
73✔
UNCOV
1238
                r = -errno;
×
UNCOV
1239
                goto fail;
×
1240
        }
1241

1242
        mac_selinux_create_file_clear();
73✔
1243

1244
        if (fstat(fd, &st) < 0) {
73✔
UNCOV
1245
                r = -errno;
×
UNCOV
1246
                goto fail;
×
1247
        }
1248

1249
        if (!S_ISFIFO(st.st_mode) ||
73✔
1250
            (st.st_mode & 0777) != (socket_mode & ~old_mask) ||
146✔
1251
            st.st_uid != getuid() ||
146✔
1252
            st.st_gid != getgid()) {
73✔
UNCOV
1253
                r = -EEXIST;
×
UNCOV
1254
                goto fail;
×
1255
        }
1256

1257
        return TAKE_FD(fd);
1258

UNCOV
1259
fail:
×
UNCOV
1260
        mac_selinux_create_file_clear();
×
1261
        return r;
1262
}
1263

1264
static int special_address_create(const char *path, bool writable) {
6✔
1265
        _cleanup_close_ int fd = -EBADF;
6✔
1266
        struct stat st;
6✔
1267

1268
        assert(path);
6✔
1269

1270
        fd = open(path, (writable ? O_RDWR : O_RDONLY)|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
6✔
1271
        if (fd < 0)
6✔
UNCOV
1272
                return -errno;
×
1273

1274
        if (fstat(fd, &st) < 0)
6✔
UNCOV
1275
                return -errno;
×
1276

1277
        /* Check whether this is a /proc, /sys or /dev file or char device */
1278
        if (!S_ISREG(st.st_mode) && !S_ISCHR(st.st_mode))
6✔
UNCOV
1279
                return -EEXIST;
×
1280

1281
        return TAKE_FD(fd);
1282
}
1283

1284
static int usbffs_address_create_at(int dfd, const char *name) {
×
UNCOV
1285
        _cleanup_close_ int fd = -EBADF;
×
1286
        struct stat st;
×
1287

UNCOV
1288
        assert(dfd >= 0);
×
1289
        assert(name);
×
1290

1291
        fd = openat(dfd, name, O_RDWR|O_CLOEXEC|O_NOCTTY|O_NONBLOCK|O_NOFOLLOW);
×
UNCOV
1292
        if (fd < 0)
×
1293
                return -errno;
×
1294

UNCOV
1295
        if (fstat(fd, &st) < 0)
×
UNCOV
1296
                return -errno;
×
1297

1298
        /* Check whether this is a regular file (ffs endpoint) */
UNCOV
1299
        if (!S_ISREG(st.st_mode))
×
UNCOV
1300
                return -EEXIST;
×
1301

1302
        return TAKE_FD(fd);
1303
}
1304

UNCOV
1305
static int mq_address_create(
×
1306
                const char *path,
1307
                mode_t mq_mode,
1308
                long maxmsg,
1309
                long msgsize) {
1310

1311
        _cleanup_close_ int fd = -EBADF;
×
1312
        struct stat st;
×
UNCOV
1313
        mode_t old_mask;
×
1314
        struct mq_attr _attr, *attr = NULL;
×
1315

1316
        assert(path);
×
1317

UNCOV
1318
        if (maxmsg > 0 && msgsize > 0) {
×
UNCOV
1319
                _attr = (struct mq_attr) {
×
1320
                        .mq_flags = O_NONBLOCK,
1321
                        .mq_maxmsg = maxmsg,
1322
                        .mq_msgsize = msgsize,
1323
                };
UNCOV
1324
                attr = &_attr;
×
1325
        }
1326

1327
        /* Enforce the right access mode for the mq */
UNCOV
1328
        old_mask = umask(~mq_mode);
×
1329

1330
        /* Include the original umask in our mask */
1331
        (void) umask(~mq_mode | old_mask);
×
UNCOV
1332
        fd = mq_open(path, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_CREAT, mq_mode, attr);
×
1333
        (void) umask(old_mask);
×
1334

UNCOV
1335
        if (fd < 0)
×
1336
                return -errno;
×
1337

UNCOV
1338
        if (fstat(fd, &st) < 0)
×
1339
                return -errno;
×
1340

1341
        if ((st.st_mode & 0777) != (mq_mode & ~old_mask) ||
×
1342
            st.st_uid != getuid() ||
×
UNCOV
1343
            st.st_gid != getgid())
×
UNCOV
1344
                return -EEXIST;
×
1345

1346
        return TAKE_FD(fd);
1347
}
1348

1349
static int socket_symlink(Socket *s) {
3,507✔
1350
        const char *p;
3,507✔
1351
        int r;
3,507✔
1352

1353
        assert(s);
3,507✔
1354

1355
        p = socket_find_symlink_target(s);
3,507✔
1356
        if (!p)
3,507✔
1357
                return 0;
1358

1359
        STRV_FOREACH(i, s->symlinks) {
2,965✔
1360
                (void) mkdir_parents_label(*i, s->directory_mode);
110✔
1361

1362
                r = symlink_idempotent(p, *i, false);
110✔
1363
                if (r == -EEXIST && s->remove_on_stop) {
110✔
1364
                        /* If there's already something where we want to create the symlink, and the destructive
1365
                         * RemoveOnStop= mode is set, then we might as well try to remove what already exists and try
1366
                         * again. */
1367

UNCOV
1368
                        if (unlink(*i) >= 0)
×
UNCOV
1369
                                r = symlink_idempotent(p, *i, false);
×
1370
                }
1371
                if (r < 0)
110✔
UNCOV
1372
                        log_unit_warning_errno(UNIT(s), r, "Failed to create symlink %s %s %s, ignoring: %m",
×
1373
                                               p, glyph(GLYPH_ARROW_RIGHT), *i);
1374
        }
1375

1376
        return 0;
1377
}
1378

UNCOV
1379
static int usbffs_write_descs(int fd, Service *s) {
×
1380
        int r;
×
1381

UNCOV
1382
        assert(fd >= 0);
×
1383
        assert(s);
×
1384

UNCOV
1385
        if (!s->usb_function_descriptors || !s->usb_function_strings)
×
1386
                return -EINVAL;
1387

UNCOV
1388
        r = copy_file_fd(s->usb_function_descriptors, fd, 0);
×
UNCOV
1389
        if (r < 0)
×
1390
                return r;
1391

UNCOV
1392
        return copy_file_fd(s->usb_function_strings, fd, 0);
×
1393
}
1394

1395
static int usbffs_dispatch_eps(SocketPort *p, int dfd) {
×
UNCOV
1396
        _cleanup_free_ DirectoryEntries *des = NULL;
×
1397
        int r;
×
1398

UNCOV
1399
        assert(p);
×
1400
        assert(dfd >= 0);
×
1401

UNCOV
1402
        r = readdir_all(dfd, RECURSE_DIR_SORT|RECURSE_DIR_IGNORE_DOT, &des);
×
UNCOV
1403
        if (r < 0)
×
1404
                return r;
1405

UNCOV
1406
        p->auxiliary_fds = new(int, des->n_entries);
×
UNCOV
1407
        if (!p->auxiliary_fds)
×
1408
                return -ENOMEM;
1409

UNCOV
1410
        FOREACH_ARRAY(i, des->entries, des->n_entries) {
×
1411
                const struct dirent *de = *i;
×
1412

UNCOV
1413
                if (streq(de->d_name, "ep0"))
×
1414
                        continue;
×
1415

1416
                r = usbffs_address_create_at(dfd, de->d_name);
×
UNCOV
1417
                if (r < 0)
×
1418
                        goto fail;
×
1419

UNCOV
1420
                p->auxiliary_fds[p->n_auxiliary_fds++] = r;
×
1421
        }
1422

UNCOV
1423
        assert(p->n_auxiliary_fds < des->n_entries);
×
1424

1425
        return 0;
1426

UNCOV
1427
fail:
×
UNCOV
1428
        socket_port_close_auxiliary_fds(p);
×
1429
        return r;
1430
}
1431

1432
int socket_load_service_unit(Socket *s, int cfd, Unit **ret) {
3,328✔
1433
        int r;
3,328✔
1434

1435
        /* Figure out what the unit that will be used to handle the connections on the socket looks like.
1436
         *
1437
         * If cfd < 0, then we don't have a connection yet. In case of Accept=yes sockets, use a fake
1438
         * instance name.
1439
         */
1440

1441
        assert(s);
3,328✔
1442
        assert(ret);
3,328✔
1443

1444
        if (UNIT_ISSET(s->service)) {
3,328✔
1445
                *ret = UNIT_DEREF(s->service);
2,671✔
1446
                return 0;
3,328✔
1447
        }
1448

1449
        if (!s->accept)
657✔
1450
                return -ENODATA;
1451

1452
        /* Build the instance name and load the unit */
1453
        _cleanup_free_ char *prefix = NULL, *instance = NULL, *name = NULL;
657✔
1454

1455
        r = unit_name_to_prefix(UNIT(s)->id, &prefix);
657✔
1456
        if (r < 0)
657✔
1457
                return r;
1458

1459
        if (cfd >= 0) {
657✔
1460
                r = instance_from_socket(cfd, s->n_accepted, &instance);
92✔
1461
                if (ERRNO_IS_NEG_DISCONNECT(r))
92✔
1462
                        /* ENOTCONN is legitimate if TCP RST was received. Other socket families might return
1463
                         * different errors. This connection is over, but the socket unit lives on. */
UNCOV
1464
                        return log_unit_debug_errno(UNIT(s), r,
×
1465
                                                    "Got error %s on incoming socket, assuming aborted connection attempt, ignoring.",
1466
                                                    ERRNO_NAME(r));
1467
                if (r < 0)
92✔
1468
                        return r;
1469
        }
1470

1471
        /* For accepting sockets, we don't know how the instance will be called until we get a connection and
1472
         * can figure out what the peer name is. So let's use "internal" as the instance to make it clear
1473
         * that this is not an actual peer name. We use "unknown" when we cannot figure out the peer. */
1474
        r = unit_name_build(prefix, instance ?: "internal", ".service", &name);
1,222✔
1475
        if (r < 0)
657✔
1476
                return r;
1477

1478
        return manager_load_unit(UNIT(s)->manager, name, NULL, NULL, ret);
657✔
1479
}
1480

1481
static int socket_determine_selinux_label(Socket *s, char **ret) {
3,179✔
1482
        Unit *service;
3,179✔
1483
        int r;
3,179✔
1484

1485
        assert(s);
3,179✔
1486
        assert(ret);
3,179✔
1487

1488
        r = socket_load_service_unit(s, /* cfd= */ -EBADF, &service);
3,179✔
1489
        if (r == -ENODATA) {
3,179✔
UNCOV
1490
                *ret = NULL;
×
UNCOV
1491
                return 0;
×
1492
        }
1493
        if (r < 0)
3,179✔
1494
                return r;
1495

1496
        r = service_determine_exec_selinux_label(SERVICE(service), ret);
6,358✔
1497
        if (r == -ENODATA) {
3,179✔
1498
                *ret = NULL;
3,179✔
1499
                return 0;
3,179✔
1500
        }
1501
        return r;
1502
}
1503

1504
static int socket_address_listen_do(
3,449✔
1505
                Socket *s,
1506
                const SocketAddress *address,
1507
                const char *label) {
1508

1509
        assert(s);
3,449✔
1510
        assert(address);
3,449✔
1511

1512
        return socket_address_listen(
6,898✔
1513
                        address,
1514
                        SOCK_CLOEXEC|SOCK_NONBLOCK,
1515
                        s->backlog,
3,449✔
1516
                        s->bind_ipv6_only,
1517
                        s->bind_to_device,
3,449✔
1518
                        s->reuse_port,
3,449✔
1519
                        s->free_bind,
3,449✔
1520
                        s->transparent,
3,449✔
1521
                        s->directory_mode,
1522
                        s->socket_mode,
1523
                        label);
1524
}
1525

1526
#define log_address_error_errno(u, address, error, fmt)          \
1527
        ({                                                       \
1528
                _cleanup_free_ char *_t = NULL;                  \
1529
                                                                 \
1530
                (void) socket_address_print(address, &_t);       \
1531
                log_unit_error_errno(u, error, fmt, strna(_t));  \
1532
        })
1533

1534
static bool fork_needed(const SocketAddress *address, Socket *s) {
3,434✔
1535
        assert(address);
3,434✔
1536
        assert(s);
3,434✔
1537

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

1540
        /* If there are any NFTSet= directives with cgroup source, we need the cgroup */
1541
        Unit *u = UNIT(s);
3,434✔
1542
        CGroupContext *c = unit_get_cgroup_context(u);
3,434✔
1543
        if (c)
3,434✔
1544
                FOREACH_ARRAY(nft_set, c->nft_set_context.sets, c->nft_set_context.n_sets)
3,434✔
UNCOV
1545
                        if (nft_set->source == NFT_SET_SOURCE_CGROUP)
×
1546
                                return true;
1547

1548
        if (IN_SET(address->sockaddr.sa.sa_family, AF_INET, AF_INET6) &&
3,434✔
UNCOV
1549
            bpf_program_supported() > 0) /* If BPF firewalling isn't supported anyway — there's no point in this forking complexity */
×
1550
                return true;
1551

1552
        return exec_needs_network_namespace(&s->exec_context);
3,434✔
1553
}
1554

1555
static int socket_address_listen_in_cgroup(
3,434✔
1556
                Socket *s,
1557
                const SocketAddress *address,
1558
                const char *label) {
1559

UNCOV
1560
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
×
1561
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
3,434✔
1562
        int fd, r;
3,434✔
1563

1564
        assert(s);
3,434✔
1565
        assert(address);
3,434✔
1566

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

1572
        if (!fork_needed(address, s)) {
3,434✔
1573
                /* Shortcut things... */
1574
                fd = socket_address_listen_do(s, address, label);
3,434✔
1575
                if (fd < 0)
3,434✔
UNCOV
1576
                        return log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
×
1577

1578
                return fd;
1579
        }
1580

1581
        r = unit_setup_exec_runtime(UNIT(s));
×
UNCOV
1582
        if (r < 0)
×
1583
                return log_unit_error_errno(UNIT(s), r, "Failed to acquire runtime: %m");
×
1584

1585
        if (s->exec_runtime && s->exec_runtime->shared) {
×
1586
                if (s->exec_context.user_namespace_path &&
×
1587
                    s->exec_runtime->shared->userns_storage_socket[0] >= 0) {
×
1588
                        r = open_shareable_ns_path(s->exec_runtime->shared->userns_storage_socket, s->exec_context.user_namespace_path, CLONE_NEWUSER);
×
UNCOV
1589
                        if (r < 0)
×
UNCOV
1590
                                return log_unit_error_errno(UNIT(s), r, "Failed to open user namespace path %s: %m", s->exec_context.user_namespace_path);
×
1591
                }
1592

1593
                if (s->exec_context.network_namespace_path &&
×
1594
                    s->exec_runtime->shared->netns_storage_socket[0] >= 0) {
×
1595
                        r = open_shareable_ns_path(s->exec_runtime->shared->netns_storage_socket, s->exec_context.network_namespace_path, CLONE_NEWNET);
×
UNCOV
1596
                        if (r < 0)
×
UNCOV
1597
                                return log_unit_error_errno(UNIT(s), r, "Failed to open network namespace path %s: %m", s->exec_context.network_namespace_path);
×
1598
                }
1599

1600
                if (s->exec_context.ipc_namespace_path &&
×
1601
                    s->exec_runtime->shared->ipcns_storage_socket[0] >= 0) {
×
1602
                        r = open_shareable_ns_path(s->exec_runtime->shared->ipcns_storage_socket, s->exec_context.ipc_namespace_path, CLONE_NEWIPC);
×
UNCOV
1603
                        if (r < 0)
×
UNCOV
1604
                                return log_unit_error_errno(UNIT(s), r, "Failed to open IPC namespace path %s: %m", s->exec_context.ipc_namespace_path);
×
1605
                }
1606
        }
1607

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

1611
        r = unit_fork_helper_process(UNIT(s), "(sd-listen)", /* into_cgroup= */ true, &pid);
×
1612
        if (r < 0)
15✔
UNCOV
1613
                return log_unit_error_errno(UNIT(s), r, "Failed to fork off listener stub process: %m");
×
1614
        if (r == 0) {
15✔
1615
                /* Child */
1616

1617
                pair[0] = safe_close(pair[0]);
15✔
1618

1619
                if (exec_needs_network_namespace(&s->exec_context) &&
15✔
1620
                    s->exec_runtime &&
×
UNCOV
1621
                    s->exec_runtime->shared &&
×
1622
                    s->exec_runtime->shared->netns_storage_socket[0] >= 0) {
×
1623

1624
                        if (namespace_type_supported(NAMESPACE_NET)) {
×
1625
                                r = setup_shareable_ns(s->exec_runtime->shared->netns_storage_socket, CLONE_NEWNET);
×
1626
                                if (r < 0) {
×
UNCOV
1627
                                        log_unit_error_errno(UNIT(s), r, "Failed to join network namespace: %m");
×
1628
                                        _exit(EXIT_NETWORK);
×
1629
                                }
1630
                        } else if (s->exec_context.network_namespace_path) {
×
UNCOV
1631
                                log_unit_error(UNIT(s), "Network namespace path configured but network namespaces not supported.");
×
1632
                                _exit(EXIT_NETWORK);
×
1633
                        } else
UNCOV
1634
                                log_unit_warning(UNIT(s), "PrivateNetwork=yes is configured, but the kernel does not support network namespaces, ignoring.");
×
1635
                }
1636

1637
                fd = socket_address_listen_do(s, address, label);
15✔
1638
                if (fd < 0) {
15✔
UNCOV
1639
                        log_address_error_errno(UNIT(s), address, fd, "Failed to create listening socket (%s): %m");
×
UNCOV
1640
                        _exit(EXIT_FAILURE);
×
1641
                }
1642

1643
                r = send_one_fd(pair[1], fd, 0);
15✔
1644
                if (r < 0) {
15✔
UNCOV
1645
                        log_address_error_errno(UNIT(s), address, r, "Failed to send listening socket (%s) to parent: %m");
×
UNCOV
1646
                        _exit(EXIT_FAILURE);
×
1647
                }
1648

1649
                _exit(EXIT_SUCCESS);
15✔
1650
        }
1651

UNCOV
1652
        pair[1] = safe_close(pair[1]);
×
UNCOV
1653
        fd = receive_one_fd(pair[0], 0);
×
1654

1655
        /* We synchronously wait for the helper, as it shouldn't be slow */
1656
        r = wait_for_terminate_and_check("(sd-listen)", pid.pid, WAIT_LOG_ABNORMAL);
×
UNCOV
1657
        if (r < 0) {
×
UNCOV
1658
                safe_close(fd);
×
1659
                return r;
1660
        }
1661

UNCOV
1662
        if (fd < 0)
×
UNCOV
1663
                return log_address_error_errno(UNIT(s), address, fd, "Failed to receive listening socket (%s): %m");
×
1664

1665
        return fd;
1666
}
1667

1668
static int socket_open_fds(Socket *orig_s) {
3,222✔
1669
        _cleanup_(socket_close_fdsp) Socket *s = orig_s;
3,222✔
1670
        _cleanup_freecon_ char *label = NULL;
3,222✔
1671
        bool know_label = false;
3,222✔
1672
        int r;
3,222✔
1673

1674
        assert(s);
3,222✔
1675

1676
        LIST_FOREACH(port, p, s->ports) {
3,222✔
1677

1678
                if (p->fd >= 0)
3,513✔
UNCOV
1679
                        continue;
×
1680

1681
                switch (p->type) {
3,513✔
1682

1683
                case SOCKET_SOCKET:
3,434✔
1684

1685
                        if (!know_label) {
3,434✔
1686
                                /* Figure out the label, if we don't it know yet. We do it once for the first
1687
                                 * socket where we need this and remember it for the rest. */
1688

1689
                                r = socket_determine_selinux_label(s, &label);
3,179✔
1690
                                if (r < 0)
3,179✔
UNCOV
1691
                                        return log_unit_error_errno(UNIT(s), r, "Failed to determine SELinux label: %m");
×
1692

1693
                                know_label = true;
1694
                        }
1695

1696
                        /* Apply the socket protocol */
1697
                        switch (p->address.type) {
3,434✔
1698

1699
                        case SOCK_STREAM:
3,251✔
1700
                                if (IN_SET(s->socket_protocol, IPPROTO_SCTP, IPPROTO_MPTCP))
3,251✔
UNCOV
1701
                                        p->address.protocol = s->socket_protocol;
×
1702
                                break;
1703

1704
                        case SOCK_SEQPACKET:
53✔
1705
                                if (s->socket_protocol == IPPROTO_SCTP)
53✔
UNCOV
1706
                                        p->address.protocol = s->socket_protocol;
×
1707
                                break;
1708

1709
                        case SOCK_DGRAM:
66✔
1710
                                if (s->socket_protocol == IPPROTO_UDPLITE)
66✔
UNCOV
1711
                                        p->address.protocol = s->socket_protocol;
×
1712
                                break;
1713
                        }
1714

1715
                        p->fd = socket_address_listen_in_cgroup(s, &p->address, label);
3,434✔
1716
                        if (p->fd < 0)
3,434✔
1717
                                return p->fd;
1718

1719
                        socket_apply_socket_options(s, p, p->fd);
3,434✔
1720
                        socket_symlink(s);
3,434✔
1721
                        break;
1722

1723
                case SOCKET_SPECIAL:
6✔
1724

1725
                        p->fd = special_address_create(p->path, s->writable);
6✔
1726
                        if (p->fd < 0)
6✔
UNCOV
1727
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open special file '%s': %m", p->path);
×
1728
                        break;
1729

1730
                case SOCKET_FIFO:
73✔
1731

1732
                        p->fd = fifo_address_create(
146✔
1733
                                        p->path,
73✔
1734
                                        s->directory_mode,
1735
                                        s->socket_mode);
1736
                        if (p->fd < 0)
73✔
UNCOV
1737
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open FIFO '%s': %m", p->path);
×
1738

1739
                        socket_apply_fifo_options(s, p->fd);
73✔
1740
                        socket_symlink(s);
73✔
1741
                        break;
1742

1743
                case SOCKET_MQUEUE:
×
1744

UNCOV
1745
                        p->fd = mq_address_create(
×
UNCOV
1746
                                        p->path,
×
1747
                                        s->socket_mode,
1748
                                        s->mq_maxmsg,
1749
                                        s->mq_msgsize);
UNCOV
1750
                        if (p->fd < 0)
×
UNCOV
1751
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open message queue '%s': %m", p->path);
×
1752
                        break;
1753

UNCOV
1754
                case SOCKET_USB_FUNCTION: {
×
1755
                        _cleanup_close_ int dfd = -EBADF;
6,735✔
1756

1757
                        dfd = open(p->path, O_DIRECTORY|O_CLOEXEC);
×
UNCOV
1758
                        if (dfd < 0)
×
UNCOV
1759
                                return log_unit_error_errno(UNIT(s), errno,
×
1760
                                                            "Failed to open USB FunctionFS dir '%s': %m", p->path);
1761

1762
                        p->fd = usbffs_address_create_at(dfd, "ep0");
×
UNCOV
1763
                        if (p->fd < 0)
×
1764
                                return log_unit_error_errno(UNIT(s), p->fd, "Failed to open USB FunctionFS ep0: %m");
×
1765

1766
                        r = usbffs_write_descs(p->fd, SERVICE(UNIT_DEREF(s->service)));
×
UNCOV
1767
                        if (r < 0)
×
1768
                                return log_unit_error_errno(UNIT(s), r, "Failed to write to USB FunctionFS ep0: %m");
×
1769

1770
                        r = usbffs_dispatch_eps(p, dfd);
×
UNCOV
1771
                        if (r < 0)
×
1772
                                return log_unit_error_errno(UNIT(s), r, "Failed to dispatch USB FunctionFS eps: %m");
×
1773

UNCOV
1774
                        break;
×
1775
                }
1776

UNCOV
1777
                default:
×
UNCOV
1778
                        assert_not_reached();
×
1779
                }
1780
        }
1781

1782
        TAKE_PTR(s);
1783
        return 0;
1784
}
1785

1786
static void socket_unwatch_fds(Socket *s) {
8,523✔
1787
        int r;
8,523✔
1788

1789
        assert(s);
8,523✔
1790

1791
        LIST_FOREACH(port, p, s->ports) {
17,732✔
1792
                if (p->fd < 0)
9,209✔
1793
                        continue;
3,513✔
1794

1795
                r = sd_event_source_set_enabled(p->event_source, SD_EVENT_OFF);
5,696✔
1796
                if (r < 0)
5,696✔
UNCOV
1797
                        log_unit_debug_errno(UNIT(s), r, "Failed to disable event source: %m");
×
1798
        }
1799
}
8,523✔
1800

1801
static int socket_watch_fds(Socket *s) {
4,793✔
1802
        int r;
4,793✔
1803

1804
        assert(s);
4,793✔
1805

1806
        LIST_FOREACH(port, p, s->ports) {
9,979✔
1807
                if (p->fd < 0)
5,186✔
UNCOV
1808
                        continue;
×
1809

1810
                if (p->event_source) {
5,186✔
1811
                        r = sd_event_source_set_enabled(p->event_source, SD_EVENT_ON);
797✔
1812
                        if (r < 0)
797✔
UNCOV
1813
                                goto fail;
×
1814
                } else {
1815
                        r = sd_event_add_io(UNIT(s)->manager->event, &p->event_source, p->fd, EPOLLIN, socket_dispatch_io, p);
4,389✔
1816
                        if (r < 0)
4,389✔
UNCOV
1817
                                goto fail;
×
1818

1819
                        (void) sd_event_source_set_description(p->event_source, "socket-port-io");
4,389✔
1820
                }
1821

1822
                r = sd_event_source_set_ratelimit(p->event_source, s->poll_limit.interval, s->poll_limit.burst);
5,186✔
1823
                if (r < 0)
5,186✔
UNCOV
1824
                        log_unit_debug_errno(UNIT(s), r, "Failed to set poll limit on I/O event source, ignoring: %m");
×
1825
        }
1826

1827
        return 0;
1828

1829
fail:
×
1830
        log_unit_warning_errno(UNIT(s), r, "Failed to watch listening fds: %m");
×
UNCOV
1831
        socket_unwatch_fds(s);
×
UNCOV
1832
        return r;
×
1833
}
1834

1835
enum {
1836
        SOCKET_OPEN_NONE,
1837
        SOCKET_OPEN_SOME,
1838
        SOCKET_OPEN_ALL,
1839
};
1840

1841
static int socket_check_open(Socket *s) {
1,338✔
1842
        bool have_open = false, have_closed = false;
1,338✔
1843

1844
        assert(s);
1,338✔
1845

1846
        LIST_FOREACH(port, p, s->ports) {
2,817✔
1847
                if (p->fd < 0)
1,479✔
1848
                        have_closed = true;
1849
                else
1850
                        have_open = true;
1,479✔
1851

1852
                if (have_open && have_closed)
1,479✔
1853
                        return SOCKET_OPEN_SOME;
1854
        }
1855

1856
        if (have_open)
1,338✔
1857
                return SOCKET_OPEN_ALL;
1,338✔
1858

1859
        return SOCKET_OPEN_NONE;
1860
}
1861

1862
static void socket_set_state(Socket *s, SocketState state) {
13,316✔
1863
        SocketState old_state;
13,316✔
1864

1865
        assert(s);
13,316✔
1866

1867
        if (s->state != state)
13,316✔
1868
                bus_unit_send_pending_change_signal(UNIT(s), false);
11,732✔
1869

1870
        old_state = s->state;
13,316✔
1871
        s->state = state;
13,316✔
1872

1873
        if (!SOCKET_STATE_WITH_PROCESS(state) && state != SOCKET_DEFERRED)
13,316✔
1874
                s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
13,121✔
1875

1876
        if (!SOCKET_STATE_WITH_PROCESS(state)) {
13,316✔
1877
                socket_unwatch_control_pid(s);
13,121✔
1878
                s->control_command = NULL;
13,121✔
1879
                s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
13,121✔
1880
        }
1881

1882
        if (state != SOCKET_LISTENING)
13,316✔
1883
                socket_unwatch_fds(s);
8,523✔
1884

1885
        if (!IN_SET(state,
8,523✔
1886
                    SOCKET_START_OPEN,
1887
                    SOCKET_START_CHOWN,
1888
                    SOCKET_START_POST,
1889
                    SOCKET_LISTENING,
1890
                    SOCKET_DEFERRED,
1891
                    SOCKET_RUNNING,
1892
                    SOCKET_STOP_PRE,
1893
                    SOCKET_STOP_PRE_SIGTERM,
1894
                    SOCKET_STOP_PRE_SIGKILL))
1895
                socket_close_fds(s);
2,734✔
1896

1897
        if (state != SOCKET_DEFERRED)
13,316✔
1898
                unit_remove_from_stop_notify_queue(UNIT(s));
13,316✔
1899

1900
        if (state != old_state)
13,316✔
1901
                log_unit_debug(UNIT(s), "Changed %s -> %s", socket_state_to_string(old_state), socket_state_to_string(state));
11,732✔
1902

1903
        unit_notify(UNIT(s), state_translation_table[old_state], state_translation_table[state], /* reload_success = */ true);
13,316✔
1904
}
13,316✔
1905

1906
static int socket_coldplug(Unit *u) {
3,204✔
1907
        Socket *s = ASSERT_PTR(SOCKET(u));
3,204✔
1908
        int r;
3,204✔
1909

1910
        assert(s->state == SOCKET_DEAD);
3,204✔
1911

1912
        if (s->deserialized_state == s->state)
3,204✔
1913
                return 0;
1914

1915
        /* Patch "deferred" back to "listening" and let socket_enter_running() figure out what to do.
1916
         * This saves us the trouble of handling flipping of DeferTrigger= vs Accept= during reload. */
1917
        if (s->deserialized_state == SOCKET_DEFERRED)
1,338✔
UNCOV
1918
                s->deserialized_state = SOCKET_LISTENING;
×
1919

1920
        if (pidref_is_set(&s->control_pid) &&
1,338✔
UNCOV
1921
            pidref_is_unwaited(&s->control_pid) > 0 &&
×
1922
            SOCKET_STATE_WITH_PROCESS(s->deserialized_state)) {
×
1923

UNCOV
1924
                r = unit_watch_pidref(UNIT(s), &s->control_pid, /* exclusive= */ false);
×
UNCOV
1925
                if (r < 0)
×
1926
                        return r;
1927

UNCOV
1928
                r = socket_arm_timer(s, /* relative= */ false, usec_add(u->state_change_timestamp.monotonic, s->timeout_usec));
×
UNCOV
1929
                if (r < 0)
×
1930
                        return r;
1931
        }
1932

1933
        if (IN_SET(s->deserialized_state,
1,338✔
1934
                   SOCKET_START_OPEN,
1935
                   SOCKET_START_CHOWN,
1936
                   SOCKET_START_POST,
1937
                   SOCKET_LISTENING,
1938
                   SOCKET_RUNNING)) {
1939

1940
                /* Originally, we used to simply reopen all sockets here that we didn't have file descriptors
1941
                 * for. However, this is problematic, as we won't traverse through the SOCKET_START_CHOWN
1942
                 * state for them, and thus the UID/GID wouldn't be right. Hence, instead simply check if we
1943
                 * have all fds open, and if there's a mismatch, warn loudly.
1944
                 *
1945
                 * Note that SOCKET_START_OPEN requires no special treatment, as it's only intermediate
1946
                 * between SOCKET_START_PRE and SOCKET_START_CHOWN and shall otherwise not be observed.
1947
                 * It's listed only for consistency. */
1948

1949
                r = socket_check_open(s);
1,338✔
1950
                if (r == SOCKET_OPEN_NONE)
1,338✔
UNCOV
1951
                        log_unit_warning(UNIT(s),
×
1952
                                         "Unit configuration changed while unit was running, "
1953
                                         "and no socket file descriptors are open. "
1954
                                         "Unit not functional until restarted.");
1955
                else if (r == SOCKET_OPEN_SOME)
1,338✔
UNCOV
1956
                        log_unit_warning(UNIT(s),
×
1957
                                         "Unit configuration changed while unit was running, "
1958
                                         "and some socket file descriptors have not been opened yet. "
1959
                                         "Unit not fully functional until restarted.");
1960
        }
1961

1962
        if (s->deserialized_state == SOCKET_LISTENING) {
1,338✔
1963
                r = socket_watch_fds(s);
764✔
1964
                if (r < 0)
764✔
1965
                        return r;
1966
        }
1967

1968
        if (!IN_SET(s->deserialized_state, SOCKET_DEAD, SOCKET_FAILED, SOCKET_CLEANING))
1,338✔
1969
                (void) unit_setup_exec_runtime(u);
1,338✔
1970

1971
        socket_set_state(s, s->deserialized_state);
1,338✔
1972
        return 0;
1,338✔
1973
}
1974

1975
static int socket_spawn(Socket *s, ExecCommand *c, PidRef *ret_pid) {
195✔
1976
        _cleanup_(exec_params_shallow_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(
195✔
1977
                        EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN);
1978
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
195✔
1979
        int r;
195✔
1980

1981
        assert(s);
195✔
1982
        assert(c);
195✔
1983
        assert(ret_pid);
195✔
1984

1985
        r = unit_prepare_exec(UNIT(s));
195✔
1986
        if (r < 0)
195✔
1987
                return r;
1988

1989
        r = socket_arm_timer(s, /* relative= */ true, s->timeout_usec);
195✔
1990
        if (r < 0)
195✔
1991
                return r;
1992

1993
        r = unit_set_exec_params(UNIT(s), &exec_params);
195✔
1994
        if (r < 0)
195✔
1995
                return r;
1996

1997
        /* Note that ExecStartPre= command doesn't inherit any FDs. It runs before we open listen FDs. */
1998
        if (s->pass_fds_to_exec) {
195✔
1999
                _cleanup_strv_free_ char **fd_names = NULL;
×
UNCOV
2000
                _cleanup_free_ int *fds = NULL;
×
2001
                int n_fds;
×
2002

UNCOV
2003
                n_fds = socket_collect_fds(s, &fds);
×
UNCOV
2004
                if (n_fds < 0)
×
2005
                        return n_fds;
2006

UNCOV
2007
                r = strv_extend_n(&fd_names, socket_fdname(s), n_fds);
×
UNCOV
2008
                if (r < 0)
×
2009
                        return r;
2010

2011
                exec_params.fds = TAKE_PTR(fds);
×
UNCOV
2012
                exec_params.fd_names = TAKE_PTR(fd_names);
×
UNCOV
2013
                exec_params.n_socket_fds = n_fds;
×
2014
        }
2015

2016
        r = exec_spawn(UNIT(s),
195✔
2017
                       c,
2018
                       &s->exec_context,
195✔
2019
                       &exec_params,
2020
                       s->exec_runtime,
2021
                       &s->cgroup_context,
195✔
2022
                       &pidref);
2023
        if (r < 0)
195✔
2024
                return r;
2025

2026
        r = unit_watch_pidref(UNIT(s), &pidref, /* exclusive= */ true);
195✔
2027
        if (r < 0)
195✔
2028
                return r;
2029

2030
        *ret_pid = TAKE_PIDREF(pidref);
195✔
2031
        return 0;
195✔
2032
}
2033

2034
static int socket_chown(Socket *s, PidRef *ret_pid) {
×
UNCOV
2035
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
×
2036
        int r;
×
2037

2038
        assert(s);
×
2039

UNCOV
2040
        r = socket_arm_timer(s, /* relative= */ true, s->timeout_usec);
×
UNCOV
2041
        if (r < 0)
×
2042
                return r;
2043

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

UNCOV
2047
        r = unit_fork_helper_process(UNIT(s), "(sd-chown)", /* into_cgroup= */ true, &pid);
×
2048
        if (r < 0)
3✔
2049
                return r;
2050
        if (r == 0) {
3✔
2051
                uid_t uid = UID_INVALID;
3✔
2052
                gid_t gid = GID_INVALID;
3✔
2053

2054
                /* Child */
2055

2056
                if (!isempty(s->user)) {
3✔
2057
                        const char *user = s->user;
1✔
2058

2059
                        r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
1✔
2060
                        if (r < 0) {
1✔
UNCOV
2061
                                log_unit_error_errno(UNIT(s), r,
×
2062
                                                     "Failed to resolve user '%s': %s",
2063
                                                     user, STRERROR_USER(r));
UNCOV
2064
                                _exit(EXIT_USER);
×
2065
                        }
2066
                }
2067

2068
                if (!isempty(s->group)) {
3✔
2069
                        const char *group = s->group;
3✔
2070

2071
                        r = get_group_creds(&group, &gid, 0);
3✔
2072
                        if (r < 0) {
3✔
UNCOV
2073
                                log_unit_error_errno(UNIT(s), r,
×
2074
                                                     "Failed to resolve group '%s': %s",
2075
                                                     group, STRERROR_GROUP(r));
UNCOV
2076
                                _exit(EXIT_GROUP);
×
2077
                        }
2078
                }
2079

2080
                LIST_FOREACH(port, p, s->ports) {
6✔
2081
                        const char *path = NULL;
3✔
2082

2083
                        if (p->type == SOCKET_SOCKET)
3✔
2084
                                path = socket_address_get_path(&p->address);
2✔
2085
                        else if (p->type == SOCKET_FIFO)
1✔
UNCOV
2086
                                path = p->path;
×
2087
                        else if (p->type == SOCKET_MQUEUE) {
1✔
2088
                                /* Use fchown on the fd since /dev/mqueue might not be mounted. */
2089
                                if (fchown(p->fd, uid, gid) < 0) {
1✔
UNCOV
2090
                                        log_unit_error_errno(UNIT(s), errno, "Failed to fchown(): %m");
×
UNCOV
2091
                                        _exit(EXIT_CHOWN);
×
2092
                                }
2093
                                continue;
1✔
2094
                        }
2095

2096
                        if (!path)
2✔
UNCOV
2097
                                continue;
×
2098

2099
                        if (chown(path, uid, gid) < 0) {
2✔
UNCOV
2100
                                log_unit_error_errno(UNIT(s), errno, "Failed to chown(): %m");
×
UNCOV
2101
                                _exit(EXIT_CHOWN);
×
2102
                        }
2103
                }
2104

2105
                _exit(EXIT_SUCCESS);
3✔
2106
        }
2107

UNCOV
2108
        r = unit_watch_pidref(UNIT(s), &pid, /* exclusive= */ true);
×
UNCOV
2109
        if (r < 0)
×
2110
                return r;
2111

UNCOV
2112
        *ret_pid = TAKE_PIDREF(pid);
×
UNCOV
2113
        return 0;
×
2114
}
2115

2116
static void socket_enter_dead(Socket *s, SocketResult f) {
2,734✔
2117
        assert(s);
2,734✔
2118

2119
        if (s->result == SOCKET_SUCCESS)
2,734✔
2120
                s->result = f;
2,734✔
2121

2122
        if (s->result == SOCKET_SUCCESS)
2,734✔
2123
                unit_log_success(UNIT(s));
2,734✔
2124
        else
UNCOV
2125
                unit_log_failure(UNIT(s), socket_result_to_string(s->result));
×
2126

2127
        unit_warn_leftover_processes(UNIT(s), /* start = */ false);
2,734✔
2128

2129
        socket_set_state(s, s->result != SOCKET_SUCCESS ? SOCKET_FAILED : SOCKET_DEAD);
5,468✔
2130

2131
        s->exec_runtime = exec_runtime_destroy(s->exec_runtime);
2,734✔
2132

2133
        unit_destroy_runtime_data(UNIT(s), &s->exec_context, /* destroy_runtime_dir = */ true);
2,734✔
2134

2135
        unit_unref_uid_gid(UNIT(s), true);
2,734✔
2136
}
2,734✔
2137

2138
static void socket_enter_signal(Socket *s, SocketState state, SocketResult f);
2139

2140
static void socket_enter_stop_post(Socket *s, SocketResult f) {
2,734✔
2141
        int r;
2,734✔
2142

2143
        assert(s);
2,734✔
2144

2145
        if (s->result == SOCKET_SUCCESS)
2,734✔
2146
                s->result = f;
2,734✔
2147

2148
        socket_unwatch_control_pid(s);
2,734✔
2149
        s->control_command_id = SOCKET_EXEC_STOP_POST;
2,734✔
2150
        s->control_command = s->exec_command[SOCKET_EXEC_STOP_POST];
2,734✔
2151

2152
        if (s->control_command) {
2,734✔
2153
                r = socket_spawn(s, s->control_command, &s->control_pid);
×
2154
                if (r < 0) {
×
2155
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop-post' task: %m");
×
UNCOV
2156
                        socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2157
                        return;
×
2158
                }
2159

UNCOV
2160
                socket_set_state(s, SOCKET_STOP_POST);
×
2161
        } else
2162
                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_SUCCESS);
2,734✔
2163
}
2164

2165
static int state_to_kill_operation(Socket *s, SocketState state) {
5,468✔
2166
        assert(s);
5,468✔
2167

2168
        if (state == SOCKET_STOP_PRE_SIGTERM)
5,468✔
UNCOV
2169
                return unit_has_job_type(UNIT(s), JOB_RESTART) ? KILL_RESTART : KILL_TERMINATE;
×
2170

2171
        if (state == SOCKET_FINAL_SIGTERM)
5,468✔
2172
                return KILL_TERMINATE;
2,734✔
2173

2174
        return KILL_KILL;
2175
}
2176

2177
static void socket_enter_signal(Socket *s, SocketState state, SocketResult f) {
5,468✔
2178
        int r;
5,468✔
2179

2180
        assert(s);
5,468✔
2181

2182
        if (s->result == SOCKET_SUCCESS)
5,468✔
2183
                s->result = f;
5,468✔
2184

2185
        r = unit_kill_context(UNIT(s), state_to_kill_operation(s, state));
5,468✔
2186
        if (r < 0) {
5,468✔
UNCOV
2187
                log_unit_warning_errno(UNIT(s), r, "Failed to kill processes: %m");
×
UNCOV
2188
                goto fail;
×
2189
        }
2190
        if (r > 0) {
5,468✔
2191
                r = socket_arm_timer(s, /* relative= */ true, s->timeout_usec);
×
2192
                if (r < 0) {
×
UNCOV
2193
                        log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
UNCOV
2194
                        goto fail;
×
2195
                }
2196

2197
                socket_set_state(s, state);
×
2198
        } else if (state == SOCKET_STOP_PRE_SIGTERM)
5,468✔
2199
                socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_SUCCESS);
×
2200
        else if (state == SOCKET_STOP_PRE_SIGKILL)
5,468✔
UNCOV
2201
                socket_enter_stop_post(s, SOCKET_SUCCESS);
×
2202
        else if (state == SOCKET_FINAL_SIGTERM)
5,468✔
2203
                socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
2,734✔
2204
        else
2205
                socket_enter_dead(s, SOCKET_SUCCESS);
2,734✔
2206

2207
        return;
2208

2209
fail:
×
UNCOV
2210
        if (IN_SET(state, SOCKET_STOP_PRE_SIGTERM, SOCKET_STOP_PRE_SIGKILL))
×
2211
                socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
×
2212
        else
UNCOV
2213
                socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
×
2214
}
2215

2216
static void socket_enter_stop_pre(Socket *s, SocketResult f) {
2,734✔
2217
        int r;
2,734✔
2218

2219
        assert(s);
2,734✔
2220

2221
        if (s->result == SOCKET_SUCCESS)
2,734✔
2222
                s->result = f;
2,734✔
2223

2224
        socket_unwatch_control_pid(s);
2,734✔
2225
        s->control_command_id = SOCKET_EXEC_STOP_PRE;
2,734✔
2226
        s->control_command = s->exec_command[SOCKET_EXEC_STOP_PRE];
2,734✔
2227

2228
        if (s->control_command) {
2,734✔
2229
                r = socket_spawn(s, s->control_command, &s->control_pid);
3✔
2230
                if (r < 0) {
3✔
2231
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'stop-pre' task: %m");
×
UNCOV
2232
                        socket_enter_stop_post(s, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2233
                        return;
×
2234
                }
2235

2236
                socket_set_state(s, SOCKET_STOP_PRE);
3✔
2237
        } else
2238
                socket_enter_stop_post(s, SOCKET_SUCCESS);
2,731✔
2239
}
2240

UNCOV
2241
static void flush_ports(Socket *s) {
×
UNCOV
2242
        assert(s);
×
2243

2244
        /* Flush all incoming traffic, regardless if actual bytes or new connections, so that this socket isn't busy
2245
         * anymore */
2246

2247
        LIST_FOREACH(port, p, s->ports) {
×
UNCOV
2248
                if (p->fd < 0)
×
2249
                        continue;
×
2250

UNCOV
2251
                if (p->type == SOCKET_MQUEUE)
×
2252
                        (void) flush_mqueue(p->fd);
×
2253
                else {
UNCOV
2254
                        (void) flush_accept(p->fd);
×
UNCOV
2255
                        (void) flush_fd(p->fd);
×
2256
                }
2257
        }
UNCOV
2258
}
×
2259

2260
static void socket_enter_listening(Socket *s) {
4,029✔
2261
        int r;
4,029✔
2262

2263
        assert(s);
4,029✔
2264

2265
        if (!s->accept && s->flush_pending) {
4,029✔
UNCOV
2266
                log_unit_debug(UNIT(s), "Flushing socket before listening.");
×
UNCOV
2267
                flush_ports(s);
×
2268
        }
2269

2270
        r = socket_watch_fds(s);
4,029✔
2271
        if (r < 0) {
4,029✔
2272
                log_unit_warning_errno(UNIT(s), r, "Failed to watch sockets: %m");
×
UNCOV
2273
                socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2274
                return;
×
2275
        }
2276

2277
        socket_set_state(s, SOCKET_LISTENING);
4,029✔
2278
}
2279

2280
static void socket_enter_start_post(Socket *s) {
3,222✔
2281
        int r;
3,222✔
2282

2283
        assert(s);
3,222✔
2284

2285
        socket_unwatch_control_pid(s);
3,222✔
2286
        s->control_command_id = SOCKET_EXEC_START_POST;
3,222✔
2287
        s->control_command = s->exec_command[SOCKET_EXEC_START_POST];
3,222✔
2288

2289
        if (s->control_command) {
3,222✔
2290
                r = socket_spawn(s, s->control_command, &s->control_pid);
192✔
2291
                if (r < 0) {
192✔
2292
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-post' task: %m");
×
UNCOV
2293
                        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2294
                        return;
×
2295
                }
2296

2297
                socket_set_state(s, SOCKET_START_POST);
192✔
2298
        } else
2299
                socket_enter_listening(s);
3,030✔
2300
}
2301

2302
static void socket_enter_start_chown(Socket *s) {
3,222✔
2303
        int r;
3,222✔
2304

2305
        assert(s);
3,222✔
2306
        assert(s->state == SOCKET_START_OPEN);
3,222✔
2307

2308
        if (!isempty(s->user) || !isempty(s->group)) {
3,222✔
2309

2310
                socket_unwatch_control_pid(s);
×
UNCOV
2311
                s->control_command_id = SOCKET_EXEC_START_CHOWN;
×
2312
                s->control_command = NULL;
×
2313

2314
                r = socket_chown(s, &s->control_pid);
×
2315
                if (r < 0) {
×
2316
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-chown' task: %m");
×
UNCOV
2317
                        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2318
                        return;
×
2319
                }
2320

UNCOV
2321
                socket_set_state(s, SOCKET_START_CHOWN);
×
2322
        } else
2323
                socket_enter_start_post(s);
3,222✔
2324
}
2325

2326
static void socket_enter_start_open(Socket *s) {
3,222✔
2327
        int r;
3,222✔
2328

2329
        assert(s);
3,222✔
2330
        assert(IN_SET(s->state, SOCKET_DEAD, SOCKET_FAILED, SOCKET_START_PRE));
3,222✔
2331

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

2337
        socket_set_state(s, SOCKET_START_OPEN);
3,222✔
2338

2339
        r = socket_open_fds(s);
3,222✔
2340
        if (r < 0) {
3,222✔
2341
                log_unit_error_errno(UNIT(s), r, "Failed to listen on sockets: %m");
×
UNCOV
2342
                socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2343
                return;
×
2344
        }
2345

2346
        socket_enter_start_chown(s);
3,222✔
2347
}
2348

2349
static void socket_enter_start_pre(Socket *s) {
3,222✔
2350
        int r;
3,222✔
2351

2352
        assert(s);
3,222✔
2353

2354
        socket_unwatch_control_pid(s);
3,222✔
2355

2356
        unit_warn_leftover_processes(UNIT(s), /* start = */ true);
3,222✔
2357

2358
        s->control_command_id = SOCKET_EXEC_START_PRE;
3,222✔
2359
        s->control_command = s->exec_command[SOCKET_EXEC_START_PRE];
3,222✔
2360

2361
        if (s->control_command) {
3,222✔
2362
                r = socket_spawn(s, s->control_command, &s->control_pid);
×
2363
                if (r < 0) {
×
2364
                        log_unit_warning_errno(UNIT(s), r, "Failed to spawn 'start-pre' task: %m");
×
UNCOV
2365
                        socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2366
                        return;
×
2367
                }
2368

UNCOV
2369
                socket_set_state(s, SOCKET_START_PRE);
×
2370
        } else
2371
                socket_enter_start_open(s);
3,222✔
2372
}
2373

UNCOV
2374
static bool socket_may_defer(Socket *s) {
×
2375
        assert(s);
×
2376

UNCOV
2377
        switch (s->defer_trigger) {
×
2378

2379
        case SOCKET_DEFER_NO:
2380
                return false;
2381

2382
        case SOCKET_DEFER_YES:
2383
                return !hashmap_isempty(UNIT(s)->manager->jobs);
×
2384

UNCOV
2385
        case SOCKET_DEFER_PATIENT:
×
UNCOV
2386
                assert(s->defer_trigger_max_usec > 0);
×
2387
                return true;
2388

UNCOV
2389
        default:
×
UNCOV
2390
                assert_not_reached();
×
2391
        }
2392
}
2393

2394
static bool socket_stop_notify(Unit *u) {
×
2395
        Socket *s = ASSERT_PTR(SOCKET(u));
×
UNCOV
2396
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
×
2397
        int r;
×
2398

2399
        assert(s->state == SOCKET_DEFERRED);
×
2400

2401
        r = manager_add_job(u->manager, JOB_START, UNIT_DEREF(s->service), JOB_LENIENT, &error, /* ret = */ NULL);
×
UNCOV
2402
        if (r >= 0) { /* Yay! */
×
UNCOV
2403
                socket_set_state(s, SOCKET_RUNNING);
×
2404
                return true; /* changed */
2405
        }
UNCOV
2406
        if (sd_bus_error_has_name(&error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE)) {
×
UNCOV
2407
                if (s->defer_trigger == SOCKET_DEFER_PATIENT || !hashmap_isempty(u->manager->jobs))
×
2408
                        /* Wait for some more */
2409
                        return false;
2410

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

UNCOV
2415
        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2416
        return true; /* changed */
2417
}
2418

UNCOV
2419
static void socket_enter_deferred(Socket *s) {
×
2420
        int r;
×
2421

UNCOV
2422
        assert(s);
×
UNCOV
2423
        assert(socket_may_defer(s));
×
2424

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

2432
        r = socket_arm_timer(s, /* relative = */ true, s->defer_trigger_max_usec);
×
2433
        if (r < 0) {
×
UNCOV
2434
                log_unit_warning_errno(UNIT(s), r, "Failed to install timer: %m");
×
UNCOV
2435
                return socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2436
        }
2437

UNCOV
2438
        unit_add_to_stop_notify_queue(UNIT(s));
×
2439

2440
        /* Disable IO event sources */
UNCOV
2441
        socket_set_state(s, SOCKET_DEFERRED);
×
2442
}
2443

2444
static void socket_enter_running(Socket *s, int cfd_in) {
272✔
2445
        /* Note that this call takes possession of the connection fd passed. It either has to assign it
2446
         * somewhere or close it. */
2447
        _cleanup_close_ int cfd = cfd_in;
272✔
2448
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
272✔
2449
        int r;
272✔
2450

2451
        assert(s);
272✔
2452

2453
        /* We don't take connections anymore if we are supposed to shut down anyway */
2454
        if (unit_stop_pending(UNIT(s))) {
272✔
2455

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

UNCOV
2458
                if (cfd >= 0)
×
2459
                        goto refuse;
×
2460

UNCOV
2461
                flush_ports(s);
×
2462
                return;
2463
        }
2464

2465
        if (s->state == SOCKET_DEFERRED) {
272✔
UNCOV
2466
                assert(cfd < 0);
×
2467
                return;
2468
        }
2469

2470
        if (!ratelimit_below(&s->trigger_limit)) {
272✔
2471
                log_unit_warning(UNIT(s), "Trigger limit hit, refusing further activation.");
×
UNCOV
2472
                socket_enter_stop_pre(s, SOCKET_FAILURE_TRIGGER_LIMIT_HIT);
×
UNCOV
2473
                goto refuse;
×
2474
        }
2475

2476
        if (cfd < 0) { /* Accept=no case */
272✔
2477
                bool pending = false;
180✔
2478
                Unit *other;
180✔
2479

2480
                /* If there's already a start pending don't bother to do anything */
2481
                UNIT_FOREACH_DEPENDENCY(other, UNIT(s), UNIT_ATOM_TRIGGERS)
628✔
2482
                        if (unit_active_or_pending(other)) {
180✔
2483
                                pending = true;
2484
                                break;
2485
                        }
2486

2487
                if (!pending) {
180✔
2488
                        if (!UNIT_ISSET(s->service)) {
88✔
2489
                                log_unit_warning(UNIT(s),
×
2490
                                                 "Service to activate vanished, refusing activation.");
UNCOV
2491
                                goto fail;
×
2492
                        }
2493

2494
                        if (s->defer_trigger != SOCKET_DEFER_NO) {
88✔
UNCOV
2495
                                r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_LENIENT, &error, /* ret = */ NULL);
×
UNCOV
2496
                                if (r < 0 && sd_bus_error_has_name(&error, BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE) && socket_may_defer(s))
×
2497
                                        /* We only check BUS_ERROR_TRANSACTION_IS_DESTRUCTIVE here, not
2498
                                         * BUS_ERROR_TRANSACTION_JOBS_CONFLICTING or BUS_ERROR_TRANSACTION_ORDER_IS_CYCLIC,
2499
                                         * since those are errors in a single transaction, which are most likely
2500
                                         * caused by dependency issues in the unit configuration.
2501
                                         * Deferring activation probably won't help. */
UNCOV
2502
                                        return socket_enter_deferred(s);
×
2503
                        } else
2504
                                r = manager_add_job(UNIT(s)->manager, JOB_START, UNIT_DEREF(s->service), JOB_REPLACE, &error, /* ret = */ NULL);
88✔
2505
                        if (r < 0)
88✔
UNCOV
2506
                                goto queue_error;
×
2507
                }
2508

2509
                socket_set_state(s, SOCKET_RUNNING);
180✔
2510
        } else { /* Accept=yes case */
2511
                _cleanup_(socket_peer_unrefp) SocketPeer *p = NULL;
92✔
2512
                Unit *service;
92✔
2513

2514
                if (s->n_connections >= s->max_connections) {
92✔
2515
                        log_unit_warning(UNIT(s), "Too many incoming connections (%u), dropping connection.",
×
2516
                                         s->n_connections);
UNCOV
2517
                        goto refuse;
×
2518
                }
2519

2520
                if (s->max_connections_per_source > 0) {
92✔
2521
                        r = socket_acquire_peer(s, cfd, &p);
89✔
2522
                        if (ERRNO_IS_NEG_DISCONNECT(r))
89✔
2523
                                return;
2524
                        if (r < 0)
89✔
2525
                                /* We didn't have enough resources to acquire peer information, let's fail. */
2526
                                goto fail;
×
2527
                        if (r > 0 && p->n_ref > s->max_connections_per_source) {
89✔
2528
                                _cleanup_free_ char *t = NULL;
×
2529

UNCOV
2530
                                if (p->peer.sa.sa_family == AF_UNIX)
×
2531
                                        (void) asprintf(&t, "UID " UID_FMT, p->peer_cred.uid);
×
2532
                                else
2533
                                        (void) sockaddr_pretty(&p->peer.sa, p->peer_salen, /* translate_ipv6= */ true, /* include_port= */ false, &t);
×
2534

UNCOV
2535
                                log_unit_warning(UNIT(s),
×
2536
                                                 "Too many incoming connections (%u) from source %s, dropping connection.",
2537
                                                 p->n_ref, strnull(t));
UNCOV
2538
                                goto refuse;
×
2539
                        }
2540
                }
2541

2542
                r = socket_load_service_unit(s, cfd, &service);
92✔
2543
                if (ERRNO_IS_NEG_DISCONNECT(r))
92✔
2544
                        return;
2545
                if (r < 0 || UNIT_IS_LOAD_ERROR(service->load_state)) {
92✔
2546
                        log_unit_warning_errno(UNIT(s), r < 0 ? r : service->load_error,
×
2547
                                               "Failed to load connection service unit: %m");
UNCOV
2548
                        goto fail;
×
2549
                }
2550
                if (service->load_state == UNIT_MASKED) {
92✔
UNCOV
2551
                        log_unit_warning(UNIT(s), "Connection service unit is masked, refusing.");
×
UNCOV
2552
                        goto fail;
×
2553
                }
2554

2555
                s->n_accepted++;
92✔
2556

2557
                r = service_set_socket_fd(SERVICE(service), cfd, s, p, s->selinux_context_from_net);
184✔
2558
                if (ERRNO_IS_NEG_DISCONNECT(r))
92✔
2559
                        return;
2560
                if (r < 0) {
92✔
UNCOV
2561
                        log_unit_warning_errno(UNIT(s), r, "Failed to set socket on service: %m");
×
UNCOV
2562
                        goto fail;
×
2563
                }
2564

2565
                /* We passed ownership of the fd and socket peer to the service now. */
2566
                TAKE_FD(cfd);
92✔
2567
                TAKE_PTR(p);
92✔
2568

2569
                s->n_connections++;
92✔
2570

2571
                r = manager_add_job(UNIT(s)->manager, JOB_START, service, JOB_REPLACE, &error, /* ret = */ NULL);
92✔
2572
                if (r < 0) {
92✔
2573
                        /* We failed to activate the new service, but it still exists. Let's make sure the
2574
                         * service closes and forgets the connection fd again, immediately. */
UNCOV
2575
                        service_release_socket_fd(SERVICE(service));
×
UNCOV
2576
                        goto queue_error;
×
2577
                }
2578

2579
                /* Notify clients about changed counters */
2580
                unit_add_to_dbus_queue(UNIT(s));
92✔
2581
        }
2582

2583
        return;
2584

2585
refuse:
×
UNCOV
2586
        s->n_refused++;
×
2587
        return;
×
2588

UNCOV
2589
queue_error:
×
UNCOV
2590
        log_unit_warning_errno(UNIT(s), r, "Failed to queue service startup job%s: %s",
×
2591
                               cfd >= 0 && !ERRNO_IS_RESOURCE(r) ? " (Maybe the service is missing or is a template unit?)" : "",
2592
                               bus_error_message(&error, r));
2593

UNCOV
2594
fail:
×
UNCOV
2595
        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
2596
}
2597

UNCOV
2598
static void socket_run_next(Socket *s) {
×
2599
        int r;
×
2600

2601
        assert(s);
×
UNCOV
2602
        assert(s->control_command);
×
2603
        assert(s->control_command->command_next);
×
2604

2605
        socket_unwatch_control_pid(s);
×
2606

2607
        s->control_command = s->control_command->command_next;
×
2608

2609
        r = socket_spawn(s, s->control_command, &s->control_pid);
×
UNCOV
2610
        if (r < 0) {
×
2611
                log_unit_warning_errno(UNIT(s), r, "Failed to spawn next task: %m");
×
2612

2613
                if (s->state == SOCKET_START_POST)
×
2614
                        socket_enter_stop_pre(s, SOCKET_FAILURE_RESOURCES);
×
UNCOV
2615
                else if (s->state == SOCKET_STOP_POST)
×
2616
                        socket_enter_dead(s, SOCKET_FAILURE_RESOURCES);
×
2617
                else
2618
                        socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_RESOURCES);
×
2619
        }
UNCOV
2620
}
×
2621

2622
static int socket_start(Unit *u) {
3,222✔
2623
        Socket *s = ASSERT_PTR(SOCKET(u));
3,222✔
2624
        int r;
3,222✔
2625

2626
        /* Cannot run this without the service being around */
2627
        if (UNIT_ISSET(s->service)) {
3,222✔
2628
                Service *service = ASSERT_PTR(SERVICE(UNIT_DEREF(s->service)));
2,678✔
2629

2630
                if (UNIT(service)->load_state != UNIT_LOADED)
2,678✔
UNCOV
2631
                        return log_unit_error_errno(u, SYNTHETIC_ERRNO(ENOENT),
×
2632
                                                    "Socket service %s not loaded, refusing.", UNIT(service)->id);
2633

2634
                /* If the service is already active we cannot start the socket */
2635
                if (SOCKET_SERVICE_IS_ACTIVE(service, /* allow_finalize = */ false))
2,678✔
UNCOV
2636
                        return log_unit_error_errno(u, SYNTHETIC_ERRNO(EBUSY),
×
2637
                                                    "Socket service %s already active, refusing.", UNIT(service)->id);
2638
        }
2639

2640
        assert(IN_SET(s->state, SOCKET_DEAD, SOCKET_FAILED));
3,222✔
2641

2642
        r = unit_acquire_invocation_id(u);
3,222✔
2643
        if (r < 0)
3,222✔
2644
                return r;
2645

2646
        s->result = SOCKET_SUCCESS;
3,222✔
2647
        exec_command_reset_status_list_array(s->exec_command, _SOCKET_EXEC_COMMAND_MAX);
3,222✔
2648

2649
        if (s->cgroup_runtime)
3,222✔
UNCOV
2650
                s->cgroup_runtime->reset_accounting = true;
×
2651

2652
        socket_enter_start_pre(s);
3,222✔
2653
        return 1;
3,222✔
2654
}
2655

2656
static int socket_stop(Unit *u) {
2,734✔
2657
        Socket *s = ASSERT_PTR(SOCKET(u));
2,734✔
2658

2659
        /* Already on it */
2660
        if (IN_SET(s->state,
2,734✔
2661
                   SOCKET_STOP_PRE,
2662
                   SOCKET_STOP_PRE_SIGTERM,
2663
                   SOCKET_STOP_PRE_SIGKILL,
2664
                   SOCKET_STOP_POST,
2665
                   SOCKET_FINAL_SIGTERM,
2666
                   SOCKET_FINAL_SIGKILL))
2667
                return 0;
2668

2669
        /* If there's already something running we go directly into
2670
         * kill mode. */
2671
        if (IN_SET(s->state,
2,734✔
2672
                   SOCKET_START_PRE,
2673
                   SOCKET_START_OPEN,
2674
                   SOCKET_START_CHOWN,
2675
                   SOCKET_START_POST)) {
UNCOV
2676
                socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_SUCCESS);
×
UNCOV
2677
                return -EAGAIN;
×
2678
        }
2679

2680
        /* If we are currently cleaning, then abort it, brutally. */
2681
        if (s->state == SOCKET_CLEANING) {
2,734✔
UNCOV
2682
                socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_SUCCESS);
×
UNCOV
2683
                return 0;
×
2684
        }
2685

2686
        assert(IN_SET(s->state, SOCKET_LISTENING, SOCKET_DEFERRED, SOCKET_RUNNING));
2,734✔
2687

2688
        socket_enter_stop_pre(s, SOCKET_SUCCESS);
2,734✔
2689
        return 1;
2,734✔
2690
}
2691

2692
static int socket_serialize(Unit *u, FILE *f, FDSet *fds) {
2,658✔
2693
        Socket *s = ASSERT_PTR(SOCKET(u));
2,658✔
2694
        int r;
2,658✔
2695

2696
        assert(f);
2,658✔
2697
        assert(fds);
2,658✔
2698

2699
        (void) serialize_item(f, "state", socket_state_to_string(s->state));
2,658✔
2700
        (void) serialize_item(f, "result", socket_result_to_string(s->result));
2,658✔
2701
        (void) serialize_item_format(f, "n-accepted", "%u", s->n_accepted);
2,658✔
2702
        (void) serialize_item_format(f, "n-refused", "%u", s->n_refused);
2,658✔
2703
        (void) serialize_pidref(f, fds, "control-pid", &s->control_pid);
2,658✔
2704

2705
        if (s->control_command_id >= 0)
2,658✔
UNCOV
2706
                (void) serialize_item(f, "control-command", socket_exec_command_to_string(s->control_command_id));
×
2707

2708
        LIST_FOREACH(port, p, s->ports) {
5,520✔
2709
                int copy;
2,862✔
2710

2711
                if (p->fd < 0)
2,862✔
2712
                        continue;
998✔
2713

2714
                copy = fdset_put_dup(fds, p->fd);
1,864✔
2715
                if (copy < 0)
1,864✔
UNCOV
2716
                        return log_unit_warning_errno(u, copy, "Failed to serialize socket fd: %m");
×
2717

2718
                if (p->type == SOCKET_SOCKET) {
1,864✔
2719
                        _cleanup_free_ char *t = NULL;
1,734✔
2720

2721
                        r = socket_address_print(&p->address, &t);
1,734✔
2722
                        if (r < 0)
1,734✔
UNCOV
2723
                                return log_unit_error_errno(u, r, "Failed to format socket address: %m");
×
2724

2725
                        if (socket_address_family(&p->address) == AF_NETLINK)
1,734✔
2726
                                (void) serialize_item_format(f, "netlink", "%i %s", copy, t);
114✔
2727
                        else
2728
                                (void) serialize_item_format(f, "socket", "%i %i %s", copy, p->address.type, t);
1,620✔
2729
                } else if (p->type == SOCKET_SPECIAL)
130✔
2730
                        (void) serialize_item_format(f, "special", "%i %s", copy, p->path);
18✔
2731
                else if (p->type == SOCKET_MQUEUE)
112✔
2732
                        (void) serialize_item_format(f, "mqueue", "%i %s", copy, p->path);
×
2733
                else if (p->type == SOCKET_USB_FUNCTION)
112✔
UNCOV
2734
                        (void) serialize_item_format(f, "ffs", "%i %s", copy, p->path);
×
2735
                else {
2736
                        assert(p->type == SOCKET_FIFO);
112✔
2737
                        (void) serialize_item_format(f, "fifo", "%i %s", copy, p->path);
112✔
2738
                }
2739
        }
2740

2741
        (void) serialize_ratelimit(f, "trigger-ratelimit", &s->trigger_limit);
2,658✔
2742

2743
        return 0;
2,658✔
2744
}
2745

2746
static int socket_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
11,379✔
2747
        Socket *s = ASSERT_PTR(SOCKET(u));
11,379✔
2748
        int r;
11,379✔
2749

2750
        assert(key);
11,379✔
2751
        assert(value);
11,379✔
2752

2753
        if (streq(key, "state")) {
11,379✔
2754
                SocketState state;
1,980✔
2755

2756
                state = socket_state_from_string(value);
1,980✔
2757
                if (state < 0)
1,980✔
UNCOV
2758
                        log_unit_debug(u, "Failed to parse state value: %s", value);
×
2759
                else
2760
                        s->deserialized_state = state;
1,980✔
2761
        } else if (streq(key, "result")) {
9,399✔
2762
                SocketResult f;
1,980✔
2763

2764
                f = socket_result_from_string(value);
1,980✔
2765
                if (f < 0)
1,980✔
2766
                        log_unit_debug(u, "Failed to parse result value: %s", value);
×
2767
                else if (f != SOCKET_SUCCESS)
1,980✔
UNCOV
2768
                        s->result = f;
×
2769

2770
        } else if (streq(key, "n-accepted")) {
7,419✔
2771
                unsigned k;
1,980✔
2772

2773
                if (safe_atou(value, &k) < 0)
1,980✔
UNCOV
2774
                        log_unit_debug(u, "Failed to parse n-accepted value: %s", value);
×
2775
                else
2776
                        s->n_accepted += k;
1,980✔
2777
        } else if (streq(key, "n-refused")) {
5,439✔
2778
                unsigned k;
1,980✔
2779

2780
                if (safe_atou(value, &k) < 0)
1,980✔
UNCOV
2781
                        log_unit_debug(u, "Failed to parse n-refused value: %s", value);
×
2782
                else
2783
                        s->n_refused += k;
1,980✔
2784
        } else if (streq(key, "control-pid")) {
3,459✔
2785

2786
                if (!pidref_is_set(&s->control_pid))
11,379✔
UNCOV
2787
                        (void) deserialize_pidref(fds, value, &s->control_pid);
×
2788

2789
        } else if (streq(key, "control-command")) {
3,459✔
2790
                SocketExecCommand id;
×
2791

2792
                id = socket_exec_command_from_string(value);
×
UNCOV
2793
                if (id < 0)
×
2794
                        log_unit_debug(u, "Failed to parse exec-command value: %s", value);
×
2795
                else {
UNCOV
2796
                        s->control_command_id = id;
×
UNCOV
2797
                        s->control_command = s->exec_command[id];
×
2798
                }
2799
        } else if (streq(key, "fifo")) {
3,459✔
2800
                _cleanup_free_ char *fdv = NULL;
90✔
2801
                bool found = false;
90✔
2802
                int fd;
90✔
2803

2804
                r = extract_first_word(&value, &fdv, NULL, 0);
90✔
2805
                if (r <= 0) {
90✔
UNCOV
2806
                        log_unit_debug(u, "Failed to parse fifo value: %s", value);
×
UNCOV
2807
                        return 0;
×
2808
                }
2809

2810
                fd = parse_fd(fdv);
90✔
2811
                if (fd < 0 || !fdset_contains(fds, fd)) {
90✔
UNCOV
2812
                        log_unit_debug(u, "Invalid fifo value: %s", fdv);
×
UNCOV
2813
                        return 0;
×
2814
                }
2815

2816
                LIST_FOREACH(port, p, s->ports)
135✔
2817
                        if (p->fd < 0 &&
135✔
2818
                            p->type == SOCKET_FIFO &&
90✔
2819
                            path_equal_or_inode_same(p->path, value, 0)) {
90✔
2820
                                p->fd = fdset_remove(fds, fd);
90✔
2821
                                found = true;
90✔
2822
                                break;
90✔
2823
                        }
2824
                if (!found)
90✔
UNCOV
2825
                        log_unit_debug(u, "No matching fifo socket found: %s", value);
×
2826

2827
        } else if (streq(key, "special")) {
3,369✔
2828
                _cleanup_free_ char *fdv = NULL;
15✔
2829
                bool found = false;
15✔
2830
                int fd;
15✔
2831

2832
                r = extract_first_word(&value, &fdv, NULL, 0);
15✔
2833
                if (r <= 0) {
15✔
UNCOV
2834
                        log_unit_debug(u, "Failed to parse special value: %s", value);
×
UNCOV
2835
                        return 0;
×
2836
                }
2837

2838
                fd = parse_fd(fdv);
15✔
2839
                if (fd < 0 || !fdset_contains(fds, fd)) {
15✔
UNCOV
2840
                        log_unit_debug(u, "Invalid special value: %s", fdv);
×
UNCOV
2841
                        return 0;
×
2842
                }
2843

2844
                LIST_FOREACH(port, p, s->ports)
15✔
2845
                        if (p->fd < 0 &&
15✔
2846
                            p->type == SOCKET_SPECIAL &&
15✔
2847
                            path_equal_or_inode_same(p->path, value, 0)) {
15✔
2848
                                p->fd = fdset_remove(fds, fd);
15✔
2849
                                found = true;
15✔
2850
                                break;
15✔
2851
                        }
2852
                if (!found)
15✔
UNCOV
2853
                        log_unit_debug(u, "No matching special socket found: %s", value);
×
2854

2855
        } else if (streq(key, "mqueue")) {
3,354✔
2856
                _cleanup_free_ char *fdv = NULL;
×
UNCOV
2857
                bool found = false;
×
2858
                int fd;
×
2859

2860
                r = extract_first_word(&value, &fdv, NULL, 0);
×
2861
                if (r <= 0) {
×
UNCOV
2862
                        log_unit_debug(u, "Failed to parse mqueue value: %s", value);
×
UNCOV
2863
                        return 0;
×
2864
                }
2865

2866
                fd = parse_fd(fdv);
×
2867
                if (fd < 0 || !fdset_contains(fds, fd)) {
×
UNCOV
2868
                        log_unit_debug(u, "Invalid mqueue value: %s", fdv);
×
UNCOV
2869
                        return 0;
×
2870
                }
2871

2872
                LIST_FOREACH(port, p, s->ports)
×
2873
                        if (p->fd < 0 &&
×
2874
                            p->type == SOCKET_MQUEUE &&
×
2875
                            streq(p->path, value)) {
×
2876
                                p->fd = fdset_remove(fds, fd);
×
UNCOV
2877
                                found = true;
×
2878
                                break;
×
2879
                        }
UNCOV
2880
                if (!found)
×
UNCOV
2881
                        log_unit_debug(u, "No matching mqueue socket found: %s", value);
×
2882

2883
        } else if (streq(key, "socket")) {
3,354✔
2884
                _cleanup_free_ char *fdv = NULL, *typev = NULL;
1,293✔
2885
                bool found = false;
1,293✔
2886
                int fd, type;
1,293✔
2887

2888
                r = extract_first_word(&value, &fdv, NULL, 0);
1,293✔
2889
                if (r <= 0) {
1,293✔
UNCOV
2890
                        log_unit_debug(u, "Failed to parse socket fd from value: %s", value);
×
UNCOV
2891
                        return 0;
×
2892
                }
2893

2894
                fd = parse_fd(fdv);
1,293✔
2895
                if (fd < 0 || !fdset_contains(fds, fd)) {
1,293✔
UNCOV
2896
                        log_unit_debug(u, "Invalid socket fd: %s", fdv);
×
UNCOV
2897
                        return 0;
×
2898
                }
2899

2900
                r = extract_first_word(&value, &typev, NULL, 0);
1,293✔
2901
                if (r <= 0) {
1,293✔
UNCOV
2902
                        log_unit_debug(u, "Failed to parse socket type from value: %s", value);
×
UNCOV
2903
                        return 0;
×
2904
                }
2905

2906
                if (safe_atoi(typev, &type) < 0 || type < 0) {
1,293✔
UNCOV
2907
                        log_unit_debug(u, "Invalid socket type: %s", typev);
×
UNCOV
2908
                        return 0;
×
2909
                }
2910

2911
                LIST_FOREACH(port, p, s->ports)
1,389✔
2912
                        if (p->fd < 0 &&
2,682✔
2913
                            socket_address_is(&p->address, value, type)) {
1,293✔
2914
                                p->fd = fdset_remove(fds, fd);
1,293✔
2915
                                found = true;
1,293✔
2916
                                break;
1,293✔
2917
                        }
2918
                if (!found)
1,293✔
UNCOV
2919
                        log_unit_debug(u, "No matching %s socket found: %s",
×
2920
                                       socket_address_type_to_string(type), value);
2921

2922
        } else if (streq(key, "netlink")) {
2,061✔
2923
                _cleanup_free_ char *fdv = NULL;
81✔
2924
                bool found = false;
81✔
2925
                int fd;
81✔
2926

2927
                r = extract_first_word(&value, &fdv, NULL, 0);
81✔
2928
                if (r <= 0) {
81✔
UNCOV
2929
                        log_unit_debug(u, "Failed to parse socket value: %s", value);
×
UNCOV
2930
                        return 0;
×
2931
                }
2932

2933
                fd = parse_fd(fdv);
81✔
2934
                if (fd < 0 || !fdset_contains(fds, fd)) {
81✔
UNCOV
2935
                        log_unit_debug(u, "Invalid socket value: %s", fdv);
×
UNCOV
2936
                        return 0;
×
2937
                }
2938

2939
                LIST_FOREACH(port, p, s->ports)
81✔
2940
                        if (p->fd < 0 &&
162✔
2941
                            socket_address_is_netlink(&p->address, value)) {
81✔
2942
                                p->fd = fdset_remove(fds, fd);
81✔
2943
                                found = true;
81✔
2944
                                break;
81✔
2945
                        }
2946
                if (!found)
81✔
UNCOV
2947
                        log_unit_debug(u, "No matching netlink socket found: %s", value);
×
2948

2949
        } else if (streq(key, "ffs")) {
1,980✔
2950
                _cleanup_free_ char *fdv = NULL;
×
UNCOV
2951
                bool found = false;
×
2952
                int fd;
×
2953

2954
                r = extract_first_word(&value, &fdv, NULL, 0);
×
2955
                if (r <= 0) {
×
UNCOV
2956
                        log_unit_debug(u, "Failed to parse ffs value: %s", value);
×
UNCOV
2957
                        return 0;
×
2958
                }
2959

2960
                fd = parse_fd(fdv);
×
2961
                if (fd < 0 || !fdset_contains(fds, fd)) {
×
UNCOV
2962
                        log_unit_debug(u, "Invalid ffs value: %s", fdv);
×
UNCOV
2963
                        return 0;
×
2964
                }
2965

2966
                LIST_FOREACH(port, p, s->ports)
×
2967
                        if (p->fd < 0 &&
×
2968
                            p->type == SOCKET_USB_FUNCTION &&
×
2969
                            path_equal_or_inode_same(p->path, value, 0)) {
×
2970
                                p->fd = fdset_remove(fds, fd);
×
UNCOV
2971
                                found = true;
×
2972
                                break;
×
2973
                        }
UNCOV
2974
                if (!found)
×
UNCOV
2975
                        log_unit_debug(u, "No matching ffs socket found: %s", value);
×
2976

2977
        } else if (streq(key, "trigger-ratelimit"))
1,980✔
2978
                (void) deserialize_ratelimit(&s->trigger_limit, key, value);
1,980✔
2979
        else
UNCOV
2980
                log_unit_debug(UNIT(s), "Unknown serialization key: %s", key);
×
2981

2982
        return 0;
2983
}
2984

2985
static void socket_distribute_fds(Unit *u, FDSet *fds) {
793✔
2986
        Socket *s = ASSERT_PTR(SOCKET(u));
793✔
2987

2988
        LIST_FOREACH(port, p, s->ports) {
1,644✔
2989
                int fd;
851✔
2990

2991
                if (p->type != SOCKET_SOCKET)
851✔
2992
                        continue;
43✔
2993

2994
                if (p->fd >= 0)
808✔
2995
                        continue;
496✔
2996

2997
                FDSET_FOREACH(fd, fds) {
828✔
2998
                        if (socket_address_matches_fd(&p->address, fd)) {
516✔
2999
                                p->fd = fdset_remove(fds, fd);
×
UNCOV
3000
                                s->deserialized_state = SOCKET_LISTENING;
×
UNCOV
3001
                                break;
×
3002
                        }
3003
                }
3004
        }
3005
}
793✔
3006

3007
static UnitActiveState socket_active_state(Unit *u) {
479,939✔
3008
        Socket *s = ASSERT_PTR(SOCKET(u));
479,939✔
3009

3010
        return state_translation_table[s->state];
479,939✔
3011
}
3012

3013
static const char *socket_sub_state_to_string(Unit *u) {
4,539✔
3014
        Socket *s = ASSERT_PTR(SOCKET(u));
4,539✔
3015

3016
        return socket_state_to_string(s->state);
4,539✔
3017
}
3018

3019
int socket_port_to_address(const SocketPort *p, char **ret) {
88✔
3020
        _cleanup_free_ char *address = NULL;
88✔
3021
        int r;
88✔
3022

3023
        assert(p);
88✔
3024
        assert(ret);
88✔
3025

3026
        switch (p->type) {
88✔
3027
                case SOCKET_SOCKET: {
84✔
3028
                        r = socket_address_print(&p->address, &address);
84✔
3029
                        if (r < 0)
84✔
3030
                                return r;
3031

3032
                        break;
3033
                }
3034

3035
                case SOCKET_SPECIAL:
4✔
3036
                case SOCKET_MQUEUE:
3037
                case SOCKET_FIFO:
3038
                case SOCKET_USB_FUNCTION:
3039
                        address = strdup(p->path);
4✔
3040
                        if (!address)
4✔
3041
                                return -ENOMEM;
3042
                        break;
3043

UNCOV
3044
                default:
×
UNCOV
3045
                        assert_not_reached();
×
3046
        }
3047

3048
        *ret = TAKE_PTR(address);
88✔
3049

3050
        return 0;
88✔
3051
}
3052

3053
const char* socket_port_type_to_string(SocketPort *p) {
88✔
3054
        assert(p);
88✔
3055

3056
        switch (p->type) {
88✔
3057

3058
        case SOCKET_SOCKET:
84✔
3059

3060
                switch (p->address.type) {
84✔
3061

3062
                case SOCK_STREAM:
3063
                        return "Stream";
3064

3065
                case SOCK_DGRAM:
6✔
3066
                        return "Datagram";
6✔
3067

3068
                case SOCK_SEQPACKET:
4✔
3069
                        return "SequentialPacket";
4✔
3070

3071
                case SOCK_RAW:
6✔
3072
                        if (socket_address_family(&p->address) == AF_NETLINK)
6✔
3073
                                return "Netlink";
3074

3075
                        _fallthrough_;
×
3076
                default:
UNCOV
3077
                        return NULL;
×
3078
                }
3079

3080
        case SOCKET_SPECIAL:
3081
                return "Special";
3082

UNCOV
3083
        case SOCKET_MQUEUE:
×
UNCOV
3084
                return "MessageQueue";
×
3085

3086
        case SOCKET_FIFO:
4✔
3087
                return "FIFO";
4✔
3088

UNCOV
3089
        case SOCKET_USB_FUNCTION:
×
3090
                return "USBFunction";
×
3091

UNCOV
3092
        default:
×
UNCOV
3093
                return NULL;
×
3094
        }
3095
}
3096

3097
SocketType socket_port_type_from_string(const char *s) {
2✔
3098
        assert(s);
2✔
3099

3100
        if (STR_IN_SET(s, "Stream", "Datagram", "SequentialPacket", "Netlink"))
2✔
3101
                return SOCKET_SOCKET;
2✔
3102
        else if (streq(s, "Special"))
2✔
3103
                return SOCKET_SPECIAL;
3104
        else if (streq(s, "MessageQueue"))
2✔
3105
                return SOCKET_MQUEUE;
3106
        else if (streq(s, "FIFO"))
2✔
3107
                return SOCKET_FIFO;
UNCOV
3108
        else if (streq(s, "USBFunction"))
×
3109
                return SOCKET_USB_FUNCTION;
3110
        else
UNCOV
3111
                return _SOCKET_TYPE_INVALID;
×
3112
}
3113

3114
static bool socket_may_gc(Unit *u) {
14,346✔
3115
        Socket *s = ASSERT_PTR(SOCKET(u));
14,346✔
3116

3117
        return s->n_connections == 0;
14,346✔
3118
}
3119

3120
static int socket_accept_do(Socket *s, int fd) {
94✔
3121
        int cfd;
94✔
3122

3123
        assert(s);
94✔
3124
        assert(fd >= 0);
94✔
3125

3126
        cfd = accept4(fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC);
94✔
3127
        if (cfd < 0)
94✔
3128
                /* Convert transient network errors into clean and well-defined EAGAIN */
UNCOV
3129
                return ERRNO_IS_ACCEPT_AGAIN(errno) ? -EAGAIN : -errno;
×
3130

3131
        return cfd;
3132
}
3133

3134
static int socket_accept_in_cgroup(Socket *s, SocketPort *p, int fd) {
92✔
UNCOV
3135
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
×
3136
        _cleanup_close_pair_ int pair[2] = EBADF_PAIR;
92✔
3137
        int cfd, r;
92✔
3138

3139
        assert(s);
92✔
3140
        assert(p);
92✔
3141
        assert(fd >= 0);
92✔
3142

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

3146
        if (!IN_SET(p->address.sockaddr.sa.sa_family, AF_INET, AF_INET6))
92✔
3147
                goto shortcut;
92✔
3148

UNCOV
3149
        if (bpf_program_supported() <= 0)
×
3150
                goto shortcut;
×
3151

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

3155
        r = unit_fork_helper_process(UNIT(s), "(sd-accept)", /* into_cgroup= */ true, &pid);
×
3156
        if (r < 0)
2✔
UNCOV
3157
                return log_unit_error_errno(UNIT(s), r, "Failed to fork off accept stub process: %m");
×
3158
        if (r == 0) {
2✔
3159
                /* Child */
3160

3161
                pair[0] = safe_close(pair[0]);
2✔
3162

3163
                cfd = socket_accept_do(s, fd);
2✔
3164
                if (cfd == -EAGAIN) /* spurious accept() */
2✔
3165
                        _exit(EXIT_SUCCESS);
×
3166
                if (cfd < 0) {
2✔
UNCOV
3167
                        log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
×
UNCOV
3168
                        _exit(EXIT_FAILURE);
×
3169
                }
3170

3171
                r = send_one_fd(pair[1], cfd, 0);
2✔
3172
                if (r < 0) {
2✔
UNCOV
3173
                        log_unit_error_errno(UNIT(s), r, "Failed to send connection socket to parent: %m");
×
UNCOV
3174
                        _exit(EXIT_FAILURE);
×
3175
                }
3176

3177
                _exit(EXIT_SUCCESS);
2✔
3178
        }
3179

UNCOV
3180
        pair[1] = safe_close(pair[1]);
×
UNCOV
3181
        cfd = receive_one_fd(pair[0], 0);
×
3182

3183
        /* We synchronously wait for the helper, as it shouldn't be slow */
3184
        r = wait_for_terminate_and_check("(sd-accept)", pid.pid, WAIT_LOG_ABNORMAL);
×
UNCOV
3185
        if (r < 0) {
×
UNCOV
3186
                safe_close(cfd);
×
3187
                return r;
3188
        }
3189

3190
        /* If we received no fd, we got EIO here. If this happens with a process exit code of EXIT_SUCCESS
3191
         * this is a spurious accept(), let's convert that back to EAGAIN here. */
3192
        if (cfd == -EIO)
×
3193
                return -EAGAIN;
UNCOV
3194
        if (cfd < 0)
×
UNCOV
3195
                return log_unit_error_errno(UNIT(s), cfd, "Failed to receive connection socket: %m");
×
3196

3197
        return cfd;
3198

3199
shortcut:
92✔
3200
        cfd = socket_accept_do(s, fd);
92✔
3201
        if (cfd == -EAGAIN) /* spurious accept(), skip it silently */
92✔
3202
                return -EAGAIN;
3203
        if (cfd < 0)
92✔
UNCOV
3204
                return log_unit_error_errno(UNIT(s), cfd, "Failed to accept connection socket: %m");
×
3205

3206
        return cfd;
3207
}
3208

3209
static int socket_dispatch_io(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
272✔
3210
        SocketPort *p = ASSERT_PTR(userdata);
272✔
3211
        int cfd = -EBADF;
272✔
3212

3213
        assert(fd >= 0);
272✔
3214

3215
        if (p->socket->state != SOCKET_LISTENING)
272✔
3216
                return 0;
3217

3218
        log_unit_debug(UNIT(p->socket), "Incoming traffic");
272✔
3219

3220
        if (revents != EPOLLIN) {
272✔
UNCOV
3221
                if (revents & EPOLLHUP)
×
3222
                        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.");
×
3223
                else
UNCOV
3224
                        log_unit_error(UNIT(p->socket), "Got unexpected poll event (0x%x) on socket.", revents);
×
UNCOV
3225
                goto fail;
×
3226
        }
3227

3228
        if (p->socket->accept &&
272✔
3229
            p->type == SOCKET_SOCKET &&
184✔
3230
            socket_address_can_accept(&p->address)) {
92✔
3231

3232
                cfd = socket_accept_in_cgroup(p->socket, p, fd);
92✔
3233
                if (cfd == -EAGAIN) /* Spurious accept() */
92✔
3234
                        return 0;
3235
                if (cfd < 0)
92✔
UNCOV
3236
                        goto fail;
×
3237

3238
                socket_apply_socket_options(p->socket, p, cfd);
92✔
3239
        }
3240

3241
        socket_enter_running(p->socket, cfd);
272✔
3242
        return 0;
272✔
3243

3244
fail:
×
UNCOV
3245
        socket_enter_stop_pre(p->socket, SOCKET_FAILURE_RESOURCES);
×
UNCOV
3246
        return 0;
×
3247
}
3248

3249
static void socket_sigchld_event(Unit *u, pid_t pid, int code, int status) {
195✔
3250
        Socket *s = ASSERT_PTR(SOCKET(u));
195✔
3251
        SocketResult f;
195✔
3252

3253
        assert(pid >= 0);
195✔
3254

3255
        if (pid != s->control_pid.pid)
195✔
3256
                return;
3257

3258
        pidref_done(&s->control_pid);
195✔
3259

3260
        if (is_clean_exit(code, status, EXIT_CLEAN_COMMAND, NULL))
195✔
3261
                f = SOCKET_SUCCESS;
3262
        else if (code == CLD_EXITED)
×
3263
                f = SOCKET_FAILURE_EXIT_CODE;
3264
        else if (code == CLD_KILLED)
×
3265
                f = SOCKET_FAILURE_SIGNAL;
UNCOV
3266
        else if (code == CLD_DUMPED)
×
3267
                f = SOCKET_FAILURE_CORE_DUMP;
3268
        else
UNCOV
3269
                assert_not_reached();
×
3270

3271
        if (s->control_command) {
195✔
3272
                exec_status_exit(&s->control_command->exec_status, &s->exec_context, pid, code, status);
195✔
3273

3274
                if (s->control_command->flags & EXEC_COMMAND_IGNORE_FAILURE)
195✔
3275
                        f = SOCKET_SUCCESS;
195✔
3276
        }
3277

3278
        unit_log_process_exit(
195✔
3279
                        u,
3280
                        "Control process",
3281
                        socket_exec_command_to_string(s->control_command_id),
3282
                        f == SOCKET_SUCCESS,
3283
                        code, status);
3284

3285
        if (s->result == SOCKET_SUCCESS)
195✔
3286
                s->result = f;
195✔
3287

3288
        if (s->control_command &&
195✔
3289
            s->control_command->command_next &&
195✔
3290
            f == SOCKET_SUCCESS) {
3291

UNCOV
3292
                log_unit_debug(u, "Running next command for state %s", socket_state_to_string(s->state));
×
UNCOV
3293
                socket_run_next(s);
×
3294
        } else {
3295
                s->control_command = NULL;
195✔
3296
                s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
195✔
3297

3298
                /* No further commands for this step, so let's figure
3299
                 * out what to do next */
3300

3301
                log_unit_debug(u, "Got final SIGCHLD for state %s", socket_state_to_string(s->state));
195✔
3302

3303
                switch (s->state) {
195✔
3304

3305
                case SOCKET_START_PRE:
×
UNCOV
3306
                        if (f == SOCKET_SUCCESS)
×
3307
                                socket_enter_start_open(s);
×
3308
                        else
UNCOV
3309
                                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, f);
×
3310
                        break;
3311

3312
                case SOCKET_START_CHOWN:
×
UNCOV
3313
                        if (f == SOCKET_SUCCESS)
×
3314
                                socket_enter_start_post(s);
×
3315
                        else
UNCOV
3316
                                socket_enter_stop_pre(s, f);
×
3317
                        break;
3318

3319
                case SOCKET_START_POST:
192✔
3320
                        if (f == SOCKET_SUCCESS)
192✔
3321
                                socket_enter_listening(s);
192✔
3322
                        else
UNCOV
3323
                                socket_enter_stop_pre(s, f);
×
3324
                        break;
3325

3326
                case SOCKET_STOP_PRE:
3✔
3327
                case SOCKET_STOP_PRE_SIGTERM:
3328
                case SOCKET_STOP_PRE_SIGKILL:
3329
                        socket_enter_stop_post(s, f);
3✔
3330
                        break;
3✔
3331

UNCOV
3332
                case SOCKET_STOP_POST:
×
3333
                case SOCKET_FINAL_SIGTERM:
3334
                case SOCKET_FINAL_SIGKILL:
UNCOV
3335
                        socket_enter_dead(s, f);
×
3336
                        break;
×
3337

3338
                case SOCKET_CLEANING:
×
3339

UNCOV
3340
                        if (s->clean_result == SOCKET_SUCCESS)
×
3341
                                s->clean_result = f;
×
3342

UNCOV
3343
                        socket_enter_dead(s, SOCKET_SUCCESS);
×
3344
                        break;
×
3345

UNCOV
3346
                default:
×
UNCOV
3347
                        assert_not_reached();
×
3348
                }
3349
        }
3350

3351
        /* Notify clients about changed exit status */
3352
        unit_add_to_dbus_queue(u);
195✔
3353
}
3354

UNCOV
3355
static int socket_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata) {
×
3356
        Socket *s = ASSERT_PTR(SOCKET(userdata));
×
3357

3358
        assert(s->timer_event_source == source);
×
3359

UNCOV
3360
        switch (s->state) {
×
3361

3362
        case SOCKET_START_PRE:
3363
                log_unit_warning(UNIT(s), "Starting timed out. Terminating.");
×
UNCOV
3364
                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
×
UNCOV
3365
                break;
×
3366

3367
        case SOCKET_START_CHOWN:
3368
        case SOCKET_START_POST:
3369
                log_unit_warning(UNIT(s), "Starting timed out. Stopping.");
×
UNCOV
3370
                socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
×
UNCOV
3371
                break;
×
3372

3373
        case SOCKET_DEFERRED:
3374
                log_unit_warning(UNIT(s), "DeferTriggerMaxSec= elapsed. Stopping.");
×
UNCOV
3375
                socket_enter_stop_pre(s, SOCKET_FAILURE_TIMEOUT);
×
UNCOV
3376
                break;
×
3377

3378
        case SOCKET_STOP_PRE:
3379
                log_unit_warning(UNIT(s), "Stopping timed out. Terminating.");
×
UNCOV
3380
                socket_enter_signal(s, SOCKET_STOP_PRE_SIGTERM, SOCKET_FAILURE_TIMEOUT);
×
3381
                break;
×
3382

3383
        case SOCKET_STOP_PRE_SIGTERM:
×
3384
                if (s->kill_context.send_sigkill) {
×
UNCOV
3385
                        log_unit_warning(UNIT(s), "Stopping timed out. Killing.");
×
3386
                        socket_enter_signal(s, SOCKET_STOP_PRE_SIGKILL, SOCKET_FAILURE_TIMEOUT);
×
3387
                } else {
UNCOV
3388
                        log_unit_warning(UNIT(s), "Stopping timed out. Skipping SIGKILL. Ignoring.");
×
UNCOV
3389
                        socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
×
3390
                }
3391
                break;
3392

3393
        case SOCKET_STOP_PRE_SIGKILL:
3394
                log_unit_warning(UNIT(s), "Processes still around after SIGKILL. Ignoring.");
×
UNCOV
3395
                socket_enter_stop_post(s, SOCKET_FAILURE_TIMEOUT);
×
UNCOV
3396
                break;
×
3397

3398
        case SOCKET_STOP_POST:
3399
                log_unit_warning(UNIT(s), "Stopping timed out (2). Terminating.");
×
UNCOV
3400
                socket_enter_signal(s, SOCKET_FINAL_SIGTERM, SOCKET_FAILURE_TIMEOUT);
×
3401
                break;
×
3402

3403
        case SOCKET_FINAL_SIGTERM:
×
3404
                if (s->kill_context.send_sigkill) {
×
UNCOV
3405
                        log_unit_warning(UNIT(s), "Stopping timed out (2). Killing.");
×
3406
                        socket_enter_signal(s, SOCKET_FINAL_SIGKILL, SOCKET_FAILURE_TIMEOUT);
×
3407
                } else {
UNCOV
3408
                        log_unit_warning(UNIT(s), "Stopping timed out (2). Skipping SIGKILL. Ignoring.");
×
UNCOV
3409
                        socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
×
3410
                }
3411
                break;
3412

3413
        case SOCKET_FINAL_SIGKILL:
3414
                log_unit_warning(UNIT(s), "Still around after SIGKILL (2). Entering failed mode.");
×
UNCOV
3415
                socket_enter_dead(s, SOCKET_FAILURE_TIMEOUT);
×
UNCOV
3416
                break;
×
3417

3418
        case SOCKET_CLEANING:
3419
                log_unit_warning(UNIT(s), "Cleaning timed out. killing.");
×
3420

UNCOV
3421
                if (s->clean_result == SOCKET_SUCCESS)
×
3422
                        s->clean_result = SOCKET_FAILURE_TIMEOUT;
×
3423

UNCOV
3424
                socket_enter_signal(s, SOCKET_FINAL_SIGKILL, 0);
×
3425
                break;
×
3426

UNCOV
3427
        default:
×
UNCOV
3428
                assert_not_reached();
×
3429
        }
3430

UNCOV
3431
        return 0;
×
3432
}
3433

3434
int socket_collect_fds(Socket *s, int **ret) {
637✔
3435
        size_t n = 0, k = 0;
637✔
3436

3437
        assert(s);
637✔
3438
        assert(ret);
637✔
3439

3440
        /* Called from the service code for requesting our fds */
3441

3442
        LIST_FOREACH(port, p, s->ports) {
1,313✔
3443
                if (p->fd >= 0)
676✔
3444
                        n++;
657✔
3445
                n += p->n_auxiliary_fds;
676✔
3446
        }
3447

3448
        if (n == 0) {
637✔
3449
                *ret = NULL;
19✔
3450
                return 0;
19✔
3451
        }
3452

3453
        int *fds = new(int, n);
618✔
3454
        if (!fds)
618✔
3455
                return -ENOMEM;
3456

3457
        LIST_FOREACH(port, p, s->ports) {
1,275✔
3458
                if (p->fd >= 0)
657✔
3459
                        fds[k++] = p->fd;
657✔
3460
                FOREACH_ARRAY(i, p->auxiliary_fds, p->n_auxiliary_fds)
657✔
UNCOV
3461
                        fds[k++] = *i;
×
3462
        }
3463

3464
        assert(k == n);
618✔
3465

3466
        *ret = fds;
618✔
3467
        return (int) n;
618✔
3468
}
3469

3470
static void socket_reset_failed(Unit *u) {
41✔
3471
        Socket *s = SOCKET(u);
41✔
3472

UNCOV
3473
        assert(s);
×
3474

3475
        if (s->state == SOCKET_FAILED)
41✔
UNCOV
3476
                socket_set_state(s, SOCKET_DEAD);
×
3477

3478
        s->result = SOCKET_SUCCESS;
41✔
3479
        s->clean_result = SOCKET_SUCCESS;
41✔
3480
}
41✔
3481

3482
void socket_connection_unref(Socket *s) {
92✔
3483
        assert(s);
92✔
3484

3485
        /* The service is dead. Yay!
3486
         *
3487
         * This is strictly for one-instance-per-connection
3488
         * services. */
3489

3490
        assert(s->n_connections > 0);
92✔
3491
        s->n_connections--;
92✔
3492

3493
        log_unit_debug(UNIT(s), "One connection closed, %u left.", s->n_connections);
92✔
3494
}
92✔
3495

3496
static void socket_trigger_notify(Unit *u, Unit *other) {
4,155✔
3497
        Socket *s = ASSERT_PTR(SOCKET(u));
4,155✔
3498

3499
        assert(other);
4,155✔
3500

3501
        /* Filter out invocations with bogus state */
3502
        assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
4,155✔
3503

3504
        Service *service = ASSERT_PTR(SERVICE(other));
4,155✔
3505

3506
        /* Don't propagate state changes from the service if we are already down */
3507
        if (!IN_SET(s->state, SOCKET_RUNNING, SOCKET_LISTENING, SOCKET_DEFERRED))
4,155✔
3508
                return;
3509

3510
        /* We don't care for the service state if we are in Accept=yes mode */
3511
        if (s->accept)
3,709✔
3512
                return;
3513

3514
        /* Propagate start limit hit state */
3515
        if (other->start_limit_hit) {
3,426✔
UNCOV
3516
                socket_enter_stop_pre(s, SOCKET_FAILURE_SERVICE_START_LIMIT_HIT);
×
UNCOV
3517
                return;
×
3518
        }
3519

3520
        /* Don't propagate anything if there's still a job queued */
3521
        if (other->job)
3,426✔
3522
                return;
3523

3524
        if (!SOCKET_SERVICE_IS_ACTIVE(service, /* allow_finalize = */ true))
2,585✔
3525
                socket_enter_listening(s);
807✔
3526

3527
        if (SERVICE(other)->state == SERVICE_RUNNING)
2,585✔
3528
                socket_set_state(s, SOCKET_RUNNING);
1,618✔
3529
}
3530

3531
static void socket_handoff_timestamp(
390✔
3532
                Unit *u,
3533
                const struct ucred *ucred,
3534
                const dual_timestamp *ts) {
3535

3536
        Socket *s = ASSERT_PTR(SOCKET(u));
390✔
3537

3538
        assert(ucred);
390✔
3539
        assert(ts);
390✔
3540

3541
        if (s->control_pid.pid == ucred->pid && s->control_command) {
390✔
3542
                exec_status_handoff(&s->control_command->exec_status, ucred, ts);
390✔
3543
                unit_add_to_dbus_queue(u);
390✔
3544
        }
3545
}
390✔
3546

3547
static int socket_get_timeout(Unit *u, usec_t *timeout) {
×
3548
        Socket *s = ASSERT_PTR(SOCKET(u));
×
UNCOV
3549
        usec_t t;
×
3550
        int r;
×
3551

UNCOV
3552
        if (!s->timer_event_source)
×
3553
                return 0;
×
3554

UNCOV
3555
        r = sd_event_source_get_time(s->timer_event_source, &t);
×
3556
        if (r < 0)
×
3557
                return r;
UNCOV
3558
        if (t == USEC_INFINITY)
×
3559
                return 0;
3560

UNCOV
3561
        *timeout = t;
×
UNCOV
3562
        return 1;
×
3563
}
3564

3565
const char* socket_fdname(Socket *s) {
833✔
3566
        assert(s);
833✔
3567

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

3571
        if (s->fdname)
833✔
3572
                return s->fdname;
3573

3574
        if (s->accept)
473✔
3575
                return "connection";
3576

3577
        return UNIT(s)->id;
459✔
3578
}
3579

3580
static PidRef* socket_control_pid(Unit *u) {
5,846✔
3581
        return &ASSERT_PTR(SOCKET(u))->control_pid;
11,692✔
3582
}
3583

3584
static int socket_clean(Unit *u, ExecCleanMask mask) {
×
3585
        Socket *s = ASSERT_PTR(SOCKET(u));
×
UNCOV
3586
        _cleanup_strv_free_ char **l = NULL;
×
3587
        int r;
×
3588

3589
        assert(mask != 0);
×
3590

UNCOV
3591
        if (s->state != SOCKET_DEAD)
×
3592
                return -EBUSY;
3593

UNCOV
3594
        r = exec_context_get_clean_directories(&s->exec_context, u->manager->prefix, mask, &l);
×
UNCOV
3595
        if (r < 0)
×
3596
                return r;
3597

UNCOV
3598
        if (strv_isempty(l))
×
3599
                return -EUNATCH;
3600

3601
        socket_unwatch_control_pid(s);
×
3602
        s->clean_result = SOCKET_SUCCESS;
×
UNCOV
3603
        s->control_command = NULL;
×
3604
        s->control_command_id = _SOCKET_EXEC_COMMAND_INVALID;
×
3605

3606
        r = socket_arm_timer(s, /* relative= */ true, s->exec_context.timeout_clean_usec);
×
3607
        if (r < 0) {
×
UNCOV
3608
                log_unit_warning_errno(u, r, "Failed to install timer: %m");
×
UNCOV
3609
                goto fail;
×
3610
        }
3611

3612
        r = unit_fork_and_watch_rm_rf(u, l, &s->control_pid);
×
3613
        if (r < 0) {
×
UNCOV
3614
                log_unit_warning_errno(u, r, "Failed to spawn cleaning task: %m");
×
UNCOV
3615
                goto fail;
×
3616
        }
3617

UNCOV
3618
        socket_set_state(s, SOCKET_CLEANING);
×
3619
        return 0;
3620

3621
fail:
×
3622
        s->clean_result = SOCKET_FAILURE_RESOURCES;
×
UNCOV
3623
        s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
×
UNCOV
3624
        return r;
×
3625
}
3626

3627
static int socket_can_clean(Unit *u, ExecCleanMask *ret) {
94✔
3628
        Socket *s = ASSERT_PTR(SOCKET(u));
94✔
3629

3630
        return exec_context_get_clean_mask(&s->exec_context, ret);
94✔
3631
}
3632

3633
static int socket_test_startable(Unit *u) {
3,222✔
3634
        Socket *s = ASSERT_PTR(SOCKET(u));
3,222✔
3635
        int r;
3,222✔
3636

3637
        /* It is already being started. */
3638
        if (IN_SET(s->state,
3,222✔
3639
                   SOCKET_START_PRE,
3640
                   SOCKET_START_OPEN,
3641
                   SOCKET_START_CHOWN,
3642
                   SOCKET_START_POST))
3643
                return false;
3644

3645
        r = unit_test_start_limit(u);
3,222✔
3646
        if (r < 0) {
3,222✔
UNCOV
3647
                socket_enter_dead(s, SOCKET_FAILURE_START_LIMIT_HIT);
×
UNCOV
3648
                return r;
×
3649
        }
3650

3651
        return true;
3652
}
3653

3654
static const char* const socket_exec_command_table[_SOCKET_EXEC_COMMAND_MAX] = {
3655
        [SOCKET_EXEC_START_PRE]   = "ExecStartPre",
3656
        [SOCKET_EXEC_START_CHOWN] = "ExecStartChown",
3657
        [SOCKET_EXEC_START_POST]  = "ExecStartPost",
3658
        [SOCKET_EXEC_STOP_PRE]    = "ExecStopPre",
3659
        [SOCKET_EXEC_STOP_POST]   = "ExecStopPost",
3660
};
3661

3662
DEFINE_STRING_TABLE_LOOKUP(socket_exec_command, SocketExecCommand);
255✔
3663

3664
static const char* const socket_result_table[_SOCKET_RESULT_MAX] = {
3665
        [SOCKET_SUCCESS]                         = "success",
3666
        [SOCKET_FAILURE_RESOURCES]               = "resources",
3667
        [SOCKET_FAILURE_TIMEOUT]                 = "timeout",
3668
        [SOCKET_FAILURE_EXIT_CODE]               = "exit-code",
3669
        [SOCKET_FAILURE_SIGNAL]                  = "signal",
3670
        [SOCKET_FAILURE_CORE_DUMP]               = "core-dump",
3671
        [SOCKET_FAILURE_START_LIMIT_HIT]         = "start-limit-hit",
3672
        [SOCKET_FAILURE_TRIGGER_LIMIT_HIT]       = "trigger-limit-hit",
3673
        [SOCKET_FAILURE_SERVICE_START_LIMIT_HIT] = "service-start-limit-hit",
3674
};
3675

3676
DEFINE_STRING_TABLE_LOOKUP(socket_result, SocketResult);
8,747✔
3677

3678
static const char* const socket_timestamping_table[_SOCKET_TIMESTAMPING_MAX] = {
3679
        [SOCKET_TIMESTAMPING_OFF] = "off",
3680
        [SOCKET_TIMESTAMPING_US]  = "us",
3681
        [SOCKET_TIMESTAMPING_NS]  = "ns",
3682
};
3683

3684
DEFINE_STRING_TABLE_LOOKUP(socket_timestamping, SocketTimestamping);
305✔
3685

3686
SocketTimestamping socket_timestamping_from_string_harder(const char *p) {
221✔
3687
        SocketTimestamping t;
221✔
3688
        int r;
221✔
3689

3690
        if (!p)
221✔
3691
                return _SOCKET_TIMESTAMPING_INVALID;
3692

3693
        t = socket_timestamping_from_string(p);
221✔
3694
        if (t >= 0)
221✔
3695
                return t;
3696

3697
        /* Let's alternatively support the various other aliases parse_time() accepts for ns and µs here,
3698
         * too. */
3699
        if (streq(p, "nsec"))
×
3700
                return SOCKET_TIMESTAMPING_NS;
UNCOV
3701
        if (STR_IN_SET(p, "usec", "µs", "μs")) /* Accept both small greek letter mu + micro sign unicode codepoints */
×
3702
                return SOCKET_TIMESTAMPING_US;
×
3703

UNCOV
3704
        r = parse_boolean(p);
×
UNCOV
3705
        if (r < 0)
×
3706
                return _SOCKET_TIMESTAMPING_INVALID;
3707

UNCOV
3708
        return r ? SOCKET_TIMESTAMPING_NS : SOCKET_TIMESTAMPING_OFF; /* If boolean yes, default to ns accuracy */
×
3709
}
3710

3711
static const char* const socket_defer_trigger_table[_SOCKET_DEFER_MAX] = {
3712
        [SOCKET_DEFER_NO]      = "no",
3713
        [SOCKET_DEFER_YES]     = "yes",
3714
        [SOCKET_DEFER_PATIENT] = "patient",
3715
};
3716

3717
DEFINE_STRING_TABLE_LOOKUP_WITH_BOOLEAN(socket_defer_trigger, SocketDeferTrigger, SOCKET_DEFER_YES);
770✔
3718

3719
const UnitVTable socket_vtable = {
3720
        .object_size = sizeof(Socket),
3721
        .exec_context_offset = offsetof(Socket, exec_context),
3722
        .cgroup_context_offset = offsetof(Socket, cgroup_context),
3723
        .kill_context_offset = offsetof(Socket, kill_context),
3724
        .exec_runtime_offset = offsetof(Socket, exec_runtime),
3725
        .cgroup_runtime_offset = offsetof(Socket, cgroup_runtime),
3726

3727
        .sections =
3728
                "Unit\0"
3729
                "Socket\0"
3730
                "Install\0",
3731
        .private_section = "Socket",
3732

3733
        .can_transient = true,
3734
        .can_trigger = true,
3735
        .can_fail = true,
3736

3737
        .init = socket_init,
3738
        .done = socket_done,
3739
        .load = socket_load,
3740

3741
        .coldplug = socket_coldplug,
3742

3743
        .dump = socket_dump,
3744

3745
        .start = socket_start,
3746
        .stop = socket_stop,
3747

3748
        .clean = socket_clean,
3749
        .can_clean = socket_can_clean,
3750

3751
        .get_timeout = socket_get_timeout,
3752

3753
        .serialize = socket_serialize,
3754
        .deserialize_item = socket_deserialize_item,
3755
        .distribute_fds = socket_distribute_fds,
3756

3757
        .active_state = socket_active_state,
3758
        .sub_state_to_string = socket_sub_state_to_string,
3759

3760
        .will_restart = unit_will_restart_default,
3761

3762
        .may_gc = socket_may_gc,
3763

3764
        .sigchld_event = socket_sigchld_event,
3765

3766
        .trigger_notify = socket_trigger_notify,
3767

3768
        .stop_notify = socket_stop_notify,
3769

3770
        .reset_failed = socket_reset_failed,
3771

3772
        .notify_handoff_timestamp = socket_handoff_timestamp,
3773

3774
        .control_pid = socket_control_pid,
3775

3776
        .bus_set_property = bus_socket_set_property,
3777
        .bus_commit_properties = bus_socket_commit_properties,
3778

3779
        .status_message_formats = {
3780
                .finished_start_job = {
3781
                        [JOB_DONE]       = "Listening on %s.",
3782
                        [JOB_FAILED]     = "Failed to listen on %s.",
3783
                        [JOB_TIMEOUT]    = "Timed out starting %s.",
3784
                },
3785
                .finished_stop_job = {
3786
                        [JOB_DONE]       = "Closed %s.",
3787
                        [JOB_FAILED]     = "Failed stopping %s.",
3788
                        [JOB_TIMEOUT]    = "Timed out stopping %s.",
3789
                },
3790
        },
3791

3792
        .test_startable = socket_test_startable,
3793
};
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