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

systemd / systemd / 14872145375

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

push

github

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

Follow-up for c94f6ab1b

297286 of 411572 relevant lines covered (72.23%)

695615.99 hits per line

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

72.18
/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 "image-policy.h"
21
#include "libcrypt-util.h"
22
#include "main-func.h"
23
#include "memory-util.h"
24
#include "mount-util.h"
25
#include "pager.h"
26
#include "parse-argument.h"
27
#include "path-util.h"
28
#include "pretty-print.h"
29
#include "selinux-util.h"
30
#include "set.h"
31
#include "smack-util.h"
32
#include "specifier.h"
33
#include "stat-util.h"
34
#include "string-util.h"
35
#include "strv.h"
36
#include "sync-util.h"
37
#include "tmpfile-util-label.h"
38
#include "uid-classification.h"
39
#include "uid-range.h"
40
#include "user-util.h"
41
#include "utf8.h"
42
#include "verbs.h"
43

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

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

66
typedef struct Item {
67
        ItemType type;
68

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

77
        gid_t gid;
78
        uid_t uid;
79

80
        char *filename;
81
        unsigned line;
82

83
        bool gid_set;
84

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

90
        bool uid_set;
91

92
        bool locked;
93

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

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

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

111
typedef struct Context {
112
        int audit_fd;
113

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

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

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

124
        uid_t search_uid;
125
        UIDRange *uid_range;
126

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

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

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

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

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

147
        set_free(c->names);
113✔
148
        uid_range_free(c->uid_range);
113✔
149
}
113✔
150

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

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

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

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

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

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

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

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

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

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

221
        assert(c);
113✔
222

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

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

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

235
                /* Note that we use trivial_hash_ops_free here, so identical strings can exist in the set. */
236
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, 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 trivial_hash_ops_free here, so identical strings can exist in the set. */
278
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, n);
420✔
279
                if (r < 0)
420✔
280
                        return r;
281
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
420✔
282

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

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

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

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

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

316
                return -errno;
×
317
        }
318

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

385
                        added = true;
386
                }
387

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

391
                        strv_sort_uniq(l);
5✔
392

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

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

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

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

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

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

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

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

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

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

433
                        added = true;
434
                }
435

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

439
                        strv_sort_uniq(l);
5✔
440

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

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

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

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

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

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

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

477
        assert(c);
113✔
478

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

592
        return 0;
87✔
593
}
594

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

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

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

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

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

620
        assert(c);
113✔
621

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

739
        return 0;
87✔
740
}
741

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

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

755
        assert(c);
113✔
756

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

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

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

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

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

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

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

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

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

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

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

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

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

827
                group_changed = true;
516✔
828
        }
829

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

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

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

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

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

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

868
        assert(c);
113✔
869

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

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

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

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

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

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

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

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

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

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

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

927
                group_changed = true;
516✔
928
        }
929

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

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

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

947
        _cleanup_free_ char *passwd_path = path_join(arg_root, "/etc/passwd");
226✔
948
        if (!passwd_path)
113✔
949
                return log_oom();
×
950

951
        _cleanup_free_ char *shadow_path = path_join(arg_root, "/etc/shadow");
226✔
952
        if (!shadow_path)
113✔
953
                return log_oom();
×
954

955
        _cleanup_free_ char *group_path = path_join(arg_root, "/etc/group");
226✔
956
        if (!group_path)
113✔
957
                return log_oom();
×
958

959
        _cleanup_free_ char *gshadow_path = path_join(arg_root, "/etc/gshadow");
226✔
960
        if (!gshadow_path)
113✔
961
                return log_oom();
×
962

963
        assert(c);
113✔
964

965
        r = write_temporary_group(c, group_path, &group, &group_tmp);
113✔
966
        if (r < 0)
113✔
967
                return r;
968

969
        r = write_temporary_gshadow(c, gshadow_path, &gshadow, &gshadow_tmp);
113✔
970
        if (r < 0)
113✔
971
                return r;
972

973
        r = write_temporary_passwd(c, passwd_path, &passwd, &passwd_tmp);
113✔
974
        if (r < 0)
113✔
975
                return r;
976

977
        r = write_temporary_shadow(c, shadow_path, &shadow, &shadow_tmp);
113✔
978
        if (r < 0)
113✔
979
                return r;
980

981
        /* Make a backup of the old files */
982
        if (group) {
113✔
983
                r = make_backup("/etc/group", group_path);
87✔
984
                if (r < 0)
87✔
985
                        return log_error_errno(r, "Failed to backup %s: %m", group_path);
×
986
        }
987
        if (gshadow) {
113✔
988
                r = make_backup("/etc/gshadow", gshadow_path);
87✔
989
                if (r < 0)
87✔
990
                        return log_error_errno(r, "Failed to backup %s: %m", gshadow_path);
×
991
        }
992

993
        if (passwd) {
113✔
994
                r = make_backup("/etc/passwd", passwd_path);
87✔
995
                if (r < 0)
87✔
996
                        return log_error_errno(r, "Failed to backup %s: %m", passwd_path);
×
997
        }
998
        if (shadow) {
113✔
999
                r = make_backup("/etc/shadow", shadow_path);
87✔
1000
                if (r < 0)
87✔
1001
                        return log_error_errno(r, "Failed to backup %s: %m", shadow_path);
×
1002
        }
1003

1004
        /* And make the new files count */
1005
        if (group) {
113✔
1006
                r = rename_and_apply_smack_floor_label(group_tmp, group_path);
87✔
1007
                if (r < 0)
87✔
1008
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1009
                                               group_tmp, group_path);
1010
                group_tmp = mfree(group_tmp);
87✔
1011
        }
1012
        /* OK, we have written the group entries successfully */
1013
        log_audit_accounts(c, ADD_GROUP);
113✔
1014
        if (gshadow) {
113✔
1015
                r = rename_and_apply_smack_floor_label(gshadow_tmp, gshadow_path);
87✔
1016
                if (r < 0)
87✔
1017
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1018
                                               gshadow_tmp, gshadow_path);
1019

1020
                gshadow_tmp = mfree(gshadow_tmp);
87✔
1021
        }
1022

1023
        if (passwd) {
113✔
1024
                r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
87✔
1025
                if (r < 0)
87✔
1026
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1027
                                               passwd_tmp, passwd_path);
1028

1029
                passwd_tmp = mfree(passwd_tmp);
87✔
1030
        }
