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

systemd / systemd / 15199265962

22 May 2025 09:40PM UTC coverage: 72.061% (-0.02%) from 72.079%
15199265962

push

github

bluca
tests: fix TEST-74-AUX-UTILS.varlinkctl.sh (#37562)

per Daan's explanation:
other subtests running as testuser apparently use systemd-run --user
--machine testuser@.host which turns user tracking in logind into "by
pin" mode. when the last pinning session exits it terminates the user.

299156 of 415145 relevant lines covered (72.06%)

703915.84 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
#include <stdlib.h>
5
#include <sys/stat.h>
6

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

48
typedef enum ItemType {
49
        ADD_USER =   'u',
50
        ADD_GROUP =  'g',
51
        ADD_MEMBER = 'm',
52
        ADD_RANGE =  'r',
53
} ItemType;
54

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

70
typedef struct Item {
71
        ItemType type;
72

73
        char *name;
74
        char *group_name;
75
        char *uid_path;
76
        char *gid_path;
77
        char *description;
78
        char *home;
79
        char *shell;
80

81
        gid_t gid;
82
        uid_t uid;
83

84
        char *filename;
85
        unsigned line;
86

87
        bool gid_set;
88

89
        /* When set the group with the specified GID must exist
90
         * and the check if a UID clashes with the GID is skipped.
91
         */
92
        bool id_set_strict;
93

94
        bool uid_set;
95

96
        bool locked;
97

98
        bool todo_user;
99
        bool todo_group;
100
} Item;
101

102
static char *arg_root = NULL;
103
static char *arg_image = NULL;
104
static CatFlags arg_cat_flags = CAT_CONFIG_OFF;
105
static const char *arg_replace = NULL;
106
static bool arg_dry_run = false;
107
static bool arg_inline = false;
108
static PagerFlags arg_pager_flags = 0;
109
static ImagePolicy *arg_image_policy = NULL;
110

111
STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
113✔
112
STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
113✔
113
STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
113✔
114

115
typedef struct Context {
116
        int audit_fd;
117

118
        OrderedHashmap *users, *groups;
119
        OrderedHashmap *todo_uids, *todo_gids;
120
        OrderedHashmap *members;
121

122
        Hashmap *database_by_uid, *database_by_username;
123
        Hashmap *database_by_gid, *database_by_groupname;
124

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

128
        uid_t search_uid;
129
        UIDRange *uid_range;
130

131
        UGIDAllocationRange login_defs;
132
        bool login_defs_need_warning;
133
} Context;
134

135
static void context_done(Context *c) {
113✔
136
        assert(c);
113✔
137

138
        c->audit_fd = close_audit_fd(c->audit_fd);
113✔
139

140
        ordered_hashmap_free(c->groups);
113✔
141
        ordered_hashmap_free(c->users);
113✔
142
        ordered_hashmap_free(c->members);
113✔
143
        ordered_hashmap_free(c->todo_uids);
113✔
144
        ordered_hashmap_free(c->todo_gids);
113✔
145

146
        hashmap_free(c->database_by_uid);
113✔
147
        hashmap_free(c->database_by_username);
113✔
148
        hashmap_free(c->database_by_gid);
113✔
149
        hashmap_free(c->database_by_groupname);
113✔
150

151
        set_free(c->names);
113✔
152
        uid_range_free(c->uid_range);
113✔
153
}
113✔
154

155
static void maybe_emit_login_defs_warning(Context *c) {
45✔
156
        assert(c);
45✔
157

158
        if (!c->login_defs_need_warning)
45✔
159
                return;
160

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

174
        c->login_defs_need_warning = false;
44✔
175
}
176

177
static void log_audit_accounts(Context *c, ItemType what) {
226✔
178
#if HAVE_AUDIT
179
        assert(c);
226✔
180
        assert(IN_SET(what, ADD_USER, ADD_GROUP));
226✔
181

182
        if (arg_dry_run || c->audit_fd < 0)
226✔
183
                return;
226✔
184

185
        Item *i;
×
186
        int type = what == ADD_USER ? AUDIT_ADD_USER : AUDIT_ADD_GROUP;
×
187
        const char *op = what == ADD_USER ? "adding-user" : "adding-group";
×
188

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

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

219
static int load_user_database(Context *c) {
113✔
220
        _cleanup_free_ char *passwd_path = NULL;
113✔
221
        _cleanup_fclose_ FILE *f = NULL;
113✔
222
        struct passwd *pw;
113✔
223
        int r;
113✔
224

225
        assert(c);
113✔
226

227
        r = chase_and_fopen_unlocked("/etc/passwd", arg_root, CHASE_PREFIX_ROOT, "re", &passwd_path, &f);
113✔
228
        if (r == -ENOENT)
113✔
229
                return 0;
230
        if (r < 0)
37✔
231
                return r;
232

233
        while ((r = fgetpwent_sane(f, &pw)) > 0) {
254✔
234

235
                char *n = strdup(pw->pw_name);
217✔
236
                if (!n)
217✔
237
                        return -ENOMEM;
238

239
                /* Note that we use trivial_hash_ops_free here, so identical strings can exist in the set. */
240
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, n);
217✔
241
                if (r < 0)
217✔
242
                        return r;
243
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
217✔
244

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

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

262
static int load_group_database(Context *c) {
113✔
263
        _cleanup_free_ char *group_path = NULL;
113✔
264
        _cleanup_fclose_ FILE *f = NULL;
113✔
265
        struct group *gr;
113✔
266
        int r;
113✔
267

268
        assert(c);
113✔
269

270
        r = chase_and_fopen_unlocked("/etc/group", arg_root, CHASE_PREFIX_ROOT, "re", &group_path, &f);
113✔
271
        if (r == -ENOENT)
113✔
272
                return 0;
273
        if (r < 0)
37✔
274
                return r;
275

276
        while ((r = fgetgrent_sane(f, &gr)) > 0) {
457✔
277
                char *n = strdup(gr->gr_name);
420✔
278
                if (!n)
420✔
279
                        return -ENOMEM;
280

281
                /* Note that we use trivial_hash_ops_free here, so identical strings can exist in the set. */
282
                r = set_ensure_consume(&c->names, &trivial_hash_ops_free, n);
420✔
283
                if (r < 0)
420✔
284
                        return r;
285
                assert(r > 0);  /* The set uses pointer comparisons, so n must not be in the set. */
420✔
286

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

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

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

312
        assert(target);
348✔
313
        assert(x);
348✔
314

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

320
                return -errno;
×
321
        }
322

323
        if (fstat(src, &st) < 0)
36✔
324
                return -errno;
×
325

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

334
        r = copy_bytes(src, fileno(dst), UINT64_MAX, COPY_REFLINK);
36✔
335
        if (r < 0)
36✔
336
                return r;
337

338
        backup = strjoina(x, "-");
180✔
339

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

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

349
        r = fsync_full(fileno(dst));
36✔
350
        if (r < 0)
36✔
351
                return r;
352

353
        if (rename(dst_tmp, backup) < 0)
36✔
354
                return errno;
×
355

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

360
static int putgrent_with_members(
753✔
361
                Context *c,
362
                const struct group *gr,
363
                FILE *group) {
364

365
        char **a;
753✔
366
        int r;
753✔
367

368
        assert(c);
753✔
369
        assert(gr);
753✔
370
        assert(group);
753✔
371

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

377
                l = strv_copy(gr->gr_mem);
10✔
378
                if (!l)
10✔
379
                        return -ENOMEM;
380

381
                STRV_FOREACH(i, a) {
20✔
382
                        if (strv_contains(l, *i))
10✔
383
                                continue;
5✔
384

385
                        r = strv_extend(&l, *i);
5✔
386
                        if (r < 0)
5✔
387
                                return r;
388

389
                        added = true;
390
                }
391

392
                if (added) {
10✔
393
                        struct group t;
5✔
394

395
                        strv_sort_uniq(l);
5✔
396

397
                        t = *gr;
5✔
398
                        t.gr_mem = l;
5✔
399

400
                        r = putgrent_sane(&t, group);
5✔
401
                        return r < 0 ? r : 1;
10✔
402
                }
403
        }
404

405
        return putgrent_sane(gr, group);
748✔
406
}
407

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

414
        char **a;
743✔
415
        int r;
743✔
416

417
        assert(sg);
743✔
418
        assert(gshadow);
743✔
419

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

425
                l = strv_copy(sg->sg_mem);
10✔
426
                if (!l)
10✔
427
                        return -ENOMEM;
428

429
                STRV_FOREACH(i, a) {
20✔
430
                        if (strv_contains(l, *i))
10✔
431
                                continue;
5✔
432

433
                        r = strv_extend(&l, *i);
5✔
434
                        if (r < 0)
5✔
435
                                return r;
436

437
                        added = true;
438
                }
439

440
                if (added) {
10✔
441
                        struct sgrp t;
5✔
442

443
                        strv_sort_uniq(l);
5✔
444

445
                        t = *sg;
5✔
446
                        t.sg_mem = l;
5✔
447

448
                        r = putsgent_sane(&t, gshadow);
5✔
449
                        return r < 0 ? r : 1;
10✔
450
                }
451
        }
452

453
        return putsgent_sane(sg, gshadow);
738✔
454
}
455
#endif
456

457
static const char* pick_shell(const Item *i) {
270✔
458
        assert(i);
270✔
459

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

469
static int write_temporary_passwd(
113✔
470
                Context *c,
471
                const char *passwd_path,
472
                FILE **ret_tmpfile,
473
                char **ret_tmpfile_path) {
474

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

481
        assert(c);
113✔
482

483
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
484
                return 0;
485

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

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

495
        original = fopen(passwd_path, "re");
87✔
496
        if (original) {
87✔
497

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

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

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

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

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

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

538
        ORDERED_HASHMAP_FOREACH(i, c->todo_uids) {
355✔
539
                _cleanup_free_ char *creds_shell = NULL, *cn = NULL;
268✔
540

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

547
                        /* "x" means the password is stored in the shadow file */
548
                        .pw_passwd = (char*) PASSWORD_SEE_SHADOW,
549

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

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

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

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

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

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

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

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

593
        *ret_tmpfile = TAKE_PTR(passwd);
87✔
594
        *ret_tmpfile_path = TAKE_PTR(passwd_tmp);
87✔
595

596
        return 0;
87✔
597
}
598

599
static usec_t epoch_or_now(void) {
87✔
600
        uint64_t epoch;
87✔
601

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

608
        return now(CLOCK_REALTIME);
87✔
609
}
610

611
static int write_temporary_shadow(
113✔
612
                Context *c,
613
                const char *shadow_path,
614
                FILE **ret_tmpfile,
615
                char **ret_tmpfile_path) {
616

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

624
        assert(c);
113✔
625

626
        if (ordered_hashmap_isempty(c->todo_uids))
113✔
627
                return 0;
628

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

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

638
        lstchg = (long) (epoch_or_now() / USEC_PER_DAY);
87✔
639

640
        original = fopen(shadow_path, "re");
87✔
641
        if (original) {
87✔
642

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

740
        *ret_tmpfile = TAKE_PTR(shadow);
87✔
741
        *ret_tmpfile_path = TAKE_PTR(shadow_tmp);
87✔
742

743
        return 0;
87✔
744
}
745

746
static int write_temporary_group(
113✔
747
                Context *c,
748
                const char *group_path,
749
                FILE **ret_tmpfile,
750
                char **ret_tmpfile_path) {
751

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

759
        assert(c);
113✔
760

761
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
762
                return 0;
763

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

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

773
        original = fopen(group_path, "re");
87✔
774
        if (original) {
87✔
775

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

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

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

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

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

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

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

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

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

831
                group_changed = true;
516✔
832
        }
833

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

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

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

852
        if (group_changed) {
87✔
853
                *ret_tmpfile = TAKE_PTR(group);
87✔
854
                *ret_tmpfile_path = TAKE_PTR(group_tmp);
87✔
855
        }
856
        return 0;
857
}
858

859
static int write_temporary_gshadow(
113✔
860
                Context *c,
861
                const char * gshadow_path,
862
                FILE **ret_tmpfile,
863
                char **ret_tmpfile_path) {
864

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

872
        assert(c);
113✔
873

874
        if (ordered_hashmap_isempty(c->todo_gids) && ordered_hashmap_isempty(c->members))
113✔
875
                return 0;
876

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

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

886
        original = fopen(gshadow_path, "re");
87✔
887
        if (original) {
87✔
888
                struct sgrp *sg;
4✔
889

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

895
                while ((r = fgetsgent_sane(original, &sg)) > 0) {
231✔
896

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

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

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

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

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

931
                group_changed = true;
516✔
932
        }
933

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

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

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

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

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

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

963
        _cleanup_free_ char *gshadow_path = path_join(arg_root, "/etc/gshadow");
226✔
964
        if (!gshadow_path)
113✔
965
                return log_oom();
×
966

967
        assert(c);
113✔
968

969
        r = write_temporary_group(c, group_path, &group, &group_tmp);
113✔
970
        if (r < 0)
113✔
971
                return r;
972

973
        r = write_temporary_gshadow(c, gshadow_path, &gshadow, &gshadow_tmp);
113✔
974
        if (r < 0)
113✔
975
                return r;
976

977
        r = write_temporary_passwd(c, passwd_path, &passwd, &passwd_tmp);
113✔
978
        if (r < 0)
113✔
979
                return r;
980

981
        r = write_temporary_shadow(c, shadow_path, &shadow, &shadow_tmp);
113✔
982
        if (r < 0)
113✔
983
                return r;
984

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

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

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

1024
                gshadow_tmp = mfree(gshadow_tmp);
87✔
1025
        }
1026

1027
        if (passwd) {
113✔
1028
                r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
87✔
1029
                if (r < 0)
87✔
1030
                        return log_error_errno(r, "Failed to rename %s to %s: %m",
×
1031
                                               passwd_tmp, passwd_path);
1032

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

1043
                shadow_tmp = mfree(shadow_tmp);
87✔
1044
        }
1045

1046
        return 0;
1047
}
1048

1049
static int uid_is_ok(
288✔
1050
                Context *c,
1051
                uid_t uid,
1052
                const char *name,
1053
                bool check_with_gid) {
1054

1055
        int r;
288✔
1056
        assert(c);
288✔
1057

1058
        /* Let's see if we already have assigned the UID a second time */
1059
        if (ordered_hashmap_get(c->todo_uids, UID_TO_PTR(uid)))
288✔
1060
                return 0;
1061

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

1067
                i = ordered_hashmap_get(c->todo_gids, GID_TO_PTR(uid));
203✔
1068
                if (i && !streq(i->name, name))
203✔
1069
                        return 0;
1070
        }
1071

1072
        /* Let's check the files directly */
1073
        if (hashmap_contains(c->database_by_uid, UID_TO_PTR(uid)))
273✔
1074
                return 0;
1075

1076
        if (check_with_gid) {
273✔
1077
                const char *n;
193✔
1078

1079
                n = hashmap_get(c->database_by_gid, GID_TO_PTR(uid));
193✔
1080
                if (n && !streq(n, name))
193✔
1081
                        return 0;
1082
        }
1083

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

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

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

1104
        return 1;
1105
}
1106

1107
static int root_stat(const char *p, struct stat *ret_st) {
×
1108
        return chase_and_stat(p, arg_root, CHASE_PREFIX_ROOT, /* ret_path= */ NULL, ret_st);
×
1109
}
1110

1111
static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
70✔
1112
        struct stat st;
70✔
1113
        bool found_uid = false, found_gid = false;
70✔
1114
        uid_t uid = 0;
70✔
1115
        gid_t gid = 0;
70✔
1116

1117
        assert(i);
70✔
1118

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

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

1130
                uid = st.st_uid;
×
1131
                found_uid = true;
×
1132

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

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

1143
                if (found_gid) {
×
1144
                        uid = (uid_t) gid;
1145
                        found_uid = true;
1146
                } else if (root_stat(i->gid_path, &st) >= 0) {
×
1147
                        uid = (uid_t) st.st_gid;
×
1148
                        found_uid = true;
×
1149
                }
1150
        }
1151

1152
        if (ret_uid) {
70✔
1153
                if (!found_uid)
40✔
1154
                        return 0;
70✔
1155

1156
                *ret_uid = uid;
×
1157
        }
1158

1159
        if (ret_gid) {
30✔
1160
                if (!found_gid)
30✔
1161
                        return 0;
1162

1163
                *ret_gid = gid;
×
1164
        }
1165

1166
        return 1;
1167
}
1168

1169
static int add_user(Context *c, Item *i) {
297✔
1170
        void *z;
297✔
1171
        int r;
297✔
1172

1173
        assert(c);
297✔
1174
        assert(i);
297✔
1175

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

1185
        if (!arg_root) {
268✔
1186
                _cleanup_free_ struct passwd *p = NULL;
5✔
1187

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

1195
                        r = free_and_strdup(&i->description, p->pw_gecos);
×
1196
                        if (r < 0)
×
1197
                                return log_oom();
×
1198

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

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

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

1220
                if (read_id_from_file(i, &candidate, NULL) > 0) {
40✔
1221

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

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

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

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

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

1264
                i->uid_set = true;
15✔
1265
                i->uid = c->search_uid;
15✔
1266
        }
1267

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

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

1282
        return 0;
1283
}
1284

1285
static int gid_is_ok(
720✔
1286
                Context *c,
1287
                gid_t gid,
1288
                const char *groupname,
1289
                bool check_with_uid) {
1290

1291
        Item *user;
720✔
1292
        char *username;
720✔
1293
        int r;
720✔
1294

1295
        assert(c);
720✔
1296
        assert(groupname);
720✔
1297

1298
        if (ordered_hashmap_get(c->todo_gids, GID_TO_PTR(gid)))
720✔
1299
                return 0;
1300

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

1308
        if (hashmap_contains(c->database_by_gid, GID_TO_PTR(gid)))
655✔
1309
                return 0;
1310

1311
        if (check_with_uid) {
517✔
1312
                username = hashmap_get(c->database_by_uid, UID_TO_PTR(gid));
183✔
1313
                if (username && !streq(username, groupname))
183✔
1314
                        return 0;
1315
        }
1316

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

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

1333
        return 1;
1334
}
1335

1336
static int get_gid_by_name(
645✔
1337
                Context *c,
1338
                const char *name,
1339
                gid_t *ret_gid) {
1340

1341
        void *z;
645✔
1342
        int r;
645✔
1343

1344
        assert(c);
645✔
1345
        assert(ret_gid);
645✔
1346

1347
        /* Check the database directly */
1348
        z = hashmap_get(c->database_by_groupname, name);
645✔
1349
        if (z) {
645✔
1350
                *ret_gid = PTR_TO_GID(z);
67✔
1351
                return 0;
67✔
1352
        }
1353

1354
        /* Also check NSS */
1355
        if (!arg_root) {
578✔
1356
                _cleanup_free_ struct group *g = NULL;
5✔
1357

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

1367
        return -ENOENT;
1368
}
1369

1370
static int add_group(Context *c, Item *i) {
639✔
1371
        int r;
639✔
1372

1373
        assert(c);
639✔
1374
        assert(i);
639✔
1375

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

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

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

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

1423
                if (read_id_from_file(i, NULL, &candidate) > 0) {
30✔
1424

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

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

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

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

1457
                i->gid_set = true;
30✔
1458
                i->gid = c->search_uid;
30✔
1459
        }
1460

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

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

1472
        return 0;
1473
}
1474

1475
static int process_item(Context *c, Item *i) {
675✔
1476
        int r;
675✔
1477

1478
        assert(c);
675✔
1479
        assert(i);
675✔
1480

1481
        switch (i->type) {
675✔
1482

1483
        case ADD_USER: {
299✔
1484
                Item *j = NULL;
299✔
1485

1486
                if (!i->gid_set) {
299✔
1487
                        j = ordered_hashmap_get(c->groups, i->group_name ?: i->name);
235✔
1488

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

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

1516
                return add_user(c, i);
297✔
1517
        }
1518

1519
        case ADD_GROUP:
376✔
1520
                return add_group(c, i);
376✔
1521

1522
        default:
×
1523
                assert_not_reached();
×
1524
        }
1525
}
1526

1527
static Item* item_free(Item *i) {
677✔
1528
        if (!i)
677✔
1529
                return NULL;
1530

1531
        free(i->name);
677✔
1532
        free(i->group_name);
677✔
1533
        free(i->uid_path);
677✔
1534
        free(i->gid_path);
677✔
1535
        free(i->description);
677✔
1536
        free(i->home);
677✔
1537
        free(i->shell);
677✔
1538
        free(i->filename);
677✔
1539
        return mfree(i);
677✔
1540
}
1541

1542
DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
1,364✔
1543
DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
675✔
1544

1545
static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
677✔
1546
        assert(name);
677✔
1547
        assert(!!filename == (line > 0));
677✔
1548

1549
        _cleanup_(item_freep) Item *new = new(Item, 1);
1,354✔
1550
        if (!new)
677✔
1551
                return NULL;
1552

1553
        *new = (Item) {
677✔
1554
                .type = type,
1555
                .line = line,
1556
        };
1557

1558
        if (free_and_strdup(&new->name, name) < 0 ||
1,354✔
1559
            free_and_strdup(&new->filename, filename) < 0)
677✔
1560
                return NULL;
×
1561

1562
        return TAKE_PTR(new);
677✔
1563
}
1564

1565
static int add_implicit(Context *c) {
113✔
1566
        char *g, **l;
113✔
1567
        int r;
113✔
1568

1569
        assert(c);
113✔
1570

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

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

1586
                                log_debug("Adding implicit user '%s' due to m line", j->name);
5✔
1587
                                TAKE_PTR(j);
5✔
1588
                        }
1589

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

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

1603
                        log_debug("Adding implicit group '%s' due to m line", j->name);
×
1604
                        TAKE_PTR(j);
×
1605
                }
1606
        }
1607

1608
        return 0;
113✔
1609
}
1610

1611
static int item_equivalent(Item *a, Item *b) {
1✔
1612
        int r;
1✔
1613

1614
        assert(a);
1✔
1615
        assert(b);
1✔
1616

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

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

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

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

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

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

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

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

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

1684
        const char *a_shell = pick_shell(a),
1✔
1685
                   *b_shell = pick_shell(b);
1✔
1686
        if (!path_equal(a_shell, b_shell) &&
1✔
1687
            !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
×
1688
                _cleanup_free_ char *pa = NULL, *pb = NULL;
×
1689

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

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

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

1714
        return true;
1715
}
1716

1717
static int parse_line(
682✔
1718
                const char *fname,
1719
                unsigned line,
1720
                const char *buffer,
1721
                bool *invalid_config,
1722
                void *context) {
1723

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

1737
        assert(fname);
682✔
1738
        assert(line >= 1);
682✔
1739
        assert(buffer);
682✔
1740
        assert(!invalid_config); /* We don't support invalid_config yet. */
682✔
1741

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

1755
        if (isempty(action))
682✔
1756
                return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
×
1757
                                  "Empty command specification.");
1758

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

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

1771
        /* Verify name */
1772
        if (empty_or_dash(name))
682✔
1773
                name = mfree(name);
×
1774

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

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

1785
        /* Verify id */
1786
        if (empty_or_dash(id))
682✔
1787
                id = mfree(id);
55✔
1788

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

1796
        /* Verify description */
1797
        if (empty_or_dash(description))
682✔
1798
                description = mfree(description);
631✔
1799

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

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

1811
        /* Verify home */
1812
        if (empty_or_dash(home))
682✔
1813
                home = mfree(home);
542✔
1814

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

1821
                path_simplify(resolved_home);
140✔
1822

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

1828
        /* Verify shell */
1829
        if (empty_or_dash(shell))
682✔
1830
                shell = mfree(shell);
661✔
1831

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

1838
                path_simplify(resolved_shell);
21✔
1839

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

1845
        switch (action[0]) {
682✔
1846

1847
        case ADD_RANGE:
×
1848
                if (locked)
×
1849
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1850
                                          "Flag '!' not permitted on lines of type 'r'.");
1851

1852
                if (resolved_name)
×
1853
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1854
                                          "Lines of type 'r' don't take a name field.");
1855

1856
                if (!resolved_id)
×
1857
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1858
                                          "Lines of type 'r' require an ID range in the third field.");
