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