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