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

systemd / systemd / 14161316195

30 Mar 2025 08:18AM UTC coverage: 71.892% (-0.08%) from 71.976%
14161316195

push

github

DaanDeMeyer
test: skip networkd tests if networkd/resolved are disabled at build time

296399 of 412283 relevant lines covered (71.89%)

653258.53 hits per line

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

72.47
/src/sysusers/sysusers.c
1
/* SPDX-License-Identifier: LGPL-2.1-or-later */
2

3
#include <getopt.h>
4

5
#include "alloc-util.h"
6
#include "audit-util.h"
7
#include "build.h"
8
#include "chase.h"
9
#include "conf-files.h"
10
#include "constants.h"
11
#include "copy.h"
12
#include "creds-util.h"
13
#include "dissect-image.h"
14
#include "env-util.h"
15
#include "fd-util.h"
16
#include "fileio.h"
17
#include "format-util.h"
18
#include "fs-util.h"
19
#include "hashmap.h"
20
#include "libcrypt-util.h"
21
#include "main-func.h"
22
#include "memory-util.h"
23
#include "mount-util.h"
24
#include "pager.h"
25
#include "parse-argument.h"
26
#include "path-util.h"
27
#include "pretty-print.h"
28
#include "selinux-util.h"
29
#include "set.h"
30
#include "smack-util.h"
31
#include "specifier.h"
32
#include "stat-util.h"
33
#include "string-util.h"
34
#include "strv.h"
35
#include "sync-util.h"
36
#include "tmpfile-util-label.h"
37
#include "uid-classification.h"
38
#include "uid-range.h"
39
#include "user-util.h"
40
#include "utf8.h"
41
#include "verbs.h"
42

43
typedef enum ItemType {
44
        ADD_USER =   'u',
45
        ADD_GROUP =  'g',
46
        ADD_MEMBER = 'm',
47
        ADD_RANGE =  'r',
48
} ItemType;
49

50
static const char* item_type_to_string(ItemType t) {
×
51
        switch (t) {
×
52
        case ADD_USER:
53
                return "user";
54
        case ADD_GROUP:
×
55
                return "group";
×
56
        case ADD_MEMBER:
×
57
                return "member";
×
58
        case ADD_RANGE:
×
59
                return "range";
×
60
        default:
×
61
                assert_not_reached();
×
62
        }
63
}
64

65
typedef struct Item {
66
        ItemType type;
67

68
        char *name;
69
        char *group_name;
70
        char *uid_path;
71
        char *gid_path;
72
        char *description;
73
        char *home;
74
        char *shell;
75

76
        gid_t gid;
77
        uid_t uid;
78

79
        char *filename;
80
        unsigned line;
81

82
        bool gid_set;
83

84
        /* When set the group with the specified GID must exist
85
         * and the check if a UID clashes with the GID is skipped.
86
         */
87
        bool id_set_strict;
88

89
        bool uid_set;
90

91
        bool locked;
92

93
        bool todo_user;
94
        bool todo_group;
95
} Item;
96

97
static char *arg_root = NULL;
98
static char *arg_image = NULL;
99
static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
100
static const char *arg_replace = NULL;
101
static bool arg_dry_run = false;
102
static bool arg_inline = false;
103
static PagerFlags arg_pager_flags = 0;
104
static ImagePolicy *arg_image_policy = NULL;
105

106
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
113✔
107
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
113✔
108
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
113✔
109

110
typedef struct Context {
111
        int audit_fd;
112

113
        OrderedHashmap *users, *groups;
114
        OrderedHashmap *todo_uids, *todo_gids;
115
        OrderedHashmap *members;
116

117
        Hashmap *database_by_uid, *database_by_username;
118
        Hashmap *database_by_gid, *database_by_groupname;
119

120
        /* A helper set to hold names that are used by database_by_{uid,gid,username,groupname} above. */
121
        Set *names;
122

123
        uid_t search_uid;
124
        UIDRange *uid_range;
125

126
        UGIDAllocationRange login_defs;
127
        bool login_defs_need_warning;
128
} Context;
129

130
static void context_done(Context *c) {
113✔
131
        assert(c);
113✔
132

133
        c->audit_fd = close_audit_fd(c->audit_fd);
113✔
134

135
        ordered_hashmap_free(c->groups);
113✔
136
        ordered_hashmap_free(c->users);
113✔
137
        ordered_hashmap_free(c->members);
113✔
138
        ordered_hashmap_free(c->todo_uids);
113✔
139
        ordered_hashmap_free(c->todo_gids);
113✔
140

141
        hashmap_free(c->database_by_uid);
113✔
142
        hashmap_free(c->database_by_username);
113✔
143
        hashmap_free(c->database_by_gid);
113✔
144
        hashmap_free(c->database_by_groupname);
113✔
145

146
        set_free_free(c->names);
113✔
147
        uid_range_free(c->uid_range);
113✔
148
}
113✔
149

150
static void maybe_emit_login_defs_warning(Context *c) {
45✔
151
        assert(c);
45✔
152

153
        if (!c->login_defs_need_warning)
45✔
154
                return;
155

156
        if (c->login_defs.system_alloc_uid_min != SYSTEM_ALLOC_UID_MIN ||
44✔
157
            c->login_defs.system_uid_max != SYSTEM_UID_MAX)
158
                log_warning("login.defs specifies UID allocation range "UID_FMT"–"UID_FMT
×
159
                            " that is different than the built-in defaults ("UID_FMT"–"UID_FMT")",
160
                            c->login_defs.system_alloc_uid_min, c->login_defs.system_uid_max,
161
                            (uid_t) SYSTEM_ALLOC_UID_MIN, (uid_t) SYSTEM_UID_MAX);
162
        if (c->login_defs.system_alloc_gid_min != SYSTEM_ALLOC_GID_MIN ||
44✔
163
            c->login_defs.system_gid_max != SYSTEM_GID_MAX)
164
                log_warning("login.defs specifies GID allocation range "GID_FMT"–"GID_FMT
×
165
                            " that is different than the built-in defaults ("GID_FMT"–"GID_FMT")",
166
                            c->login_defs.system_alloc_gid_min, c->login_defs.system_gid_max,
167
                            (gid_t) SYSTEM_ALLOC_GID_MIN, (gid_t) SYSTEM_GID_MAX);
168

169
        c->login_defs_need_warning = false;
44✔
170
}
171

172
static void log_audit_accounts(Context *c, ItemType what) {
226✔
173
#if HAVE_AUDIT
174
        assert(c);
226✔
175
        assert(IN_SET(what, ADD_USER, ADD_GROUP));
226✔
176

177
        if (arg_dry_run || c->audit_fd < 0)
226✔
178
                return;
226✔
179

180
        Item *i;
×
181
        int type = what == ADD_USER ? AUDIT_ADD_USER : AUDIT_ADD_GROUP;
×
182
        const char *op = what == ADD_USER ? "adding-user" : "adding-group";
×
183

184
        /* Notes:
185
         *
186
         * The op must not contain whitespace. The format with a dash matches what Fedora shadow-utils uses.
187
         *
188
         * We send id == -1, even though we know the number, in particular on success. This is because if we
189
         * send the id, the generated audit message will not contain the name. The name seems more useful
190
         * than the number, hence send just the name:
191
         *
192
         * type=ADD_USER msg=audit(01/10/2025 16:02:00.639:3854) :
193
         *   pid=3846380 uid=root auid=zbyszek ses=2 msg='op=adding-user id=unknown(952) exe=systemd-sysusers ... res=success'
194
         * vs.
195
         * type=ADD_USER msg=audit(01/10/2025 16:03:15.457:3908) :
196
         *   pid=3846607 uid=root auid=zbyszek ses=2 msg='op=adding-user acct=foo5 exe=systemd-sysusers ... res=success'
197
         */
198

199
        ORDERED_HASHMAP_FOREACH(i, what == ADD_USER ? c->todo_uids : c->todo_gids)
×
200
                audit_log_acct_message(
×
201
                                c->audit_fd,
202
                                type,
203
                                program_invocation_short_name,
204
                                op,
205
                                i->name,
×
206
                                /* id= */ (unsigned) -1,
207
                                /* host= */ NULL,
208
                                /* addr= */ NULL,
209
                                /* tty= */ NULL,
210
                                /* success= */ 1);
211
#endif
212
}
213

214
static int load_user_database(Context *c) {
113✔
215
        _cleanup_free_ char *passwd_path = NULL;
113✔
216
        _cleanup_fclose_ FILE *f = NULL;
113✔
217
        struct passwd *pw;
113✔
218
        int r;
113✔
219

220
        assert(c);
113✔
221

222
        r = chase_and_fopen_unlocked("/etc/passwd", arg_root, CHASE_PREFIX_ROOT, "re", &passwd_path, &f);
113✔
223
        if (r == -ENOENT)
113✔
224
                return 0;
225
        if (r < 0)
37✔
226
                return r;
227

228
        while ((r = fgetpwent_sane(f, &pw)) > 0) {
254✔
229

230
                char *n = strdup(pw->pw_name);
217✔
231
                if (!n)
217✔
232
                        return -ENOMEM;
233

234
                /* Note that we use NULL hash_ops (i.e. trivial_hash_ops) here, so identical strings can
235
                 * exist in the set. */
236
                r = set_ensure_consume(&c->names, /* hash_ops= */ NULL, n);
217✔
237
                if (r < 0)
217✔
238
                        return r;
239
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
217✔
240

241
                r = hashmap_ensure_put(&c->database_by_username, &string_hash_ops, n, UID_TO_PTR(pw->pw_uid));
217✔
242
                if (r == -EEXIST)
217✔
243
                        log_debug_errno(r, "%s: user '%s' is listed twice, ignoring duplicate uid.",
×
244
                                        passwd_path, n);
245
                else if (r < 0)
217✔
246
                        return r;
247

248
                r = hashmap_ensure_put(&c->database_by_uid, /* hash_ops= */ NULL, UID_TO_PTR(pw->pw_uid), n);
217✔
249
                if (r == -EEXIST)
217✔
250
                        log_debug_errno(r, "%s: uid "UID_FMT" is listed twice, ignoring duplicate name.",
260✔
251
                                        passwd_path, pw->pw_uid);
252
                else if (r < 0)
211✔
253
                        return r;
254
        }
255
        return r;
256
}
257

258
static int load_group_database(Context *c) {
113✔
259
        _cleanup_free_ char *group_path = NULL;
113✔
260
        _cleanup_fclose_ FILE *f = NULL;
113✔
261
        struct group *gr;
113✔
262
        int r;
113✔
263

264
        assert(c);
113✔
265

266
        r = chase_and_fopen_unlocked("/etc/group", arg_root, CHASE_PREFIX_ROOT, "re", &group_path, &f);
113✔
267
        if (r == -ENOENT)
113✔
268
                return 0;
269
        if (r < 0)
37✔
270
                return r;
271

272
        while ((r = fgetgrent_sane(f, &gr)) > 0) {
457✔
273
                char *n = strdup(gr->gr_name);
420✔
274
                if (!n)
420✔
275
                        return -ENOMEM;
276

277
                /* Note that we use NULL hash_ops (i.e. trivial_hash_ops) here, so identical strings can
278
                 * exist in the set. */
279
                r = set_ensure_consume(&c->names, /* hash_ops= */ NULL, n);
420✔
280
                if (r < 0)
420✔
281
                        return r;
282
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
420✔
283

284
                r = hashmap_ensure_put(&c->database_by_groupname, &string_hash_ops, n, GID_TO_PTR(gr->gr_gid));
420✔
285
                if (r == -EEXIST)
420✔
286
                        log_debug_errno(r, "%s: group '%s' is listed twice, ignoring duplicate gid.",
×
287
                                        group_path, n);
288
                else if (r < 0)
420✔
289
                        return r;
290

291
                r = hashmap_ensure_put(&c->database_by_gid, /* hash_ops= */ NULL, GID_TO_PTR(gr->gr_gid), n);
420✔
292
                if (r == -EEXIST)
420✔
293
                        log_debug_errno(r, "%s: gid "GID_FMT" is listed twice, ignoring duplicate name.",
469✔
294
                                        group_path, gr->gr_gid);
295
                else if (r < 0)
408✔
296
                        return r;
297
        }
298
        return r;
299
}
300

