summaryrefslogtreecommitdiff
path: root/minix/lib/libc/gen/getpass.c
blob: 623439629b075d4fbba66cb1d36d85afcb2223f6 (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
/*	getpass() - read a password		Author: Kees J. Bot
 *							Feb 16 1993
 */
#include <sys/cdefs.h>
#include "namespace.h"

#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <termios.h>
#include <string.h>

#ifdef __weak_alias
__weak_alias(getpass, _getpass)
#endif

static int intr;

static void catch(int sig)
{
	intr= 1;
}

char *getpass(const char *prompt)
{
	struct sigaction osa, sa;
	struct termios cooked, raw;
	static char password[32+1];
	int fd, n= 0;

	/* Try to open the controlling terminal. */
	if ((fd= open("/dev/tty", O_RDONLY)) < 0) return NULL;

	/* Trap interrupts unless ignored. */
	intr= 0;
	sigaction(SIGINT, NULL, &osa);
	if (osa.sa_handler != SIG_IGN) {
		sigemptyset(&sa.sa_mask);
		sa.sa_flags= 0;
		sa.sa_handler= catch;
		sigaction(SIGINT, &sa, &osa);
	}

	/* Set the terminal to non-echo mode. */
	tcgetattr(fd, &cooked);
	raw= cooked;
	raw.c_iflag|= ICRNL;
	raw.c_lflag&= ~ECHO;
	raw.c_lflag|= ECHONL;
	raw.c_oflag|= OPOST | ONLCR;
	tcsetattr(fd, TCSANOW, &raw);

	/* Print the prompt.  (After setting non-echo!) */
	write(2, prompt, strlen(prompt));

	/* Read the password, 32 characters max. */
	while (read(fd, password+n, 1) > 0) {
		if (password[n] == '\n') break;
		if (n < 32) n++;
	}
	password[n]= 0;

	/* Terminal back to cooked mode. */
	tcsetattr(fd, TCSANOW, &cooked);

	close(fd);

	/* Interrupt? */
	sigaction(SIGINT, &osa, NULL);
	if (intr) raise(SIGINT);

	return password;
}