xref: /openbsd-src/bin/csh/file.c (revision b1f6b19767b9e5ace57cdaf723a422fde3f45f11)
1 /*	$OpenBSD: file.c,v 1.12 2002/07/24 19:53:50 millert Exp $	*/
2 /*	$NetBSD: file.c,v 1.11 1996/11/08 19:34:37 christos Exp $	*/
3 
4 /*-
5  * Copyright (c) 1980, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *	This product includes software developed by the University of
19  *	California, Berkeley and its contributors.
20  * 4. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #ifndef lint
38 #if 0
39 static char sccsid[] = "@(#)file.c	8.2 (Berkeley) 3/19/94";
40 #else
41 static char rcsid[] = "$OpenBSD: file.c,v 1.12 2002/07/24 19:53:50 millert Exp $";
42 #endif
43 #endif /* not lint */
44 
45 #ifdef FILEC
46 
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/stat.h>
50 #include <termios.h>
51 #include <dirent.h>
52 #include <pwd.h>
53 #include <stdlib.h>
54 #include <unistd.h>
55 #ifndef SHORT_STRINGS
56 #include <string.h>
57 #endif /* SHORT_STRINGS */
58 #include <stdarg.h>
59 
60 #include "csh.h"
61 #include "extern.h"
62 
63 /*
64  * Tenex style file name recognition, .. and more.
65  * History:
66  *	Author: Ken Greer, Sept. 1975, CMU.
67  *	Finally got around to adding to the Cshell., Ken Greer, Dec. 1981.
68  */
69 
70 #define ON	1
71 #define OFF	0
72 #ifndef TRUE
73 #define TRUE 1
74 #endif
75 #ifndef FALSE
76 #define FALSE 0
77 #endif
78 
79 #define ESC	'\033'
80 
81 typedef enum {
82     LIST, RECOGNIZE
83 }       COMMAND;
84 
85 static void	 setup_tty(int);
86 static void	 back_to_col_1(void);
87 static void	 pushback(Char *);
88 static void	 catn(Char *, Char *, int);
89 static void	 copyn(Char *, Char *, int);
90 static Char	 filetype(Char *, Char *);
91 static void	 print_by_column(Char *, Char *[], int);
92 static Char	*tilde(Char *, Char *);
93 static void	 retype(void);
94 static void	 beep(void);
95 static void	 print_recognized_stuff(Char *);
96 static void	 extract_dir_and_name(Char *, Char *, Char *);
97 static Char	*getentry(DIR *, int);
98 static void	 free_items(Char **, int);
99 static int	 tsearch(Char *, COMMAND, int);
100 static int	 recognize(Char *, Char *, int, int);
101 static int	 is_prefix(Char *, Char *);
102 static int	 is_suffix(Char *, Char *);
103 static int	 ignored(Char *);
104 
105 /*
106  * Put this here so the binary can be patched with adb to enable file
107  * completion by default.  Filec controls completion, nobeep controls
108  * ringing the terminal bell on incomplete expansions.
109  */
110 bool    filec = 0;
111 
112 static void
113 setup_tty(on)
114     int     on;
115 {
116     struct termios tchars;
117 
118     (void) tcgetattr(SHIN, &tchars);
119 
120     if (on) {
121 	tchars.c_cc[VEOL] = ESC;
122 	if (tchars.c_lflag & ICANON)
123 	    on = TCSADRAIN;
124 	else {
125 	    tchars.c_lflag |= ICANON;
126 	    on = TCSAFLUSH;
127 	}
128     }
129     else {
130 	tchars.c_cc[VEOL] = _POSIX_VDISABLE;
131 	on = TCSADRAIN;
132     }
133 
134     (void) tcsetattr(SHIN, on, &tchars);
135 }
136 
137 /*
138  * Move back to beginning of current line
139  */
140 static void
141 back_to_col_1()
142 {
143     struct termios tty, tty_normal;
144     sigset_t sigset, osigset;
145 
146     sigemptyset(&sigset);
147     sigaddset(&sigset, SIGINT);
148     sigprocmask(SIG_BLOCK, &sigset, &osigset);
149     (void) tcgetattr(SHOUT, &tty);
150     tty_normal = tty;
151     tty.c_iflag &= ~INLCR;
152     tty.c_oflag &= ~ONLCR;
153     (void) tcsetattr(SHOUT, TCSADRAIN, &tty);
154     (void) write(SHOUT, "\r", 1);
155     (void) tcsetattr(SHOUT, TCSADRAIN, &tty_normal);
156     sigprocmask(SIG_SETMASK, &osigset, NULL);
157 }
158 
159 /*
160  * Push string contents back into tty queue
161  */
162 static void
163 pushback(string)
164     Char   *string;
165 {
166     register Char *p;
167     struct termios tty, tty_normal;
168     sigset_t sigset, osigset;
169     char    c;
170 
171     sigemptyset(&sigset);
172     sigaddset(&sigset, SIGINT);
173     sigprocmask(SIG_BLOCK, &sigset, &osigset);
174     (void) tcgetattr(SHOUT, &tty);
175     tty_normal = tty;
176     tty.c_lflag &= ~(ECHOKE | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOCTL);
177     (void) tcsetattr(SHOUT, TCSADRAIN, &tty);
178 
179     for (p = string; (c = *p) != '\0'; p++)
180 	(void) ioctl(SHOUT, TIOCSTI, (ioctl_t) & c);
181     (void) tcsetattr(SHOUT, TCSADRAIN, &tty_normal);
182     sigprocmask(SIG_SETMASK, &osigset, NULL);
183 }
184 
185 /*
186  * Concatenate src onto tail of des.
187  * Des is a string whose maximum length is count.
188  * Always null terminate.
189  */
190 static void
191 catn(des, src, count)
192     register Char *des, *src;
193     register int count;
194 {
195     while (--count >= 0 && *des)
196 	des++;
197     while (--count >= 0)
198 	if ((*des++ = *src++) == 0)
199 	    return;
200     *des = '\0';
201 }
202 
203 /*
204  * Like strncpy but always leave room for trailing \0
205  * and always null terminate.
206  */
207 static void
208 copyn(des, src, count)
209     register Char *des, *src;
210     register int count;
211 {
212     while (--count >= 0)
213 	if ((*des++ = *src++) == 0)
214 	    return;
215     *des = '\0';
216 }
217 
218 static  Char
219 filetype(dir, file)
220     Char   *dir, *file;
221 {
222     Char    path[MAXPATHLEN];
223     struct stat statb;
224 
225     catn(Strcpy(path, dir), file, sizeof(path) / sizeof(Char));
226     if (lstat(short2str(path), &statb) == 0) {
227 	switch (statb.st_mode & S_IFMT) {
228 	case S_IFDIR:
229 	    return ('/');
230 
231 	case S_IFLNK:
232 	    if (stat(short2str(path), &statb) == 0 &&	/* follow it out */
233 		S_ISDIR(statb.st_mode))
234 		return ('>');
235 	    else
236 		return ('@');
237 
238 	case S_IFSOCK:
239 	    return ('=');
240 
241 	default:
242 	    if (statb.st_mode & 0111)
243 		return ('*');
244 	}
245     }
246     return (' ');
247 }
248 
249 static struct winsize win;
250 
251 /*
252  * Print sorted down columns
253  */
254 static void
255 print_by_column(dir, items, count)
256     Char   *dir, *items[];
257     int     count;
258 {
259     register int i, rows, r, c, maxwidth = 0, columns;
260 
261     if (ioctl(SHOUT, TIOCGWINSZ, (ioctl_t) & win) < 0 || win.ws_col == 0)
262 	win.ws_col = 80;
263     for (i = 0; i < count; i++)
264 	maxwidth = maxwidth > (r = Strlen(items[i])) ? maxwidth : r;
265     maxwidth += 2;		/* for the file tag and space */
266     columns = win.ws_col / maxwidth;
267     if (columns == 0)
268 	columns = 1;
269     rows = (count + (columns - 1)) / columns;
270     for (r = 0; r < rows; r++) {
271 	for (c = 0; c < columns; c++) {
272 	    i = c * rows + r;
273 	    if (i < count) {
274 		register int w;
275 
276 		(void) fprintf(cshout, "%s", vis_str(items[i]));
277 		(void) fputc(dir ? filetype(dir, items[i]) : ' ', cshout);
278 		if (c < columns - 1) {	/* last column? */
279 		    w = Strlen(items[i]) + 1;
280 		    for (; w < maxwidth; w++)
281 			(void) fputc(' ', cshout);
282 		}
283 	    }
284 	}
285 	(void) fputc('\r', cshout);
286 	(void) fputc('\n', cshout);
287     }
288 }
289 
290 /*
291  * Expand file name with possible tilde usage
292  *	~person/mumble
293  * expands to
294  *	home_directory_of_person/mumble
295  */
296 static Char *
297 tilde(new, old)
298     Char   *new, *old;
299 {
300     register Char *o, *p;
301     register struct passwd *pw;
302     static Char person[40];
303 
304     if (old[0] != '~')
305 	return (Strcpy(new, old));
306 
307     for (p = person, o = &old[1]; *o && *o != '/'; *p++ = *o++)
308 	continue;
309     *p = '\0';
310     if (person[0] == '\0')
311 	(void) Strcpy(new, value(STRhome));
312     else {
313 	pw = getpwnam(short2str(person));
314 	if (pw == NULL)
315 	    return (NULL);
316 	(void) Strcpy(new, str2short(pw->pw_dir));
317     }
318     (void) Strcat(new, o);
319     return (new);
320 }
321 
322 /*
323  * Cause pending line to be printed
324  */
325 static void
326 retype()
327 {
328     struct termios tty;
329 
330     (void) tcgetattr(SHOUT, &tty);
331     tty.c_lflag |= PENDIN;
332     (void) tcsetattr(SHOUT, TCSADRAIN, &tty);
333 }
334 
335 static void
336 beep()
337 {
338     if (adrof(STRnobeep) == 0)
339 	(void) write(SHOUT, "\007", 1);
340 }
341 
342 /*
343  * Erase that silly ^[ and
344  * print the recognized part of the string
345  */
346 static void
347 print_recognized_stuff(recognized_part)
348     Char   *recognized_part;
349 {
350     /* An optimized erasing of that silly ^[ */
351     (void) fputc('\b', cshout);
352     (void) fputc('\b', cshout);
353     switch (Strlen(recognized_part)) {
354 
355     case 0:			/* erase two Characters: ^[ */
356 	(void) fputc(' ', cshout);
357 	(void) fputc(' ', cshout);
358 	(void) fputc('\b', cshout);
359 	(void) fputc('\b', cshout);
360 	break;
361 
362     case 1:			/* overstrike the ^, erase the [ */
363 	(void) fprintf(cshout, "%s", vis_str(recognized_part));
364 	(void) fputc(' ', cshout);
365 	(void) fputc('\b', cshout);
366 	break;
367 
368     default:			/* overstrike both Characters ^[ */
369 	(void) fprintf(cshout, "%s", vis_str(recognized_part));
370 	break;
371     }
372     (void) fflush(cshout);
373 }
374 
375 /*
376  * Parse full path in file into 2 parts: directory and file names
377  * Should leave final slash (/) at end of dir.
378  */
379 static void
380 extract_dir_and_name(path, dir, name)
381     Char   *path, *dir, *name;
382 {
383     register Char *p;
384 
385     p = Strrchr(path, '/');
386     if (p == NULL) {
387 	copyn(name, path, MAXNAMLEN);
388 	dir[0] = '\0';
389     }
390     else {
391 	copyn(name, ++p, MAXNAMLEN);
392 	copyn(dir, path, p - path);
393     }
394 }
395 
396 static Char *
397 getentry(dir_fd, looking_for_lognames)
398     DIR    *dir_fd;
399     int     looking_for_lognames;
400 {
401     register struct passwd *pw;
402     register struct dirent *dirp;
403 
404     if (looking_for_lognames) {
405 	if ((pw = getpwent()) == NULL)
406 	    return (NULL);
407 	return (str2short(pw->pw_name));
408     }
409     if ((dirp = readdir(dir_fd)) != NULL)
410 	return (str2short(dirp->d_name));
411     return (NULL);
412 }
413 
414 static void
415 free_items(items, numitems)
416     Char **items;
417     int numitems;
418 {
419     int i;
420 
421     for (i = 0; i < numitems; i++)
422 	xfree((ptr_t) items[i]);
423     xfree((ptr_t) items);
424 }
425 
426 #define FREE_ITEMS(items) { \
427 	sigset_t sigset, osigset;\
428 \
429 	sigemptyset(&sigset);\
430 	sigaddset(&sigset, SIGINT);\
431 	sigprocmask(SIG_BLOCK, &sigset, &osigset);\
432 	free_items(items, numitems);\
433 	sigprocmask(SIG_SETMASK, &osigset, NULL);\
434 }
435 
436 /*
437  * Perform a RECOGNIZE or LIST command on string "word".
438  */
439 static int
440 tsearch(word, command, max_word_length)
441     Char   *word;
442     COMMAND command;
443     int     max_word_length;
444 {
445     register DIR *dir_fd;
446     register int numitems = 0, ignoring = TRUE, nignored = 0;
447     register int name_length, looking_for_lognames;
448     Char    tilded_dir[MAXPATHLEN], dir[MAXPATHLEN];
449     Char    name[MAXNAMLEN + 1], extended_name[MAXNAMLEN + 1];
450     Char   *entry;
451     Char   **items = NULL;
452     size_t  maxitems = 0;
453 
454     looking_for_lognames = (*word == '~') && (Strchr(word, '/') == NULL);
455     if (looking_for_lognames) {
456 	(void) setpwent();
457 	copyn(name, &word[1], MAXNAMLEN);	/* name sans ~ */
458 	dir_fd = NULL;
459     }
460     else {
461 	extract_dir_and_name(word, dir, name);
462 	if (tilde(tilded_dir, dir) == 0)
463 	    return (0);
464 	dir_fd = opendir(*tilded_dir ? short2str(tilded_dir) : ".");
465 	if (dir_fd == NULL)
466 	    return (0);
467     }
468 
469 again:				/* search for matches */
470     name_length = Strlen(name);
471     for (numitems = 0; (entry = getentry(dir_fd, looking_for_lognames)) != NULL;) {
472 	if (!is_prefix(name, entry))
473 	    continue;
474 	/* Don't match . files on null prefix match */
475 	if (name_length == 0 && entry[0] == '.' &&
476 	    !looking_for_lognames)
477 	    continue;
478 	if (command == LIST) {
479 	    if (numitems >= maxitems) {
480 		maxitems += 1024;
481 		if (items == NULL)
482 			items = (Char **) xmalloc(sizeof(*items) * maxitems);
483 		else
484 			items = (Char **) xrealloc((ptr_t) items,
485 			    sizeof(*items) * maxitems);
486 	    }
487 	    items[numitems] = (Char *) xmalloc((size_t) (Strlen(entry) + 1) *
488 					       sizeof(Char));
489 	    copyn(items[numitems], entry, MAXNAMLEN);
490 	    numitems++;
491 	}
492 	else {			/* RECOGNIZE command */
493 	    if (ignoring && ignored(entry))
494 		nignored++;
495 	    else if (recognize(extended_name,
496 			       entry, name_length, ++numitems))
497 		break;
498 	}
499     }
500     if (ignoring && numitems == 0 && nignored > 0) {
501 	ignoring = FALSE;
502 	nignored = 0;
503 	if (looking_for_lognames)
504 	    (void) setpwent();
505 	else
506 	    rewinddir(dir_fd);
507 	goto again;
508     }
509 
510     if (looking_for_lognames)
511 	(void) endpwent();
512     else
513 	(void) closedir(dir_fd);
514     if (numitems == 0)
515 	return (0);
516     if (command == RECOGNIZE) {
517 	if (looking_for_lognames)
518 	    copyn(word, STRtilde, 1);
519 	else
520 	    /* put back dir part */
521 	    copyn(word, dir, max_word_length);
522 	/* add extended name */
523 	catn(word, extended_name, max_word_length);
524 	return (numitems);
525     }
526     else {			/* LIST */
527 	qsort((ptr_t) items, numitems, sizeof(*items),
528 		(int (*)(const void *, const void *)) sortscmp);
529 	print_by_column(looking_for_lognames ? NULL : tilded_dir,
530 			items, numitems);
531 	if (items != NULL)
532 	    FREE_ITEMS(items);
533     }
534     return (0);
535 }
536 
537 /*
538  * Object: extend what user typed up to an ambiguity.
539  * Algorithm:
540  * On first match, copy full entry (assume it'll be the only match)
541  * On subsequent matches, shorten extended_name to the first
542  * Character mismatch between extended_name and entry.
543  * If we shorten it back to the prefix length, stop searching.
544  */
545 static int
546 recognize(extended_name, entry, name_length, numitems)
547     Char   *extended_name, *entry;
548     int     name_length, numitems;
549 {
550     if (numitems == 1)		/* 1st match */
551 	copyn(extended_name, entry, MAXNAMLEN);
552     else {			/* 2nd & subsequent matches */
553 	register Char *x, *ent;
554 	register int len = 0;
555 
556 	x = extended_name;
557 	for (ent = entry; *x && *x == *ent++; x++, len++)
558 	    continue;
559 	*x = '\0';		/* Shorten at 1st Char diff */
560 	if (len == name_length)	/* Ambiguous to prefix? */
561 	    return (-1);	/* So stop now and save time */
562     }
563     return (0);
564 }
565 
566 /*
567  * Return true if check matches initial Chars in template.
568  * This differs from PWB imatch in that if check is null
569  * it matches anything.
570  */
571 static int
572 is_prefix(check, template)
573     register Char *check, *template;
574 {
575     do
576 	if (*check == 0)
577 	    return (TRUE);
578     while (*check++ == *template++);
579     return (FALSE);
580 }
581 
582 /*
583  *  Return true if the Chars in template appear at the
584  *  end of check, I.e., are it's suffix.
585  */
586 static int
587 is_suffix(check, template)
588     Char   *check, *template;
589 {
590     register Char *c, *t;
591 
592     for (c = check; *c++;)
593 	continue;
594     for (t = template; *t++;)
595 	continue;
596     for (;;) {
597 	if (t == template)
598 	    return 1;
599 	if (c == check || *--t != *--c)
600 	    return 0;
601     }
602 }
603 
604 int
605 tenex(inputline, inputline_size)
606     Char   *inputline;
607     int     inputline_size;
608 {
609     register int numitems, num_read;
610     char    tinputline[BUFSIZ];
611 
612 
613     setup_tty(ON);
614 
615     while ((num_read = read(SHIN, tinputline, BUFSIZ)) > 0) {
616 	int     i;
617 	static Char delims[] = {' ', '\'', '"', '\t', ';', '&', '<',
618 	'>', '(', ')', '|', '^', '%', '\0'};
619 	register Char *str_end, *word_start, last_Char, should_retype;
620 	register int space_left;
621 	COMMAND command;
622 
623 	for (i = 0; i < num_read; i++)
624 	    inputline[i] = (unsigned char) tinputline[i];
625 	last_Char = inputline[num_read - 1] & ASCII;
626 
627 	if (last_Char == '\n' || num_read == inputline_size)
628 	    break;
629 	command = (last_Char == ESC) ? RECOGNIZE : LIST;
630 	if (command == LIST)
631 	    (void) fputc('\n', cshout);
632 	str_end = &inputline[num_read];
633 	if (last_Char == ESC)
634 	    --str_end;		/* wipeout trailing cmd Char */
635 	*str_end = '\0';
636 	/*
637 	 * Find LAST occurrence of a delimiter in the inputline. The word start
638 	 * is one Character past it.
639 	 */
640 	for (word_start = str_end; word_start > inputline; --word_start)
641 	    if (Strchr(delims, word_start[-1]))
642 		break;
643 	space_left = inputline_size - (word_start - inputline) - 1;
644 	numitems = tsearch(word_start, command, space_left);
645 
646 	if (command == RECOGNIZE) {
647 	    /* print from str_end on */
648 	    print_recognized_stuff(str_end);
649 	    if (numitems != 1)	/* Beep = No match/ambiguous */
650 		beep();
651 	}
652 
653 	/*
654 	 * Tabs in the input line cause trouble after a pushback. tty driver
655 	 * won't backspace over them because column positions are now
656 	 * incorrect. This is solved by retyping over current line.
657 	 */
658 	should_retype = FALSE;
659 	if (Strchr(inputline, '\t')) {	/* tab Char in input line? */
660 	    back_to_col_1();
661 	    should_retype = TRUE;
662 	}
663 	if (command == LIST)	/* Always retype after a LIST */
664 	    should_retype = TRUE;
665 	if (should_retype)
666 	    printprompt();
667 	pushback(inputline);
668 	if (should_retype)
669 	    retype();
670     }
671     setup_tty(OFF);
672     return (num_read);
673 }
674 
675 static int
676 ignored(entry)
677     register Char *entry;
678 {
679     struct varent *vp;
680     register Char **cp;
681 
682     if ((vp = adrof(STRfignore)) == NULL || (cp = vp->vec) == NULL)
683 	return (FALSE);
684     for (; *cp != NULL; cp++)
685 	if (is_suffix(entry, *cp))
686 	    return (TRUE);
687     return (FALSE);
688 }
689 #endif				/* FILEC */
690