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