Catch up with the latest LWKT msgport updating.
[dragonfly/vkernel-mp.git] / contrib / less-394 / filename.c
blob8b1c4c99421c483726dab1d5fcc24b28ec88c884
1 /*
2 * Copyright (C) 1984-2005 Mark Nudelman
4 * You may distribute under the terms of either the GNU General Public
5 * License or the Less License, as specified in the README file.
7 * For more information about less, or for information on how to
8 * contact the author, see the README file.
9 */
13 * Routines to mess around with filenames (and files).
14 * Much of this is very OS dependent.
17 #include "less.h"
18 #include "lglob.h"
19 #if MSDOS_COMPILER
20 #include <dos.h>
21 #if MSDOS_COMPILER==WIN32C && !defined(_MSC_VER)
22 #include <dir.h>
23 #endif
24 #if MSDOS_COMPILER==DJGPPC
25 #include <glob.h>
26 #include <dir.h>
27 #define _MAX_PATH PATH_MAX
28 #endif
29 #endif
30 #ifdef _OSK
31 #include <rbf.h>
32 #ifndef _OSK_MWC32
33 #include <modes.h>
34 #endif
35 #endif
36 #if OS2
37 #include <signal.h>
38 #endif
40 #if HAVE_STAT
41 #include <sys/stat.h>
42 #ifndef S_ISDIR
43 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
44 #endif
45 #ifndef S_ISREG
46 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
47 #endif
48 #endif
51 extern int force_open;
52 extern int secure;
53 extern int use_lessopen;
54 extern IFILE curr_ifile;
55 extern IFILE old_ifile;
56 #if SPACES_IN_FILENAMES
57 extern char openquote;
58 extern char closequote;
59 #endif
62 * Remove quotes around a filename.
64 public char *
65 shell_unquote(str)
66 char *str;
68 char *name;
69 char *p;
71 name = p = (char *) ecalloc(strlen(str)+1, sizeof(char));
72 if (*str == openquote)
74 str++;
75 while (*str != '\0')
77 if (*str == closequote)
79 if (str[1] != closequote)
80 break;
81 str++;
83 *p++ = *str++;
85 } else
87 char *esc = get_meta_escape();
88 int esclen = strlen(esc);
89 while (*str != '\0')
91 if (esclen > 0 && strncmp(str, esc, esclen) == 0)
92 str += esclen;
93 *p++ = *str++;
96 *p = '\0';
97 return (name);
101 * Get the shell's escape character.
103 public char *
104 get_meta_escape()
106 char *s;
108 s = lgetenv("LESSMETAESCAPE");
109 if (s == NULL)
110 s = DEF_METAESCAPE;
111 return (s);
115 * Get the characters which the shell considers to be "metacharacters".
117 static char *
118 metachars()
120 static char *mchars = NULL;
122 if (mchars == NULL)
124 mchars = lgetenv("LESSMETACHARS");
125 if (mchars == NULL)
126 mchars = DEF_METACHARS;
128 return (mchars);
132 * Is this a shell metacharacter?
134 static int
135 metachar(c)
136 char c;
138 return (strchr(metachars(), c) != NULL);
142 * Insert a backslash before each metacharacter in a string.
144 public char *
145 shell_quote(s)
146 char *s;
148 char *p;
149 char *newstr;
150 int len;
151 char *esc = get_meta_escape();
152 int esclen = strlen(esc);
153 int use_quotes = 0;
154 int have_quotes = 0;
157 * Determine how big a string we need to allocate.
159 len = 1; /* Trailing null byte */
160 for (p = s; *p != '\0'; p++)
162 len++;
163 if (*p == openquote || *p == closequote)
164 have_quotes = 1;
165 if (metachar(*p))
167 if (esclen == 0)
170 * We've got a metachar, but this shell
171 * doesn't support escape chars. Use quotes.
173 use_quotes = 1;
174 } else
177 * Allow space for the escape char.
179 len += esclen;
183 if (use_quotes)
185 if (have_quotes)
187 * We can't quote a string that contains quotes.
189 return (NULL);
190 len = strlen(s) + 3;
193 * Allocate and construct the new string.
195 newstr = p = (char *) ecalloc(len, sizeof(char));
196 if (use_quotes)
198 SNPRINTF3(newstr, len, "%c%s%c", openquote, s, closequote);
199 } else
201 while (*s != '\0')
203 if (metachar(*s))
206 * Add the escape char.
208 strcpy(p, esc);
209 p += esclen;
211 *p++ = *s++;
213 *p = '\0';
215 return (newstr);
219 * Return a pathname that points to a specified file in a specified directory.
220 * Return NULL if the file does not exist in the directory.
222 static char *
223 dirfile(dirname, filename)
224 char *dirname;
225 char *filename;
227 char *pathname;
228 char *qpathname;
229 int len;
230 int f;
232 if (dirname == NULL || *dirname == '\0')
233 return (NULL);
235 * Construct the full pathname.
237 len= strlen(dirname) + strlen(filename) + 2;
238 pathname = (char *) calloc(len, sizeof(char));
239 if (pathname == NULL)
240 return (NULL);
241 SNPRINTF3(pathname, len, "%s%s%s", dirname, PATHNAME_SEP, filename);
243 * Make sure the file exists.
245 qpathname = shell_unquote(pathname);
246 f = open(qpathname, OPEN_READ);
247 if (f < 0)
249 free(pathname);
250 pathname = NULL;
251 } else
253 close(f);
255 free(qpathname);
256 return (pathname);
260 * Return the full pathname of the given file in the "home directory".
262 public char *
263 homefile(filename)
264 char *filename;
266 register char *pathname;
269 * Try $HOME/filename.
271 pathname = dirfile(lgetenv("HOME"), filename);
272 if (pathname != NULL)
273 return (pathname);
274 #if OS2
276 * Try $INIT/filename.
278 pathname = dirfile(lgetenv("INIT"), filename);
279 if (pathname != NULL)
280 return (pathname);
281 #endif
282 #if MSDOS_COMPILER || OS2
284 * Look for the file anywhere on search path.
286 pathname = (char *) calloc(_MAX_PATH, sizeof(char));
287 #if MSDOS_COMPILER==DJGPPC
289 char *res = searchpath(filename);
290 if (res == 0)
291 *pathname = '\0';
292 else
293 strcpy(pathname, res);
295 #else
296 _searchenv(filename, "PATH", pathname);
297 #endif
298 if (*pathname != '\0')
299 return (pathname);
300 free(pathname);
301 #endif
302 return (NULL);
306 * Expand a string, substituting any "%" with the current filename,
307 * and any "#" with the previous filename.
308 * But a string of N "%"s is just replaced with N-1 "%"s.
309 * Likewise for a string of N "#"s.
310 * {{ This is a lot of work just to support % and #. }}
312 public char *
313 fexpand(s)
314 char *s;
316 register char *fr, *to;
317 register int n;
318 register char *e;
319 IFILE ifile;
321 #define fchar_ifile(c) \
322 ((c) == '%' ? curr_ifile : \
323 (c) == '#' ? old_ifile : NULL_IFILE)
326 * Make one pass to see how big a buffer we
327 * need to allocate for the expanded string.
329 n = 0;
330 for (fr = s; *fr != '\0'; fr++)
332 switch (*fr)
334 case '%':
335 case '#':
336 if (fr > s && fr[-1] == *fr)
339 * Second (or later) char in a string
340 * of identical chars. Treat as normal.
342 n++;
343 } else if (fr[1] != *fr)
346 * Single char (not repeated). Treat specially.
348 ifile = fchar_ifile(*fr);
349 if (ifile == NULL_IFILE)
350 n++;
351 else
352 n += strlen(get_filename(ifile));
355 * Else it is the first char in a string of
356 * identical chars. Just discard it.
358 break;
359 default:
360 n++;
361 break;
365 e = (char *) ecalloc(n+1, sizeof(char));
368 * Now copy the string, expanding any "%" or "#".
370 to = e;
371 for (fr = s; *fr != '\0'; fr++)
373 switch (*fr)
375 case '%':
376 case '#':
377 if (fr > s && fr[-1] == *fr)
379 *to++ = *fr;
380 } else if (fr[1] != *fr)
382 ifile = fchar_ifile(*fr);
383 if (ifile == NULL_IFILE)
384 *to++ = *fr;
385 else
387 strcpy(to, get_filename(ifile));
388 to += strlen(to);
391 break;
392 default:
393 *to++ = *fr;
394 break;
397 *to = '\0';
398 return (e);
401 #if TAB_COMPLETE_FILENAME
404 * Return a blank-separated list of filenames which "complete"
405 * the given string.
407 public char *
408 fcomplete(s)
409 char *s;
411 char *fpat;
412 char *qs;
414 if (secure)
415 return (NULL);
417 * Complete the filename "s" by globbing "s*".
419 #if MSDOS_COMPILER && (MSDOS_COMPILER == MSOFTC || MSDOS_COMPILER == BORLANDC)
421 * But in DOS, we have to glob "s*.*".
422 * But if the final component of the filename already has
423 * a dot in it, just do "s*".
424 * (Thus, "FILE" is globbed as "FILE*.*",
425 * but "FILE.A" is globbed as "FILE.A*").
428 char *slash;
429 int len;
430 for (slash = s+strlen(s)-1; slash > s; slash--)
431 if (*slash == *PATHNAME_SEP || *slash == '/')
432 break;
433 len = strlen(s) + 4;
434 fpat = (char *) ecalloc(len, sizeof(char));
435 if (strchr(slash, '.') == NULL)
436 SNPRINTF1(fpat, len, "%s*.*", s);
437 else
438 SNPRINTF1(fpat, len, "%s*", s);
440 #else
442 int len = strlen(s) + 2;
443 fpat = (char *) ecalloc(len, sizeof(char));
444 SNPRINTF1(fpat, len, "%s*", s);
446 #endif
447 qs = lglob(fpat);
448 s = shell_unquote(qs);
449 if (strcmp(s,fpat) == 0)
452 * The filename didn't expand.
454 free(qs);
455 qs = NULL;
457 free(s);
458 free(fpat);
459 return (qs);
461 #endif
464 * Try to determine if a file is "binary".
465 * This is just a guess, and we need not try too hard to make it accurate.
467 public int
468 bin_file(f)
469 int f;
471 int i;
472 int n;
473 unsigned char data[64];
475 if (!seekable(f))
476 return (0);
477 if (lseek(f, (off_t)0, 0) == BAD_LSEEK)
478 return (0);
479 n = read(f, data, sizeof(data));
480 for (i = 0; i < n; i++)
481 if (binary_char(data[i]))
482 return (1);
483 return (0);
487 * Try to determine the size of a file by seeking to the end.
489 static POSITION
490 seek_filesize(f)
491 int f;
493 off_t spos;
495 spos = lseek(f, (off_t)0, 2);
496 if (spos == BAD_LSEEK)
497 return (NULL_POSITION);
498 return ((POSITION) spos);
502 * Read a string from a file.
503 * Return a pointer to the string in memory.
505 static char *
506 readfd(fd)
507 FILE *fd;
509 int len;
510 int ch;
511 char *buf;
512 char *p;
515 * Make a guess about how many chars in the string
516 * and allocate a buffer to hold it.
518 len = 100;
519 buf = (char *) ecalloc(len, sizeof(char));
520 for (p = buf; ; p++)
522 if ((ch = getc(fd)) == '\n' || ch == EOF)
523 break;
524 if (p - buf >= len-1)
527 * The string is too big to fit in the buffer we have.
528 * Allocate a new buffer, twice as big.
530 len *= 2;
531 *p = '\0';
532 p = (char *) ecalloc(len, sizeof(char));
533 strcpy(p, buf);
534 free(buf);
535 buf = p;
536 p = buf + strlen(buf);
538 *p = ch;
540 *p = '\0';
541 return (buf);
546 #if HAVE_POPEN
548 FILE *popen();
551 * Execute a shell command.
552 * Return a pointer to a pipe connected to the shell command's standard output.
554 static FILE *
555 shellcmd(cmd)
556 char *cmd;
558 FILE *fd;
560 #if HAVE_SHELL
561 char *shell;
563 shell = lgetenv("SHELL");
564 if (shell != NULL && *shell != '\0')
566 char *scmd;
567 char *esccmd;
570 * Read the output of <$SHELL -c cmd>.
571 * Escape any metacharacters in the command.
573 esccmd = shell_quote(cmd);
574 if (esccmd == NULL)
576 fd = popen(cmd, "r");
577 } else
579 int len = strlen(shell) + strlen(esccmd) + 5;
580 scmd = (char *) ecalloc(len, sizeof(char));
581 SNPRINTF3(scmd, len, "%s %s %s", shell, shell_coption(), esccmd);
582 free(esccmd);
583 fd = popen(scmd, "r");
584 free(scmd);
586 } else
587 #endif
589 fd = popen(cmd, "r");
592 * Redirection in `popen' might have messed with the
593 * standard devices. Restore binary input mode.
595 SET_BINARY(0);
596 return (fd);
599 #endif /* HAVE_POPEN */
603 * Expand a filename, doing any system-specific metacharacter substitutions.
605 public char *
606 lglob(filename)
607 char *filename;
609 char *gfilename;
610 char *ofilename;
612 ofilename = fexpand(filename);
613 if (secure)
614 return (ofilename);
615 filename = shell_unquote(ofilename);
617 #ifdef DECL_GLOB_LIST
620 * The globbing function returns a list of names.
622 int length;
623 char *p;
624 char *qfilename;
625 DECL_GLOB_LIST(list)
627 GLOB_LIST(filename, list);
628 if (GLOB_LIST_FAILED(list))
630 free(filename);
631 return (ofilename);
633 length = 1; /* Room for trailing null byte */
634 for (SCAN_GLOB_LIST(list, p))
636 INIT_GLOB_LIST(list, p);
637 qfilename = shell_quote(p);
638 if (qfilename != NULL)
640 length += strlen(qfilename) + 1;
641 free(qfilename);
644 gfilename = (char *) ecalloc(length, sizeof(char));
645 for (SCAN_GLOB_LIST(list, p))
647 INIT_GLOB_LIST(list, p);
648 qfilename = shell_quote(p);
649 if (qfilename != NULL)
651 sprintf(gfilename + strlen(gfilename), "%s ", qfilename);
652 free(qfilename);
656 * Overwrite the final trailing space with a null terminator.
658 *--p = '\0';
659 GLOB_LIST_DONE(list);
661 #else
662 #ifdef DECL_GLOB_NAME
665 * The globbing function returns a single name, and
666 * is called multiple times to walk thru all names.
668 register char *p;
669 register int len;
670 register int n;
671 char *pathname;
672 char *qpathname;
673 DECL_GLOB_NAME(fnd,drive,dir,fname,ext,handle)
675 GLOB_FIRST_NAME(filename, &fnd, handle);
676 if (GLOB_FIRST_FAILED(handle))
678 free(filename);
679 return (ofilename);
682 _splitpath(filename, drive, dir, fname, ext);
683 len = 100;
684 gfilename = (char *) ecalloc(len, sizeof(char));
685 p = gfilename;
686 do {
687 n = strlen(drive) + strlen(dir) + strlen(fnd.GLOB_NAME) + 1;
688 pathname = (char *) ecalloc(n, sizeof(char));
689 SNPRINTF3(pathname, n, "%s%s%s", drive, dir, fnd.GLOB_NAME);
690 qpathname = shell_quote(pathname);
691 free(pathname);
692 if (qpathname != NULL)
694 n = strlen(qpathname);
695 while (p - gfilename + n + 2 >= len)
698 * No room in current buffer.
699 * Allocate a bigger one.
701 len *= 2;
702 *p = '\0';
703 p = (char *) ecalloc(len, sizeof(char));
704 strcpy(p, gfilename);
705 free(gfilename);
706 gfilename = p;
707 p = gfilename + strlen(gfilename);
709 strcpy(p, qpathname);
710 free(qpathname);
711 p += n;
712 *p++ = ' ';
714 } while (GLOB_NEXT_NAME(handle, &fnd) == 0);
717 * Overwrite the final trailing space with a null terminator.
719 *--p = '\0';
720 GLOB_NAME_DONE(handle);
722 #else
723 #if HAVE_POPEN
726 * We get the shell to glob the filename for us by passing
727 * an "echo" command to the shell and reading its output.
729 FILE *fd;
730 char *s;
731 char *lessecho;
732 char *cmd;
733 char *esc;
734 int len;
736 esc = get_meta_escape();
737 if (strlen(esc) == 0)
738 esc = "-";
739 esc = shell_quote(esc);
740 if (esc == NULL)
742 free(filename);
743 return (ofilename);
745 lessecho = lgetenv("LESSECHO");
746 if (lessecho == NULL || *lessecho == '\0')
747 lessecho = "lessecho";
749 * Invoke lessecho, and read its output (a globbed list of filenames).
751 len = strlen(lessecho) + strlen(ofilename) + (7*strlen(metachars())) + 24;
752 cmd = (char *) ecalloc(len, sizeof(char));
753 SNPRINTF4(cmd, len, "%s -p0x%x -d0x%x -e%s ", lessecho, openquote, closequote, esc);
754 free(esc);
755 for (s = metachars(); *s != '\0'; s++)
756 sprintf(cmd + strlen(cmd), "-n0x%x ", *s);
757 sprintf(cmd + strlen(cmd), "-- %s", ofilename);
758 fd = shellcmd(cmd);
759 free(cmd);
760 if (fd == NULL)
763 * Cannot create the pipe.
764 * Just return the original (fexpanded) filename.
766 free(filename);
767 return (ofilename);
769 gfilename = readfd(fd);
770 pclose(fd);
771 if (*gfilename == '\0')
773 free(gfilename);
774 free(filename);
775 return (ofilename);
778 #else
780 * No globbing functions at all. Just use the fexpanded filename.
782 gfilename = save(filename);
783 #endif
784 #endif
785 #endif
786 free(filename);
787 free(ofilename);
788 return (gfilename);
792 * See if we should open a "replacement file"
793 * instead of the file we're about to open.
795 public char *
796 open_altfile(filename, pf, pfd)
797 char *filename;
798 int *pf;
799 void **pfd;
801 #if !HAVE_POPEN
802 return (NULL);
803 #else
804 char *lessopen;
805 char *cmd;
806 int len;
807 FILE *fd;
808 #if HAVE_FILENO
809 int returnfd = 0;
810 #endif
812 if (!use_lessopen || secure)
813 return (NULL);
814 ch_ungetchar(-1);
815 if ((lessopen = lgetenv("LESSOPEN")) == NULL)
816 return (NULL);
817 if (strcmp(filename, "-") == 0)
818 return (NULL);
819 if (*lessopen == '|')
822 * If LESSOPEN starts with a |, it indicates
823 * a "pipe preprocessor".
825 #if HAVE_FILENO
826 lessopen++;
827 returnfd = 1;
828 #else
829 error("LESSOPEN pipe is not supported", NULL_PARG);
830 return (NULL);
831 #endif
834 len = strlen(lessopen) + strlen(filename) + 2;
835 cmd = (char *) ecalloc(len, sizeof(char));
836 SNPRINTF1(cmd, len, lessopen, filename);
837 fd = shellcmd(cmd);
838 free(cmd);
839 if (fd == NULL)
842 * Cannot create the pipe.
844 return (NULL);
846 #if HAVE_FILENO
847 if (returnfd)
849 int f;
850 char c;
853 * Read one char to see if the pipe will produce any data.
854 * If it does, push the char back on the pipe.
856 f = fileno(fd);
857 SET_BINARY(f);
858 if (read(f, &c, 1) != 1)
861 * Pipe is empty. This means there is no alt file.
863 pclose(fd);
864 return (NULL);
866 ch_ungetchar(c);
867 *pfd = (void *) fd;
868 *pf = f;
869 return (save("-"));
871 #endif
872 cmd = readfd(fd);
873 pclose(fd);
874 if (*cmd == '\0')
876 * Pipe is empty. This means there is no alt file.
878 return (NULL);
879 return (cmd);
880 #endif /* HAVE_POPEN */
884 * Close a replacement file.
886 public void
887 close_altfile(altfilename, filename, pipefd)
888 char *altfilename;
889 char *filename;
890 void *pipefd;
892 #if HAVE_POPEN
893 char *lessclose;
894 FILE *fd;
895 char *cmd;
896 int len;
898 if (secure)
899 return;
900 if (pipefd != NULL)
902 #if OS2
904 * The pclose function of OS/2 emx sometimes fails.
905 * Send SIGINT to the piped process before closing it.
907 kill(((FILE*)pipefd)->_pid, SIGINT);
908 #endif
909 pclose((FILE*) pipefd);
911 if ((lessclose = lgetenv("LESSCLOSE")) == NULL)
912 return;
913 len = strlen(lessclose) + strlen(filename) + strlen(altfilename) + 2;
914 cmd = (char *) ecalloc(len, sizeof(char));
915 SNPRINTF2(cmd, len, lessclose, filename, altfilename);
916 fd = shellcmd(cmd);
917 free(cmd);
918 if (fd != NULL)
919 pclose(fd);
920 #endif
924 * Is the specified file a directory?
926 public int
927 is_dir(filename)
928 char *filename;
930 int isdir = 0;
932 filename = shell_unquote(filename);
933 #if HAVE_STAT
935 int r;
936 struct stat statbuf;
938 r = stat(filename, &statbuf);
939 isdir = (r >= 0 && S_ISDIR(statbuf.st_mode));
941 #else
942 #ifdef _OSK
944 register int f;
946 f = open(filename, S_IREAD | S_IFDIR);
947 if (f >= 0)
948 close(f);
949 isdir = (f >= 0);
951 #endif
952 #endif
953 free(filename);
954 return (isdir);
958 * Returns NULL if the file can be opened and
959 * is an ordinary file, otherwise an error message
960 * (if it cannot be opened or is a directory, etc.)
962 public char *
963 bad_file(filename)
964 char *filename;
966 register char *m = NULL;
968 filename = shell_unquote(filename);
969 if (is_dir(filename))
971 static char is_a_dir[] = " is a directory";
973 m = (char *) ecalloc(strlen(filename) + sizeof(is_a_dir),
974 sizeof(char));
975 strcpy(m, filename);
976 strcat(m, is_a_dir);
977 } else
979 #if HAVE_STAT
980 int r;
981 struct stat statbuf;
983 r = stat(filename, &statbuf);
984 if (r < 0)
986 m = errno_message(filename);
987 } else if (force_open)
989 m = NULL;
990 } else if (!S_ISREG(statbuf.st_mode))
992 static char not_reg[] = " is not a regular file (use -f to see it)";
993 m = (char *) ecalloc(strlen(filename) + sizeof(not_reg),
994 sizeof(char));
995 strcpy(m, filename);
996 strcat(m, not_reg);
998 #endif
1000 free(filename);
1001 return (m);
1005 * Return the size of a file, as cheaply as possible.
1006 * In Unix, we can stat the file.
1008 public POSITION
1009 filesize(f)
1010 int f;
1012 #if HAVE_STAT
1013 struct stat statbuf;
1015 if (fstat(f, &statbuf) >= 0)
1016 return ((POSITION) statbuf.st_size);
1017 #else
1018 #ifdef _OSK
1019 long size;
1021 if ((size = (long) _gs_size(f)) >= 0)
1022 return ((POSITION) size);
1023 #endif
1024 #endif
1025 return (seek_filesize(f));
1031 public char *
1032 shell_coption()
1034 return ("-c");