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 | * |
| 8 | * This program is free software; you can redistribute it and/or modify |
| 9 | * it under the terms of the GNU General Public License as published by |
| 10 | * the Free Software Foundation; either version 2 of the License, or |
| 11 | * (at your option) any later version. |
| 12 | * |
| 13 | * This program is distributed in the hope that it will be useful, |
| 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 16 | * General Public License for more details. |
| 17 | * |
| 18 | * You should have received a copy of the GNU General Public License |
| 19 | * along with this program; if not, write to the Free Software |
| 20 | * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 21 | */ |
| 22 | |
| 23 | #include <stdio.h> |
| 24 | #include <string.h> |
| 25 | #include <unistd.h> |
| 26 | #include <fcntl.h> |
| 27 | #include <signal.h> |
| 28 | #include <termios.h> |
| 29 | #include <sys/ioctl.h> |
| 30 | #define PWD_BUFFER_SIZE 256 |
| 31 | |
| 32 | |
| 33 | /* do nothing signal handler */ |
| 34 | static void askpass_timeout(int ignore) |
| 35 | { |
| 36 | } |
| 37 | |
| 38 | char *bb_askpass(int timeout, const char * prompt) |
| 39 | { |
| 40 | char *ret; |
| 41 | int i, size; |
| 42 | struct sigaction sa; |
| 43 | struct termios old, new; |
| 44 | static char passwd[PWD_BUFFER_SIZE]; |
| 45 | |
| 46 | tcgetattr(STDIN_FILENO, &old); |
| 47 | |
| 48 | size = sizeof(passwd); |
| 49 | ret = passwd; |
| 50 | memset(passwd, 0, size); |
| 51 | |
| 52 | fputs(prompt, stdout); |
| 53 | fflush(stdout); |
| 54 | |
| 55 | tcgetattr(STDIN_FILENO, &new); |
| 56 | new.c_iflag &= ~(IUCLC|IXON|IXOFF|IXANY); |
| 57 | new.c_lflag &= ~(ECHO|ECHOE|ECHOK|ECHONL|TOSTOP); |
| 58 | tcsetattr(STDIN_FILENO, TCSANOW, &new); |
| 59 | |
| 60 | if (timeout) { |
| 61 | sa.sa_flags = 0; |
| 62 | sa.sa_handler = askpass_timeout; |
| 63 | sigaction(SIGALRM, &sa, NULL); |
| 64 | alarm(timeout); |
| 65 | } |
| 66 | |
| 67 | if (read(STDIN_FILENO, passwd, size-1) <= 0) { |
| 68 | ret = NULL; |
| 69 | } else { |
| 70 | for(i = 0; i < size && passwd[i]; i++) { |
| 71 | if (passwd[i]== '\r' || passwd[i] == '\n') { |
| 72 | passwd[i]= 0; |
| 73 | break; |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | if (timeout) { |
| 79 | alarm(0); |
| 80 | } |
| 81 | |
| 82 | tcsetattr(STDIN_FILENO, TCSANOW, &old); |
| 83 | fputs("\n", stdout); |
| 84 | fflush(stdout); |
| 85 | return ret; |
| 86 | } |
| 87 | |