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

systemd / systemd / 14872145375

06 May 2025 09:07PM UTC coverage: 72.232% (+0.02%) from 72.214%
14872145375

push

github

DaanDeMeyer
string-table: annotate _to_string and _from_string with _const_ and _pure_, respectively

Follow-up for c94f6ab1b

297286 of 411572 relevant lines covered (72.23%)

695615.99 hits per line

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

87.5
/src/userdb/userwork.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <poll.h>
4
#include <sys/wait.h>
5

6
#include "sd-daemon.h"
7
#include "sd-varlink.h"
8

9
#include "argv-util.h"
10
#include "env-util.h"
11
#include "errno-util.h"
12
#include "fd-util.h"
13
#include "group-record.h"
14
#include "io-util.h"
15
#include "json-util.h"
16
#include "main-func.h"
17
#include "process-util.h"
18
#include "strv.h"
19
#include "time-util.h"
20
#include "user-record.h"
21
#include "user-record-nss.h"
22
#include "user-util.h"
23
#include "userdb.h"
24
#include "varlink-io.systemd.UserDatabase.h"
25
#include "varlink-util.h"
26

27
#define ITERATIONS_MAX 64U
28
#define RUNTIME_MAX_USEC (5 * USEC_PER_MINUTE)
29
#define PRESSURE_SLEEP_TIME_USEC (50 * USEC_PER_MSEC)
30
#define CONNECTION_IDLE_USEC (15 * USEC_PER_SEC)
31
#define LISTEN_IDLE_USEC (90 * USEC_PER_SEC)
32

33
typedef struct LookupParameters {
34
        const char *name;
35
        union {
36
                uid_t uid;
37
                gid_t gid;
38
        };
39
        const char *service;
40
        UserDBMatch match;
41
} LookupParameters;
42

43
static void lookup_parameters_done(LookupParameters *p) {
15,760✔
44
        assert(p);
15,760✔
45

46
        userdb_match_done(&p->match);
15,760✔
47
}
15,760✔
48

49
static int add_nss_service(sd_json_variant **v) {
2,707✔
50
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *status = NULL, *z = NULL;
5,414✔
51
        sd_id128_t mid;
2,707✔
52
        int r;
2,707✔
53

54
        assert(v);
2,707✔
55

56
        /* Patch in service field if it's missing. The assumption here is that this field is unset only for
57
         * NSS records */
58

59
        if (sd_json_variant_by_key(*v, "service"))
2,707✔
60
                return 0;
61

62
        r = sd_id128_get_machine(&mid);
2,707✔
63
        if (r < 0)
2,707✔
64
                return r;
65

66
        status = sd_json_variant_ref(sd_json_variant_by_key(*v, "status"));
2,707✔
67
        z = sd_json_variant_ref(sd_json_variant_by_key(status, SD_ID128_TO_STRING(mid)));
2,707✔
68

69
        if (sd_json_variant_by_key(z, "service"))
2,707✔
70
                return 0;
71

72
        r = sd_json_variant_set_field_string(&z, "service", "io.systemd.NameServiceSwitch");
2,558✔
73
        if (r < 0)
2,558✔
74
                return r;
75

76
        r = sd_json_variant_set_field(&status, SD_ID128_TO_STRING(mid), z);
2,558✔
77
        if (r < 0)
2,558✔
78
                return r;
79

80
        return sd_json_variant_set_field(v, "status", status);
2,558✔
81
}
82