301
static int make_backup(const char *target, const char *x) {
348✔
302
        _cleanup_(unlink_and_freep) char *dst_tmp = NULL;
×
303
        _cleanup_fclose_ FILE *dst = NULL;
348✔
304
        _cleanup_close_ int src = -EBADF;
348✔
305
        const char *backup;
348✔
306
        struct stat st;
348✔
307
        int r;
348✔
308

309
        assert(target);
348✔
310
        assert(x);
348✔
311

312
        src = open(x, O_RDONLY|O_CLOEXEC|O_NOCTTY);
348✔
313
        if (src < 0) {
348✔
314
                if (errno == ENOENT) /* No backup necessary... */
312✔
315
                        return 0;
316

317
                return -errno;
×
318
        }
319

320
        if (fstat(src, &st) < 0)
36✔
321
                return -errno;
×
322

323
        r = fopen_temporary_label(
36✔
324
                        target,   /* The path for which to the look up the label */
325
                        x,        /* Where we want the file actually to end up */
326
                        &dst,     /* The temporary file we write to */
327
                        &dst_tmp);
328
        if (r < 0)
36✔
329
                return r;
330

331
        r = copy_bytes(src, fileno(dst), UINT64_MAX, COPY_REFLINK);
36✔
332
        if (r < 0)
36✔
333
                return r;
334

335
        backup = strjoina(x, "-");
180✔
336

337
        /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
338
         * unreadable by others, then it isn't too bad... */
339
        r = fchmod_and_chown_with_fallback(fileno(dst), dst_tmp, st.st_mode & 07777, st.st_uid, st.st_gid);
36✔
340
        if (r < 0)
36✔
341
                log_warning_errno(r, "Failed to change access mode or ownership of %s: %m", backup);
×
342

343
        if (futimens(fileno(dst), (const struct timespec[2]) { st.st_atim, st.st_mtim }) < 0)
36✔
344
                log_warning_errno(errno, "Failed to fix access and modification time of %s: %m", backup);
×
345

346
        r = fsync_full(fileno(dst));
36✔
347
        if (r < 0)
36✔
348
                return r;
349

350
        if (rename(dst_tmp, backup) < 0)
36✔
351
                return errno;
×
352

353
        dst_tmp = mfree(dst_tmp); /* disable the unlink_and_freep() hook now that the file has been renamed */
36✔
354
        return 0;
36✔
355
}
356

357
static int putgrent_with_members(
753✔
358
                Context *c,
359
                const struct group *gr,
360
                FILE *group) {
361

362
        char **a;
753✔
363
        int r;
753✔
364

365
        assert(c);
753✔
366
        assert(gr);
753✔
367
        assert(group);
753✔
368

369
        a = ordered_hashmap_get(c->members, gr->gr_name);
753✔
370
        if (a) {
753✔
371
                _cleanup_strv_free_ char **l = NULL;
10✔
372
                bool added = false;
10✔
373

374
                l = strv_copy(gr->gr_mem);
10✔
375
                if (!l)
10✔
376
                        return -ENOMEM;
377

378
                STRV_FOREACH(i, a) {
20✔
379
                        if (strv_contains(l, *i))
10✔
380
                                continue;
5✔
381

382
                        r = strv_extend(&l, *i);
5✔
383
                        if (r < 0)
5✔
384
                                return r;
385

386
                        added = true;
387
                }
388

389
                if (added) {
10✔
390
                        struct group t;
5✔
391

392
                        strv_sort_uniq(l);
5✔
393

394
                        t = *gr;
5✔
395
                        t.gr_mem = l;
5✔
396

397
                        r = putgrent_sane(&t, group);
5✔
398
                        return r < 0 ? r : 1;
10✔
399
                }
400
        }
401

402
        return putgrent_sane(gr, group);
748✔
403
}
404

405
#if ENABLE_GSHADOW
406
static int putsgent_with_members(
743✔
407
                Context *c,
408
                const struct sgrp *sg,
409
                FILE *gshadow) {
410

411
        char **a;
743✔
412
        int r;
743✔
413

414
        assert(sg);
743✔
415
        assert(gshadow);
743✔
416

417
        a = ordered_hashmap_get(c->members, sg->sg_namp);
743✔
418
        if (a) {
743✔
419
                _cleanup_strv_free_ char **l = NULL;
10✔
420
                bool added = false;
10✔
421

422
                l = strv_copy(sg->sg_mem);
10✔
423
                if (!l)
10✔
424
                        return -ENOMEM;
425

426
                STRV_FOREACH(i, a) {
20✔
427
                        if (strv_contains(l, *i))
10✔
428
                                continue;
5✔
429

430
                        r = strv_extend(&l, *i);
5✔
431
                        if (r < 0)
5✔
432
                                return r;
433

434
                        added = true;
435
                }
436

437
                if (added) {
10✔
438
                        struct sgrp t;
5✔
439

440
                        strv_sort_uniq(l);
5✔
441

442
                        t = *sg;
5✔
443
                        t.sg_mem = l;
5✔
444

445
                        r = putsgent_sane(&t, gshadow);
5✔
446
                        return r < 0 ? r : 1;
10✔
447
                }
448
        }
449

450
        return putsgent_sane(sg, gshadow);
738✔
451
}
452
#endif
453

454
static const char* pick_shell(const Item *i) {
270✔
455
        assert(i);
270✔
456

457
        if (i->type != ADD_USER)
270✔
458
                return NULL;
459
        if (i->shell)
268✔
460
                return i->shell;
461
        if (i->uid_set && i->uid == 0)
248✔
462
                return default_root_shell(arg_root);
10✔
463
        return NOLOGIN;
464
}
465

466
static int write_temporary_passwd(
113✔
467
                Context *c,
468
                const char *passwd_path,
469
                FILE **ret_tmpfile,
470
                char **ret_tmpfile_path) {
471

472
        _cleanup_fclose_ FILE *original = NULL, *passwd = NULL;
113✔
473
        _cleanup_(unlink_and_freep) char *passwd_tmp = NULL;
113✔
474
        struct passwd *pw = NULL;
113✔
475
        Item *i;
113✔
476
        int r;
113✔
477

478
        assert(c);
113✔
479

480
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
481
                return 0;
482

483
        if (arg_dry_run) {
87✔
484
                log_info("Would write /etc/passwd%s", glyph(GLYPH_ELLIPSIS));
×
485
                return 0;
×
486
        }
487

488
        r = fopen_temporary_label("/etc/passwd", passwd_path, &passwd, &passwd_tmp);
87✔
489
        if (r < 0)
87✔
490
                return log_debug_errno(r, "Failed to open temporary copy of %s: %m", passwd_path);
×
491

492
        original = fopen(passwd_path, "re");
87✔
493
        if (original) {
87✔
494

495
                /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
496
                 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
497
                 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
498
                 * it easier to depend on sysusers in packaging scripts and suchlike. */
499
                r = copy_rights_with_fallback(fileno(original), fileno(passwd), passwd_tmp);
14✔
500
                if (r < 0)
14✔
501
                        return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
×
502
                                               passwd_path, passwd_tmp);
503

504
                while ((r = fgetpwent_sane(original, &pw)) > 0) {
138✔
505
                        i = ordered_hashmap_get(c->users, pw->pw_name);
129✔
506
                        if (i && i->todo_user)
129✔
507
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
508
                                                       "%s: User \"%s\" already exists.",
509
                                                       passwd_path, pw->pw_name);
510

511
                        if (ordered_hashmap_contains(c->todo_uids, UID_TO_PTR(pw->pw_uid)))
129✔
512
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
513
                                                       "%s: Detected collision for UID " UID_FMT ".",
514
                                                       passwd_path, pw->pw_uid);
515

516
                        /* Make sure we keep the NIS entries (if any) at the end. */
517
                        if (IN_SET(pw->pw_name[0], '+', '-'))
129✔
518
                                break;
519

520
                        r = putpwent_sane(pw, passwd);
124✔
521
                        if (r < 0)
124✔
522
                                return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
×
523
                                                       pw->pw_name);
524
                }
525
                if (r < 0)
14✔
526
                        return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
×
527

528
        } else {
529
                if (errno != ENOENT)
73✔
530
                        return log_debug_errno(errno, "Failed to open %s: %m", passwd_path);
×
531
                if (fchmod(fileno(passwd), 0644) < 0)
73✔
532
                        return log_debug_errno(errno, "Failed to fchmod %s: %m", passwd_tmp);
×
533
        }
534

535
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
355✔
536
                _cleanup_free_ char *creds_shell = NULL, *cn = NULL;
268✔
537

538
                struct passwd n = {
1,072✔
539
                        .pw_name = i->name,
268✔
540
                        .pw_uid = i->uid,
268✔
541
                        .pw_gid = i->gid,
268✔
542
                        .pw_gecos = (char*) strempty(i->description),
268✔
543

544
                        /* "x" means the password is stored in the shadow file */
545
                        .pw_passwd = (char*) PASSWORD_SEE_SHADOW,
546

547
                        /* We default to the root directory as home */
548
                        .pw_dir = i->home ?: (char*) "/",
268✔
549

550
                        /* Initialize the shell to nologin, with one exception:
551
                         * for root we patch in something special */
552
                        .pw_shell = (char*) pick_shell(i),
268✔
553
                };
554

555
                /* Try to pick up the shell for this account via the credentials logic */
556
                cn = strjoin("passwd.shell.", i->name);
268✔
557
                if (!cn)
268✔
558
                        return -ENOMEM;
559

560
                r = read_credential(cn, (void**) &creds_shell, NULL);
268✔
561
                if (r < 0)
268✔
562
                        log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
268✔
563
                else
564
                        n.pw_shell = creds_shell;
×
565

566
                r = putpwent_sane(&n, passwd);
268✔
567
                if (r < 0)
268✔
568
                        return log_debug_errno(r, "Failed to add new user \"%s\" to temporary passwd file: %m",
×
569
                                               i->name);
570
        }
571

572
        /* Append the remaining NIS entries if any */
573
        while (pw) {
87✔
574
                r = putpwent_sane(pw, passwd);
5✔
575
                if (r < 0)
5✔
576
                        return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
×
577
                                               pw->pw_name);
578

579
                r = fgetpwent_sane(original, &pw);
5✔
580
                if (r < 0)
5✔
581
                        return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
×
582
                if (r == 0)
5✔
583
                        break;
584
        }
585

586
        r = fflush_sync_and_check(passwd);
87✔
587
        if (r < 0)
87✔
588
                return log_debug_errno(r, "Failed to flush %s: %m", passwd_tmp);
×
589

590
        *ret_tmpfile = TAKE_PTR(passwd);
87✔
591
        *ret_tmpfile_path = TAKE_PTR(passwd_tmp);
87✔
592

593
        return 0;
87✔
594
}
595

