fix return value of ungetc when argument is outside unsigned char range
[musl.git] / src / legacy / getpass.c
blobd51286c0b03b3b3e9109a1e20804dbb9d4f3c4a1
1 #define _GNU_SOURCE
2 #include <stdio.h>
3 #include <termios.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <string.h>
8 char *getpass(const char *prompt)
10 int fd;
11 struct termios s, t;
12 ssize_t l;
13 static char password[128];
15 if ((fd = open("/dev/tty", O_RDWR|O_NOCTTY|O_CLOEXEC)) < 0) return 0;
17 tcgetattr(fd, &t);
18 s = t;
19 t.c_lflag &= ~(ECHO|ISIG);
20 t.c_lflag |= ICANON;
21 t.c_iflag &= ~(INLCR|IGNCR);
22 t.c_iflag |= ICRNL;
23 tcsetattr(fd, TCSAFLUSH, &t);
24 tcdrain(fd);
26 dprintf(fd, "%s", prompt);
28 l = read(fd, password, sizeof password);
29 if (l >= 0) {
30 if (l > 0 && password[l-1] == '\n' || l==sizeof password) l--;
31 password[l] = 0;
34 tcsetattr(fd, TCSAFLUSH, &s);
36 dprintf(fd, "\n");
37 close(fd);
39 return l<0 ? 0 : password;