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