libbb: rename bb_ask -> bb_ask_noecho, bb_ask_confirmation -> bb_ask_y_confirmation
[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_noecho_stdin(const char *prompt)
17 {
18         return bb_ask_noecho(STDIN_FILENO, 0, prompt);
19 }
20 char* FAST_FUNC bb_ask_noecho(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         /* Switch off echo */
41         tio.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL);
42         tcsetattr(fd, TCSANOW, &tio);
43
44         memset(&sa, 0, sizeof(sa));
45         /* sa.sa_flags = 0; - no SA_RESTART! */
46         /* SIGINT and SIGALRM will interrupt reads below */
47         sa.sa_handler = askpass_timeout;
48         sigaction(SIGINT, &sa, &oldsa);
49         if (timeout) {
50                 sigaction_set(SIGALRM, &sa);
51                 alarm(timeout);
52         }
53
54         passwd = auto_string(xmalloc(sizeof_passwd));
55         ret = passwd;
56         i = 0;
57         while (1) {
58                 int r = read(fd, &ret[i], 1);
59                 if ((i == 0 && r == 0) /* EOF (^D) with no password */
60                  || r < 0 /* read is interrupted by timeout or ^C */
61                 ) {
62                         ret = NULL;
63                         break;
64                 }
65                 if (r == 0 /* EOF */
66                  || ret[i] == '\r' || ret[i] == '\n' /* EOL */
67                  || ++i == sizeof_passwd-1 /* line limit */
68                 ) {
69                         ret[i] = '\0';
70                         break;
71                 }
72         }
73
74         if (timeout) {
75                 alarm(0);
76         }
77         sigaction_set(SIGINT, &oldsa);
78         tcsetattr(fd, TCSANOW, &oldtio);
79         bb_putchar('\n');
80         fflush_all();
81         return ret;
82 }