Fix Linux getlogin{_r,} implementation
[glibc.git] / sysdeps / unix / sysv / linux / getlogin_r.c
blobd07846ccb89b3487b25118e95c06a6d26291766d
1 /* Copyright (C) 2010 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Lesser General Public
6 License as published by the Free Software Foundation; either
7 version 2.1 of the License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Lesser General Public License for more details.
14 You should have received a copy of the GNU Lesser General Public
15 License along with the GNU C Library; if not, write to the Free
16 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
17 02111-1307 USA. */
19 #include <pwd.h>
20 #include <unistd.h>
21 #include <not-cancel.h>
23 #define STATIC static
24 static int getlogin_r_fd0 (char *name, size_t namesize);
25 #define getlogin_r getlogin_r_fd0
26 #include <sysdeps/unix/getlogin_r.c>
27 #undef getlogin_r
30 int
31 attribute_hidden
32 __getlogin_r_loginuid (name, namesize)
33 char *name;
34 size_t namesize;
36 int fd = open_not_cancel_2 ("/proc/self/loginuid", O_RDONLY);
37 if (fd == -1)
38 return 1;
40 ssize_t n = TEMP_FAILURE_RETRY (read_not_cancel (fd, name, namesize));
41 close_not_cancel_no_status (fd);
43 uid_t uid;
44 char *endp;
45 if (n <= 0
46 || (uid = strtoul (name, &endp, 10), endp == name || *endp != '\0'))
47 return 1;
49 size_t buflen = 1024;
50 char *buf = alloca (buflen);
51 bool use_malloc = false;
52 struct passwd pwd;
53 struct passwd *tpwd;
54 int res;
56 while ((res = __getpwuid_r (uid, &pwd, buf, buflen, &tpwd)) != 0)
57 if (__libc_use_alloca (2 * buflen))
58 extend_alloca (buf, buflen, 2 * buflen);
59 else
61 buflen *= 2;
62 char *newp = realloc (use_malloc ? buf : NULL, buflen);
63 if (newp == NULL)
65 fail:
66 if (use_malloc)
67 free (buf);
68 return 1;
70 buf = newp;
71 use_malloc = true;
74 if (tpwd == NULL)
75 goto fail;
77 strncpy (name, pwd.pw_name, namesize - 1);
78 name[namesize - 1] = '\0';
80 if (use_malloc)
81 free (buf);
83 return 0;
87 /* Return the login name of the user, or NULL if it can't be determined.
88 The returned pointer, if not NULL, is good only until the next call. */
90 int
91 getlogin_r (name, namesize)
92 char *name;
93 size_t namesize;
95 if (__getlogin_r_loginuid (name, namesize) == 0)
96 return 0;
98 return getlogin_r_fd0 (name, namesize);
100 libc_hidden_def (getlogin_r)