2 * Copyright (C) 1984-2015 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, see the README file.
12 * Routines to mess around with filenames (and files).
13 * Much of this is very OS dependent.
20 #if MSDOS_COMPILER==WIN32C && !defined(_MSC_VER)
23 #if MSDOS_COMPILER==DJGPPC
26 #define _MAX_PATH PATH_MAX
42 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
45 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
50 extern int force_open;
52 extern int use_lessopen;
55 extern IFILE curr_ifile;
56 extern IFILE old_ifile;
57 #if SPACES_IN_FILENAMES
58 extern char openquote;
59 extern char closequote;
63 * Remove quotes around a filename.
66 shell_unquote(char *str)
71 name = p = (char *) ecalloc(strlen(str)+1, sizeof(char));
72 if (*str == openquote)
77 if (*str == closequote)
79 if (str[1] != closequote)
87 char *esc = get_meta_escape();
88 int esclen = (int) strlen(esc);
91 if (esclen > 0 && strncmp(str, esc, esclen) == 0)
101 * Get the shell's escape character.
104 get_meta_escape(void)
108 s = lgetenv("LESSMETAESCAPE");
115 * Get the characters which the shell considers to be "metacharacters".
120 static char *mchars = NULL;
124 mchars = lgetenv("LESSMETACHARS");
126 mchars = DEF_METACHARS;
132 * Is this a shell metacharacter?
137 return (strchr(metachars(), c) != NULL);
141 * Insert a backslash before each metacharacter in a string.
149 char *esc = get_meta_escape();
150 int esclen = (int) strlen(esc);
155 * Determine how big a string we need to allocate.
157 len = 1; /* Trailing null byte */
158 for (p = s; *p != '\0'; p++)
161 if (*p == openquote || *p == closequote)
168 * We've got a metachar, but this shell
169 * doesn't support escape chars. Use quotes.
175 * Allow space for the escape char.
185 * We can't quote a string that contains quotes.
188 len = (int) strlen(s) + 3;
191 * Allocate and construct the new string.
193 newstr = p = (char *) ecalloc(len, sizeof(char));
196 SNPRINTF3(newstr, len, "%c%s%c", openquote, s, closequote);
204 * Add the escape char.
217 * Return a pathname that points to a specified file in a specified directory.
218 * Return NULL if the file does not exist in the directory.
221 dirfile(char *dirname, char *filename)
228 if (dirname == NULL || *dirname == '\0')
231 * Construct the full pathname.
233 len = (int) (strlen(dirname) + strlen(filename) + 2);
234 pathname = (char *) calloc(len, sizeof(char));
235 if (pathname == NULL)
237 SNPRINTF3(pathname, len, "%s%s%s", dirname, PATHNAME_SEP, filename);
239 * Make sure the file exists.
241 qpathname = shell_unquote(pathname);
242 f = open(qpathname, OPEN_READ);
256 * Return the full pathname of the given file in the "home directory".
259 homefile(char *filename)
264 * Try $HOME/filename.
266 pathname = dirfile(lgetenv("HOME"), filename);
267 if (pathname != NULL)
271 * Try $INIT/filename.
273 pathname = dirfile(lgetenv("INIT"), filename);
274 if (pathname != NULL)
277 #if MSDOS_COMPILER || OS2
279 * Look for the file anywhere on search path.
281 pathname = (char *) calloc(_MAX_PATH, sizeof(char));
282 #if MSDOS_COMPILER==DJGPPC
284 char *res = searchpath(filename);
288 strcpy(pathname, res);
291 _searchenv(filename, "PATH", pathname);
293 if (*pathname != '\0')
301 * Expand a string, substituting any "%" with the current filename,
302 * and any "#" with the previous filename.
303 * But a string of N "%"s is just replaced with N-1 "%"s.
304 * Likewise for a string of N "#"s.
305 * {{ This is a lot of work just to support % and #. }}
315 #define fchar_ifile(c) \
316 ((c) == '%' ? curr_ifile : \
317 (c) == '#' ? old_ifile : NULL_IFILE)
320 * Make one pass to see how big a buffer we
321 * need to allocate for the expanded string.
324 for (fr = s; *fr != '\0'; fr++)
330 if (fr > s && fr[-1] == *fr)
333 * Second (or later) char in a string
334 * of identical chars. Treat as normal.
337 } else if (fr[1] != *fr)
340 * Single char (not repeated). Treat specially.
342 ifile = fchar_ifile(*fr);
343 if (ifile == NULL_IFILE)
346 n += (int) strlen(get_filename(ifile));
349 * Else it is the first char in a string of
350 * identical chars. Just discard it.
359 e = (char *) ecalloc(n+1, sizeof(char));
362 * Now copy the string, expanding any "%" or "#".
365 for (fr = s; *fr != '\0'; fr++)
371 if (fr > s && fr[-1] == *fr)
374 } else if (fr[1] != *fr)
376 ifile = fchar_ifile(*fr);
377 if (ifile == NULL_IFILE)
381 strcpy(to, get_filename(ifile));
396 #if TAB_COMPLETE_FILENAME
399 * Return a blank-separated list of filenames which "complete"
411 * Complete the filename "s" by globbing "s*".
413 #if MSDOS_COMPILER && (MSDOS_COMPILER == MSOFTC || MSDOS_COMPILER == BORLANDC)
415 * But in DOS, we have to glob "s*.*".
416 * But if the final component of the filename already has
417 * a dot in it, just do "s*".
418 * (Thus, "FILE" is globbed as "FILE*.*",
419 * but "FILE.A" is globbed as "FILE.A*").
424 for (slash = s+strlen(s)-1; slash > s; slash--)
425 if (*slash == *PATHNAME_SEP || *slash == '/')
427 len = (int) strlen(s) + 4;
428 fpat = (char *) ecalloc(len, sizeof(char));
429 if (strchr(slash, '.') == NULL)
430 SNPRINTF1(fpat, len, "%s*.*", s);
432 SNPRINTF1(fpat, len, "%s*", s);
436 int len = (int) strlen(s) + 2;
437 fpat = (char *) ecalloc(len, sizeof(char));
438 SNPRINTF1(fpat, len, "%s*", s);
442 s = shell_unquote(qs);
443 if (strcmp(s,fpat) == 0)
446 * The filename didn't expand.
458 * Try to determine if a file is "binary".
459 * This is just a guess, and we need not try too hard to make it accurate.
472 if (lseek(f, (off_t)0, SEEK_SET) == BAD_LSEEK)
474 n = read(f, data, sizeof(data));
479 bin_count = utf_bin_count(data, n);
483 for (p = data; p < pend; )
485 LWCHAR c = step_char(&p, +1, pend);
486 if (ctldisp == OPT_ONPLUS && IS_CSI_START(c))
489 c = step_char(&p, +1, pend);
490 } while (p < pend && is_ansi_middle(c));
491 } else if (binary_char(c))
496 * Call it a binary file if there are more than 5 binary characters
497 * in the first 256 bytes of the file.
499 return (bin_count > 5);
503 * Try to determine the size of a file by seeking to the end.
510 spos = lseek(f, (off_t)0, SEEK_END);
511 if (spos == BAD_LSEEK)
512 return (NULL_POSITION);
513 return ((POSITION) spos);
517 * Read a string from a file.
518 * Return a pointer to the string in memory.
529 * Make a guess about how many chars in the string
530 * and allocate a buffer to hold it.
533 buf = (char *) ecalloc(len, sizeof(char));
536 if ((ch = getc(fd)) == '\n' || ch == EOF)
538 if (p - buf >= len-1)
541 * The string is too big to fit in the buffer we have.
542 * Allocate a new buffer, twice as big.
546 p = (char *) ecalloc(len, sizeof(char));
550 p = buf + strlen(buf);
565 * Execute a shell command.
566 * Return a pointer to a pipe connected to the shell command's standard output.
576 shell = lgetenv("SHELL");
577 if (shell != NULL && *shell != '\0')
583 * Read the output of <$SHELL -c cmd>.
584 * Escape any metacharacters in the command.
586 esccmd = shell_quote(cmd);
589 fd = popen(cmd, "r");
592 int len = (int) (strlen(shell) + strlen(esccmd) + 5);
593 scmd = (char *) ecalloc(len, sizeof(char));
594 SNPRINTF3(scmd, len, "%s %s %s", shell, shell_coption(), esccmd);
596 fd = popen(scmd, "r");
602 fd = popen(cmd, "r");
605 * Redirection in `popen' might have messed with the
606 * standard devices. Restore binary input mode.
612 #endif /* HAVE_POPEN */
616 * Expand a filename, doing any system-specific metacharacter substitutions.
619 lglob(char *filename)
624 ofilename = fexpand(filename);
627 filename = shell_unquote(ofilename);
629 #ifdef DECL_GLOB_LIST
632 * The globbing function returns a list of names.
639 GLOB_LIST(filename, list);
640 if (GLOB_LIST_FAILED(list))
645 length = 1; /* Room for trailing null byte */
646 for (SCAN_GLOB_LIST(list, p))
648 INIT_GLOB_LIST(list, p);
649 qfilename = shell_quote(p);
650 if (qfilename != NULL)
652 length += strlen(qfilename) + 1;
656 gfilename = (char *) ecalloc(length, sizeof(char));
657 for (SCAN_GLOB_LIST(list, p))
659 INIT_GLOB_LIST(list, p);
660 qfilename = shell_quote(p);
661 if (qfilename != NULL)
663 sprintf(gfilename + strlen(gfilename), "%s ", qfilename);
668 * Overwrite the final trailing space with a null terminator.
671 GLOB_LIST_DONE(list);
674 #ifdef DECL_GLOB_NAME
677 * The globbing function returns a single name, and
678 * is called multiple times to walk thru all names.
685 DECL_GLOB_NAME(fnd,drive,dir,fname,ext,handle)
687 GLOB_FIRST_NAME(filename, &fnd, handle);
688 if (GLOB_FIRST_FAILED(handle))
694 _splitpath(filename, drive, dir, fname, ext);
696 gfilename = (char *) ecalloc(len, sizeof(char));
699 n = (int) (strlen(drive) + strlen(dir) + strlen(fnd.GLOB_NAME) + 1);
700 pathname = (char *) ecalloc(n, sizeof(char));
701 SNPRINTF3(pathname, n, "%s%s%s", drive, dir, fnd.GLOB_NAME);
702 qpathname = shell_quote(pathname);
704 if (qpathname != NULL)
706 n = (int) strlen(qpathname);
707 while (p - gfilename + n + 2 >= len)
710 * No room in current buffer.
711 * Allocate a bigger one.
715 p = (char *) ecalloc(len, sizeof(char));
716 strcpy(p, gfilename);
719 p = gfilename + strlen(gfilename);
721 strcpy(p, qpathname);
726 } while (GLOB_NEXT_NAME(handle, &fnd) == 0);
729 * Overwrite the final trailing space with a null terminator.
732 GLOB_NAME_DONE(handle);
738 * We get the shell to glob the filename for us by passing
739 * an "echo" command to the shell and reading its output.
748 esc = get_meta_escape();
749 if (strlen(esc) == 0)
751 esc = shell_quote(esc);
757 lessecho = lgetenv("LESSECHO");
758 if (lessecho == NULL || *lessecho == '\0')
759 lessecho = "lessecho";
761 * Invoke lessecho, and read its output (a globbed list of filenames).
763 len = (int) (strlen(lessecho) + strlen(ofilename) + (7*strlen(metachars())) + 24);
764 cmd = (char *) ecalloc(len, sizeof(char));
765 SNPRINTF4(cmd, len, "%s -p0x%x -d0x%x -e%s ", lessecho, openquote, closequote, esc);
767 for (s = metachars(); *s != '\0'; s++)
768 sprintf(cmd + strlen(cmd), "-n0x%x ", *s);
769 sprintf(cmd + strlen(cmd), "-- %s", ofilename);
775 * Cannot create the pipe.
776 * Just return the original (fexpanded) filename.
781 gfilename = readfd(fd);
783 if (*gfilename == '\0')
792 * No globbing functions at all. Just use the fexpanded filename.
794 gfilename = save(filename);
804 * Return number of %s escapes in a string.
805 * Return a large number if there are any other % escapes besides %s.
808 num_pct_s(char *lessopen)
812 while (*lessopen != '\0')
814 if (*lessopen == '%')
816 if (lessopen[1] == '%')
818 else if (lessopen[1] == 's')
829 * See if we should open a "replacement file"
830 * instead of the file we're about to open.
833 open_altfile(char *filename, int *pf, void **pfd)
846 if (!use_lessopen || secure)
849 if ((lessopen = lgetenv("LESSOPEN")) == NULL)
851 while (*lessopen == '|')
854 * If LESSOPEN starts with a |, it indicates
855 * a "pipe preprocessor".
858 error("LESSOPEN pipe is not supported", NULL_PARG);
865 if (*lessopen == '-') {
867 * Lessopen preprocessor will accept "-" as a filename.
871 if (strcmp(filename, "-") == 0)
874 if (num_pct_s(lessopen) > 1)
876 error("Invalid LESSOPEN variable", NULL_PARG);
880 len = (int) (strlen(lessopen) + strlen(filename) + 2);
881 cmd = (char *) ecalloc(len, sizeof(char));
882 SNPRINTF1(cmd, len, lessopen, filename);
888 * Cannot create the pipe.
899 * Read one char to see if the pipe will produce any data.
900 * If it does, push the char back on the pipe.
904 if (read(f, &c, 1) != 1)
908 * If more than 1 pipe char was specified,
909 * the exit status tells whether the file itself
910 * is empty, or if there is no alt file.
911 * If only one pipe char, just assume no alt file.
913 int status = pclose(fd);
914 if (returnfd > 1 && status == 0) {
917 return (save(FAKE_EMPTYFILE));
931 * Pipe is empty. This means there is no alt file.
935 #endif /* HAVE_POPEN */
939 * Close a replacement file.
942 close_altfile(char *altfilename, char *filename, void *pipefd)
956 * The pclose function of OS/2 emx sometimes fails.
957 * Send SIGINT to the piped process before closing it.
959 kill(((FILE*)pipefd)->_pid, SIGINT);
961 pclose((FILE*) pipefd);
963 if ((lessclose = lgetenv("LESSCLOSE")) == NULL)
965 if (num_pct_s(lessclose) > 2)
967 error("Invalid LESSCLOSE variable", NULL_PARG);
970 len = (int) (strlen(lessclose) + strlen(filename) + strlen(altfilename) + 2);
971 cmd = (char *) ecalloc(len, sizeof(char));
972 SNPRINTF2(cmd, len, lessclose, filename, altfilename);
981 * Is the specified file a directory?
984 is_dir(char *filename)
988 filename = shell_unquote(filename);
994 r = stat(filename, &statbuf);
995 isdir = (r >= 0 && S_ISDIR(statbuf.st_mode));
1002 f = open(filename, S_IREAD | S_IFDIR);
1014 * Returns NULL if the file can be opened and
1015 * is an ordinary file, otherwise an error message
1016 * (if it cannot be opened or is a directory, etc.)
1019 bad_file(char *filename)
1023 filename = shell_unquote(filename);
1024 if (!force_open && is_dir(filename))
1026 static char is_a_dir[] = " is a directory";
1028 m = (char *) ecalloc(strlen(filename) + sizeof(is_a_dir),
1030 strcpy(m, filename);
1031 strcat(m, is_a_dir);
1036 struct stat statbuf;
1038 r = stat(filename, &statbuf);
1041 m = errno_message(filename);
1042 } else if (force_open)
1045 } else if (!S_ISREG(statbuf.st_mode))
1047 static char not_reg[] = " is not a regular file (use -f to see it)";
1048 m = (char *) ecalloc(strlen(filename) + sizeof(not_reg),
1050 strcpy(m, filename);
1060 * Return the size of a file, as cheaply as possible.
1061 * In Unix, we can stat the file.
1067 struct stat statbuf;
1069 if (fstat(f, &statbuf) >= 0)
1070 return ((POSITION) statbuf.st_size);
1075 if ((size = (long) _gs_size(f)) >= 0)
1076 return ((POSITION) size);
1079 return (seek_filesize(f));
1092 * Return last component of a pathname.
1095 last_component(char *name)
1099 for (slash = name + strlen(name); slash > name; )
1102 if (*slash == *PATHNAME_SEP || *slash == '/')