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