83
static int build_user_json(sd_varlink *link, UserRecord *ur, sd_json_variant **ret) {
2,263✔
84
        _cleanup_(user_record_unrefp) UserRecord *stripped = NULL;
×
85
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
2,263✔
86
        UserRecordLoadFlags flags;
2,263✔
87
        uid_t peer_uid;
2,263✔
88
        bool trusted;
2,263✔
89
        int r;
2,263✔
90

91
        assert(ur);
2,263✔
92
        assert(ret);
2,263✔
93

94
        r = sd_varlink_get_peer_uid(link, &peer_uid);
2,263✔
95
        if (r < 0) {
2,263✔
96
                log_debug_errno(r, "Unable to query peer UID, ignoring: %m");
×
97
                trusted = false;
98
        } else
99
                trusted = peer_uid == 0 || peer_uid == ur->uid;
2,263✔
100

101
        flags = USER_RECORD_REQUIRE_REGULAR|USER_RECORD_ALLOW_PER_MACHINE|USER_RECORD_ALLOW_BINDING|USER_RECORD_STRIP_SECRET|USER_RECORD_ALLOW_STATUS|USER_RECORD_ALLOW_SIGNATURE|USER_RECORD_PERMISSIVE;
102
        if (trusted)
103
                flags |= USER_RECORD_ALLOW_PRIVILEGED;
104
        else
105
                flags |= USER_RECORD_STRIP_PRIVILEGED;
106

107
        r = user_record_clone(ur, flags, &stripped);
2,263✔
108
        if (r < 0)
2,263✔
109
                return r;
110

111
        stripped->incomplete =
4,526✔
112
                ur->incomplete ||
2,263✔
113
                (FLAGS_SET(ur->mask, USER_RECORD_PRIVILEGED) &&
2,263✔
114
                 !FLAGS_SET(stripped->mask, USER_RECORD_PRIVILEGED));
1,692✔
115

116
        v = sd_json_variant_ref(stripped->json);
2,263✔
117
        r = add_nss_service(&v);
2,263✔
118
        if (r < 0)
2,263✔
119
                return r;
120

121
        return sd_json_buildo(
2,263✔
122
                        ret,
123
                        SD_JSON_BUILD_PAIR("record", SD_JSON_BUILD_VARIANT(v)),
124
                        SD_JSON_BUILD_PAIR("incomplete", SD_JSON_BUILD_BOOLEAN(stripped->incomplete)));
125
}
126

127
static int userdb_flags_from_service(sd_varlink *link, const char *service, UserDBFlags *ret) {
29,536✔
128
        assert(link);
29,536✔
129
        assert(ret);
29,536✔
130

131
        if (streq_ptr(service, "io.systemd.NameServiceSwitch"))
29,536✔
132
                *ret = USERDB_NSS_ONLY|USERDB_AVOID_MULTIPLEXER;
22✔
133
        else if (streq_ptr(service, "io.systemd.DropIn"))
29,514✔
134
                *ret = USERDB_DROPIN_ONLY|USERDB_AVOID_MULTIPLEXER;
28,208✔
135
        else if (streq_ptr(service, "io.systemd.Multiplexer"))
1,306✔
136
                *ret = USERDB_AVOID_MULTIPLEXER;
1,306✔
137
        else
138
                return sd_varlink_error(link, "io.systemd.UserDatabase.BadService", NULL);
×
139

140
        return 0;
141
}
142

143
static int vl_method_get_user_record(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
2,684✔
144

145
        static const sd_json_dispatch_field dispatch_table[] = {
2,684✔
146
                { "uid",             _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, uid),                    0             },
147
                { "userName",        SD_JSON_VARIANT_STRING,        json_dispatch_const_user_group_name, offsetof(LookupParameters, name),                   SD_JSON_RELAX },
148
                { "service",         SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string,       offsetof(LookupParameters, service),                0             },
149
                { "fuzzyNames",      SD_JSON_VARIANT_ARRAY,         sd_json_dispatch_strv,               offsetof(LookupParameters, match.fuzzy_names),      0             },
150
                { "dispositionMask", SD_JSON_VARIANT_ARRAY,         json_dispatch_dispositions_mask,     offsetof(LookupParameters, match.disposition_mask), 0             },
151
                { "uidMin",          _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, match.uid_min),          0             },
152
                { "uidMax",          _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, match.uid_max),          0             },
153
                {}
154
        };
155

156
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
2,684✔
157
        _cleanup_(user_record_unrefp) UserRecord *hr = NULL;
2,684✔
158
        _cleanup_(lookup_parameters_done) LookupParameters p = {
2,684✔
159
                .uid = UID_INVALID,
160
                .match = USERDB_MATCH_NULL,
161
        };
162
        UserDBFlags userdb_flags;
2,684✔
163
        int r;
2,684✔
164

165
        assert(parameters);
2,684✔
166

167
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
2,684✔
168
        if (r != 0)
2,684✔
169
                return r;
170

171
        r = userdb_flags_from_service(link, p.service, &userdb_flags);
2,683✔
172
        if (r != 0) /* return value of < 0 means error (as usual); > 0 means 'already processed and replied,
2,683✔
173
                     * we are done'; == 0 means 'not processed, caller should process now' */
174
                return r;
175

176
        if (uid_is_valid(p.uid))