596
static usec_t epoch_or_now(void) {
87✔
597
        uint64_t epoch;
87✔
598

599
        if (secure_getenv_uint64("SOURCE_DATE_EPOCH", &epoch) >= 0) {
87✔
600
                if (epoch > UINT64_MAX/USEC_PER_SEC) /* Overflow check */
×
601
                        return USEC_INFINITY;
87✔
602
                return (usec_t) epoch * USEC_PER_SEC;
×
603
        }
604

605
        return now(CLOCK_REALTIME);
87✔
606
}
607

608
static int write_temporary_shadow(
113✔
609
                Context *c,
610
                const char *shadow_path,
611
                FILE **ret_tmpfile,
612
                char **ret_tmpfile_path) {
613

614
        _cleanup_fclose_ FILE *original = NULL, *shadow = NULL;
113✔
615
        _cleanup_(unlink_and_freep) char *shadow_tmp = NULL;
113✔
616
        struct spwd *sp = NULL;
113✔
617
        long lstchg;
113✔
618
        Item *i;
113✔
619
        int r;
113✔
620

621
        assert(c);
113✔
622

623
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
624
                return 0;
625

626
        if (arg_dry_run) {
87✔
627
                log_info("Would write /etc/shadow%s", glyph(GLYPH_ELLIPSIS));
×
628
                return 0;
×
629
        }
630

631
        r = fopen_temporary_label("/etc/shadow", shadow_path, &shadow, &shadow_tmp);
87✔
632
        if (r < 0)
87✔
633
                return log_debug_errno(r, "Failed to open temporary copy of %s: %m", shadow_path);
×
634

635
        lstchg = (long) (epoch_or_now() / USEC_PER_DAY);
87✔
636

637
        original = fopen(shadow_path, "re");
87✔
638
        if (original) {
87✔
639

640
                r = copy_rights_with_fallback(fileno(original), fileno(shadow), shadow_tmp);
4✔
641
                if (r < 0)
4✔
642
                        return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
×
643
                                               shadow_path, shadow_tmp);
644

645
                while ((r = fgetspent_sane(original, &sp)) > 0) {
103✔
646
                        i = ordered_hashmap_get(c->users, sp->sp_namp);
99✔
647
                        if (i && i->todo_user) {
99✔
648
                                /* we will update the existing entry */
649
                                sp->sp_lstchg = lstchg;
×
650

651
                                /* only the /etc/shadow stage is left, so we can
652
                                 * safely remove the item from the todo set */
653
                                i->todo_user = false;
×
654
                                ordered_hashmap_remove(c->todo_uids, UID_TO_PTR(i->uid));
×
655
                        }
656

657
                        /* Make sure we keep the NIS entries (if any) at the end. */
658
                        if (IN_SET(sp->sp_namp[0], '+', '-'))
99✔
659
                                break;
660

661
                        r = putspent_sane(sp, shadow);
99✔
662
                        if (r < 0)
99✔
663
                                return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
×
664
                                                       sp->sp_namp);
665

666
                }
667
                if (r < 0)
4✔
668
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
×
669

670
        } else {
671
                if (errno != ENOENT)
83✔
672
                        return log_debug_errno(errno, "Failed to open %s: %m", shadow_path);
×
673
                if (fchmod(fileno(shadow), 0000) < 0)
83✔
674
                        return log_debug_errno(errno, "Failed to fchmod %s: %m", shadow_tmp);
×
675
        }
676

677
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
355✔
678
                _cleanup_(erase_and_freep) char *creds_password = NULL;
268✔
679
                bool is_hashed;
268✔
680

681
                struct spwd n = {
536✔
682
                        .sp_namp = i->name,
268✔
683
                        .sp_lstchg = lstchg,
684
                        .sp_min = -1,
685
                        .sp_max = -1,
686
                        .sp_warn = -1,
687
                        .sp_inact = -1,
688
                        .sp_expire = i->locked ? 1 : -1, /* Negative expiration means "unset". Expiration 0 or 1 means "locked" */
268✔
689
                        .sp_flag = ULONG_MAX, /* this appears to be what everybody does ... */
690
                };
691

692
                r = get_credential_user_password(i->name, &creds_password, &is_hashed);
268✔
693
                if (r < 0)
268✔
694
                        log_debug_errno(r, "Couldn't read password credential for user '%s', ignoring: %m", i->name);
268✔
695

696
                if (creds_password && !is_hashed) {
268✔
697
                        _cleanup_(erase_and_freep) char* plaintext_password = TAKE_PTR(creds_password);
×
698
                        r = hash_password(plaintext_password, &creds_password);
×
699
                        if (r < 0)
×
700
                                return log_debug_errno(r, "Failed to hash password: %m");
×
701
                }
702

703
                if (creds_password)
268✔
704
                        n.sp_pwdp = creds_password;
×
705
                else if (streq(i->name, "root"))
268✔
706
                        /* Let firstboot set the password later */
707
                        n.sp_pwdp = (char*) PASSWORD_UNPROVISIONED;
10✔
708
                else
709
                        n.sp_pwdp = (char*) PASSWORD_LOCKED_AND_INVALID;
258✔
710

711
                r = putspent_sane(&n, shadow);
268✔
712
                if (r < 0)
268✔
713
                        return log_debug_errno(r, "Failed to add new user \"%s\" to temporary shadow file: %m",
×
714
                                               i->name);
715
        }
716

717
        /* Append the remaining NIS entries if any */
718
        while (sp) {
87✔
719
                r = putspent_sane(sp, shadow);
×
720
                if (r < 0)
×
721
                        return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
×
722
                                               sp->sp_namp);
723

724
                r = fgetspent_sane(original, &sp);
×
725
                if (r < 0)
×
726
                        return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
×
727
                if (r == 0)
×
728
                        break;
729
        }
730
        if (!IN_SET(errno, 0, ENOENT))
87✔
731
                return -errno;
×
732

733
        r = fflush_sync_and_check(shadow);
87✔
734
        if (r < 0)
87✔
735
                return log_debug_errno(r, "Failed to flush %s: %m", shadow_tmp);
×
736

737
        *ret_tmpfile = TAKE_PTR(shadow);
87✔
738
        *ret_tmpfile_path = TAKE_PTR(shadow_tmp);
87✔
739

740
        return 0;
87✔
741
}
742

743
static int write_temporary_group(
113✔
744
                Context *c,
745
                const char *group_path,
746
                FILE **ret_tmpfile,
747
                char **ret_tmpfile_path) {
748

749
        _cleanup_fclose_ FILE *original = NULL, *group = NULL;
113✔
750
        _cleanup_(unlink_and_freep) char *group_tmp = NULL;
113✔
751
        bool group_changed = false;
113✔
752
        struct group *gr = NULL;
113✔
753
        Item *i;
113✔
754
        int r;
113✔
755

756
        assert(c);
113✔
757

758
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
759
                return 0;
760

761
        if (arg_dry_run) {
87✔
762
                log_info("Would write /etc/group%s", glyph(GLYPH_ELLIPSIS));
×
763
                return 0;
×
764
        }
765

766
        r = fopen_temporary_label("/etc/group", group_path, &group, &group_tmp);
87✔
767
        if (r < 0)
87✔
768
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", group_path);
×
769

770
        original = fopen(group_path, "re");
87✔
771
        if (original) {
87✔
772

773
                r = copy_rights_with_fallback(fileno(original), fileno(group), group_tmp);
14✔
774
                if (r < 0)
14✔
775
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
×
776
                                               group_path, group_tmp);
777

778
                while ((r = fgetgrent_sane(original, &gr)) > 0) {
251✔
779
                        /* Safety checks against name and GID collisions. Normally,
780
                         * this should be unnecessary, but given that we look at the
781
                         * entries anyway here, let's make an extra verification
782
                         * step that we don't generate duplicate entries. */
783

784
                        i = ordered_hashmap_get(c->groups, gr->gr_name);
242✔
785
                        if (i && i->todo_group)
242✔
786
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
787
                                                       "%s: Group \"%s\" already exists.",
788
                                                       group_path, gr->gr_name);
789

790
                        if (ordered_hashmap_contains(c->todo_gids, GID_TO_PTR(gr->gr_gid)))
242✔
791
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
792
                                                       "%s: Detected collision for GID " GID_FMT ".",
793
                                                       group_path, gr->gr_gid);
794

795
                        /* Make sure we keep the NIS entries (if any) at the end. */
796
                        if (IN_SET(gr->gr_name[0], '+', '-'))
242✔
797
                                break;
798

799
                        r = putgrent_with_members(c, gr, group);
237✔
800
                        if (r < 0)
237✔
801
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
×
802
                                                       gr->gr_name);
803
                        if (r > 0)
237✔
804
                                group_changed = true;
×
805
                }
806
                if (r < 0)
14✔
807
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
×
808

809
        } else {
810
                if (errno != ENOENT)
73✔
811
                        return log_error_errno(errno, "Failed to open %s: %m", group_path);
×
812
                if (fchmod(fileno(group), 0644) < 0)
73✔
813
                        return log_error_errno(errno, "Failed to fchmod %s: %m", group_tmp);
×
814
        }
815

816
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
603✔
817
                struct group n = {
516✔
818
                        .gr_name = i->name,
516✔
819
                        .gr_gid = i->gid,
516✔
820
                        .gr_passwd = (char*) PASSWORD_SEE_SHADOW,
821
                };
822

823
                r = putgrent_with_members(c, &n, group);
516✔
824
                if (r < 0)
516✔
825
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary group file: %m",
×
826
                                               gr->gr_name);
827

828
                group_changed = true;
516✔
829
        }
830

831
        /* Append the remaining NIS entries if any */
832
        while (gr) {
97✔
833
                r = putgrent_sane(gr, group);
15✔
834
                if (r < 0)
15✔
835
                        return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
×
836
                                               gr->gr_name);
837

838
                r = fgetgrent_sane(original, &gr);
15✔
839
                if (r < 0)
15✔
840
                        return log_error_errno(r, "Failed to read %s: %m", group_path);
×
841
                if (r == 0)
15✔
842
                        break;
843
        }
844

845
        r = fflush_sync_and_check(group);
87✔
846
        if (r < 0)
87✔
847
                return log_error_errno(r, "Failed to flush %s: %m", group_tmp);
×
848

849
        if (group_changed) {
87✔
850
                *ret_tmpfile = TAKE_PTR(group);
87✔
851
                *ret_tmpfile_path = TAKE_PTR(group_tmp);
87✔
852
        }
853
        return 0;
854
}
855

856
static int write_temporary_gshadow(
113✔
857
                Context *c,
858
                const char * gshadow_path,
859
                FILE **ret_tmpfile,
860
                char **ret_tmpfile_path) {
861

862
#if ENABLE_GSHADOW
863
        _cleanup_fclose_ FILE *original = NULL, *gshadow = NULL;
113✔
864
        _cleanup_(unlink_and_freep) char *gshadow_tmp = NULL;
113✔
865
        bool group_changed = false;
113✔
866
        Item *i;
113✔
867
        int r;
113✔
868

869
        assert(c);
113✔
870

871
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
872
                return 0;
873

874
        if (arg_dry_run) {
87✔
875
                log_info("Would write /etc/gshadow%s", glyph(GLYPH_ELLIPSIS));
×
876
                return 0;
×
877
        }
878

879
        r = fopen_temporary_label("/etc/gshadow", gshadow_path, &gshadow, &gshadow_tmp);
87✔
880
        if (r < 0)
87✔
881
                return log_error_errno(r, "Failed to open temporary copy of %s: %m", gshadow_path);
×
882

883
        original = fopen(gshadow_path, "re");
87✔
884
        if (original) {
87✔
885
                struct sgrp *sg;
4✔
886

887
                r = copy_rights_with_fallback(fileno(original), fileno(gshadow), gshadow_tmp);
4✔
888
                if (r < 0)
4✔
889
                        return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
×
890
                                               gshadow_path, gshadow_tmp);
891

892
                while ((r = fgetsgent_sane(original, &sg)) > 0) {
231✔
893

894
                        i = ordered_hashmap_get(c->groups, sg->sg_namp);
227✔
895
                        if (i && i->todo_group)
227✔
896
                                return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
×
897
                                                       "%s: Group \"%s\" already exists.",
898
                                                       gshadow_path, sg->sg_namp);
899

900
                        r = putsgent_with_members(c, sg, gshadow);
227✔
901
                        if (r < 0)
227✔
902
                                return log_error_errno(r, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
×
903
                                                       sg->sg_namp);
904
                        if (r > 0)
227✔
905
                                group_changed = true;
×
906
                }
