]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/sysusers/sysusers.c
pid1: port unit namespacing to new /run/systemd/mount-rootfs dir
[thirdparty/systemd.git] / src / sysusers / sysusers.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
1b992147 2
3f6fd1ba 3#include <getopt.h>
932ad62b 4#include <utmp.h>
1b992147 5
b5efdb8a 6#include "alloc-util.h"
d6b4d1c7 7#include "build.h"
f461a28d 8#include "chase.h"
1b992147 9#include "conf-files.h"
28db6fbf 10#include "constants.h"
1b992147 11#include "copy.h"
99e9f896 12#include "creds-util.h"
0c3ee127 13#include "dissect-image.h"
3fa8a114 14#include "env-util.h"
a0f29c76 15#include "fd-util.h"
ee228be1 16#include "fileio.h"
f97b34a6 17#include "format-util.h"
dcd5c891 18#include "fs-util.h"
3f6fd1ba 19#include "hashmap.h"
99e9f896 20#include "libcrypt-util.h"
71da1673 21#include "main-func.h"
99e9f896 22#include "memory-util.h"
0c3ee127 23#include "mount-util.h"
d481b830 24#include "nscd-flush.h"
dcd5c891 25#include "pager.h"
614b022c 26#include "parse-argument.h"
3f6fd1ba 27#include "path-util.h"
294bf0c3 28#include "pretty-print.h"
3f6fd1ba 29#include "selinux-util.h"
0c3ee127 30#include "set.h"
07630cea 31#include "smack-util.h"
3f6fd1ba 32#include "specifier.h"
5f465fda 33#include "stat-util.h"
07630cea 34#include "string-util.h"
3f6fd1ba 35#include "strv.h"
bf819d3a 36#include "sync-util.h"
e4de7287 37#include "tmpfile-util-label.h"
b085d224 38#include "uid-alloc-range.h"
3f6fd1ba 39#include "uid-range.h"
a0f29c76 40#include "user-util.h"
3f6fd1ba 41#include "utf8.h"
1b992147
LP
42
43typedef enum ItemType {
9a5af4b7
ZJS
44 ADD_USER = 'u',
45 ADD_GROUP = 'g',
a12b0cc3 46 ADD_MEMBER = 'm',
9a5af4b7 47 ADD_RANGE = 'r',
1b992147 48} ItemType;
dcd5c891 49
9a5af4b7
ZJS
50static inline const char* item_type_to_string(ItemType t) {
51 switch (t) {
52 case ADD_USER:
53 return "user";
54 case ADD_GROUP:
55 return "group";
56 case ADD_MEMBER:
57 return "member";
58 case ADD_RANGE:
59 return "range";
60 default:
61 assert_not_reached();
62 }
63}
64
1b992147
LP
65typedef struct Item {
66 ItemType type;
67
68 char *name;
649916d3 69 char *group_name;
1b992147
LP
70 char *uid_path;
71 char *gid_path;
72 char *description;
7629889c 73 char *home;
7b1aaf66 74 char *shell;
1b992147
LP
75
76 gid_t gid;
77 uid_t uid;
78
9a87bdd7
ZJS
79 char *filename;
80 unsigned line;
81
616c5354 82 bool gid_set;
fb959f14 83
3f316701
ZJS
84 /* When set the group with the specified GID must exist
85 * and the check if a UID clashes with the GID is skipped.
fb959f14 86 */
616c5354 87 bool id_set_strict;
fb959f14 88
616c5354 89 bool uid_set;
1b992147 90
616c5354
ZJS
91 bool todo_user;
92 bool todo_group;
1b992147
LP
93} Item;
94
95static char *arg_root = NULL;
0c3ee127 96static char *arg_image = NULL;
ec0327d6 97static bool arg_cat_config = false;
d16a1c1b 98static const char *arg_replace = NULL;
64fe1095 99static bool arg_dry_run = false;
1b600bd5 100static bool arg_inline = false;
0221d68a 101static PagerFlags arg_pager_flags = 0;
84be0c71 102static ImagePolicy *arg_image_policy = NULL;
1b992147 103
5bc9c980
MV
104static OrderedHashmap *users = NULL, *groups = NULL;
105static OrderedHashmap *todo_uids = NULL, *todo_gids = NULL;
106static OrderedHashmap *members = NULL;
1b992147 107
71da1673
YW
108static Hashmap *database_by_uid = NULL, *database_by_username = NULL;
109static Hashmap *database_by_gid = NULL, *database_by_groupname = NULL;
110static Set *database_users = NULL, *database_groups = NULL;
1b992147 111
fed1e721 112static uid_t search_uid = UID_INVALID;
8530dc44 113static UidRange *uid_range = NULL;
1b992147 114
4b6f9b20
ZJS
115static UGIDAllocationRange login_defs = {};
116static bool login_defs_need_warning = false;
117
71da1673
YW
118STATIC_DESTRUCTOR_REGISTER(groups, ordered_hashmap_freep);
119STATIC_DESTRUCTOR_REGISTER(users, ordered_hashmap_freep);
120STATIC_DESTRUCTOR_REGISTER(members, ordered_hashmap_freep);
121STATIC_DESTRUCTOR_REGISTER(todo_uids, ordered_hashmap_freep);
122STATIC_DESTRUCTOR_REGISTER(todo_gids, ordered_hashmap_freep);
123STATIC_DESTRUCTOR_REGISTER(database_by_uid, hashmap_freep);
124STATIC_DESTRUCTOR_REGISTER(database_by_username, hashmap_freep);
125STATIC_DESTRUCTOR_REGISTER(database_users, set_free_freep);
126STATIC_DESTRUCTOR_REGISTER(database_by_gid, hashmap_freep);
127STATIC_DESTRUCTOR_REGISTER(database_by_groupname, hashmap_freep);
128STATIC_DESTRUCTOR_REGISTER(database_groups, set_free_freep);
8dcc66ce 129STATIC_DESTRUCTOR_REGISTER(uid_range, uid_range_freep);
71da1673 130STATIC_DESTRUCTOR_REGISTER(arg_root, freep);
0c3ee127 131STATIC_DESTRUCTOR_REGISTER(arg_image, freep);
84be0c71 132STATIC_DESTRUCTOR_REGISTER(arg_image_policy, image_policy_freep);
71da1673 133
08c7c321
ZJS
134static int errno_is_not_exists(int code) {
135 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
136 * not found. */
137 return IN_SET(code, 0, ENOENT, ESRCH, EBADF, EPERM);
138}
139
7519b880
ZJS
140/* Note: the lifetime of the compound literal is the immediately surrounding block,
141 * see C11 §6.5.2.5, and
142 * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */
143#define FORMAT_UID(is_set, uid) \
144 ((is_set) ? snprintf_ok((char[DECIMAL_STR_MAX(uid_t)]){}, DECIMAL_STR_MAX(uid_t), UID_FMT, uid) : "(unset)")
145#define FORMAT_GID(is_set, gid) \
146 ((is_set) ? snprintf_ok((char[DECIMAL_STR_MAX(gid_t)]){}, DECIMAL_STR_MAX(gid_t), GID_FMT, gid) : "(unset)")
147
4b6f9b20
ZJS
148static void maybe_emit_login_defs_warning(void) {
149 if (!login_defs_need_warning)
150 return;
151
152 if (login_defs.system_alloc_uid_min != SYSTEM_ALLOC_UID_MIN ||
153 login_defs.system_uid_max != SYSTEM_UID_MAX)
154 log_warning("login.defs specifies UID allocation range "UID_FMT"–"UID_FMT
155 " that is different than the built-in defaults ("UID_FMT"–"UID_FMT")",
156 login_defs.system_alloc_uid_min, login_defs.system_uid_max,
2676befc 157 (uid_t) SYSTEM_ALLOC_UID_MIN, (uid_t) SYSTEM_UID_MAX);
4b6f9b20
ZJS
158 if (login_defs.system_alloc_gid_min != SYSTEM_ALLOC_GID_MIN ||
159 login_defs.system_gid_max != SYSTEM_GID_MAX)
160 log_warning("login.defs specifies GID allocation range "GID_FMT"–"GID_FMT
161 " that is different than the built-in defaults ("GID_FMT"–"GID_FMT")",
162 login_defs.system_alloc_gid_min, login_defs.system_gid_max,
2676befc 163 (gid_t) SYSTEM_ALLOC_GID_MIN, (gid_t) SYSTEM_GID_MAX);
4b6f9b20
ZJS
164
165 login_defs_need_warning = false;
166}
167
1b992147
LP
168static int load_user_database(void) {
169 _cleanup_fclose_ FILE *f = NULL;
170 const char *passwd_path;
171 struct passwd *pw;
172 int r;
173
1d13f648 174 passwd_path = prefix_roota(arg_root, "/etc/passwd");
1b992147
LP
175 f = fopen(passwd_path, "re");
176 if (!f)
177 return errno == ENOENT ? 0 : -errno;
178
71da1673 179 r = hashmap_ensure_allocated(&database_by_username, &string_hash_ops);
1b992147
LP
180 if (r < 0)
181 return r;
182
71da1673 183 r = hashmap_ensure_allocated(&database_by_uid, NULL);
1b992147
LP
184 if (r < 0)
185 return r;
186
71da1673 187 r = set_ensure_allocated(&database_users, NULL);
1b992147
LP
188 if (r < 0)
189 return r;
190
100d5f6e 191 while ((r = fgetpwent_sane(f, &pw)) > 0) {
43e948ee 192 char *n;
340ac019 193 int k, q;
1b992147
LP
194
195 n = strdup(pw->pw_name);
196 if (!n)
197 return -ENOMEM;
198
71da1673
YW
199 k = set_put(database_users, n);
200 if (k < 0) {
1b992147
LP
201 free(n);
202 return k;
203 }
204
71da1673
YW
205 k = hashmap_put(database_by_username, n, UID_TO_PTR(pw->pw_uid));
206 if (k < 0 && k != -EEXIST)
207 return k;
1b992147 208
71da1673
YW
209 q = hashmap_put(database_by_uid, UID_TO_PTR(pw->pw_uid), n);
210 if (q < 0 && q != -EEXIST)
211 return q;
1b992147 212 }
100d5f6e 213 return r;
1b992147
LP
214}
215
216static int load_group_database(void) {
217 _cleanup_fclose_ FILE *f = NULL;
218 const char *group_path;
219 struct group *gr;
220 int r;
221
1d13f648 222 group_path = prefix_roota(arg_root, "/etc/group");
1b992147
LP
223 f = fopen(group_path, "re");
224 if (!f)
225 return errno == ENOENT ? 0 : -errno;
226
71da1673 227 r = hashmap_ensure_allocated(&database_by_groupname, &string_hash_ops);
1b992147
LP
228 if (r < 0)
229 return r;
230
71da1673 231 r = hashmap_ensure_allocated(&database_by_gid, NULL);
1b992147
LP
232 if (r < 0)
233 return r;
234
71da1673 235 r = set_ensure_allocated(&database_groups, NULL);
1b992147
LP
236 if (r < 0)
237 return r;
238
f030d36c 239 while ((r = fgetgrent_sane(f, &gr)) > 0) {
1b992147
LP
240 char *n;
241 int k, q;
242
243 n = strdup(gr->gr_name);
244 if (!n)
245 return -ENOMEM;
246
71da1673
YW
247 k = set_put(database_groups, n);
248 if (k < 0) {
1b992147
LP
249 free(n);
250 return k;
251 }
252
71da1673
YW
253 k = hashmap_put(database_by_groupname, n, GID_TO_PTR(gr->gr_gid));
254 if (k < 0 && k != -EEXIST)
255 return k;
1b992147 256
71da1673
YW
257 q = hashmap_put(database_by_gid, GID_TO_PTR(gr->gr_gid), n);
258 if (q < 0 && q != -EEXIST)
259 return q;
1b992147 260 }
f030d36c 261 return r;
1b992147
LP
262}
263
9f1c1940 264static int make_backup(const char *target, const char *x) {
62c03398 265 _cleanup_(unlink_and_freep) char *dst_tmp = NULL;
9f1c1940 266 _cleanup_fclose_ FILE *dst = NULL;
5bb1d7fb 267 _cleanup_close_ int src = -EBADF;
62c03398 268 const char *backup;
1b992147
LP
269 struct stat st;
270 int r;
271
62c03398
LP
272 assert(target);
273 assert(x);
274
1b992147
LP
275 src = open(x, O_RDONLY|O_CLOEXEC|O_NOCTTY);
276 if (src < 0) {
277 if (errno == ENOENT) /* No backup necessary... */
278 return 0;
279
280 return -errno;
281 }
282
283 if (fstat(src, &st) < 0)
284 return -errno;
285
62c03398 286 r = fopen_temporary_label(
47fb161e 287 target, /* The path for which to the look up the label */
62c03398 288 x, /* Where we want the file actually to end up */
47fb161e
ZJS
289 &dst, /* The temporary file we write to */
290 &dst_tmp);
9f1c1940
ZJS
291 if (r < 0)
292 return r;
1b992147 293
f5fbe71d 294 r = copy_bytes(src, fileno(dst), UINT64_MAX, COPY_REFLINK);
1b992147 295 if (r < 0)
62c03398 296 return r;
9f1c1940 297
63c372cb 298 backup = strjoina(x, "-");
9f1c1940 299
62c03398
LP
300 /* Copy over the access mask. Don't fail on chmod() or chown(). If it stays owned by us and/or
301 * unreadable by others, then it isn't too bad... */
b78d7f24 302 r = fchmod_and_chown_with_fallback(fileno(dst), dst_tmp, st.st_mode & 07777, st.st_uid, st.st_gid);
c039af23
YW
303 if (r < 0)
304 log_warning_errno(r, "Failed to change access mode or ownership of %s: %m", backup);
1b992147 305
62c03398 306 if (futimens(fileno(dst), (const struct timespec[2]) { st.st_atim, st.st_mtim }) < 0)
56f64d95 307 log_warning_errno(errno, "Failed to fix access and modification time of %s: %m", backup);
1b992147 308
62c03398 309 r = fsync_full(fileno(dst));
0675e94a 310 if (r < 0)
62c03398 311 return r;
0675e94a 312
62c03398
LP
313 if (rename(dst_tmp, backup) < 0)
314 return errno;
1b992147 315
7802194a 316 dst_tmp = mfree(dst_tmp); /* disable the unlink_and_freep() hook now that the file has been renamed */
1b992147 317 return 0;
1b992147
LP
318}
319
a12b0cc3
LP
320static int putgrent_with_members(const struct group *gr, FILE *group) {
321 char **a;
322
323 assert(gr);
324 assert(group);
325
5bc9c980 326 a = ordered_hashmap_get(members, gr->gr_name);
a12b0cc3
LP
327 if (a) {
328 _cleanup_strv_free_ char **l = NULL;
329 bool added = false;
a12b0cc3
LP
330
331 l = strv_copy(gr->gr_mem);
332 if (!l)
333 return -ENOMEM;
334
335 STRV_FOREACH(i, a) {
d29cc4d6 336 if (strv_contains(l, *i))
a12b0cc3
LP
337 continue;
338
339 if (strv_extend(&l, *i) < 0)
340 return -ENOMEM;
341
342 added = true;
343 }
344
345 if (added) {
346 struct group t;
100d5f6e 347 int r;
a12b0cc3
LP
348
349 strv_uniq(l);
350 strv_sort(l);
351
352 t = *gr;
353 t.gr_mem = l;
354
100d5f6e
FB
355 r = putgrent_sane(&t, group);
356 return r < 0 ? r : 1;
a12b0cc3
LP
357 }
358 }
359
100d5f6e 360 return putgrent_sane(gr, group);
a12b0cc3
LP
361}
362
349cc4a5 363#if ENABLE_GSHADOW
9ab315cc
LP
364static int putsgent_with_members(const struct sgrp *sg, FILE *gshadow) {
365 char **a;
366
367 assert(sg);
368 assert(gshadow);
369
5bc9c980 370 a = ordered_hashmap_get(members, sg->sg_namp);
9ab315cc
LP
371 if (a) {
372 _cleanup_strv_free_ char **l = NULL;
373 bool added = false;
9ab315cc
LP
374
375 l = strv_copy(sg->sg_mem);
376 if (!l)
377 return -ENOMEM;
378
379 STRV_FOREACH(i, a) {
d29cc4d6 380 if (strv_contains(l, *i))
9ab315cc
LP
381 continue;
382
383 if (strv_extend(&l, *i) < 0)
384 return -ENOMEM;
385
386 added = true;
387 }
388
389 if (added) {
390 struct sgrp t;
100d5f6e 391 int r;
9ab315cc
LP
392
393 strv_uniq(l);
394 strv_sort(l);
395
396 t = *sg;
397 t.sg_mem = l;
398
100d5f6e
FB
399 r = putsgent_sane(&t, gshadow);
400 return r < 0 ? r : 1;
9ab315cc
LP
401 }
402 }
403
100d5f6e 404 return putsgent_sane(sg, gshadow);
9ab315cc 405}
b14e1b43 406#endif
9ab315cc 407
5f465fda
ZJS
408static const char* pick_shell(const Item *i) {
409 if (i->type != ADD_USER)
410 return NULL;
411 if (i->shell)
412 return i->shell;
413 if (i->uid_set && i->uid == 0)
8a7adccb 414 return default_root_shell(arg_root);
5f465fda 415 return NOLOGIN;
7b1aaf66
ZJS
416}
417
b20b0b66
FB
418static int write_temporary_passwd(const char *passwd_path, FILE **tmpfile, char **tmpfile_path) {
419 _cleanup_fclose_ FILE *original = NULL, *passwd = NULL;
1dd98a71 420 _cleanup_(unlink_and_freep) char *passwd_tmp = NULL;
563dc6f8 421 struct passwd *pw = NULL;
1b992147
LP
422 Item *i;
423 int r;
424
98167876 425 if (ordered_hashmap_isempty(todo_uids))
b20b0b66 426 return 0;
1b992147 427
64fe1095 428 if (arg_dry_run) {
28e5e1e9 429 log_info("Would write /etc/passwd%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
64fe1095
ZJS
430 return 0;
431 }
432
b20b0b66
FB
433 r = fopen_temporary_label("/etc/passwd", passwd_path, &passwd, &passwd_tmp);
434 if (r < 0)
335f6ab4 435 return log_debug_errno(r, "Failed to open temporary copy of %s: %m", passwd_path);
b20b0b66
FB
436
437 original = fopen(passwd_path, "re");
438 if (original) {
b20b0b66 439
82855aa6
ZJS
440 /* Allow fallback path for when /proc is not mounted. On any normal system /proc will be
441 * mounted, but e.g. when 'dnf --installroot' is used, it might not be. There is no security
442 * relevance here, since the environment is ultimately trusted, and not requiring /proc makes
443 * it easier to depend on sysusers in packaging scripts and suchlike. */
444 r = copy_rights_with_fallback(fileno(original), fileno(passwd), passwd_tmp);
1b992147 445 if (r < 0)
335f6ab4
ZJS
446 return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
447 passwd_path, passwd_tmp);
1b992147 448
100d5f6e 449 while ((r = fgetpwent_sane(original, &pw)) > 0) {
5bc9c980 450 i = ordered_hashmap_get(users, pw->pw_name);
330d1def
ZJS
451 if (i && i->todo_user)
452 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
453 "%s: User \"%s\" already exists.",
454 passwd_path, pw->pw_name);
e3c72c21 455
330d1def
ZJS
456 if (ordered_hashmap_contains(todo_uids, UID_TO_PTR(pw->pw_uid)))
457 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
458 "%s: Detected collision for UID " UID_FMT ".",
459 passwd_path, pw->pw_uid);
b20b0b66 460
563dc6f8
FB
461 /* Make sure we keep the NIS entries (if any) at the end. */
462 if (IN_SET(pw->pw_name[0], '+', '-'))
463 break;
464
100d5f6e
FB
465 r = putpwent_sane(pw, passwd);
466 if (r < 0)
335f6ab4
ZJS
467 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
468 pw->pw_name);
b20b0b66 469 }
100d5f6e 470 if (r < 0)
335f6ab4 471 return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
1dd98a71
FB
472
473 } else {
474 if (errno != ENOENT)
335f6ab4 475 return log_debug_errno(errno, "Failed to open %s: %m", passwd_path);
1dd98a71 476 if (fchmod(fileno(passwd), 0644) < 0)
335f6ab4 477 return log_debug_errno(errno, "Failed to fchmod %s: %m", passwd_tmp);
b20b0b66
FB
478 }
479
90e74a66 480 ORDERED_HASHMAP_FOREACH(i, todo_uids) {
99e9f896
LP
481 _cleanup_free_ char *creds_shell = NULL, *cn = NULL;
482
b20b0b66
FB
483 struct passwd n = {
484 .pw_name = i->name,
485 .pw_uid = i->uid,
486 .pw_gid = i->gid,
d610e142 487 .pw_gecos = (char*) strempty(i->description),
1b992147 488
b20b0b66 489 /* "x" means the password is stored in the shadow file */
53c25ac9 490 .pw_passwd = (char*) PASSWORD_SEE_SHADOW,
a12b0cc3 491
b20b0b66 492 /* We default to the root directory as home */
636e72bc 493 .pw_dir = i->home ?: (char*) "/",
1b992147 494
b20b0b66
FB
495 /* Initialize the shell to nologin, with one exception:
496 * for root we patch in something special */
5f465fda 497 .pw_shell = (char*) pick_shell(i),
b20b0b66 498 };
9ab315cc 499
99e9f896
LP
500 /* Try to pick up the shell for this account via the credentials logic */
501 cn = strjoin("passwd.shell.", i->name);
502 if (!cn)
503 return -ENOMEM;
504
505 r = read_credential(cn, (void**) &creds_shell, NULL);
506 if (r < 0)
507 log_debug_errno(r, "Couldn't read credential '%s', ignoring: %m", cn);
508 else
509 n.pw_shell = creds_shell;
510
100d5f6e
FB
511 r = putpwent_sane(&n, passwd);
512 if (r < 0)
335f6ab4
ZJS
513 return log_debug_errno(r, "Failed to add new user \"%s\" to temporary passwd file: %m",
514 pw->pw_name);
b20b0b66
FB
515 }
516
563dc6f8
FB
517 /* Append the remaining NIS entries if any */
518 while (pw) {
100d5f6e
FB
519 r = putpwent_sane(pw, passwd);
520 if (r < 0)
335f6ab4
ZJS
521 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary passwd file: %m",
522 pw->pw_name);
563dc6f8 523
100d5f6e
FB
524 r = fgetpwent_sane(original, &pw);
525 if (r < 0)
335f6ab4 526 return log_debug_errno(r, "Failed to read %s: %m", passwd_path);
100d5f6e
FB
527 if (r == 0)
528 break;
563dc6f8 529 }
563dc6f8 530
19193b48 531 r = fflush_sync_and_check(passwd);
b20b0b66 532 if (r < 0)
335f6ab4 533 return log_debug_errno(r, "Failed to flush %s: %m", passwd_tmp);
b20b0b66 534
1cc6c93a
YW
535 *tmpfile = TAKE_PTR(passwd);
536 *tmpfile_path = TAKE_PTR(passwd_tmp);
537
b20b0b66 538 return 0;
b20b0b66
FB
539}
540
3fa8a114
JSMR
541static usec_t epoch_or_now(void) {
542 uint64_t epoch;
543
544 if (getenv_uint64_secure("SOURCE_DATE_EPOCH", &epoch) >= 0) {
545 if (epoch > UINT64_MAX/USEC_PER_SEC) /* Overflow check */
546 return USEC_INFINITY;
547 return (usec_t) epoch * USEC_PER_SEC;
548 }
549
550 return now(CLOCK_REALTIME);
551}
552
b20b0b66
FB
553static int write_temporary_shadow(const char *shadow_path, FILE **tmpfile, char **tmpfile_path) {
554 _cleanup_fclose_ FILE *original = NULL, *shadow = NULL;
1dd98a71 555 _cleanup_(unlink_and_freep) char *shadow_tmp = NULL;
19ec7de2 556 struct spwd *sp = NULL;
b20b0b66
FB
557 long lstchg;
558 Item *i;
559 int r;
560
98167876 561 if (ordered_hashmap_isempty(todo_uids))
b20b0b66
FB
562 return 0;
563
64fe1095 564 if (arg_dry_run) {
28e5e1e9 565 log_info("Would write /etc/shadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
64fe1095
ZJS
566 return 0;
567 }
568
b20b0b66
FB
569 r = fopen_temporary_label("/etc/shadow", shadow_path, &shadow, &shadow_tmp);
570 if (r < 0)
335f6ab4 571 return log_debug_errno(r, "Failed to open temporary copy of %s: %m", shadow_path);
9ab315cc 572
3fa8a114 573 lstchg = (long) (epoch_or_now() / USEC_PER_DAY);
b20b0b66
FB
574
575 original = fopen(shadow_path, "re");
576 if (original) {
b20b0b66 577
82855aa6 578 r = copy_rights_with_fallback(fileno(original), fileno(shadow), shadow_tmp);
9ab315cc 579 if (r < 0)
335f6ab4
ZJS
580 return log_debug_errno(r, "Failed to copy permissions from %s to %s: %m",
581 shadow_path, shadow_tmp);
9ab315cc 582
100d5f6e 583 while ((r = fgetspent_sane(original, &sp)) > 0) {
5bc9c980 584 i = ordered_hashmap_get(users, sp->sp_namp);
b20b0b66
FB
585 if (i && i->todo_user) {
586 /* we will update the existing entry */
587 sp->sp_lstchg = lstchg;
e3c72c21 588
b20b0b66
FB
589 /* only the /etc/shadow stage is left, so we can
590 * safely remove the item from the todo set */
591 i->todo_user = false;
5bc9c980 592 ordered_hashmap_remove(todo_uids, UID_TO_PTR(i->uid));
9ab315cc 593 }
b20b0b66 594
19ec7de2
FB
595 /* Make sure we keep the NIS entries (if any) at the end. */
596 if (IN_SET(sp->sp_namp[0], '+', '-'))
597 break;
598
100d5f6e
FB
599 r = putspent_sane(sp, shadow);
600 if (r < 0)
335f6ab4
ZJS
601 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
602 sp->sp_namp);
603
b20b0b66 604 }
100d5f6e 605 if (r < 0)
335f6ab4 606 return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
1dd98a71
FB
607
608 } else {
609 if (errno != ENOENT)
335f6ab4 610 return log_debug_errno(errno, "Failed to open %s: %m", shadow_path);
1dd98a71 611 if (fchmod(fileno(shadow), 0000) < 0)
335f6ab4 612 return log_debug_errno(errno, "Failed to fchmod %s: %m", shadow_tmp);
b20b0b66 613 }
9ab315cc 614
90e74a66 615 ORDERED_HASHMAP_FOREACH(i, todo_uids) {
99e9f896 616 _cleanup_(erase_and_freep) char *creds_password = NULL;
ff86850b 617 bool is_hashed;
99e9f896 618
b20b0b66
FB
619 struct spwd n = {
620 .sp_namp = i->name,
53c25ac9 621 .sp_pwdp = (char*) PASSWORD_LOCKED_AND_INVALID,
b20b0b66
FB
622 .sp_lstchg = lstchg,
623 .sp_min = -1,
624 .sp_max = -1,
625 .sp_warn = -1,
626 .sp_inact = -1,
12c82937 627 .sp_expire = -1,
f5fbe71d 628 .sp_flag = ULONG_MAX, /* this appears to be what everybody does ... */
b20b0b66 629 };
9ab315cc 630
ff86850b
LN
631 r = get_credential_user_password(i->name, &creds_password, &is_hashed);
632 if (r < 0)
633 log_debug_errno(r, "Couldn't read password credential for user '%s', ignoring: %m", i->name);
99e9f896 634
ff86850b
LN
635 if (creds_password && !is_hashed) {
636 _cleanup_(erase_and_freep) char* plaintext_password = TAKE_PTR(creds_password);
637 r = hash_password(plaintext_password, &creds_password);
99e9f896 638 if (r < 0)
ff86850b
LN
639 return log_debug_errno(r, "Failed to hash password: %m");
640 }
99e9f896
LP
641
642 if (creds_password)
643 n.sp_pwdp = creds_password;
644
100d5f6e
FB
645 r = putspent_sane(&n, shadow);
646 if (r < 0)
335f6ab4
ZJS
647 return log_debug_errno(r, "Failed to add new user \"%s\" to temporary shadow file: %m",
648 sp->sp_namp);
1b992147 649 }
19ec7de2
FB
650
651 /* Append the remaining NIS entries if any */
652 while (sp) {
100d5f6e
FB
653 r = putspent_sane(sp, shadow);
654 if (r < 0)
335f6ab4
ZJS
655 return log_debug_errno(r, "Failed to add existing user \"%s\" to temporary shadow file: %m",
656 sp->sp_namp);
19ec7de2 657
100d5f6e
FB
658 r = fgetspent_sane(original, &sp);
659 if (r < 0)
335f6ab4 660 return log_debug_errno(r, "Failed to read %s: %m", shadow_path);
100d5f6e
FB
661 if (r == 0)
662 break;
19ec7de2
FB
663 }
664 if (!IN_SET(errno, 0, ENOENT))
665 return -errno;
1b992147 666
0675e94a 667 r = fflush_sync_and_check(shadow);
b20b0b66 668 if (r < 0)
335f6ab4 669 return log_debug_errno(r, "Failed to flush %s: %m", shadow_tmp);
b20b0b66 670
1cc6c93a
YW
671 *tmpfile = TAKE_PTR(shadow);
672 *tmpfile_path = TAKE_PTR(shadow_tmp);
673
b20b0b66 674 return 0;
b20b0b66 675}
1b992147 676
b20b0b66
FB
677static int write_temporary_group(const char *group_path, FILE **tmpfile, char **tmpfile_path) {
678 _cleanup_fclose_ FILE *original = NULL, *group = NULL;
1dd98a71 679 _cleanup_(unlink_and_freep) char *group_tmp = NULL;
b20b0b66 680 bool group_changed = false;
563dc6f8 681 struct group *gr = NULL;
b20b0b66
FB
682 Item *i;
683 int r;
1b992147 684
98167876 685 if (ordered_hashmap_isempty(todo_gids) && ordered_hashmap_isempty(members))
b20b0b66 686 return 0;
e3c72c21 687
64fe1095 688 if (arg_dry_run) {
28e5e1e9 689 log_info("Would write /etc/group%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
64fe1095
ZJS
690 return 0;
691 }
692
b20b0b66
FB
693 r = fopen_temporary_label("/etc/group", group_path, &group, &group_tmp);
694 if (r < 0)
4c795066 695 return log_error_errno(r, "Failed to open temporary copy of %s: %m", group_path);
b20b0b66
FB
696
697 original = fopen(group_path, "re");
698 if (original) {
b20b0b66 699
82855aa6 700 r = copy_rights_with_fallback(fileno(original), fileno(group), group_tmp);
b20b0b66 701 if (r < 0)
4c795066 702 return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
335f6ab4 703 group_path, group_tmp);
b20b0b66 704
100d5f6e 705 while ((r = fgetgrent_sane(original, &gr)) > 0) {
b20b0b66
FB
706 /* Safety checks against name and GID collisions. Normally,
707 * this should be unnecessary, but given that we look at the
708 * entries anyway here, let's make an extra verification
709 * step that we don't generate duplicate entries. */
710
5bc9c980 711 i = ordered_hashmap_get(groups, gr->gr_name);
330d1def
ZJS
712 if (i && i->todo_group)
713 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
714 "%s: Group \"%s\" already exists.",
715 group_path, gr->gr_name);
b20b0b66 716
330d1def
ZJS
717 if (ordered_hashmap_contains(todo_gids, GID_TO_PTR(gr->gr_gid)))
718 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
719 "%s: Detected collision for GID " GID_FMT ".",
720 group_path, gr->gr_gid);
1b992147 721
563dc6f8
FB
722 /* Make sure we keep the NIS entries (if any) at the end. */
723 if (IN_SET(gr->gr_name[0], '+', '-'))
724 break;
725
b20b0b66
FB
726 r = putgrent_with_members(gr, group);
727 if (r < 0)
4c795066 728 return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
335f6ab4 729 gr->gr_name);
b20b0b66
FB
730 if (r > 0)
731 group_changed = true;
b20b0b66 732 }
100d5f6e 733 if (r < 0)
4c795066 734 return log_error_errno(r, "Failed to read %s: %m", group_path);
1dd98a71
FB
735
736 } else {
737 if (errno != ENOENT)
4c795066 738 return log_error_errno(errno, "Failed to open %s: %m", group_path);
1dd98a71 739 if (fchmod(fileno(group), 0644) < 0)
4c795066 740 return log_error_errno(errno, "Failed to fchmod %s: %m", group_tmp);
b20b0b66 741 }
7629889c 742
90e74a66 743 ORDERED_HASHMAP_FOREACH(i, todo_gids) {
b20b0b66
FB
744 struct group n = {
745 .gr_name = i->name,
746 .gr_gid = i->gid,
53c25ac9 747 .gr_passwd = (char*) PASSWORD_SEE_SHADOW,
b20b0b66 748 };
1b992147 749
b20b0b66
FB
750 r = putgrent_with_members(&n, group);
751 if (r < 0)
4c795066 752 return log_error_errno(r, "Failed to add new group \"%s\" to temporary group file: %m",
335f6ab4 753 gr->gr_name);
7629889c 754
b20b0b66
FB
755 group_changed = true;
756 }
1b992147 757
563dc6f8
FB
758 /* Append the remaining NIS entries if any */
759 while (gr) {
100d5f6e
FB
760 r = putgrent_sane(gr, group);
761 if (r < 0)
4c795066 762 return log_error_errno(r, "Failed to add existing group \"%s\" to temporary group file: %m",
335f6ab4 763 gr->gr_name);
563dc6f8 764
100d5f6e
FB
765 r = fgetgrent_sane(original, &gr);
766 if (r < 0)
4c795066 767 return log_error_errno(r, "Failed to read %s: %m", group_path);
100d5f6e
FB
768 if (r == 0)
769 break;
563dc6f8 770 }
563dc6f8 771
0675e94a 772 r = fflush_sync_and_check(group);
b20b0b66 773 if (r < 0)
4c795066 774 return log_error_errno(r, "Failed to flush %s: %m", group_tmp);
1b992147 775
b20b0b66 776 if (group_changed) {
1cc6c93a
YW
777 *tmpfile = TAKE_PTR(group);
778 *tmpfile_path = TAKE_PTR(group_tmp);
b20b0b66
FB
779 }
780 return 0;
b20b0b66
FB
781}
782
783static int write_temporary_gshadow(const char * gshadow_path, FILE **tmpfile, char **tmpfile_path) {
349cc4a5 784#if ENABLE_GSHADOW
b20b0b66 785 _cleanup_fclose_ FILE *original = NULL, *gshadow = NULL;
1dd98a71 786 _cleanup_(unlink_and_freep) char *gshadow_tmp = NULL;
b20b0b66 787 bool group_changed = false;
b20b0b66
FB
788 Item *i;
789 int r;
790
98167876 791 if (ordered_hashmap_isempty(todo_gids) && ordered_hashmap_isempty(members))
b20b0b66
FB
792 return 0;
793
64fe1095 794 if (arg_dry_run) {
28e5e1e9 795 log_info("Would write /etc/gshadow%s", special_glyph(SPECIAL_GLYPH_ELLIPSIS));
64fe1095
ZJS
796 return 0;
797 }
798
b20b0b66
FB
799 r = fopen_temporary_label("/etc/gshadow", gshadow_path, &gshadow, &gshadow_tmp);
800 if (r < 0)
4c795066 801 return log_error_errno(r, "Failed to open temporary copy of %s: %m", gshadow_path);
9ab315cc 802
b20b0b66
FB
803 original = fopen(gshadow_path, "re");
804 if (original) {
805 struct sgrp *sg;
806
82855aa6 807 r = copy_rights_with_fallback(fileno(original), fileno(gshadow), gshadow_tmp);
1b992147 808 if (r < 0)
4c795066 809 return log_error_errno(r, "Failed to copy permissions from %s to %s: %m",
335f6ab4 810 gshadow_path, gshadow_tmp);
9ab315cc 811
100d5f6e 812 while ((r = fgetsgent_sane(original, &sg)) > 0) {
c5abf225 813
5bc9c980 814 i = ordered_hashmap_get(groups, sg->sg_namp);
330d1def
ZJS
815 if (i && i->todo_group)
816 return log_error_errno(SYNTHETIC_ERRNO(EEXIST),
817 "%s: Group \"%s\" already exists.",
818 gshadow_path, sg->sg_namp);
9ab315cc 819
b20b0b66 820 r = putsgent_with_members(sg, gshadow);
fff19499 821 if (r < 0)
4c795066 822 return log_error_errno(r, "Failed to add existing group \"%s\" to temporary gshadow file: %m",
335f6ab4 823 sg->sg_namp);
b20b0b66
FB
824 if (r > 0)
825 group_changed = true;
b20b0b66 826 }
100d5f6e
FB
827 if (r < 0)
828 return r;
1dd98a71
FB
829
830 } else {
831 if (errno != ENOENT)
4c795066 832 return log_error_errno(errno, "Failed to open %s: %m", gshadow_path);
1dd98a71 833 if (fchmod(fileno(gshadow), 0000) < 0)
4c795066 834 return log_error_errno(errno, "Failed to fchmod %s: %m", gshadow_tmp);
b20b0b66 835 }
9ab315cc 836
90e74a66 837 ORDERED_HASHMAP_FOREACH(i, todo_gids) {
b20b0b66
FB
838 struct sgrp n = {
839 .sg_namp = i->name,
53c25ac9 840 .sg_passwd = (char*) PASSWORD_LOCKED_AND_INVALID,
b20b0b66 841 };
9ab315cc 842
b20b0b66 843 r = putsgent_with_members(&n, gshadow);
9ab315cc 844 if (r < 0)
4c795066 845 return log_error_errno(r, "Failed to add new group \"%s\" to temporary gshadow file: %m",
335f6ab4 846 n.sg_namp);
b20b0b66
FB
847
848 group_changed = true;
9ab315cc
LP
849 }
850
0675e94a 851 r = fflush_sync_and_check(gshadow);
b20b0b66 852 if (r < 0)
4c795066 853 return log_error_errno(r, "Failed to flush %s: %m", gshadow_tmp);
b20b0b66 854
9ab315cc 855 if (group_changed) {
1cc6c93a
YW
856 *tmpfile = TAKE_PTR(gshadow);
857 *tmpfile_path = TAKE_PTR(gshadow_tmp);
b20b0b66 858 }
b14e1b43 859#endif
62d1c93a 860 return 0;
b20b0b66
FB
861}
862
863static int write_files(void) {
b20b0b66 864 _cleanup_fclose_ FILE *passwd = NULL, *group = NULL, *shadow = NULL, *gshadow = NULL;
1dd98a71 865 _cleanup_(unlink_and_freep) char *passwd_tmp = NULL, *group_tmp = NULL, *shadow_tmp = NULL, *gshadow_tmp = NULL;
62d1c93a 866 const char *passwd_path, *shadow_path, *group_path, *gshadow_path;
b20b0b66
FB
867 int r;
868
869 passwd_path = prefix_roota(arg_root, "/etc/passwd");
870 shadow_path = prefix_roota(arg_root, "/etc/shadow");
871 group_path = prefix_roota(arg_root, "/etc/group");
872 gshadow_path = prefix_roota(arg_root, "/etc/gshadow");
873
874 r = write_temporary_group(group_path, &group, &group_tmp);
875 if (r < 0)
1dd98a71 876 return r;
b20b0b66
FB
877
878 r = write_temporary_gshadow(gshadow_path, &gshadow, &gshadow_tmp);
879 if (r < 0)
1dd98a71 880 return r;
b20b0b66
FB
881
882 r = write_temporary_passwd(passwd_path, &passwd, &passwd_tmp);
883 if (r < 0)
1dd98a71 884 return r;
b20b0b66
FB
885
886 r = write_temporary_shadow(shadow_path, &shadow, &shadow_tmp);
887 if (r < 0)
1dd98a71 888 return r;
b20b0b66
FB
889
890 /* Make a backup of the old files */
891 if (group) {
892 r = make_backup("/etc/group", group_path);
893 if (r < 0)
4c795066 894 return log_error_errno(r, "Failed to make backup %s: %m", group_path);
b20b0b66
FB
895 }
896 if (gshadow) {
897 r = make_backup("/etc/gshadow", gshadow_path);
898 if (r < 0)
4c795066 899 return log_error_errno(r, "Failed to make backup %s: %m", gshadow_path);
1b992147
LP
900 }
901
902 if (passwd) {
9f1c1940 903 r = make_backup("/etc/passwd", passwd_path);
1b992147 904 if (r < 0)
4c795066 905 return log_error_errno(r, "Failed to make backup %s: %m", passwd_path);
1b992147 906 }
9ab315cc
LP
907 if (shadow) {
908 r = make_backup("/etc/shadow", shadow_path);
909 if (r < 0)
4c795066 910 return log_error_errno(r, "Failed to make backup %s: %m", shadow_path);
9ab315cc 911 }
1b992147
LP
912
913 /* And make the new files count */
b20b0b66 914 if (group) {
2da3dc69 915 r = rename_and_apply_smack_floor_label(group_tmp, group_path);
b20b0b66 916 if (r < 0)
4c795066 917 return log_error_errno(r, "Failed to rename %s to %s: %m",
335f6ab4 918 group_tmp, group_path);
b20b0b66 919 group_tmp = mfree(group_tmp);
d481b830
FB
920
921 if (!arg_root && !arg_image)
922 (void) nscd_flush_cache(STRV_MAKE("group"));
b20b0b66
FB
923 }
924 if (gshadow) {
2da3dc69 925 r = rename_and_apply_smack_floor_label(gshadow_tmp, gshadow_path);
b20b0b66 926 if (r < 0)
4c795066 927 return log_error_errno(r, "Failed to rename %s to %s: %m",
335f6ab4 928 gshadow_tmp, gshadow_path);
1b992147 929
b20b0b66 930 gshadow_tmp = mfree(gshadow_tmp);
1b992147
LP
931 }
932
933 if (passwd) {
2da3dc69 934 r = rename_and_apply_smack_floor_label(passwd_tmp, passwd_path);
c02e7b1e 935 if (r < 0)
4c795066 936 return log_error_errno(r, "Failed to rename %s to %s: %m",
335f6ab4 937 passwd_tmp, passwd_path);
1b992147 938
97b11eed 939 passwd_tmp = mfree(passwd_tmp);
d481b830
FB
940
941 if (!arg_root && !arg_image)
942 (void) nscd_flush_cache(STRV_MAKE("passwd"));
1b992147 943 }
9ab315cc 944 if (shadow) {
2da3dc69 945 r = rename_and_apply_smack_floor_label(shadow_tmp, shadow_path);
c02e7b1e 946 if (r < 0)
4c795066 947 return log_error_errno(r, "Failed to rename %s to %s: %m",
335f6ab4 948 shadow_tmp, shadow_path);
9ab315cc 949
97b11eed 950 shadow_tmp = mfree(shadow_tmp);
9ab315cc 951 }
1b992147 952
1dd98a71 953 return 0;
1b992147
LP
954}
955
b9ee05c2 956static int uid_is_ok(uid_t uid, const char *name, bool check_with_gid) {
1b992147
LP
957
958 /* Let's see if we already have assigned the UID a second time */
5bc9c980 959 if (ordered_hashmap_get(todo_uids, UID_TO_PTR(uid)))
1b992147
LP
960 return 0;
961
962 /* Try to avoid using uids that are already used by a group
963 * that doesn't have the same name as our new user. */
b9ee05c2 964 if (check_with_gid) {
62d1c93a
ZJS
965 Item *i;
966
b9ee05c2
MV
967 i = ordered_hashmap_get(todo_gids, GID_TO_PTR(uid));
968 if (i && !streq(i->name, name))
969 return 0;
970 }
1b992147
LP
971
972 /* Let's check the files directly */
71da1673 973 if (hashmap_contains(database_by_uid, UID_TO_PTR(uid)))
1b992147
LP
974 return 0;
975
b9ee05c2 976 if (check_with_gid) {
62d1c93a
ZJS
977 const char *n;
978
71da1673 979 n = hashmap_get(database_by_gid, GID_TO_PTR(uid));
b9ee05c2
MV
980 if (n && !streq(n, name))
981 return 0;
982 }
1b992147
LP
983
984 /* Let's also check via NSS, to avoid UID clashes over LDAP and such, just in case */
985 if (!arg_root) {
62d1c93a
ZJS
986 struct passwd *p;
987 struct group *g;
988
1b992147
LP
989 errno = 0;
990 p = getpwuid(uid);
991 if (p)
992 return 0;
b0284aba 993 if (!IN_SET(errno, 0, ENOENT))
1b992147
LP
994 return -errno;
995
b9ee05c2
MV
996 if (check_with_gid) {
997 errno = 0;
998 g = getgrgid((gid_t) uid);
999 if (g) {
1000 if (!streq(g->gr_name, name))
1001 return 0;
1002 } else if (!IN_SET(errno, 0, ENOENT))
1003 return -errno;
1004 }
1b992147
LP
1005 }
1006
1007 return 1;
1008}
1009
1010static int root_stat(const char *p, struct stat *st) {
1011 const char *fix;
1012
1d13f648 1013 fix = prefix_roota(arg_root, p);
7c248223 1014 return RET_NERRNO(stat(fix, st));
1b992147
LP
1015}
1016
905ec0c0 1017static int read_id_from_file(Item *i, uid_t *ret_uid, gid_t *ret_gid) {
1b992147
LP
1018 struct stat st;
1019 bool found_uid = false, found_gid = false;
56d21cde
PDS
1020 uid_t uid = 0;
1021 gid_t gid = 0;
1b992147
LP
1022
1023 assert(i);
1024
3f316701 1025 /* First, try to get the GID directly */
905ec0c0 1026 if (ret_gid && i->gid_path && root_stat(i->gid_path, &st) >= 0) {
1b992147
LP
1027 gid = st.st_gid;
1028 found_gid = true;
1029 }
1030
3f316701 1031 /* Then, try to get the UID directly */
905ec0c0 1032 if ((ret_uid || (ret_gid && !found_gid))
1b992147
LP
1033 && i->uid_path
1034 && root_stat(i->uid_path, &st) >= 0) {
1035
1036 uid = st.st_uid;
1037 found_uid = true;
1038
3f316701 1039 /* If we need the gid, but had no success yet, also derive it from the UID path */
905ec0c0 1040 if (ret_gid && !found_gid) {
1b992147
LP
1041 gid = st.st_gid;
1042 found_gid = true;
1043 }
1044 }
1045
3f316701 1046 /* If that didn't work yet, then let's reuse the GID as UID */
905ec0c0 1047 if (ret_uid && !found_uid && i->gid_path) {
1b992147
LP
1048
1049 if (found_gid) {
1050 uid = (uid_t) gid;
1051 found_uid = true;
1052 } else if (root_stat(i->gid_path, &st) >= 0) {
1053 uid = (uid_t) st.st_gid;
1054 found_uid = true;
1055 }
1056 }
1057
905ec0c0 1058 if (ret_uid) {
1b992147
LP
1059 if (!found_uid)
1060 return 0;
1061
905ec0c0 1062 *ret_uid = uid;
1b992147
LP
1063 }
1064
905ec0c0 1065 if (ret_gid) {
1b992147
LP
1066 if (!found_gid)
1067 return 0;
1068
905ec0c0 1069 *ret_gid = gid;
1b992147
LP
1070 }
1071
1072 return 1;
1073}
1074
1075static int add_user(Item *i) {
1076 void *z;
1077 int r;
1078
1079 assert(i);
1080
1081 /* Check the database directly */
71da1673 1082 z = hashmap_get(database_by_username, i->name);
1b992147
LP
1083 if (z) {
1084 log_debug("User %s already exists.", i->name);
c1b6b04f 1085 i->uid = PTR_TO_UID(z);
1b992147
LP
1086 i->uid_set = true;
1087 return 0;
1088 }
1089
1090 if (!arg_root) {
1091 struct passwd *p;
1b992147
LP
1092
1093 /* Also check NSS */
1094 errno = 0;
1095 p = getpwnam(i->name);
1096 if (p) {
1097 log_debug("User %s already exists.", i->name);
1098 i->uid = p->pw_uid;
1099 i->uid_set = true;
1100
2fc09a9c
DM
1101 r = free_and_strdup(&i->description, p->pw_gecos);
1102 if (r < 0)
1103 return log_oom();
1104
1b992147
LP
1105 return 0;
1106 }
08c7c321 1107 if (!errno_is_not_exists(errno))
4a62c710 1108 return log_error_errno(errno, "Failed to check if user %s already exists: %m", i->name);
1b992147
LP
1109 }
1110
3f316701 1111 /* Try to use the suggested numeric UID */
1b992147 1112 if (i->uid_set) {
b9ee05c2 1113 r = uid_is_ok(i->uid, i->name, !i->id_set_strict);
f647962d 1114 if (r < 0)
3f316701 1115 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
1b992147 1116 if (r == 0) {
5374bc7c 1117 log_info("Suggested user ID " UID_FMT " for %s already used.", i->uid, i->name);
1b992147
LP
1118 i->uid_set = false;
1119 }
1120 }
1121
1122 /* If that didn't work, try to read it from the specified path */
1123 if (!i->uid_set) {
1124 uid_t c;
1125
1126 if (read_id_from_file(i, &c, NULL) > 0) {
1127
8dcc66ce 1128 if (c <= 0 || !uid_range_contains(uid_range, c))
1b992147
LP
1129 log_debug("User ID " UID_FMT " of file not suitable for %s.", c, i->name);
1130 else {
b9ee05c2 1131 r = uid_is_ok(c, i->name, true);
f647962d 1132 if (r < 0)
3f316701 1133 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
f647962d 1134 else if (r > 0) {
1b992147
LP
1135 i->uid = c;
1136 i->uid_set = true;
1137 } else
1138 log_debug("User ID " UID_FMT " of file for %s is already used.", c, i->name);
1139 }
1140 }
1141 }
1142
b938cb90 1143 /* Otherwise, try to reuse the group ID */
1b992147 1144 if (!i->uid_set && i->gid_set) {
b9ee05c2 1145 r = uid_is_ok((uid_t) i->gid, i->name, true);
f647962d 1146 if (r < 0)
3f316701 1147 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
1b992147
LP
1148 if (r > 0) {
1149 i->uid = (uid_t) i->gid;
1150 i->uid_set = true;
1151 }
1152 }
1153
1154 /* And if that didn't work either, let's try to find a free one */
1155 if (!i->uid_set) {
4b6f9b20
ZJS
1156 maybe_emit_login_defs_warning();
1157
8530dc44 1158 for (;;) {
8dcc66ce 1159 r = uid_range_next_lower(uid_range, &search_uid);
330d1def
ZJS
1160 if (r < 0)
1161 return log_error_errno(r, "No free user ID available for %s.", i->name);
1b992147 1162
b9ee05c2 1163 r = uid_is_ok(search_uid, i->name, true);
f647962d 1164 if (r < 0)
3f316701 1165 return log_error_errno(r, "Failed to verify UID " UID_FMT ": %m", i->uid);
f647962d 1166 else if (r > 0)
1b992147
LP
1167 break;
1168 }
1169
1b992147
LP
1170 i->uid_set = true;
1171 i->uid = search_uid;
1b992147
LP
1172 }
1173
1dfb9321
SS
1174 r = ordered_hashmap_ensure_put(&todo_uids, NULL, UID_TO_PTR(i->uid), i);
1175 if (r == -EEXIST)
3f316701 1176 return log_error_errno(r, "Requested user %s with UID " UID_FMT " and gid" GID_FMT " to be created is duplicated "
1dfb9321
SS
1177 "or conflicts with another user.", i->name, i->uid, i->gid);
1178 if (r == -ENOMEM)
1b992147 1179 return log_oom();
1b992147 1180 if (r < 0)
3f316701 1181 return log_error_errno(r, "Failed to store user %s with UID " UID_FMT " and GID " GID_FMT " to be created: %m",
1dfb9321 1182 i->name, i->uid, i->gid);
1b992147 1183
c1b6b04f 1184 i->todo_user = true;
9a5af4b7 1185 log_info("Creating user '%s' (%s) with UID " UID_FMT " and GID " GID_FMT ".",
62d1c93a 1186 i->name, strna(i->description), i->uid, i->gid);
1b992147
LP
1187
1188 return 0;
1189}
1190
4ae3e8c9 1191static int gid_is_ok(gid_t gid, const char *groupname, bool check_with_uid) {
1b992147
LP
1192 struct group *g;
1193 struct passwd *p;
4ae3e8c9
LB
1194 Item *user;
1195 char *username;
1196
1197 assert(groupname);
1b992147 1198
5bc9c980 1199 if (ordered_hashmap_get(todo_gids, GID_TO_PTR(gid)))
1b992147
LP
1200 return 0;
1201
1202 /* Avoid reusing gids that are already used by a different user */
4ae3e8c9
LB
1203 if (check_with_uid) {
1204 user = ordered_hashmap_get(todo_uids, UID_TO_PTR(gid));
1205 if (user && !streq(user->name, groupname))
1206 return 0;
1207 }
1b992147 1208
71da1673 1209 if (hashmap_contains(database_by_gid, GID_TO_PTR(gid)))
1b992147
LP
1210 return 0;
1211
4ae3e8c9
LB
1212 if (check_with_uid) {
1213 username = hashmap_get(database_by_uid, UID_TO_PTR(gid));
1214 if (username && !streq(username, groupname))
1215 return 0;
1216 }
1b992147
LP
1217
1218 if (!arg_root) {
1219 errno = 0;
1220 g = getgrgid(gid);
1221 if (g)
1222 return 0;
b0284aba 1223 if (!IN_SET(errno, 0, ENOENT))
1b992147
LP
1224 return -errno;
1225
6b6e45eb
LB
1226 if (check_with_uid) {
1227 errno = 0;
1228 p = getpwuid((uid_t) gid);
1229 if (p)
1230 return 0;
1231 if (!IN_SET(errno, 0, ENOENT))
1232 return -errno;
1233 }
1b992147
LP
1234 }
1235
1236 return 1;
1237}
1238
649916d3 1239static int get_gid_by_name(const char *name, gid_t *gid) {
1b992147 1240 void *z;
1b992147 1241
649916d3 1242 assert(gid);
1b992147
LP
1243
1244 /* Check the database directly */
649916d3 1245 z = hashmap_get(database_by_groupname, name);
1b992147 1246 if (z) {
649916d3 1247 *gid = PTR_TO_GID(z);
1b992147
LP
1248 return 0;
1249 }
1250
1251 /* Also check NSS */
1252 if (!arg_root) {
1253 struct group *g;
1254
1255 errno = 0;
649916d3 1256 g = getgrnam(name);
1b992147 1257 if (g) {
649916d3 1258 *gid = g->gr_gid;
1b992147
LP
1259 return 0;
1260 }
08c7c321 1261 if (!errno_is_not_exists(errno))
649916d3
DM
1262 return log_error_errno(errno, "Failed to check if group %s already exists: %m", name);
1263 }
1264
1265 return -ENOENT;
1266}
1267
1268static int add_group(Item *i) {
1269 int r;
1270
1271 assert(i);
1272
1273 r = get_gid_by_name(i->name, &i->gid);
1274 if (r != -ENOENT) {
1275 if (r < 0)
1276 return r;
1277 log_debug("Group %s already exists.", i->name);
1278 i->gid_set = true;
1279 return 0;
1b992147
LP
1280 }
1281
3f316701 1282 /* Try to use the suggested numeric GID */
1b992147 1283 if (i->gid_set) {
4ae3e8c9 1284 r = gid_is_ok(i->gid, i->name, false);
f647962d 1285 if (r < 0)
3f316701 1286 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
b9ee05c2 1287 if (i->id_set_strict) {
3f316701
ZJS
1288 /* If we require the GID to already exist we can return here:
1289 * r > 0: means the GID does not exist -> fail
1290 * r == 0: means the GID exists -> nothing more to do.
28e7fad7 1291 */
baaa35ad
ZJS
1292 if (r > 0)
1293 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
c0f86d66 1294 "Failed to create %s: please create GID " GID_FMT,
baaa35ad 1295 i->name, i->gid);
28e7fad7
MV
1296 if (r == 0)
1297 return 0;
1298 }
1b992147 1299 if (r == 0) {
5374bc7c 1300 log_info("Suggested group ID " GID_FMT " for %s already used.", i->gid, i->name);
1b992147
LP
1301 i->gid_set = false;
1302 }
1303 }
1304
1305 /* Try to reuse the numeric uid, if there's one */
1306 if (!i->gid_set && i->uid_set) {
4ae3e8c9 1307 r = gid_is_ok((gid_t) i->uid, i->name, true);
f647962d 1308 if (r < 0)
3f316701 1309 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
1b992147
LP
1310 if (r > 0) {
1311 i->gid = (gid_t) i->uid;
1312 i->gid_set = true;
1313 }
1314 }
1315
1316 /* If that didn't work, try to read it from the specified path */
1317 if (!i->gid_set) {
1318 gid_t c;
1319
1320 if (read_id_from_file(i, NULL, &c) > 0) {
1321
8dcc66ce 1322 if (c <= 0 || !uid_range_contains(uid_range, c))
1b992147
LP
1323 log_debug("Group ID " GID_FMT " of file not suitable for %s.", c, i->name);
1324 else {
4ae3e8c9 1325 r = gid_is_ok(c, i->name, true);
f647962d 1326 if (r < 0)
3f316701 1327 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
f647962d 1328 else if (r > 0) {
1b992147
LP
1329 i->gid = c;
1330 i->gid_set = true;
1331 } else
1332 log_debug("Group ID " GID_FMT " of file for %s already used.", c, i->name);
1333 }
1334 }
1335 }
1336
1337 /* And if that didn't work either, let's try to find a free one */
1338 if (!i->gid_set) {
4b6f9b20
ZJS
1339 maybe_emit_login_defs_warning();
1340
8530dc44
LP
1341 for (;;) {
1342 /* We look for new GIDs in the UID pool! */
8dcc66ce 1343 r = uid_range_next_lower(uid_range, &search_uid);
330d1def
ZJS
1344 if (r < 0)
1345 return log_error_errno(r, "No free group ID available for %s.", i->name);
8530dc44 1346
4ae3e8c9 1347 r = gid_is_ok(search_uid, i->name, true);
f647962d 1348 if (r < 0)
3f316701 1349 return log_error_errno(r, "Failed to verify GID " GID_FMT ": %m", i->gid);
f647962d 1350 else if (r > 0)
1b992147
LP
1351 break;
1352 }
1353
1b992147 1354 i->gid_set = true;
8530dc44 1355 i->gid = search_uid;
1b992147
LP
1356 }
1357
1dfb9321
SS
1358 r = ordered_hashmap_ensure_put(&todo_gids, NULL, GID_TO_PTR(i->gid), i);
1359 if (r == -EEXIST)
3f316701 1360 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);
1dfb9321 1361 if (r == -ENOMEM)
1b992147 1362 return log_oom();
1b992147 1363 if (r < 0)
3f316701 1364 return log_error_errno(r, "Failed to store group %s with GID " GID_FMT " to be created: %m", i->name, i->gid);
1b992147 1365
c1b6b04f 1366 i->todo_group = true;
9a5af4b7 1367 log_info("Creating group '%s' with GID " GID_FMT ".", i->name, i->gid);
1b992147
LP
1368
1369 return 0;
1370}
1371
1372static int process_item(Item *i) {
1373 int r;
1374
1375 assert(i);
1376
1377 switch (i->type) {
1378
b5327d0a 1379 case ADD_USER: {
5ed47c4d
LB
1380 Item *j = NULL;
1381
1382 if (!i->gid_set)
1383 j = ordered_hashmap_get(groups, i->group_name ?: i->name);
b5327d0a 1384
b5327d0a 1385 if (j && j->todo_group) {
649916d3 1386 /* When a group with the target name is already in queue,
b5327d0a
YW
1387 * use the information about the group and do not create
1388 * duplicated group entry. */
1389 i->gid_set = j->gid_set;
1390 i->gid = j->gid;
1391 i->id_set_strict = true;
649916d3
DM
1392 } else if (i->group_name) {
1393 /* When a group name was given instead of a GID and it's
1394 * not in queue, then it must already exist. */
1395 r = get_gid_by_name(i->group_name, &i->gid);
1396 if (r < 0)
1397 return log_error_errno(r, "Group %s not found.", i->group_name);
1398 i->gid_set = true;
1399 i->id_set_strict = true;
b5327d0a
YW
1400 } else {
1401 r = add_group(i);
1402 if (r < 0)
1403 return r;
1404 }
1b992147
LP
1405
1406 return add_user(i);
b5327d0a 1407 }
1b992147 1408
e2c2060f 1409 case ADD_GROUP:
1b992147 1410 return add_group(i);
1b992147 1411
a12b0cc3 1412 default:
04499a70 1413 assert_not_reached();
a12b0cc3 1414 }
1b992147
LP
1415}
1416
71da1673 1417static Item* item_free(Item *i) {
1b992147 1418 if (!i)
71da1673 1419 return NULL;
1b992147
LP
1420
1421 free(i->name);
649916d3 1422 free(i->group_name);
1b992147
LP
1423 free(i->uid_path);
1424 free(i->gid_path);
1425 free(i->description);
d9b8ea54 1426 free(i->home);
7b1aaf66 1427 free(i->shell);
9a87bdd7 1428 free(i->filename);
71da1673 1429 return mfree(i);
1b992147
LP
1430}
1431
1432DEFINE_TRIVIAL_CLEANUP_FUNC(Item*, item_free);
71da1673 1433DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, char, string_hash_func, string_compare_func, Item, item_free);
1b992147 1434
9a87bdd7
ZJS
1435static Item* item_new(ItemType type, const char *name, const char *filename, unsigned line) {
1436 assert(name);
1437 assert(!!filename == (line > 0));
1438
1439 _cleanup_(item_freep) Item *new = new(Item, 1);
1440 if (!new)
1441 return NULL;
1442
1443 *new = (Item) {
1444 .type = type,
1445 .line = line,
1446 };
1447
1448 if (free_and_strdup(&new->name, name) < 0 ||
1449 free_and_strdup(&new->filename, filename) < 0)
1450 return NULL;
1451
1452 return TAKE_PTR(new);
1453}
1454
a12b0cc3
LP
1455static int add_implicit(void) {
1456 char *g, **l;
a12b0cc3
LP
1457 int r;
1458
1459 /* Implicitly create additional users and groups, if they were listed in "m" lines */
90e74a66 1460 ORDERED_HASHMAP_FOREACH_KEY(l, g, members) {
d4f0412d
YW
1461 STRV_FOREACH(m, l)
1462 if (!ordered_hashmap_get(users, *m)) {
9a87bdd7
ZJS
1463 _cleanup_(item_freep) Item *j =
1464 item_new(ADD_USER, *m, /* filename= */ NULL, /* line= */ 0);
a12b0cc3
LP
1465 if (!j)
1466 return log_oom();
1467
f334deba
SS
1468 r = ordered_hashmap_ensure_put(&users, &item_hash_ops, j->name, j);
1469 if (r == -ENOMEM)
a12b0cc3 1470 return log_oom();
f334deba
SS
1471 if (r < 0)
1472 return log_error_errno(r, "Failed to add implicit user '%s': %m", j->name);
a12b0cc3
LP
1473
1474 log_debug("Adding implicit user '%s' due to m line", j->name);
f334deba 1475 TAKE_PTR(j);
a12b0cc3 1476 }
d4f0412d
YW
1477
1478 if (!(ordered_hashmap_get(users, g) ||
1479 ordered_hashmap_get(groups, g))) {
9a87bdd7
ZJS
1480 _cleanup_(item_freep) Item *j =
1481 item_new(ADD_GROUP, g, /* filename= */ NULL, /* line= */ 0);
d4f0412d
YW
1482 if (!j)
1483 return log_oom();
1484
f334deba
SS
1485 r = ordered_hashmap_ensure_put(&groups, &item_hash_ops, j->name, j);
1486 if (r == -ENOMEM)
d4f0412d 1487 return log_oom();
f334deba
SS
1488 if (r < 0)
1489 return log_error_errno(r, "Failed to add implicit group '%s': %m", j->name);
d4f0412d
YW
1490
1491 log_debug("Adding implicit group '%s' due to m line", j->name);
f334deba 1492 TAKE_PTR(j);
a12b0cc3
LP
1493 }
1494 }
1495
1496 return 0;
1497}
1498
5f465fda
ZJS
1499static int item_equivalent(Item *a, Item *b) {
1500 int r;
1501
1b992147
LP
1502 assert(a);
1503 assert(b);
1504
7519b880
ZJS
1505 if (a->type != b->type) {
1506 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1507 "Item not equivalent because types differ");
1b992147 1508 return false;
7519b880 1509 }
1b992147 1510
7519b880
ZJS
1511 if (!streq_ptr(a->name, b->name)) {
1512 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1513 "Item not equivalent because names differ ('%s' vs. '%s')",
1514 a->name, b->name);
1b992147 1515 return false;
7519b880 1516 }
1b992147 1517
5f465fda 1518 /* Paths were simplified previously, so we can use streq. */
7519b880
ZJS
1519 if (!streq_ptr(a->uid_path, b->uid_path)) {
1520 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1521 "Item not equivalent because UID paths differ (%s vs. %s)",
1522 a->uid_path ?: "(unset)", b->uid_path ?: "(unset)");
1b992147 1523 return false;
7519b880 1524 }
1b992147 1525
7519b880
ZJS
1526 if (!streq_ptr(a->gid_path, b->gid_path)) {
1527 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1528 "Item not equivalent because GID paths differ (%s vs. %s)",
1529 a->gid_path ?: "(unset)", b->gid_path ?: "(unset)");
1b992147 1530 return false;
7519b880 1531 }
1b992147 1532
7519b880
ZJS
1533 if (!streq_ptr(a->description, b->description)) {
1534 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1535 "Item not equivalent because descriptions differ ('%s' vs. '%s')",
1536 strempty(a->description), strempty(b->description));
1b992147 1537 return false;
7519b880 1538 }
1b992147 1539
7519b880
ZJS
1540 if ((a->uid_set != b->uid_set) ||
1541 (a->uid_set && a->uid != b->uid)) {
1542 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1543 "Item not equivalent because UIDs differ (%s vs. %s)",
1544 FORMAT_UID(a->uid_set, a->uid), FORMAT_UID(b->uid_set, b->uid));
1b992147 1545 return false;
7519b880 1546 }
1b992147 1547
7519b880
ZJS
1548 if ((a->gid_set != b->gid_set) ||
1549 (a->gid_set && a->gid != b->gid)) {
1550 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1551 "Item not equivalent because GIDs differ (%s vs. %s)",
1552 FORMAT_GID(a->gid_set, a->gid), FORMAT_GID(b->gid_set, b->gid));
1b992147 1553 return false;
7519b880 1554 }
1b992147 1555
7519b880
ZJS
1556 if (!streq_ptr(a->home, b->home)) {
1557 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1558 "Item not equivalent because home directories differ ('%s' vs. '%s')",
1559 strempty(a->description), strempty(b->description));
7629889c 1560 return false;
7519b880 1561 }
7629889c 1562
5f465fda
ZJS
1563 /* Check if the two paths refer to the same file.
1564 * If the paths are equal (after normalization), it's obviously the same file.
1565 * If both paths specify a nologin shell, treat them as the same (e.g. /bin/true and /bin/false).
1566 * Otherwise, try to resolve the paths, and see if we get the same result, (e.g. /sbin/nologin and
1567 * /usr/sbin/nologin).
1568 * If we can't resolve something, treat different paths as different. */
1569
1570 const char *a_shell = pick_shell(a),
1571 *b_shell = pick_shell(b);
1572 if (!path_equal_ptr(a_shell, b_shell) &&
1573 !(is_nologin_shell(a_shell) && is_nologin_shell(b_shell))) {
1574 _cleanup_free_ char *pa = NULL, *pb = NULL;
1575
f461a28d 1576 r = chase(a_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pa, NULL);
5f465fda
ZJS
1577 if (r < 0) {
1578 log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
1579 r, "Failed to look up path '%s%s%s': %m",
1580 strempty(arg_root), arg_root ? "/" : "", a_shell);
1581 return ERRNO_IS_RESOURCE(r) ? r : false;
1582 }
1583
f461a28d 1584 r = chase(b_shell, arg_root, CHASE_PREFIX_ROOT | CHASE_NONEXISTENT, &pb, NULL);
5f465fda
ZJS
1585 if (r < 0) {
1586 log_full_errno(ERRNO_IS_RESOURCE(r) ? LOG_ERR : LOG_DEBUG,
1587 r, "Failed to look up path '%s%s%s': %m",
1588 strempty(arg_root), arg_root ? "/" : "", b_shell);
1589 return ERRNO_IS_RESOURCE(r) ? r : false;
1590 }
1591
7519b880
ZJS
1592 if (!path_equal(pa, pb)) {
1593 log_syntax(NULL, LOG_DEBUG, a->filename, a->line, 0,
1594 "Item not equivalent because shells differ ('%s' vs. '%s')",
1595 pa, pb);
5f465fda 1596 return false;
7519b880 1597 }
5f465fda 1598 }
7b1aaf66 1599
1b992147
LP
1600 return true;
1601}
1602
1b992147 1603static int parse_line(const char *fname, unsigned line, const char *buffer) {
7b1aaf66
ZJS
1604 _cleanup_free_ char *action = NULL,
1605 *name = NULL, *resolved_name = NULL,
1606 *id = NULL, *resolved_id = NULL,
b8bed700
YW
1607 *description = NULL, *resolved_description = NULL,
1608 *home = NULL, *resolved_home = NULL,
71fb1588 1609 *shell = NULL, *resolved_shell = NULL;
1b992147
LP
1610 _cleanup_(item_freep) Item *i = NULL;
1611 Item *existing;
5bc9c980 1612 OrderedHashmap *h;
7629889c
LP
1613 int r;
1614 const char *p;
1b992147
LP
1615
1616 assert(fname);
1617 assert(line >= 1);
1618 assert(buffer);
1619
7629889c
LP
1620 /* Parse columns */
1621 p = buffer;
4ec85141 1622 r = extract_many_words(&p, NULL, EXTRACT_UNQUOTE,
7b1aaf66 1623 &action, &name, &id, &description, &home, &shell, NULL);
330d1def 1624 if (r < 0)
87c696f2 1625 return log_syntax(NULL, LOG_ERR, fname, line, r, "Syntax error.");
330d1def 1626 if (r < 2)
87c696f2
ZJS
1627 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1628 "Missing action and name columns.");
330d1def 1629 if (!isempty(p))
87c696f2
ZJS
1630 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1631 "Trailing garbage.");
1b992147 1632
7629889c 1633 /* Verify action */
330d1def 1634 if (strlen(action) != 1)
87c696f2
ZJS
1635 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1636 "Unknown modifier '%s'.", action);
1b992147 1637
330d1def 1638 if (!IN_SET(action[0], ADD_USER, ADD_GROUP, ADD_MEMBER, ADD_RANGE))
87c696f2
ZJS
1639 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EBADMSG),
1640 "Unknown command type '%c'.", action[0]);
1b992147 1641
7629889c 1642 /* Verify name */
e7b88b7b 1643 if (empty_or_dash(name))
97b11eed 1644 name = mfree(name);
1b992147 1645
8530dc44 1646 if (name) {
de61a04b 1647 r = specifier_printf(name, NAME_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_name);
330d1def 1648 if (r < 0)
87c696f2 1649 return log_syntax(NULL, LOG_ERR, fname, line, r, "Failed to replace specifiers in '%s': %m", name);
8530dc44 1650
7a8867ab 1651 if (!valid_user_group_name(resolved_name, 0))
87c696f2
ZJS
1652 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1653 "'%s' is not a valid user or group name.", resolved_name);
1b992147
LP
1654 }
1655
8530dc44 1656 /* Verify id */
e7b88b7b 1657 if (empty_or_dash(id))
97b11eed 1658 id = mfree(id);
7629889c 1659
8530dc44 1660 if (id) {
de61a04b 1661 r = specifier_printf(id, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_id);
330d1def 1662 if (r < 0)
87c696f2
ZJS
1663 return log_syntax(NULL, LOG_ERR, fname, line, r,
1664 "Failed to replace specifiers in '%s': %m", name);
8530dc44
LP
1665 }
1666
1667 /* Verify description */
e7b88b7b 1668 if (empty_or_dash(description))
97b11eed 1669 description = mfree(description);
1b992147 1670
8530dc44 1671 if (description) {
de61a04b 1672 r = specifier_printf(description, LONG_LINE_MAX, system_and_tmp_specifier_table, arg_root, NULL, &resolved_description);
330d1def 1673 if (r < 0)
87c696f2
ZJS
1674 return log_syntax(NULL, LOG_ERR, fname, line, r,
1675 "Failed to replace specifiers in '%s': %m", description);
b8bed700 1676
330d1def 1677 if (!valid_gecos(resolved_description))
87c696f2
ZJS
1678 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1679 "'%s' is not a valid GECOS field.", resolved_description);
8530dc44
LP
1680 }
1681
1682 /* Verify home */
e7b88b7b 1683 if (empty_or_dash(home))
97b11eed 1684 home = mfree(home);
1b992147 1685
8530dc44 1686 if (home) {
de61a04b 1687 r = specifier_printf(home, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_home);
330d1def 1688 if (r < 0)
87c696f2
ZJS
1689 return log_syntax(NULL, LOG_ERR, fname, line, r,
1690 "Failed to replace specifiers in '%s': %m", home);
b8bed700 1691
eef74f91
ZJS
1692 path_simplify(resolved_home);
1693
330d1def 1694 if (!valid_home(resolved_home))
87c696f2
ZJS
1695 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1696 "'%s' is not a valid home directory field.", resolved_home);
8530dc44
LP
1697 }
1698
7b1aaf66 1699 /* Verify shell */
e7b88b7b 1700 if (empty_or_dash(shell))
7b1aaf66
ZJS
1701 shell = mfree(shell);
1702
1703 if (shell) {
de61a04b 1704 r = specifier_printf(shell, PATH_MAX-1, system_and_tmp_specifier_table, arg_root, NULL, &resolved_shell);
330d1def 1705 if (r < 0)
87c696f2
ZJS
1706 return log_syntax(NULL, LOG_ERR, fname, line, r,
1707 "Failed to replace specifiers in '%s': %m", shell);
7b1aaf66 1708
eef74f91
ZJS
1709 path_simplify(resolved_shell);
1710
330d1def 1711 if (!valid_shell(resolved_shell))
87c696f2
ZJS
1712 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1713 "'%s' is not a valid login shell field.", resolved_shell);
7b1aaf66
ZJS
1714 }
1715
a12b0cc3 1716 switch (action[0]) {
1b992147 1717
8530dc44 1718 case ADD_RANGE:
330d1def 1719 if (resolved_name)
87c696f2
ZJS
1720 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1721 "Lines of type 'r' don't take a name field.");
330d1def
ZJS
1722
1723 if (!resolved_id)
87c696f2
ZJS
1724 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1725 "Lines of type 'r' require an ID range in the third field.");
330d1def
ZJS
1726
1727 if (description || home || shell)
87c696f2
ZJS
1728 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1729 "Lines of type '%c' don't take a %s field.",
1730 action[0],
1731 description ? "GECOS" : home ? "home directory" : "login shell");
7629889c 1732
8dcc66ce 1733 r = uid_range_add_str(&uid_range, resolved_id);
330d1def 1734 if (r < 0)
87c696f2
ZJS
1735 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1736 "Invalid UID range %s.", resolved_id);
1b992147 1737
8530dc44
LP
1738 return 0;
1739
1740 case ADD_MEMBER: {
8530dc44 1741 /* Try to extend an existing member or group item */
330d1def 1742 if (!name)
87c696f2
ZJS
1743 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1744 "Lines of type 'm' require a user name in the second field.");
330d1def
ZJS
1745
1746 if (!resolved_id)
87c696f2
ZJS
1747 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1748 "Lines of type 'm' require a group name in the third field.");
330d1def 1749
7a8867ab 1750 if (!valid_user_group_name(resolved_id, 0))
87c696f2
ZJS
1751 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1752 "'%s' is not a valid user or group name.", resolved_id);
330d1def
ZJS
1753
1754 if (description || home || shell)
87c696f2
ZJS
1755 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1756 "Lines of type '%c' don't take a %s field.",
1757 action[0],
1758 description ? "GECOS" : home ? "home directory" : "login shell");
8530dc44 1759
cde79109 1760 r = string_strv_ordered_hashmap_put(&members, resolved_id, resolved_name);
7629889c 1761 if (r < 0)
cde79109 1762 return log_error_errno(r, "Failed to store mapping for %s: %m", resolved_id);
a12b0cc3
LP
1763
1764 return 0;
1b992147
LP
1765 }
1766
a12b0cc3 1767 case ADD_USER:
330d1def 1768 if (!name)
87c696f2
ZJS
1769 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1770 "Lines of type 'u' require a user name in the second field.");
8530dc44 1771
71da1673 1772 r = ordered_hashmap_ensure_allocated(&users, &item_hash_ops);
a12b0cc3
LP
1773 if (r < 0)
1774 return log_oom();
1775
9a87bdd7 1776 i = item_new(ADD_USER, resolved_name, fname, line);
a12b0cc3
LP
1777 if (!i)
1778 return log_oom();
1779
8530dc44 1780 if (resolved_id) {
9a87bdd7
ZJS
1781 if (path_is_absolute(resolved_id))
1782 i->uid_path = path_simplify(TAKE_PTR(resolved_id));
1783 else {
4cb41413
MV
1784 _cleanup_free_ char *uid = NULL, *gid = NULL;
1785 if (split_pair(resolved_id, ":", &uid, &gid) == 0) {
1786 r = parse_gid(gid, &i->gid);
649916d3 1787 if (r < 0) {
7a8867ab 1788 if (valid_user_group_name(gid, 0))
649916d3
DM
1789 i->group_name = TAKE_PTR(gid);
1790 else
87c696f2
ZJS
1791 return log_syntax(NULL, LOG_ERR, fname, line, r,
1792 "Failed to parse GID: '%s': %m", id);
649916d3
DM
1793 } else {
1794 i->gid_set = true;
1795 i->id_set_strict = true;
1796 }
4cb41413 1797 free_and_replace(resolved_id, uid);
a12b0cc3 1798 }
1825c909
MV
1799 if (!streq(resolved_id, "-")) {
1800 r = parse_uid(resolved_id, &i->uid);
1801 if (r < 0)
87c696f2
ZJS
1802 return log_syntax(NULL, LOG_ERR, fname, line, r,
1803 "Failed to parse UID: '%s': %m", id);
1825c909
MV
1804 i->uid_set = true;
1805 }
a12b0cc3
LP
1806 }
1807 }
1808
b8bed700
YW
1809 i->description = TAKE_PTR(resolved_description);
1810 i->home = TAKE_PTR(resolved_home);
1cc6c93a 1811 i->shell = TAKE_PTR(resolved_shell);
7b1aaf66 1812
1b992147 1813 h = users;
a12b0cc3
LP
1814 break;
1815
1816 case ADD_GROUP:
330d1def 1817 if (!name)
87c696f2
ZJS
1818 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1819 "Lines of type 'g' require a user name in the second field.");
a12b0cc3 1820
330d1def 1821 if (description || home || shell)
87c696f2
ZJS
1822 return log_syntax(NULL, LOG_ERR, fname, line, SYNTHETIC_ERRNO(EINVAL),
1823 "Lines of type '%c' don't take a %s field.",
1824 action[0],
1825 description ? "GECOS" : home ? "home directory" : "login shell");
7629889c 1826
71da1673 1827 r = ordered_hashmap_ensure_allocated(&groups, &item_hash_ops);
7629889c
LP
1828 if (r < 0)
1829 return log_oom();
1830
9a87bdd7 1831 i = item_new(ADD_GROUP, resolved_name, fname, line);
a12b0cc3
LP
1832 if (!i)
1833 return log_oom();
1834
8530dc44 1835 if (resolved_id) {
9a87bdd7
ZJS
1836 if (path_is_absolute(resolved_id))
1837 i->gid_path = path_simplify(TAKE_PTR(resolved_id));
1838 else {
8530dc44 1839 r = parse_gid(resolved_id, &i->gid);
4cb41413 1840 if (r < 0)
87c696f2
ZJS
1841 return log_syntax(NULL, LOG_ERR, fname, line, r,
1842 "Failed to parse GID: '%s': %m", id);
a12b0cc3
LP
1843
1844 i->gid_set = true;
1845 }
1846 }
1847
1b992147 1848 h = groups;
a12b0cc3 1849 break;
8530dc44 1850
bce415ed 1851 default:
9a87bdd7 1852 assert_not_reached();
1b992147 1853 }
a12b0cc3 1854
5bc9c980 1855 existing = ordered_hashmap_get(h, i->name);
1b992147 1856 if (existing) {
5f465fda 1857 /* Two functionally-equivalent items are fine */
7519b880 1858 r = item_equivalent(i, existing);
5f465fda
ZJS
1859 if (r < 0)
1860 return r;
9a87bdd7
ZJS
1861 if (r == 0) {
1862 if (existing->filename)
1863 log_syntax(NULL, LOG_WARNING, fname, line, 0,
1864 "Conflict with earlier configuration for %s '%s' in %s:%u, ignoring line.",
1865 item_type_to_string(i->type),
1866 i->name,
1867 existing->filename, existing->line);
1868 else
1869 log_syntax(NULL, LOG_WARNING, fname, line, 0,
1870 "Conflict with earlier configuration for %s '%s', ignoring line.",
1871 item_type_to_string(i->type),
1872 i->name);
1873 }
1b992147
LP
1874
1875 return 0;
1876 }
1877
5bc9c980 1878 r = ordered_hashmap_put(h, i->name, i);
a12b0cc3
LP
1879 if (r < 0)
1880 return log_oom();
1b992147
LP
1881
1882 i = NULL;
1883 return 0;
1884}
1885
1886static int read_config_file(const char *fn, bool ignore_enoent) {
dfc87cbf 1887 _cleanup_fclose_ FILE *rf = NULL;
2708160c 1888 _cleanup_free_ char *pp = NULL;
dfc87cbf 1889 FILE *f = NULL;
1b992147 1890 unsigned v = 0;
c4640902 1891 int r = 0;
1b992147
LP
1892
1893 assert(fn);
1894
dfc87cbf
LP
1895 if (streq(fn, "-"))
1896 f = stdin;
1897 else {
2708160c 1898 r = search_and_fopen(fn, "re", arg_root, (const char**) CONF_PATHS_STRV("sysusers.d"), &rf, &pp);
dfc87cbf
LP
1899 if (r < 0) {
1900 if (ignore_enoent && r == -ENOENT)
1901 return 0;
1b992147 1902
8d3d7072 1903 return log_error_errno(r, "Failed to open '%s', ignoring: %m", fn);
dfc87cbf
LP
1904 }
1905
1906 f = rf;
2708160c 1907 fn = pp;
1b992147
LP
1908 }
1909
050ca299
LP
1910 for (;;) {
1911 _cleanup_free_ char *line = NULL;
1b992147
LP
1912 char *l;
1913 int k;
1914
050ca299
LP
1915 k = read_line(f, LONG_LINE_MAX, &line);
1916 if (k < 0)
1917 return log_error_errno(k, "Failed to read '%s': %m", fn);
1918 if (k == 0)
1919 break;
1920
1b992147
LP
1921 v++;
1922
1923 l = strstrip(line);
4c701096 1924 if (IN_SET(*l, 0, '#'))
1b992147
LP
1925 continue;
1926
1927 k = parse_line(fn, v, l);
1928 if (k < 0 && r == 0)
1929 r = k;
1930 }
1931
1932 if (ferror(f)) {
56f64d95 1933 log_error_errno(errno, "Failed to read from file %s: %m", fn);
1b992147
LP
1934 if (r == 0)
1935 r = -EIO;
1936 }
1937
1938 return r;
1939}
1940
ec0327d6
ZJS
1941static int cat_config(void) {
1942 _cleanup_strv_free_ char **files = NULL;
ec0327d6
ZJS
1943 int r;
1944
a826d4f7 1945 r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, NULL);
ec0327d6
ZJS
1946 if (r < 0)
1947 return r;
1948
384c2c32 1949 pager_open(arg_pager_flags);
dcd5c891 1950
ec0327d6
ZJS
1951 return cat_files(NULL, files, 0);
1952}
1953
37ec0fdd
LP
1954static int help(void) {
1955 _cleanup_free_ char *link = NULL;
1956 int r;
1957
1958 r = terminal_urlify_man("systemd-sysusers.service", "8", &link);
1959 if (r < 0)
1960 return log_oom();
1961
1b992147
LP
1962 printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n"
1963 "Creates system user accounts.\n\n"
1964 " -h --help Show this help\n"
1965 " --version Show package version\n"
ec0327d6 1966 " --cat-config Show configuration files\n"
601185b4 1967 " --root=PATH Operate on an alternate filesystem root\n"
0c3ee127 1968 " --image=PATH Operate on disk image as filesystem root\n"
84be0c71 1969 " --image-policy=POLICY Specify disk image dissection policy\n"
d16a1c1b 1970 " --replace=PATH Treat arguments as replacement for PATH\n"
64fe1095 1971 " --dry-run Just print what would be done\n"
1b600bd5 1972 " --inline Treat arguments as configuration lines\n"
dcd5c891 1973 " --no-pager Do not pipe output into a pager\n"
bc556335
DDM
1974 "\nSee the %s for details.\n",
1975 program_invocation_short_name,
1976 link);
37ec0fdd
LP
1977
1978 return 0;
1b992147
LP
1979}
1980
1981static int parse_argv(int argc, char *argv[]) {
1982
1983 enum {
1984 ARG_VERSION = 0x100,
ec0327d6 1985 ARG_CAT_CONFIG,
1b992147 1986 ARG_ROOT,
0c3ee127 1987 ARG_IMAGE,
06e78680 1988 ARG_IMAGE_POLICY,
d16a1c1b 1989 ARG_REPLACE,
64fe1095 1990 ARG_DRY_RUN,
1b600bd5 1991 ARG_INLINE,
dcd5c891 1992 ARG_NO_PAGER,
1b992147
LP
1993 };
1994
1995 static const struct option options[] = {
84be0c71
LP
1996 { "help", no_argument, NULL, 'h' },
1997 { "version", no_argument, NULL, ARG_VERSION },
1998 { "cat-config", no_argument, NULL, ARG_CAT_CONFIG },
1999 { "root", required_argument, NULL, ARG_ROOT },
2000 { "image", required_argument, NULL, ARG_IMAGE },
06e78680 2001 { "image-policy", required_argument, NULL, ARG_IMAGE_POLICY },
84be0c71
LP
2002 { "replace", required_argument, NULL, ARG_REPLACE },
2003 { "dry-run", no_argument, NULL, ARG_DRY_RUN },
2004 { "inline", no_argument, NULL, ARG_INLINE },
2005 { "no-pager", no_argument, NULL, ARG_NO_PAGER },
1b992147
LP
2006 {}
2007 };
2008
0f474365 2009 int c, r;
1b992147
LP
2010
2011 assert(argc >= 0);
2012 assert(argv);
2013
601185b4 2014 while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
1b992147
LP
2015
2016 switch (c) {
2017
2018 case 'h':
37ec0fdd 2019 return help();
1b992147
LP
2020
2021 case ARG_VERSION:
3f6fd1ba 2022 return version();
1b992147 2023
ec0327d6
ZJS
2024 case ARG_CAT_CONFIG:
2025 arg_cat_config = true;
2026 break;
2027
1b992147 2028 case ARG_ROOT:
614b022c 2029 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_root);
0f474365 2030 if (r < 0)
0f03c2a4 2031 return r;
1b992147
LP
2032 break;
2033
0c3ee127 2034 case ARG_IMAGE:
3537577c
ZJS
2035#ifdef STANDALONE
2036 return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
2037 "This systemd-sysusers version is compiled without support for --image=.");
2038#else
614b022c 2039 r = parse_path_argument(optarg, /* suppress_root= */ false, &arg_image);
0c3ee127
LP
2040 if (r < 0)
2041 return r;
2042 break;
3537577c 2043#endif
0c3ee127 2044
06e78680
YW
2045 case ARG_IMAGE_POLICY:
2046 r = parse_image_policy_argument(optarg, &arg_image_policy);
2047 if (r < 0)
2048 return r;
2049 break;
2050
d16a1c1b
ZJS
2051 case ARG_REPLACE:
2052 if (!path_is_absolute(optarg) ||
baaa35ad
ZJS
2053 !endswith(optarg, ".conf"))
2054 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2055 "The argument to --replace= must an absolute path to a config file");
d16a1c1b
ZJS
2056
2057 arg_replace = optarg;
2058 break;
2059
64fe1095
ZJS
2060 case ARG_DRY_RUN:
2061 arg_dry_run = true;
2062 break;
2063
1b600bd5
ZJS
2064 case ARG_INLINE:
2065 arg_inline = true;
2066 break;
2067
dcd5c891 2068 case ARG_NO_PAGER:
0221d68a 2069 arg_pager_flags |= PAGER_DISABLE;
dcd5c891
LP
2070 break;
2071
1b992147
LP
2072 case '?':
2073 return -EINVAL;
2074
2075 default:
04499a70 2076 assert_not_reached();
1b992147 2077 }
1b992147 2078
baaa35ad
ZJS
2079 if (arg_replace && arg_cat_config)
2080 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2081 "Option --replace= is not supported with --cat-config");
ec0327d6 2082
baaa35ad
ZJS
2083 if (arg_replace && optind >= argc)
2084 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
2085 "When --replace= is given, some configuration items must be specified");
d16a1c1b 2086
0c3ee127
LP
2087 if (arg_image && arg_root)
2088 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Please specify either --root= or --image=, the combination of both is not supported.");
2089
1b992147
LP
2090 return 1;
2091}
2092
d16a1c1b 2093static int parse_arguments(char **args) {
d16a1c1b
ZJS
2094 unsigned pos = 1;
2095 int r;
2096
2097 STRV_FOREACH(arg, args) {
2098 if (arg_inline)
2099 /* Use (argument):n, where n==1 for the first positional arg */
2100 r = parse_line("(argument)", pos, *arg);
2101 else
3acb6ede 2102 r = read_config_file(*arg, /* ignore_enoent= */ false);
d16a1c1b
ZJS
2103 if (r < 0)
2104 return r;
2105
2106 pos++;
2107 }
2108
2109 return 0;
2110}
2111
ec0327d6 2112static int read_config_files(char **args) {
d16a1c1b
ZJS
2113 _cleanup_strv_free_ char **files = NULL;
2114 _cleanup_free_ char *p = NULL;
d16a1c1b
ZJS
2115 int r;
2116
a826d4f7 2117 r = conf_files_list_with_replacement(arg_root, CONF_PATHS_STRV("sysusers.d"), arg_replace, &files, &p);
d16a1c1b 2118 if (r < 0)
ec0327d6 2119 return r;
d16a1c1b
ZJS
2120
2121 STRV_FOREACH(f, files)
2122 if (p && path_equal(*f, p)) {
28e5e1e9 2123 log_debug("Parsing arguments at position \"%s\"%s", *f, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
d16a1c1b
ZJS
2124
2125 r = parse_arguments(args);
2126 if (r < 0)
2127 return r;
2128 } else {
28e5e1e9 2129 log_debug("Reading config file \"%s\"%s", *f, special_glyph(SPECIAL_GLYPH_ELLIPSIS));
d16a1c1b
ZJS
2130
2131 /* Just warn, ignore result otherwise */
3acb6ede 2132 (void) read_config_file(*f, /* ignore_enoent= */ true);
d16a1c1b
ZJS
2133 }
2134
2135 return 0;
2136}
2137
3acb6ede
LP
2138static int read_credential_lines(void) {
2139 _cleanup_free_ char *j = NULL;
2140 const char *d;
2141 int r;
2142
2143 r = get_credentials_dir(&d);
2144 if (r == -ENXIO)
2145 return 0;
2146 if (r < 0)
2147 return log_error_errno(r, "Failed to get credentials directory: %m");
2148
2149 j = path_join(d, "sysusers.extra");
2150 if (!j)
2151 return log_oom();
2152
2153 (void) read_config_file(j, /* ignore_enoent= */ true);
2154 return 0;
2155}
2156
71da1673 2157static int run(int argc, char *argv[]) {
3537577c 2158#ifndef STANDALONE
0c3ee127 2159 _cleanup_(loop_device_unrefp) LoopDevice *loop_device = NULL;
0c3ee127 2160 _cleanup_(umount_and_rmdir_and_freep) char *unlink_dir = NULL;
3537577c 2161#endif
5bb1d7fb 2162 _cleanup_close_ int lock = -EBADF;
1b992147 2163 Item *i;
dd2fd972 2164 int r;
1b992147
LP
2165
2166 r = parse_argv(argc, argv);
2167 if (r <= 0)
71da1673 2168 return r;
1b992147 2169
d2acb93d 2170 log_setup();
1b992147 2171
71da1673
YW
2172 if (arg_cat_config)
2173 return cat_config();
ec0327d6 2174
1b992147
LP
2175 umask(0022);
2176
c3dacc8b 2177 r = mac_selinux_init();
71da1673 2178 if (r < 0)
a9ba0e32 2179 return r;
1b992147 2180
3537577c 2181#ifndef STANDALONE
0c3ee127
LP
2182 if (arg_image) {
2183 assert(!arg_root);
2184
2185 r = mount_image_privately_interactively(
2186 arg_image,
84be0c71 2187 arg_image_policy,
4b5de5dd
LP
2188 DISSECT_IMAGE_GENERIC_ROOT |
2189 DISSECT_IMAGE_REQUIRE_ROOT |
2190 DISSECT_IMAGE_VALIDATE_OS |
2191 DISSECT_IMAGE_RELAX_VAR_CHECK |
c65f854a
LP
2192 DISSECT_IMAGE_FSCK |
2193 DISSECT_IMAGE_GROWFS,
0c3ee127 2194 &unlink_dir,
a133d2c3 2195 /* ret_dir_fd= */ NULL,
e330f97a 2196 &loop_device);
0c3ee127
LP
2197 if (r < 0)
2198 return r;
2199
2200 arg_root = strdup(unlink_dir);
2201 if (!arg_root)
2202 return log_oom();
2203 }
3537577c
ZJS
2204#else
2205 assert(!arg_image);
2206#endif
0c3ee127 2207
3acb6ede
LP
2208 /* If command line arguments are specified along with --replace, read all configuration files and
2209 * insert the positional arguments at the specified place. Otherwise, if command line arguments are
2210 * specified, execute just them, and finally, without --replace= or any positional arguments, just
2211 * read configuration and execute it. */
d16a1c1b 2212 if (arg_replace || optind >= argc)
ec0327d6 2213 r = read_config_files(argv + optind);
d16a1c1b
ZJS
2214 else
2215 r = parse_arguments(argv + optind);
2216 if (r < 0)
71da1673 2217 return r;
1b992147 2218
3acb6ede
LP
2219 r = read_credential_lines();
2220 if (r < 0)
2221 return r;
2222
2223 /* Let's tell nss-systemd not to synthesize the "root" and "nobody" entries for it, so that our
2224 * detection whether the names or UID/GID area already used otherwise doesn't get confused. After
2225 * all, even though nss-systemd synthesizes these users/groups, they should still appear in
2226 * /etc/passwd and /etc/group, as the synthesizing logic is merely supposed to be fallback for cases
2227 * where we run with a completely unpopulated /etc. */
71da1673
YW
2228 if (setenv("SYSTEMD_NSS_BYPASS_SYNTHETIC", "1", 1) < 0)
2229 return log_error_errno(errno, "Failed to set SYSTEMD_NSS_BYPASS_SYNTHETIC environment variable: %m");
fe102d6a 2230
8530dc44 2231 if (!uid_range) {
aa25270c 2232 /* Default to default range of SYSTEMD_UID_MIN..SYSTEM_UID_MAX. */
4b6f9b20 2233 r = read_login_defs(&login_defs, NULL, arg_root);
71da1673 2234 if (r < 0)
aa25270c
ZJS
2235 return log_error_errno(r, "Failed to read %s%s: %m",
2236 strempty(arg_root), "/etc/login.defs");
2237
4b6f9b20
ZJS
2238 login_defs_need_warning = true;
2239
aa25270c 2240 /* We pick a range that very conservative: we look at compiled-in maximum and the value in
3f316701 2241 * /etc/login.defs. That way the UIDs/GIDs which we allocate will be interpreted correctly,
aa25270c
ZJS
2242 * even if /etc/login.defs is removed later. (The bottom bound doesn't matter much, since
2243 * it's only used during allocation, so we use the configured value directly). */
4b6f9b20
ZJS
2244 uid_t begin = login_defs.system_alloc_uid_min,
2245 end = MIN3((uid_t) SYSTEM_UID_MAX, login_defs.system_uid_max, login_defs.system_gid_max);
aa25270c 2246 if (begin < end) {
8dcc66ce 2247 r = uid_range_add(&uid_range, begin, end - begin + 1);
aa25270c
ZJS
2248 if (r < 0)
2249 return log_oom();
2250 }
8530dc44
LP
2251 }
2252
a12b0cc3
LP
2253 r = add_implicit();
2254 if (r < 0)
71da1673 2255 return r;
a12b0cc3 2256
64fe1095
ZJS
2257 if (!arg_dry_run) {
2258 lock = take_etc_passwd_lock(arg_root);
2259 if (lock < 0)
2260 return log_error_errno(lock, "Failed to take /etc/passwd lock: %m");
2261 }
1b992147
LP
2262
2263 r = load_user_database();
71da1673
YW
2264 if (r < 0)
2265 return log_error_errno(r, "Failed to load user database: %m");
1b992147
LP
2266
2267 r = load_group_database();
71da1673
YW
2268 if (r < 0)
2269 return log_error_errno(r, "Failed to read group database: %m");
1b992147 2270
90e74a66 2271 ORDERED_HASHMAP_FOREACH(i, groups)
c1a32819 2272 (void) process_item(i);
1b992147 2273
90e74a66 2274 ORDERED_HASHMAP_FOREACH(i, users)
c1a32819 2275 (void) process_item(i);
1b992147 2276
4c795066 2277 return write_files();
1b992147 2278}
71da1673
YW
2279
2280DEFINE_MAIN_FUNCTION(run);