2,683✔
177
                r = userdb_by_uid(p.uid, &p.match, userdb_flags, &hr);
845✔
178
        else if (p.name)
1,838✔
179
                r = userdb_by_name(p.name, &p.match, userdb_flags, &hr);
1,821✔
180
        else {
181
                _cleanup_(userdb_iterator_freep) UserDBIterator *iterator = NULL;
×
182
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *last = NULL;
17✔
183

184
                r = userdb_all(&p.match, userdb_flags, &iterator);
17✔
185
                if (IN_SET(r, -ESRCH, -ENOLINK))
17✔
186
                        /* We turn off Varlink lookups in various cases (e.g. in case we only enable DropIn
187
                         * backend) — this might make userdb_all return ENOLINK (which indicates that varlink
188
                         * was off and no other suitable source or entries were found). Let's hide this
189
                         * implementation detail and always return NoRecordFound in this case, since from a
190
                         * client's perspective it's irrelevant if there was no entry at all or just not on
191
                         * the service that the query was limited to. */
192
                        return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
×
193
                if (r < 0)
17✔
194
                        return r;
195

196
                for (;;) {
312✔
197
                        _cleanup_(user_record_unrefp) UserRecord *z = NULL;
329✔
198

199
                        r = userdb_iterator_get(iterator, &p.match, &z);
329✔
200
                        if (r == -ESRCH)
329✔
201
                                break;
202
                        if (r < 0)
312✔
203
                                return r;
204

205
                        if (last) {
312✔
206
                                r = sd_varlink_notify(link, last);
297✔
207
                                if (r < 0)
297✔
208
                                        return r;
209

210
                                last = sd_json_variant_unref(last);
297✔
211
                        }
212

213
                        r = build_user_json(link, z, &last);
312✔
214
                        if (r < 0)
312✔
215
                                return r;
216
                }
217

218
                if (!last)
17✔
219
                        return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
2✔
220

221
                return sd_varlink_reply(link, last);
15✔
222
        }
223
        if (r == -ESRCH)
2,666✔
224
                return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
715✔
225
        if (r == -ENOEXEC)
1,951✔
226
                return sd_varlink_error(link, "io.systemd.UserDatabase.NonMatchingRecordFound", NULL);
×
227
        if (r < 0) {
1,951✔
228
                log_debug_errno(r, "User lookup failed abnormally: %m");
×
229
                return sd_varlink_error(link, "io.systemd.UserDatabase.ServiceNotAvailable", NULL);
×
230
        }
231

232
        if ((uid_is_valid(p.uid) && hr->uid != p.uid) ||
1,951✔
233
            (p.name && !user_record_matches_user_name(hr, p.name)))
1,951✔
234
                return sd_varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
×
235

236
        r = build_user_json(link, hr, &v);
1,951✔
237
        if (r < 0)
1,951✔
238
                return r;
239

240
        return sd_varlink_reply(link, v);
1,951✔
241
}
242

243
static int build_group_json(sd_varlink *link, GroupRecord *gr, sd_json_variant **ret) {
444✔
244
        _cleanup_(group_record_unrefp) GroupRecord *stripped = NULL;
×
245
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
444✔
246
        UserRecordLoadFlags flags;
444✔
247
        uid_t peer_uid;
444✔
248
        bool trusted;
444✔
249
        int r;
444✔
250

251
        assert(gr);
444✔
252
        assert(ret);
444✔
253

254
        r = sd_varlink_get_peer_uid(link, &peer_uid);
444✔
255
        if (r < 0) {
444✔
256
                log_debug_errno(r, "Unable to query peer UID, ignoring: %m");
×
257
                trusted = false;
258
        } else
259
                trusted = peer_uid == 0;
444✔
260

261
        flags = USER_RECORD_REQUIRE_REGULAR|USER_RECORD_ALLOW_PER_MACHINE|USER_RECORD_ALLOW_BINDING|USER_RECORD_STRIP_SECRET|USER_RECORD_ALLOW_STATUS|USER_RECORD_ALLOW_SIGNATURE|USER_RECORD_PERMISSIVE;
444✔
262
        if (trusted)
444✔
263
                flags |= USER_RECORD_ALLOW_PRIVILEGED;
264
        else
265
                flags |= USER_RECORD_STRIP_PRIVILEGED;
266

267
        r = group_record_clone(gr, flags, &stripped);
444✔
268
        if (r < 0)
444✔
269
                return r;
270

271
        stripped->incomplete =
888✔
272
                gr->incomplete ||
444✔
273
                (FLAGS_SET(gr->mask, USER_RECORD_PRIVILEGED) &&
444✔
274
                 !FLAGS_SET(stripped->mask, USER_RECORD_PRIVILEGED));
26✔
275

276
        v = sd_json_variant_ref(gr->json);
444✔
277
        r = add_nss_service(&v);
444✔
278
        if (r < 0)
444✔
279
                return r;
280

281
        return sd_json_buildo(
444✔
282
                        ret,
283
                        SD_JSON_BUILD_PAIR("record", SD_JSON_BUILD_VARIANT(v)),
284
                        SD_JSON_BUILD_PAIR("incomplete", SD_JSON_BUILD_BOOLEAN(stripped->incomplete)));
285
}
286