907
                if (r < 0)
4✔
908
                        return r;
909

910
        } else {
911
                if (errno != ENOENT)
83✔
912
                        return log_error_errno(errno, "Failed to open %s: %m", gshadow_path);
×
913
                if (fchmod(fileno(gshadow), 0000) < 0)
83✔
914
                        return log_error_errno(errno, "Failed to fchmod %s: %m", gshadow_tmp);
×
915
        }
916

917
        ORDERED_HASHMAP_FOREACH(i, c->todo_gids) {
603✔
918
                struct sgrp n = {
516✔
919
                        .sg_namp = i->name,
516✔
920
                        .sg_passwd = (char*) PASSWORD_LOCKED_AND_INVALID,
921
                };
922

923
                r = putsgent_with_members(c, &n, gshadow);
516✔
924
                if (r < 0)
516✔
925
                        return log_error_errno(r, "Failed to add new group \"%s\" to temporary gshadow file: %m",
×
926
                                               n.sg_namp);
927

928
                group_changed = true;
516✔
929
        }
930

931
        r = fflush_sync_and_check(gshadow);
87✔
932
        if (r < 0)
87✔
933
                return log_error_errno(r, "Failed to flush %s: %m", gshadow_tmp);
×
934

935
        if (group_changed) {
87✔
936
                *ret_tmpfile = TAKE_PTR(gshadow);
87✔
937
                *ret_tmpfile_path = TAKE_PTR(gshadow_tmp);
87✔
938
        }
939
#endif
940
        return 0;
941
}
942

943
static int write_files(Context *c) {
113✔
944
        _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;
339✔
945
        _cleanup_(unlink_and_freep) char *passwd_tmp = NULL, *group_tmp = NULL, *shadow_tmp = NULL, *gshadow_tmp = NULL;
113✔
946
        int r;
113✔
947

948
        const char
113✔
949
                *passwd_path = prefix_roota(arg_root, "/etc/passwd"),
221✔
950
                *shadow_path = prefix_roota(arg_root, "/etc/shadow"),
221✔
951
                *group_path = prefix_roota(arg_root, "/etc/group"),
221✔
952
                *gshadow_path = prefix_roota(arg_root, "/etc/gshadow");
221✔
953

954
        assert(c);
113✔
955

956
        r = write_temporary_group(c, group_path, &group, &group_tmp);
113✔
957
        if (r < 0)
113✔
958
                return r;
959

960
        r = write_temporary_gshadow(c, gshadow_path, &gshadow, &gshadow_tmp);
113✔
961
        if (r < 0)
113✔
962
                return r;
963

964
        r = write_temporary_passwd(c, passwd_path, &passwd, &passwd_tmp);
113✔
965
        if (r < 0)
113✔
966
                return r;
967

968
        r = write_temporary_shadow(c, shadow_path, &shadow, &shadow_tmp);
113✔
969
        if (r < 0)
113✔
970
                return r;
971

972
        /* Make a backup of the old files */
973
        if (group) {
113✔
974
                r = make_backup("/etc/group", group_path);
87✔
975
                if (r < 0)
87✔
976
                        return log_error_errno(r, "Failed to backup %s: %m", group_path);
×
977
        }
978
        if (gshadow) {
113✔
979
                r = make_backup("/etc/gshadow", gshadow_path);
87✔
980
                if (r < 0)
87✔
981
                        return log_error_errno(r, "Failed to backup %s: %m", gshadow_path);
×
982
        }
983

984
        if (passwd) {
113✔
985
                r = make_backup("/etc/passwd", passwd_path);
87✔
986
                if (r < 0)
87✔
987
                        return log_error_errno(r, "Failed to backup %s: %m", passwd_path);
×
988
        }
989
        if (shadow) {
113✔
990
                r = make_backup("/etc/shadow", shadow_path);
87✔
991
                if (r < 0)
87✔
992
                        return log_error_errno(r, "Failed to backup %s: %m", shadow_path);
×
993
        }
994

995
        /* And make the new files count */
996
        if (group) {
113✔
997
                r = rename_and_apply_smack_floor_label(group_tmp, group_path);
87✔
998
                if (r < 0)
87✔
999
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1000
                                               group_tmp, group_path);
1001
                group_tmp = mfree(group_tmp);
87✔
1002
        }
1003
        /* OK, we have written the group entries successfully */
1004
        log_audit_accounts(c, ADD_GROUP);
113✔
1005
        if (gshadow) {
113✔
1006
                r = rename_and_apply_smack_floor_label(gshadow_tmp, gshadow_path);
87✔
1007
                if (r < 0)
87✔
1008
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1009
                                               gshadow_tmp, gshadow_path);
1010

1011
                gshadow_tmp = mfree(gshadow_tmp);
87✔
1012
        }
1013

1014
        if (passwd) {
113✔
1015
                r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
87✔
1016
                if (r < 0)
87✔
1017
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1018
                                               passwd_tmp, passwd_path);
1019

1020
                passwd_tmp = mfree(passwd_tmp);
87✔
1021
        }
1022
        /* OK, we have written the user entries successfully */
1023
        log_audit_accounts(c, ADD_USER);
113✔
1024
        if (shadow) {
113✔
1025
                r = rename_and_apply_smack_floor_label(shadow_tmp, shadow_path);
87✔
1026
                if (r < 0)
87✔
1027
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1028
                                               shadow_tmp, shadow_path);
1029

1030
                shadow_tmp = mfree(shadow_tmp);
87✔
1031
        }
1032

1033
        return 0;
1034
}
1035

1036
static int uid_is_ok(
288✔
1037
                Context *c,
1038
                uid_t uid,
1039
                const char *name,
1040
                bool check_with_gid) {
1041

1042
        int r;
288✔
1043
        assert(c);
288✔
1044

1045
        /* Let's see if we already have assigned the UID a second time */
1046
        if (ordered_hashmap_get(c->todo_uids, UID_TO_PTR(uid)))
288✔
1047
                return 0;
1048

1049
        /* Try to avoid using uids that are already used by a group
1050
         * that doesn't have the same name as our new user. */
1051
        if (check_with_gid) {
283✔
1052
                Item *i;
203✔
1053

1054
                i = ordered_hashmap_get(c->todo_gids, GID_TO_PTR(uid));
203✔
1055
                if (i && !streq(i->name, name))
203✔
1056
                        return 0;
1057
        }
1058

1059
        /* Let's check the files directly */
1060
        if (hashmap_contains(c->database_by_uid, UID_TO_PTR(uid)))
273✔
1061
                return 0;
1062

1063
        if (check_with_gid) {
273✔
1064
                const char *n;
193✔
1065

1066
                n = hashmap_get(c->database_by_gid, GID_TO_PTR(uid));
193✔
1067
                if (n && !streq(n, name))
193✔
1068
                        return 0;
1069
        }
1070

1071
        /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
1072
        if (!arg_root) {
268✔
1073
                _cleanup_free_ struct group *g = NULL;
5✔
1074

1075
                r = getpwuid_malloc(uid, /* ret= */ NULL);
5✔
1076
                if (r >= 0)
5✔
1077
                        return 0;
1078
                if (r != -ESRCH)
5✔
1079
                        log_warning_errno(r, "Unexpected failure while looking up UID '" UID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
×
1080

1081
                if (check_with_gid) {
5✔
1082
                        r = getgrgid_malloc((gid_t) uid, &g);
5✔
1083
                        if (r >= 0) {
5✔
1084
                                if (!streq(g->gr_name, name))
×
1085
                                        return 0;
1086
                        } else if (r != -ESRCH)
5✔
1087
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
5✔
1088
                }
1089
        }
1090

1091
        return 1;
1092
}
1093

1094
static int root_stat(const char *p, struct stat *ret_st) {
×
1095
        return chase_and_stat(p, arg_root, CHASE_PREFIX_ROOT, /* ret_path= */ NULL, ret_st);
×
1096
}
1097

1098
static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
70✔
1099
        struct stat st;
70✔
1100
        bool found_uid = false, found_gid = false;
70✔
1101
        uid_t uid = 0;
70✔
1102
        gid_t gid = 0;
70✔
1103

1104
        assert(i);
70✔
1105

1106
        /* First, try to get the GID directly */
1107
        if (ret_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
70✔
1108
                gid = st.st_gid;
×
1109
                found_gid = true;
×
1110
        }
1111

1112
        /* Then, try to get the UID directly */
1113
        if ((ret_uid || (ret_gid && !found_gid))
70✔
1114
            && i->uid_path
70✔
1115
            && root_stat(i->uid_path, &st) >= 0) {
×
1116

1117
                uid = st.st_uid;
×
1118
                found_uid = true;
×
1119

1120
                /* If we need the gid, but had no success yet, also derive it from the UID path */
1121
                if (ret_gid && !found_gid) {
×
1122
                        gid = st.st_gid;
×
1123
                        found_gid = true;
×
1124
                }
1125
        }
1126

1127
        /* If that didn't work yet, then let's reuse the GID as UID */
1128
        if (ret_uid && !found_uid && i->gid_path) {
70✔
1129

1130
                if (found_gid) {
×
1131
                        uid = (uid_t) gid;
1132
                        found_uid = true;
1133
                } else if (root_stat(i->gid_path, &st) >= 0) {
×
1134
                        uid = (uid_t) st.st_gid;
×
1135
                        found_uid = true;
×
1136
                }
1137
        }
1138

1139
        if (ret_uid) {
70✔
1140
                if (!found_uid)
40✔
1141
                        return 0;
70✔
1142

1143
                *ret_uid = uid;
×
1144
        }
1145

1146
        if (ret_gid) {
30✔
1147
                if (!found_gid)
30✔
1148
                        return 0;
1149

1150
                *ret_gid = gid;
×
1151
        }
1152

1153
        return 1;
1154
}
1155

