/* getpassword.c -- Get password via console * * GPLv2 - Copyright (C) 2008 * David Sommerseth * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 * of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * */ #include #include #include int get_console_input(char *buf, size_t len, const char *prompt, int hidden) { struct termios term_orig, term_noecho; char *ptr; // Print prompt fprintf(stdout, "%s ", prompt); if( hidden == 1 ) { // Get current terminal settings if( tcgetattr(fileno(stdin), &term_orig) ) { return -2; // Could not get the current terminal status } // Create a copy of current settings and turn off echo to terminal memcpy(&term_noecho, &term_orig, sizeof(struct termios)); term_noecho.c_lflag &= ~ECHO; if( tcsetattr(fileno(stdin), TCSAFLUSH, &term_noecho) ) { return -3; // Could not set the new terminal settings } } // Read user input from stdin fgets(buf, len, stdin); if( hidden == 1 ) { // Restore terminal to saved state tcsetattr(fileno(stdin), TCSANOW, &term_orig); } // Remove trailing spaces if( buf != NULL ) { ptr = buf + strlen(buf) - 1; while( (ptr > buf) && ((*ptr == 0x20) || (*ptr == '\n') || (*ptr == '\r')) ) { *ptr = 0; ptr--; } ptr++; } if( hidden ) { fprintf(stdout, "\n"); } return (buf != NULL ? strlen(buf) : -1); }