1859

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

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

1871
                return 0;
1872

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

1879
                if (locked)
10✔
1880
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1881
                                          "Flag '!' not permitted on lines of type 'm'.");
1882

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

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

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

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

1901
                return 0;
1902
        }
1903

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

1909
                r = ordered_hashmap_ensure_allocated(&c->users, &item_hash_ops);
295✔
1910
                if (r < 0)
295✔
1911
                        return log_oom();
×
1912

1913
                i = item_new(ADD_USER, resolved_name, fname, line);
295✔
1914
                if (!i)
295✔
1915
                        return log_oom();
×
1916

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

1946
                i->description = TAKE_PTR(resolved_description);
294✔
1947
                i->home = TAKE_PTR(resolved_home);
294✔
1948
                i->shell = TAKE_PTR(resolved_shell);
294✔
1949
                i->locked = locked;
294✔
1950

1951
                h = c->users;
294✔
1952
                break;
294✔
1953

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

1959
                if (locked)
377✔
1960
                        return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
×
1961
                                          "Flag '!' not permitted on lines of type 'g'.");
1962

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

1969
                r = ordered_hashmap_ensure_allocated(&c->groups, &item_hash_ops);
377✔
1970
                if (r < 0)
377✔
1971
                        return log_oom();
×
1972

1973
                i = item_new(ADD_GROUP, resolved_name, fname, line);