1156
static int add_user(Context *c, Item *i) {
297✔
1157
        void *z;
297✔
1158
        int r;
297✔
1159

1160
        assert(c);
297✔
1161
        assert(i);
297✔
1162

1163
        /* Check the database directly */
1164
        z = hashmap_get(c->database_by_username, i->name);
297✔
1165
        if (z) {
297✔
1166
                log_debug("User %s already exists.", i->name);
29✔
1167
                i->uid = PTR_TO_UID(z);
29✔
1168
                i->uid_set = true;
29✔
1169
                return 0;
29✔
1170
        }
1171

1172
        if (!arg_root) {
268✔
1173
                _cleanup_free_ struct passwd *p = NULL;
5✔
1174

1175
                /* Also check NSS */
1176
                r = getpwnam_malloc(i->name, &p);
5✔
1177
                if (r >= 0) {
5✔
1178
                        log_debug("User %s already exists.", i->name);
×
1179
                        i->uid = p->pw_uid;
×
1180
                        i->uid_set = true;
×
1181

1182
                        r = free_and_strdup(&i->description, p->pw_gecos);
×
1183
                        if (r < 0)
×
1184
                                return log_oom();
×
1185

1186
                        return 0;
1187
                }
1188
                if (r != -ESRCH)
5✔
1189
                        log_warning_errno(r, "Unexpected failure while looking up user '%s' via NSS, assuming it doesn't exist: %m", i->name);
5✔
1190
        }
1191

1192
        /* Try to use the suggested numeric UID */
1193
        if (i->uid_set) {
268✔
1194
                r = uid_is_ok(c, i->uid, i->name, !i->id_set_strict);
233✔
1195
                if (r < 0)
233✔
1196
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1197
                if (r == 0) {
233✔
1198
                        log_info("Suggested user ID " UID_FMT " for %s already used.", i->uid, i->name);
5✔
1199
                        i->uid_set = false;
5✔
1200
                }
1201
        }
1202

1203
        /* If that didn't work, try to read it from the specified path */
1204
        if (!i->uid_set) {
268✔
1205
                uid_t candidate;
40✔
1206

1207
                if (read_id_from_file(i, &candidate, NULL) > 0) {
40✔
1208

1209
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
1210
                                log_debug("User ID " UID_FMT " of file not suitable for %s.", candidate, i->name);
×
1211
                        else {
1212
                                r = uid_is_ok(c, candidate, i->name, true);
×
1213
                                if (r < 0)
×
1214
                                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1215
                                else if (r > 0) {
×
1216
                                        i->uid = candidate;
×
1217
                                        i->uid_set = true;
×
1218
                                } else
1219
                                        log_debug("User ID " UID_FMT " of file for %s is already used.", candidate, i->name);
40✔
1220
                        }
1221
                }
1222
        }
1223

1224
        /* Otherwise, try to reuse the group ID */
1225
        if (!i->uid_set && i->gid_set) {
268✔
1226
                r = uid_is_ok(c, (uid_t) i->gid, i->name, true);
40✔
1227
                if (r < 0)
40✔
1228
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1229
                if (r > 0) {
40✔
1230
                        i->uid = (uid_t) i->gid;
25✔
1231
                        i->uid_set = true;
25✔
1232
                }
1233
        }
1234

1235
        /* And if that didn't work either, let's try to find a free one */
1236
        if (!i->uid_set) {
268✔
1237
                maybe_emit_login_defs_warning(c);
15✔
1238

1239
                for (;;) {
15✔
1240
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
15✔
1241
                        if (r < 0)
15✔
1242
                                return log_error_errno(r, "No free user ID available for %s.", i->name);
×
1243

1244
                        r = uid_is_ok(c, c->search_uid, i->name, true);
15✔
1245
                        if (r < 0)
15✔
1246
                                return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1247
                        else if (r > 0)
15✔
1248
                                break;
1249
                }
1250

1251
                i->uid_set = true;
15✔
1252
                i->uid = c->search_uid;
15✔
1253
        }
1254

1255
        r = ordered_hashmap_ensure_put(&c->todo_uids, NULL, UID_TO_PTR(i->uid), i);
268✔
1256
        if (r == -EEXIST)
268✔
1257
                return log_error_errno(r, "Requested user %s with UID " UID_FMT " and gid" GID_FMT " to be created is duplicated "
×
1258
                                       "or conflicts with another user.", i->name, i->uid, i->gid);
1259
        if (r == -ENOMEM)
268✔
1260
                return log_oom();
×
1261
        if (r < 0)
268✔
1262
                return log_error_errno(r, "Failed to store user %s with UID " UID_FMT " and GID " GID_FMT " to be created: %m",
×
1263
                                       i->name, i->uid, i->gid);
1264

1265
        i->todo_user = true;
268✔
1266
        log_info("Creating user '%s' (%s) with UID " UID_FMT " and GID " GID_FMT ".",
538✔
1267
                 i->name, strna(i->description), i->uid, i->gid);
1268

1269
        return 0;
1270
}
1271

1272
static int gid_is_ok(
720✔
1273
                Context *c,
1274
                gid_t gid,
1275
                const char *groupname,
1276
                bool check_with_uid) {
1277

1278
        Item *user;
720✔
1279
        char *username;
720✔
1280
        int r;
720✔
1281

1282
        assert(c);
720✔
1283
        assert(groupname);
720✔
1284

1285
        if (ordered_hashmap_get(c->todo_gids, GID_TO_PTR(gid)))
720✔
1286
                return 0;
1287

1288
        /* Avoid reusing gids that are already used by a different user */
1289
        if (check_with_uid) {
655✔
1290
                user = ordered_hashmap_get(c->todo_uids, UID_TO_PTR(gid));
321✔
1291
                if (user && !streq(user->name, groupname))
321✔
1292
                        return 0;
1293
        }
1294

1295
        if (hashmap_contains(c->database_by_gid, GID_TO_PTR(gid)))
655✔
1296
                return 0;
1297

1298
        if (check_with_uid) {
517✔
1299
                username = hashmap_get(c->database_by_uid, UID_TO_PTR(gid));
183✔
1300
                if (username && !streq(username, groupname))
183✔
1301
                        return 0;
1302
        }
1303

1304
        if (!arg_root) {
517✔
1305
                r = getgrgid_malloc(gid, /* ret= */ NULL);
5✔
1306
                if (r >= 0)
5✔
1307
                        return 0;
1308
                if (r != -ESRCH)
5✔
1309
                        log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", gid);
×
1310

1311
                if (check_with_uid) {
5✔
1312
                        r = getpwuid_malloc(gid, /* ret= */ NULL);
5✔
1313
                        if (r >= 0)
5✔
1314
                                return 0;
1315
                        if (r != -ESRCH)
5✔
1316
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", gid);
×
1317
                }
1318
        }
1319

1320
        return 1;
1321
}
1322

1323
static int get_gid_by_name(
645✔
1324
                Context *c,
1325
                const char *name,
1326
                gid_t *ret_gid) {
1327

1328
        void *z;
645✔
1329
        int r;
645✔
1330

1331
        assert(c);
645✔
1332
        assert(ret_gid);
645✔
1333

1334
        /* Check the database directly */
1335
        z = hashmap_get(c->database_by_groupname, name);
645✔
1336
        if (z) {
645✔
1337
                *ret_gid = PTR_TO_GID(z);
67✔
1338
                return 0;
67✔
1339
        }
1340

1341
        /* Also check NSS */
1342
        if (!arg_root) {
578✔
1343
                _cleanup_free_ struct group *g = NULL;
5✔
1344

1345
                r = getgrnam_malloc(name, &g);
5✔
1346
                if (r >= 0) {
5✔
1347
                        *ret_gid = g->gr_gid;
×
1348
                        return 0;
×
1349
                }
1350
                if (r != -ESRCH)
5✔
1351
                        log_warning_errno(r, "Unexpected failure while looking up group '%s' via NSS, assuming it doesn't exist: %m", name);
5✔
1352
        }
1353

1354
        return -ENOENT;
1355
}
1356

1357
static int add_group(Context *c, Item *i) {
639✔
1358
        int r;
639✔
1359

1360
        assert(c);
639✔
1361
        assert(i);
639✔
1362

1363
        r = get_gid_by_name(c, i->name, &i->gid);
639✔
1364
        if (r != -ENOENT) {
639✔
1365
                if (r < 0)
62✔
1366
                        return r;
1367
                log_debug("Group %s already exists.", i->name);
62✔
1368
                i->gid_set = true;
62✔
1369
                return 0;
62✔
1370
        }
1371

1372
        /* Try to use the suggested numeric GID */
1373
        if (i->gid_set) {
577✔
1374
                r = gid_is_ok(c, i->gid, i->name, false);
394✔
1375
                if (r < 0)
394✔
1376
                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1377
                if (i->id_set_strict) {
394✔
1378
                        /* If we require the GID to already exist we can return here:
1379
                         * r > 0: means the GID does not exist -> fail
1380
                         * r == 0: means the GID exists -> nothing more to do.
1381
                         */
1382
                        if (r > 0)
61✔
1383
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1✔
1384
                                                       "Failed to create %s: please create GID " GID_FMT,
1385
                                                       i->name, i->gid);
1386
                        if (r == 0)
60✔
1387
                                return 0;
1388
                }
1389
                if (r == 0) {
333✔
1390
                        log_info("Suggested group ID " GID_FMT " for %s already used.", i->gid, i->name);
×
1391
                        i->gid_set = false;
×
1392
                }
1393
        }
1394

1395
        /* Try to reuse the numeric uid, if there's one */
1396
        if (!i->gid_set && i->uid_set) {
516✔
1397
                r = gid_is_ok(c, (gid_t) i->uid, i->name, true);
158✔
1398
                if (r < 0)
158✔
1399
                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1400
                if (r > 0) {
158✔
1401
                        i->gid = (gid_t) i->uid;
153✔
1402
                        i->gid_set = true;
153✔
1403
                }
1404
        }
1405

1406
        /* If that didn't work, try to read it from the specified path */
1407
        if (!i->gid_set) {
516✔
1408
                gid_t candidate;
30✔
1409

1410
                if (read_id_from_file(i, NULL, &candidate) > 0) {
30✔
1411

1412
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
1413
                                log_debug("Group ID " GID_FMT " of file not suitable for %s.", candidate, i->name);
×
1414
                        else {
1415
                                r = gid_is_ok(c, candidate, i->name, true);
×
1416
                                if (r < 0)
×
1417
                                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1418
                                else if (r > 0) {
×
1419
                                        i->gid = candidate;
×
1420
                                        i->gid_set = true;
×
1421
                                } else
1422
                                        log_debug("Group ID " GID_FMT " of file for %s already used.", candidate, i->name);
30✔
1423
                        }
1424
                }
1425
        }
1426

1427
        /* And if that didn't work either, let's try to find a free one */
1428
        if (!i->gid_set) {
516✔
1429
                maybe_emit_login_defs_warning(c);
30✔
1430

1431
                for (;;) {
168✔
1432
                        /* We look for new GIDs in the UID pool! */
1433
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
168✔
1434
                        if (r < 0)
168✔
1435
                                return log_error_errno(r, "No free group ID available for %s.", i->name);
×
1436

1437
                        r = gid_is_ok(c, c->search_uid, i->name, true);
168✔
1438
                        if (r < 0)
168✔
1439
                                return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1440
                        else if (r > 0)
168✔
1441
                                break;
1442
                }
1443

1444
                i->gid_set = true;
30✔
1445
                i->gid = c->search_uid;
30✔
1446
        }
1447

1448
        r = ordered_hashmap_ensure_put(&c->todo_gids, NULL, GID_TO_PTR(i->gid), i);
516✔
1449
        if (r == -EEXIST)
516✔
1450
                return log_error_errno(r, "Requested group %s with GID "GID_FMT " to be created is duplicated or conflicts with another user.", i->name, i->gid);
×
1451
        if (r == -ENOMEM)
516✔
1452
                return log_oom();
×
1453
        if (r < 0)
516✔
1454
                return log_error_errno(r, "Failed to store group %s with GID " GID_FMT " to be created: %m", i->name, i->gid);
×
1455

1456
        i->todo_group = true;
516✔
1457
        log_info("Creating group '%s' with GID " GID_FMT ".", i->name, i->gid);
516✔
1458

1459
        return 0;
1460
}
1461