1031
        /* OK, we have written the user entries successfully */
1032
        log_audit_accounts(c, ADD_USER);
113✔
1033
        if (shadow) {
113✔
1034
                r = rename_and_apply_smack_floor_label(shadow_tmp, shadow_path);
87✔
1035
                if (r < 0)
87✔
1036
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1037
                                               shadow_tmp, shadow_path);
1038

1039
                shadow_tmp = mfree(shadow_tmp);
87✔
1040
        }
1041

1042
        return 0;
1043
}
1044

1045
static int uid_is_ok(
288✔
1046
                Context *c,
1047
                uid_t uid,
1048
                const char *name,
1049
                bool check_with_gid) {
1050

1051
        int r;
288✔
1052
        assert(c);
288✔
1053

1054
        /* Let's see if we already have assigned the UID a second time */
1055
        if (ordered_hashmap_get(c->todo_uids, UID_TO_PTR(uid)))
288✔
1056
                return 0;
1057

1058
        /* Try to avoid using uids that are already used by a group
1059
         * that doesn't have the same name as our new user. */
1060
        if (check_with_gid) {
283✔
1061
                Item *i;
203✔
1062

1063
                i = ordered_hashmap_get(c->todo_gids, GID_TO_PTR(uid));
203✔
1064
                if (i && !streq(i->name, name))
203✔
1065
                        return 0;
1066
        }
1067

1068
        /* Let's check the files directly */
1069
        if (hashmap_contains(c->database_by_uid, UID_TO_PTR(uid)))
273✔
1070
                return 0;
1071

1072
        if (check_with_gid) {
273✔
1073
                const char *n;
193✔
1074

1075
                n = hashmap_get(c->database_by_gid, GID_TO_PTR(uid));
193✔
1076
                if (n && !streq(n, name))
193✔
1077
                        return 0;
1078
        }
1079

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

1084
                r = getpwuid_malloc(uid, /* ret= */ NULL);
5✔
1085
                if (r >= 0)
5✔
1086
                        return 0;
1087
                if (r != -ESRCH)
5✔
1088
                        log_warning_errno(r, "Unexpected failure while looking up UID '" UID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
×
1089

1090
                if (check_with_gid) {
5✔
1091
                        r = getgrgid_malloc((gid_t) uid, &g);
5✔
1092
                        if (r >= 0) {
5✔
1093
                                if (!streq(g->gr_name, name))
×
1094
                                        return 0;
1095
                        } else if (r != -ESRCH)
5✔
1096
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", uid);
5✔
1097
                }
1098
        }
1099

1100
        return 1;
1101
}
1102

1103
static int root_stat(const char *p, struct stat *ret_st) {
×
1104
        return chase_and_stat(p, arg_root, CHASE_PREFIX_ROOT, /* ret_path= */ NULL, ret_st);
×
1105
}
1106

1107
static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
70✔
1108
        struct stat st;
70✔
1109
        bool found_uid = false, found_gid = false;
70✔
1110
        uid_t uid = 0;
70✔
1111
        gid_t gid = 0;
70✔
1112

1113
        assert(i);
70✔
1114

1115
        /* First, try to get the GID directly */
1116
        if (ret_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
70✔
1117
                gid = st.st_gid;
×
1118
                found_gid = true;
×
1119
        }
1120

1121
        /* Then, try to get the UID directly */
1122
        if ((ret_uid || (ret_gid && !found_gid))
70✔
1123
            && i->uid_path
70✔
1124
            && root_stat(i->uid_path, &st) >= 0) {
×
1125

1126
                uid = st.st_uid;
×
1127
                found_uid = true;
×
1128

1129
                /* If we need the gid, but had no success yet, also derive it from the UID path */
1130
                if (ret_gid && !found_gid) {
×
1131
                        gid = st.st_gid;
×
1132
                        found_gid = true;
×
1133
                }
1134
        }
1135

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

1139
                if (found_gid) {
×
1140
                        uid = (uid_t) gid;
1141
                        found_uid = true;
1142
                } else if (root_stat(i->gid_path, &st) >= 0) {
×
1143
                        uid = (uid_t) st.st_gid;
×
1144
                        found_uid = true;
×
1145
                }
1146
        }
1147

1148
        if (ret_uid) {
70✔
1149
                if (!found_uid)
40✔
1150
                        return 0;
70✔
1151

1152
                *ret_uid = uid;
×
1153
        }
1154

1155
        if (ret_gid) {
30✔
1156
                if (!found_gid)
30✔
1157
                        return 0;
1158

1159
                *ret_gid = gid;
×
1160
        }
1161

1162
        return 1;
1163
}
1164

1165
static int add_user(Context *c, Item *i) {
297✔
1166
        void *z;
297✔
1167
        int r;
297✔
1168

1169
        assert(c);
297✔
1170
        assert(i);
297✔
1171

1172
        /* Check the database directly */
1173
        z = hashmap_get(c->database_by_username, i->name);
297✔
1174
        if (z) {
297✔
1175
                log_debug("User %s already exists.", i->name);
29✔
1176
                i->uid = PTR_TO_UID(z);
29✔
1177
                i->uid_set = true;
29✔
1178
                return 0;
29✔
1179
        }
1180

1181
        if (!arg_root) {
268✔
1182
                _cleanup_free_ struct passwd *p = NULL;
5✔
1183

1184
                /* Also check NSS */
1185
                r = getpwnam_malloc(i->name, &p);
5✔
1186
                if (r >= 0) {
5✔
1187
                        log_debug("User %s already exists.", i->name);
×
1188
                        i->uid = p->pw_uid;
×
1189
                        i->uid_set = true;
×
1190

1191
                        r = free_and_strdup(&i->description, p->pw_gecos);
×
1192
                        if (r < 0)
×
1193
                                return log_oom();
×
1194

1195
                        return 0;
1196
                }
1197
                if (r != -ESRCH)
5✔
1198
                        log_warning_errno(r, "Unexpected failure while looking up user '%s' via NSS, assuming it doesn't exist: %m", i->name);
5✔
1199
        }
1200

1201
        /* Try to use the suggested numeric UID */
1202
        if (i->uid_set) {
268✔
1203
                r = uid_is_ok(c, i->uid, i->name, !i->id_set_strict);
233✔
1204
                if (r < 0)
233✔
1205
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1206
                if (r == 0) {
233✔
1207
                        log_info("Suggested user ID " UID_FMT " for %s already used.", i->uid, i->name);
5✔
1208
                        i->uid_set = false;
5✔
1209
                }
1210
        }
1211

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

1216
                if (read_id_from_file(i, &candidate, NULL) > 0) {
40✔
1217

1218
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
1219
                                log_debug("User ID " UID_FMT " of file not suitable for %s.", candidate, i->name);
×
1220
                        else {
1221
                                r = uid_is_ok(c, candidate, i->name, true);
×
1222
                                if (r < 0)
×
1223
                                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1224
                                else if (r > 0) {
×
1225
                                        i->uid = candidate;
×
1226
                                        i->uid_set = true;
×
1227
                                } else
1228
                                        log_debug("User ID " UID_FMT " of file for %s is already used.", candidate, i->name);
×
1229
                        }
1230
                }
1231
        }
