1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
14 #include "sd-messages.h"
16 #include "alloc-util.h"
18 #include "errno-util.h"
21 #include "format-util.h"
22 #include "lock-util.h"
25 #include "parse-util.h"
26 #include "path-util.h"
27 #include "random-util.h"
28 #include "string-util.h"
30 #include "user-util.h"
33 bool uid_is_valid(uid_t uid
) {
35 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.436. */
37 /* Some libc APIs use UID_INVALID as special placeholder */
38 if (uid
== (uid_t
) UINT32_C(0xFFFFFFFF))
41 /* A long time ago UIDs where 16 bit, hence explicitly avoid the 16-bit -1 too */
42 if (uid
== (uid_t
) UINT32_C(0xFFFF))
48 int parse_uid(const char *s
, uid_t
*ret
) {
54 assert_cc(sizeof(uid_t
) == sizeof(uint32_t));
56 /* We are very strict when parsing UIDs, and prohibit +/- as prefix, leading zero as prefix, and
57 * whitespace. We do this, since this call is often used in a context where we parse things as UID
58 * first, and if that doesn't work we fall back to NSS. Thus we really want to make sure that UIDs
59 * are parsed as UIDs only if they really really look like UIDs. */
60 r
= safe_atou32_full(s
, 10
61 | SAFE_ATO_REFUSE_PLUS_MINUS
62 | SAFE_ATO_REFUSE_LEADING_ZERO
63 | SAFE_ATO_REFUSE_LEADING_WHITESPACE
, &uid
);
67 if (!uid_is_valid(uid
))
68 return -ENXIO
; /* we return ENXIO instead of EINVAL
69 * here, to make it easy to distinguish
70 * invalid numeric uids from invalid
79 int parse_uid_range(const char *s
, uid_t
*ret_lower
, uid_t
*ret_upper
) {
80 _cleanup_free_
char *word
= NULL
;
88 r
= extract_first_word(&s
, &word
, "-", EXTRACT_DONT_COALESCE_SEPARATORS
);
94 r
= parse_uid(word
, &l
);
98 /* Check for the upper bound and extract it if needed */
100 /* Single number with no dash. */
103 /* Trailing dash is an error. */
106 r
= parse_uid(s
, &u
);
119 char* getlogname_malloc(void) {
123 if (isatty(STDIN_FILENO
) && fstat(STDIN_FILENO
, &st
) >= 0)
128 return uid_to_name(uid
);
131 char* getusername_malloc(void) {
134 e
= secure_getenv("USER");
138 return uid_to_name(getuid());
141 bool is_nologin_shell(const char *shell
) {
142 return PATH_IN_SET(shell
,
143 /* 'nologin' is the friendliest way to disable logins for a user account. It prints a nice
144 * message and exits. Different distributions place the binary at different places though,
145 * hence let's list them all. */
150 /* 'true' and 'false' work too for the same purpose, but are less friendly as they don't do
151 * any message printing. Different distributions place the binary at various places but at
152 * least not in the 'sbin' directory. */
159 const char* default_root_shell_at(int rfd
) {
160 /* We want to use the preferred shell, i.e. DEFAULT_USER_SHELL, which usually
161 * will be /bin/bash. Fall back to /bin/sh if DEFAULT_USER_SHELL is not found,
162 * or any access errors. */
164 assert(rfd
>= 0 || rfd
== AT_FDCWD
);
166 int r
= chaseat(rfd
, DEFAULT_USER_SHELL
, CHASE_AT_RESOLVE_IN_ROOT
, NULL
, NULL
);
167 if (r
< 0 && r
!= -ENOENT
)
168 log_debug_errno(r
, "Failed to look up shell '%s': %m", DEFAULT_USER_SHELL
);
170 return DEFAULT_USER_SHELL
;
175 const char* default_root_shell(const char *root
) {
176 _cleanup_close_
int rfd
= -EBADF
;
178 rfd
= open(empty_to_root(root
), O_CLOEXEC
| O_DIRECTORY
| O_PATH
);
182 return default_root_shell_at(rfd
);
185 static int synthesize_user_creds(
186 const char **username
,
187 uid_t
*ret_uid
, gid_t
*ret_gid
,
188 const char **ret_home
,
189 const char **ret_shell
,
190 UserCredsFlags flags
) {
195 /* We enforce some special rules for uid=0 and uid=65534: in order to avoid NSS lookups for root we hardcode
196 * their user record data. */
198 if (STR_IN_SET(*username
, "root", "0")) {
208 *ret_shell
= default_root_shell(NULL
);
213 if (STR_IN_SET(*username
, NOBODY_USER_NAME
, "65534") &&
214 synthesize_nobody()) {
215 *username
= NOBODY_USER_NAME
;
218 *ret_uid
= UID_NOBODY
;
220 *ret_gid
= GID_NOBODY
;
222 *ret_home
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: "/";
224 *ret_shell
= FLAGS_SET(flags
, USER_CREDS_CLEAN
) ? NULL
: NOLOGIN
;
233 const char **username
,
234 uid_t
*ret_uid
, gid_t
*ret_gid
,
235 const char **ret_home
,
236 const char **ret_shell
,
237 UserCredsFlags flags
) {
239 bool patch_username
= false;
240 uid_t u
= UID_INVALID
;
247 if (!FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
) ||
248 (!ret_home
&& !ret_shell
)) {
250 /* So here's the deal: normally, we'll try to synthesize all records we can synthesize, and override
251 * the user database with that. However, if the user specifies USER_CREDS_PREFER_NSS then the
252 * user database will override the synthetic records instead — except if the user is only interested in
253 * the UID and/or GID (but not the home directory, or the shell), in which case we'll always override
254 * the user database (i.e. the USER_CREDS_PREFER_NSS flag has no effect in this case). Why?
255 * Simply because there are valid usecase where the user might change the home directory or the shell
256 * of the relevant users, but changing the UID/GID mappings for them is something we explicitly don't
259 r
= synthesize_user_creds(username
, ret_uid
, ret_gid
, ret_home
, ret_shell
, flags
);
262 if (r
!= -ENOMEDIUM
) /* not a username we can synthesize */
266 if (parse_uid(*username
, &u
) >= 0) {
270 /* If there are multiple users with the same id, make sure to leave $USER to the configured value
271 * instead of the first occurrence in the database. However if the uid was configured by a numeric uid,
272 * then let's pick the real username from /etc/passwd. */
274 patch_username
= true;
275 else if (FLAGS_SET(flags
, USER_CREDS_ALLOW_MISSING
) && !ret_gid
&& !ret_home
&& !ret_shell
) {
277 /* If the specified user is a numeric UID and it isn't in the user database, and the caller
278 * passed USER_CREDS_ALLOW_MISSING and was only interested in the UID, then just return that
279 * and don't complain. */
288 p
= getpwnam(*username
);
291 /* getpwnam() may fail with ENOENT if /etc/passwd is missing.
292 * For us that is equivalent to the name not being defined. */
293 r
= IN_SET(errno
, 0, ENOENT
) ? -ESRCH
: -errno
;
295 /* If the user requested that we only synthesize as fallback, do so now */
296 if (FLAGS_SET(flags
, USER_CREDS_PREFER_NSS
))
297 if (synthesize_user_creds(username
, ret_uid
, ret_gid
, ret_home
, ret_shell
, flags
) >= 0)
303 if (ret_uid
&& !uid_is_valid(p
->pw_uid
))
306 if (ret_gid
&& !gid_is_valid(p
->pw_gid
))
310 *ret_uid
= p
->pw_uid
;
313 *ret_gid
= p
->pw_gid
;
316 /* Note: we don't insist on normalized paths, since there are setups that have /./ in the path */
317 *ret_home
= (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
318 (empty_or_root(p
->pw_dir
) ||
319 !path_is_valid(p
->pw_dir
) ||
320 !path_is_absolute(p
->pw_dir
))) ? NULL
: p
->pw_dir
;
323 *ret_shell
= (FLAGS_SET(flags
, USER_CREDS_CLEAN
) &&
324 (isempty(p
->pw_shell
) ||
325 !path_is_valid(p
->pw_shell
) ||
326 !path_is_absolute(p
->pw_shell
) ||
327 is_nologin_shell(p
->pw_shell
))) ? 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 for (size_t i
= 0; i
< size
; i
++)
477 int in_gid(gid_t gid
) {
478 _cleanup_free_ gid_t
*gids
= NULL
;
484 if (getegid() == gid
)
487 if (!gid_is_valid(gid
))
490 ngroups
= getgroups_alloc(&gids
);
494 return gid_list_has(gids
, ngroups
, gid
);
497 int in_group(const char *name
) {
501 r
= get_group_creds(&name
, &gid
, 0);
508 int merge_gid_lists(const gid_t
*list1
, size_t size1
, const gid_t
*list2
, size_t size2
, gid_t
**ret
) {
512 if (size2
> INT_MAX
- size1
)
515 gid_t
*buf
= new(gid_t
, size1
+ size2
);
519 /* Duplicates need to be skipped on merging, otherwise they'll be passed on and stored in the kernel. */
520 for (size_t i
= 0; i
< size1
; i
++)
521 if (!gid_list_has(buf
, nresult
, list1
[i
]))
522 buf
[nresult
++] = list1
[i
];
523 for (size_t i
= 0; i
< size2
; i
++)
524 if (!gid_list_has(buf
, nresult
, list2
[i
]))
525 buf
[nresult
++] = list2
[i
];
530 int getgroups_alloc(gid_t
** gids
) {
532 _cleanup_free_ gid_t
*p
= NULL
;
534 unsigned attempt
= 0;
536 allocated
= new(gid_t
, ngroups
);
542 ngroups
= getgroups(ngroups
, p
);
548 /* Give up eventually */
552 /* Get actual size needed, and size the array explicitly. Note that this is potentially racy
553 * to use (in multi-threaded programs), hence let's call this in a loop. */
554 ngroups
= getgroups(0, NULL
);
562 p
= allocated
= new(gid_t
, ngroups
);
571 int get_home_dir(char **ret
) {
572 _cleanup_free_
struct passwd
*p
= NULL
;
579 /* Take the user specified one */
580 e
= secure_getenv("HOME");
581 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
584 /* Hardcode home directory for root and nobody to avoid NSS */
590 if (u
== UID_NOBODY
&& synthesize_nobody()) {
595 /* Check the database... */
596 r
= getpwuid_malloc(u
, &p
);
601 if (!path_is_valid(e
) || !path_is_absolute(e
))
605 return path_simplify_alloc(e
, ret
);
608 int get_shell(char **ret
) {
609 _cleanup_free_
struct passwd
*p
= NULL
;
616 /* Take the user specified one */
617 e
= secure_getenv("SHELL");
618 if (e
&& path_is_valid(e
) && path_is_absolute(e
))
621 /* Hardcode shell for root and nobody to avoid NSS */
624 e
= default_root_shell(NULL
);
627 if (u
== UID_NOBODY
&& synthesize_nobody()) {
632 /* Check the database... */
633 r
= getpwuid_malloc(u
, &p
);
638 if (!path_is_valid(e
) || !path_is_absolute(e
))
642 return path_simplify_alloc(e
, ret
);
645 int fully_set_uid_gid(uid_t uid
, gid_t gid
, const gid_t supplementary_gids
[], size_t n_supplementary_gids
) {
648 assert(supplementary_gids
|| n_supplementary_gids
== 0);
650 /* Sets all UIDs and all GIDs to the specified ones. Drops all auxiliary GIDs */
652 r
= maybe_setgroups(n_supplementary_gids
, supplementary_gids
);
656 if (gid_is_valid(gid
))
657 if (setresgid(gid
, gid
, gid
) < 0)
660 if (uid_is_valid(uid
))
661 if (setresuid(uid
, uid
, uid
) < 0)
667 int take_etc_passwd_lock(const char *root
) {
670 /* This is roughly the same as lckpwdf(), but not as awful. We don't want to use alarm() and signals,
671 * hence we implement our own trivial version of this.
673 * Note that shadow-utils also takes per-database locks in addition to lckpwdf(). However, we don't,
674 * given that they are redundant: they invoke lckpwdf() first and keep it during everything they do.
675 * The per-database locks are awfully racy, and thus we just won't do them. */
677 _cleanup_free_
char *path
= path_join(root
, ETC_PASSWD_LOCK_PATH
);
679 return log_oom_debug();
681 (void) mkdir_parents(path
, 0755);
683 _cleanup_close_
int fd
= open(path
, O_WRONLY
|O_CREAT
|O_CLOEXEC
|O_NOCTTY
|O_NOFOLLOW
, 0600);
685 return log_debug_errno(errno
, "Cannot open %s: %m", path
);
687 r
= unposix_lock(fd
, LOCK_EX
);
689 return log_debug_errno(r
, "Locking %s failed: %m", path
);
694 bool valid_user_group_name(const char *u
, ValidUserFlags flags
) {
697 /* Checks if the specified name is a valid user/group name. There are two flavours of this call:
698 * strict mode is the default which is POSIX plus some extra rules; and relaxed mode where we accept
699 * pretty much everything except the really worst offending names.
701 * Whenever we synthesize users ourselves we should use the strict mode. But when we process users
702 * created by other stuff, let's be more liberal. */
704 if (isempty(u
)) /* An empty user name is never valid */
707 if (parse_uid(u
, NULL
) >= 0) /* Something that parses as numeric UID string is valid exactly when the
708 * flag for it is set */
709 return FLAGS_SET(flags
, VALID_USER_ALLOW_NUMERIC
);
711 if (FLAGS_SET(flags
, VALID_USER_RELAX
)) {
713 /* In relaxed mode we just check very superficially. Apparently SSSD and other stuff is
714 * extremely liberal (way too liberal if you ask me, even inserting "@" in user names, which
715 * is bound to cause problems for example when used with an MTA), hence only filter the most
716 * obvious cases, or where things would result in an invalid entry if such a user name would
717 * show up in /etc/passwd (or equivalent getent output).
719 * Note that we stepped far out of POSIX territory here. It's not our fault though, but
720 * SSSD's, Samba's and everybody else who ignored POSIX on this. (I mean, I am happy to step
721 * outside of POSIX' bounds any day, but I must say in this case I probably wouldn't
724 if (startswith(u
, " ") || endswith(u
, " ")) /* At least expect whitespace padding is removed
725 * at front and back (accept in the middle, since
726 * that's apparently a thing on Windows). Note
727 * that this also blocks usernames consisting of
728 * whitespace only. */
731 if (!utf8_is_valid(u
)) /* We want to synthesize JSON from this, hence insist on UTF-8 */
734 if (string_has_cc(u
, NULL
)) /* CC characters are just dangerous (and \n in particular is the
735 * record separator in /etc/passwd), so we can't allow that. */
738 if (strpbrk(u
, ":/")) /* Colons are the field separator in /etc/passwd, we can't allow
739 * that. Slashes are special to file systems paths and user names
740 * typically show up in the file system as home directories, hence
741 * don't allow slashes. */
744 if (in_charset(u
, "0123456789")) /* Don't allow fully numeric strings, they might be confused
745 * with UIDs (note that this test is more broad than
746 * the parse_uid() test above, as it will cover more than
747 * the 32-bit range, and it will detect 65535 (which is in
748 * invalid UID, even though in the unsigned 32 bit range) */
751 if (u
[0] == '-' && in_charset(u
+ 1, "0123456789")) /* Don't allow negative fully numeric
752 * strings either. After all some people
753 * write 65535 as -1 (even though that's
754 * not even true on 32-bit uid_t
758 if (dot_or_dot_dot(u
)) /* User names typically become home directory names, and these two are
759 * special in that context, don't allow that. */
762 /* Compare with strict result and warn if result doesn't match */
763 if (FLAGS_SET(flags
, VALID_USER_WARN
) && !valid_user_group_name(u
, 0))
764 log_struct(LOG_NOTICE
,
765 LOG_MESSAGE("Accepting user/group name '%s', which does not match strict user/group name rules.", u
),
766 "USER_GROUP_NAME=%s", u
,
767 "MESSAGE_ID=" SD_MESSAGE_UNSAFE_USER_NAME_STR
);
769 /* Note that we make no restrictions on the length in relaxed mode! */
774 /* Also see POSIX IEEE Std 1003.1-2008, 2016 Edition, 3.437. We are a bit stricter here
775 * however. Specifically we deviate from POSIX rules:
777 * - We don't allow empty user names (see above)
778 * - We require that names fit into the appropriate utmp field
779 * - We don't allow any dots (this conflicts with chown syntax which permits dots as user/group name separator)
780 * - We don't allow dashes or digit as the first character
782 * Note that other systems are even more restrictive, and don't permit underscores or uppercase characters.
785 if (!ascii_isalpha(u
[0]) &&
789 for (i
= u
+1; *i
; i
++)
790 if (!ascii_isalpha(*i
) &&
791 !ascii_isdigit(*i
) &&
792 !IN_SET(*i
, '_', '-'))
797 sz
= sysconf(_SC_LOGIN_NAME_MAX
);
802 if (l
> NAME_MAX
) /* must fit in a filename */
804 if (l
> UT_NAMESIZE
- 1)
811 bool valid_gecos(const char *d
) {
816 if (!utf8_is_valid(d
))
819 if (string_has_cc(d
, NULL
))
822 /* Colons are used as field separators, and hence not OK */
829 char* mangle_gecos(const char *d
) {
832 /* Makes sure the provided string becomes valid as a GEGOS field, by dropping bad chars. glibc's
833 * putwent() only changes \n and : to spaces. We do more: replace all CC too, and remove invalid
840 for (char *i
= mangled
; *i
; i
++) {
843 if ((uint8_t) *i
< (uint8_t) ' ' || *i
== ':') {
848 len
= utf8_encoded_valid_unichar(i
, SIZE_MAX
);
860 bool valid_home(const char *p
) {
861 /* Note that this function is also called by valid_shell(), any
862 * changes must account for that. */
867 if (!utf8_is_valid(p
))
870 if (string_has_cc(p
, NULL
))
873 if (!path_is_absolute(p
))
876 if (!path_is_normalized(p
))
879 /* Colons are used as field separators, and hence not OK */
886 int maybe_setgroups(size_t size
, const gid_t
*list
) {
889 /* Check if setgroups is allowed before we try to drop all the auxiliary groups */
890 if (size
== 0) { /* Dropping all aux groups? */
891 _cleanup_free_
char *setgroups_content
= NULL
;
894 r
= read_one_line_file("/proc/self/setgroups", &setgroups_content
);
896 /* Old kernels don't have /proc/self/setgroups, so assume we can use setgroups */
897 can_setgroups
= true;
901 can_setgroups
= streq(setgroups_content
, "allow");
903 if (!can_setgroups
) {
904 log_debug("Skipping setgroups(), /proc/self/setgroups is set to 'deny'");
909 return RET_NERRNO(setgroups(size
, list
));
912 bool synthesize_nobody(void) {
913 /* Returns true when we shall synthesize the "nobody" user (which we do by default). This can be turned off by
914 * touching /etc/systemd/dont-synthesize-nobody in order to provide upgrade compatibility with legacy systems
915 * that used the "nobody" user name and group name for other UIDs/GIDs than 65534.
917 * Note that we do not employ any kind of synchronization on the following caching variable. If the variable is
918 * accessed in multi-threaded programs in the worst case it might happen that we initialize twice, but that
919 * shouldn't matter as each initialization should come to the same result. */
920 static int cache
= -1;
923 cache
= access("/etc/systemd/dont-synthesize-nobody", F_OK
) < 0;
928 int putpwent_sane(const struct passwd
*pw
, FILE *stream
) {
933 if (putpwent(pw
, stream
) != 0)
934 return errno_or_else(EIO
);
939 int putspent_sane(const struct spwd
*sp
, FILE *stream
) {
944 if (putspent(sp
, stream
) != 0)
945 return errno_or_else(EIO
);
950 int putgrent_sane(const struct group
*gr
, FILE *stream
) {
955 if (putgrent(gr
, stream
) != 0)
956 return errno_or_else(EIO
);
962 int putsgent_sane(const struct sgrp
*sg
, FILE *stream
) {
967 if (putsgent(sg
, stream
) != 0)
968 return errno_or_else(EIO
);
974 int fgetpwent_sane(FILE *stream
, struct passwd
**pw
) {
979 struct passwd
*p
= fgetpwent(stream
);
980 if (!p
&& errno
!= ENOENT
)
981 return errno_or_else(EIO
);
987 int fgetspent_sane(FILE *stream
, struct spwd
**sp
) {
992 struct spwd
*s
= fgetspent(stream
);
993 if (!s
&& errno
!= ENOENT
)
994 return errno_or_else(EIO
);
1000 int fgetgrent_sane(FILE *stream
, struct group
**gr
) {
1005 struct group
*g
= fgetgrent(stream
);
1006 if (!g
&& errno
!= ENOENT
)
1007 return errno_or_else(EIO
);
1014 int fgetsgent_sane(FILE *stream
, struct sgrp
**sg
) {
1019 struct sgrp
*s
= fgetsgent(stream
);
1020 if (!s
&& errno
!= ENOENT
)
1021 return errno_or_else(EIO
);
1028 int is_this_me(const char *username
) {
1032 /* Checks if the specified username is our current one. Passed string might be a UID or a user name. */
1034 r
= get_user_creds(&username
, &uid
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
1038 return uid
== getuid();
1041 const char* get_home_root(void) {
1044 /* For debug purposes allow overriding where we look for home dirs */
1045 e
= secure_getenv("SYSTEMD_HOME_ROOT");
1046 if (e
&& path_is_absolute(e
) && path_is_normalized(e
))
1052 static size_t getpw_buffer_size(void) {
1053 long bufsize
= sysconf(_SC_GETPW_R_SIZE_MAX
);
1054 return bufsize
<= 0 ? 4096U : (size_t) bufsize
;
1057 static bool errno_is_user_doesnt_exist(int error
) {
1058 /* See getpwnam(3) and getgrnam(3): those codes and others can be returned if the user or group are
1060 return IN_SET(abs(error
), ENOENT
, ESRCH
, EBADF
, EPERM
);
1063 int getpwnam_malloc(const char *name
, struct passwd
**ret
) {
1064 size_t bufsize
= getpw_buffer_size();
1067 /* A wrapper around getpwnam_r() that allocates the necessary buffer on the heap. The caller must
1068 * free() the returned sructured! */
1074 _cleanup_free_
void *buf
= NULL
;
1076 buf
= malloc(ALIGN(sizeof(struct passwd
)) + bufsize
);
1080 struct passwd
*pw
= NULL
;
1081 r
= getpwnam_r(name
, buf
, (char*) buf
+ ALIGN(sizeof(struct passwd
)), (size_t) bufsize
, &pw
);
1085 *ret
= TAKE_PTR(buf
);
1094 /* getpwnam() may fail with ENOENT if /etc/passwd is missing. For us that is equivalent to
1095 * the name not being defined. */
1096 if (errno_is_user_doesnt_exist(r
))
1101 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct passwd
)))
1107 int getpwuid_malloc(uid_t uid
, struct passwd
**ret
) {
1108 size_t bufsize
= getpw_buffer_size();
1111 if (!uid_is_valid(uid
))
1115 _cleanup_free_
void *buf
= NULL
;
1117 buf
= malloc(ALIGN(sizeof(struct passwd
)) + bufsize
);
1121 struct passwd
*pw
= NULL
;
1122 r
= getpwuid_r(uid
, buf
, (char*) buf
+ ALIGN(sizeof(struct passwd
)), (size_t) bufsize
, &pw
);
1126 *ret
= TAKE_PTR(buf
);
1135 if (errno_is_user_doesnt_exist(r
))
1140 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct passwd
)))
1146 static size_t getgr_buffer_size(void) {
1147 long bufsize
= sysconf(_SC_GETGR_R_SIZE_MAX
);
1148 return bufsize
<= 0 ? 4096U : (size_t) bufsize
;
1151 int getgrnam_malloc(const char *name
, struct group
**ret
) {
1152 size_t bufsize
= getgr_buffer_size();
1159 _cleanup_free_
void *buf
= NULL
;
1161 buf
= malloc(ALIGN(sizeof(struct group
)) + bufsize
);
1165 struct group
*gr
= NULL
;
1166 r
= getgrnam_r(name
, buf
, (char*) buf
+ ALIGN(sizeof(struct group
)), (size_t) bufsize
, &gr
);
1170 *ret
= TAKE_PTR(buf
);
1179 if (errno_is_user_doesnt_exist(r
))
1184 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct group
)))
1190 int getgrgid_malloc(gid_t gid
, struct group
**ret
) {
1191 size_t bufsize
= getgr_buffer_size();
1194 if (!gid_is_valid(gid
))
1198 _cleanup_free_
void *buf
= NULL
;
1200 buf
= malloc(ALIGN(sizeof(struct group
)) + bufsize
);
1204 struct group
*gr
= NULL
;
1205 r
= getgrgid_r(gid
, buf
, (char*) buf
+ ALIGN(sizeof(struct group
)), (size_t) bufsize
, &gr
);
1209 *ret
= TAKE_PTR(buf
);
1218 if (errno_is_user_doesnt_exist(r
))
1223 if (bufsize
> SIZE_MAX
/2 - ALIGN(sizeof(struct group
)))