1 /* 2 * Copyright 2006, Haiku, Inc. All Rights Reserved. 3 * Distributed under the terms of the MIT License. 4 * 5 * Authors: 6 * Axel Dörfler, axeld@pinc-software.de 7 */ 8 9 10 #include <stdbool.h> 11 #include <stdio.h> 12 #include <termios.h> 13 #include <unistd.h> 14 15 16 char * 17 getpass(const char *prompt) 18 { 19 static char password[128]; 20 struct termios termios; 21 bool changed = false; 22 23 // Turn off echo 24 25 if (tcgetattr(fileno(stdin), &termios) == 0) { 26 struct termios noEchoTermios = termios; 27 28 noEchoTermios.c_lflag &= ~(ECHO | ISIG); 29 changed = tcsetattr(fileno(stdin), TCSAFLUSH, &noEchoTermios) == 0; 30 } 31 32 // Show prompt 33 fputs(prompt, stdout); 34 fflush(stdout); 35 36 // Read password 37 if (fgets(password, sizeof(password), stdin) != NULL) { 38 size_t length = strlen(password); 39 40 if (password[length - 1] == '\n') 41 password[length - 1] = '\0'; 42 43 if (changed) { 44 // Manually move to the next line 45 putchar('\n'); 46 } 47 } 48 49 // Restore termios setting 50 if (changed) 51 tcsetattr(fileno(stdin), TCSAFLUSH, &termios); 52 53 return password; 54 } 55