1232

1233
        /* Otherwise, try to reuse the group ID */
1234
        if (!i->uid_set && i->gid_set) {
268✔
1235
                r = uid_is_ok(c, (uid_t) i->gid, i->name, true);
40✔
1236
                if (r < 0)
40✔
1237
                        return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1238
                if (r > 0) {
40✔
1239
                        i->uid = (uid_t) i->gid;
25✔
1240
                        i->uid_set = true;
25✔
1241
                }
1242
        }
1243

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

1248
                for (;;) {
15✔
1249
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
15✔
1250
                        if (r < 0)
15✔
1251
                                return log_error_errno(r, "No free user ID available for %s.", i->name);
×
1252

1253
                        r = uid_is_ok(c, c->search_uid, i->name, true);
15✔
1254
                        if (r < 0)
15✔
1255
                                return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
×
1256
                        else if (r > 0)
15✔
1257
                                break;
1258
                }
1259

1260
                i->uid_set = true;
15✔
1261
                i->uid = c->search_uid;
15✔
1262
        }
1263

1264
        r = ordered_hashmap_ensure_put(&c->todo_uids, NULL, UID_TO_PTR(i->uid), i);
268✔
1265
        if (r == -EEXIST)
268✔
1266
                return log_error_errno(r, "Requested user %s with UID " UID_FMT " and gid" GID_FMT " to be created is duplicated "
×
1267
                                       "or conflicts with another user.", i->name, i->uid, i->gid);
1268
        if (r == -ENOMEM)
268✔
1269
                return log_oom();
×
1270
        if (r < 0)
268✔
1271
                return log_error_errno(r, "Failed to store user %s with UID " UID_FMT " and GID " GID_FMT " to be created: %m",
×
1272
                                       i->name, i->uid, i->gid);
1273

1274
        i->todo_user = true;
268✔
1275
        log_info("Creating user '%s' (%s) with UID " UID_FMT " and GID " GID_FMT ".",
509✔
1276
                 i->name, strna(i->description), i->uid, i->gid);
1277

1278
        return 0;
1279
}
1280

1281
static int gid_is_ok(
720✔
1282
                Context *c,
1283
                gid_t gid,
1284
                const char *groupname,
1285
                bool check_with_uid) {
1286

1287
        Item *user;
720✔
1288
        char *username;
720✔
1289
        int r;
720✔
1290

1291
        assert(c);
720✔
1292
        assert(groupname);
720✔
1293

1294
        if (ordered_hashmap_get(c->todo_gids, GID_TO_PTR(gid)))
720✔
1295
                return 0;
1296

1297
        /* Avoid reusing gids that are already used by a different user */
1298
        if (check_with_uid) {
655✔
1299
                user = ordered_hashmap_get(c->todo_uids, UID_TO_PTR(gid));
321✔
1300
                if (user && !streq(user->name, groupname))
321✔
1301
                        return 0;
1302
        }
1303

1304
        if (hashmap_contains(c->database_by_gid, GID_TO_PTR(gid)))
655✔
1305
                return 0;
1306

1307
        if (check_with_uid) {
517✔
1308
                username = hashmap_get(c->database_by_uid, UID_TO_PTR(gid));
183✔
1309
                if (username && !streq(username, groupname))
183✔
1310
                        return 0;
1311
        }
1312

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

1320
                if (check_with_uid) {
5✔
1321
                        r = getpwuid_malloc(gid, /* ret= */ NULL);
5✔
1322
                        if (r >= 0)
5✔
1323
                                return 0;
1324
                        if (r != -ESRCH)
5✔
1325
                                log_warning_errno(r, "Unexpected failure while looking up GID '" GID_FMT "' via NSS, assuming it doesn't exist: %m", gid);
×
1326
                }
1327
        }
1328

1329
        return 1;
1330
}
1331

1332
static int get_gid_by_name(
645✔
1333
                Context *c,
1334
                const char *name,
1335
                gid_t *ret_gid) {
1336

1337
        void *z;
645✔
1338
        int r;
645✔
1339

1340
        assert(c);
645✔
1341
        assert(ret_gid);
645✔
1342

1343
        /* Check the database directly */
1344
        z = hashmap_get(c->database_by_groupname, name);
645✔
1345
        if (z) {
645✔
1346
                *ret_gid = PTR_TO_GID(z);
67✔
1347
                return 0;
67✔
1348
        }
1349

1350
        /* Also check NSS */
1351
        if (!arg_root) {
578✔
1352
                _cleanup_free_ struct group *g = NULL;
5✔
1353

1354
                r = getgrnam_malloc(name, &g);
5✔
1355
                if (r >= 0) {
5✔
1356
                        *ret_gid = g->gr_gid;
×
1357
                        return 0;
×
1358
                }
1359
                if (r != -ESRCH)
5✔
1360
                        log_warning_errno(r, "Unexpected failure while looking up group '%s' via NSS, assuming it doesn't exist: %m", name);
5✔
1361
        }
1362

1363
        return -ENOENT;
1364
}
1365

