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