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