1366
static int add_group(Context *c, Item *i) {
639✔
1367
        int r;
639✔
1368

1369
        assert(c);
639✔
1370
        assert(i);
639✔
1371

1372
        r = get_gid_by_name(c, i->name, &i->gid);
639✔
1373
        if (r != -ENOENT) {
639✔
1374
                if (r < 0)
62✔
1375
                        return r;
1376
                log_debug("Group %s already exists.", i->name);
62✔
1377
                i->gid_set = true;
62✔
1378
                return 0;
62✔
1379
        }
1380

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

1404
        /* Try to reuse the numeric uid, if there's one */
1405
        if (!i->gid_set && i->uid_set) {
516✔
1406
                r = gid_is_ok(c, (gid_t) i->uid, i->name, true);
158✔
1407
                if (r < 0)
158✔
1408
                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1409
                if (r > 0) {
158✔
1410
                        i->gid = (gid_t) i->uid;
153✔
1411
                        i->gid_set = true;
153✔
1412
                }
1413
        }
1414

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

1419
                if (read_id_from_file(i, NULL, &candidate) > 0) {
30✔
1420

1421
                        if (candidate <= 0 || !uid_range_contains(c->uid_range, candidate))
×
1422
                                log_debug("Group ID " GID_FMT " of file not suitable for %s.", candidate, i->name);
×
1423
                        else {
1424
                                r = gid_is_ok(c, candidate, i->name, true);
×
1425
                                if (r < 0)
×
1426
                                        return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1427
                                else if (r > 0) {
×
1428
                                        i->gid = candidate;
×
1429
                                        i->gid_set = true;
×
1430
                                } else
1431
                                        log_debug("Group ID " GID_FMT " of file for %s already used.", candidate, i->name);
×
1432
                        }
1433
                }
1434
        }
1435

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

1440
                for (;;) {
168✔
1441
                        /* We look for new GIDs in the UID pool! */
1442
                        r = uid_range_next_lower(c->uid_range, &c->search_uid);
168✔
1443
                        if (r < 0)
168✔
1444
                                return log_error_errno(r, "No free group ID available for %s.", i->name);
×
1445

1446
                        r = gid_is_ok(c, c->search_uid, i->name, true);
168✔
1447
                        if (r < 0)
168✔
1448
                                return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
×
1449
                        else if (r > 0)
168✔
1450
                                break;
1451
                }
1452

1453
                i->gid_set = true;
30✔
1454
                i->gid = c->search_uid;
30✔
1455
        }
1456

1457
        r = ordered_hashmap_ensure_put(&c->todo_gids, NULL, GID_TO_PTR(i->gid), i);
516✔
1458
        if (r == -EEXIST)
516✔
1459
                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);
×
1460
        if (r == -ENOMEM)
516✔
1461
                return log_oom();
×
1462
        if (r < 0)
516✔
1463
                return log_error_errno(r, "Failed to store group %s with GID " GID_FMT " to be created: %m", i->name, i->gid);
×
1464

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

1468
        return 0;
1469
}
1470

1471
static int process_item(Context *c, Item *i) {
675✔
1472
        int r;
675✔
1473

1474
        assert(c);
675✔
1475
        assert(i);
675✔
1476

1477
        switch (i->type) {
675✔
1478

1479
        case ADD_USER: {
299✔
1480
                Item *j = NULL;
299✔
1481

1482
                if (!i->gid_set) {
299✔
1483
                        j = ordered_hashmap_get(c->groups, i->group_name ?: i->name);
235✔
1484

1485
                        /* If that's not a match, also check if the group name
1486
                         * matches a user name in the queue. */
1487
                        if (!j && i->group_name)
235✔
1488
                                j = ordered_hashmap_get(c->users, i->group_name);
11✔
1489
                }
1490

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

1512
                return add_user(c, i);
297✔
1513
        }
1514

1515
        case ADD_GROUP:
376✔
1516
                return add_group(c, i);
376✔
1517

1518
        default:
×
1519
                assert_not_reached();
×
1520
        }
1521
}
1522

1523
static Item* item_free(Item *i) {
677✔
1524
        if (!i)
677✔
1525
                return NULL;
1526

1527
        free(i->name);
677✔
1528
        free(i->group_name);
677✔
1529
        free(i->uid_path);
677✔
1530
        free(i->gid_path);
677✔
1531
        free(i->description);
677✔
1532
        free(i->home);
677✔
1533
        free(i->shell);
677✔
1534
        free(i->filename);
677✔
1535
        return mfree(i);
677✔
1536
}
1537

1538
DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1,364✔
1539
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
675✔
1540

1541
static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
677✔
1542
        assert(name);
677✔
1543
        assert(!!filename == (line > 0));
677✔
1544

1545
        _cleanup_(item_freep) Item *new = new(Item, 1);
1,354✔
1546
        if (!new)
677✔
1547
                return NULL;
1548

1549
        *new = (Item) {
677✔
1550
                .type = type,
1551
                .line = line,
1552
        };
1553

1554
        if (free_and_strdup(&new->name, name) < 0 ||
1,354✔
1555
            free_and_strdup(&new->filename, filename) < 0)
677✔
1556
                return NULL;
×
1557

1558
        return TAKE_PTR(new);
677✔
1559
}
1560

1561
static int add_implicit(Context *c) {
113✔
1562
        char *g, **l;
113✔
1563
        int r;
113✔
1564

1565
        assert(c);
113✔
1566

1567
        /* Implicitly create additional users and groups, if they were listed in "m" lines */
1568
        ORDERED_HASHMAP_FOREACH_KEY(l, g, c->members) {
236✔
1569
                STRV_FOREACH(m, l)
20✔
1570
                        if (!ordered_hashmap_get(c->users, *m)) {
10✔
1571
                                _cleanup_(item_freep) Item *j =
×
1572
                                        item_new(ADD_USER, *m, /* filename= */ NULL, /* line= */ 0);
5✔
1573
                                if (!j)
5✔
1574
                                        return log_oom();
×
1575

1576
                                r = ordered_hashmap_ensure_put(&c->users, &item_hash_ops, j->name, j);
5✔
1577
                                if (r == -ENOMEM)
5✔
1578
                                        return log_oom();
×
1579
                                if (r < 0)
5✔
1580
                                        return log_error_errno(r, "Failed to add implicit user '%s': %m", j->name);
×
1581

1582
                                log_debug("Adding implicit user '%s' due to m line", j->name);
5✔
1583
                                TAKE_PTR(j);
5✔
1584
                        }
1585

1586
                if (!(ordered_hashmap_get(c->users, g) ||
10✔
1587
                      ordered_hashmap_get(c->groups, g))) {
2✔
1588
                        _cleanup_(item_freep) Item *j =
×
1589
                                item_new(ADD_GROUP, g, /* filename= */ NULL, /* line= */ 0);
×
1590
                        if (!j)
×
1591
                                return log_oom();
×
1592

1593
                        r = ordered_hashmap_ensure_put(&c->groups, &item_hash_ops, j->name, j);
×
1594
                        if (r == -ENOMEM)
×
1595
                                return log_oom();
×
1596
                        if (r < 0)
×
1597
                                return log_error_errno(r, "Failed to add implicit group '%s': %m", j->name);
×
1598

1599
                        log_debug("Adding implicit group '%s' due to m line", j->name);
×
1600
                        TAKE_PTR(j);
×
1601
                }
1602
        }
1603

1604
        return 0;
113✔
1605
}
1606

