Eric Andersen | 6f9a778 | 2004-05-01 01:27:30 +0000 | [diff] [blame] | 1 | /* 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-Fischer | 20f4000 | 2006-01-30 17:17:14 +0000 | [diff] [blame] | 8 | * Licensed under GPLv2 or later, see file LICENSE in this tarball for details. |
Eric Andersen | 6f9a778 | 2004-05-01 01:27:30 +0000 | [diff] [blame] | 9 | */ |
| 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-Fischer | 20f4000 | 2006-01-30 17:17:14 +0000 | [diff] [blame] | 18 | |
| 19 | #include "libbb.h" |
Eric Andersen | 6f9a778 | 2004-05-01 01:27:30 +0000 | [diff] [blame] | 20 | #define PWD_BUFFER_SIZE 256 |
| 21 | |
| 22 | |
| 23 | /* do nothing signal handler */ |
Bernhard Reutner-Fischer | 20f4000 | 2006-01-30 17:17:14 +0000 | [diff] [blame] | 24 | static void askpass_timeout(int ATTRIBUTE_UNUSED ignore) |
Eric Andersen | 6f9a778 | 2004-05-01 01:27:30 +0000 | [diff] [blame] | 25 | { |
| 26 | } |
| 27 | |
| 28 | char *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 Landley | e422af6 | 2005-12-12 07:02:15 +0000 | [diff] [blame] | 37 | tcflush(STDIN_FILENO, TCIFLUSH); |
Eric Andersen | 6f9a778 | 2004-05-01 01:27:30 +0000 | [diff] [blame] | 38 | |
| 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 | |