blob: 097a0a290c3d7eb454ce71ca4e407a570fe5939c [file] [log] [blame]
Eric Andersen6f9a7782004-05-01 01:27:30 +00001/* 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 *
Bernhard Reutner-Fischer20f40002006-01-30 17:17:14 +00008 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
Eric Andersen6f9a7782004-05-01 01:27:30 +00009 */
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>
Bernhard Reutner-Fischer20f40002006-01-30 17:17:14 +000018
19#include "libbb.h"
Eric Andersen6f9a7782004-05-01 01:27:30 +000020
21/* do nothing signal handler */
Bernhard Reutner-Fischer20f40002006-01-30 17:17:14 +000022static void askpass_timeout(int ATTRIBUTE_UNUSED ignore)
Eric Andersen6f9a7782004-05-01 01:27:30 +000023{
24}
25
26char *bb_askpass(int timeout, const char * prompt)
27{
Denis Vlasenko6429aab2006-09-23 12:22:11 +000028 static char passwd[64];
29
Eric Andersen6f9a7782004-05-01 01:27:30 +000030 char *ret;
Denis Vlasenko6429aab2006-09-23 12:22:11 +000031 int i;
Eric Andersen6f9a7782004-05-01 01:27:30 +000032 struct sigaction sa;
33 struct termios old, new;
Eric Andersen6f9a7782004-05-01 01:27:30 +000034
35 tcgetattr(STDIN_FILENO, &old);
Rob Landleye422af62005-12-12 07:02:15 +000036 tcflush(STDIN_FILENO, TCIFLUSH);
Eric Andersen6f9a7782004-05-01 01:27:30 +000037
Denis Vlasenko6429aab2006-09-23 12:22:11 +000038 memset(passwd, 0, sizeof(passwd));
Eric Andersen6f9a7782004-05-01 01:27:30 +000039
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
Denis Vlasenko6429aab2006-09-23 12:22:11 +000055 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')
Denis Vlasenkoab24e182006-11-30 16:41:15 +000063 passwd[i] = '\0';
Denis Vlasenko6429aab2006-09-23 12:22:11 +000064 } while (passwd[i++]);
Eric Andersen6f9a7782004-05-01 01:27:30 +000065 }
66
67 if (timeout) {
68 alarm(0);
69 }
70
71 tcsetattr(STDIN_FILENO, TCSANOW, &old);
Denis Vlasenko6429aab2006-09-23 12:22:11 +000072 puts("");
Eric Andersen6f9a7782004-05-01 01:27:30 +000073 fflush(stdout);
74 return ret;
75}