377✔
1974
                if (!i)
377✔
1975
                        return log_oom();
×
1976

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

1986
                                i->gid_set = true;
351✔
1987
                        }
1988
                }
1989

1990
                h = c->groups;
377✔
1991
                break;
377✔
1992

1993
        default:
×
1994
                assert_not_reached();
×
1995
        }
1996

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

2017
                return 0;
1✔
2018
        }
2019

2020
        r = ordered_hashmap_put(h, i->name, i);
670✔
2021
        if (r < 0)
670✔
2022
                return log_oom();
×
2023

2024
        i = NULL;
670✔
2025
        return 0;
670✔
2026
}
2027

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

2039
static int cat_config(void) {
×
2040
        _cleanup_strv_free_ char **files = NULL;
×
2041
        int r;
×
2042

2043
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
×
2044
        if (r < 0)
×
2045
                return r;
2046

2047
        pager_open(arg_pager_flags);
×
2048

2049
        return cat_files(NULL, files, arg_cat_flags);
×
2050
}
2051

2052
static int help(void) {
×
2053
        _cleanup_free_ char *link = NULL;
×
2054
        int r;
×
2055

2056
        r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
×
2057
        if (r < 0)
×
2058
                return log_oom();
×
2059

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

2082
        return 0;
2083
}
2084