287
static int vl_method_get_group_record(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
13,076✔
288

289
        static const sd_json_dispatch_field dispatch_table[] = {
13,076✔
290
                { "gid",             _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, gid),                    0             },
291
                { "groupName",       SD_JSON_VARIANT_STRING,        json_dispatch_const_user_group_name, offsetof(LookupParameters, name),                   SD_JSON_RELAX },
292
                { "service",         SD_JSON_VARIANT_STRING,        sd_json_dispatch_const_string,       offsetof(LookupParameters, service),                0             },
293
                { "fuzzyNames",      SD_JSON_VARIANT_ARRAY,         sd_json_dispatch_strv,               offsetof(LookupParameters, match.fuzzy_names),      0             },
294
                { "dispositionMask", SD_JSON_VARIANT_ARRAY,         json_dispatch_dispositions_mask,     offsetof(LookupParameters, match.disposition_mask), 0             },
295
                { "gidMin",          _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, match.gid_min),          0             },
296
                { "gidMax",          _SD_JSON_VARIANT_TYPE_INVALID, sd_json_dispatch_uid_gid,            offsetof(LookupParameters, match.gid_max),          0             },
297
                {}
298
        };
299

300
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
13,076✔
301
        _cleanup_(group_record_unrefp) GroupRecord *g = NULL;
13,076✔
302
        _cleanup_(lookup_parameters_done) LookupParameters p = {
13,076✔
303
                .gid = GID_INVALID,
304
                .match = USERDB_MATCH_NULL,
305
        };
306
        UserDBFlags userdb_flags;
13,076✔
307
        int r;
13,076✔
308

309
        assert(parameters);
13,076✔
310

311
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
13,076✔
312
        if (r != 0)
13,076✔
313
                return r;
314

315
        r = userdb_flags_from_service(link, p.service, &userdb_flags);
13,076✔
316
        if (r != 0)
13,076✔
317
                return r;
318

319
        if (gid_is_valid(p.gid))
13,076✔
320
                r = groupdb_by_gid(p.gid, &p.match, userdb_flags, &g);
1,357✔
321
        else if (p.name)
11,719✔
322
                r = groupdb_by_name(p.name, &p.match, userdb_flags, &g);
11,710✔
323
        else {
324
                _cleanup_(userdb_iterator_freep) UserDBIterator *iterator = NULL;
×
325
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *last = NULL;
9✔
326

327
                r = groupdb_all(&p.match, userdb_flags, &iterator);
9✔
328
                if (IN_SET(r, -ESRCH, -ENOLINK))
9✔
329
                        return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
×
330
                if (r < 0)
9✔
331
                        return r;
332

333
                for (;;) {
232✔
334
                        _cleanup_(group_record_unrefp) GroupRecord *z = NULL;
241✔
335

336
                        r = groupdb_iterator_get(iterator, &p.match, &z);
241✔
337
                        if (r == -ESRCH)
241✔
338
                                break;
339
                        if (r < 0)
232✔
340
                                return r;
341

342
                        if (last) {
232✔
343
                                r = sd_varlink_notify(link, last);
225✔
344
                                if (r < 0)
225✔
345
                                        return r;
346

347
                                last = sd_json_variant_unref(last);
225✔
348
                        }
349

350
                        r = build_group_json(link, z, &last);
232✔
351
                        if (r < 0)
232✔
352
                                return r;
353
                }
354

355
                if (!last)
9✔
356
                        return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
2✔
357

358
                return sd_varlink_reply(link, last);
7✔
359
        }
