1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
11 #include "sd-messages.h"
13 #include "alloc-util.h"
15 #include "errno-util.h"
16 #include "extract-word.h"
19 #include "format-util.h"
20 #include "lock-util.h"
23 #include "parse-util.h"
24 #include "path-util.h"
25 #include "string-util.h"
27 #include "terminal-util.h"
28 #include "user-util.h"
31 bool uid_is_valid(uid_t uid
) {
33 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
35 /* Some libc APIs use UID_INVALID as special placeholder */
36 if (uid
== (uid_t
) UINT32_C(0xFFFFFFFF))
39 /* A long time ago UIDs where 16 bit, hence explicitly avoid the 16-bit -1 too */
40 if (uid
== (uid_t
) UINT32_C(0xFFFF))
46 int parse_uid(const char *s
, uid_t
*ret
) {
52 assert_cc(sizeof(uid_t
) == sizeof(uint32_t));
54 /* We are very strict when parsing UIDs, and prohibit +/- as prefix, leading zero as prefix, and
55 * whitespace. We do this, since this call is often used in a context where we parse things as UID
56 * first, and if that doesn't work we fall back to NSS. Thus we really want to make sure that UIDs
57 * are parsed as UIDs only if they really really look like UIDs. */
58 r
= safe_atou32_full(s
, 10
59 | SAFE_ATO_REFUSE_PLUS_MINUS
60 | SAFE_ATO_REFUSE_LEADING_ZERO
61 | SAFE_ATO_REFUSE_LEADING_WHITESPACE
, &uid
);
65 if (!uid_is_valid(uid
))
66 return -ENXIO
; /* we return ENXIO instead of EINVAL
67 * here, to make it easy to distinguish
68 * invalid numeric uids from invalid
77 int parse_uid_range(const char *s
, uid_t
*ret_lower
, uid_t
*ret_upper
) {
78 _cleanup_free_
char *word
= NULL
;
86 r
= extract_first_word(&s
, &word
, "-", EXTRACT_DONT_COALESCE_SEPARATORS
);
92 r
= parse_uid(word
, &l
);
96 /* Check for the upper bound and extract it if needed */
98 /* Single number with no dash. */
101 /* Trailing dash is an error. */
104 r
= parse_uid(s
, &u
);
117 char* getlogname_malloc(void) {
121 if (isatty_safe(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
126 return uid_to_name(uid
);
129 char* getusername_malloc(void) {
132 e
= secure_getenv("USER");
136 return uid_to_name(getuid());
139 bool is_nologin_shell(const char *shell
) {
140 return PATH_IN_SET(shell
,
141 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
142 * message and exits. Different distributions place the binary at different places though,
143 * hence let's list them all. */
148 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
149 * any message printing. Different distributions place the binary at various places but at
150 * least not in the 'sbin' directory. */
157 bool shell_is_placeholder(const char *shell
) {
158 return isempty(shell
) || is_nologin_shell(shell
);
161 const char* default_root_shell_at(int rfd
) {
162 /* We want to use the preferred shell, i.e. DEFAULT_USER_SHELL, which usually
163 * will be /bin/bash. Fall back to /bin/sh if DEFAULT_USER_SHELL is not found,
164 * or any access errors. */
166 assert(rfd
>= 0 || rfd
== AT_FDCWD
);
168 int r
= chaseat(rfd
, DEFAULT_USER_SHELL
, CHASE_AT_RESOLVE_IN_ROOT
, NULL
, NULL
);
169 if (r
< 0 && r
!= -ENOENT
)
170 log_debug_errno(r
, "Failed to look up shell '%s': %m", DEFAULT_USER_SHELL
);
172 return DEFAULT_USER_SHELL
;
177 const char* default_root_shell(const char *root
) {
178 _cleanup_close_
int rfd
= -EBADF
;
180 rfd
= open(empty_to_root(root
), O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
184 return default_root_shell_at(rfd
);
187 static int synthesize_user_creds(
188 const char **username
,
189 uid_t
*ret_uid
, gid_t
*ret_gid
,
190 const char **ret_home
,
191 const char **ret_shell
,
192 UserCredsFlags flags
) {
197 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
198 * their user record data. */
200 if (STR_IN_SET(*username
, "root", "0")) {
210 *ret_shell
= default_root_shell(NULL
);
215 if (STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534") &&
216 synthesize_nobody()) {
217 *username
= NOBODY_USER_NAME
;
220 *ret_uid
= UID_NOBODY
;
222 *ret_gid
= GID_NOBODY
;
224 *ret_home
= FLAGS_SET(flags
, USER_CREDS_SUPPRESS_PLACEHOLDER
) ? NULL
: "/";
226 *ret_shell
= FLAGS_SET(flags
, USER_CREDS_SUPPRESS_PLACEHOLDER
) ? NULL
: NOLOGIN
;
235 const char **username
,
236 uid_t
*ret_uid
, gid_t
*ret_gid
,
237 const char **ret_home
,
238 const char **ret_shell
,
239 UserCredsFlags flags
) {
241 bool patch_username
= false;
242 uid_t u
= UID_INVALID
;
248 assert((ret_home
|| ret_shell
) || !(flags
& (USER_CREDS_SUPPRESS_PLACEHOLDER
|USER_CREDS_CLEAN
)));
250 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
251 (!ret_home
&& !ret_shell
)) {
253 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
254 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
255 * user database will override the synthetic records instead — except if the user is only interested in
256 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
257 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
258 * Simply because there are valid usecase where the user might change the home directory or the shell
259 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
262 r
= synthesize_user_creds(username
, ret_uid
, ret_gid
, ret_home
, ret_shell
, flags
);
265 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
269 if (parse_uid(*username
, &u
) >= 0) {
273 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
274 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
275 * then let's pick the real username from /etc/passwd. */
277 patch_username
= true;
278 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !ret_gid
&& !ret_home
&& !ret_shell
) {
280 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
281 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then just return that
282 * and don't complain. */
291 p
= getpwnam(*username
);
294 /* getpwnam() may fail with ENOENT if /etc/passwd is missing.
295 * For us that is equivalent to the name not being defined. */
296 r
= IN_SET(errno
, 0, ENOENT
) ? -ESRCH
: -errno
;
298 /* If the user requested that we only synthesize as fallback, do so now */
299 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
))
300 if (synthesize_user_creds(username
, ret_uid
, ret_gid
, ret_home
, ret_shell
, flags
) >= 0)
306 if (ret_uid
&& !uid_is_valid(p
->pw_uid
))
309 if (ret_gid
&& !gid_is_valid(p
->pw_gid
))
313 *ret_uid
= p
->pw_uid
;
316 *ret_gid
= p
->pw_gid
;
319 /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
320 *ret_home
= (FLAGS_SET(flags
, USER_CREDS_SUPPRESS_PLACEHOLDER
) && empty_or_root(p
->pw_dir
)) ||
321 (FLAGS_SET(flags
, USER_CREDS_CLEAN
) && (!path_is_valid(p
->pw_dir
) || !path_is_absolute(p
->pw_dir
)))
325 *ret_shell
= (FLAGS_SET(flags
, USER_CREDS_SUPPRESS_PLACEHOLDER
) && shell_is_placeholder(p
->pw_shell
)) ||
326 (FLAGS_SET(flags
, USER_CREDS_CLEAN
) && (!path_is_valid(p
->pw_shell
) || !path_is_absolute(p
->pw_shell
)))
327 ? NULL
: p
->pw_shell
;
330 *username
= p
->pw_name
;
335 static int synthesize_group_creds(
336 const char **groupname
,
342 if (STR_IN_SET(*groupname
, "root", "0")) {
351 if (STR_IN_SET(*groupname
, NOBODY_GROUP_NAME
, "65534") &&
352 synthesize_nobody()) {
353 *groupname
= NOBODY_GROUP_NAME
;
356 *ret_gid
= GID_NOBODY
;
364 int get_group_creds(const char **groupname
, gid_t
*ret_gid
, UserCredsFlags flags
) {
365 bool patch_groupname
= false;
373 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
)) {
374 r
= synthesize_group_creds(groupname
, ret_gid
);
377 if (r
!= -ENOMEDIUM
) /* not a groupname we can synthesize */
381 if (parse_gid(*groupname
, &id
) >= 0) {
386 patch_groupname
= true;
387 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
)) {
395 g
= getgrnam(*groupname
);
399 /* getgrnam() may fail with ENOENT if /etc/group is missing.
400 * For us that is equivalent to the name not being defined. */
401 r
= IN_SET(errno
, 0, ENOENT
) ? -ESRCH
: -errno
;
403 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
))
404 if (synthesize_group_creds(groupname
, ret_gid
) >= 0)
411 if (!gid_is_valid(g
->gr_gid
))
414 *ret_gid
= g
->gr_gid
;
418 *groupname
= g
->gr_name
;
423 char* uid_to_name(uid_t uid
) {
427 /* Shortcut things to avoid NSS lookups */
429 return strdup("root");
430 if (uid
== UID_NOBODY
&& synthesize_nobody())
431 return strdup(NOBODY_USER_NAME
);
433 if (uid_is_valid(uid
)) {
434 _cleanup_free_
struct passwd
*pw
= NULL
;
436 r
= getpwuid_malloc(uid
, &pw
);
438 return strdup(pw
->pw_name
);
441 if (asprintf(&ret
, UID_FMT
, uid
) < 0)
447 char* gid_to_name(gid_t gid
) {
452 return strdup("root");
453 if (gid
== GID_NOBODY
&& synthesize_nobody())
454 return strdup(NOBODY_GROUP_NAME
);
456 if (gid_is_valid(gid
)) {
457 _cleanup_free_
struct group
*gr
= NULL
;
459 r
= getgrgid_malloc(gid
, &gr
);
461 return strdup(gr
->gr_name
);
464 if (asprintf(&ret
, GID_FMT
, gid
) < 0)
470 static bool gid_list_has(const gid_t
*list
, size_t size
, gid_t val
) {
471 assert(list
|| size
== 0);
473 FOREACH_ARRAY(i
, list
, size
)
480 int in_gid(gid_t gid
) {
481 _cleanup_free_ gid_t
*gids
= NULL
;
487 if (getegid() == gid
)
490 if (!gid_is_valid(gid
))
493 ngroups
= getgroups_alloc(&gids
);
497 return gid_list_has(gids
, ngroups
, gid
);
500 int in_group(const char *name
) {
504 r
= get_group_creds(&name
, &gid
, 0);
511 int merge_gid_lists(const gid_t
*list1
, size_t size1
, const gid_t
*list2
, size_t size2
, gid_t
**ret
) {
515 if (size2
> INT_MAX
- size1
)
518 gid_t
*buf
= new(gid_t
, size1
+ size2
);
522 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
523 for (size_t i
= 0; i
< size1
; i
++)
524 if (!gid_list_has(buf
, nresult
, list1
[i
]))
525 buf
[nresult
++] = list1
[i
];
526 for (size_t i
= 0; i
< size2
; i
++)
527 if (!gid_list_has(buf
, nresult
, list2
[i
]))
528 buf
[nresult
++] = list2
[i
];
533 int getgroups_alloc(gid_t
**ret
) {
538 for (unsigned attempt
= 0;;) {
539 _cleanup_free_ gid_t
*p
= NULL
;
541 p
= new(gid_t
, ngroups
);
545 ngroups
= getgroups(ngroups
, p
);
555 /* Give up eventually */
559 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
560 * to use (in multi-threaded programs), hence let's call this in a loop. */
561 ngroups
= getgroups(0, NULL
);
572 int get_home_dir(char **ret
) {
573 _cleanup_free_
struct passwd
*p
= NULL
;
580 /* Take the user specified one */
581 e
= secure_getenv("HOME");
582 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
585 /* Hardcode home directory for root and nobody to avoid NSS */
591 if (u
== UID_NOBODY
&& synthesize_nobody()) {
596 /* Check the database... */
597 r
= getpwuid_malloc(u
, &p
);
602 if (!path_is_valid(e
) || !path_is_absolute(e
))
606 return path_simplify_alloc(e
, ret
);
609 int get_shell(char **ret
) {
610 _cleanup_free_
struct passwd
*p
= NULL
;
617 /* Take the user specified one */
618 e
= secure_getenv("SHELL");
619 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
622 /* Hardcode shell for root and nobody to avoid NSS */
625 e
= default_root_shell(NULL
);
628 if (u
== UID_NOBODY
&& synthesize_nobody()) {
633 /* Check the database... */
634 r
= getpwuid_malloc(u
, &p
);
639 if (!path_is_valid(e
) || !path_is_absolute(e
))
643 return path_simplify_alloc(e
, ret
);
646 int fully_set_uid_gid(uid_t uid
, gid_t gid
, const gid_t supplementary_gids
[], size_t n_supplementary_gids
) {
649 assert(supplementary_gids
|| n_supplementary_gids
== 0);
651 /* Sets all UIDs and all GIDs to the specified ones. Drops all auxiliary GIDs */
653 r
= maybe_setgroups(n_supplementary_gids
, supplementary_gids
);
657 if (gid_is_valid(gid
))
658 if (setresgid(gid
, gid
, gid
) < 0)
661 if (uid_is_valid(uid
))
662 if (setresuid(uid
, uid
, uid
) < 0)
668 int take_etc_passwd_lock(const char *root
) {
671 /* This is roughly the same as lckpwdf(), but not as awful. We don't want to use alarm() and signals,
672 * hence we implement our own trivial version of this.
674 * Note that shadow-utils also takes per-database locks in addition to lckpwdf(). However, we don't,
675 * given that they are redundant: they invoke lckpwdf() first and keep it during everything they do.
676 * The per-database locks are awfully racy, and thus we just won't do them. */
678 _cleanup_free_
char *path
= path_join(root
, ETC_PASSWD_LOCK_PATH
);
680 return log_oom_debug();
682 (void) mkdir_parents(path
, 0755);
684 _cleanup_close_
int fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
686 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
688 r
= unposix_lock(fd
, LOCK_EX
);
690 return log_debug_errno(r
, "Locking %s failed: %m", path
);
695 bool valid_user_group_name(const char *u
, ValidUserFlags flags
) {
698 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
699 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
700 * pretty much everything except the really worst offending names.
702 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
703 * created by other stuff, let's be more liberal. */
705 if (isempty(u
)) /* An empty user name is never valid */
708 if (parse_uid(u
, NULL
) >= 0) /* Something that parses as numeric UID string is valid exactly when the
709 * flag for it is set */
710 return FLAGS_SET(flags
, VALID_USER_ALLOW_NUMERIC
);
712 if (FLAGS_SET(flags
, VALID_USER_RELAX
)) {
714 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
715 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
716 * is bound to cause problems for example when used with an MTA), hence only filter the most
717 * obvious cases, or where things would result in an invalid entry if such a user name would
718 * show up in /etc/passwd (or equivalent getent output).
720 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
721 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
722 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
725 if (startswith(u
, " ") || endswith(u
, " ")) /* At least expect whitespace padding is removed
726 * at front and back (accept in the middle, since
727 * that's apparently a thing on Windows). Note
728 * that this also blocks usernames consisting of
729 * whitespace only. */
732 if (!utf8_is_valid(u
)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
735 if (string_has_cc(u
, NULL
)) /* CC characters are just dangerous (and \n in particular is the
736 * record separator in /etc/passwd), so we can't allow that. */
739 if (strpbrk(u
, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
740 * that. Slashes are special to file systems paths and user names
741 * typically show up in the file system as home directories, hence
742 * don't allow slashes. */
745 if (in_charset(u
, "0123456789")) /* Don't allow fully numeric strings, they might be confused
746 * with UIDs (note that this test is more broad than
747 * the parse_uid() test above, as it will cover more than
748 * the 32-bit range, and it will detect 65535 (which is in
749 * invalid UID, even though in the unsigned 32 bit range) */
752 if (u
[0] == '-' && in_charset(u
+ 1, "0123456789")) /* Don't allow negative fully numeric
753 * strings either. After all some people
754 * write 65535 as -1 (even though that's
755 * not even true on 32-bit uid_t
759 if (dot_or_dot_dot(u
)) /* User names typically become home directory names, and these two are
760 * special in that context, don't allow that. */
763 /* Compare with strict result and warn if result doesn't match */
764 if (FLAGS_SET(flags
, VALID_USER_WARN
) && !valid_user_group_name(u
, 0))
765 log_struct(LOG_NOTICE
,
766 LOG_MESSAGE("Accepting user/group name '%s', which does not match strict user/group name rules.", u
),
767 LOG_ITEM("USER_GROUP_NAME=%s", u
),
768 LOG_MESSAGE_ID(SD_MESSAGE_UNSAFE_USER_NAME_STR
));
770 /* Note that we make no restrictions on the length in relaxed mode! */
775 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
776 * however. Specifically we deviate from POSIX rules:
778 * - We don't allow empty user names (see above)
779 * - We require that names fit into the appropriate utmp field
780 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
781 * - We don't allow dashes or digit as the first character
783 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
786 if (!ascii_isalpha(u
[0]) &&
790 for (i
= u
+1; *i
; i
++)
791 if (!ascii_isalpha(*i
) &&
792 !ascii_isdigit(*i
) &&
793 !IN_SET(*i
, '_', '-'))
798 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
801 if (l
> (size_t) sz
) /* glibc: 256 */
803 if (l
> NAME_MAX
) /* must fit in a filename: 255 */
805 if (l
> sizeof_field(struct utmpx
, ut_user
) - 1) /* must fit in utmp: 31 */
812 bool valid_gecos(const char *d
) {
817 if (!utf8_is_valid(d
))
820 if (string_has_cc(d
, NULL
))
823 /* Colons are used as field separators, and hence not OK */
830 char* mangle_gecos(const char *d
) {
833 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
834 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
841 for (char *i
= mangled
; *i
; i
++) {
844 if ((uint8_t) *i
< (uint8_t) ' ' || *i
== ':') {
849 len
= utf8_encoded_valid_unichar(i
, SIZE_MAX
);
861 bool valid_home(const char *p
) {
862 /* Note that this function is also called by valid_shell(), any
863 * changes must account for that. */
868 if (!utf8_is_valid(p
))
871 if (string_has_cc(p
, NULL
))
874 if (!path_is_absolute(p
))
877 if (!path_is_normalized(p
))
880 /* Colons are used as field separators, and hence not OK */
887 bool valid_shell(const char *p
) {
888 /* We have the same requirements, so just piggy-back on the home check.
890 * Let's ignore /etc/shells because this is only applicable to real and not system users. It is also
891 * incompatible with the idea of empty /etc/. */
895 return !endswith(p
, "/"); /* one additional restriction: shells may not be dirs */
898 int maybe_setgroups(size_t size
, const gid_t
*list
) {
901 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
902 if (size
== 0) { /* Dropping all aux groups? */
903 _cleanup_free_
char *setgroups_content
= NULL
;
906 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
908 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
909 can_setgroups
= true;
913 can_setgroups
= streq(setgroups_content
, "allow");
915 if (!can_setgroups
) {
916 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
921 return RET_NERRNO(setgroups(size
, list
));
924 bool synthesize_nobody(void) {
925 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
926 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
927 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
929 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
930 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
931 * shouldn't matter as each initialization should come to the same result. */
932 static int cache
= -1;
935 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
940 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
945 if (putpwent(pw
, stream
) != 0)
946 return errno_or_else(EIO
);
951 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
956 if (putspent(sp
, stream
) != 0)
957 return errno_or_else(EIO
);
962 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
967 if (putgrent(gr
, stream
) != 0)
968 return errno_or_else(EIO
);
974 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
979 if (putsgent(sg
, stream
) != 0)
980 return errno_or_else(EIO
);
986 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
991 struct passwd
*p
= fgetpwent(stream
);
992 if (!p
&& !IN_SET(errno
, 0, ENOENT
))
999 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
1004 struct spwd
*s
= fgetspent(stream
);
1005 if (!s
&& !IN_SET(errno
, 0, ENOENT
))
1012 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
1017 struct group
*g
= fgetgrent(stream
);
1018 if (!g
&& !IN_SET(errno
, 0, ENOENT
))
1026 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
1031 struct sgrp
*s
= fgetsgent(stream
);
1032 if (!s
&& !IN_SET(errno
, 0, ENOENT
))
1040 int is_this_me(const char *username
) {
1044 /* Checks if the specified username is our current one. Passed string might be a UID or a user name. */
1046 r
= get_user_creds(&username
, &uid
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
1050 return uid
== getuid();
1053 const char* get_home_root(void) {
1056 /* For debug purposes allow overriding where we look for home dirs */
1057 e
= secure_getenv("SYSTEMD_HOME_ROOT");
1058 if (e
&& path_is_absolute(e
) && path_is_normalized(e
))
1064 static size_t getpw_buffer_size(void) {
1065 long bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1066 return bufsize
<= 0 ? 4096U : (size_t) bufsize
;
1069 static bool errno_is_user_doesnt_exist(int error
) {
1070 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
1072 return IN_SET(abs(error
), ENOENT
, ESRCH
, EBADF
, EPERM
);
1075 int getpwnam_malloc(const char *name
, struct passwd
**ret
) {
1076 size_t bufsize
= getpw_buffer_size();
1079 /* A wrapper around getpwnam_r() that allocates the necessary buffer on the heap. The caller must
1080 * free() the returned structures! */
1086 _cleanup_free_
void *buf
= NULL
;
1088 buf
= malloc0(ALIGN(sizeof(struct passwd
)) + bufsize
);
1092 struct passwd
*pw
= NULL
;
1093 r
= getpwnam_r(name
, buf
, (char*) buf
+ ALIGN(sizeof(struct passwd
)), (size_t) bufsize
, &pw
);
1097 *ret
= TAKE_PTR(buf
);
1106 /* getpwnam() may fail with ENOENT if /etc/passwd is missing. For us that is equivalent to
1107 * the name not being defined. */
1108 if (errno_is_user_doesnt_exist(r
))
1113 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct passwd
)))
1119 int getpwuid_malloc(uid_t uid
, struct passwd
**ret
) {
1120 size_t bufsize
= getpw_buffer_size();
1123 if (!uid_is_valid(uid
))
1127 _cleanup_free_
void *buf
= NULL
;
1129 buf
= malloc0(ALIGN(sizeof(struct passwd
)) + bufsize
);
1133 struct passwd
*pw
= NULL
;
1134 r
= getpwuid_r(uid
, buf
, (char*) buf
+ ALIGN(sizeof(struct passwd
)), (size_t) bufsize
, &pw
);
1138 *ret
= TAKE_PTR(buf
);
1147 if (errno_is_user_doesnt_exist(r
))
1152 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct passwd
)))
1158 static size_t getgr_buffer_size(void) {
1159 long bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1160 return bufsize
<= 0 ? 4096U : (size_t) bufsize
;
1163 int getgrnam_malloc(const char *name
, struct group
**ret
) {
1164 size_t bufsize
= getgr_buffer_size();
1171 _cleanup_free_
void *buf
= NULL
;
1173 buf
= malloc0(ALIGN(sizeof(struct group
)) + bufsize
);
1177 struct group
*gr
= NULL
;
1178 r
= getgrnam_r(name
, buf
, (char*) buf
+ ALIGN(sizeof(struct group
)), (size_t) bufsize
, &gr
);
1182 *ret
= TAKE_PTR(buf
);
1191 if (errno_is_user_doesnt_exist(r
))
1196 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct group
)))
1202 int getgrgid_malloc(gid_t gid
, struct group
**ret
) {
1203 size_t bufsize
= getgr_buffer_size();
1206 if (!gid_is_valid(gid
))
1210 _cleanup_free_
void *buf
= NULL
;
1212 buf
= malloc0(ALIGN(sizeof(struct group
)) + bufsize
);
1216 struct group
*gr
= NULL
;
1217 r
= getgrgid_r(gid
, buf
, (char*) buf
+ ALIGN(sizeof(struct group
)), (size_t) bufsize
, &gr
);
1221 *ret
= TAKE_PTR(buf
);
1230 if (errno_is_user_doesnt_exist(r
))
1235 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct group
)))