whitespace and comment format fixes, no code changes
[oweals/busybox.git] / libbb / bb_askpass.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Ask for a password
4  *
5  * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
6  *
7  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
8  */
9 #include "libbb.h"
10
11 /* do nothing signal handler */
12 static void askpass_timeout(int UNUSED_PARAM ignore)
13 {
14 }
15
16 char* FAST_FUNC bb_ask_stdin(const char *prompt)
17 {
18         return bb_ask(STDIN_FILENO, 0, prompt);
19 }
20 char* FAST_FUNC bb_ask(const int fd, int timeout, const char *prompt)
21 {
22         /* Was static char[BIGNUM] */
23         enum { sizeof_passwd = 128 };
24
25         char *passwd;
26         char *ret;
27         int i;
28         struct sigaction sa, oldsa;
29         struct termios tio, oldtio;
30
31         tcflush(fd, TCIFLUSH);
32         /* Was buggy: was printing prompt *before* flushing input,
33          * which was upsetting "expect" based scripts of some users.
34          */
35         fputs(prompt, stdout);
36         fflush_all();
37
38         tcgetattr(fd, &oldtio);
39         tio = oldtio;
40 #if 0
41         /* Switch off UPPERCASE->lowercase conversion (never used since 198x)
42          * and XON/XOFF (why we want to mess with this??)
43          */
44 # ifndef IUCLC
45 #  define IUCLC 0
46 # endif
47         tio.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
48 #endif
49         /* Switch off echo */
50         tio.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);
51         tcsetattr(fd, TCSANOW, &tio);
52
53         memset(&sa, 0, sizeof(sa));
54         /* sa.sa_flags = 0; - no SA_RESTART! */
55         /* SIGINT and SIGALRM will interrupt reads below */
56         sa.sa_handler = askpass_timeout;
57         sigaction(SIGINT, &sa, &oldsa);
58         if (timeout) {
59                 sigaction_set(SIGALRM, &sa);
60                 alarm(timeout);
61         }
62
63         passwd = auto_string(xmalloc(sizeof_passwd));
64         ret = passwd;
65         i = 0;
66         while (1) {
67                 int r = read(fd, &ret[i], 1);
68                 if ((i == 0 && r == 0) /* EOF (^D) with no password */
69                  || r < 0
70                 ) {
71                         /* read is interrupted by timeout or ^C */
72                         ret = NULL;
73                         break;
74                 }
75                 if (r == 0 /* EOF */
76                  || ret[i] == '\r' || ret[i] == '\n' /* EOL */
77                  || ++i == sizeof_passwd-1 /* line limit */
78                 ) {
79                         ret[i] = '\0';
80                         break;
81                 }
82         }
83
84         if (timeout) {
85                 alarm(0);
86         }
87         sigaction_set(SIGINT, &oldsa);
88         tcsetattr(fd, TCSANOW, &oldtio);
89         bb_putchar('\n');
90         fflush_all();
91         return ret;
92 }