360
        if (r == -ESRCH)
13,067✔
361
                return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
12,855✔
362
        if (r == -ENOEXEC)
212✔
363
                return sd_varlink_error(link, "io.systemd.UserDatabase.NonMatchingRecordFound", NULL);
×
364
        if (r < 0) {
212✔
365
                log_debug_errno(r, "Group lookup failed abnormally: %m");
×
366
                return sd_varlink_error(link, "io.systemd.UserDatabase.ServiceNotAvailable", NULL);
×
367
        }
368

369
        if ((uid_is_valid(p.gid) && g->gid != p.gid) ||
212✔
370
            (p.name && !group_record_matches_group_name(g, p.name)))
212✔
371
                return sd_varlink_error(link, "io.systemd.UserDatabase.ConflictingRecordFound", NULL);
×
372

373
        r = build_group_json(link, g, &v);
212✔
374
        if (r < 0)
212✔
375
                return r;
376

377
        return sd_varlink_reply(link, v);
212✔
378
}
379

380
typedef struct MembershipLookupParameters {
381
        const char *user_name;
382
        const char *group_name;
383
        const char *service;
384
} MembershipLookupParameters;
385

386
static int vl_method_get_memberships(sd_varlink *link, sd_json_variant *parameters, sd_varlink_method_flags_t flags, void *userdata) {
13,777✔
387
        static const sd_json_dispatch_field dispatch_table[] = {
13,777✔
388
                { "userName",  SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(MembershipLookupParameters, user_name),  SD_JSON_RELAX },
389
                { "groupName", SD_JSON_VARIANT_STRING, json_dispatch_const_user_group_name, offsetof(MembershipLookupParameters, group_name), SD_JSON_RELAX },
390
                { "service",   SD_JSON_VARIANT_STRING, sd_json_dispatch_const_string,       offsetof(MembershipLookupParameters, service),    0             },
391
                {}
392
        };
393

394
        _cleanup_free_ char *last_user_name = NULL, *last_group_name = NULL;
13,777✔
395
        _cleanup_(userdb_iterator_freep) UserDBIterator *iterator = NULL;
13,777✔
396
        MembershipLookupParameters p = {};
13,777✔
397
        UserDBFlags userdb_flags;
13,777✔
398
        int r;
13,777✔
399

400
        assert(parameters);
13,777✔
401

402
        r = sd_varlink_dispatch(link, parameters, dispatch_table, &p);
13,777✔
403
        if (r != 0)
13,777✔
404
                return r;
405

406
        r = userdb_flags_from_service(link, p.service, &userdb_flags);
13,777✔
407
        if (r != 0)
13,777✔
408
                return r;
409

410
        if (p.group_name)
13,777✔
411
                r = membershipdb_by_group(p.group_name, userdb_flags, &iterator);
12,468✔
412
        else if (p.user_name)
1,309✔
413
                r = membershipdb_by_user(p.user_name, userdb_flags, &iterator);
1,306✔
414
        else
415
                r = membershipdb_all(userdb_flags, &iterator);
3✔
416
        if (IN_SET(r, -ESRCH, -ENOLINK))
13,777✔
417
                return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
13,625✔
418
        if (r < 0)
152✔
419
                return r;
420

421
        for (;;) {
190✔
422
                _cleanup_free_ char *user_name = NULL, *group_name = NULL;
×
423

424
                r = membershipdb_iterator_get(iterator, &user_name, &group_name);
190✔
425
                if (r == -ESRCH)
190✔
426
                        break;
427
                if (r < 0)
38✔
428
                        return r;
429

430
                /* If both group + user are specified do a-posteriori filtering */
431
                if (p.group_name && p.user_name && !streq(group_name, p.group_name))
38✔
432
                        continue;
×
433

434
                if (last_user_name) {
38✔
435
                        assert(last_group_name);
14✔
436

437
                        r = sd_varlink_notifybo(
14✔
438
                                        link,
439
                                        SD_JSON_BUILD_PAIR("userName", SD_JSON_BUILD_STRING(last_user_name)),
440
                                        SD_JSON_BUILD_PAIR("groupName", SD_JSON_BUILD_STRING(last_group_name)));
441
                        if (r < 0)
14✔
442
                                return r;
443
                }
444

445
                free_and_replace(last_user_name, user_name);
38✔
446
                free_and_replace(last_group_name, group_name);
38✔
447
        }
448

449
        if (!last_user_name) {
152✔
450
                assert(!last_group_name);
128✔
451
                return sd_varlink_error(link, "io.systemd.UserDatabase.NoRecordFound", NULL);
128✔
452
        }
453

454
        assert(last_group_name);
24✔
455

456
        return sd_varlink_replybo(
24✔
457
                        link,
458
                        SD_JSON_BUILD_PAIR("userName", SD_JSON_BUILD_STRING(last_user_name)),
459
                        SD_JSON_BUILD_PAIR("groupName", SD_JSON_BUILD_STRING(last_group_name)));
460
}
461

