Tomato 1.28
[tomato.git] / release / src / router / busybox / libbb / bb_askpass.c
blobc0dcf0c5ff84fa52c5ec4edf2d8afd455282832f
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 tarball for details.
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 if (!passwd)
34 passwd = xmalloc(sizeof_passwd);
35 memset(passwd, 0, sizeof_passwd);
37 tcgetattr(fd, &oldtio);
38 tcflush(fd, TCIFLUSH);
39 tio = oldtio;
40 tio.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
41 tio.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
42 tcsetattr_stdin_TCSANOW(&tio);
44 memset(&sa, 0, sizeof(sa));
45 /* sa.sa_flags = 0; - no SA_RESTART! */
46 /* SIGINT and SIGALRM will interrupt read below */
47 sa.sa_handler = askpass_timeout;
48 sigaction(SIGINT, &sa, &oldsa);
49 if (timeout) {
50 sigaction_set(SIGALRM, &sa);
51 alarm(timeout);
54 fputs(prompt, stdout);
55 fflush(stdout);
56 ret = NULL;
57 /* On timeout or Ctrl-C, read will hopefully be interrupted,
58 * and we return NULL */
59 if (read(fd, passwd, sizeof_passwd - 1) > 0) {
60 ret = passwd;
61 i = 0;
62 /* Last byte is guaranteed to be 0
63 (read did not overwrite it) */
64 do {
65 if (passwd[i] == '\r' || passwd[i] == '\n')
66 passwd[i] = '\0';
67 } while (passwd[i++]);
70 if (timeout) {
71 alarm(0);
73 sigaction_set(SIGINT, &oldsa);
75 tcsetattr_stdin_TCSANOW(&oldtio);
76 bb_putchar('\n');
77 fflush(stdout);
78 return ret;