2 * psql - the PostgreSQL interactive terminal
4 * Copyright 2000 by PostgreSQL Global Development Group
6 * $Header: /cvsroot/pgsql/src/port/sprompt.c,v 1.1 2003/08/08 04:52:22 momjian Exp $
13 * Generalized function especially intended for reading in usernames and
14 * password interactively. Reads from /dev/tty or stdin/stderr.
16 * prompt: The prompt to print
17 * maxlen: How many characters to accept
18 * echo: Set to false if you want to hide what is entered (for passwords)
20 * Returns a malloc()'ed string with the input (w/o trailing newline).
32 bool prompt_state = false;
33 extern char *simple_prompt(const char *prompt, int maxlen, bool echo);
36 simple_prompt(const char *prompt, int maxlen, bool echo)
44 struct termios t_orig,
54 destination = (char *) malloc(maxlen + 1);
58 prompt_state = true; /* disable SIGINT */
61 * Do not try to collapse these into one "w+" mode file. Doesn't work
62 * on some platforms (eg, HPUX 10.20).
64 termin = fopen("/dev/tty", "r");
65 termout = fopen("/dev/tty", "w");
66 if (!termin || !termout)
79 tcgetattr(fileno(termin), &t);
82 tcsetattr(fileno(termin), TCSAFLUSH, &t);
88 /* get a new handle to turn echo off */
89 t_orig = (LPDWORD) malloc(sizeof(DWORD));
90 t = GetStdHandle(STD_INPUT_HANDLE);
92 /* save the old configuration first */
93 GetConsoleMode(t, t_orig);
95 /* set to the new mode */
96 SetConsoleMode(t, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT);
103 fputs(gettext(prompt), termout);
107 if (fgets(destination, maxlen + 1, termin) == NULL)
108 destination[0] = '\0';
110 length = strlen(destination);
111 if (length > 0 && destination[length - 1] != '\n')
113 /* eat rest of the line */
119 if (fgets(buf, sizeof(buf), termin) == NULL)
121 buflen = strlen(buf);
122 } while (buflen > 0 && buf[buflen - 1] != '\n');
125 if (length > 0 && destination[length - 1] == '\n')
126 /* remove trailing newline */
127 destination[length - 1] = '\0';
129 #ifdef HAVE_TERMIOS_H
132 tcsetattr(fileno(termin), TCSAFLUSH, &t_orig);
133 fputs("\n", termout);
140 /* reset to the original console mode */
141 SetConsoleMode(t, *t_orig);
142 fputs("\n", termout);
155 prompt_state = false; /* SIGINT okay again */