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