aboutsummaryrefslogtreecommitdiff
path: root/src/bin/pg_id/pg_id.c
blob: b118e5e2078e2c6beed44779bd261ed662ebab05 (plain)
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
/*
 * pg_id.c
 *
 * A crippled id utility for use in various shell scripts in use by PostgreSQL
 * (in particular initdb)
 *
 * Copyright (C) 2000 by PostgreSQL Global Development Group
 *
 * $Header: /cvsroot/pgsql/src/bin/pg_id/Attic/pg_id.c,v 1.13 2000/02/16 13:15:25 momjian Exp $
 */
#include <postgres.h>

#ifdef HAVE_GETOPT_H
#include <getopt.h>
#endif
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char * argv[])
{
    int c;
    int nameflag = 0,
        realflag = 0,
        userflag = 0;
    const char * username = NULL;

    struct passwd * pw;

    while ((c = getopt(argc, argv, "nru")) != -1)
    {
        switch(c)
        {
            case 'n':
                nameflag = 1;
                break;
            case 'r':
                realflag = 1;
                break;
            case 'u':
                userflag = 1;
                break;
            default:
                fprintf(stderr, "Usage: %s [-n] [-r] [-u] [username]\n", argv[0]);
                exit(1);
        }
    }

    if (argc - optind >= 1)
        username = argv[optind];

    if (nameflag && !userflag)
    {
        fprintf(stderr, "%s: -n must be used together with -u\n", argv[0]);
        exit(1);
    }
    if (username && realflag)
    {
        fprintf(stderr, "%s: -r cannot be used when a user name is given\n", argv[0]);
        exit(1);
    }


    if (username)
    {
        pw = getpwnam(username);
        if (!pw)
        {
            fprintf(stderr, "%s: %s: no such user\n", argv[0], username);
            exit(1);
        }
    }
    else if (realflag)
        pw = getpwuid(getuid());
    else
        pw = getpwuid(geteuid());
            
    if (!pw)
    {
        perror(argv[0]);
        exit(1);
    }

    if (!userflag)
        printf("uid=%d(%s)\n", (int)pw->pw_uid, pw->pw_name);
    else if (nameflag)
        puts(pw->pw_name);
    else
        printf("%d\n", (int)pw->pw_uid);

    return 0;
}