1607
static int item_equivalent(Item *a, Item *b) {
1✔
1608
        int r;
1✔
1609

1610
        assert(a);
1✔
1611
        assert(b);
1✔
1612

1613
        if (a->type != b->type) {
1✔
1614
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1615
                           "Item not equivalent because types differ");
1616
                return false;
×
1617
        }
1618

1619
        if (!streq_ptr(a->name, b->name)) {
1✔
1620
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1621
                           "Item not equivalent because names differ ('%s' vs. '%s')",
1622
                           a->name, b->name);
1623
                return false;
×
1624
        }
1625

1626
        /* Paths were simplified previously, so we can use streq. */
1627
        if (!streq_ptr(a->uid_path, b->uid_path)) {
1✔
1628
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1629
                           "Item not equivalent because UID paths differ (%s vs. %s)",
1630
                           a->uid_path ?: "(unset)", b->uid_path ?: "(unset)");
1631
                return false;
×
1632
        }
1633

1634
        if (!streq_ptr(a->gid_path, b->gid_path)) {
1✔
1635
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1636
                           "Item not equivalent because GID paths differ (%s vs. %s)",
1637
                           a->gid_path ?: "(unset)", b->gid_path ?: "(unset)");
1638
                return false;
×
1639
        }
1640

1641
        if (!streq_ptr(a->description, b->description))  {
1✔
1642
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1643
                           "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1644
                           strempty(a->description), strempty(b->description));
1645
                return false;
×
1646
        }
1647

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

1657
        if ((a->gid_set != b->gid_set) ||
1✔
1658
            (a->gid_set && a->gid != b->gid)) {
1✔
1659
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1660
                           "Item not equivalent because GIDs differ (%s vs. %s)",
1661
                           a->gid_set ? FORMAT_GID(a->gid) : "(unset)",
1662
                           b->gid_set ? FORMAT_GID(b->gid) : "(unset)");
1663
                return false;
×
1664
        }
1665

1666
        if (!streq_ptr(a->home, b->home)) {
1✔
1667
                log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1668
                           "Item not equivalent because home directories differ ('%s' vs. '%s')",
1669
                           strempty(a->description), strempty(b->description));
1670
                return false;
×
1671
        }
1672

1673
        /* Check if the two paths refer to the same file.
1674
         * If the paths are equal (after normalization), it's obviously the same file.
1675
         * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1676
         * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1677
         * /usr/sbin/nologin).
1678
         * If we can't resolve something, treat different paths as different. */
1679

1680
        const char *a_shell = pick_shell(a),
1✔
1681
                   *b_shell = pick_shell(b);
1✔
1682
        if (!path_equal(a_shell, b_shell) &&
1✔
1683
            !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
×
1684
                _cleanup_free_ char *pa = NULL, *pb = NULL;
×
1685

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

1694
                r = chase(b_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pb, NULL);
×
1695
                if (r < 0) {
×
1696
                        log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
×
1697
                                       r, "Failed to look up path '%s%s%s': %m",
1698
                                       strempty(arg_root), arg_root ? "/" : "", b_shell);
1699
                        return ERRNO_IS_RESOURCE(r) ? r : false;
×
1700
                }
1701

1702
                if (!path_equal(pa, pb)) {
×
1703
                        log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
×
1704
                                   "Item not equivalent because shells differ ('%s' vs. '%s')",
1705
                                   pa, pb);
1706
                        return false;
×
1707
                }
1708
        }
1709

1710
        return true;
1711
}
1712

1713
static int parse_line(
682✔
1714
                const char *fname,
1715
                unsigned line,
1716
                const char *buffer,
1717
                bool *invalid_config,
1718
                void *context) {
1719

1720
        Context *c = ASSERT_PTR(context);
682✔
1721
        _cleanup_free_ char *action = NULL,
1,364✔
1722
                *name = NULL, *resolved_name = NULL,
×
1723
                *id = NULL, *resolved_id = NULL,
×
1724
                *description = NULL, *resolved_description = NULL,
×
1725
                *home = NULL, *resolved_home = NULL,
×
1726
                *shell = NULL, *resolved_shell = NULL;
682✔
1727
        _cleanup_(item_freep) Item *i = NULL;
682✔
1728
        Item *existing;
682✔
1729
        OrderedHashmap *h;
682✔
1730
        int r;
682✔
1731
        const char *p;
682✔
1732

1733
        assert(fname);
682✔
1734
        assert(line >= 1);
682✔
1735
        assert(buffer);
682✔
1736
        assert(!invalid_config); /* We don't support invalid_config yet. */
682✔
1737

1738
        /* Parse columns */
1739
        p = buffer;
682✔
1740
        r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
682✔
1741
                               &action, &name, &id, &description, &home, &shell);
1742
        if (r < 0)
682✔
1743
                return log_syntax(NULL, LOG_ERR, fname, line, r, "Syntax error.");
×
1744
        if (r < 2)
682✔
1745
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1746
                                  "Missing action and name columns.");
1747
        if (!isempty(p))
682✔
1748
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1749
                                  "Trailing garbage.");
1750

1751
        if (isempty(action))
682✔
1752
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1753
                                  "Empty command specification.");
1754

1755
        bool locked = false;
1756
        for (int pos = 1; action[pos]; pos++)
694✔
1757
                if (action[pos] == '!' && !locked)
12✔
1758
                        locked = true;
12✔
1759
                else
1760
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1761
                                          "Unknown modifiers in command '%s'.", action);
1762

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

1767
        /* Verify name */
1768
        if (empty_or_dash(name))
682✔
1769
                name = mfree(name);
×
1770

1771
        if (name) {
682✔
1772
                r = specifier_printf(name, NAME_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_name);
682✔
1773
                if (r < 0)
682✔
1774
                        return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", name);
×
1775

1776
                if (!valid_user_group_name(resolved_name, 0))
682✔
1777
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1778
                                          "'%s' is not a valid user or group name.", resolved_name);
