1 /* vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80: */
2 /*
3  * Copyright 2017 Red Hat, Inc.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17 
18 #pragma once
19 
20 #include <string.h>
21 #include <ctype.h>
22 
23 #ifdef _WIN32
24 static const char *
jwe_getpass(const char * prompt)25 jwe_getpass(const char *prompt)
26 {
27     static char pwd[4096];
28 
29     fprintf(stdout, "%s", prompt);
30 
31     memset(pwd, 0, sizeof(pwd));
32     for (size_t i = 0; i < sizeof(pwd) - 1; i++) {
33         int c = fgetc(stdin);
34         if (c == EOF || !isprint(c) || isspace(c))
35             break;
36 
37         pwd[i] = c;
38     }
39 
40     return pwd;
41 }
42 #else
43 #include <termios.h>
44 static const char *
jwe_getpass(const char * prompt)45 jwe_getpass(const char *prompt)
46 {
47     static char pwd[4096];
48     struct termios of, nf;
49     FILE *tty = NULL;
50 
51     tty = fopen("/dev/tty", "r+");
52     if (!tty)
53         return NULL;
54 
55     tcgetattr(fileno(tty), &of);
56     nf = of;
57     nf.c_lflag &= ~ECHO;
58     nf.c_lflag |= ECHONL;
59 
60     if (tcsetattr(fileno(tty), TCSANOW, &nf) != 0) {
61         fclose(tty);
62         return NULL;
63     }
64 
65     fprintf(tty, "%s", prompt);
66 
67     memset(pwd, 0, sizeof(pwd));
68     for (size_t i = 0; i < sizeof(pwd) - 1; i++) {
69         int c = fgetc(tty);
70         if (c == EOF || !isprint(c) || isspace(c))
71             break;
72 
73         pwd[i] = c;
74     }
75 
76     tcsetattr(fileno(tty), TCSANOW, &of);
77     fclose(tty);
78     return pwd;
79 }
80 #endif
81