1/* input.c -- character input functions for readline. */
2
3/* Copyright (C) 1994-2017 Free Software Foundation, Inc.
4
5   This file is part of the GNU Readline Library (Readline), a library
6   for reading lines of text with interactive input and history editing.
7
8   Readline is free software: you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation, either version 3 of the License, or
11   (at your option) any later version.
12
13   Readline is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with Readline.  If not, see <http://www.gnu.org/licenses/>.
20*/
21
22#define READLINE_LIBRARY
23
24#if defined (__TANDEM)
25#  define _XOPEN_SOURCE_EXTENDED 1
26#  define _TANDEM_SOURCE 1
27#  include <floss.h>
28#endif
29
30#if defined (HAVE_CONFIG_H)
31#  include <config.h>
32#endif
33
34#include <sys/types.h>
35#include <fcntl.h>
36#if defined (HAVE_SYS_FILE_H)
37#  include <sys/file.h>
38#endif /* HAVE_SYS_FILE_H */
39
40#if defined (HAVE_UNISTD_H)
41#  include <unistd.h>
42#endif /* HAVE_UNISTD_H */
43
44#if defined (HAVE_STDLIB_H)
45#  include <stdlib.h>
46#else
47#  include "ansi_stdlib.h"
48#endif /* HAVE_STDLIB_H */
49
50#include <signal.h>
51
52#include "posixselect.h"
53
54#if defined (FIONREAD_IN_SYS_IOCTL)
55#  include <sys/ioctl.h>
56#endif
57
58#include <stdio.h>
59#include <errno.h>
60
61#if !defined (errno)
62extern int errno;
63#endif /* !errno */
64
65/* System-specific feature definitions and include files. */
66#include "rldefs.h"
67#include "rlmbutil.h"
68
69/* Some standard library routines. */
70#include "readline.h"
71
72#include "rlprivate.h"
73#include "rlshell.h"
74#include "xmalloc.h"
75
76/* What kind of non-blocking I/O do we have? */
77#if !defined (O_NDELAY) && defined (O_NONBLOCK)
78#  define O_NDELAY O_NONBLOCK	/* Posix style */
79#endif
80
81#if defined (HAVE_PSELECT)
82extern sigset_t _rl_orig_sigset;
83#endif
84
85/* Non-null means it is a pointer to a function to run while waiting for
86   character input. */
87rl_hook_func_t *rl_event_hook = (rl_hook_func_t *)NULL;
88
89/* A function to call if a read(2) is interrupted by a signal. */
90rl_hook_func_t *rl_signal_event_hook = (rl_hook_func_t *)NULL;
91
92/* A function to replace _rl_input_available for applications using the
93   callback interface. */
94rl_hook_func_t *rl_input_available_hook = (rl_hook_func_t *)NULL;
95
96rl_getc_func_t *rl_getc_function = rl_getc;
97
98static int _keyboard_input_timeout = 100000;		/* 0.1 seconds; it's in usec */
99
100static int ibuffer_space PARAMS((void));
101static int rl_get_char PARAMS((int *));
102static int rl_gather_tyi PARAMS((void));
103
104/* Windows isatty returns true for every character device, including the null
105   device, so we need to perform additional checks. */
106#if defined (_WIN32) && !defined (__CYGWIN__)
107#include <io.h>
108#include <conio.h>
109#define WIN32_LEAN_AND_MEAN 1
110#include <windows.h>
111
112int
113win32_isatty (int fd)
114{
115  if (_isatty(fd))
116    {
117      HANDLE h;
118      DWORD ignored;
119
120      if ((h = (HANDLE) _get_osfhandle (fd)) == INVALID_HANDLE_VALUE)
121	{
122	  errno = EBADF;
123	  return 0;
124	}
125      if (GetConsoleMode (h, &ignored) != 0)
126	return 1;
127    }
128  errno = ENOTTY;
129  return 0;
130}
131
132#define isatty(x)	win32_isatty(x)
133#endif
134
135/* **************************************************************** */
136/*								    */
137/*			Character Input Buffering       	    */
138/*								    */
139/* **************************************************************** */
140
141static int pop_index, push_index;
142static unsigned char ibuffer[512];
143static int ibuffer_len = sizeof (ibuffer) - 1;
144
145#define any_typein (push_index != pop_index)
146
147int
148_rl_any_typein (void)
149{
150  return any_typein;
151}
152
153int
154_rl_pushed_input_available (void)
155{
156  return (push_index != pop_index);
157}
158
159/* Return the amount of space available in the buffer for stuffing
160   characters. */
161static int
162ibuffer_space (void)
163{
164  if (pop_index > push_index)
165    return (pop_index - push_index - 1);
166  else
167    return (ibuffer_len - (push_index - pop_index));
168}
169
170/* Get a key from the buffer of characters to be read.
171   Return the key in KEY.
172   Result is non-zero if there was a key, or 0 if there wasn't. */
173static int
174rl_get_char (int *key)
175{
176  if (push_index == pop_index)
177    return (0);
178
179  *key = ibuffer[pop_index++];
180#if 0
181  if (pop_index >= ibuffer_len)
182#else
183  if (pop_index > ibuffer_len)
184#endif
185    pop_index = 0;
186
187  return (1);
188}
189
190/* Stuff KEY into the *front* of the input buffer.
191   Returns non-zero if successful, zero if there is
192   no space left in the buffer. */
193int
194_rl_unget_char (int key)
195{
196  if (ibuffer_space ())
197    {
198      pop_index--;
199      if (pop_index < 0)
200	pop_index = ibuffer_len;
201      ibuffer[pop_index] = key;
202      return (1);
203    }
204  return (0);
205}
206
207/* If a character is available to be read, then read it and stuff it into
208   IBUFFER.  Otherwise, just return.  Returns number of characters read
209   (0 if none available) and -1 on error (EIO). */
210static int
211rl_gather_tyi (void)
212{
213  int tty;
214  register int tem, result;
215  int chars_avail, k;
216  char input;
217#if defined(HAVE_SELECT)
218  fd_set readfds, exceptfds;
219  struct timeval timeout;
220#endif
221
222  chars_avail = 0;
223  input = 0;
224  tty = fileno (rl_instream);
225
226#if defined (HAVE_SELECT)
227  FD_ZERO (&readfds);
228  FD_ZERO (&exceptfds);
229  FD_SET (tty, &readfds);
230  FD_SET (tty, &exceptfds);
231  USEC_TO_TIMEVAL (_keyboard_input_timeout, timeout);
232  result = select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout);
233  if (result <= 0)
234    return 0;	/* Nothing to read. */
235#endif
236
237  result = -1;
238  errno = 0;
239#if defined (FIONREAD)
240  result = ioctl (tty, FIONREAD, &chars_avail);
241  if (result == -1 && errno == EIO)
242    return -1;
243  if (result == -1)
244    chars_avail = 0;
245#endif
246
247#if defined (O_NDELAY)
248  if (result == -1)
249    {
250      tem = fcntl (tty, F_GETFL, 0);
251
252      fcntl (tty, F_SETFL, (tem | O_NDELAY));
253      chars_avail = read (tty, &input, 1);
254
255      fcntl (tty, F_SETFL, tem);
256      if (chars_avail == -1 && errno == EAGAIN)
257	return 0;
258      if (chars_avail == -1 && errno == EIO)
259	return -1;
260      if (chars_avail == 0)	/* EOF */
261	{
262	  rl_stuff_char (EOF);
263	  return (0);
264	}
265    }
266#endif /* O_NDELAY */
267
268#if defined (__MINGW32__)
269  /* Use getch/_kbhit to check for available console input, in the same way
270     that we read it normally. */
271   chars_avail = isatty (tty) ? _kbhit () : 0;
272   result = 0;
273#endif
274
275  /* If there's nothing available, don't waste time trying to read
276     something. */
277  if (chars_avail <= 0)
278    return 0;
279
280  tem = ibuffer_space ();
281
282  if (chars_avail > tem)
283    chars_avail = tem;
284
285  /* One cannot read all of the available input.  I can only read a single
286     character at a time, or else programs which require input can be
287     thwarted.  If the buffer is larger than one character, I lose.
288     Damn! */
289  if (tem < ibuffer_len)
290    chars_avail = 0;
291
292  if (result != -1)
293    {
294      while (chars_avail--)
295	{
296	  RL_CHECK_SIGNALS ();
297	  k = (*rl_getc_function) (rl_instream);
298	  if (rl_stuff_char (k) == 0)
299	    break;			/* some problem; no more room */
300	  if (k == NEWLINE || k == RETURN)
301	    break;
302	}
303    }
304  else
305    {
306      if (chars_avail)
307	rl_stuff_char (input);
308    }
309
310  return 1;
311}
312
313int
314rl_set_keyboard_input_timeout (int u)
315{
316  int o;
317
318  o = _keyboard_input_timeout;
319  if (u >= 0)
320    _keyboard_input_timeout = u;
321  return (o);
322}
323
324/* Is there input available to be read on the readline input file
325   descriptor?  Only works if the system has select(2) or FIONREAD.
326   Uses the value of _keyboard_input_timeout as the timeout; if another
327   readline function wants to specify a timeout and not leave it up to
328   the user, it should use _rl_input_queued(timeout_value_in_microseconds)
329   instead. */
330int
331_rl_input_available (void)
332{
333#if defined(HAVE_SELECT)
334  fd_set readfds, exceptfds;
335  struct timeval timeout;
336#endif
337#if !defined (HAVE_SELECT) && defined(FIONREAD)
338  int chars_avail;
339#endif
340  int tty;
341
342  if (rl_input_available_hook)
343    return (*rl_input_available_hook) ();
344
345  tty = fileno (rl_instream);
346
347#if defined (HAVE_SELECT)
348  FD_ZERO (&readfds);
349  FD_ZERO (&exceptfds);
350  FD_SET (tty, &readfds);
351  FD_SET (tty, &exceptfds);
352  USEC_TO_TIMEVAL (_keyboard_input_timeout, timeout);
353  return (select (tty + 1, &readfds, (fd_set *)NULL, &exceptfds, &timeout) > 0);
354#else
355
356#if defined (FIONREAD)
357  if (ioctl (tty, FIONREAD, &chars_avail) == 0)
358    return (chars_avail);
359#endif
360
361#endif
362
363#if defined (__MINGW32__)
364  if (isatty (tty))
365    return (_kbhit ());
366#endif
367
368  return 0;
369}
370
371int
372_rl_nchars_available ()
373{
374  int chars_avail, fd, result;
375
376  chars_avail = 0;
377
378#if defined (FIONREAD)
379  fd = fileno (rl_instream);
380  errno = 0;
381  result = ioctl (fd, FIONREAD, &chars_avail);
382  if (result == -1 && errno == EIO)
383    return -1;
384#endif
385
386  return chars_avail;
387}
388
389int
390_rl_input_queued (int t)
391{
392  int old_timeout, r;
393
394  old_timeout = rl_set_keyboard_input_timeout (t);
395  r = _rl_input_available ();
396  rl_set_keyboard_input_timeout (old_timeout);
397  return r;
398}
399
400void
401_rl_insert_typein (int c)
402{
403  int key, t, i;
404  char *string;
405
406  i = key = 0;
407  string = (char *)xmalloc (ibuffer_len + 1);
408  string[i++] = (char) c;
409
410  while ((t = rl_get_char (&key)) &&
411	 _rl_keymap[key].type == ISFUNC &&
412	 _rl_keymap[key].function == rl_insert)
413    string[i++] = key;
414
415  if (t)
416    _rl_unget_char (key);
417
418  string[i] = '\0';
419  rl_insert_text (string);
420  xfree (string);
421}
422
423/* Add KEY to the buffer of characters to be read.  Returns 1 if the
424   character was stuffed correctly; 0 otherwise. */
425int
426rl_stuff_char (int key)
427{
428  if (ibuffer_space () == 0)
429    return 0;
430
431  if (key == EOF)
432    {
433      key = NEWLINE;
434      rl_pending_input = EOF;
435      RL_SETSTATE (RL_STATE_INPUTPENDING);
436    }
437  ibuffer[push_index++] = key;
438#if 0
439  if (push_index >= ibuffer_len)
440#else
441  if (push_index > ibuffer_len)
442#endif
443    push_index = 0;
444
445  return 1;
446}
447
448/* Make C be the next command to be executed. */
449int
450rl_execute_next (int c)
451{
452  rl_pending_input = c;
453  RL_SETSTATE (RL_STATE_INPUTPENDING);
454  return 0;
455}
456
457/* Clear any pending input pushed with rl_execute_next() */
458int
459rl_clear_pending_input (void)
460{
461  rl_pending_input = 0;
462  RL_UNSETSTATE (RL_STATE_INPUTPENDING);
463  return 0;
464}
465
466/* **************************************************************** */
467/*								    */
468/*			     Character Input			    */
469/*								    */
470/* **************************************************************** */
471
472/* Read a key, including pending input. */
473int
474rl_read_key (void)
475{
476  int c, r;
477
478  if (rl_pending_input)
479    {
480      c = rl_pending_input;	/* XXX - cast to unsigned char if > 0? */
481      rl_clear_pending_input ();
482    }
483  else
484    {
485      /* If input is coming from a macro, then use that. */
486      if (c = _rl_next_macro_key ())
487	return ((unsigned char)c);
488
489      /* If the user has an event function, then call it periodically. */
490      if (rl_event_hook)
491	{
492	  while (rl_event_hook)
493	    {
494	      if (rl_get_char (&c) != 0)
495		break;
496
497	      if ((r = rl_gather_tyi ()) < 0)	/* XXX - EIO */
498		{
499		  rl_done = 1;
500		  return (errno == EIO ? (RL_ISSTATE (RL_STATE_READCMD) ? READERR : EOF) : '\n');
501		}
502	      else if (r > 0)			/* read something */
503		continue;
504
505	      RL_CHECK_SIGNALS ();
506	      if (rl_done)		/* XXX - experimental */
507		return ('\n');
508	      (*rl_event_hook) ();
509	    }
510	}
511      else
512	{
513	  if (rl_get_char (&c) == 0)
514	    c = (*rl_getc_function) (rl_instream);
515/* fprintf(stderr, "rl_read_key: calling RL_CHECK_SIGNALS: _rl_caught_signal = %d\r\n", _rl_caught_signal); */
516	  RL_CHECK_SIGNALS ();
517	}
518    }
519
520  return (c);
521}
522
523int
524rl_getc (FILE *stream)
525{
526  int result;
527  unsigned char c;
528#if defined (HAVE_PSELECT)
529  sigset_t empty_set;
530  fd_set readfds;
531#endif
532
533  while (1)
534    {
535      RL_CHECK_SIGNALS ();
536
537      /* We know at this point that _rl_caught_signal == 0 */
538
539#if defined (__MINGW32__)
540      if (isatty (fileno (stream)))
541	return (_getch ());	/* "There is no error return." */
542#endif
543      result = 0;
544#if defined (HAVE_PSELECT)
545      FD_ZERO (&readfds);
546      FD_SET (fileno (stream), &readfds);
547#  if defined (HANDLE_SIGNALS)
548      result = pselect (fileno (stream) + 1, &readfds, NULL, NULL, NULL, &_rl_orig_sigset);
549#  else
550      sigemptyset (&empty_set);
551      sigprocmask (SIG_BLOCK, (sigset_t *)NULL, &empty_set);
552      result = pselect (fileno (stream) + 1, &readfds, NULL, NULL, NULL, &empty_set);
553#  endif /* HANDLE_SIGNALS */
554#endif
555      if (result >= 0)
556	result = read (fileno (stream), &c, sizeof (unsigned char));
557
558      if (result == sizeof (unsigned char))
559	return (c);
560
561      /* If zero characters are returned, then the file that we are
562	 reading from is empty!  Return EOF in that case. */
563      if (result == 0)
564	return (EOF);
565
566#if defined (__BEOS__)
567      if (errno == EINTR)
568	continue;
569#endif
570
571#if defined (EWOULDBLOCK)
572#  define X_EWOULDBLOCK EWOULDBLOCK
573#else
574#  define X_EWOULDBLOCK -99
575#endif
576
577#if defined (EAGAIN)
578#  define X_EAGAIN EAGAIN
579#else
580#  define X_EAGAIN -99
581#endif
582
583      if (errno == X_EWOULDBLOCK || errno == X_EAGAIN)
584	{
585	  if (sh_unset_nodelay_mode (fileno (stream)) < 0)
586	    return (EOF);
587	  continue;
588	}
589
590#undef X_EWOULDBLOCK
591#undef X_EAGAIN
592
593/* fprintf(stderr, "rl_getc: result = %d errno = %d\n", result, errno); */
594
595handle_error:
596      /* If the error that we received was EINTR, then try again,
597	 this is simply an interrupted system call to read ().  We allow
598	 the read to be interrupted if we caught SIGHUP, SIGTERM, or any
599	 of the other signals readline treats specially. If the
600	 application sets an event hook, call it for other signals.
601	 Otherwise (not EINTR), some error occurred, also signifying EOF. */
602      if (errno != EINTR)
603	return (RL_ISSTATE (RL_STATE_READCMD) ? READERR : EOF);
604      /* fatal signals of interest */
605#if defined (SIGHUP)
606      else if (_rl_caught_signal == SIGHUP || _rl_caught_signal == SIGTERM)
607#else
608      else if (_rl_caught_signal == SIGTERM)
609#endif
610	return (RL_ISSTATE (RL_STATE_READCMD) ? READERR : EOF);
611      /* keyboard-generated signals of interest */
612#if defined (SIGQUIT)
613      else if (_rl_caught_signal == SIGINT || _rl_caught_signal == SIGQUIT)
614#else
615      else if (_rl_caught_signal == SIGINT)
616#endif
617        RL_CHECK_SIGNALS ();
618#if defined (SIGTSTP)
619      else if (_rl_caught_signal == SIGTSTP)
620	RL_CHECK_SIGNALS ();
621#endif
622      /* non-keyboard-generated signals of interest */
623#if defined (SIGWINCH)
624      else if (_rl_caught_signal == SIGWINCH)
625	RL_CHECK_SIGNALS ();
626#endif /* SIGWINCH */
627#if defined (SIGALRM)
628      else if (_rl_caught_signal == SIGALRM
629#  if defined (SIGVTALRM)
630		|| _rl_caught_signal == SIGVTALRM
631#  endif
632	      )
633        RL_CHECK_SIGNALS ();
634#endif  /* SIGALRM */
635
636      if (rl_signal_event_hook)
637	(*rl_signal_event_hook) ();
638    }
639}
640
641#if defined (HANDLE_MULTIBYTE)
642/* read multibyte char */
643int
644_rl_read_mbchar (char *mbchar, int size)
645{
646  int mb_len, c;
647  size_t mbchar_bytes_length;
648  wchar_t wc;
649  mbstate_t ps, ps_back;
650
651  memset(&ps, 0, sizeof (mbstate_t));
652  memset(&ps_back, 0, sizeof (mbstate_t));
653
654  mb_len = 0;
655  while (mb_len < size)
656    {
657      c = (mb_len == 0) ? _rl_bracketed_read_key () : rl_read_key ();
658
659      if (c < 0)
660	break;
661
662      mbchar[mb_len++] = c;
663
664      mbchar_bytes_length = mbrtowc (&wc, mbchar, mb_len, &ps);
665      if (mbchar_bytes_length == (size_t)(-1))
666	break;		/* invalid byte sequence for the current locale */
667      else if (mbchar_bytes_length == (size_t)(-2))
668	{
669	  /* shorted bytes */
670	  ps = ps_back;
671	  continue;
672	}
673      else if (mbchar_bytes_length == 0)
674	{
675	  mbchar[0] = '\0';	/* null wide character */
676	  mb_len = 1;
677	  break;
678	}
679      else if (mbchar_bytes_length > (size_t)(0))
680	break;
681    }
682
683  return mb_len;
684}
685
686/* Read a multibyte-character string whose first character is FIRST into
687   the buffer MB of length MLEN.  Returns the last character read, which
688   may be FIRST.  Used by the search functions, among others.  Very similar
689   to _rl_read_mbchar. */
690int
691_rl_read_mbstring (int first, char *mb, int mlen)
692{
693  int i, c, n;
694  mbstate_t ps;
695
696  c = first;
697  memset (mb, 0, mlen);
698  for (i = 0; c >= 0 && i < mlen; i++)
699    {
700      mb[i] = (char)c;
701      memset (&ps, 0, sizeof (mbstate_t));
702      n = _rl_get_char_len (mb, &ps);
703      if (n == -2)
704	{
705	  /* Read more for multibyte character */
706	  RL_SETSTATE (RL_STATE_MOREINPUT);
707	  c = rl_read_key ();
708	  RL_UNSETSTATE (RL_STATE_MOREINPUT);
709	}
710      else
711	break;
712    }
713  return c;
714}
715#endif /* HANDLE_MULTIBYTE */
716