2085
static int parse_argv(int argc, char *argv[]) {
113✔
2086

2087
        enum {
113✔
2088
                ARG_VERSION = 0x100,
2089
                ARG_CAT_CONFIG,
2090
                ARG_TLDR,
2091
                ARG_ROOT,
2092
                ARG_IMAGE,
2093
                ARG_IMAGE_POLICY,
2094
                ARG_REPLACE,
2095
                ARG_DRY_RUN,
2096
                ARG_INLINE,
2097
                ARG_NO_PAGER,
2098
        };
2099

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

2115
        int c, r;
113✔
2116

2117
        assert(argc >= 0);
113✔
2118
        assert(argv);
113✔
2119

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

2122
                switch (c) {
147✔
2123

2124
                case 'h':
×
2125
                        return help();
×
2126

2127
                case ARG_VERSION:
×
2128
                        return version();
×
2129

2130
                case ARG_CAT_CONFIG:
×
2131
                        arg_cat_flags = CAT_CONFIG_ON;
×
2132
                        break;
×
2133

2134
                case ARG_TLDR:
×
2135
                        arg_cat_flags = CAT_TLDR;
×
2136
                        break;
×
2137

2138
                case ARG_ROOT:
108✔
2139
                        r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
108✔
2140
                        if (r < 0)
108✔
2141
                                return r;
2142
                        break;
2143

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

2155
                case ARG_IMAGE_POLICY:
×
2156
                        r = parse_image_policy_argument(optarg, &arg_image_policy);
×
2157
                        if (r < 0)
×
2158
                                return r;
2159
                        break;
2160

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

2169
                        arg_replace = optarg;
35✔
2170
                        break;
35✔
2171

2172
                case ARG_DRY_RUN:
×
2173
                        arg_dry_run = true;
×
2174
                        break;
×
2175

2176
                case ARG_INLINE:
4✔
2177
                        arg_inline = true;
4✔
2178
                        break;
4✔
2179

2180
                case ARG_NO_PAGER:
×
2181
                        arg_pager_flags |= PAGER_DISABLE;
×
2182
                        break;
×
2183

2184
                case '?':
2185
                        return -EINVAL;
2186

2187
                default:
×
2188
                        assert_not_reached();
×
2189
                }
2190

2191
        if (arg_replace && arg_cat_flags != CAT_CONFIG_OFF)
113✔
2192
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2193
                                       "Option --replace= is not supported with --cat-config/--tldr.");