1462
static int process_item(Context *c, Item *i) {
675✔
1463
        int r;
675✔
1464

1465
        assert(c);
675✔
1466
        assert(i);
675✔
1467

1468
        switch (i->type) {
675✔
1469

1470
        case ADD_USER: {
299✔
1471
                Item *j = NULL;
299✔
1472

1473
                if (!i->gid_set) {
299✔
1474
                        j = ordered_hashmap_get(c->groups, i->group_name ?: i->name);
235✔
1475

1476
                        /* If that's not a match, also check if the group name
1477
                         * matches a user name in the queue. */
1478
                        if (!j && i->group_name)
235✔
1479
                                j = ordered_hashmap_get(c->users, i->group_name);
11✔
1480
                }
1481

1482
                if (j && j->todo_group) {
235✔
1483
                        /* When a group with the target name is already in queue,
1484
                         * use the information about the group and do not create
1485
                         * duplicated group entry. */
1486
                        i->gid_set = j->gid_set;
30✔
1487
                        i->gid = j->gid;
30✔
1488
                        i->id_set_strict = true;
30✔
1489
                } else if (i->group_name) {
269✔
1490
                        /* When a group name was given instead of a GID and it's
1491
                         * not in queue, then it must already exist. */
1492
                        r = get_gid_by_name(c, i->group_name, &i->gid);
6✔
1493
                        if (r < 0)
6✔
1494
                                return log_error_errno(r, "Group %s not found.", i->group_name);
1✔
1495
                        i->gid_set = true;
5✔
1496
                        i->id_set_strict = true;
5✔
1497
                } else {
1498
                        r = add_group(c, i);
263✔
1499
                        if (r < 0)
263✔
1500
                                return r;
1501
                }
1502

1503
                return add_user(c, i);
297✔
1504
        }
1505

1506
        case ADD_GROUP:
376✔
1507
                return add_group(c, i);
376✔
1508

1509
        default:
×
1510
                assert_not_reached();
×
1511
        }
1512
}
1513

1514
static Item* item_free(Item *i) {
677✔
1515
        if (!i)
677✔
1516
                return NULL;
1517

1518
        free(i->name);
677✔
1519
        free(i->group_name);
677✔
1520
        free(i->uid_path);
677✔
1521
        free(i->gid_path);
677✔
1522
        free(i->description);
677✔
1523
        free(i->home);
677✔
1524
        free(i->shell);
677✔
1525
        free(i->filename);
677✔
1526
        return mfree(i);
677✔
1527
}
1528

1529
DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1,364✔
1530
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
675✔
1531

1532
static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
677✔
1533
        assert(name);
677✔
1534
        assert(!!filename == (line > 0));
677✔
1535

1536
        _cleanup_(item_freep) Item *new = new(Item, 1);
1,354✔
1537
        if (!new)
677✔
1538
                return NULL;
1539

1540
        *new = (Item) {
677✔
1541
                .type = type,
1542
                .line = line,
1543
        };
1544

1545
        if (free_and_strdup(&new->name, name) < 0 ||
1,354✔
1546
            free_and_strdup(&new->filename, filename) < 0)
677✔
1547
                return NULL;
×
1548

1549
        return TAKE_PTR(new);
677✔
1550
}
1551

1552
static int add_implicit(Context *c) {
113✔
1553
        char *g, **l;
113✔
1554
        int r;
113✔
1555

1556
        assert(c);
113✔
1557

1558
        /* Implicitly create additional users and groups, if they were listed in "m" lines */
1559
        ORDERED_HASHMAP_FOREACH_KEY(l, g, c->members) {
236✔
1560
                STRV_FOREACH(m, l)
20✔
1561
                        if (!ordered_hashmap_get(c->users, *m)) {
10✔
1562
                                _cleanup_(item_freep) Item *j =
×
1563
                                        item_new(ADD_USER, *m, /* filename= */ NULL, /* line= */ 0);
5✔
1564
                                if (!j)
5✔
1565
                                        return log_oom();
×
1566

1567
                                r = ordered_hashmap_ensure_put(&c->users, &item_hash_ops, j->name, j);
5✔
1568
                                if (r == -ENOMEM)
5✔
1569
                                        return log_oom();
×
1570
                                if (r < 0)
5✔
1571
                                        return log_error_errno(r, "Failed to add implicit user '%s': %m", j->name);
×
1572

1573
                                log_debug("Adding implicit user '%s' due to m line", j->name);
5✔
1574
                                TAKE_PTR(j);
5✔
1575
                        }
1576

1577
                if (!(ordered_hashmap_get(c->users, g) ||
10✔
1578
                      ordered_hashmap_get(c->groups, g))) {
2✔
1579
                        _cleanup_(item_freep) Item *j =
×
1580
                                item_new(ADD_GROUP, g, /* filename= */ NULL, /* line= */ 0);
×
1581
                        if (!j)
×
1582
                                return log_oom();
×
1583

1584
                        r = ordered_hashmap_ensure_put(&c->groups, &item_hash_ops, j->name, j);
×
1585
                        if (r == -ENOMEM)
×
1586
                                return log_oom();
×
1587
                        if (r < 0)
×
1588
                                return log_error_errno(r, "Failed to add implicit group '%s': %m", j->name);
×
1589

1590
                        log_debug("Adding implicit group '%s' due to m line", j->name);
×
1591
                        TAKE_PTR(j);
×
1592
                }
1593
        }
1594

1595
        return 0;
113✔
1596
}
1597

1598
static int item_equivalent(Item *a, Item *b) {
1✔
1599
        int r;
1✔
1600

1601
        assert(a);
1✔
1602
        assert(b);
1✔
1603

1604
        if (a->type != b->type) {
1✔
1605
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1606
                           "Item not equivalent because types differ");
1607
                return false;
×
1608
        }
1609

1610
        if (!streq_ptr(a->name, b->name)) {
1✔
1611
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1612
                           "Item not equivalent because names differ ('%s' vs. '%s')",
1613
                           a->name, b->name);
1614
                return false;
×
1615
        }
1616

1617
        /* Paths were simplified previously, so we can use streq. */
1618
        if (!streq_ptr(a->uid_path, b->uid_path)) {
1✔
1619
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1620
                           "Item not equivalent because UID paths differ (%s vs. %s)",
1621
                           a->uid_path ?: "(unset)", b->uid_path ?: "(unset)");
1622
                return false;
×
1623
        }
1624

1625
        if (!streq_ptr(a->gid_path, b->gid_path)) {
1✔
1626
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1627
                           "Item not equivalent because GID paths differ (%s vs. %s)",
1628
                           a->gid_path ?: "(unset)", b->gid_path ?: "(unset)");
1629
                return false;
×
1630
        }
1631

1632
        if (!streq_ptr(a->description, b->description))  {
1✔
1633
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1634
                           "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1635
                           strempty(a->description), strempty(b->description));
1636
                return false;
×
1637
        }
1638

1639
        if ((a->uid_set != b->uid_set) ||
1✔
1640
            (a->uid_set && a->uid != b->uid)) {
×
1641
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1642
                           "Item not equivalent because UIDs differ (%s vs. %s)",
1643
                           a->uid_set ? FORMAT_UID(a->uid) : "(unset)",
1644
                           b->uid_set ? FORMAT_UID(b->uid) : "(unset)");
1645
                return false;
×
1646
        }
1647

1648
        if ((a->gid_set != b->gid_set) ||
1✔
1649
            (a->gid_set && a->gid != b->gid)) {
1✔
1650
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1651
                           "Item not equivalent because GIDs differ (%s vs. %s)",
1652
                           a->gid_set ? FORMAT_GID(a->gid) : "(unset)",
1653
                           b->gid_set ? FORMAT_GID(b->gid) : "(unset)");
1654
                return false;
×
1655
        }
1656

1657
        if (!streq_ptr(a->home, b->home)) {
1✔
1658
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1659
                           "Item not equivalent because home directories differ ('%s' vs. '%s')",
1660
                           strempty(a->description), strempty(b->description));
1661
                return false;
×
1662
        }
1663

1664
        /* Check if the two paths refer to the same file.
1665
         * If the paths are equal (after normalization), it's obviously the same file.
1666
         * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1667
         * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1668
         * /usr/sbin/nologin).
1669
         * If we can't resolve something, treat different paths as different. */
1670

1671
        const char *a_shell = pick_shell(a),
1✔
1672
                   *b_shell = pick_shell(b);
1✔
1673
        if (!path_equal(a_shell, b_shell) &&
1✔
1674
            !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
×
1675
                _cleanup_free_ char *pa = NULL, *pb = NULL;
×
1676

1677
                r = chase(a_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pa, NULL);
×
1678
                if (r < 0) {
×
1679
                        log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
×
1680
                                       r, "Failed to look up path '%s%s%s': %m",
1681
                                       strempty(arg_root), arg_root ? "/" : "", a_shell);
1682
                        return ERRNO_IS_RESOURCE(r) ? r : false;
×
1683
                }
1684

1685
                r = chase(b_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pb, NULL);
×
1686
                if (r < 0) {
×
1687
                        log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
×
1688
                                       r, "Failed to look up path '%s%s%s': %m",
1689
                                       strempty(arg_root), arg_root ? "/" : "", b_shell);
1690
                        return ERRNO_IS_RESOURCE(r) ? r : false;
×
1691
                }
1692

1693
                if (!path_equal(pa, pb)) {
×
1694
                        log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1695
                                   "Item not equivalent because shells differ ('%s' vs. '%s')",
1696
                                   pa, pb);
1697
                        return false;
×
1698
                }
1699
        }
1700

1701
        return true;
1702
}
1703

1704
static int parse_line(
682✔
1705
                const char *fname,
1706
                unsigned line,
1707
                const char *buffer,
1708
                bool *invalid_config,
1709
                void *context) {
1710

1711
        Context *c = ASSERT_PTR(context);
682✔
1712
        _cleanup_free_ char *action = NULL,
1,364✔
1713
                *name = NULL, *resolved_name = NULL,
×
1714
                *id = NULL, *resolved_id = NULL,
×
1715
                *description = NULL, *resolved_description = NULL,
×
1716
                *home = NULL, *resolved_home = NULL,
×
1717
                *shell = NULL, *resolved_shell = NULL;
682✔
1718
        _cleanup_(item_freep) Item *i = NULL;
682✔
1719
        Item *existing;
682✔
1720
        OrderedHashmap *h;
682✔
1721
        int r;
682✔
1722
        const char *p;
682✔
1723

1724
        assert(fname);
682✔
1725
        assert(line >= 1);
682✔
1726
        assert(buffer);
682✔
1727
        assert(!invalid_config); /* We don't support invalid_config yet. */
682✔
1728

1729
        /* Parse columns */
1730
        p = buffer;
682✔
1731
        r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
682✔
1732
                               &action, &name, &id, &description, &home, &shell);
1733
        if (r < 0)
682✔
1734
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Syntax error.");
×
1735
        if (r < 2)
682✔
1736
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1737
                                  "Missing action and name columns.");
1738
        if (!isempty(p))
682✔
1739
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1740
                                  "Trailing garbage.");
1741

1742
        if (isempty(action))
682✔
1743
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1744
                                  "Empty command specification.");
1745

1746
        bool locked = false;
1747
        for (int pos = 1; action[pos]; pos++)
694✔
1748
                if (action[pos] == '!' && !locked)
12✔
1749
                        locked = true;
12✔
1750
                else
1751
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1752
                                          "Unknown modifiers in command '%s'.", action);
1753

1754
        if (!IN_SET(action[0], ADD_USER, ADD_GROUP, ADD_MEMBER, ADD_RANGE))
682✔
1755
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1756
                                  "Unknown command type '%c'.", action[0]);
1757

1758
        /* Verify name */
1759
        if (empty_or_dash(name))
682✔
1760
                name = mfree(name);
×
1761

