1 /*-
2  * Copyright (c) 1993
3  *	The Regents of the University of California.  All rights reserved.
4  * Copyright (c) 1997-2005
5  *	Herbert Xu <herbert@gondor.apana.org.au>.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Kenneth Almquist.
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 <sys/param.h>
36 #ifdef HAVE_PATHS_H
37 #include <paths.h>
38 #endif
39 #include <stdio.h>
40 #include <stdlib.h>
41 #include <unistd.h>
42 #include <getopt.h>
43 /*
44  * Editline and history functions (and glue).
45  */
46 #include "shell.h"
47 #include "parser.h"
48 #include "var.h"
49 #include "options.h"
50 #include "main.h"
51 #include "output.h"
52 #include "mystring.h"
53 #include "error.h"
54 #ifndef SMALL
55 #include "myhistedit.h"
56 #include "eval.h"
57 #include "memalloc.h"
58 
59 #define MAXHISTLOOPS	4	/* max recursions through fc */
60 #define DEFEDITOR	"ed"	/* default editor *should* be $EDITOR */
61 
62 History *hist;	/* history cookie */
63 EditLine *el;	/* editline cookie */
64 int displayhist;
65 static FILE *el_in, *el_out;
66 
67 STATIC const char *fc_replace(const char *, char *, char *);
68 
69 #ifdef DEBUG
70 extern FILE *tracefile;
71 #endif
72 
73 /*
74  * Set history and editing status.  Called whenever the status may
75  * have changed (figures out what to do).
76  */
77 void
histedit(void)78 histedit(void)
79 {
80 	FILE *el_err;
81 
82 #define editing (Eflag || Vflag)
83 
84 	if (iflag) {
85 		if (!hist) {
86 			/*
87 			 * turn history on
88 			 */
89 			INTOFF;
90 			hist = history_init();
91 			INTON;
92 
93 			if (hist != NULL)
94 				sethistsize(histsizeval());
95 			else
96 				out2str("sh: can't initialize history\n");
97 		}
98 		if (editing && !el && isatty(0)) { /* && isatty(2) ??? */
99 			/*
100 			 * turn editing on
101 			 */
102 			INTOFF;
103 			if (el_in == NULL)
104 				el_in = fdopen(0, "r");
105 			if (el_out == NULL)
106 				el_out = fdopen(2, "w");
107 			if (el_in == NULL || el_out == NULL)
108 				goto bad;
109 			el_err = el_out;
110 #if DEBUG
111 			if (tracefile)
112 				el_err = tracefile;
113 #endif
114 			el = el_init(arg0, el_in, el_out, el_err);
115 			if (el != NULL) {
116 				if (hist)
117 					el_set(el, EL_HIST, history, hist);
118 				el_set(el, EL_PROMPT, getprompt);
119 			} else {
120 bad:
121 				out2str("sh: can't initialize editing\n");
122 			}
123 			INTON;
124 		} else if (!editing && el) {
125 			INTOFF;
126 			el_end(el);
127 			el = NULL;
128 			INTON;
129 		}
130 		if (el) {
131 			if (Vflag)
132 				el_set(el, EL_EDITOR, "vi");
133 			else if (Eflag)
134 				el_set(el, EL_EDITOR, "emacs");
135 			el_source(el, NULL);
136 		}
137 	} else {
138 		INTOFF;
139 		if (el) {	/* no editing if not interactive */
140 			el_end(el);
141 			el = NULL;
142 		}
143 		if (hist) {
144 			history_end(hist);
145 			hist = NULL;
146 		}
147 		INTON;
148 	}
149 }
150 
151 
152 void
sethistsize(const char * hs)153 sethistsize(const char *hs)
154 {
155 	int histsize;
156 	HistEvent he;
157 
158 	if (hist != NULL) {
159 		if (hs == NULL || *hs == '\0' ||
160 		   (histsize = atoi(hs)) < 0)
161 			histsize = 100;
162 		history(hist, &he, H_SETSIZE, histsize);
163 	}
164 }
165 
166 void
setterm(const char * term)167 setterm(const char *term)
168 {
169 	if (el != NULL && term != NULL)
170 		if (el_set(el, EL_TERMINAL, term) != 0) {
171 			outfmt(out2, "sh: Can't set terminal type %s\n", term);
172 			outfmt(out2, "sh: Using dumb terminal settings.\n");
173 		}
174 }
175 
176 /*
177  *  This command is provided since POSIX decided to standardize
178  *  the Korn shell fc command.  Oh well...
179  */
180 int
histcmd(int argc,char ** argv)181 histcmd(int argc, char **argv)
182 {
183 	int ch;
184 	const char *editor = NULL;
185 	HistEvent he;
186 	int lflg = 0, nflg = 0, rflg = 0, sflg = 0;
187 	int i, retval;
188 	const char *firststr, *laststr;
189 	int first, last, direction;
190 	char *pat = NULL, *repl;	/* ksh "fc old=new" crap */
191 	static int active = 0;
192 	struct jmploc jmploc;
193 	struct jmploc *volatile savehandler;
194 	char editfile[MAXPATHLEN + 1];
195 	FILE *efp;
196 #ifdef __GNUC__
197 	/* Avoid longjmp clobbering */
198 	(void) &editor;
199 	(void) &lflg;
200 	(void) &nflg;
201 	(void) &rflg;
202 	(void) &sflg;
203 	(void) &firststr;
204 	(void) &laststr;
205 	(void) &pat;
206 	(void) &repl;
207 	(void) &efp;
208 	(void) &argc;
209 	(void) &argv;
210 #endif
211 
212 	if (hist == NULL)
213 		sh_error("history not active");
214 
215 	if (argc == 1)
216 		sh_error("missing history argument");
217 
218 #ifdef __GLIBC__
219 	optind = 0;
220 #else
221 	optreset = 1; optind = 1; /* initialize getopt */
222 #endif
223 	while (not_fcnumber(argv[optind]) &&
224 	      (ch = getopt(argc, argv, ":e:lnrs")) != -1)
225 		switch ((char)ch) {
226 		case 'e':
227 			editor = optionarg;
228 			break;
229 		case 'l':
230 			lflg = 1;
231 			break;
232 		case 'n':
233 			nflg = 1;
234 			break;
235 		case 'r':
236 			rflg = 1;
237 			break;
238 		case 's':
239 			sflg = 1;
240 			break;
241 		case ':':
242 			sh_error("option -%c expects argument", optopt);
243 			/* NOTREACHED */
244 		case '?':
245 		default:
246 			sh_error("unknown option: -%c", optopt);
247 			/* NOTREACHED */
248 		}
249 	argc -= optind, argv += optind;
250 
251 	/*
252 	 * If executing...
253 	 */
254 	if (lflg == 0 || editor || sflg) {
255 		lflg = 0;	/* ignore */
256 		editfile[0] = '\0';
257 		/*
258 		 * Catch interrupts to reset active counter and
259 		 * cleanup temp files.
260 		 */
261 		if (setjmp(jmploc.loc)) {
262 			active = 0;
263 			if (*editfile)
264 				unlink(editfile);
265 			handler = savehandler;
266 			longjmp(handler->loc, 1);
267 		}
268 		savehandler = handler;
269 		handler = &jmploc;
270 		if (++active > MAXHISTLOOPS) {
271 			active = 0;
272 			displayhist = 0;
273 			sh_error("called recursively too many times");
274 		}
275 		/*
276 		 * Set editor.
277 		 */
278 		if (sflg == 0) {
279 			if (editor == NULL &&
280 			    (editor = bltinlookup("FCEDIT")) == NULL &&
281 			    (editor = bltinlookup("EDITOR")) == NULL)
282 				editor = DEFEDITOR;
283 			if (editor[0] == '-' && editor[1] == '\0') {
284 				sflg = 1;	/* no edit */
285 				editor = NULL;
286 			}
287 		}
288 	}
289 
290 	/*
291 	 * If executing, parse [old=new] now
292 	 */
293 	if (lflg == 0 && argc > 0 &&
294 	     ((repl = strchr(argv[0], '=')) != NULL)) {
295 		pat = argv[0];
296 		*repl++ = '\0';
297 		argc--, argv++;
298 	}
299 	/*
300 	 * determine [first] and [last]
301 	 */
302 	switch (argc) {
303 	case 0:
304 		firststr = lflg ? "-16" : "-1";
305 		laststr = "-1";
306 		break;
307 	case 1:
308 		firststr = argv[0];
309 		laststr = lflg ? "-1" : argv[0];
310 		break;
311 	case 2:
312 		firststr = argv[0];
313 		laststr = argv[1];
314 		break;
315 	default:
316 		sh_error("too many args");
317 		/* NOTREACHED */
318 	}
319 	/*
320 	 * Turn into event numbers.
321 	 */
322 	first = str_to_event(firststr, 0);
323 	last = str_to_event(laststr, 1);
324 
325 	if (rflg) {
326 		i = last;
327 		last = first;
328 		first = i;
329 	}
330 	/*
331 	 * XXX - this should not depend on the event numbers
332 	 * always increasing.  Add sequence numbers or offset
333 	 * to the history element in next (diskbased) release.
334 	 */
335 	direction = first < last ? H_PREV : H_NEXT;
336 
337 	/*
338 	 * If editing, grab a temp file.
339 	 */
340 	if (editor) {
341 		int fd;
342 		INTOFF;		/* easier */
343 		sprintf(editfile, "%s_shXXXXXX", _PATH_TMP);
344 		if ((fd = mkstemp(editfile)) < 0)
345 			sh_error("can't create temporary file %s", editfile);
346 		if ((efp = fdopen(fd, "w")) == NULL) {
347 			close(fd);
348 			sh_error("can't allocate stdio buffer for temp");
349 		}
350 	}
351 
352 	/*
353 	 * Loop through selected history events.  If listing or executing,
354 	 * do it now.  Otherwise, put into temp file and call the editor
355 	 * after.
356 	 *
357 	 * The history interface needs rethinking, as the following
358 	 * convolutions will demonstrate.
359 	 */
360 	history(hist, &he, H_FIRST);
361 	retval = history(hist, &he, H_NEXT_EVENT, first);
362 	for (;retval != -1; retval = history(hist, &he, direction)) {
363 		if (lflg) {
364 			if (!nflg)
365 				out1fmt("%5d ", he.num);
366 			out1str(he.str);
367 		} else {
368 			const char *s = pat ?
369 			   fc_replace(he.str, pat, repl) : he.str;
370 
371 			if (sflg) {
372 				if (displayhist) {
373 					out2str(s);
374 				}
375 
376 				evalstring(s, 0);
377 				if (displayhist && hist) {
378 					/*
379 					 *  XXX what about recursive and
380 					 *  relative histnums.
381 					 */
382 					history(hist, &he, H_ENTER, s);
383 				}
384 			} else
385 				fputs(s, efp);
386 		}
387 		/*
388 		 * At end?  (if we were to lose last, we'd sure be
389 		 * messed up).
390 		 */
391 		if (he.num == last)
392 			break;
393 	}
394 	if (editor) {
395 		char *editcmd;
396 
397 		fclose(efp);
398 		editcmd = stalloc(strlen(editor) + strlen(editfile) + 2);
399 		sprintf(editcmd, "%s %s", editor, editfile);
400 		/* XXX - should use no JC command */
401 		evalstring(editcmd, 0);
402 		INTON;
403 		readcmdfile(editfile);	/* XXX - should read back - quick tst */
404 		unlink(editfile);
405 	}
406 
407 	if (lflg == 0 && active > 0)
408 		--active;
409 	if (displayhist)
410 		displayhist = 0;
411 	return 0;
412 }
413 
414 STATIC const char *
fc_replace(const char * s,char * p,char * r)415 fc_replace(const char *s, char *p, char *r)
416 {
417 	char *dest;
418 	int plen = strlen(p);
419 
420 	STARTSTACKSTR(dest);
421 	while (*s) {
422 		if (*s == *p && strncmp(s, p, plen) == 0) {
423 			while (*r)
424 				STPUTC(*r++, dest);
425 			s += plen;
426 			*p = '\0';	/* so no more matches */
427 		} else
428 			STPUTC(*s++, dest);
429 	}
430 	STACKSTRNUL(dest);
431 	dest = grabstackstr(dest);
432 
433 	return (dest);
434 }
435 
436 int
not_fcnumber(char * s)437 not_fcnumber(char *s)
438 {
439 	if (s == NULL)
440 		return 0;
441         if (*s == '-')
442                 s++;
443 	return (!is_number(s));
444 }
445 
446 int
str_to_event(const char * str,int last)447 str_to_event(const char *str, int last)
448 {
449 	HistEvent he;
450 	const char *s = str;
451 	int relative = 0;
452 	int i, retval;
453 
454 	retval = history(hist, &he, H_FIRST);
455 	switch (*s) {
456 	case '-':
457 		relative = 1;
458 		/*FALLTHROUGH*/
459 	case '+':
460 		s++;
461 	}
462 	if (is_number(s)) {
463 		i = atoi(s);
464 		if (relative) {
465 			while (retval != -1 && i--) {
466 				retval = history(hist, &he, H_NEXT);
467 			}
468 			if (retval == -1)
469 				retval = history(hist, &he, H_LAST);
470 		} else {
471 			retval = history(hist, &he, H_NEXT_EVENT, i);
472 			if (retval == -1) {
473 				/*
474 				 * the notion of first and last is
475 				 * backwards to that of the history package
476 				 */
477 				retval = history(hist, &he,
478 						last ? H_FIRST : H_LAST);
479 			}
480 		}
481 		if (retval == -1)
482 			sh_error("history number %s not found (internal error)",
483 				 str);
484 	} else {
485 		/*
486 		 * pattern
487 		 */
488 		retval = history(hist, &he, H_PREV_STR, str);
489 		if (retval == -1)
490 			sh_error("history pattern not found: %s", str);
491 	}
492 	return (he.num);
493 }
494 #endif
495