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