2 * Copyright (C) 1984-2021 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
39 #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
42 #define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
46 extern int force_open;
48 extern int use_lessopen;
51 extern IFILE curr_ifile;
52 extern IFILE old_ifile;
53 #if SPACES_IN_FILENAMES
54 extern char openquote;
55 extern char closequote;
59 * Remove quotes around a filename.
68 name = p = (char *) ecalloc(strlen(str)+1, sizeof(char));
69 if (*str == openquote)
74 if (*str == closequote)
76 if (str[1] != closequote)
84 char *esc = get_meta_escape();
85 int esclen = (int) strlen(esc);
88 if (esclen > 0 && strncmp(str, esc, esclen) == 0)
98 * Get the shell's escape character.
101 get_meta_escape(VOID_PARAM)
105 s = lgetenv("LESSMETAESCAPE");
112 * Get the characters which the shell considers to be "metacharacters".
115 metachars(VOID_PARAM)
117 static char *mchars = NULL;
121 mchars = lgetenv("LESSMETACHARS");
123 mchars = DEF_METACHARS;
129 * Is this a shell metacharacter?
135 return (strchr(metachars(), c) != NULL);
139 * Insert a backslash before each metacharacter in a string.
148 char *esc = get_meta_escape();
149 int esclen = (int) strlen(esc);
154 * Determine how big a string we need to allocate.
156 len = 1; /* Trailing null byte */
157 for (p = s; *p != '\0'; p++)
160 if (*p == openquote || *p == closequote)
167 * We've got a metachar, but this shell
168 * doesn't support escape chars. Use quotes.
174 * Allow space for the escape char.
184 * We can't quote a string that contains quotes.
187 len = (int) strlen(s) + 3;
190 * Allocate and construct the new string.
192 newstr = p = (char *) ecalloc(len, sizeof(char));
195 SNPRINTF3(newstr, len, "%c%s%c", openquote, s, closequote);
203 * Add the escape char.
216 * Return a pathname that points to a specified file in a specified directory.
217 * Return NULL if the file does not exist in the directory.
220 dirfile(dirname, filename, must_exist)
229 if (dirname == NULL || *dirname == '\0')
232 * Construct the full pathname.
234 len = (int) (strlen(dirname) + strlen(filename) + 2);
235 pathname = (char *) calloc(len, sizeof(char));
236 if (pathname == NULL)
238 SNPRINTF3(pathname, len, "%s%s%s", dirname, PATHNAME_SEP, filename);
242 * Make sure the file exists.
244 f = open(pathname, OPEN_READ);
258 * Return the full pathname of the given file in the "home directory".
266 /* Try $HOME/filename. */
267 pathname = dirfile(lgetenv("HOME"), filename, 1);
268 if (pathname != NULL)
271 /* Try $INIT/filename. */
272 pathname = dirfile(lgetenv("INIT"), filename, 1);
273 if (pathname != NULL)
276 #if MSDOS_COMPILER || OS2
277 /* Look for the file anywhere on search path. */
278 pathname = (char *) ecalloc(_MAX_PATH, sizeof(char));
279 #if MSDOS_COMPILER==DJGPPC
281 char *res = searchpath(filename);
285 strcpy(pathname, res);
288 _searchenv(filename, "PATH", pathname);
290 if (*pathname != '\0')
298 * Expand a string, substituting any "%" with the current filename,
299 * and any "#" with the previous filename.
300 * But a string of N "%"s is just replaced with N-1 "%"s.
301 * Likewise for a string of N "#"s.
302 * {{ This is a lot of work just to support % and #. }}
313 #define fchar_ifile(c) \
314 ((c) == '%' ? curr_ifile : \
315 (c) == '#' ? old_ifile : NULL_IFILE)
318 * Make one pass to see how big a buffer we
319 * need to allocate for the expanded string.
322 for (fr = s; *fr != '\0'; fr++)
328 if (fr > s && fr[-1] == *fr)
331 * Second (or later) char in a string
332 * of identical chars. Treat as normal.
335 } else if (fr[1] != *fr)
338 * Single char (not repeated). Treat specially.
340 ifile = fchar_ifile(*fr);
341 if (ifile == NULL_IFILE)
344 n += (int) strlen(get_filename(ifile));
347 * Else it is the first char in a string of
348 * identical chars. Just discard it.
357 e = (char *) ecalloc(n+1, sizeof(char));
360 * Now copy the string, expanding any "%" or "#".
363 for (fr = s; *fr != '\0'; fr++)
369 if (fr > s && fr[-1] == *fr)
372 } else if (fr[1] != *fr)
374 ifile = fchar_ifile(*fr);
375 if (ifile == NULL_IFILE)
379 strcpy(to, get_filename(ifile));
394 #if TAB_COMPLETE_FILENAME
397 * Return a blank-separated list of filenames which "complete"
410 * Complete the filename "s" by globbing "s*".
412 #if MSDOS_COMPILER && (MSDOS_COMPILER == MSOFTC || MSDOS_COMPILER == BORLANDC)
414 * But in DOS, we have to glob "s*.*".
415 * But if the final component of the filename already has
416 * a dot in it, just do "s*".
417 * (Thus, "FILE" is globbed as "FILE*.*",
418 * but "FILE.A" is globbed as "FILE.A*").
423 for (slash = s+strlen(s)-1; slash > s; slash--)
424 if (*slash == *PATHNAME_SEP || *slash == '/')
426 len = (int) strlen(s) + 4;
427 fpat = (char *) ecalloc(len, sizeof(char));
428 if (strchr(slash, '.') == NULL)
429 SNPRINTF1(fpat, len, "%s*.*", s);
431 SNPRINTF1(fpat, len, "%s*", s);
435 int len = (int) strlen(s) + 2;
436 fpat = (char *) ecalloc(len, sizeof(char));
437 SNPRINTF1(fpat, len, "%s*", s);
441 s = shell_unquote(qs);
442 if (strcmp(s,fpat) == 0)
445 * The filename didn't expand.
457 * Try to determine if a file is "binary".
458 * 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));
478 for (p = data; p < edata; )
480 if (utf_mode && !is_utf8_well_formed(p, edata-data))
483 utf_skip_to_lead(&p, edata);
486 LWCHAR c = step_char(&p, +1, edata);
487 struct ansi_state *pansi;
488 if (ctldisp == OPT_ONPLUS && (pansi = ansi_start(c)) != NULL)
490 skip_ansi(pansi, &p, edata);
492 } else if (binary_char(c))
497 * Call it a binary file if there are more than 5 binary characters
498 * in the first 256 bytes of the file.
500 return (bin_count > 5);
504 * Try to determine the size of a file by seeking to the end.
512 spos = lseek(f, (off_t)0, SEEK_END);
513 if (spos == BAD_LSEEK)
514 return (NULL_POSITION);
515 return ((POSITION) spos);
520 * Read a string from a file.
521 * Return a pointer to the string in memory.
533 * Make a guess about how many chars in the string
534 * and allocate a buffer to hold it.
537 buf = (char *) ecalloc(len, sizeof(char));
540 if ((ch = getc(fd)) == '\n' || ch == EOF)
542 if (p - buf >= len-1)
545 * The string is too big to fit in the buffer we have.
546 * Allocate a new buffer, twice as big.
550 p = (char *) ecalloc(len, sizeof(char));
554 p = buf + strlen(buf);
563 * Execute a shell command.
564 * Return a pointer to a pipe connected to the shell command's standard output.
575 shell = lgetenv("SHELL");
576 if (!isnullenv(shell))
582 * Read the output of <$SHELL -c cmd>.
583 * Escape any metacharacters in the command.
585 esccmd = shell_quote(cmd);
588 fd = popen(cmd, "r");
591 int len = (int) (strlen(shell) + strlen(esccmd) + 5);
592 scmd = (char *) ecalloc(len, sizeof(char));
593 SNPRINTF3(scmd, len, "%s %s %s", shell, shell_coption(), esccmd);
595 fd = popen(scmd, "r");
601 fd = popen(cmd, "r");
604 * Redirection in `popen' might have messed with the
605 * standard devices. Restore binary input mode.
611 #endif /* HAVE_POPEN */
615 * Expand a filename, doing any system-specific metacharacter substitutions.
623 filename = fexpand(filename);
627 #ifdef DECL_GLOB_LIST
630 * The globbing function returns a list of names.
637 GLOB_LIST(filename, list);
638 if (GLOB_LIST_FAILED(list))
642 length = 1; /* Room for trailing null byte */
643 for (SCAN_GLOB_LIST(list, p))
645 INIT_GLOB_LIST(list, p);
646 qfilename = shell_quote(p);
647 if (qfilename != NULL)
649 length += strlen(qfilename) + 1;
653 gfilename = (char *) ecalloc(length, sizeof(char));
654 for (SCAN_GLOB_LIST(list, p))
656 INIT_GLOB_LIST(list, p);
657 qfilename = shell_quote(p);
658 if (qfilename != NULL)
660 sprintf(gfilename + strlen(gfilename), "%s ", qfilename);
665 * Overwrite the final trailing space with a null terminator.
668 GLOB_LIST_DONE(list);
671 #ifdef DECL_GLOB_NAME
674 * The globbing function returns a single name, and
675 * is called multiple times to walk thru all names.
682 DECL_GLOB_NAME(fnd,drive,dir,fname,ext,handle)
684 GLOB_FIRST_NAME(filename, &fnd, handle);
685 if (GLOB_FIRST_FAILED(handle))
690 _splitpath(filename, drive, dir, fname, ext);
692 gfilename = (char *) ecalloc(len, sizeof(char));
695 n = (int) (strlen(drive) + strlen(dir) + strlen(fnd.GLOB_NAME) + 1);
696 pfilename = (char *) ecalloc(n, sizeof(char));
697 SNPRINTF3(pfilename, n, "%s%s%s", drive, dir, fnd.GLOB_NAME);
698 qfilename = shell_quote(pfilename);
700 if (qfilename != NULL)
702 n = (int) strlen(qfilename);
703 while (p - gfilename + n + 2 >= len)
706 * No room in current buffer.
707 * Allocate a bigger one.
711 p = (char *) ecalloc(len, sizeof(char));
712 strcpy(p, gfilename);
715 p = gfilename + strlen(gfilename);
717 strcpy(p, qfilename);
722 } while (GLOB_NEXT_NAME(handle, &fnd) == 0);
725 * Overwrite the final trailing space with a null terminator.
728 GLOB_NAME_DONE(handle);
734 * We get the shell to glob the filename for us by passing
735 * an "echo" command to the shell and reading its output.
744 esc = get_meta_escape();
745 if (strlen(esc) == 0)
747 esc = shell_quote(esc);
752 lessecho = lgetenv("LESSECHO");
753 if (isnullenv(lessecho))
754 lessecho = "lessecho";
756 * Invoke lessecho, and read its output (a globbed list of filenames).
758 len = (int) (strlen(lessecho) + strlen(filename) + (7*strlen(metachars())) + 24);
759 cmd = (char *) ecalloc(len, sizeof(char));
760 SNPRINTF4(cmd, len, "%s -p0x%x -d0x%x -e%s ", lessecho, openquote, closequote, esc);
762 for (s = metachars(); *s != '\0'; s++)
763 sprintf(cmd + strlen(cmd), "-n0x%x ", *s);
764 sprintf(cmd + strlen(cmd), "-- %s", filename);
770 * Cannot create the pipe.
771 * Just return the original (fexpanded) filename.
775 gfilename = readfd(fd);
777 if (*gfilename == '\0')
785 * No globbing functions at all. Just use the fexpanded filename.
787 gfilename = save(filename);
796 * Return canonical pathname.
803 char rpath[PATH_MAX];
804 if (realpath(path, rpath) != NULL)
805 return (save(rpath));
812 * Return number of %s escapes in a string.
813 * Return a large number if there are any other % escapes besides %s.
821 while (*lessopen != '\0')
823 if (*lessopen == '%')
825 if (lessopen[1] == '%')
827 else if (lessopen[1] == 's')
839 * See if we should open a "replacement file"
840 * instead of the file we're about to open.
843 open_altfile(filename, pf, pfd)
860 if (!use_lessopen || secure)
863 if ((lessopen = lgetenv("LESSOPEN")) == NULL)
865 while (*lessopen == '|')
868 * If LESSOPEN starts with a |, it indicates
869 * a "pipe preprocessor".
872 error("LESSOPEN pipe is not supported", NULL_PARG);
879 if (*lessopen == '-')
882 * Lessopen preprocessor will accept "-" as a filename.
887 if (strcmp(filename, "-") == 0)
890 if (num_pct_s(lessopen) != 1)
892 error("LESSOPEN ignored: must contain exactly one %%s", NULL_PARG);
896 qfilename = shell_quote(filename);
897 len = (int) (strlen(lessopen) + strlen(qfilename) + 2);
898 cmd = (char *) ecalloc(len, sizeof(char));
899 SNPRINTF1(cmd, len, lessopen, qfilename);
906 * Cannot create the pipe.
917 * The alt file is a pipe. Read one char
918 * to see if the pipe will produce any data.
919 * If it does, push the char back on the pipe.
923 if (read(f, &c, 1) != 1)
927 * If more than 1 pipe char was specified,
928 * the exit status tells whether the file itself
929 * is empty, or if there is no alt file.
930 * If only one pipe char, just assume no alt file.
932 int status = pclose(fd);
933 if (returnfd > 1 && status == 0) {
937 return (save(FAKE_EMPTYFILE));
942 /* Alt pipe contains data, so use it. */
949 /* The alt file is a regular file. Read its name from LESSOPEN. */
955 * Pipe is empty. This means there is no alt file.
961 #endif /* HAVE_POPEN */
965 * Close a replacement file.
968 close_altfile(altfilename, filename)
981 if ((lessclose = lgetenv("LESSCLOSE")) == NULL)
983 if (num_pct_s(lessclose) > 2)
985 error("LESSCLOSE ignored; must contain no more than 2 %%s", NULL_PARG);
988 len = (int) (strlen(lessclose) + strlen(filename) + strlen(altfilename) + 2);
989 cmd = (char *) ecalloc(len, sizeof(char));
990 SNPRINTF2(cmd, len, lessclose, filename, altfilename);
999 * Is the specified file a directory?
1010 struct stat statbuf;
1012 r = stat(filename, &statbuf);
1013 isdir = (r >= 0 && S_ISDIR(statbuf.st_mode));
1020 f = open(filename, S_IREAD | S_IFDIR);
1031 * Returns NULL if the file can be opened and
1032 * is an ordinary file, otherwise an error message
1033 * (if it cannot be opened or is a directory, etc.)
1041 if (!force_open && is_dir(filename))
1043 static char is_a_dir[] = " is a directory";
1045 m = (char *) ecalloc(strlen(filename) + sizeof(is_a_dir),
1047 strcpy(m, filename);
1048 strcat(m, is_a_dir);
1053 struct stat statbuf;
1055 r = stat(filename, &statbuf);
1058 m = errno_message(filename);
1059 } else if (force_open)
1062 } else if (!S_ISREG(statbuf.st_mode))
1064 static char not_reg[] = " is not a regular file (use -f to see it)";
1065 m = (char *) ecalloc(strlen(filename) + sizeof(not_reg),
1067 strcpy(m, filename);
1076 * Return the size of a file, as cheaply as possible.
1077 * In Unix, we can stat the file.
1084 struct stat statbuf;
1086 if (fstat(f, &statbuf) >= 0)
1087 return ((POSITION) statbuf.st_size);
1092 if ((size = (long) _gs_size(f)) >= 0)
1093 return ((POSITION) size);
1096 return (seek_filesize(f));
1103 shell_coption(VOID_PARAM)
1109 * Return last component of a pathname.
1112 last_component(name)
1117 for (slash = name + strlen(name); slash > name; )
1120 if (*slash == *PATHNAME_SEP || *slash == '/')