Debian Codegraph @

src/utils/simple_get_pass.cpp

raw
1 /*
2 * This File is part of Davix, The IO library for HTTP based protocols
3 * Copyright (C) 2013 Adrien Devresse <[email protected]>, CERN
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
18 *
19 */
20
21
22 #include <davix_internal_config.hpp>
23 #include "simple_get_pass.h"
24 #include <cstdio>
25 #include <iostream>
26
27 #if defined HAVE_TERMIOS_H
28 #include <termios.h>
29 #elif defined HAVE_GETPASS
30 #include <unistd.h>
31 #elif defined HAVE_SETCONSOLEMODE
32 #include <windows.h>
33 #else
34 #error "impossible to compile simple_get_pass"
35 #endif
36
37 int simple_get_pass(char* passwd, size_t max_size){
38 int ret = 0;
39 #if defined HAVE_TERMIOS_H
40 struct termios old_term, new_term;
41 FILE* stream = stdin;
42
43 /* Turn echoing off and fail if we can't. */
44 if (tcgetattr (fileno (stream), &old_term) != 0)
45 return -1;
46 new_term = old_term;
47 new_term.c_lflag &= ~ECHO;
48 if (tcsetattr (fileno (stream), TCSAFLUSH, &new_term) != 0)
49 return -1;
50
51 /* Read the password. */
52 std::cin.getline(passwd, max_size);
53 ret = strlen(passwd);
54
55 /* Restore terminal. */
56 (void) tcsetattr (fileno (stream), TCSAFLUSH, &old_term);
57
58 #elif HAVE_SETCONSOLEMODE
59 HANDLE hstdin = GetStdHandle(STD_INPUT_HANDLE);
60 DWORD mode;
61
62 if (!GetConsoleMode(hstdin, &mode))
63 return -1;
64
65 if (hstdin == INVALID_HANDLE_VALUE || !(SetConsoleMode(hstdin, 0)))
66 return -1;
67 std::cin.getline(passwd, max_size);
68 ret = strlen(passwd);
69
70 if (!SetConsoleMode(hstdin, mode))
71 return -1;
72 #else
73 char* p;
74 if((p = getpass("")) == NULL)
75 return -1;
76 *passwd = strdup(p);
77 ret = strlen(p);
78 #endif
79 return ret;
80
81 }
82
83
84