small stupid changes. no code changes
[oweals/busybox.git] / libbb / bb_askpass.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Ask for a password
4  * I use a static buffer in this function.  Plan accordingly.
5  *
6  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7  *
8  * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
9  */
10
11 #include <stdio.h>
12 #include <string.h>
13 #include <unistd.h>
14 #include <fcntl.h>
15 #include <signal.h>
16 #include <termios.h>
17 #include <sys/ioctl.h>
18
19 #include "libbb.h"
20
21 /* do nothing signal handler */
22 static void askpass_timeout(int ATTRIBUTE_UNUSED ignore)
23 {
24 }
25
26 char *bb_askpass(int timeout, const char * prompt)
27 {
28         static char passwd[64];
29
30         char *ret;
31         int i;
32         struct sigaction sa;
33         struct termios old, new;
34
35         tcgetattr(STDIN_FILENO, &old);
36         tcflush(STDIN_FILENO, TCIFLUSH);
37
38         memset(passwd, 0, sizeof(passwd));
39
40         fputs(prompt, stdout);
41         fflush(stdout);
42
43         tcgetattr(STDIN_FILENO, &new);
44         new.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
45         new.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
46         tcsetattr(STDIN_FILENO, TCSANOW, &new);
47
48         if (timeout) {
49                 sa.sa_flags = 0;
50                 sa.sa_handler = askpass_timeout;
51                 sigaction(SIGALRM, &sa, NULL);
52                 alarm(timeout);
53         }
54
55         ret = NULL;
56         if (read(STDIN_FILENO, passwd, sizeof(passwd)-1) > 0) {
57                 ret = passwd;
58                 i = 0;
59                 /* Last byte is guaranteed to be 0
60                    (read did not overwrite it) */
61                 do {
62                         if (passwd[i] == '\r' || passwd[i] == '\n')
63                                 passwd[i] = '\0';
64                 } while (passwd[i++]);
65         }
66
67         if (timeout) {
68                 alarm(0);
69         }
70
71         tcsetattr(STDIN_FILENO, TCSANOW, &old);
72         puts("");
73         fflush(stdout);
74         return ret;
75 }