1/*	$NetBSD: read.c,v 1.69 2012/09/11 12:31:08 christos Exp $	*/
2
3/*-
4 * Copyright (c) 1992, 1993
5 *	The Regents of the University of California.  All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Christos Zoulas of Cornell University.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 *    may be used to endorse or promote products derived from this software
20 *    without specific prior written permission.
21 *
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32 * SUCH DAMAGE.
33 */
34
35#include "config.h"
36#if !defined(lint) && !defined(SCCSID)
37#if 0
38static char sccsid[] = "@(#)read.c	8.1 (Berkeley) 6/4/93";
39#else
40__RCSID("$NetBSD: read.c,v 1.69 2012/09/11 12:31:08 christos Exp $");
41#endif
42#endif /* not lint && not SCCSID */
43
44/*
45 * read.c: Clean this junk up! This is horrible code.
46 *	   Terminal read functions
47 */
48#include <errno.h>
49#include <fcntl.h>
50#include <unistd.h>
51#include <stdlib.h>
52#include <limits.h>
53#include "el.h"
54
55#define OKCMD	-1	/* must be -1! */
56
57private int	read__fixio(int, int);
58private int	read_preread(EditLine *);
59private int	read_char(EditLine *, Char *);
60private int	read_getcmd(EditLine *, el_action_t *, Char *);
61private void	read_pop(c_macro_t *);
62
63/* read_init():
64 *	Initialize the read stuff
65 */
66protected int
67read_init(EditLine *el)
68{
69	/* builtin read_char */
70	el->el_read.read_char = read_char;
71	return 0;
72}
73
74
75/* el_read_setfn():
76 *	Set the read char function to the one provided.
77 *	If it is set to EL_BUILTIN_GETCFN, then reset to the builtin one.
78 */
79protected int
80el_read_setfn(EditLine *el, el_rfunc_t rc)
81{
82	el->el_read.read_char = (rc == EL_BUILTIN_GETCFN) ? read_char : rc;
83	return 0;
84}
85
86
87/* el_read_getfn():
88 *	return the current read char function, or EL_BUILTIN_GETCFN
89 *	if it is the default one
90 */
91protected el_rfunc_t
92el_read_getfn(EditLine *el)
93{
94       return el->el_read.read_char == read_char ?
95	    EL_BUILTIN_GETCFN : el->el_read.read_char;
96}
97
98
99#ifndef MIN
100#define MIN(A,B) ((A) < (B) ? (A) : (B))
101#endif
102
103#ifdef DEBUG_EDIT
104private void
105read_debug(EditLine *el)
106{
107
108	if (el->el_line.cursor > el->el_line.lastchar)
109		(void) fprintf(el->el_errfile, "cursor > lastchar\r\n");
110	if (el->el_line.cursor < el->el_line.buffer)
111		(void) fprintf(el->el_errfile, "cursor < buffer\r\n");
112	if (el->el_line.cursor > el->el_line.limit)
113		(void) fprintf(el->el_errfile, "cursor > limit\r\n");
114	if (el->el_line.lastchar > el->el_line.limit)
115		(void) fprintf(el->el_errfile, "lastchar > limit\r\n");
116	if (el->el_line.limit != &el->el_line.buffer[EL_BUFSIZ - 2])
117		(void) fprintf(el->el_errfile, "limit != &buffer[EL_BUFSIZ-2]\r\n");
118}
119#endif /* DEBUG_EDIT */
120
121
122/* read__fixio():
123 *	Try to recover from a read error
124 */
125/* ARGSUSED */
126private int
127read__fixio(int fd __attribute__((__unused__)), int e)
128{
129
130	switch (e) {
131	case -1:		/* Make sure that the code is reachable */
132
133#ifdef EWOULDBLOCK
134	case EWOULDBLOCK:
135#ifndef TRY_AGAIN
136#define TRY_AGAIN
137#endif
138#endif /* EWOULDBLOCK */
139
140#if defined(POSIX) && defined(EAGAIN)
141#if defined(EWOULDBLOCK) && EWOULDBLOCK != EAGAIN
142	case EAGAIN:
143#ifndef TRY_AGAIN
144#define TRY_AGAIN
145#endif
146#endif /* EWOULDBLOCK && EWOULDBLOCK != EAGAIN */
147#endif /* POSIX && EAGAIN */
148
149		e = 0;
150#ifdef TRY_AGAIN
151#if defined(F_SETFL) && defined(O_NDELAY)
152		if ((e = fcntl(fd, F_GETFL, 0)) == -1)
153			return -1;
154
155		if (fcntl(fd, F_SETFL, e & ~O_NDELAY) == -1)
156			return -1;
157		else
158			e = 1;
159#endif /* F_SETFL && O_NDELAY */
160
161#ifdef FIONBIO
162		{
163			int zero = 0;
164
165			if (ioctl(fd, FIONBIO, &zero) == -1)
166				return -1;
167			else
168				e = 1;
169		}
170#endif /* FIONBIO */
171
172#endif /* TRY_AGAIN */
173		return e ? 0 : -1;
174
175	case EINTR:
176		return 0;
177
178	default:
179		return -1;
180	}
181}
182
183
184/* read_preread():
185 *	Try to read the stuff in the input queue;
186 */
187private int
188read_preread(EditLine *el)
189{
190	int chrs = 0;
191
192	if (el->el_tty.t_mode == ED_IO)
193		return 0;
194
195#ifndef WIDECHAR
196/* FIONREAD attempts to buffer up multiple bytes, and to make that work
197 * properly with partial wide/UTF-8 characters would need some careful work. */
198#ifdef FIONREAD
199	(void) ioctl(el->el_infd, FIONREAD, &chrs);
200	if (chrs > 0) {
201		char buf[EL_BUFSIZ];
202
203		chrs = read(el->el_infd, buf,
204		    (size_t) MIN(chrs, EL_BUFSIZ - 1));
205		if (chrs > 0) {
206			buf[chrs] = '\0';
207			el_push(el, buf);
208		}
209	}
210#endif /* FIONREAD */
211#endif
212	return chrs > 0;
213}
214
215
216/* el_push():
217 *	Push a macro
218 */
219public void
220FUN(el,push)(EditLine *el, const Char *str)
221{
222	c_macro_t *ma = &el->el_chared.c_macro;
223
224	if (str != NULL && ma->level + 1 < EL_MAXMACRO) {
225		ma->level++;
226		if ((ma->macro[ma->level] = Strdup(str)) != NULL)
227			return;
228		ma->level--;
229	}
230	terminal_beep(el);
231	terminal__flush(el);
232}
233
234
235/* read_getcmd():
236 *	Get next command from the input stream, return OKCMD on success.
237 *	Character values > 255 are not looked up in the map, but inserted.
238 */
239private int
240read_getcmd(EditLine *el, el_action_t *cmdnum, Char *ch)
241{
242	el_action_t cmd;
243	int num;
244
245	el->el_errno = 0;
246	do {
247		if ((num = FUN(el,getc)(el, ch)) != 1) {/* if EOF or error */
248			el->el_errno = num == 0 ? 0 : errno;
249			return 0;	/* not OKCMD */
250		}
251
252#ifdef	KANJI
253		if ((*ch & 0200)) {
254			el->el_state.metanext = 0;
255			cmd = CcViMap[' '];
256			break;
257		} else
258#endif /* KANJI */
259
260		if (el->el_state.metanext) {
261			el->el_state.metanext = 0;
262			*ch |= 0200;
263		}
264#ifdef WIDECHAR
265		if (*ch >= N_KEYS)
266			cmd = ED_INSERT;
267		else
268#endif
269			cmd = el->el_map.current[(unsigned char) *ch];
270		if (cmd == ED_SEQUENCE_LEAD_IN) {
271			keymacro_value_t val;
272			switch (keymacro_get(el, ch, &val)) {
273			case XK_CMD:
274				cmd = val.cmd;
275				break;
276			case XK_STR:
277				FUN(el,push)(el, val.str);
278				break;
279#ifdef notyet
280			case XK_EXE:
281				/* XXX: In the future to run a user function */
282				RunCommand(val.str);
283				break;
284#endif
285			default:
286				EL_ABORT((el->el_errfile, "Bad XK_ type \n"));
287				break;
288			}
289		}
290		if (el->el_map.alt == NULL)
291			el->el_map.current = el->el_map.key;
292	} while (cmd == ED_SEQUENCE_LEAD_IN);
293	*cmdnum = cmd;
294	return OKCMD;
295}
296
297#ifdef WIDECHAR
298/* utf8_islead():
299 *	Test whether a byte is a leading byte of a UTF-8 sequence.
300 */
301private int
302utf8_islead(int c)
303{
304	return c < 0x80 ||	       /* single byte char */
305	       (c >= 0xc2 && c <= 0xf4); /* start of multibyte sequence */
306}
307#endif
308
309/* read_char():
310 *	Read a character from the tty.
311 */
312private int
313read_char(EditLine *el, Char *cp)
314{
315	ssize_t num_read;
316	int tried = 0;
317	char cbuf[MB_LEN_MAX];
318	size_t cbp = 0;
319	int bytes = 0;
320
321 again:
322	el->el_signal->sig_no = 0;
323	while ((num_read = read(el->el_infd, cbuf + cbp, (size_t)1)) == -1) {
324		int e = errno;
325		switch (el->el_signal->sig_no) {
326		case SIGCONT:
327			FUN(el,set)(el, EL_REFRESH);
328			/*FALLTHROUGH*/
329		case SIGWINCH:
330			sig_set(el);
331			goto again;
332		default:
333			break;
334		}
335		if (!tried && read__fixio(el->el_infd, e) == 0)
336			tried = 1;
337		else {
338			errno = e;
339			*cp = '\0';
340			return -1;
341		}
342	}
343	if (num_read == 0) return 0;
344
345#ifdef WIDECHAR
346	if (el->el_flags & CHARSET_IS_UTF8) {
347		if (!utf8_islead((unsigned char)cbuf[0]))
348			goto again; /* discard the byte we read and try again */
349		++cbp;
350		if ((bytes = ct_mbtowc(cp, cbuf, cbp)) == -1) {
351			ct_mbtowc_reset;
352			if (cbp >= MB_LEN_MAX) { /* "shouldn't happen" */
353				errno = EILSEQ;
354				*cp = '\0';
355				return -1;
356			}
357			goto again;
358		}
359	} else if (isascii((unsigned char)cbuf[0]) ||
360		/* we don't support other multibyte charsets */
361		++cbp != 1 ||
362		/* Try non-ASCII characters in a 8-bit character set */
363		(bytes = ct_mbtowc(cp, cbuf, cbp)) != 1)
364#endif
365		*cp = (unsigned char)cbuf[0];
366
367	if ((el->el_flags & IGNORE_EXTCHARS) && bytes > 1) {
368		cbp = 0; /* skip this character */
369		goto again;
370	}
371
372	return (int)num_read;
373}
374
375/* read_pop():
376 *	Pop a macro from the stack
377 */
378private void
379read_pop(c_macro_t *ma)
380{
381	int i;
382
383	el_free(ma->macro[0]);
384	for (i = 0; i < ma->level; i++)
385		ma->macro[i] = ma->macro[i + 1];
386	ma->level--;
387	ma->offset = 0;
388}
389
390/* el_getc():
391 *	Read a character
392 */
393public int
394FUN(el,getc)(EditLine *el, Char *cp)
395{
396	int num_read;
397	c_macro_t *ma = &el->el_chared.c_macro;
398
399	terminal__flush(el);
400	for (;;) {
401		if (ma->level < 0) {
402			if (!read_preread(el))
403				break;
404		}
405
406		if (ma->level < 0)
407			break;
408
409		if (ma->macro[0][ma->offset] == '\0') {
410			read_pop(ma);
411			continue;
412		}
413
414		*cp = ma->macro[0][ma->offset++];
415
416		if (ma->macro[0][ma->offset] == '\0') {
417			/* Needed for QuoteMode On */
418			read_pop(ma);
419		}
420
421		return 1;
422	}
423
424#ifdef DEBUG_READ
425	(void) fprintf(el->el_errfile, "Turning raw mode on\n");
426#endif /* DEBUG_READ */
427	if (tty_rawmode(el) < 0)/* make sure the tty is set up correctly */
428		return 0;
429
430#ifdef DEBUG_READ
431	(void) fprintf(el->el_errfile, "Reading a character\n");
432#endif /* DEBUG_READ */
433	num_read = (*el->el_read.read_char)(el, cp);
434	if (num_read < 0)
435		el->el_errno = errno;
436#ifdef WIDECHAR
437	if (el->el_flags & NARROW_READ)
438		*cp = *(char *)(void *)cp;
439#endif
440#ifdef DEBUG_READ
441	(void) fprintf(el->el_errfile, "Got it %c\n", *cp);
442#endif /* DEBUG_READ */
443	return num_read;
444}
445
446protected void
447read_prepare(EditLine *el)
448{
449	if (el->el_flags & HANDLE_SIGNALS)
450		sig_set(el);
451	if (el->el_flags & NO_TTY)
452		return;
453	if ((el->el_flags & (UNBUFFERED|EDIT_DISABLED)) == UNBUFFERED)
454		tty_rawmode(el);
455
456	/* This is relatively cheap, and things go terribly wrong if
457	   we have the wrong size. */
458	el_resize(el);
459	re_clear_display(el);	/* reset the display stuff */
460	ch_reset(el, 0);
461	re_refresh(el);		/* print the prompt */
462
463	if (el->el_flags & UNBUFFERED)
464		terminal__flush(el);
465}
466
467protected void
468read_finish(EditLine *el)
469{
470	if ((el->el_flags & UNBUFFERED) == 0)
471		(void) tty_cookedmode(el);
472	if (el->el_flags & HANDLE_SIGNALS)
473		sig_clr(el);
474}
475
476public const Char *
477FUN(el,gets)(EditLine *el, int *nread)
478{
479	int retval;
480	el_action_t cmdnum = 0;
481	int num;		/* how many chars we have read at NL */
482	Char ch, *cp;
483	int crlf = 0;
484	int nrb;
485#ifdef FIONREAD
486	c_macro_t *ma = &el->el_chared.c_macro;
487#endif /* FIONREAD */
488
489	if (nread == NULL)
490		nread = &nrb;
491	*nread = 0;
492
493	if (el->el_flags & NO_TTY) {
494		size_t idx;
495
496		cp = el->el_line.buffer;
497		while ((num = (*el->el_read.read_char)(el, cp)) == 1) {
498			/* make sure there is space for next character */
499			if (cp + 1 >= el->el_line.limit) {
500				idx = (size_t)(cp - el->el_line.buffer);
501				if (!ch_enlargebufs(el, (size_t)2))
502					break;
503				cp = &el->el_line.buffer[idx];
504			}
505			cp++;
506			if (el->el_flags & UNBUFFERED)
507				break;
508			if (cp[-1] == '\r' || cp[-1] == '\n')
509				break;
510		}
511		if (num == -1) {
512			if (errno == EINTR)
513				cp = el->el_line.buffer;
514			el->el_errno = errno;
515		} else if (num == 0) el->el_state.thiscmd = EL_EOF;
516
517		goto noedit;
518	}
519
520
521#ifdef FIONREAD
522	if (el->el_tty.t_mode == EX_IO && ma->level < 0) {
523		long chrs = 0;
524
525		(void) ioctl(el->el_infd, FIONREAD, &chrs);
526		if (chrs == 0) {
527			if (tty_rawmode(el) < 0) {
528				errno = 0;
529				*nread = 0;
530				return NULL;
531			}
532		}
533	}
534#endif /* FIONREAD */
535
536	if ((el->el_flags & UNBUFFERED) == 0)
537		read_prepare(el);
538
539	if (el->el_flags & EDIT_DISABLED) {
540		size_t idx;
541
542		if ((el->el_flags & UNBUFFERED) == 0)
543			cp = el->el_line.buffer;
544		else
545			cp = el->el_line.lastchar;
546
547		terminal__flush(el);
548
549		while ((num = (*el->el_read.read_char)(el, cp)) == 1) {
550			/* make sure there is space next character */
551			if (cp + 1 >= el->el_line.limit) {
552				idx = (size_t)(cp - el->el_line.buffer);
553				if (!ch_enlargebufs(el, (size_t)2))
554					break;
555				cp = &el->el_line.buffer[idx];
556			}
557			cp++;
558			crlf = cp[-1] == '\r' || cp[-1] == '\n';
559			if (el->el_flags & UNBUFFERED)
560				break;
561			if (crlf)
562				break;
563		}
564
565		if (num == -1) {
566			if (errno == EINTR)
567				cp = el->el_line.buffer;
568			el->el_errno = errno;
569		} else if (num == 0) el->el_state.thiscmd = EL_EOF;
570
571		goto noedit;
572	}
573
574	for (num = OKCMD; num == OKCMD;) {	/* while still editing this
575						 * line */
576#ifdef DEBUG_EDIT
577		read_debug(el);
578#endif /* DEBUG_EDIT */
579		/* if EOF or error */
580		if ((num = read_getcmd(el, &cmdnum, &ch)) != OKCMD) {
581#ifdef DEBUG_READ
582			(void) fprintf(el->el_errfile,
583			    "Returning from el_gets %d\n", num);
584#endif /* DEBUG_READ */
585			if (num == 0) el->el_state.thiscmd = EL_EOF;
586			break;
587		}
588		if (el->el_errno == EINTR) {
589			el->el_line.buffer[0] = '\0';
590			el->el_line.lastchar =
591			    el->el_line.cursor = el->el_line.buffer;
592			break;
593		}
594		if ((unsigned int)cmdnum >= (unsigned int)el->el_map.nfunc) {	/* BUG CHECK command */
595#ifdef DEBUG_EDIT
596			(void) fprintf(el->el_errfile,
597			    "ERROR: illegal command from key 0%o\r\n", ch);
598#endif /* DEBUG_EDIT */
599			continue;	/* try again */
600		}
601		/* now do the real command */
602#ifdef DEBUG_READ
603		{
604			el_bindings_t *b;
605			for (b = el->el_map.help; b->name; b++)
606				if (b->func == cmdnum)
607					break;
608			if (b->name)
609				(void) fprintf(el->el_errfile,
610				    "Executing %s\n", b->name);
611			else
612				(void) fprintf(el->el_errfile,
613				    "Error command = %d\n", cmdnum);
614		}
615#endif /* DEBUG_READ */
616		/* vi redo needs these way down the levels... */
617		el->el_state.thiscmd = cmdnum;
618		el->el_state.thisch = ch;
619		if (el->el_map.type == MAP_VI &&
620		    el->el_map.current == el->el_map.key &&
621		    el->el_chared.c_redo.pos < el->el_chared.c_redo.lim) {
622			if (cmdnum == VI_DELETE_PREV_CHAR &&
623			    el->el_chared.c_redo.pos != el->el_chared.c_redo.buf
624			    && Isprint(el->el_chared.c_redo.pos[-1]))
625				el->el_chared.c_redo.pos--;
626			else
627				*el->el_chared.c_redo.pos++ = ch;
628		}
629		retval = (*el->el_map.func[cmdnum]) (el, ch);
630#ifdef DEBUG_READ
631		(void) fprintf(el->el_errfile,
632			"Returned state %d\n", retval );
633#endif /* DEBUG_READ */
634
635		/* save the last command here */
636		el->el_state.lastcmd = cmdnum;
637
638		/* use any return value */
639		switch (retval) {
640		case CC_CURSOR:
641			re_refresh_cursor(el);
642			break;
643
644		case CC_REDISPLAY:
645			re_clear_lines(el);
646			re_clear_display(el);
647			/* FALLTHROUGH */
648
649		case CC_REFRESH:
650			re_refresh(el);
651			break;
652
653		case CC_REFRESH_BEEP:
654			re_refresh(el);
655			terminal_beep(el);
656			break;
657
658		case CC_NORM:	/* normal char */
659			break;
660
661		case CC_ARGHACK:	/* Suggested by Rich Salz */
662			/* <rsalz@pineapple.bbn.com> */
663			continue;	/* keep going... */
664
665		case CC_EOF:	/* end of file typed */
666			if ((el->el_flags & UNBUFFERED) == 0)
667				num = 0;
668			else if (num == -1) {
669				*el->el_line.lastchar++ = CONTROL('d');
670				el->el_line.cursor = el->el_line.lastchar;
671				num = 1;
672			}
673			break;
674
675		case CC_NEWLINE:	/* normal end of line */
676			num = (int)(el->el_line.lastchar - el->el_line.buffer);
677			break;
678
679		case CC_FATAL:	/* fatal error, reset to known state */
680#ifdef DEBUG_READ
681			(void) fprintf(el->el_errfile,
682			    "*** editor fatal ERROR ***\r\n\n");
683#endif /* DEBUG_READ */
684			/* put (real) cursor in a known place */
685			re_clear_display(el);	/* reset the display stuff */
686			ch_reset(el, 1);	/* reset the input pointers */
687			re_refresh(el); /* print the prompt again */
688			break;
689
690		case CC_ERROR:
691		default:	/* functions we don't know about */
692#ifdef DEBUG_READ
693			(void) fprintf(el->el_errfile,
694			    "*** editor ERROR ***\r\n\n");
695#endif /* DEBUG_READ */
696			terminal_beep(el);
697			terminal__flush(el);
698			break;
699		}
700		el->el_state.argument = 1;
701		el->el_state.doingarg = 0;
702		el->el_chared.c_vcmd.action = NOP;
703		if (el->el_flags & UNBUFFERED)
704			break;
705	}
706
707	terminal__flush(el);		/* flush any buffered output */
708	/* make sure the tty is set up correctly */
709	if ((el->el_flags & UNBUFFERED) == 0) {
710		read_finish(el);
711		*nread = num != -1 ? num : 0;
712	} else {
713		*nread = (int)(el->el_line.lastchar - el->el_line.buffer);
714	}
715	goto done;
716noedit:
717	el->el_line.cursor = el->el_line.lastchar = cp;
718	*cp = '\0';
719	*nread = (int)(el->el_line.cursor - el->el_line.buffer);
720done:
721	if (*nread == 0) {
722		if (num == -1) {
723			*nread = -1;
724			errno = el->el_errno;
725		}
726		return NULL;
727	} else {
728		el->el_line.buffer[*nread] = 0;
729		return el->el_line.buffer;
730	}
731}
732