File: get_username.c

package info (click to toggle)
putty 0.78-2%2Bdeb12u2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 13,964 kB
  • sloc: ansic: 137,777; python: 7,775; perl: 1,798; makefile: 133; sh: 111
file content (52 lines) | stat: -rw-r--r-- 1,149 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
 * Implementation of get_username() for Unix.
 */

#include <unistd.h>
#include <pwd.h>

#include "putty.h"

char *get_username(void)
{
    struct passwd *p;
    uid_t uid = getuid();
    char *user, *ret = NULL;

    /*
     * First, find who we think we are using getlogin. If this
     * agrees with our uid, we'll go along with it. This should
     * allow sharing of uids between several login names whilst
     * coping correctly with people who have su'ed.
     */
    user = getlogin();
#if HAVE_SETPWENT
    setpwent();
#endif
    if (user)
        p = getpwnam(user);
    else
        p = NULL;
    if (p && p->pw_uid == uid) {
        /*
         * The result of getlogin() really does correspond to
         * our uid. Fine.
         */
        ret = user;
    } else {
        /*
         * If that didn't work, for whatever reason, we'll do
         * the simpler version: look up our uid in the password
         * file and map it straight to a name.
         */
        p = getpwuid(uid);
        if (!p)
            return NULL;
        ret = p->pw_name;
    }
#if HAVE_ENDPWENT
    endpwent();
#endif

    return dupstr(ret);
}