90e39a21f75f0fcdda763fca5899ceff4c948922
[openssl.git] / crypto / ui / ui_openssl.c
1 /*
2  * Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <openssl/e_os2.h>
11 #include <openssl/err.h>
12
13 /*
14  * need for #define _POSIX_C_SOURCE arises whenever you pass -ansi to gcc
15  * [maybe others?], because it masks interfaces not discussed in standard,
16  * sigaction and fileno included. -pedantic would be more appropriate for the
17  * intended purposes, but we can't prevent users from adding -ansi.
18  */
19 #if defined(OPENSSL_SYS_VXWORKS)
20 # include <sys/types.h>
21 #endif
22
23 #if !defined(_POSIX_C_SOURCE) && defined(OPENSSL_SYS_VMS)
24 # ifndef _POSIX_C_SOURCE
25 #  define _POSIX_C_SOURCE 2
26 # endif
27 #endif
28 #include <signal.h>
29 #include <stdio.h>
30 #include <string.h>
31 #include <errno.h>
32
33 #if !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS)
34 # ifdef OPENSSL_UNISTD
35 #  include OPENSSL_UNISTD
36 # else
37 #  include <unistd.h>
38 # endif
39 /*
40  * If unistd.h defines _POSIX_VERSION, we conclude that we are on a POSIX
41  * system and have sigaction and termios.
42  */
43 # if defined(_POSIX_VERSION)
44
45 #  define SIGACTION
46 #  if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY)
47 #   define TERMIOS
48 #  endif
49
50 # endif
51 #endif
52
53 /* 06-Apr-92 Luke Brennan    Support for VMS */
54 #include "ui_locl.h"
55 #include "internal/cryptlib.h"
56
57 #ifdef OPENSSL_SYS_VMS          /* prototypes for sys$whatever */
58 # include <starlet.h>
59 # ifdef __DECC
60 #  pragma message disable DOLLARID
61 # endif
62 #endif
63
64 #ifdef WIN_CONSOLE_BUG
65 # include <windows.h>
66 # ifndef OPENSSL_SYS_WINCE
67 #  include <wincon.h>
68 # endif
69 #endif
70
71 /*
72  * There are 6 types of terminal interface supported, TERMIO, TERMIOS, VMS,
73  * MSDOS, WIN32 Console and SGTTY.
74  *
75  * If someone defines one of the macros TERMIO, TERMIOS or SGTTY, it will
76  * remain respected.  Otherwise, we default to TERMIOS except for a few
77  * systems that require something different.
78  *
79  * Note: we do not use SGTTY unless it's defined by the configuration.  We
80  * may eventually opt to remove it's use entirely.
81  */
82
83 #if !defined(TERMIOS) && !defined(TERMIO) && !defined(SGTTY)
84
85 # if defined(_LIBC)
86 #  undef  TERMIOS
87 #  define TERMIO
88 #  undef  SGTTY
89 /*
90  * We know that VMS, MSDOS, VXWORKS, use entirely other mechanisms.
91  */
92 # elif !defined(OPENSSL_SYS_VMS) \
93         && !defined(OPENSSL_SYS_MSDOS) \
94         && !defined(OPENSSL_SYS_VXWORKS)
95 #  define TERMIOS
96 #  undef  TERMIO
97 #  undef  SGTTY
98 # endif
99
100 #endif
101
102 #ifdef TERMIOS
103 # include <termios.h>
104 # define TTY_STRUCT             struct termios
105 # define TTY_FLAGS              c_lflag
106 # define TTY_get(tty,data)      tcgetattr(tty,data)
107 # define TTY_set(tty,data)      tcsetattr(tty,TCSANOW,data)
108 #endif
109
110 #ifdef TERMIO
111 # include <termio.h>
112 # define TTY_STRUCT             struct termio
113 # define TTY_FLAGS              c_lflag
114 # define TTY_get(tty,data)      ioctl(tty,TCGETA,data)
115 # define TTY_set(tty,data)      ioctl(tty,TCSETA,data)
116 #endif
117
118 #ifdef SGTTY
119 # include <sgtty.h>
120 # define TTY_STRUCT             struct sgttyb
121 # define TTY_FLAGS              sg_flags
122 # define TTY_get(tty,data)      ioctl(tty,TIOCGETP,data)
123 # define TTY_set(tty,data)      ioctl(tty,TIOCSETP,data)
124 #endif
125
126 #if !defined(_LIBC) && !defined(OPENSSL_SYS_MSDOS) && !defined(OPENSSL_SYS_VMS)
127 # include <sys/ioctl.h>
128 #endif
129
130 #ifdef OPENSSL_SYS_MSDOS
131 # include <conio.h>
132 #endif
133
134 #ifdef OPENSSL_SYS_VMS
135 # include <ssdef.h>
136 # include <iodef.h>
137 # include <ttdef.h>
138 # include <descrip.h>
139 struct IOSB {
140     short iosb$w_value;
141     short iosb$w_count;
142     long iosb$l_info;
143 };
144 #endif
145
146 #ifndef NX509_SIG
147 # define NX509_SIG 32
148 #endif
149
150 /* Define globals.  They are protected by a lock */
151 #ifdef SIGACTION
152 static struct sigaction savsig[NX509_SIG];
153 #else
154 static void (*savsig[NX509_SIG]) (int);
155 #endif
156
157 #ifdef OPENSSL_SYS_VMS
158 static struct IOSB iosb;
159 static $DESCRIPTOR(terminal, "TT");
160 static long tty_orig[3], tty_new[3]; /* XXX Is there any guarantee that this
161                                       * will always suffice for the actual
162                                       * structures? */
163 static long status;
164 static unsigned short channel = 0;
165 #elif defined(_WIN32) && !defined(_WIN32_WCE)
166 static DWORD tty_orig, tty_new;
167 #else
168 # if !defined(OPENSSL_SYS_MSDOS) || defined(__DJGPP__)
169 static TTY_STRUCT tty_orig, tty_new;
170 # endif
171 #endif
172 static FILE *tty_in, *tty_out;
173 static int is_a_tty;
174
175 /* Declare static functions */
176 #if !defined(OPENSSL_SYS_WINCE)
177 static int read_till_nl(FILE *);
178 static void recsig(int);
179 static void pushsig(void);
180 static void popsig(void);
181 #endif
182 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
183 static int noecho_fgets(char *buf, int size, FILE *tty);
184 #endif
185 static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl);
186
187 static int read_string(UI *ui, UI_STRING *uis);
188 static int write_string(UI *ui, UI_STRING *uis);
189
190 static int open_console(UI *ui);
191 static int echo_console(UI *ui);
192 static int noecho_console(UI *ui);
193 static int close_console(UI *ui);
194
195 static UI_METHOD ui_openssl = {
196     "OpenSSL default user interface",
197     open_console,
198     write_string,
199     NULL,                       /* No flusher is needed for command lines */
200     read_string,
201     close_console,
202     NULL
203 };
204
205 /* The method with all the built-in thingies */
206 UI_METHOD *UI_OpenSSL(void)
207 {
208     return &ui_openssl;
209 }
210
211 /*
212  * The following function makes sure that info and error strings are printed
213  * before any prompt.
214  */
215 static int write_string(UI *ui, UI_STRING *uis)
216 {
217     switch (UI_get_string_type(uis)) {
218     case UIT_ERROR:
219     case UIT_INFO:
220         fputs(UI_get0_output_string(uis), tty_out);
221         fflush(tty_out);
222         break;
223     case UIT_NONE:
224     case UIT_PROMPT:
225     case UIT_VERIFY:
226     case UIT_BOOLEAN:
227         break;
228     }
229     return 1;
230 }
231
232 static int read_string(UI *ui, UI_STRING *uis)
233 {
234     int ok = 0;
235
236     switch (UI_get_string_type(uis)) {
237     case UIT_BOOLEAN:
238         fputs(UI_get0_output_string(uis), tty_out);
239         fputs(UI_get0_action_string(uis), tty_out);
240         fflush(tty_out);
241         return read_string_inner(ui, uis,
242                                  UI_get_input_flags(uis) & UI_INPUT_FLAG_ECHO,
243                                  0);
244     case UIT_PROMPT:
245         fputs(UI_get0_output_string(uis), tty_out);
246         fflush(tty_out);
247         return read_string_inner(ui, uis,
248                                  UI_get_input_flags(uis) & UI_INPUT_FLAG_ECHO,
249                                  1);
250     case UIT_VERIFY:
251         fprintf(tty_out, "Verifying - %s", UI_get0_output_string(uis));
252         fflush(tty_out);
253         if ((ok = read_string_inner(ui, uis,
254                                     UI_get_input_flags(uis) &
255                                     UI_INPUT_FLAG_ECHO, 1)) <= 0)
256             return ok;
257         if (strcmp(UI_get0_result_string(uis), UI_get0_test_string(uis)) != 0) {
258             fprintf(tty_out, "Verify failure\n");
259             fflush(tty_out);
260             return 0;
261         }
262         break;
263     case UIT_NONE:
264     case UIT_INFO:
265     case UIT_ERROR:
266         break;
267     }
268     return 1;
269 }
270
271 #if !defined(OPENSSL_SYS_WINCE)
272 /* Internal functions to read a string without echoing */
273 static int read_till_nl(FILE *in)
274 {
275 # define SIZE 4
276     char buf[SIZE + 1];
277
278     do {
279         if (!fgets(buf, SIZE, in))
280             return 0;
281     } while (strchr(buf, '\n') == NULL);
282     return 1;
283 }
284
285 static volatile sig_atomic_t intr_signal;
286 #endif
287
288 static int read_string_inner(UI *ui, UI_STRING *uis, int echo, int strip_nl)
289 {
290     static int ps;
291     int ok;
292     char result[BUFSIZ];
293     int maxsize = BUFSIZ - 1;
294 #if !defined(OPENSSL_SYS_WINCE)
295     char *p = NULL;
296     int echo_eol = !echo;
297
298     intr_signal = 0;
299     ok = 0;
300     ps = 0;
301
302     pushsig();
303     ps = 1;
304
305     if (!echo && !noecho_console(ui))
306         goto error;
307     ps = 2;
308
309     result[0] = '\0';
310 # if defined(_WIN32)
311     if (is_a_tty) {
312         DWORD numread;
313 #  if defined(CP_UTF8)
314         if (GetEnvironmentVariableW(L"OPENSSL_WIN32_UTF8", NULL, 0) != 0) {
315             WCHAR wresult[BUFSIZ];
316
317             if (ReadConsoleW(GetStdHandle(STD_INPUT_HANDLE),
318                          wresult, maxsize, &numread, NULL)) {
319                 if (numread >= 2 &&
320                     wresult[numread-2] == L'\r' &&
321                     wresult[numread-1] == L'\n') {
322                     wresult[numread-2] = L'\n';
323                     numread--;
324                 }
325                 wresult[numread] = '\0';
326                 if (WideCharToMultiByte(CP_UTF8, 0, wresult, -1,
327                                         result, sizeof(result), NULL, 0) > 0)
328                     p = result;
329
330                 OPENSSL_cleanse(wresult, sizeof(wresult));
331             }
332         } else
333 #  endif
334         if (ReadConsoleA(GetStdHandle(STD_INPUT_HANDLE),
335                          result, maxsize, &numread, NULL)) {
336             if (numread >= 2 &&
337                 result[numread-2] == '\r' && result[numread-1] == '\n') {
338                 result[numread-2] = '\n';
339                 numread--;
340             }
341             result[numread] = '\0';
342             p = result;
343         }
344     } else
345 # elif defined(OPENSSL_SYS_MSDOS)
346     if (!echo) {
347         noecho_fgets(result, maxsize, tty_in);
348         p = result;             /* FIXME: noecho_fgets doesn't return errors */
349     } else
350 # endif
351     p = fgets(result, maxsize, tty_in);
352     if (p == NULL)
353         goto error;
354     if (feof(tty_in))
355         goto error;
356     if (ferror(tty_in))
357         goto error;
358     if ((p = (char *)strchr(result, '\n')) != NULL) {
359         if (strip_nl)
360             *p = '\0';
361     } else if (!read_till_nl(tty_in))
362         goto error;
363     if (UI_set_result(ui, uis, result) >= 0)
364         ok = 1;
365
366  error:
367     if (intr_signal == SIGINT)
368         ok = -1;
369     if (echo_eol)
370         fprintf(tty_out, "\n");
371     if (ps >= 2 && !echo && !echo_console(ui))
372         ok = 0;
373
374     if (ps >= 1)
375         popsig();
376 #else
377     ok = 1;
378 #endif
379
380     OPENSSL_cleanse(result, BUFSIZ);
381     return ok;
382 }
383
384 /* Internal functions to open, handle and close a channel to the console.  */
385 static int open_console(UI *ui)
386 {
387     CRYPTO_THREAD_write_lock(ui->lock);
388     is_a_tty = 1;
389
390 #if defined(OPENSSL_SYS_VXWORKS)
391     tty_in = stdin;
392     tty_out = stderr;
393 #elif defined(_WIN32) && !defined(_WIN32_WCE)
394     if ((tty_out = fopen("conout$", "w")) == NULL)
395         tty_out = stderr;
396
397     if (GetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), &tty_orig)) {
398         tty_in = stdin;
399     } else {
400         is_a_tty = 0;
401         if ((tty_in = fopen("conin$", "r")) == NULL)
402             tty_in = stdin;
403     }
404 #else
405 # ifdef OPENSSL_SYS_MSDOS
406 #  define DEV_TTY "con"
407 # else
408 #  define DEV_TTY "/dev/tty"
409 # endif
410     if ((tty_in = fopen(DEV_TTY, "r")) == NULL)
411         tty_in = stdin;
412     if ((tty_out = fopen(DEV_TTY, "w")) == NULL)
413         tty_out = stderr;
414 #endif
415
416 #if defined(TTY_get) && !defined(OPENSSL_SYS_VMS)
417     if (TTY_get(fileno(tty_in), &tty_orig) == -1) {
418 # ifdef ENOTTY
419         if (errno == ENOTTY)
420             is_a_tty = 0;
421         else
422 # endif
423 # ifdef EINVAL
424             /*
425              * Ariel Glenn ariel@columbia.edu reports that solaris can return
426              * EINVAL instead.  This should be ok
427              */
428         if (errno == EINVAL)
429             is_a_tty = 0;
430         else
431 # endif
432 # ifdef ENODEV
433             /*
434              * MacOS X returns ENODEV (Operation not supported by device),
435              * which seems appropriate.
436              */
437         if (errno == ENODEV)
438             is_a_tty = 0;
439         else
440 # endif
441             {
442                 char tmp_num[10];
443                 BIO_snprintf(tmp_num, sizeof(tmp_num) - 1, "%d", errno);
444                 UIerr(UI_F_OPEN_CONSOLE, UI_R_UNKNOWN_TTYGET_ERRNO_VALUE);
445                 ERR_add_error_data(2, "errno=", tmp_num);
446
447                 return 0;
448             }
449     }
450 #endif
451 #ifdef OPENSSL_SYS_VMS
452     status = sys$assign(&terminal, &channel, 0, 0);
453
454     /* if there isn't a TT device, something is very wrong */
455     if (status != SS$_NORMAL)
456         return 0;
457
458     status = sys$qiow(0, channel, IO$_SENSEMODE, &iosb, 0, 0, tty_orig, 12,
459                       0, 0, 0, 0);
460
461     /* If IO$_SENSEMODE doesn't work, this is not a terminal device */
462     if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
463         is_a_tty = 0;
464 #endif
465     return 1;
466 }
467
468 static int noecho_console(UI *ui)
469 {
470 #ifdef TTY_FLAGS
471     memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig));
472     tty_new.TTY_FLAGS &= ~ECHO;
473 #endif
474
475 #if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
476     if (is_a_tty && (TTY_set(fileno(tty_in), &tty_new) == -1))
477         return 0;
478 #endif
479 #ifdef OPENSSL_SYS_VMS
480     if (is_a_tty) {
481         tty_new[0] = tty_orig[0];
482         tty_new[1] = tty_orig[1] | TT$M_NOECHO;
483         tty_new[2] = tty_orig[2];
484         status = sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_new, 12,
485                           0, 0, 0, 0);
486         if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
487             return 0;
488     }
489 #endif
490 #if defined(_WIN32) && !defined(_WIN32_WCE)
491     if (is_a_tty) {
492         tty_new = tty_orig;
493         tty_new &= ~ENABLE_ECHO_INPUT;
494         SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), tty_new);
495     }
496 #endif
497     return 1;
498 }
499
500 static int echo_console(UI *ui)
501 {
502 #if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
503     memcpy(&(tty_new), &(tty_orig), sizeof(tty_orig));
504     tty_new.TTY_FLAGS |= ECHO;
505 #endif
506
507 #if defined(TTY_set) && !defined(OPENSSL_SYS_VMS)
508     if (is_a_tty && (TTY_set(fileno(tty_in), &tty_new) == -1))
509         return 0;
510 #endif
511 #ifdef OPENSSL_SYS_VMS
512     if (is_a_tty) {
513         tty_new[0] = tty_orig[0];
514         tty_new[1] = tty_orig[1] & ~TT$M_NOECHO;
515         tty_new[2] = tty_orig[2];
516         status = sys$qiow(0, channel, IO$_SETMODE, &iosb, 0, 0, tty_new, 12,
517                           0, 0, 0, 0);
518         if ((status != SS$_NORMAL) || (iosb.iosb$w_value != SS$_NORMAL))
519             return 0;
520     }
521 #endif
522 #if defined(_WIN32) && !defined(_WIN32_WCE)
523     if (is_a_tty) {
524         tty_new = tty_orig;
525         tty_new |= ENABLE_ECHO_INPUT;
526         SetConsoleMode(GetStdHandle(STD_INPUT_HANDLE), tty_new);
527     }
528 #endif
529     return 1;
530 }
531
532 static int close_console(UI *ui)
533 {
534     if (tty_in != stdin)
535         fclose(tty_in);
536     if (tty_out != stderr)
537         fclose(tty_out);
538 #ifdef OPENSSL_SYS_VMS
539     status = sys$dassgn(channel);
540     if (status != SS$_NORMAL)
541         return 0;
542 #endif
543     CRYPTO_THREAD_unlock(ui->lock);
544
545     return 1;
546 }
547
548 #if !defined(OPENSSL_SYS_WINCE)
549 /* Internal functions to handle signals and act on them */
550 static void pushsig(void)
551 {
552 # ifndef OPENSSL_SYS_WIN32
553     int i;
554 # endif
555 # ifdef SIGACTION
556     struct sigaction sa;
557
558     memset(&sa, 0, sizeof(sa));
559     sa.sa_handler = recsig;
560 # endif
561
562 # ifdef OPENSSL_SYS_WIN32
563     savsig[SIGABRT] = signal(SIGABRT, recsig);
564     savsig[SIGFPE] = signal(SIGFPE, recsig);
565     savsig[SIGILL] = signal(SIGILL, recsig);
566     savsig[SIGINT] = signal(SIGINT, recsig);
567     savsig[SIGSEGV] = signal(SIGSEGV, recsig);
568     savsig[SIGTERM] = signal(SIGTERM, recsig);
569 # else
570     for (i = 1; i < NX509_SIG; i++) {
571 #  ifdef SIGUSR1
572         if (i == SIGUSR1)
573             continue;
574 #  endif
575 #  ifdef SIGUSR2
576         if (i == SIGUSR2)
577             continue;
578 #  endif
579 #  ifdef SIGKILL
580         if (i == SIGKILL)       /* We can't make any action on that. */
581             continue;
582 #  endif
583 #  ifdef SIGACTION
584         sigaction(i, &sa, &savsig[i]);
585 #  else
586         savsig[i] = signal(i, recsig);
587 #  endif
588     }
589 # endif
590
591 # ifdef SIGWINCH
592     signal(SIGWINCH, SIG_DFL);
593 # endif
594 }
595
596 static void popsig(void)
597 {
598 # ifdef OPENSSL_SYS_WIN32
599     signal(SIGABRT, savsig[SIGABRT]);
600     signal(SIGFPE, savsig[SIGFPE]);
601     signal(SIGILL, savsig[SIGILL]);
602     signal(SIGINT, savsig[SIGINT]);
603     signal(SIGSEGV, savsig[SIGSEGV]);
604     signal(SIGTERM, savsig[SIGTERM]);
605 # else
606     int i;
607     for (i = 1; i < NX509_SIG; i++) {
608 #  ifdef SIGUSR1
609         if (i == SIGUSR1)
610             continue;
611 #  endif
612 #  ifdef SIGUSR2
613         if (i == SIGUSR2)
614             continue;
615 #  endif
616 #  ifdef SIGACTION
617         sigaction(i, &savsig[i], NULL);
618 #  else
619         signal(i, savsig[i]);
620 #  endif
621     }
622 # endif
623 }
624
625 static void recsig(int i)
626 {
627     intr_signal = i;
628 }
629 #endif
630
631 /* Internal functions specific for Windows */
632 #if defined(OPENSSL_SYS_MSDOS) && !defined(_WIN32)
633 static int noecho_fgets(char *buf, int size, FILE *tty)
634 {
635     int i;
636     char *p;
637
638     p = buf;
639     for (;;) {
640         if (size == 0) {
641             *p = '\0';
642             break;
643         }
644         size--;
645 # if defined(_WIN32)
646         i = _getch();
647 # else
648         i = getch();
649 # endif
650         if (i == '\r')
651             i = '\n';
652         *(p++) = i;
653         if (i == '\n') {
654             *p = '\0';
655             break;
656         }
657     }
658 # ifdef WIN_CONSOLE_BUG
659     /*
660      * Win95 has several evil console bugs: one of these is that the last
661      * character read using getch() is passed to the next read: this is
662      * usually a CR so this can be trouble. No STDIO fix seems to work but
663      * flushing the console appears to do the trick.
664      */
665     {
666         HANDLE inh;
667         inh = GetStdHandle(STD_INPUT_HANDLE);
668         FlushConsoleInputBuffer(inh);
669     }
670 # endif
671     return (strlen(buf));
672 }
673 #endif