1779
        }
1780

1781
        /* Verify id */
1782
        if (empty_or_dash(id))
682✔
1783
                id = mfree(id);
55✔
1784

1785
        if (id) {
682✔
1786
                r = specifier_printf(id, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_id);
627✔
1787
                if (r < 0)
627✔
1788
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1789
                                          "Failed to replace specifiers in '%s': %m", name);
1790
        }
1791

1792
        /* Verify description */
1793
        if (empty_or_dash(description))
682✔
1794
                description = mfree(description);
631✔
1795

1796
        if (description) {
682✔
1797
                r = specifier_printf(description, LONG_LINE_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_description);
51✔
1798
                if (r < 0)
51✔
1799
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1800
                                          "Failed to replace specifiers in '%s': %m", description);
1801

1802
                if (!valid_gecos(resolved_description))
51✔
1803
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1804
                                          "'%s' is not a valid GECOS field.", resolved_description);
1805
        }
1806

1807
        /* Verify home */
1808
        if (empty_or_dash(home))
682✔
1809
                home = mfree(home);
542✔
1810

1811
        if (home) {
682✔
1812
                r = specifier_printf(home, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_home);
140✔
1813
                if (r < 0)
140✔
1814
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1815
                                          "Failed to replace specifiers in '%s': %m", home);
1816

1817
                path_simplify(resolved_home);
140✔
1818

1819
                if (!valid_home(resolved_home))
140✔
1820
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1821
                                          "'%s' is not a valid home directory field.", resolved_home);
1822
        }
1823

1824
        /* Verify shell */
1825
        if (empty_or_dash(shell))
682✔
1826
                shell = mfree(shell);
661✔
1827

1828
        if (shell) {
682✔
1829
                r = specifier_printf(shell, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_shell);
21✔
1830
                if (r < 0)
21✔
1831
                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1832
                                          "Failed to replace specifiers in '%s': %m", shell);
1833

1834
                path_simplify(resolved_shell);
21✔
1835

1836
                if (!valid_shell(resolved_shell))
21✔
1837
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1838
                                          "'%s' is not a valid login shell field.", resolved_shell);
1839
        }
1840

1841
        switch (action[0]) {
682✔
1842

1843
        case ADD_RANGE:
×
1844
                if (locked)
×
1845
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1846
                                          "Flag '!' not permitted on lines of type 'r'.");
1847

1848
                if (resolved_name)
×
1849
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1850
                                          "Lines of type 'r' don't take a name field.");
1851

1852
                if (!resolved_id)
×
1853
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1854
                                          "Lines of type 'r' require an ID range in the third field.");
1855

1856
                if (description || home || shell)
×
1857
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1858
                                          "Lines of type '%c' don't take a %s field.",
1859
                                          action[0],
1860
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1861

1862
                r = uid_range_add_str(&c->uid_range, resolved_id);
×
1863
                if (r < 0)
×
1864
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1865
                                          "Invalid UID range %s.", resolved_id);
1866

1867
                return 0;
1868

1869
        case ADD_MEMBER: {
10✔
1870
                /* Try to extend an existing member or group item */
1871
                if (!name)
10✔
1872
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1873
                                          "Lines of type 'm' require a user name in the second field.");
1874

1875
                if (locked)
10✔
1876
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1877
                                          "Flag '!' not permitted on lines of type 'm'.");
1878

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

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

1887
                if (description || home || shell)
10✔
1888
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1889
                                          "Lines of type '%c' don't take a %s field.",
1890
                                          action[0],
1891
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1892

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

1897
                return 0;
1898
        }
1899

1900
        case ADD_USER:
295✔
1901
                if (!name)
295✔
1902
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1903
                                          "Lines of type 'u' require a user name in the second field.");
1904

1905
                r = ordered_hashmap_ensure_allocated(&c->users, &item_hash_ops);
295✔
1906
                if (r < 0)
295✔
1907
                        return log_oom();
×
1908

1909
                i = item_new(ADD_USER, resolved_name, fname, line);
295✔
1910
                if (!i)
295✔
1911
                        return log_oom();
×
1912

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

1942
                i->description = TAKE_PTR(resolved_description);
294✔
1943
                i->home = TAKE_PTR(resolved_home);
294✔
1944
                i->shell = TAKE_PTR(resolved_shell);
294✔
1945
                i->locked = locked;
294✔
1946

1947
                h = c->users;
294✔
1948
                break;
294✔
1949

1950
        case ADD_GROUP:
377✔
1951
                if (!name)
377✔
1952
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1953
                                          "Lines of type 'g' require a user name in the second field.");
1954

1955
                if (locked)
377✔
1956
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1957
                                          "Flag '!' not permitted on lines of type 'g'.");
1958

1959
                if (description || home || shell)
377✔
1960
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1961
                                          "Lines of type '%c' don't take a %s field.",
1962
                                          action[0],
1963
                                          description ? "GECOS" : home ? "home directory" : "login shell");
1964

1965
                r = ordered_hashmap_ensure_allocated(&c->groups, &item_hash_ops);
377✔
1966
                if (r < 0)
377✔
1967
                        return log_oom();
×
1968

1969
                i = item_new(ADD_GROUP, resolved_name, fname, line);
377✔
1970
                if (!i)
377✔
1971
                        return log_oom();
×
1972

1973
                if (resolved_id) {
377✔
1974
                        if (path_is_absolute(resolved_id))
351✔
1975
                                i->gid_path = path_simplify(TAKE_PTR(resolved_id));
×
1976
                        else {
1977
                                r = parse_gid(resolved_id, &i->gid);
351✔
1978
                                if (r < 0)
351✔
1979
                                        return log_syntax(NULL, LOG_ERR, fname, line, r,
×
1980
                                                          "Failed to parse GID: '%s': %m", id);
1981

1982
                                i->gid_set = true;
351✔
1983
                        }
1984
                }
1985

1986
                h = c->groups;
377✔
1987
                break;
377✔
1988

1989
        default:
×
1990
                assert_not_reached();
×
1991
        }
1992

1993
        existing = ordered_hashmap_get(h, i->name);