462
static int process_connection(sd_varlink_server *server, int _fd) {
29,640✔
463
        _cleanup_close_ int fd = TAKE_FD(_fd); /* always take possession */
29,640✔
464
        _cleanup_(sd_varlink_close_unrefp) sd_varlink *vl = NULL;
29,640✔
465
        int r;
29,640✔
466

467
        assert(server);
29,640✔
468
        assert(fd >= 0);
29,640✔
469

470
        r = sd_varlink_server_add_connection(server, fd, &vl);
29,640✔
471
        if (r < 0)
29,640✔
472
                return log_error_errno(r, "Failed to add connection: %m");
×
473

474
        TAKE_FD(fd);
29,640✔
475
        vl = sd_varlink_ref(vl);
29,640✔
476

477
        for (;;) {
276,026✔
478
                r = sd_varlink_process(vl);
276,026✔
479
                if (r == -ENOTCONN) {
276,026✔
480
                        log_debug("Connection terminated.");
29,640✔
481
                        break;
482
                }
483
                if (r < 0)
246,386✔
484
                        return log_error_errno(r, "Failed to process connection: %m");
×
485
                if (r > 0)
246,386✔
486
                        continue;
207,068✔
487

488
                r = sd_varlink_wait(vl, CONNECTION_IDLE_USEC);
39,318✔
489
                if (r < 0)
39,318✔
490
                        return log_error_errno(r, "Failed to wait for connection events: %m");
×
491
                if (r == 0)
39,318✔
492
                        break;
493
        }
494

495
        return 0;
496
}
497