2194

2195
        if (arg_replace && optind >= argc)
113✔
2196
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2197
                                       "When --replace= is given, some configuration items must be specified.");
2198

2199
        if (arg_image && arg_root)
113✔
2200
                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
×
2201
                                       "Use either --root= or --image=, the combination of both is not supported.");
2202

2203
        return 1;
2204
}
2205

2206
static int parse_arguments(Context *c, char **args) {
41✔
2207
        unsigned pos = 1;
41✔
2208
        int r;
41✔
2209

2210
        assert(c);
41✔
2211

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

2221
                pos++;
44✔
2222
        }
2223

2224
        return 0;
2225
}
2226

2227
static int read_config_files(Context *c, char **args) {
90✔
2228
        _cleanup_strv_free_ char **files = NULL;
×
2229
        _cleanup_free_ char *p = NULL;
90✔
2230
        int r;
90✔
2231

2232
        assert(c);
90✔
2233

2234
        r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
90✔
2235
        if (r < 0)
90✔
2236
                return r;
2237

2238
        STRV_FOREACH(f, files)
202✔
2239
                if (p && path_equal(*f, p)) {
112✔
2240
                        log_debug("Parsing arguments at position \"%s\"%s", *f, glyph(GLYPH_ELLIPSIS));
18✔
2241

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

2248
                        /* Just warn, ignore result otherwise */
2249
                        (void) read_config_file(c, *f, /* ignore_enoent= */ true);
94✔
2250
                }
2251

2252
        return 0;
2253
}
2254