671✔
1994
        if (existing) {
671✔
1995
                /* Two functionally-equivalent items are fine */
1996
                r = item_equivalent(i, existing);
1✔
1997
                if (r < 0)
1✔
1998
                        return r;
1999
                if (r == 0) {
1✔
2000
                        if (existing->filename)
×
2001
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
2002
                                           "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
2003
                                           item_type_to_string(i->type),
2004
                                           i->name,
2005
                                           existing->filename, existing->line);
2006
                        else
2007
                                log_syntax(NULL, LOG_WARNING, fname, line, 0,
×
2008
                                           "Conflict with earlier configuration for %s '%s', ignoring line.",
2009
                                           item_type_to_string(i->type),
2010
                                           i->name);
2011
                }
2012

2013
                return 0;
1✔
2014
        }
2015

2016
        r = ordered_hashmap_put(h, i->name, i);
670✔
2017
        if (r < 0)
670✔
2018
                return log_oom();
×
2019

2020
        i = NULL;
670✔
2021
        return 0;
670✔
2022
}
2023

2024
static int read_config_file(Context *c, const char *fn, bool ignore_enoent) {
132✔
2025
        return conf_file_read(
396✔
2026
                        arg_root,
2027
                        (const char**) CONF_PATHS_STRV("sysusers.d"),
132✔
2028
                        ASSERT_PTR(fn),
132✔
2029
                        parse_line,
2030
                        ASSERT_PTR(c),
132✔
2031
                        ignore_enoent,
2032
                        /* invalid_config= */ NULL);
2033
}
2034

2035
static int cat_config(void) {
×
2036
        _cleanup_strv_free_ char **files = NULL;
×
2037
        int r;
×
2038

2039
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
×
2040
        if (r < 0)
×
2041
                return r;
2042

2043
        pager_open(arg_pager_flags);
×
2044

2045
        return cat_files(NULL, files, arg_cat_flags);
×
2046
}
2047

2048
static int help(void) {
×
2049
        _cleanup_free_ char *link = NULL;
×
2050
        int r;
×
2051

2052
        r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
×
2053
        if (r < 0)
×
2054
                return log_oom();
×
2055

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

2078
        return 0;
2079
}
2080

2081
static int parse_argv(int argc, char *argv[]) {
113✔
2082

2083
        enum {
113✔
2084
                ARG_VERSION = 0x100,
2085
                ARG_CAT_CONFIG,
2086
                ARG_TLDR,
2087
                ARG_ROOT,
2088
                ARG_IMAGE,
2089
                ARG_IMAGE_POLICY,
2090
                ARG_REPLACE,
2091
                ARG_DRY_RUN,
2092
                ARG_INLINE,
2093
                ARG_NO_PAGER,
2094
        };
2095

2096
        static const struct option options[] = {
113✔
2097
                { "help",         no_argument,       NULL, 'h'              },
2098
                { "version",      no_argument,       NULL, ARG_VERSION      },
2099
                { "cat-config",   no_argument,       NULL, ARG_CAT_CONFIG   },
2100
                { "tldr",         no_argument,       NULL, ARG_TLDR         },
2101
                { "root",         required_argument, NULL, ARG_ROOT         },
2102
                { "image",        required_argument, NULL, ARG_IMAGE        },
2103
                { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
2104
                { "replace",      required_argument, NULL, ARG_REPLACE      },
2105
                { "dry-run",      no_argument,       NULL, ARG_DRY_RUN      },
2106
                { "inline",       no_argument,       NULL, ARG_INLINE       },
2107
                { "no-pager",     no_argument,       NULL, ARG_NO_PAGER     },
2108
                {}
2109
        };
2110

2111
        int c, r;
113✔
2112

2113
        assert(argc >= 0);
113✔
2114
        assert(argv);
113✔
2115

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

2118
                switch (c) {
147✔
2119

2120
                case 'h':
×
2121
                        return help();
×
2122

2123
                case ARG_VERSION:
×
2124
                        return version();
×
2125

2126
                case ARG_CAT_CONFIG:
×
2127
                        arg_cat_flags = CAT_CONFIG_ON;
×
2128
                        break;
×
2129

2130
                case ARG_TLDR:
×
2131
                        arg_cat_flags = CAT_TLDR;
×
2132
                        break;
×
2133

2134
                case ARG_ROOT:
108✔
2135
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
108✔
2136
                        if (r < 0)
108✔
2137
                                return r;
2138
                        break;
2139

2140
                case ARG_IMAGE:
×
2141
#ifdef STANDALONE
2142
                        return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2143
                                               "This systemd-sysusers version is compiled without support for --image=.");
2144
#else
2145
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
×
2146
                        if (r < 0)
×
2147
                                return r;
2148
                        break;
2149
#endif
2150

2151
                case ARG_IMAGE_POLICY:
×
2152
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
2153
                        if (r < 0)
×
2154
                                return r;
2155
                        break;
2156

2157
                case ARG_REPLACE:
35✔
2158
                        if (!path_is_absolute(optarg))
35✔
2159
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2160
                                                       "The argument to --replace= must be an absolute path.");
2161
                        if (!endswith(optarg, ".conf"))
35✔
2162
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2163
                                                       "The argument to --replace= must have the extension '.conf'.");
2164

2165
                        arg_replace = optarg;
35✔
2166
                        break;
35✔
2167

2168
                case ARG_DRY_RUN:
×
2169
                        arg_dry_run = true;
×
2170
                        break;
×
2171

2172
                case ARG_INLINE:
4✔
2173
                        arg_inline = true;
4✔
2174
                        break;
4✔
2175

2176
                case ARG_NO_PAGER:
×
2177
                        arg_pager_flags |= PAGER_DISABLE;
×
2178
                        break;
×
2179

2180
                case '?':
2181
                        return -EINVAL;
2182

2183
                default:
×
2184
                        assert_not_reached();
×
2185
                }
2186

2187
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
113✔
2188
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2189
                                       "Option --replace= is not supported with --cat-config/--tldr.");
2190

2191
        if (arg_replace && optind >= argc)
113✔
2192
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2193
                                       "When --replace= is given, some configuration items must be specified.");
2194

2195
        if (arg_image && arg_root)
113✔
2196
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2197
                                       "Use either --root= or --image=, the combination of both is not supported.");
2198

2199
        return 1;
2200
}
2201

2202
static int parse_arguments(Context *c, char **args) {
41✔
2203
        unsigned pos = 1;
41✔
2204
        int r;
41✔
2205

2206
        assert(c);
41✔
2207

2208
        STRV_FOREACH(arg, args) {
85✔
2209
                if (arg_inline)
44✔
2210
                        /* Use (argument):n, where n==1 for the first positional arg */
2211
                        r = parse_line("(argument)", pos, *arg, /* invalid_config= */ NULL, c);
7✔
2212
                else
2213
                        r = read_config_file(c, *arg, /* ignore_enoent= */ false);
37✔
2214
                if (r < 0)
44✔
2215
                        return r;
2216

2217
                pos++;
44✔
2218
        }
2219

2220
        return 0;
2221
}
2222

