summaryrefslogtreecommitdiff
path: root/src/getpass.c
blob: 1a73b7ae0afd8705afee78a951a17fdd16d1ac43 (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
#include <config.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#ifndef _WIN32
# include <termios.h>
# include <unistd.h>
#endif

#define OUT_STREAM stdout

const char *read_pass(const char *msg)
{
#ifndef _WIN32
    struct termios old, new;
#endif
    static char input[128];
    char *p;

    fputs(msg, stderr);

#ifndef _WIN32
    /* Turn echoing off and fail if we can't. */
    if (tcgetattr(fileno(OUT_STREAM), &old) != 0) {
	perror("tcgetattr");
	exit(1);
    }

    new = old;
    new.c_lflag &= ~ECHO;
    if (tcsetattr(fileno(OUT_STREAM), TCSAFLUSH, &new) != 0) {
	perror("tcsetattr");
	exit(1);
    }
#endif

    /* Read the password. */
    p = fgets(input, sizeof(input), stdin);

#ifndef _WIN32
    /* Restore terminal. */
    (void) tcsetattr(fileno(OUT_STREAM), TCSAFLUSH, &old);
#endif

    if (p == NULL || strlen(p) == 0 || p[0] == '\n')
	return NULL;

    /* overwrite the newline */
    input[strlen(p) - 1] = 0;

    return p;
}