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