AMD64 - Fix format conversions and other warnings.
[dragonfly.git] / contrib / less / filename.c
blob72e97971104f48ec33bda3543dfeacf3c52d061d
1 /*
2 * Copyright (C) 1984-2008 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 int ctldisp;
55 extern int utf_mode;
56 extern IFILE curr_ifile;
57 extern IFILE old_ifile;
58 #if SPACES_IN_FILENAMES
59 extern char openquote;
60 extern char closequote;
61 #endif
64 * Remove quotes around a filename.
66 public char *
67 shell_unquote(str)
68 char *str;
70 char *name;
71 char *p;
73 name = p = (char *) ecalloc(strlen(str)+1, sizeof(char));
74 if (*str == openquote)
76 str++;
77 while (*str != '\0')
79 if (*str == closequote)
81 if (str[1] != closequote)
82 break;
83 str++;
85 *p++ = *str++;
87 } else
89 char *esc = get_meta_escape();
90 int esclen = strlen(esc);
91 while (*str != '\0')
93 if (esclen > 0 && strncmp(str, esc, esclen) == 0)
94 str += esclen;
95 *p++ = *str++;
98 *p = '\0';
99 return (name);
103 * Get the shell's escape character.
105 public char *
106 get_meta_escape()
108 char *s;
110 s = lgetenv("LESSMETAESCAPE");
111 if (s == NULL)
112 s = DEF_METAESCAPE;
113 return (s);
117 * Get the characters which the shell considers to be "metacharacters".
119 static char *
120 metachars()
122 static char *mchars = NULL;
124 if (mchars == NULL)
126 mchars = lgetenv("LESSMETACHARS");
127 if (mchars == NULL)
128 mchars = DEF_METACHARS;
130 return (mchars);
134 * Is this a shell metacharacter?
136 static int
137 metachar(c)
138 char c;
140 return (strchr(metachars(), c) != NULL);
144 * Insert a backslash before each metacharacter in a string.
146 public char *
147 shell_quote(s)
148 char *s;
150 char *p;
151 char *newstr;
152 int len;
153 char *esc = get_meta_escape();
154 int esclen = strlen(esc);
155 int use_quotes = 0;
156 int have_quotes = 0;
159 * Determine how big a string we need to allocate.
161 len = 1; /* Trailing null byte */
162 for (p = s; *p != '\0'; p++)
164 len++;
165 if (*p == openquote || *p == closequote)
166 have_quotes = 1;
167 if (metachar(*p))
169 if (esclen == 0)
172 * We've got a metachar, but this shell
173 * doesn't support escape chars. Use quotes.
175 use_quotes = 1;
176 } else
179 * Allow space for the escape char.
181 len += esclen;
185 if (use_quotes)
187 if (have_quotes)
189 * We can't quote a string that contains quotes.
191 return (NULL);
192 len = strlen(s) + 3;
195 * Allocate and construct the new string.
197 newstr = p = (char *) ecalloc(len, sizeof(char));
198 if (use_quotes)
200 SNPRINTF3(newstr, len, "%c%s%c", openquote, s, closequote);
201 } else
203 while (*s != '\0')
205 if (metachar(*s))
208 * Add the escape char.
210 strcpy(p, esc);
211 p += esclen;
213 *p++ = *s++;
215 *p = '\0';
217 return (newstr);
221 * Return a pathname that points to a specified file in a specified directory.
222 * Return NULL if the file does not exist in the directory.
224 static char *
225 dirfile(dirname, filename)
226 char *dirname;
227 char *filename;
229 char *pathname;
230 char *qpathname;
231 int len;
232 int f;
234 if (dirname == NULL || *dirname == '\0')
235 return (NULL);
237 * Construct the full pathname.
239 len= strlen(dirname) + strlen(filename) + 2;
240 pathname = (char *) calloc(len, sizeof(char));
241 if (pathname == NULL)
242 return (NULL);
243 SNPRINTF3(pathname, len, "%s%s%s", dirname, PATHNAME_SEP, filename);
245 * Make sure the file exists.
247 qpathname = shell_unquote(pathname);
248 f = open(qpathname, OPEN_READ);
249 if (f < 0)
251 free(pathname);
252 pathname = NULL;
253 } else
255 close(f);
257 free(qpathname);
258 return (pathname);
262 * Return the full pathname of the given file in the "home directory".
264 public char *
265 homefile(filename)
266 char *filename;
268 register char *pathname;
271 * Try $HOME/filename.
273 pathname = dirfile(lgetenv("HOME"), filename);
274 if (pathname != NULL)
275 return (pathname);
276 #if OS2
278 * Try $INIT/filename.
280 pathname = dirfile(lgetenv("INIT"), filename);
281 if (pathname != NULL)
282 return (pathname);
283 #endif
284 #if MSDOS_COMPILER || OS2
286 * Look for the file anywhere on search path.
288 pathname = (char *) calloc(_MAX_PATH, sizeof(char));
289 #if MSDOS_COMPILER==DJGPPC
291 char *res = searchpath(filename);
292 if (res == 0)
293 *pathname = '\0';
294 else
295 strcpy(pathname, res);
297 #else
298 _searchenv(filename, "PATH", pathname);
299 #endif
300 if (*pathname != '\0')
301 return (pathname);
302 free(pathname);
303 #endif
304 return (NULL);
308 * Expand a string, substituting any "%" with the current filename,
309 * and any "#" with the previous filename.
310 * But a string of N "%"s is just replaced with N-1 "%"s.
311 * Likewise for a string of N "#"s.
312 * {{ This is a lot of work just to support % and #. }}
314 public char *
315 fexpand(s)
316 char *s;
318 register char *fr, *to;
319 register int n;
320 register char *e;
321 IFILE ifile;
323 #define fchar_ifile(c) \
324 ((c) == '%' ? curr_ifile : \
325 (c) == '#' ? old_ifile : NULL_IFILE)
328 * Make one pass to see how big a buffer we
329 * need to allocate for the expanded string.
331 n = 0;
332 for (fr = s; *fr != '\0'; fr++)
334 switch (*fr)
336 case '%':
337 case '#':
338 if (fr > s && fr[-1] == *fr)
341 * Second (or later) char in a string
342 * of identical chars. Treat as normal.
344 n++;
345 } else if (fr[1] != *fr)
348 * Single char (not repeated). Treat specially.
350 ifile = fchar_ifile(*fr);
351 if (ifile == NULL_IFILE)
352 n++;
353 else
354 n += strlen(get_filename(ifile));
357 * Else it is the first char in a string of
358 * identical chars. Just discard it.
360 break;
361 default:
362 n++;
363 break;
367 e = (char *) ecalloc(n+1, sizeof(char));
370 * Now copy the string, expanding any "%" or "#".
372 to = e;
373 for (fr = s; *fr != '\0'; fr++)
375 switch (*fr)
377 case '%':
378 case '#':
379 if (fr > s && fr[-1] == *fr)
381 *to++ = *fr;
382 } else if (fr[1] != *fr)
384 ifile = fchar_ifile(*fr);
385 if (ifile == NULL_IFILE)
386 *to++ = *fr;
387 else
389 strcpy(to, get_filename(ifile));
390 to += strlen(to);
393 break;
394 default:
395 *to++ = *fr;
396 break;
399 *to = '\0';
400 return (e);
403 #if TAB_COMPLETE_FILENAME
406 * Return a blank-separated list of filenames which "complete"
407 * the given string.
409 public char *
410 fcomplete(s)
411 char *s;
413 char *fpat;
414 char *qs;
416 if (secure)
417 return (NULL);
419 * Complete the filename "s" by globbing "s*".
421 #if MSDOS_COMPILER && (MSDOS_COMPILER == MSOFTC || MSDOS_COMPILER == BORLANDC)
423 * But in DOS, we have to glob "s*.*".
424 * But if the final component of the filename already has
425 * a dot in it, just do "s*".
426 * (Thus, "FILE" is globbed as "FILE*.*",
427 * but "FILE.A" is globbed as "FILE.A*").
430 char *slash;
431 int len;
432 for (slash = s+strlen(s)-1; slash > s; slash--)
433 if (*slash == *PATHNAME_SEP || *slash == '/')
434 break;
435 len = strlen(s) + 4;
436 fpat = (char *) ecalloc(len, sizeof(char));
437 if (strchr(slash, '.') == NULL)
438 SNPRINTF1(fpat, len, "%s*.*", s);
439 else
440 SNPRINTF1(fpat, len, "%s*", s);
442 #else
444 int len = strlen(s) + 2;
445 fpat = (char *) ecalloc(len, sizeof(char));
446 SNPRINTF1(fpat, len, "%s*", s);
448 #endif
449 qs = lglob(fpat);
450 s = shell_unquote(qs);
451 if (strcmp(s,fpat) == 0)
454 * The filename didn't expand.
456 free(qs);
457 qs = NULL;
459 free(s);
460 free(fpat);
461 return (qs);
463 #endif
466 * Try to determine if a file is "binary".
467 * This is just a guess, and we need not try too hard to make it accurate.
469 public int
470 bin_file(f)
471 int f;
473 int n;
474 int bin_count = 0;
475 char data[256];
476 char* p;
477 char* pend;
479 if (!seekable(f))
480 return (0);
481 if (lseek(f, (off_t)0, SEEK_SET) == BAD_LSEEK)
482 return (0);
483 n = read(f, data, sizeof(data));
484 pend = &data[n];
485 for (p = data; p < pend; )
487 LWCHAR c = step_char(&p, +1, pend);
488 if (ctldisp == OPT_ONPLUS && IS_CSI_START(c))
490 do {
491 c = step_char(&p, +1, pend);
492 } while (p < pend && is_ansi_middle(c));
493 } else if (binary_char(c))
494 bin_count++;
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.
506 static POSITION
507 seek_filesize(f)
508 int f;
510 off_t spos;
512 spos = lseek(f, (off_t)0, SEEK_END);
513 if (spos == BAD_LSEEK)
514 return (NULL_POSITION);
515 return ((POSITION) spos);
519 * Read a string from a file.
520 * Return a pointer to the string in memory.
522 static char *
523 readfd(fd)
524 FILE *fd;
526 int len;
527 int ch;
528 char *buf;
529 char *p;
532 * Make a guess about how many chars in the string
533 * and allocate a buffer to hold it.
535 len = 100;
536 buf = (char *) ecalloc(len, sizeof(char));
537 for (p = buf; ; p++)
539 if ((ch = getc(fd)) == '\n' || ch == EOF)
540 break;
541 if (p - buf >= len-1)
544 * The string is too big to fit in the buffer we have.
545 * Allocate a new buffer, twice as big.
547 len *= 2;
548 *p = '\0';
549 p = (char *) ecalloc(len, sizeof(char));
550 strcpy(p, buf);
551 free(buf);
552 buf = p;
553 p = buf + strlen(buf);
555 *p = ch;
557 *p = '\0';
558 return (buf);
563 #if HAVE_POPEN
565 FILE *popen();
568 * Execute a shell command.
569 * Return a pointer to a pipe connected to the shell command's standard output.
571 static FILE *
572 shellcmd(cmd)
573 char *cmd;
575 FILE *fd;
577 #if HAVE_SHELL
578 char *shell;
580 shell = lgetenv("SHELL");
581 if (shell != NULL && *shell != '\0')
583 char *scmd;
584 char *esccmd;
587 * Read the output of <$SHELL -c cmd>.
588 * Escape any metacharacters in the command.
590 esccmd = shell_quote(cmd);
591 if (esccmd == NULL)
593 fd = popen(cmd, "r");
594 } else
596 int len = strlen(shell) + strlen(esccmd) + 5;
597 scmd = (char *) ecalloc(len, sizeof(char));
598 SNPRINTF3(scmd, len, "%s %s %s", shell, shell_coption(), esccmd);
599 free(esccmd);
600 fd = popen(scmd, "r");
601 free(scmd);
603 } else
604 #endif
606 fd = popen(cmd, "r");
609 * Redirection in `popen' might have messed with the
610 * standard devices. Restore binary input mode.
612 SET_BINARY(0);
613 return (fd);
616 #endif /* HAVE_POPEN */
620 * Expand a filename, doing any system-specific metacharacter substitutions.
622 public char *
623 lglob(filename)
624 char *filename;
626 char *gfilename;
627 char *ofilename;
629 ofilename = fexpand(filename);
630 if (secure)
631 return (ofilename);
632 filename = shell_unquote(ofilename);
634 #ifdef DECL_GLOB_LIST
637 * The globbing function returns a list of names.
639 int length;
640 char *p;
641 char *qfilename;
642 DECL_GLOB_LIST(list)
644 GLOB_LIST(filename, list);
645 if (GLOB_LIST_FAILED(list))
647 free(filename);
648 return (ofilename);
650 length = 1; /* Room for trailing null byte */
651 for (SCAN_GLOB_LIST(list, p))
653 INIT_GLOB_LIST(list, p);
654 qfilename = shell_quote(p);
655 if (qfilename != NULL)
657 length += strlen(qfilename) + 1;
658 free(qfilename);
661 gfilename = (char *) ecalloc(length, sizeof(char));
662 for (SCAN_GLOB_LIST(list, p))
664 INIT_GLOB_LIST(list, p);
665 qfilename = shell_quote(p);
666 if (qfilename != NULL)
668 sprintf(gfilename + strlen(gfilename), "%s ", qfilename);
669 free(qfilename);
673 * Overwrite the final trailing space with a null terminator.
675 *--p = '\0';
676 GLOB_LIST_DONE(list);
678 #else
679 #ifdef DECL_GLOB_NAME
682 * The globbing function returns a single name, and
683 * is called multiple times to walk thru all names.
685 register char *p;
686 register int len;
687 register int n;
688 char *pathname;
689 char *qpathname;
690 DECL_GLOB_NAME(fnd,drive,dir,fname,ext,handle)
692 GLOB_FIRST_NAME(filename, &fnd, handle);
693 if (GLOB_FIRST_FAILED(handle))
695 free(filename);
696 return (ofilename);
699 _splitpath(filename, drive, dir, fname, ext);
700 len = 100;
701 gfilename = (char *) ecalloc(len, sizeof(char));
702 p = gfilename;
703 do {
704 n = strlen(drive) + strlen(dir) + strlen(fnd.GLOB_NAME) + 1;
705 pathname = (char *) ecalloc(n, sizeof(char));
706 SNPRINTF3(pathname, n, "%s%s%s", drive, dir, fnd.GLOB_NAME);
707 qpathname = shell_quote(pathname);
708 free(pathname);
709 if (qpathname != NULL)
711 n = strlen(qpathname);
712 while (p - gfilename + n + 2 >= len)
715 * No room in current buffer.
716 * Allocate a bigger one.
718 len *= 2;
719 *p = '\0';
720 p = (char *) ecalloc(len, sizeof(char));
721 strcpy(p, gfilename);
722 free(gfilename);
723 gfilename = p;
724 p = gfilename + strlen(gfilename);
726 strcpy(p, qpathname);
727 free(qpathname);
728 p += n;
729 *p++ = ' ';
731 } while (GLOB_NEXT_NAME(handle, &fnd) == 0);
734 * Overwrite the final trailing space with a null terminator.
736 *--p = '\0';
737 GLOB_NAME_DONE(handle);
739 #else
740 #if HAVE_POPEN
743 * We get the shell to glob the filename for us by passing
744 * an "echo" command to the shell and reading its output.
746 FILE *fd;
747 char *s;
748 char *lessecho;
749 char *cmd;
750 char *esc;
751 int len;
753 esc = get_meta_escape();
754 if (strlen(esc) == 0)
755 esc = "-";
756 esc = shell_quote(esc);
757 if (esc == NULL)
759 free(filename);
760 return (ofilename);
762 lessecho = lgetenv("LESSECHO");
763 if (lessecho == NULL || *lessecho == '\0')
764 lessecho = "lessecho";
766 * Invoke lessecho, and read its output (a globbed list of filenames).
768 len = strlen(lessecho) + strlen(ofilename) + (7*strlen(metachars())) + 24;
769 cmd = (char *) ecalloc(len, sizeof(char));
770 SNPRINTF4(cmd, len, "%s -p0x%x -d0x%x -e%s ", lessecho, openquote, closequote, esc);
771 free(esc);
772 for (s = metachars(); *s != '\0'; s++)
773 sprintf(cmd + strlen(cmd), "-n0x%x ", *s);
774 sprintf(cmd + strlen(cmd), "-- %s", ofilename);
775 fd = shellcmd(cmd);
776 free(cmd);
777 if (fd == NULL)
780 * Cannot create the pipe.
781 * Just return the original (fexpanded) filename.
783 free(filename);
784 return (ofilename);
786 gfilename = readfd(fd);
787 pclose(fd);
788 if (*gfilename == '\0')
790 free(gfilename);
791 free(filename);
792 return (ofilename);
795 #else
797 * No globbing functions at all. Just use the fexpanded filename.
799 gfilename = save(filename);
800 #endif
801 #endif
802 #endif
803 free(filename);
804 free(ofilename);
805 return (gfilename);
809 * See if we should open a "replacement file"
810 * instead of the file we're about to open.
812 public char *
813 open_altfile(filename, pf, pfd)
814 char *filename;
815 int *pf;
816 void **pfd;
818 #if !HAVE_POPEN
819 return (NULL);
820 #else
821 char *lessopen;
822 char *cmd;
823 int len;
824 FILE *fd;
825 #if HAVE_FILENO
826 int returnfd = 0;
827 #endif
829 if (!use_lessopen || secure)
830 return (NULL);
831 ch_ungetchar(-1);
832 if ((lessopen = lgetenv("LESSOPEN")) == NULL)
833 return (NULL);
834 if (*lessopen == '|')
837 * If LESSOPEN starts with a |, it indicates
838 * a "pipe preprocessor".
840 #if !HAVE_FILENO
841 error("LESSOPEN pipe is not supported", NULL_PARG);
842 return (NULL);
843 #else
844 lessopen++;
845 returnfd = 1;
846 if (*lessopen == '-') {
848 * Lessopen preprocessor will accept "-" as a filename.
850 lessopen++;
851 } else {
852 if (strcmp(filename, "-") == 0)
853 return (NULL);
855 #endif
858 len = strlen(lessopen) + strlen(filename) + 2;
859 cmd = (char *) ecalloc(len, sizeof(char));
860 SNPRINTF1(cmd, len, lessopen, filename);
861 fd = shellcmd(cmd);
862 free(cmd);
863 if (fd == NULL)
866 * Cannot create the pipe.
868 return (NULL);
870 #if HAVE_FILENO
871 if (returnfd)
873 int f;
874 char c;
877 * Read one char to see if the pipe will produce any data.
878 * If it does, push the char back on the pipe.
880 f = fileno(fd);
881 SET_BINARY(f);
882 if (read(f, &c, 1) != 1)
885 * Pipe is empty. This means there is no alt file.
887 pclose(fd);
888 return (NULL);
890 ch_ungetchar(c);
891 *pfd = (void *) fd;
892 *pf = f;
893 return (save("-"));
895 #endif
896 cmd = readfd(fd);
897 pclose(fd);
898 if (*cmd == '\0')
900 * Pipe is empty. This means there is no alt file.
902 return (NULL);
903 return (cmd);
904 #endif /* HAVE_POPEN */
908 * Close a replacement file.
910 public void
911 close_altfile(altfilename, filename, pipefd)
912 char *altfilename;
913 char *filename;
914 void *pipefd;
916 #if HAVE_POPEN
917 char *lessclose;
918 FILE *fd;
919 char *cmd;
920 int len;
922 if (secure)
923 return;
924 if (pipefd != NULL)
926 #if OS2
928 * The pclose function of OS/2 emx sometimes fails.
929 * Send SIGINT to the piped process before closing it.
931 kill(((FILE*)pipefd)->_pid, SIGINT);
932 #endif
933 pclose((FILE*) pipefd);
935 if ((lessclose = lgetenv("LESSCLOSE")) == NULL)
936 return;
937 len = strlen(lessclose) + strlen(filename) + strlen(altfilename) + 2;
938 cmd = (char *) ecalloc(len, sizeof(char));
939 SNPRINTF2(cmd, len, lessclose, filename, altfilename);
940 fd = shellcmd(cmd);
941 free(cmd);
942 if (fd != NULL)
943 pclose(fd);
944 #endif
948 * Is the specified file a directory?
950 public int
951 is_dir(filename)
952 char *filename;
954 int isdir = 0;
956 filename = shell_unquote(filename);
957 #if HAVE_STAT
959 int r;
960 struct stat statbuf;
962 r = stat(filename, &statbuf);
963 isdir = (r >= 0 && S_ISDIR(statbuf.st_mode));
965 #else
966 #ifdef _OSK
968 register int f;
970 f = open(filename, S_IREAD | S_IFDIR);
971 if (f >= 0)
972 close(f);
973 isdir = (f >= 0);
975 #endif
976 #endif
977 free(filename);
978 return (isdir);
982 * Returns NULL if the file can be opened and
983 * is an ordinary file, otherwise an error message
984 * (if it cannot be opened or is a directory, etc.)
986 public char *
987 bad_file(filename)
988 char *filename;
990 register char *m = NULL;
992 filename = shell_unquote(filename);
993 if (!force_open && is_dir(filename))
995 static char is_a_dir[] = " is a directory";
997 m = (char *) ecalloc(strlen(filename) + sizeof(is_a_dir),
998 sizeof(char));
999 strcpy(m, filename);
1000 strcat(m, is_a_dir);
1001 } else
1003 #if HAVE_STAT
1004 int r;
1005 struct stat statbuf;
1007 r = stat(filename, &statbuf);
1008 if (r < 0)
1010 m = errno_message(filename);
1011 } else if (force_open)
1013 m = NULL;
1014 } else if (!S_ISREG(statbuf.st_mode))
1016 static char not_reg[] = " is not a regular file (use -f to see it)";
1017 m = (char *) ecalloc(strlen(filename) + sizeof(not_reg),
1018 sizeof(char));
1019 strcpy(m, filename);
1020 strcat(m, not_reg);
1022 #endif
1024 free(filename);
1025 return (m);
1029 * Return the size of a file, as cheaply as possible.
1030 * In Unix, we can stat the file.
1032 public POSITION
1033 filesize(f)
1034 int f;
1036 #if HAVE_STAT
1037 struct stat statbuf;
1039 if (fstat(f, &statbuf) >= 0)
1040 return ((POSITION) statbuf.st_size);
1041 #else
1042 #ifdef _OSK
1043 long size;
1045 if ((size = (long) _gs_size(f)) >= 0)
1046 return ((POSITION) size);
1047 #endif
1048 #endif
1049 return (seek_filesize(f));
1055 public char *
1056 shell_coption()
1058 return ("-c");