2 RCSID("$OpenBSD: cli.c,v 1.9 2001/02/10 12:44:02 markus Exp $");
8 static int cli_input = -1;
9 static int cli_output = -1;
10 static int cli_from_stdin = 0;
23 cli_open(int from_stdin)
25 if (cli_input >= 0 && cli_output >= 0 && cli_from_stdin == from_stdin)
29 if (!cli_from_stdin && cli_input >= 0) {
30 (void)close(cli_input);
32 cli_input = STDIN_FILENO;
33 cli_output = STDERR_FILENO;
35 cli_input = cli_output = open(_PATH_TTY, O_RDWR);
37 fatal("You have no controlling tty. Cannot read passphrase.");
40 cli_from_stdin = from_stdin;
42 return cli_input >= 0 && cli_output >= 0 && cli_from_stdin == from_stdin;
48 if (!cli_from_stdin && cli_input >= 0)
63 cli_echo_disable(void)
66 sigaddset(&nset, SIGTSTP);
67 (void) sigprocmask(SIG_BLOCK, &nset, &oset);
71 memset(&nsa, 0, sizeof(nsa));
72 nsa.sa_handler = intrcatch;
73 (void) sigaction(SIGINT, &nsa, &osa);
76 if (tcgetattr(cli_input, &otio) == 0 && (otio.c_lflag & ECHO)) {
79 ntio.c_lflag &= ~(ECHO | ECHOE | ECHOK | ECHONL);
80 (void) tcsetattr(cli_input, TCSANOW, &ntio);
86 cli_echo_restore(void)
88 if (echo_modified != 0) {
89 tcsetattr(cli_input, TCSANOW, &otio);
93 (void) sigprocmask(SIG_SETMASK, &oset, NULL);
94 (void) sigaction(SIGINT, &osa, NULL);
97 kill(getpid(), SIGINT);
99 /* XXX tty has not neccessarily drained by now? */
107 cli_read(char* buf, int size, int echo)
116 if (read(cli_input, &ch, 1) != 1)
118 if (ch == '\n' || intr != 0)
128 (void) write(cli_output, "\n", 1);
133 cli_write(const char* buf, int size)
135 int i, len, pos, ret = 0;
138 output = xmalloc(4*size);
139 for (p = output, i = 0; i < size; i++) {
140 if (buf[i] == '\n' || buf[i] == '\r')
143 p = vis(p, buf[i], 0, 0);
147 for (pos = 0; pos < len; pos += ret) {
148 ret = write(cli_output, output + pos, len - pos);
159 * Presents a prompt and returns the response allocated with xmalloc().
160 * Uses /dev/tty or stdin/out depending on arg. Optionally disables echo
161 * of response depending on arg. Tries to ensure that no other userland
162 * buffer is storing the response.
165 cli_read_passphrase(const char* prompt, int from_stdin, int echo_enable)
170 if (!cli_open(from_stdin))
171 fatal("Cannot read passphrase.");
175 cli_write(prompt, strlen(prompt));
176 cli_read(buf, sizeof buf, echo_enable);
181 memset(buf, 0, sizeof(buf));
186 cli_prompt(char* prompt, int echo_enable)
188 return cli_read_passphrase(prompt, 0, echo_enable);
195 cli_write(mesg, strlen(mesg));
196 cli_write("\n", strlen("\n"));