2 Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
3 2004, 2005, 2007 Free Software Foundation, Inc.
4 Written 1994, 1995, 1996 by:
5 Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
6 Jakub Jelinek, Mauricio Plaza.
8 The file_date routine is mostly from GNU's fileutils package,
9 written by Richard Stallman and David MacKenzie.
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
33 #include <sys/types.h>
39 #include "main.h" /* mc_home */
40 #include "cmd.h" /* guess_message_value */
41 #include "mountlist.h"
42 #include "win.h" /* xterm_flag */
49 static const char app_text
[] = "Midnight-Commander";
50 int easy_patterns
= 1;
52 extern void str_replace(char *s
, char from
, char to
)
54 for (; *s
!= '\0'; s
++) {
61 is_7bit_printable (unsigned char c
)
63 return (c
> 31 && c
< 127);
67 is_iso_printable (unsigned char c
)
69 return ((c
> 31 && c
< 127) || c
>= 160);
73 is_8bit_printable (unsigned char c
)
75 /* "Full 8 bits output" doesn't work on xterm */
77 return is_iso_printable (c
);
79 return (c
> 31 && c
!= 127 && c
!= 155);
88 /* "Display bits" is ignored, since the user controls the output
89 by setting the output codepage */
90 return is_8bit_printable (c
);
93 return is_7bit_printable (c
);
95 if (full_eight_bits
) {
96 return is_8bit_printable (c
);
98 return is_iso_printable (c
);
99 #endif /* !HAVE_CHARSET */
102 /* Calculates the message dimensions (lines and columns) */
104 msglen (const char *text
, int *lines
, int *columns
)
106 int nlines
= 1; /* even the empty string takes one line */
110 for (; *text
!= '\0'; text
++) {
116 if (colindex
> ncolumns
)
126 * Copy from s to d, and trim the beginning if necessary, and prepend
127 * "..." in this case. The destination string can have at most len
128 * bytes, not counting trailing 0.
131 trim (const char *s
, char *d
, int len
)
138 source_len
= strlen (s
);
139 if (source_len
> len
) {
140 /* Cannot fit the whole line */
142 /* We only have room for the dots */
143 memset (d
, '.', len
);
147 /* Begin with ... and add the rest of the source string */
149 strcpy (d
+ 3, s
+ 3 + source_len
- len
);
152 /* We can copy the whole line */
158 * Quote the filename for the purpose of inserting it into the command
159 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
160 * processed by the mc command line.
163 name_quote (const char *s
, int quote_percent
)
167 d
= ret
= g_malloc (strlen (s
) * 2 + 2 + 1);
173 for (; *s
; s
++, d
++) {
217 fake_name_quote (const char *s
, int quote_percent
)
219 (void) quote_percent
;
224 * Remove the middle part of the string to fit given length.
225 * Use "~" to show where the string was truncated.
226 * Return static buffer, no need to free() it.
229 name_trunc (const char *txt
, size_t trunc_len
)
231 static char x
[MC_MAXPATHLEN
+ MC_MAXPATHLEN
];
240 if (trunc_len
> sizeof (x
) - 1) {
241 trunc_len
= sizeof (x
) - 1;
243 txt_len
= strlen (txt
);
244 if (txt_len
<= trunc_len
) {
247 size_t y
= (trunc_len
/ 2) + (trunc_len
% 2);
248 strncpy (x
, txt
, (size_t) y
);
249 strncpy (x
+ y
, txt
+ (txt_len
- (trunc_len
/ 2)), trunc_len
/ 2);
254 if (!is_printable (*p
))
260 * path_trunc() is the same as name_trunc() above but
261 * it deletes possible password from path for security
265 path_trunc (const char *path
, size_t trunc_len
) {
267 char *secure_path
= strip_password (g_strdup (path
), 1);
269 ret
= name_trunc (secure_path
, trunc_len
);
270 g_free (secure_path
);
276 size_trunc (double size
)
278 static char x
[BUF_TINY
];
279 long int divisor
= 1;
280 const char *xtra
= "";
282 if (size
> 999999999L){
285 if (size
/divisor
> 999999999L){
290 g_snprintf (x
, sizeof (x
), "%.0f%s", (size
/divisor
), xtra
);
295 size_trunc_sep (double size
)
302 p
= y
= size_trunc (size
);
304 d
= x
+ sizeof (x
) - 1;
306 while (p
>= y
&& isalpha ((unsigned char) *p
))
308 for (count
= 0; p
>= y
; count
++){
322 * Print file SIZE to BUFFER, but don't exceed LEN characters,
323 * not including trailing 0. BUFFER should be at least LEN+1 long.
324 * This function is called for every file on panels, so avoid
325 * floating point by any means.
327 * Units: size units (filesystem sizes are 1K blocks)
328 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
331 size_trunc_len (char *buffer
, int len
, off_t size
, int units
)
333 /* Avoid taking power for every file. */
334 static const off_t power10
[] =
335 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
337 static const char * const suffix
[] =
338 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL
};
341 /* Don't print more than 9 digits - use suffix. */
342 if (len
== 0 || len
> 9)
345 for (j
= units
; suffix
[j
] != NULL
; j
++) {
348 /* Empty files will print "0" even with minimal width. */
349 g_snprintf (buffer
, len
+ 1, "0");
353 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
354 g_snprintf (buffer
, len
+ 1, (len
> 1) ? "~%s" : "%s",
355 (j
> 1) ? suffix
[j
- 1] : "B");
359 if (size
< power10
[len
- (j
> 0)]) {
360 g_snprintf (buffer
, len
+ 1, "%lu%s", (unsigned long) size
, suffix
[j
]);
364 /* Powers of 1024, with rounding. */
365 size
= (size
+ 512) >> 10;
372 if ((S_IXUSR
& mode
) || (S_IXGRP
& mode
) || (S_IXOTH
& mode
))
377 #define ismode(n,m) ((n & m) == m)
380 string_perm (mode_t mode_bits
)
382 static char mode
[11];
384 strcpy (mode
, "----------");
385 if (S_ISDIR (mode_bits
))
387 if (S_ISCHR (mode_bits
))
389 if (S_ISBLK (mode_bits
))
391 if (S_ISLNK (mode_bits
))
393 if (S_ISFIFO (mode_bits
))
395 if (S_ISNAM (mode_bits
))
397 if (S_ISSOCK (mode_bits
))
399 if (S_ISDOOR (mode_bits
))
401 if (ismode (mode_bits
, S_IXOTH
))
403 if (ismode (mode_bits
, S_IWOTH
))
405 if (ismode (mode_bits
, S_IROTH
))
407 if (ismode (mode_bits
, S_IXGRP
))
409 if (ismode (mode_bits
, S_IWGRP
))
411 if (ismode (mode_bits
, S_IRGRP
))
413 if (ismode (mode_bits
, S_IXUSR
))
415 if (ismode (mode_bits
, S_IWUSR
))
417 if (ismode (mode_bits
, S_IRUSR
))
420 if (ismode (mode_bits
, S_ISUID
))
421 mode
[3] = (mode
[3] == 'x') ? 's' : 'S';
424 if (ismode (mode_bits
, S_ISGID
))
425 mode
[6] = (mode
[6] == 'x') ? 's' : 'S';
428 if (ismode (mode_bits
, S_ISVTX
))
429 mode
[9] = (mode
[9] == 'x') ? 't' : 'T';
434 /* p: string which might contain an url with a password (this parameter is
436 has_prefix = 0: The first parameter is an url without a prefix
437 (user[:pass]@]machine[:port][remote-dir). Delete
439 has_prefix = 1: Search p for known url prefixes. If found delete
440 the password from the url.
441 Caveat: only the first url is found
444 strip_password (char *p
, int has_prefix
)
446 static const struct {
449 } prefixes
[] = { {"/#ftp:", 6},
459 char *at
, *inner_colon
, *dir
;
463 for (i
= 0; i
< sizeof (prefixes
)/sizeof (prefixes
[0]); i
++) {
467 if((q
= strstr (p
, prefixes
[i
].name
)) == 0)
470 p
= q
+ prefixes
[i
].len
;
473 if ((dir
= strchr (p
, PATH_SEP
)) != NULL
)
476 /* search for any possible user */
477 at
= strrchr (p
, '@');
482 /* We have a username */
484 inner_colon
= memchr (p
, ':', at
- p
);
486 memmove (inner_colon
, at
, strlen(at
) + 1);
494 strip_home_and_password(const char *dir
)
497 static char newdir
[MC_MAXPATHLEN
];
499 if (home_dir
&& !strncmp (dir
, home_dir
, len
= strlen (home_dir
)) &&
500 (dir
[len
] == PATH_SEP
|| dir
[len
] == '\0')){
502 g_strlcpy (&newdir
[1], &dir
[len
], sizeof(newdir
) - 1);
506 /* We do not strip homes in /#ftp tree, I do not like ~'s there
508 g_strlcpy (newdir
, dir
, sizeof(newdir
));
509 strip_password (newdir
, 1);
514 maybe_start_group (char *d
, int do_group
, int *was_wildcard
)
527 maybe_end_group (char *d
, int do_group
, int *was_wildcard
)
539 /* If shell patterns are on converts a shell pattern to a regular
540 expression. Called by regexp_match and mask_rename. */
541 /* Shouldn't we support [a-fw] type wildcards as well ?? */
543 convert_pattern (const char *pattern
, int match_type
, int do_group
)
547 int was_wildcard
= 0;
550 if ((match_type
!= match_regex
) && easy_patterns
){
551 new_pattern
= g_malloc (MC_MAXPATHLEN
);
553 if (match_type
== match_file
)
555 for (s
= pattern
; *s
; s
++, d
++){
558 d
= maybe_start_group (d
, do_group
, &was_wildcard
);
564 d
= maybe_start_group (d
, do_group
, &was_wildcard
);
569 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
575 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
580 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
581 if (match_type
== match_file
)
586 return g_strdup (pattern
);
590 regexp_match (const char *pattern
, const char *string
, int match_type
)
593 static char *old_pattern
= NULL
;
598 if (!old_pattern
|| STRCOMP (old_pattern
, pattern
) || old_type
!= match_type
){
601 g_free (old_pattern
);
604 my_pattern
= convert_pattern (pattern
, match_type
, 0);
605 if (regcomp (&r
, my_pattern
, REG_EXTENDED
|REG_NOSUB
|MC_ARCH_FLAGS
)) {
609 old_pattern
= my_pattern
;
610 old_type
= match_type
;
612 rval
= !regexec (&r
, string
, 0, NULL
, 0);
617 extension (const char *filename
)
619 const char *d
= strrchr (filename
, '.');
620 return (d
!= NULL
) ? d
+ 1 : "";
624 get_int (const char *file
, const char *key
, int def
)
626 return GetPrivateProfileInt (app_text
, key
, def
, file
);
630 set_int (const char *file
, const char *key
, int value
)
632 char buffer
[BUF_TINY
];
634 g_snprintf (buffer
, sizeof (buffer
), "%d", value
);
635 return WritePrivateProfileString (app_text
, key
, buffer
, file
);
639 get_config_string (const char *file
, const char *key
, const char *defval
)
642 (void)GetPrivateProfileString (app_text
, key
, defval
, buffer
, sizeof(buffer
), file
);
643 return g_strdup (buffer
);
647 set_config_string (const char *file
, const char *key
, const char *val
)
649 (void)WritePrivateProfileString (app_text
, key
, val
, file
);
653 exist_file (const char *name
)
655 return access (name
, R_OK
) == 0;
659 load_file (const char *filename
)
666 if ((data_file
= fopen (filename
, "r")) == NULL
){
669 if (fstat (fileno (data_file
), &s
) != 0){
673 data
= g_malloc (s
.st_size
+1);
674 read_size
= fread (data
, 1, s
.st_size
, data_file
);
675 data
[read_size
] = 0;
687 load_mc_home_file (const char *filename
, char **allocated_filename
)
689 char *hintfile_base
, *hintfile
;
693 hintfile_base
= concat_dir_and_file (mc_home
, filename
);
694 lang
= guess_message_value ();
696 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
697 data
= load_file (hintfile
);
701 /* Fall back to the two-letter language code */
702 if (lang
[0] && lang
[1])
704 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
705 data
= load_file (hintfile
);
709 hintfile
= hintfile_base
;
710 data
= load_file (hintfile_base
);
716 if (hintfile
!= hintfile_base
)
717 g_free (hintfile_base
);
719 if (allocated_filename
)
720 *allocated_filename
= hintfile
;
727 /* Check strftime() results. Some systems (i.e. Solaris) have different
728 short-month-name sizes for different locales */
730 i18n_checktimelength (void)
732 time_t testtime
= time (NULL
);
733 struct tm
* lt
= localtime(&testtime
);
737 // huh, localtime() doesnt seem to work ... falling back to "(invalid)"
738 length
= strlen(INVALID_TIME_TEXT
);
740 char buf
[MAX_I18NTIMELENGTH
+ 1];
742 a
= strftime (buf
, sizeof(buf
)-1, _("%b %e %H:%M"), lt
);
743 b
= strftime (buf
, sizeof(buf
)-1, _("%b %e %Y"), lt
);
747 /* Don't handle big differences. Use standard value (email bug, please) */
748 if ( length
> MAX_I18NTIMELENGTH
|| length
< MIN_I18NTIMELENGTH
)
749 length
= STD_I18NTIMELENGTH
;
755 file_date (time_t when
)
757 static char timebuf
[MAX_I18NTIMELENGTH
+ 1];
758 time_t current_time
= time ((time_t) 0);
759 static size_t i18n_timelength
= 0;
760 static const char *fmtyear
, *fmttime
;
763 if (i18n_timelength
== 0){
764 i18n_timelength
= i18n_checktimelength() + 1;
766 /* strftime() format string for old dates */
767 fmtyear
= _("%b %e %Y");
768 /* strftime() format string for recent dates */
769 fmttime
= _("%b %e %H:%M");
772 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
773 || current_time
< when
- 60L * 60L) /* In the future. */
774 /* The file is fairly old or in the future.
775 POSIX says the cutoff is 6 months old;
776 approximate this by 6*30 days.
777 Allow a 1 hour slop factor for what is considered "the future",
778 to allow for NFS server/client clock disagreement.
779 Show the year instead of the time of day. */
785 FMT_LOCALTIME(timebuf
, i18n_timelength
, fmt
, when
);
791 extract_line (const char *s
, const char *top
)
793 static char tmp_line
[BUF_MEDIUM
];
796 while (*s
&& *s
!= '\n' && (size_t) (t
- tmp_line
) < sizeof (tmp_line
)-1 && s
< top
)
802 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
804 _icase_search (const char *text
, const char *data
, int *lng
)
806 const char *d
= text
;
807 const char *e
= data
;
813 while (*(e
+1) == '\b' && *(e
+2)) {
817 if (toupper((unsigned char) *d
) == toupper((unsigned char) *e
))
826 *lng
= strlen (text
) + dlng
;
833 /* The basename routine */
835 x_basename (const char *s
)
838 return ((where
= strrchr (s
, PATH_SEP
))) ? where
+ 1 : s
;
843 unix_error_string (int error_num
)
845 static char buffer
[BUF_LARGE
];
846 #if GLIB_MAJOR_VERSION >= 2
847 gchar
*strerror_currentlocale
;
849 strerror_currentlocale
= g_locale_from_utf8(g_strerror (error_num
), -1, NULL
, NULL
, NULL
);
850 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
851 strerror_currentlocale
, error_num
);
852 g_free(strerror_currentlocale
);
854 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
855 g_strerror (error_num
), error_num
);
861 skip_separators (const char *s
)
864 if (*s
!= ' ' && *s
!= '\t' && *s
!= ',')
870 skip_numbers (const char *s
)
873 if (!isdigit ((unsigned char) *s
))
878 /* Remove all control sequences from the argument string. We define
879 * "control sequence", in a sort of pidgin BNF, as follows:
881 * control-seq = Esc non-'['
882 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
884 * This scheme works for all the terminals described in my termcap /
885 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
886 * terminals. If I hear from a single person who uses such a terminal
887 * with MC, I'll be glad to add support for it. (Dugan)
888 * Non-printable characters are also removed.
892 strip_ctrl_codes (char *s
)
894 char *w
; /* Current position where the stripped data is written */
895 char *r
; /* Current position where the original data is read */
900 for (w
= s
, r
= s
; *r
; ) {
901 if (*r
== ESC_CHAR
) {
902 /* Skip the control sequence's arguments */ ;
904 /* strchr() matches trailing binary 0 */
905 while (*(++r
) && strchr ("0123456789;?", *r
));
909 * Now we are at the last character of the sequence.
910 * Skip it unless it's binary 0.
917 if (is_printable(*r
))
928 get_current_wd (char *buffer
, int size
)
933 p
= g_get_current_dir ();
941 memcpy (buffer
, p
, len
);
946 #endif /* !USE_VFS */
948 enum compression_type
949 get_compression_type (int fd
)
951 unsigned char magic
[16];
953 /* Read the magic signature */
954 if (mc_read (fd
, (char *) magic
, 4) != 4)
955 return COMPRESSION_NONE
;
957 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
958 if (magic
[0] == 037 && (magic
[1] == 0213 || magic
[1] == 0236)) {
959 return COMPRESSION_GZIP
;
963 if (magic
[0] == 0120 && magic
[1] == 0113 && magic
[2] == 003
964 && magic
[3] == 004) {
965 /* Read compression type */
966 mc_lseek (fd
, 8, SEEK_SET
);
967 if (mc_read (fd
, (char *) magic
, 2) != 2)
968 return COMPRESSION_NONE
;
970 /* Gzip can handle only deflated (8) or stored (0) files */
971 if ((magic
[0] != 8 && magic
[0] != 0) || magic
[1] != 0)
972 return COMPRESSION_NONE
;
974 /* Compatible with gzip */
975 return COMPRESSION_GZIP
;
978 /* PACK_MAGIC and LZH_MAGIC and compress magic */
980 && (magic
[1] == 036 || magic
[1] == 0240 || magic
[1] == 0235)) {
981 /* Compatible with gzip */
982 return COMPRESSION_GZIP
;
985 /* BZIP and BZIP2 files */
986 if ((magic
[0] == 'B') && (magic
[1] == 'Z') &&
987 (magic
[3] >= '1') && (magic
[3] <= '9')) {
990 return COMPRESSION_BZIP
;
992 return COMPRESSION_BZIP2
;
996 /* LZMA files; both LZMA_Alone and LZMA utils formats. The LZMA_Alone
997 * format is used by the LZMA_Alone tool from LZMA SDK. The LZMA utils
998 * format is the default format of LZMA utils 4.32.1 and later. */
999 if (magic
[0] < 0xE1 || (magic
[0] == 0xFF && magic
[1] == 'L' &&
1000 magic
[2] == 'Z' && magic
[3] == 'M')) {
1001 if (mc_read (fd
, (char *) magic
+ 4, 9) == 9) {
1002 /* LZMA utils format */
1003 if (magic
[0] == 0xFF && magic
[4] == 'A' && magic
[5] == 0x00)
1004 return COMPRESSION_LZMA
;
1005 /* The LZMA_Alone format has no magic bytes, thus we
1006 * need to play a wizard. This can give false positives,
1007 * thus the detection below should be removed when
1008 * the newer LZMA utils format has got popular. */
1009 if (magic
[0] < 0xE1 && magic
[4] < 0x20 &&
1010 ((magic
[10] == 0x00 && magic
[11] == 0x00 &&
1011 magic
[12] == 0x00) ||
1012 (magic
[5] == 0xFF && magic
[6] == 0xFF &&
1013 magic
[7] == 0xFF && magic
[8] == 0xFF &&
1014 magic
[9] == 0xFF && magic
[10] == 0xFF &&
1015 magic
[11] == 0xFF && magic
[12] == 0xFF)))
1016 return COMPRESSION_LZMA
;
1024 decompress_extension (int type
)
1027 case COMPRESSION_GZIP
: return "#ugz";
1028 case COMPRESSION_BZIP
: return "#ubz";
1029 case COMPRESSION_BZIP2
: return "#ubz2";
1030 case COMPRESSION_LZMA
: return "#ulzma";
1032 /* Should never reach this place */
1033 fprintf (stderr
, "Fatal: decompress_extension called with an unknown argument\n");
1039 add_hook (Hook
**hook_list
, void (*hook_fn
)(void *), void *data
)
1041 Hook
*new_hook
= g_new (Hook
, 1);
1043 new_hook
->hook_fn
= hook_fn
;
1044 new_hook
->next
= *hook_list
;
1045 new_hook
->hook_data
= data
;
1047 *hook_list
= new_hook
;
1051 execute_hooks (Hook
*hook_list
)
1056 /* We copy the hook list first so tahat we let the hook
1057 * function call delete_hook
1061 add_hook (&new_hook
, hook_list
->hook_fn
, hook_list
->hook_data
);
1062 hook_list
= hook_list
->next
;
1067 (*new_hook
->hook_fn
)(new_hook
->hook_data
);
1068 new_hook
= new_hook
->next
;
1071 for (hook_list
= p
; hook_list
;){
1073 hook_list
= hook_list
->next
;
1079 delete_hook (Hook
**hook_list
, void (*hook_fn
)(void *))
1081 Hook
*current
, *new_list
, *next
;
1085 for (current
= *hook_list
; current
; current
= next
){
1086 next
= current
->next
;
1087 if (current
->hook_fn
== hook_fn
)
1090 add_hook (&new_list
, current
->hook_fn
, current
->hook_data
);
1092 *hook_list
= new_list
;
1096 hook_present (Hook
*hook_list
, void (*hook_fn
)(void *))
1100 for (p
= hook_list
; p
; p
= p
->next
)
1101 if (p
->hook_fn
== hook_fn
)
1107 wipe_password (char *passwd
)
1118 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1119 /* Returns a newly allocated string */
1121 convert_controls (const char *p
)
1123 char *valcopy
= g_strdup (p
);
1126 /* Parse the escape special character */
1127 for (q
= valcopy
; *p
;){
1130 if ((*p
== 'e') || (*p
== 'E')){
1140 char c
= (*p
| 0x20);
1141 if (c
>= 'a' && c
<= 'z') {
1156 resolve_symlinks (const char *path
)
1158 char *buf
, *buf2
, *q
, *r
, c
;
1163 if (*path
!= PATH_SEP
)
1165 r
= buf
= g_malloc (MC_MAXPATHLEN
);
1166 buf2
= g_malloc (MC_MAXPATHLEN
);
1171 q
= strchr (p
+ 1, PATH_SEP
);
1173 q
= strchr (p
+ 1, 0);
1179 if (mc_lstat (path
, &mybuf
) < 0) {
1185 if (!S_ISLNK (mybuf
.st_mode
))
1188 len
= mc_readlink (path
, buf2
, MC_MAXPATHLEN
- 1);
1196 if (*buf2
== PATH_SEP
)
1201 canonicalize_pathname (buf
);
1202 r
= strchr (buf
, 0);
1203 if (!*r
|| *(r
- 1) != PATH_SEP
) {
1213 strcpy (buf
, PATH_SEP_STR
);
1214 else if (*(r
- 1) == PATH_SEP
&& r
!= buf
+ 1)
1220 /* Finds out a relative path from first to second, i.e. goes as many ..
1221 * as needed up in first and then goes down using second */
1223 diff_two_paths (const char *first
, const char *second
)
1225 char *p
, *q
, *r
, *s
, *buf
= NULL
;
1226 int i
, j
, prevlen
= -1, currlen
;
1227 char *my_first
= NULL
, *my_second
= NULL
;
1229 my_first
= resolve_symlinks (first
);
1230 if (my_first
== NULL
)
1232 my_second
= resolve_symlinks (second
);
1233 if (my_second
== NULL
) {
1237 for (j
= 0; j
< 2; j
++) {
1241 r
= strchr (p
, PATH_SEP
);
1242 s
= strchr (q
, PATH_SEP
);
1246 if (strcmp (p
, q
)) {
1247 *r
= PATH_SEP
; *s
= PATH_SEP
;
1250 *r
= PATH_SEP
; *s
= PATH_SEP
;
1256 for (i
= 0; (p
= strchr (p
+ 1, PATH_SEP
)) != NULL
; i
++);
1257 currlen
= (i
+ 1) * 3 + strlen (q
) + 1;
1259 if (currlen
< prevlen
)
1267 p
= buf
= g_malloc (currlen
);
1269 for (; i
>= 0; i
--, p
+= 3)
1278 /* If filename is NULL, then we just append PATH_SEP to the dir */
1280 concat_dir_and_file (const char *dir
, const char *file
)
1282 int i
= strlen (dir
);
1284 if (dir
[i
-1] == PATH_SEP
)
1285 return g_strconcat (dir
, file
, (char *) NULL
);
1287 return g_strconcat (dir
, PATH_SEP_STR
, file
, (char *) NULL
);
1290 /* Append text to GList, remove all entries with the same text */
1292 list_append_unique (GList
*list
, char *text
)
1294 GList
*link
, *newlink
;
1297 * Go to the last position and traverse the list backwards
1298 * starting from the second last entry to make sure that we
1299 * are not removing the current link.
1301 list
= g_list_append (list
, text
);
1302 list
= g_list_last (list
);
1303 link
= g_list_previous (list
);
1306 newlink
= g_list_previous (link
);
1307 if (!strcmp ((char *) link
->data
, text
)) {
1308 g_free (link
->data
);
1309 g_list_remove_link (list
, link
);
1310 g_list_free_1 (link
);
1318 /* Following code heavily borrows from libiberty, mkstemps.c */
1320 /* Number of attempts to create a temporary file */
1322 #define TMP_MAX 16384
1323 #endif /* !TMP_MAX */
1327 * pname (output) - pointer to the name of the temp file (needs g_free).
1328 * NULL if the function fails.
1329 * prefix - part of the filename before the random part.
1330 * Prepend $TMPDIR or /tmp if there are no path separators.
1331 * suffix - if not NULL, part of the filename after the random part.
1334 * handle of the open file or -1 if couldn't open any.
1337 mc_mkstemps (char **pname
, const char *prefix
, const char *suffix
)
1339 static const char letters
[]
1340 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1341 static unsigned long value
;
1348 if (strchr (prefix
, PATH_SEP
) == NULL
) {
1349 /* Add prefix first to find the position of XXXXXX */
1350 tmpbase
= concat_dir_and_file (mc_tmpdir (), prefix
);
1352 tmpbase
= g_strdup (prefix
);
1355 tmpname
= g_strconcat (tmpbase
, "XXXXXX", suffix
, (char *) NULL
);
1357 XXXXXX
= &tmpname
[strlen (tmpbase
)];
1360 /* Get some more or less random data. */
1361 gettimeofday (&tv
, NULL
);
1362 value
+= (tv
.tv_usec
<< 16) ^ tv
.tv_sec
^ getpid ();
1364 for (count
= 0; count
< TMP_MAX
; ++count
) {
1365 unsigned long v
= value
;
1368 /* Fill in the random bits. */
1369 XXXXXX
[0] = letters
[v
% 62];
1371 XXXXXX
[1] = letters
[v
% 62];
1373 XXXXXX
[2] = letters
[v
% 62];
1375 XXXXXX
[3] = letters
[v
% 62];
1377 XXXXXX
[4] = letters
[v
% 62];
1379 XXXXXX
[5] = letters
[v
% 62];
1381 fd
= open (tmpname
, O_RDWR
| O_CREAT
| O_TRUNC
| O_EXCL
,
1384 /* Successfully created. */
1388 /* This is a random value. It is only necessary that the next
1389 TMP_MAX values generated by adding 7777 to VALUE are different
1390 with (module 2^32). */
1394 /* Unsuccessful. Free the filename. */
1402 * Read and restore position for the given filename.
1403 * If there is no stored data, return line 1 and col 0.
1406 load_file_position (const char *filename
, long *line
, long *column
)
1410 char buf
[MC_MAXPATHLEN
+ 20];
1417 /* open file with positions */
1418 fn
= concat_dir_and_file (home_dir
, MC_FILEPOS
);
1419 f
= fopen (fn
, "r");
1424 len
= strlen (filename
);
1426 while (fgets (buf
, sizeof (buf
), f
)) {
1429 /* check if the filename matches the beginning of string */
1430 if (strncmp (buf
, filename
, len
) != 0)
1433 /* followed by single space */
1434 if (buf
[len
] != ' ')
1437 /* and string without spaces */
1439 if (strchr (p
, ' '))
1442 *line
= strtol(p
, const_cast(char **, &p
), 10);
1444 *column
= strtol(p
+1, const_cast(char **, &p
), 10);
1453 /* Save position for the given file */
1455 save_file_position (const char *filename
, long line
, long column
)
1459 char buf
[MC_MAXPATHLEN
+ 20];
1463 len
= strlen (filename
);
1465 tmp
= concat_dir_and_file (home_dir
, MC_FILEPOS_TMP
);
1466 fn
= concat_dir_and_file (home_dir
, MC_FILEPOS
);
1468 /* open temporary file */
1469 t
= fopen (tmp
, "w");
1476 /* put the new record */
1477 if (line
!= 1 || column
!= 0) {
1478 fprintf (t
, "%s %ld;%ld\n", filename
, line
, column
);
1481 /* copy records from the old file */
1482 f
= fopen (fn
, "r");
1484 while (fgets (buf
, sizeof (buf
), f
)) {
1485 /* Skip entries for the current filename */
1486 if (strncmp (buf
, filename
, len
) == 0 && buf
[len
] == ' '
1487 && !strchr (&buf
[len
+ 1], ' '))
1490 fprintf (t
, "%s", buf
);
1491 if (++i
> MC_FILEPOS_ENTRIES
)
1504 cstrcasestr (const char *haystack
, const char *needle
)
1507 size_t i
, needle_len
;
1509 needle_len
= strlen (needle
);
1510 for (hptr
= haystack
; *hptr
!= '\0'; hptr
++) {
1511 for (i
= 0; i
< needle_len
; i
++) {
1512 if (toupper ((unsigned char) hptr
[i
]) !=
1513 toupper ((unsigned char) needle
[i
]))
1524 cstrstr (const char *haystack
, const char *needle
)
1526 return strstr(haystack
, needle
);
1530 str_unconst (const char *s
)
1535 #define ASCII_A (0x40 + 1)
1536 #define ASCII_Z (0x40 + 26)
1537 #define ASCII_a (0x60 + 1)
1538 #define ASCII_z (0x60 + 26)
1541 ascii_alpha_to_cntrl (int ch
)
1543 if ((ch
>= ASCII_A
&& ch
<= ASCII_Z
)
1544 || (ch
>= ASCII_a
&& ch
<= ASCII_z
)) {
1553 const char *result
, *sep
;
1556 sep
= strchr(result
, '|');
1557 return (sep
!= NULL
) ? sep
+ 1 : result
;
1560 #define shell_escape_toesc(x) \
1561 (((x)==' ')||((x)=='!')||((x)=='#')||((x)=='$')||((x)=='%')|| \
1562 ((x)=='(')||((x)==')')||((x)=='\'')||((x)=='&')||((x)=='~')|| \
1563 ((x)=='{')||((x)=='}')||((x)=='[')||((x)==']')||((x)=='`')|| \
1564 ((x)=='?')||((x)=='|')||((x)=='<')||((x)=='>')||((x)==';')|| \
1565 ((x)=='*')||((x)=='\\')||((x)=='"'))
1567 #define shell_escape_nottoesc(x) \
1568 (((x)!=0) && (!shell_escape_toesc((x))))
1570 /** To be compatible with the general posix command lines we have to escape
1571 strings for the command line
1577 return escaped string (which needs to be freed later)
1580 shell_escape(const char* src
)
1583 char *result
= NULL
;
1585 if ((src
==NULL
)||(!(*src
)))
1588 str
= g_string_new("");
1590 /* look for the first char to escape */
1594 /* copy over all chars not to escape */
1595 while ((c
=(*src
)) && shell_escape_nottoesc(c
))
1597 g_string_append_c(str
,c
);
1601 /* at this point we either have an \0 or an char to escape */
1604 g_string_free(str
,FALSE
);
1608 g_string_append_c(str
,'\\');
1609 g_string_append_c(str
,c
);
1614 /** Unescape paths or other strings for e.g the internal cd
1615 shell-unescape within a given buffer (writing to it!)
1618 string for unescaping
1621 return unescaped string (which needs to be freed)
1624 shell_unescape(const char* text
)
1627 char *result
= NULL
;
1633 /* look for the first \ - that's quick skipover if there's nothing to escape */
1634 const char* readptr
= text
;
1635 while ((*readptr
) && ((*readptr
)!='\\')) readptr
++;
1637 result
= g_strdup(text
);
1640 str
= g_string_new_len(text
, readptr
- text
);
1642 /* if we're here, we're standing on the first '\' */
1644 while ((c
= *readptr
))
1649 switch ((c
= *readptr
))
1651 case '\0': /* end of string! malformed escape string */
1654 case 'n': g_string_append_c(str
,'\n'); break;
1655 case 'r': g_string_append_c(str
,'\r'); break;
1656 case 't': g_string_append_c(str
,'\t'); break;
1679 g_string_append_c(str
,c
); break;
1682 else /* got a normal character */
1684 g_string_append_c(str
,c
);
1691 g_string_free(str
,FALSE
);
1695 /** Check if char in pointer contain escape'd chars
1701 return TRUE if string contain escaped chars
1702 otherwise return FALSE
1705 shell_is_char_escaped ( const char *in
)
1707 if (in
== NULL
|| !*in
|| in
[0] != '\\')
1709 if (shell_escape_toesc(in
[1]))