498
static int run(int argc, char *argv[]) {
477✔
499
        usec_t start_time, listen_idle_usec, last_busy_usec = USEC_INFINITY;
477✔
500
        _cleanup_(sd_varlink_server_unrefp) sd_varlink_server *server = NULL;
477✔
501
        _cleanup_(pidref_done) PidRef parent = PIDREF_NULL;
×
502
        unsigned n_iterations = 0;
477✔
503
        int m, listen_fd, r;
477✔
504

505
        log_setup();
477✔
506

507
        m = sd_listen_fds(false);
477✔
508
        if (m < 0)
477✔
509
                return log_error_errno(m, "Failed to determine number of listening fds: %m");
×
510
        if (m == 0)
477✔
511
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No socket to listen on received.");
×
512
        if (m > 1)
477✔
513
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Worker can only listen on a single socket at a time.");
×
514

515
        listen_fd = SD_LISTEN_FDS_START;
477✔
516

517
        r = fd_nonblock(listen_fd, false);
477✔
518
        if (r < 0)
477✔
519
                return log_error_errno(r, "Failed to turn off non-blocking mode for listening socket: %m");
×
520

521
        r = varlink_server_new(&server, 0, NULL);
477✔
522
        if (r < 0)
477✔
523
                return log_error_errno(r, "Failed to allocate varlink server: %m");
×
524

525
        r = sd_varlink_server_add_interface(server, &vl_interface_io_systemd_UserDatabase);
477✔
526
        if (r < 0)
477✔
527
                return log_error_errno(r, "Failed to add UserDatabase interface to varlink server: %m");
×
528

529
        r = sd_varlink_server_bind_method_many(
477✔
530
                        server,
531
                        "io.systemd.UserDatabase.GetUserRecord",  vl_method_get_user_record,
532
                        "io.systemd.UserDatabase.GetGroupRecord", vl_method_get_group_record,
533
                        "io.systemd.UserDatabase.GetMemberships", vl_method_get_memberships);
534
        if (r < 0)
477✔
535
                return log_error_errno(r, "Failed to bind methods: %m");
×
536

537
        r = getenv_bool("USERDB_FIXED_WORKER");
477✔
538
        if (r < 0)
477✔
539
                return log_error_errno(r, "Failed to parse USERDB_FIXED_WORKER: %m");
×
540
        listen_idle_usec = r ? USEC_INFINITY : LISTEN_IDLE_USEC;
477✔
541

542
        r = userdb_block_nss_systemd(true);
477✔
543
        if (r < 0)
477✔
544
                return log_error_errno(r, "Failed to disable userdb NSS compatibility: %m");
×
545

546
        r = pidref_set_parent(&parent);
477✔
547
        if (r < 0)
477✔
548
                return log_error_errno(r, "Failed to acquire pidfd of parent process: %m");
×
549
        if (parent.pid == 1) /* We got reparented away from userdbd? */
477✔
550
                return log_error_errno(SYNTHETIC_ERRNO(ESRCH), "Parent already died, exiting.");
×
551

552
        start_time = now(CLOCK_MONOTONIC);
477✔
553

554
        for (;;) {
30,394✔
555
                _cleanup_close_ int fd = -EBADF;
477✔
556
                usec_t n;
30,394✔
557

558
                /* Exit the worker in regular intervals, to flush out all memory use */
559
                if (n_iterations++ > ITERATIONS_MAX) {
30,394✔
560
                        log_debug("Exiting worker, processed %u iterations, that's enough.", n_iterations);
445✔
561
                        break;
562
                }
563

564
                n = now(CLOCK_MONOTONIC);
29,949✔
565
                if (n >= usec_add(start_time, RUNTIME_MAX_USEC)) {
59,898✔
566
                        log_debug("Exiting worker, ran for %s, that's enough.",
22✔
567
                                  FORMAT_TIMESPAN(usec_sub_unsigned(n, start_time), 0));
568
                        break;
11✔
569
                }
570

571
                if (last_busy_usec == USEC_INFINITY)
29,938✔
572
                        last_busy_usec = n;
573
                else if (listen_idle_usec != USEC_INFINITY && n >= usec_add(last_busy_usec, listen_idle_usec)) {
365✔
574
                        log_debug("Exiting worker, been idle for %s.",
42✔
575
                                  FORMAT_TIMESPAN(usec_sub_unsigned(n, last_busy_usec), 0));
576
                        break;
21✔
577
                }
578

579
                (void) rename_process("systemd-userwork: waiting...");
29,917✔
580
                fd = RET_NERRNO(accept4(listen_fd, NULL, NULL, SOCK_NONBLOCK|SOCK_CLOEXEC));
29,917✔
581
                (void) rename_process("systemd-userwork: processing...");
29,917✔
582

583
                if (fd == -EAGAIN)
29,917✔
584
                        continue; /* The listening socket has SO_RECVTIMEO set, hence a timeout is expected
277✔
585
                                   * after a while, let's check if it's time to exit though. */
586
                if (fd == -EINTR)
29,640✔
587
                        continue; /* Might be that somebody attached via strace, let's just continue in that
×
588
                                   * case */
589
                if (fd < 0)
29,640✔
590
                        return log_error_errno(fd, "Failed to accept() from listening socket: %m");
×
591

592
                if (now(CLOCK_MONOTONIC) <= usec_add(n, PRESSURE_SLEEP_TIME_USEC)) {
29,640✔
593
                        /* We only slept a very short time? If so, let's see if there are more sockets
594
                         * pending, and if so, let's ask our parent for more workers */
595

596
                        r = fd_wait_for_event(listen_fd, POLLIN, 0);
24,143✔
597
                        if (r < 0)
24,143✔
598
                                return log_error_errno(r, "Failed to test for POLLIN on listening socket: %m");
×
599

600
                        if (FLAGS_SET(r, POLLIN)) {
24,143✔
601
                                r = pidref_kill(&parent, SIGUSR2);
249✔
602
                                if (r == -ESRCH)
249✔
603
                                        return log_error_errno(r, "Parent already died?");
×
604
                                if (r < 0)
249✔
605
                                        return log_error_errno(r, "Failed to send SIGUSR2 signal to parent: %m");
×
606
                        }
607
                }
608

609
                (void) process_connection(server, TAKE_FD(fd));
29,640✔
610
                last_busy_usec = USEC_INFINITY;
29,640✔
611
        }
612

613
        return 0;
614
}
615

616
DEFINE_MAIN_FUNCTION(run);
477✔
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