blob: 65ddd5a24a2650847d2c12d181d0c1d39040e7a4 [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#define PWD_BUFFER_SIZE 256
21
22
23/* do nothing signal handler */
Bernhard Reutner-Fischer20f40002006-01-30 17:17:14 +000024static void askpass_timeout(int ATTRIBUTE_UNUSED ignore)
Eric Andersen6f9a7782004-05-01 01:27:30 +000025{
26}
27
28char *bb_askpass(int timeout, const char * prompt)
29{
30 char *ret;
31 int i, size;
32 struct sigaction sa;
33 struct termios old, new;
34 static char passwd[PWD_BUFFER_SIZE];
35
36 tcgetattr(STDIN_FILENO, &old);
Rob Landleye422af62005-12-12 07:02:15 +000037 tcflush(STDIN_FILENO, TCIFLUSH);
Eric Andersen6f9a7782004-05-01 01:27:30 +000038
39 size = sizeof(passwd);
40 ret = passwd;
41 memset(passwd, 0, size);
42
43 fputs(prompt, stdout);
44 fflush(stdout);
45
46 tcgetattr(STDIN_FILENO, &new);
47 new.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY);
48 new.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP);
49 tcsetattr(STDIN_FILENO, TCSANOW, &new);
50
51 if (timeout) {
52 sa.sa_flags = 0;
53 sa.sa_handler = askpass_timeout;
54 sigaction(SIGALRM, &sa, NULL);
55 alarm(timeout);
56 }
57
58 if (read(STDIN_FILENO, passwd, size-1) <= 0) {
59 ret = NULL;
60 } else {
61 for(i = 0; i < size && passwd[i]; i++) {
62 if (passwd[i]== '\r' || passwd[i] == '\n') {
63 passwd[i]= 0;
64 break;
65 }
66 }
67 }
68
69 if (timeout) {
70 alarm(0);
71 }
72
73 tcsetattr(STDIN_FILENO, TCSANOW, &old);
74 fputs("\n", stdout);
75 fflush(stdout);
76 return ret;
77}
78