1 /*-------------------------------------------------------------------------
4 * simple_prompt() routine
6 * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/port/sprompt.c,v 1.22 2010/01/02 16:58:13 momjian Exp $
13 *-------------------------------------------------------------------------
20 * Generalized function especially intended for reading in usernames and
21 * password interactively. Reads from /dev/tty or stdin/stderr.
23 * prompt: The prompt to print
24 * maxlen: How many characters to accept
25 * echo: Set to false if you want to hide what is entered (for passwords)
27 * Returns a malloc()'ed string with the input (w/o trailing newline).
35 extern char *simple_prompt(const char *prompt, int maxlen, bool echo);
38 simple_prompt(const char *prompt, int maxlen, bool echo)
46 struct termios t_orig,
51 LPDWORD t_orig = NULL;
55 destination = (char *) malloc(maxlen + 1);
60 * Do not try to collapse these into one "w+" mode file. Doesn't work on
61 * some platforms (eg, HPUX 10.20).
63 termin = fopen(DEVTTY, "r");
64 termout = fopen(DEVTTY, "w");
65 if (!termin || !termout
67 /* See DEVTTY comment for msys */
68 || (getenv("OSTYPE") && strcmp(getenv("OSTYPE"), "msys") == 0)
83 tcgetattr(fileno(termin), &t);
86 tcsetattr(fileno(termin), TCSAFLUSH, &t);
92 /* get a new handle to turn echo off */
93 t_orig = (LPDWORD) malloc(sizeof(DWORD));
94 t = GetStdHandle(STD_INPUT_HANDLE);
96 /* save the old configuration first */
97 GetConsoleMode(t, t_orig);
99 /* set to the new mode */
100 SetConsoleMode(t, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT);
107 fputs(_(prompt), termout);
111 if (fgets(destination, maxlen + 1, termin) == NULL)
112 destination[0] = '\0';
114 length = strlen(destination);
115 if (length > 0 && destination[length - 1] != '\n')
117 /* eat rest of the line */
123 if (fgets(buf, sizeof(buf), termin) == NULL)
125 buflen = strlen(buf);
126 } while (buflen > 0 && buf[buflen - 1] != '\n');
129 if (length > 0 && destination[length - 1] == '\n')
130 /* remove trailing newline */
131 destination[length - 1] = '\0';
133 #ifdef HAVE_TERMIOS_H
136 tcsetattr(fileno(termin), TCSAFLUSH, &t_orig);
137 fputs("\n", termout);
144 /* reset to the original console mode */
145 SetConsoleMode(t, *t_orig);
146 fputs("\n", termout);