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