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 <string.h> 13 #include <termios.h> 14 #include <unistd.h> 15 16 17 char * 18 getpass(const char *prompt) 19 { 20 static char password[128]; 21 struct termios termios; 22 bool changed = false; 23 24 // Turn off echo 25 26 if (tcgetattr(fileno(stdin), &termios) == 0) { 27 struct termios noEchoTermios = termios; 28 29 noEchoTermios.c_lflag &= ~(ECHO | ISIG); 30 changed = tcsetattr(fileno(stdin), TCSAFLUSH, &noEchoTermios) == 0; 31 } 32 33 // Show prompt 34 fputs(prompt, stdout); 35 fflush(stdout); 36 37 // Read password 38 if (fgets(password, sizeof(password), stdin) != NULL) { 39 size_t length = strlen(password); 40 41 if (password[length - 1] == '\n') 42 password[length - 1] = '\0'; 43 44 if (changed) { 45 // Manually move to the next line 46 putchar('\n'); 47 } 48 } 49 50 // Restore termios setting 51 if (changed) 52 tcsetattr(fileno(stdin), TCSAFLUSH, &termios); 53 54 return password; 55 } 56