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