1762
        if (name) {
682✔
1763
                r = specifier_printf(name, NAME_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_name);
682✔
1764
                if (r < 0)
682✔
1765
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", name);
×
1766

1767
                if (!valid_user_group_name(resolved_name, 0))
682✔
1768
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1769
                                          "'%s' is not a valid user or group name.", resolved_name);
1770
        }
1771

1772
        /* Verify id */
1773
        if (empty_or_dash(id))
682✔
1774
                id = mfree(id);
55✔
1775

1776
        if (id) {
682✔
1777
                r = specifier_printf(id, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_id);
627✔
1778
                if (r < 0)
627✔
1779
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1780
                                          "Failed to replace specifiers in '%s': %m", name);
1781
        }
1782

1783
        /* Verify description */
1784
        if (empty_or_dash(description))
682✔
1785
                description = mfree(description);
631✔
1786

1787
        if (description) {
682✔
1788
                r = specifier_printf(description, LONG_LINE_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_description);
51✔
1789
                if (r < 0)
51✔
1790
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1791
                                          "Failed to replace specifiers in '%s': %m", description);
1792

1793
                if (!valid_gecos(resolved_description))
51✔
1794
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1795
                                          "'%s' is not a valid GECOS field.", resolved_description);
1796
        }
1797

1798
        /* Verify home */
1799
        if (empty_or_dash(home))
682✔
1800
                home = mfree(home);
542✔
1801

1802
        if (home) {
682✔
1803
                r = specifier_printf(home, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_home);
140✔
1804
                if (r < 0)
140✔
1805
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1806
                                          "Failed to replace specifiers in '%s': %m", home);
1807

1808
                path_simplify(resolved_home);
140✔
1809

1810
                if (!valid_home(resolved_home))
140✔
1811
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1812
                                          "'%s' is not a valid home directory field.", resolved_home);
1813
        }
1814

1815
        /* Verify shell */
1816
        if (empty_or_dash(shell))
682✔
1817
                shell = mfree(shell);
661✔
1818

1819
        if (shell) {
682✔
1820
                r = specifier_printf(shell, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_shell);
21✔
1821
                if (r < 0)
21✔
1822
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1823
                                          "Failed to replace specifiers in '%s': %m", shell);
1824

1825
                path_simplify(resolved_shell);
21✔
1826

1827
                if (!valid_shell(resolved_shell))
21✔
1828
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1829
                                          "'%s' is not a valid login shell field.", resolved_shell);
1830
        }
1831

1832
        switch (action[0]) {
682✔
1833

1834
        case ADD_RANGE:
×
1835
                if (locked)
×
1836
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1837
                                          "Flag '!' not permitted on lines of type 'r'.");
1838

1839
                if (resolved_name)
×
1840
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1841
                                          "Lines of type 'r' don't take a name field.");
1842

1843
                if (!resolved_id)
×
1844
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1845
                                          "Lines of type 'r' require an ID range in the third field.");
1846

1847
                if (description || home || shell)
×
1848
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1849
                                          "Lines of type '%c' don't take a %s field.",
1850
                                          action[0],
1851
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1852

1853
                r = uid_range_add_str(&c->uid_range, resolved_id);
×
1854
                if (r < 0)
×
1855
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1856
                                          "Invalid UID range %s.", resolved_id);
1857

1858
                return 0;
1859

1860
        case ADD_MEMBER: {
10✔
1861
                /* Try to extend an existing member or group item */
1862
                if (!name)
10✔
1863
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1864
                                          "Lines of type 'm' require a user name in the second field.");
1865

1866
                if (locked)
10✔
1867
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1868
                                          "Flag '!' not permitted on lines of type 'm'.");
1869

1870
                if (!resolved_id)
10✔
1871
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1872
                                          "Lines of type 'm' require a group name in the third field.");
1873

1874
                if (!valid_user_group_name(resolved_id, 0))
10✔
1875
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1876
                                               "'%s' is not a valid user or group name.", resolved_id);
1877

1878
                if (description || home || shell)
10✔
1879
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1880
                                          "Lines of type '%c' don't take a %s field.",
1881
                                          action[0],
1882
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1883

1884
                r = string_strv_ordered_hashmap_put(&c->members, resolved_id, resolved_name);
10✔
1885
                if (r < 0)
10✔
1886
                        return log_error_errno(r, "Failed to store mapping for %s: %m", resolved_id);
×
1887

1888
                return 0;
1889
        }
1890

1891
        case ADD_USER:
295✔
1892
                if (!name)
295✔
1893
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1894
                                          "Lines of type 'u' require a user name in the second field.");
1895

1896
                r = ordered_hashmap_ensure_allocated(&c->users, &item_hash_ops);
295✔
1897
                if (r < 0)
295✔
1898
                        return log_oom();
×
1899

1900
                i = item_new(ADD_USER, resolved_name, fname, line);
295✔
1901
                if (!i)
295✔
1902
                        return log_oom();
×
1903

1904
                if (resolved_id) {
295✔
1905
                        if (path_is_absolute(resolved_id))
266✔
1906
                                i->uid_path = path_simplify(TAKE_PTR(resolved_id));
×
1907
                        else {
1908
                                _cleanup_free_ char *uid = NULL, *gid = NULL;
266✔
1909
                                if (split_pair(resolved_id, ":", &uid, &gid) == 0) {
266✔
1910
                                        r = parse_gid(gid, &i->gid);
90✔
1911
                                        if (r < 0) {
90✔
1912
                                                if (valid_user_group_name(gid, 0))
26✔
1913
                                                        i->group_name = TAKE_PTR(gid);
26✔
1914
                                                else
1915
                                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1916
                                                                          "Failed to parse GID: '%s': %m", id);
1917
                                        } else {
1918
                                                i->gid_set = true;
64✔
1919
                                                i->id_set_strict = true;
64✔
1920
                                        }
1921
                                        free_and_replace(resolved_id, uid);
90✔
1922
                                }
1923
                                if (!streq(resolved_id, "-")) {
266✔
1924
                                        r = parse_uid(resolved_id, &i->uid);
251✔
1925
                                        if (r < 0)
251✔
1926
                                                return log_syntax(NULL, LOG_ERR, fname, line, r,
1✔
1927
                                                                  "Failed to parse UID: '%s': %m", id);
1928
                                        i->uid_set = true;
250✔
1929
                                }
1930
                        }
1931
                }
1932

1933
                i->description = TAKE_PTR(resolved_description);
294✔
1934
                i->home = TAKE_PTR(resolved_home);
294✔
1935
                i->shell = TAKE_PTR(resolved_shell);
294✔
1936
                i->locked = locked;
294✔
1937

1938
                h = c->users;
294✔
1939
                break;
294✔
1940

1941
        case ADD_GROUP:
377✔
1942
                if (!name)
377✔
1943
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1944
                                          "Lines of type 'g' require a user name in the second field.");
1945

1946
                if (locked)
377✔
1947
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1948
                                          "Flag '!' not permitted on lines of type 'g'.");
1949

1950
                if (description || home || shell)
377✔
1951
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1952
                                          "Lines of type '%c' don't take a %s field.",
1953
                                          action[0],
1954
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1955

1956
                r = ordered_hashmap_ensure_allocated(&c->groups, &item_hash_ops);
377✔
1957
                if (r < 0)
377✔
1958
                        return log_oom();
×
1959

1960
                i = item_new(ADD_GROUP, resolved_name, fname, line);
377✔
1961
                if (!i)
377✔
1962
                        return log_oom();
×
1963

1964
                if (resolved_id) {
377✔
1965
                        if (path_is_absolute(resolved_id))
351✔
1966
                                i->gid_path = path_simplify(TAKE_PTR(resolved_id));
×
1967
                        else {
1968
                                r = parse_gid(resolved_id, &i->gid);
351✔
1969
                                if (r < 0)
351✔
1970
                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1971
                                                          "Failed to parse GID: '%s': %m", id);
1972

1973
                                i->gid_set = true;
351✔
1974
                        }
1975
                }
1976

1977
                h = c->groups;
377✔
1978
                break;
377✔
1979

1980
        default:
×
1981
                assert_not_reached();
×
1982
        }
1983

1984
        existing = ordered_hashmap_get(h, i->name);
671✔
1985
        if (existing) {
671✔
1986
                /* Two functionally-equivalent items are fine */
1987
                r = item_equivalent(i, existing);
1✔
1988
                if (r < 0)
1✔
1989
                        return r;
1990
                if (r == 0) {
1✔
1991
                        if (existing->filename)
×
1992
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
1993
                                           "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
1994
                                           item_type_to_string(i->type),
1995
                                           i->name,
1996
                                           existing->filename, existing->line);
1997
                        else
1998
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
1999
                                           "Conflict with earlier configuration for %s '%s', ignoring line.",
2000
                                           item_type_to_string(i->type),
2001
                                           i->name);
2002
                }
2003

2004
                return 0;
1✔
2005
        }
2006

2007
        r = ordered_hashmap_put(h, i->name, i);
670✔
2008
        if (r < 0)
670✔
2009
                return log_oom();
×
2010

2011
        i = NULL;
670✔
2012
        return 0;
670✔
2013
}
2014

2015
static int read_config_file(Context *c, const char *fn, bool ignore_enoent) {
132✔
2016
        return conf_file_read(
396✔
2017
                        arg_root,
2018
                        (const char**) CONF_PATHS_STRV("sysusers.d"),
132✔
2019
                        ASSERT_PTR(fn),
132✔
2020
                        parse_line,
2021
                        ASSERT_PTR(c),
132✔
2022
                        ignore_enoent,
2023
                        /* invalid_config= */ NULL);
2024
}
2025

2026
static int cat_config(void) {
×
2027
        _cleanup_strv_free_ char **files = NULL;
×
2028
        int r;
×
2029

2030
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
×
2031
        if (r < 0)
×
2032
                return r;
2033

2034
        pager_open(arg_pager_flags);
×
2035

2036
        return cat_files(NULL, files, arg_cat_flags);
×
2037
}
2038

2039
static int help(void) {
×
2040
        _cleanup_free_ char *link = NULL;
×
2041
        int r;
×
2042

2043
        r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
×
2044
        if (r < 0)
×
2045
                return log_oom();
×
2046

2047
        printf("%1$s [OPTIONS...] [CONFIGURATION FILE...]\n"
×
2048
               "\n%2$sCreates system user and group accounts.%4$s\n"
2049
               "\n%3$sCommands:%4$s\n"
2050
               "     --cat-config           Show configuration files\n"
2051
               "     --tldr                 Show non-comment parts of configuration\n"
2052
               "  -h --help                 Show this help\n"
2053
               "     --version              Show package version\n"
2054
               "\n%3$sOptions:%4$s\n"
2055
               "     --root=PATH            Operate on an alternate filesystem root\n"
2056
               "     --image=PATH           Operate on disk image as filesystem root\n"
2057
               "     --image-policy=POLICY  Specify disk image dissection policy\n"
2058
               "     --replace=PATH         Treat arguments as replacement for PATH\n"
2059
               "     --dry-run              Just print what would be done\n"
2060
               "     --inline               Treat arguments as configuration lines\n"
2061
               "     --no-pager             Do not pipe output into a pager\n"
2062
               "\nSee the %5$s for details.\n",
2063
               program_invocation_short_name,
2064
               ansi_highlight(),
2065
               ansi_underline(),
2066
               ansi_normal(),
2067
               link);
2068

2069
        return 0;
2070
}
2071