2255
static int read_credential_lines(Context *c) {
113✔
2256
        _cleanup_free_ char *j = NULL;
113✔
2257
        const char *d;
113✔
2258
        int r;
113✔
2259

2260
        assert(c);
113✔
2261

2262
        r = get_credentials_dir(&d);
113✔
2263
        if (r == -ENXIO)
113✔
2264
                return 0;
2265
        if (r < 0)
1✔
2266
                return log_error_errno(r, "Failed to get credentials directory: %m");
×
2267

2268
        j = path_join(d, "sysusers.extra");
1✔
2269
        if (!j)
1✔
2270
                return log_oom();
×
2271

2272
        (void) read_config_file(c, j, /* ignore_enoent= */ true);
1✔
2273
        return 0;
2274
}
2275

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

2287
        Item *i;
113✔
2288
        int r;
113✔
2289

2290
        r = parse_argv(argc, argv);
113✔
2291
        if (r <= 0)
113✔
2292
                return r;
2293

2294
        log_setup();
113✔
2295

2296
        if (arg_cat_flags != CAT_CONFIG_OFF)
113✔
2297
                return cat_config();
×
2298

2299
        if (should_bypass("SYSTEMD_SYSUSERS"))
113✔
2300
                return 0;
2301

2302
        umask(0022);