2223
static int read_config_files(Context *c, char **args) {
90✔
2224
        _cleanup_strv_free_ char **files = NULL;
×
2225
        _cleanup_free_ char *p = NULL;
90✔
2226
        int r;
90✔
2227

2228
        assert(c);
90✔
2229

2230
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
90✔
2231
        if (r < 0)
90✔
2232
                return r;
2233

2234
        STRV_FOREACH(f, files)
202✔
2235
                if (p && path_equal(*f, p)) {
112✔
2236
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
18✔
2237

2238
                        r = parse_arguments(c, args);
18✔
2239
                        if (r < 0)
18✔
2240
                                return r;
2241
                } else {
2242
                        log_debug("Reading config file \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
116✔
2243

2244
                        /* Just warn, ignore result otherwise */
2245
                        (void) read_config_file(c, *f, /* ignore_enoent= */ true);
94✔
2246
                }
2247

2248
        return 0;
2249
}
2250

2251
static int read_credential_lines(Context *c) {
113✔
2252
        _cleanup_free_ char *j = NULL;
113✔
2253
        const char *d;
113✔
2254
        int r;
113✔
2255

2256
        assert(c);
113✔
2257

2258
        r = get_credentials_dir(&d);
113✔
2259
        if (r == -ENXIO)
113✔
2260
                return 0;
2261
        if (r < 0)
1✔
2262
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
2263

2264
        j = path_join(d, "sysusers.extra");
1✔
2265
        if (!j)
1✔
2266
                return log_oom();
×
2267

2268
        (void) read_config_file(c, j, /* ignore_enoent= */ true);
1✔
2269
        return 0;
2270
}
2271

2272
static int run(int argc, char *argv[]) {
113✔
2273
#ifndef STANDALONE
2274
        _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
113✔
2275
        _cleanup_(umount_and_freep) char *mounted_dir = NULL;
×
2276
#endif
2277
        _cleanup_close_ int lock = -EBADF;
113✔
2278
        _cleanup_(context_done) Context c = {
113✔
2279
                .audit_fd = -EBADF,
2280
                .search_uid = UID_INVALID,
2281
        };
2282

2283
        Item *i;
113✔
2284
        int r;
113✔
2285

2286
        r = parse_argv(argc, argv);
113✔
2287
        if (r <= 0)
113✔
2288
                return r;
2289

2290
        log_setup();
113✔
2291

2292
        if (arg_cat_flags != CAT_CONFIG_OFF)
113✔
2293
                return cat_config();
×
2294

2295
        if (should_bypass("SYSTEMD_SYSUSERS"))
113✔
2296
                return 0;
2297

2298
        umask(0022);
113✔
2299

2300
        r = mac_init();
113✔
2301
        if (r < 0)
113✔
2302
                return r;
2303

2304
#ifndef STANDALONE
2305
        if (arg_image) {
113✔
2306
                assert(!arg_root);
×
2307

2308
                r = mount_image_privately_interactively(
×
2309
                                arg_image,
2310
                                arg_image_policy,
2311
                                DISSECT_IMAGE_GENERIC_ROOT |
2312
                                DISSECT_IMAGE_REQUIRE_ROOT |
2313
                                DISSECT_IMAGE_VALIDATE_OS |
2314
                                DISSECT_IMAGE_RELAX_VAR_CHECK |
2315
                                DISSECT_IMAGE_FSCK |
2316
                                DISSECT_IMAGE_GROWFS |
2317
                                DISSECT_IMAGE_ALLOW_USERSPACE_VERITY,
2318
                                &mounted_dir,
2319
                                /* ret_dir_fd= */ NULL,
2320
                                &loop_device);
2321
                if (r < 0)
×
2322
                        return r;
2323

2324
                arg_root = strdup(mounted_dir);
×
2325
                if (!arg_root)
×
2326
                        return log_oom();
×
2327
        }
2328
#else
2329
        assert(!arg_image);
2330
#endif
2331

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

2336
        /* If command line arguments are specified along with --replace, read all configuration files and
2337
         * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2338
         * specified, execute just them, and finally, without --replace= or any positional arguments, just
2339
         * read configuration and execute it. */
2340
        if (arg_replace || optind >= argc)
113✔
2341
                r = read_config_files(&c, argv + optind);
90✔
2342
        else
2343
                r = parse_arguments(&c, argv + optind);
23✔
2344
        if (r < 0)
113✔
2345
                return r;
2346

2347
        r = read_credential_lines(&c);
113✔
2348
        if (r < 0)
113✔
2349
                return r;
2350

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

2359
        if (!c.uid_range) {
113✔
2360
                /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
2361
                r = read_login_defs(&c.login_defs, NULL, arg_root);
113✔
2362
                if (r < 0)
113✔
2363
                        return log_error_errno(r, "Failed to read %s%s: %m",
×
2364
                                               strempty(arg_root), "/etc/login.defs");
2365

2366
                c.login_defs_need_warning = true;
113✔
2367

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

2381
        r = add_implicit(&c);
113✔
2382
        if (r < 0)
113✔
2383
                return r;
2384

2385
        if (!arg_dry_run) {
113✔
2386
                lock = take_etc_passwd_lock(arg_root);
113✔
2387
                if (lock < 0)
113✔
2388
                        return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
×
2389
        }
2390

2391
        r = load_user_database(&c);
113✔
2392
        if (r < 0)
113✔
2393
                return log_error_errno(r, "Failed to load user database: %m");
×
2394

2395
        r = load_group_database(&c);
113✔
2396
        if (r < 0)
113✔
2397
                return log_error_errno(r, "Failed to read group database: %m");
×
2398

2399
        ORDERED_HASHMAP_FOREACH(i, c.groups)
489✔
2400
                (void) process_item(&c, i);
376✔
2401

2402
        ORDERED_HASHMAP_FOREACH(i, c.users)
412✔
2403
                (void) process_item(&c, i);
299✔
2404

2405
        return write_files(&c);
113✔
2406
}
2407

2408
DEFINE_MAIN_FUNCTION(run);
113✔
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