2072
static int parse_argv(int argc, char *argv[]) {
113✔
2073

2074
        enum {
113✔
2075
                ARG_VERSION = 0x100,
2076
                ARG_CAT_CONFIG,
2077
                ARG_TLDR,
2078
                ARG_ROOT,
2079
                ARG_IMAGE,
2080
                ARG_IMAGE_POLICY,
2081
                ARG_REPLACE,
2082
                ARG_DRY_RUN,
2083
                ARG_INLINE,
2084
                ARG_NO_PAGER,
2085
        };
2086

2087
        static const struct option options[] = {
113✔
2088
                { "help",         no_argument,       NULL, 'h'              },
2089
                { "version",      no_argument,       NULL, ARG_VERSION      },
2090
                { "cat-config",   no_argument,       NULL, ARG_CAT_CONFIG   },
2091
                { "tldr",         no_argument,       NULL, ARG_TLDR         },
2092
                { "root",         required_argument, NULL, ARG_ROOT         },
2093
                { "image",        required_argument, NULL, ARG_IMAGE        },
2094
                { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
2095
                { "replace",      required_argument, NULL, ARG_REPLACE      },
2096
                { "dry-run",      no_argument,       NULL, ARG_DRY_RUN      },
2097
                { "inline",       no_argument,       NULL, ARG_INLINE       },
2098
                { "no-pager",     no_argument,       NULL, ARG_NO_PAGER     },
2099
                {}
2100
        };
2101

2102
        int c, r;
113✔
2103

2104
        assert(argc >= 0);
113✔
2105
        assert(argv);
113✔
2106

2107
        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
260✔
2108

2109
                switch (c) {
147✔
2110

2111
                case 'h':
×
2112
                        return help();
×
2113

2114
                case ARG_VERSION:
×
2115
                        return version();
×
2116

2117
                case ARG_CAT_CONFIG:
×
2118
                        arg_cat_flags = CAT_CONFIG_ON;
×
2119
                        break;
×
2120

2121
                case ARG_TLDR:
×
2122
                        arg_cat_flags = CAT_TLDR;
×
2123
                        break;
×
2124

2125
                case ARG_ROOT:
108✔
2126
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
108✔
2127
                        if (r < 0)
108✔
2128
                                return r;
2129
                        break;
2130

2131
                case ARG_IMAGE:
×
2132
#ifdef STANDALONE
2133
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2134
                                               "This systemd-sysusers version is compiled without support for --image=.");
2135
#else
2136
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
2137
                        if (r < 0)
×
2138
                                return r;
2139
                        break;
2140
#endif
2141

2142
                case ARG_IMAGE_POLICY:
×
2143
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
2144
                        if (r < 0)
×
2145
                                return r;
2146
                        break;
2147

2148
                case ARG_REPLACE:
35✔
2149
                        if (!path_is_absolute(optarg))
35✔
2150
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2151
                                                       "The argument to --replace= must be an absolute path.");
2152
                        if (!endswith(optarg, ".conf"))
35✔
2153
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2154
                                                       "The argument to --replace= must have the extension '.conf'.");
2155

2156
                        arg_replace = optarg;
35✔
2157
                        break;
35✔
2158

2159
                case ARG_DRY_RUN:
×
2160
                        arg_dry_run = true;
×
2161
                        break;
×
2162

2163
                case ARG_INLINE:
4✔
2164
                        arg_inline = true;
4✔
2165
                        break;
4✔
2166

2167
                case ARG_NO_PAGER:
×
2168
                        arg_pager_flags |= PAGER_DISABLE;
×
2169
                        break;
×
2170

2171
                case '?':
2172
                        return -EINVAL;
2173

2174
                default:
×
2175
                        assert_not_reached();
×
2176
                }
2177

2178
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
113✔
2179
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2180
                                       "Option --replace= is not supported with --cat-config/--tldr.");
2181

2182
        if (arg_replace && optind >= argc)
113✔
2183
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2184
                                       "When --replace= is given, some configuration items must be specified.");
2185

2186
        if (arg_image && arg_root)
113✔
2187
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2188
                                       "Use either --root= or --image=, the combination of both is not supported.");
2189

2190
        return 1;
2191
}
2192

2193
static int parse_arguments(Context *c, char **args) {
41✔
2194
        unsigned pos = 1;
41✔
2195
        int r;
41✔
2196

2197
        assert(c);
41✔
2198

2199
        STRV_FOREACH(arg, args) {
85✔
2200
                if (arg_inline)
44✔
2201
                        /* Use (argument):n, where n==1 for the first positional arg */
2202
                        r = parse_line("(argument)", pos, *arg, /* invalid_config= */ NULL, c);
7✔
2203
                else
2204
                        r = read_config_file(c, *arg, /* ignore_enoent= */ false);
37✔
2205
                if (r < 0)
44✔
2206
                        return r;
2207

2208
                pos++;
44✔
2209
        }
2210

2211
        return 0;
2212
}
2213

2214
static int read_config_files(Context *c, char **args) {
90✔
2215
        _cleanup_strv_free_ char **files = NULL;
×
2216
        _cleanup_free_ char *p = NULL;
90✔
2217
        int r;
90✔
2218

2219
        assert(c);
90✔
2220

2221
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
90✔
2222
        if (r < 0)
90✔
2223
                return r;
2224

2225
        STRV_FOREACH(f, files)
202✔
2226
                if (p && path_equal(*f, p)) {
112✔
2227
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
18✔
2228

2229
                        r = parse_arguments(c, args);
18✔
2230
                        if (r < 0)
18✔
2231
                                return r;
2232
                } else {
2233
                        log_debug("Reading config file \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
116✔
2234

2235
                        /* Just warn, ignore result otherwise */
2236
                        (void) read_config_file(c, *f, /* ignore_enoent= */ true);
94✔
2237
                }
2238

2239
        return 0;
2240
}
2241

2242
static int read_credential_lines(Context *c) {
113✔
2243
        _cleanup_free_ char *j = NULL;
113✔
2244
        const char *d;
113✔
2245
        int r;
113✔
2246

2247
        assert(c);
113✔
2248

2249
        r = get_credentials_dir(&d);
113✔
2250
        if (r == -ENXIO)
113✔
2251
                return 0;
2252
        if (r < 0)
1✔
2253
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
2254

2255
        j = path_join(d, "sysusers.extra");
1✔
2256
        if (!j)
1✔
2257
                return log_oom();
×
2258

2259
        (void) read_config_file(c, j, /* ignore_enoent= */ true);
1✔
2260
        return 0;
2261
}
2262

2263
static int run(int argc, char *argv[]) {
113✔
2264
#ifndef STANDALONE
2265
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
113✔
2266
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
×
2267
#endif
2268
        _cleanup_close_ int lock = -EBADF;
113✔
2269
        _cleanup_(context_done) Context c = {
113✔
2270
                .audit_fd = -EBADF,
2271
                .search_uid = UID_INVALID,
2272
        };
2273

2274
        Item *i;
113✔
2275
        int r;
113✔
2276

2277
        r = parse_argv(argc, argv);
113✔
2278
        if (r <= 0)
113✔
2279
                return r;
2280

2281
        log_setup();
113✔
2282

2283
        if (arg_cat_flags != CAT_CONFIG_OFF)
113✔
2284
                return cat_config();
×
2285

2286
        if (should_bypass("SYSTEMD_SYSUSERS"))
113✔
2287
                return 0;
2288

2289
        umask(0022);
113✔
2290

2291
        r = mac_init();
113✔
2292
        if (r < 0)
113✔
2293
                return r;
2294

2295
#ifndef STANDALONE
2296
        if (arg_image) {
113✔
2297
                assert(!arg_root);
×
2298

2299
                r = mount_image_privately_interactively(
×
2300
                                arg_image,
2301
                                arg_image_policy,
2302
                                DISSECT_IMAGE_GENERIC_ROOT |
2303
                                DISSECT_IMAGE_REQUIRE_ROOT |
2304
                                DISSECT_IMAGE_VALIDATE_OS |
2305
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
2306
                                DISSECT_IMAGE_FSCK |
2307
                                DISSECT_IMAGE_GROWFS |
2308
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
2309
                                &mounted_dir,
2310
                                /* ret_dir_fd= */ NULL,
2311
                                &loop_device);
2312
                if (r < 0)
×
2313
                        return r;
2314

2315
                arg_root = strdup(mounted_dir);
×
2316
                if (!arg_root)
×
2317
                        return log_oom();
×
2318
        }
2319
#else
2320
        assert(!arg_image);
2321
#endif
2322

2323
        /* Prepare to emit audit events, but only if we're operating on the host system. */
2324
        if (!arg_root)
113✔
2325
                c.audit_fd = open_audit_fd_or_warn();
5✔
2326

2327
        /* If command line arguments are specified along with --replace, read all configuration files and
2328
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2329
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
2330
         * read configuration and execute it. */
2331
        if (arg_replace || optind >= argc)
113✔
2332
                r = read_config_files(&c, argv + optind);
90✔
2333
        else
2334
                r = parse_arguments(&c, argv + optind);
23✔
2335
        if (r < 0)
113✔
2336
                return r;
2337

2338
        r = read_credential_lines(&c);
113✔
2339
        if (r < 0)
113✔
2340
                return r;
2341

2342
        /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our
2343
         * detection whether the names or UID/GID area already used otherwise doesn't get confused. After
2344
         * all, even though nss-systemd synthesizes these users/groups, they should still appear in
2345
         * /etc/passwd and /etc/group, as the synthesizing logic is merely supposed to be fallback for cases
2346
         * where we run with a completely unpopulated /etc. */
2347
        if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
113✔
2348
                return log_error_errno(errno, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
×
2349

2350
        if (!c.uid_range) {
113✔
2351
                /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2352
                r = read_login_defs(&c.login_defs, NULL, arg_root);
113✔
2353
                if (r < 0)
113✔
2354
                        return log_error_errno(r, "Failed to read %s%s: %m",
×
2355
                                               strempty(arg_root), "/etc/login.defs");
2356

2357
                c.login_defs_need_warning = true;
113✔
2358

2359
                /* We pick a range that very conservative: we look at compiled-in maximum and the value in
2360
                 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
2361
                 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2362
                 * it's only used during allocation, so we use the configured value directly). */
2363
                uid_t begin = c.login_defs.system_alloc_uid_min,
113✔
2364
                      end = MIN3((uid_t) SYSTEM_UID_MAX, c.login_defs.system_uid_max, c.login_defs.system_gid_max);
113✔
2365
                if (begin < end) {
113✔
2366
                        r = uid_range_add(&c.uid_range, begin, end - begin + 1);
113✔
2367
                        if (r < 0)
113✔
2368
                                return log_oom();
×
2369
                }
2370
        }
2371

2372
        r = add_implicit(&c);
113✔
2373
        if (r < 0)
113✔
2374
                return r;
2375

2376
        if (!arg_dry_run) {
113✔
2377
                lock = take_etc_passwd_lock(arg_root);
113✔
2378
                if (lock < 0)
113✔
2379
                        return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
×
2380
        }
2381

2382
        r = load_user_database(&c);
113✔
2383
        if (r < 0)
113✔
2384
                return log_error_errno(r, "Failed to load user database: %m");
×
2385

2386
        r = load_group_database(&c);
113✔
2387
        if (r < 0)
113✔
2388
                return log_error_errno(r, "Failed to read group database: %m");
×
2389

2390
        ORDERED_HASHMAP_FOREACH(i, c.groups)
489✔
2391
                (void) process_item(&c, i);
376✔
2392

2393
        ORDERED_HASHMAP_FOREACH(i, c.users)
412✔
2394
                (void) process_item(&c, i);
299✔
2395

2396
        return write_files(&c);
113✔
2397
}
2398

2399
DEFINE_MAIN_FUNCTION(run);
226✔
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