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