113✔
2303

2304
        r = mac_init();
113✔
2305
        if (r < 0)
113✔
2306
                return r;
2307

2308
#ifndef STANDALONE
2309
        if (arg_image) {
113✔
2310
                assert(!arg_root);
×
2311

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

2328
                arg_root = strdup(mounted_dir);
×
2329
                if (!arg_root)
×
2330
                        return log_oom();
×
2331
        }
2332
#else
2333
        assert(!arg_image);
2334
#endif
2335

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

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

2351
        r = read_credential_lines(&c);
113✔
2352
        if (r < 0)
113✔
2353
                return r;
2354

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

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

2370
                c.login_defs_need_warning = true;
113✔
2371

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

2385
        r = add_implicit(&c);
113✔
2386
        if (r < 0)
113✔
2387
                return r;
2388

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

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

2399
        r = load_group_database(&c);
113✔
2400
        if (r < 0)
113✔
2401
                return log_error_errno(r, "Failed to read group database: %m");
×
2402

2403
        ORDERED_HASHMAP_FOREACH(i, c.groups)
489✔
2404
                (void) process_item(&c, i);
376✔
2405

2406
        ORDERED_HASHMAP_FOREACH(i, c.users)
412✔
2407
                (void) process_item(&c, i);
299✔
2408

2409
        return write_files(&c);
113✔
2410
}
2411

2412
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