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. */
34 #include <sys/types.h>
40 #include "main.h" /* mc_home */
41 #include "cmd.h" /* guess_message_value */
42 #include "mountlist.h"
43 #include "win.h" /* xterm_flag */
50 static const char app_text
[] = "Midnight-Commander";
51 int easy_patterns
= 1;
53 extern void str_replace(char *s
, char from
, char to
)
55 for (; *s
!= '\0'; s
++) {
62 is_7bit_printable (unsigned char c
)
64 return (c
> 31 && c
< 127);
68 is_iso_printable (unsigned char c
)
70 return ((c
> 31 && c
< 127) || c
>= 160);
74 is_8bit_printable (unsigned char c
)
76 /* "Full 8 bits output" doesn't work on xterm */
78 return is_iso_printable (c
);
80 return (c
> 31 && c
!= 127 && c
!= 155);
89 /* "Display bits" is ignored, since the user controls the output
90 by setting the output codepage */
91 return is_8bit_printable (c
);
94 return is_7bit_printable (c
);
96 if (full_eight_bits
) {
97 return is_8bit_printable (c
);
99 return is_iso_printable (c
);
100 #endif /* !HAVE_CHARSET */
103 /* Calculates the message dimensions (lines and columns) */
105 msglen (const char *text
, int *lines
, int *columns
)
107 int nlines
= 1; /* even the empty string takes one line */
111 for (; *text
!= '\0'; text
++) {
117 if (colindex
> ncolumns
)
127 * Copy from s to d, and trim the beginning if necessary, and prepend
128 * "..." in this case. The destination string can have at most len
129 * bytes, not counting trailing 0.
132 trim (const char *s
, char *d
, int len
)
139 source_len
= strlen (s
);
140 if (source_len
> len
) {
141 /* Cannot fit the whole line */
143 /* We only have room for the dots */
144 memset (d
, '.', len
);
148 /* Begin with ... and add the rest of the source string */
150 strcpy (d
+ 3, s
+ 3 + source_len
- len
);
153 /* We can copy the whole line */
159 * Quote the filename for the purpose of inserting it into the command
160 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
161 * processed by the mc command line.
164 name_quote (const char *s
, int quote_percent
)
168 d
= ret
= g_malloc (strlen (s
) * 2 + 2 + 1);
174 for (; *s
; s
++, d
++) {
218 fake_name_quote (const char *s
, int quote_percent
)
220 (void) quote_percent
;
225 * Remove the middle part of the string to fit given length.
226 * Use "~" to show where the string was truncated.
227 * Return static buffer, no need to free() it.
230 name_trunc (const char *txt
, size_t trunc_len
)
232 static char x
[MC_MAXPATHLEN
+ MC_MAXPATHLEN
];
241 if (trunc_len
> sizeof (x
) - 1) {
242 trunc_len
= sizeof (x
) - 1;
244 txt_len
= strlen (txt
);
245 if (txt_len
<= trunc_len
) {
248 size_t y
= (trunc_len
/ 2) + (trunc_len
% 2);
249 strncpy (x
, txt
, (size_t) y
);
250 strncpy (x
+ y
, txt
+ (txt_len
- (trunc_len
/ 2)), trunc_len
/ 2);
255 if (!is_printable (*p
))
261 * path_trunc() is the same as name_trunc() above but
262 * it deletes possible password from path for security
266 path_trunc (const char *path
, size_t trunc_len
) {
268 char *secure_path
= strip_password (g_strdup (path
), 1);
270 ret
= name_trunc (secure_path
, trunc_len
);
271 g_free (secure_path
);
277 size_trunc (double size
)
279 static char x
[BUF_TINY
];
280 long int divisor
= 1;
281 const char *xtra
= "";
283 if (size
> 999999999L){
286 if (size
/divisor
> 999999999L){
291 g_snprintf (x
, sizeof (x
), "%.0f%s", (size
/divisor
), xtra
);
296 size_trunc_sep (double size
)
303 p
= y
= size_trunc (size
);
305 d
= x
+ sizeof (x
) - 1;
307 while (p
>= y
&& isalpha ((unsigned char) *p
))
309 for (count
= 0; p
>= y
; count
++){
323 * Print file SIZE to BUFFER, but don't exceed LEN characters,
324 * not including trailing 0. BUFFER should be at least LEN+1 long.
325 * This function is called for every file on panels, so avoid
326 * floating point by any means.
328 * Units: size units (filesystem sizes are 1K blocks)
329 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
332 size_trunc_len (char *buffer
, int len
, off_t size
, int units
)
334 /* Avoid taking power for every file. */
335 static const off_t power10
[] =
336 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
338 static const char * const suffix
[] =
339 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL
};
342 /* Don't print more than 9 digits - use suffix. */
343 if (len
== 0 || len
> 9)
346 for (j
= units
; suffix
[j
] != NULL
; j
++) {
349 /* Empty files will print "0" even with minimal width. */
350 g_snprintf (buffer
, len
+ 1, "0");
354 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
355 g_snprintf (buffer
, len
+ 1, (len
> 1) ? "~%s" : "%s",
356 (j
> 1) ? suffix
[j
- 1] : "B");
360 if (size
< power10
[len
- (j
> 0)]) {
361 g_snprintf (buffer
, len
+ 1, "%lu%s", (unsigned long) size
, suffix
[j
]);
365 /* Powers of 1024, with rounding. */
366 size
= (size
+ 512) >> 10;
373 if ((S_IXUSR
& mode
) || (S_IXGRP
& mode
) || (S_IXOTH
& mode
))
378 #define ismode(n,m) ((n & m) == m)
381 string_perm (mode_t mode_bits
)
383 static char mode
[11];
385 strcpy (mode
, "----------");
386 if (S_ISDIR (mode_bits
))
388 if (S_ISCHR (mode_bits
))
390 if (S_ISBLK (mode_bits
))
392 if (S_ISLNK (mode_bits
))
394 if (S_ISFIFO (mode_bits
))
396 if (S_ISNAM (mode_bits
))
398 if (S_ISSOCK (mode_bits
))
400 if (S_ISDOOR (mode_bits
))
402 if (ismode (mode_bits
, S_IXOTH
))
404 if (ismode (mode_bits
, S_IWOTH
))
406 if (ismode (mode_bits
, S_IROTH
))
408 if (ismode (mode_bits
, S_IXGRP
))
410 if (ismode (mode_bits
, S_IWGRP
))
412 if (ismode (mode_bits
, S_IRGRP
))
414 if (ismode (mode_bits
, S_IXUSR
))
416 if (ismode (mode_bits
, S_IWUSR
))
418 if (ismode (mode_bits
, S_IRUSR
))
421 if (ismode (mode_bits
, S_ISUID
))
422 mode
[3] = (mode
[3] == 'x') ? 's' : 'S';
425 if (ismode (mode_bits
, S_ISGID
))
426 mode
[6] = (mode
[6] == 'x') ? 's' : 'S';
429 if (ismode (mode_bits
, S_ISVTX
))
430 mode
[9] = (mode
[9] == 'x') ? 't' : 'T';
435 /* p: string which might contain an url with a password (this parameter is
437 has_prefix = 0: The first parameter is an url without a prefix
438 (user[:pass]@]machine[:port][remote-dir). Delete
440 has_prefix = 1: Search p for known url prefixes. If found delete
441 the password from the url.
442 Caveat: only the first url is found
445 strip_password (char *p
, int has_prefix
)
447 static const struct {
450 } prefixes
[] = { {"/#ftp:", 6},
460 char *at
, *inner_colon
, *dir
;
464 for (i
= 0; i
< sizeof (prefixes
)/sizeof (prefixes
[0]); i
++) {
468 if((q
= strstr (p
, prefixes
[i
].name
)) == 0)
471 p
= q
+ prefixes
[i
].len
;
474 if ((dir
= strchr (p
, PATH_SEP
)) != NULL
)
477 /* search for any possible user */
478 at
= strrchr (p
, '@');
483 /* We have a username */
485 inner_colon
= memchr (p
, ':', at
- p
);
487 memmove (inner_colon
, at
, strlen(at
) + 1);
495 strip_home_and_password(const char *dir
)
498 static char newdir
[MC_MAXPATHLEN
];
500 if (home_dir
&& !strncmp (dir
, home_dir
, len
= strlen (home_dir
)) &&
501 (dir
[len
] == PATH_SEP
|| dir
[len
] == '\0')){
503 g_strlcpy (&newdir
[1], &dir
[len
], sizeof(newdir
) - 1);
507 /* We do not strip homes in /#ftp tree, I do not like ~'s there
509 g_strlcpy (newdir
, dir
, sizeof(newdir
));
510 strip_password (newdir
, 1);
515 maybe_start_group (char *d
, int do_group
, int *was_wildcard
)
528 maybe_end_group (char *d
, int do_group
, int *was_wildcard
)
540 /* If shell patterns are on converts a shell pattern to a regular
541 expression. Called by regexp_match and mask_rename. */
542 /* Shouldn't we support [a-fw] type wildcards as well ?? */
544 convert_pattern (const char *pattern
, int match_type
, int do_group
)
548 int was_wildcard
= 0;
551 if ((match_type
!= match_regex
) && easy_patterns
){
552 new_pattern
= g_malloc (MC_MAXPATHLEN
);
554 if (match_type
== match_file
)
556 for (s
= pattern
; *s
; s
++, d
++){
559 d
= maybe_start_group (d
, do_group
, &was_wildcard
);
565 d
= maybe_start_group (d
, do_group
, &was_wildcard
);
570 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
576 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
581 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
582 if (match_type
== match_file
)
587 return g_strdup (pattern
);
591 regexp_match (const char *pattern
, const char *string
, int match_type
)
594 static char *old_pattern
= NULL
;
599 if (!old_pattern
|| STRCOMP (old_pattern
, pattern
) || old_type
!= match_type
){
602 g_free (old_pattern
);
605 my_pattern
= convert_pattern (pattern
, match_type
, 0);
606 if (regcomp (&r
, my_pattern
, REG_EXTENDED
|REG_NOSUB
|MC_ARCH_FLAGS
)) {
610 old_pattern
= my_pattern
;
611 old_type
= match_type
;
613 rval
= !regexec (&r
, string
, 0, NULL
, 0);
618 extension (const char *filename
)
620 const char *d
= strrchr (filename
, '.');
621 return (d
!= NULL
) ? d
+ 1 : "";
625 get_int (const char *file
, const char *key
, int def
)
627 return GetPrivateProfileInt (app_text
, key
, def
, file
);
631 set_int (const char *file
, const char *key
, int value
)
633 char buffer
[BUF_TINY
];
635 g_snprintf (buffer
, sizeof (buffer
), "%d", value
);
636 return WritePrivateProfileString (app_text
, key
, buffer
, file
);
640 get_config_string (const char *file
, const char *key
, const char *defval
)
643 (void)GetPrivateProfileString (app_text
, key
, defval
, buffer
, sizeof(buffer
), file
);
644 return g_strdup (buffer
);
648 set_config_string (const char *file
, const char *key
, const char *val
)
650 (void)WritePrivateProfileString (app_text
, key
, val
, file
);
654 exist_file (const char *name
)
656 return access (name
, R_OK
) == 0;
660 load_file (const char *filename
)
667 if ((data_file
= fopen (filename
, "r")) == NULL
){
670 if (fstat (fileno (data_file
), &s
) != 0){
674 data
= g_malloc (s
.st_size
+1);
675 read_size
= fread (data
, 1, s
.st_size
, data_file
);
676 data
[read_size
] = 0;
688 load_mc_home_file (const char *filename
, char **allocated_filename
)
690 char *hintfile_base
, *hintfile
;
694 hintfile_base
= concat_dir_and_file (mc_home
, filename
);
695 lang
= guess_message_value ();
697 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
698 data
= load_file (hintfile
);
702 /* Fall back to the two-letter language code */
703 if (lang
[0] && lang
[1])
705 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
706 data
= load_file (hintfile
);
710 hintfile
= hintfile_base
;
711 data
= load_file (hintfile_base
);
717 if (hintfile
!= hintfile_base
)
718 g_free (hintfile_base
);
720 if (allocated_filename
)
721 *allocated_filename
= hintfile
;
728 /* Check strftime() results. Some systems (i.e. Solaris) have different
729 short-month-name sizes for different locales */
731 i18n_checktimelength (void)
733 time_t testtime
= time (NULL
);
734 struct tm
* lt
= localtime(&testtime
);
738 // huh, localtime() doesnt seem to work ... falling back to "(invalid)"
739 length
= strlen(INVALID_TIME_TEXT
);
741 char buf
[MAX_I18NTIMELENGTH
+ 1];
743 a
= strftime (buf
, sizeof(buf
)-1, _("%b %e %H:%M"), lt
);
744 b
= strftime (buf
, sizeof(buf
)-1, _("%b %e %Y"), lt
);
748 /* Don't handle big differences. Use standard value (email bug, please) */
749 if ( length
> MAX_I18NTIMELENGTH
|| length
< MIN_I18NTIMELENGTH
)
750 length
= STD_I18NTIMELENGTH
;
756 file_date (time_t when
)
758 static char timebuf
[MAX_I18NTIMELENGTH
+ 1];
759 time_t current_time
= time ((time_t) 0);
760 static size_t i18n_timelength
= 0;
761 static const char *fmtyear
, *fmttime
;
764 if (i18n_timelength
== 0){
765 i18n_timelength
= i18n_checktimelength() + 1;
767 /* strftime() format string for old dates */
768 fmtyear
= _("%b %e %Y");
769 /* strftime() format string for recent dates */
770 fmttime
= _("%b %e %H:%M");
773 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
774 || current_time
< when
- 60L * 60L) /* In the future. */
775 /* The file is fairly old or in the future.
776 POSIX says the cutoff is 6 months old;
777 approximate this by 6*30 days.
778 Allow a 1 hour slop factor for what is considered "the future",
779 to allow for NFS server/client clock disagreement.
780 Show the year instead of the time of day. */
786 FMT_LOCALTIME(timebuf
, i18n_timelength
, fmt
, when
);
792 extract_line (const char *s
, const char *top
)
794 static char tmp_line
[BUF_MEDIUM
];
797 while (*s
&& *s
!= '\n' && (size_t) (t
- tmp_line
) < sizeof (tmp_line
)-1 && s
< top
)
803 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
805 _icase_search (const char *text
, const char *data
, int *lng
)
807 const char *d
= text
;
808 const char *e
= data
;
814 while (*(e
+1) == '\b' && *(e
+2)) {
818 if (toupper((unsigned char) *d
) == toupper((unsigned char) *e
))
827 *lng
= strlen (text
) + dlng
;
834 /* The basename routine */
836 x_basename (const char *s
)
839 return ((where
= strrchr (s
, PATH_SEP
))) ? where
+ 1 : s
;
844 unix_error_string (int error_num
)
846 static char buffer
[BUF_LARGE
];
847 #if GLIB_MAJOR_VERSION >= 2
848 gchar
*strerror_currentlocale
;
850 strerror_currentlocale
= g_locale_from_utf8(g_strerror (error_num
), -1, NULL
, NULL
, NULL
);
851 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
852 strerror_currentlocale
, error_num
);
853 g_free(strerror_currentlocale
);
855 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
856 g_strerror (error_num
), error_num
);
862 skip_separators (const char *s
)
865 if (*s
!= ' ' && *s
!= '\t' && *s
!= ',')
871 skip_numbers (const char *s
)
874 if (!isdigit ((unsigned char) *s
))
879 /* Remove all control sequences from the argument string. We define
880 * "control sequence", in a sort of pidgin BNF, as follows:
882 * control-seq = Esc non-'['
883 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
885 * This scheme works for all the terminals described in my termcap /
886 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
887 * terminals. If I hear from a single person who uses such a terminal
888 * with MC, I'll be glad to add support for it. (Dugan)
889 * Non-printable characters are also removed.
893 strip_ctrl_codes (char *s
)
895 char *w
; /* Current position where the stripped data is written */
896 char *r
; /* Current position where the original data is read */
901 for (w
= s
, r
= s
; *r
; ) {
902 if (*r
== ESC_CHAR
) {
903 /* Skip the control sequence's arguments */ ;
905 /* strchr() matches trailing binary 0 */
906 while (*(++r
) && strchr ("0123456789;?", *r
));
910 * Skip xterm's OSC (Operating System Command)
911 * http://www.xfree86.org/current/ctlseqs.html
917 for (; *new_r
; ++new_r
)
927 if (*(new_r
+ 1) == '\\')
938 * Now we are at the last character of the sequence.
939 * Skip it unless it's binary 0.
946 if (is_printable(*r
))
957 get_current_wd (char *buffer
, int size
)
962 p
= g_get_current_dir ();
970 memcpy (buffer
, p
, len
);
975 #endif /* !USE_VFS */
977 enum compression_type
978 get_compression_type (int fd
)
980 unsigned char magic
[4];
982 /* Read the magic signature */
983 if (mc_read (fd
, (char *) magic
, 4) != 4)
984 return COMPRESSION_NONE
;
986 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
987 if (magic
[0] == 037 && (magic
[1] == 0213 || magic
[1] == 0236)) {
988 return COMPRESSION_GZIP
;
992 if (magic
[0] == 0120 && magic
[1] == 0113 && magic
[2] == 003
993 && magic
[3] == 004) {
994 /* Read compression type */
995 mc_lseek (fd
, 8, SEEK_SET
);
996 if (mc_read (fd
, (char *) magic
, 2) != 2)
997 return COMPRESSION_NONE
;
999 /* Gzip can handle only deflated (8) or stored (0) files */
1000 if ((magic
[0] != 8 && magic
[0] != 0) || magic
[1] != 0)
1001 return COMPRESSION_NONE
;
1003 /* Compatible with gzip */
1004 return COMPRESSION_GZIP
;
1007 /* PACK_MAGIC and LZH_MAGIC and compress magic */
1009 && (magic
[1] == 036 || magic
[1] == 0240 || magic
[1] == 0235)) {
1010 /* Compatible with gzip */
1011 return COMPRESSION_GZIP
;
1014 /* BZIP and BZIP2 files */
1015 if ((magic
[0] == 'B') && (magic
[1] == 'Z') &&
1016 (magic
[3] >= '1') && (magic
[3] <= '9')) {
1019 return COMPRESSION_BZIP
;
1021 return COMPRESSION_BZIP2
;
1028 decompress_extension (int type
)
1031 case COMPRESSION_GZIP
: return "#ugz";
1032 case COMPRESSION_BZIP
: return "#ubz";
1033 case COMPRESSION_BZIP2
: return "#ubz2";
1035 /* Should never reach this place */
1036 fprintf (stderr
, "Fatal: decompress_extension called with an unknown argument\n");
1042 add_hook (Hook
**hook_list
, void (*hook_fn
)(void *), void *data
)
1044 Hook
*new_hook
= g_new (Hook
, 1);
1046 new_hook
->hook_fn
= hook_fn
;
1047 new_hook
->next
= *hook_list
;
1048 new_hook
->hook_data
= data
;
1050 *hook_list
= new_hook
;
1054 execute_hooks (Hook
*hook_list
)
1059 /* We copy the hook list first so tahat we let the hook
1060 * function call delete_hook
1064 add_hook (&new_hook
, hook_list
->hook_fn
, hook_list
->hook_data
);
1065 hook_list
= hook_list
->next
;
1070 (*new_hook
->hook_fn
)(new_hook
->hook_data
);
1071 new_hook
= new_hook
->next
;
1074 for (hook_list
= p
; hook_list
;){
1076 hook_list
= hook_list
->next
;
1082 delete_hook (Hook
**hook_list
, void (*hook_fn
)(void *))
1084 Hook
*current
, *new_list
, *next
;
1088 for (current
= *hook_list
; current
; current
= next
){
1089 next
= current
->next
;
1090 if (current
->hook_fn
== hook_fn
)
1093 add_hook (&new_list
, current
->hook_fn
, current
->hook_data
);
1095 *hook_list
= new_list
;
1099 hook_present (Hook
*hook_list
, void (*hook_fn
)(void *))
1103 for (p
= hook_list
; p
; p
= p
->next
)
1104 if (p
->hook_fn
== hook_fn
)
1110 wipe_password (char *passwd
)
1121 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1122 /* Returns a newly allocated string */
1124 convert_controls (const char *p
)
1126 char *valcopy
= g_strdup (p
);
1129 /* Parse the escape special character */
1130 for (q
= valcopy
; *p
;){
1133 if ((*p
== 'e') || (*p
== 'E')){
1143 char c
= (*p
| 0x20);
1144 if (c
>= 'a' && c
<= 'z') {
1159 resolve_symlinks (const char *path
)
1161 char *buf
, *buf2
, *q
, *r
, c
;
1166 if (*path
!= PATH_SEP
)
1168 r
= buf
= g_malloc (MC_MAXPATHLEN
);
1169 buf2
= g_malloc (MC_MAXPATHLEN
);
1174 q
= strchr (p
+ 1, PATH_SEP
);
1176 q
= strchr (p
+ 1, 0);
1182 if (mc_lstat (path
, &mybuf
) < 0) {
1188 if (!S_ISLNK (mybuf
.st_mode
))
1191 len
= mc_readlink (path
, buf2
, MC_MAXPATHLEN
- 1);
1199 if (*buf2
== PATH_SEP
)
1204 canonicalize_pathname (buf
);
1205 r
= strchr (buf
, 0);
1206 if (!*r
|| *(r
- 1) != PATH_SEP
) {
1216 strcpy (buf
, PATH_SEP_STR
);
1217 else if (*(r
- 1) == PATH_SEP
&& r
!= buf
+ 1)
1223 /* Finds out a relative path from first to second, i.e. goes as many ..
1224 * as needed up in first and then goes down using second */
1226 diff_two_paths (const char *first
, const char *second
)
1228 char *p
, *q
, *r
, *s
, *buf
= NULL
;
1229 int i
, j
, prevlen
= -1, currlen
;
1230 char *my_first
= NULL
, *my_second
= NULL
;
1232 my_first
= resolve_symlinks (first
);
1233 if (my_first
== NULL
)
1235 my_second
= resolve_symlinks (second
);
1236 if (my_second
== NULL
) {
1240 for (j
= 0; j
< 2; j
++) {
1244 r
= strchr (p
, PATH_SEP
);
1245 s
= strchr (q
, PATH_SEP
);
1249 if (strcmp (p
, q
)) {
1250 *r
= PATH_SEP
; *s
= PATH_SEP
;
1253 *r
= PATH_SEP
; *s
= PATH_SEP
;
1259 for (i
= 0; (p
= strchr (p
+ 1, PATH_SEP
)) != NULL
; i
++);
1260 currlen
= (i
+ 1) * 3 + strlen (q
) + 1;
1262 if (currlen
< prevlen
)
1270 p
= buf
= g_malloc (currlen
);
1272 for (; i
>= 0; i
--, p
+= 3)
1281 /* If filename is NULL, then we just append PATH_SEP to the dir */
1283 concat_dir_and_file (const char *dir
, const char *file
)
1285 int i
= strlen (dir
);
1287 if (dir
[i
-1] == PATH_SEP
)
1288 return g_strconcat (dir
, file
, (char *) NULL
);
1290 return g_strconcat (dir
, PATH_SEP_STR
, file
, (char *) NULL
);
1293 /* Append text to GList, remove all entries with the same text */
1295 list_append_unique (GList
*list
, char *text
)
1297 GList
*link
, *newlink
;
1300 * Go to the last position and traverse the list backwards
1301 * starting from the second last entry to make sure that we
1302 * are not removing the current link.
1304 list
= g_list_append (list
, text
);
1305 list
= g_list_last (list
);
1306 link
= g_list_previous (list
);
1309 newlink
= g_list_previous (link
);
1310 if (!strcmp ((char *) link
->data
, text
)) {
1311 g_free (link
->data
);
1312 g_list_remove_link (list
, link
);
1313 g_list_free_1 (link
);
1321 /* Following code heavily borrows from libiberty, mkstemps.c */
1323 /* Number of attempts to create a temporary file */
1325 #define TMP_MAX 16384
1326 #endif /* !TMP_MAX */
1330 * pname (output) - pointer to the name of the temp file (needs g_free).
1331 * NULL if the function fails.
1332 * prefix - part of the filename before the random part.
1333 * Prepend $TMPDIR or /tmp if there are no path separators.
1334 * suffix - if not NULL, part of the filename after the random part.
1337 * handle of the open file or -1 if couldn't open any.
1340 mc_mkstemps (char **pname
, const char *prefix
, const char *suffix
)
1342 static const char letters
[]
1343 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1344 static unsigned long value
;
1351 if (strchr (prefix
, PATH_SEP
) == NULL
) {
1352 /* Add prefix first to find the position of XXXXXX */
1353 tmpbase
= concat_dir_and_file (mc_tmpdir (), prefix
);
1355 tmpbase
= g_strdup (prefix
);
1358 tmpname
= g_strconcat (tmpbase
, "XXXXXX", suffix
, (char *) NULL
);
1360 XXXXXX
= &tmpname
[strlen (tmpbase
)];
1363 /* Get some more or less random data. */
1364 gettimeofday (&tv
, NULL
);
1365 value
+= (tv
.tv_usec
<< 16) ^ tv
.tv_sec
^ getpid ();
1367 for (count
= 0; count
< TMP_MAX
; ++count
) {
1368 unsigned long v
= value
;
1371 /* Fill in the random bits. */
1372 XXXXXX
[0] = letters
[v
% 62];
1374 XXXXXX
[1] = letters
[v
% 62];
1376 XXXXXX
[2] = letters
[v
% 62];
1378 XXXXXX
[3] = letters
[v
% 62];
1380 XXXXXX
[4] = letters
[v
% 62];
1382 XXXXXX
[5] = letters
[v
% 62];
1384 fd
= open (tmpname
, O_RDWR
| O_CREAT
| O_TRUNC
| O_EXCL
,
1387 /* Successfully created. */
1391 /* This is a random value. It is only necessary that the next
1392 TMP_MAX values generated by adding 7777 to VALUE are different
1393 with (module 2^32). */
1397 /* Unsuccessful. Free the filename. */
1405 * Read and restore position for the given filename.
1406 * If there is no stored data, return line 1 and col 0.
1409 load_file_position (const char *filename
, long *line
, long *column
)
1413 char buf
[MC_MAXPATHLEN
+ 20];
1420 /* open file with positions */
1421 fn
= concat_dir_and_file (home_dir
, MC_FILEPOS
);
1422 f
= fopen (fn
, "r");
1427 len
= strlen (filename
);
1429 while (fgets (buf
, sizeof (buf
), f
)) {
1432 /* check if the filename matches the beginning of string */
1433 if (strncmp (buf
, filename
, len
) != 0)
1436 /* followed by single space */
1437 if (buf
[len
] != ' ')
1440 /* and string without spaces */
1442 if (strchr (p
, ' '))
1445 *line
= strtol(p
, const_cast(char **, &p
), 10);
1447 *column
= strtol(p
+1, const_cast(char **, &p
), 10);
1456 /* Save position for the given file */
1458 save_file_position (const char *filename
, long line
, long column
)
1462 char buf
[MC_MAXPATHLEN
+ 20];
1466 len
= strlen (filename
);
1468 tmp
= concat_dir_and_file (home_dir
, MC_FILEPOS_TMP
);
1469 fn
= concat_dir_and_file (home_dir
, MC_FILEPOS
);
1471 /* open temporary file */
1472 t
= fopen (tmp
, "w");
1479 /* put the new record */
1480 if (line
!= 1 || column
!= 0) {
1481 fprintf (t
, "%s %ld;%ld\n", filename
, line
, column
);
1484 /* copy records from the old file */
1485 f
= fopen (fn
, "r");
1487 while (fgets (buf
, sizeof (buf
), f
)) {
1488 /* Skip entries for the current filename */
1489 if (strncmp (buf
, filename
, len
) == 0 && buf
[len
] == ' '
1490 && !strchr (&buf
[len
+ 1], ' '))
1493 fprintf (t
, "%s", buf
);
1494 if (++i
> MC_FILEPOS_ENTRIES
)
1507 cstrcasestr (const char *haystack
, const char *needle
)
1510 size_t i
, needle_len
;
1512 needle_len
= strlen (needle
);
1513 for (hptr
= haystack
; *hptr
!= '\0'; hptr
++) {
1514 for (i
= 0; i
< needle_len
; i
++) {
1515 if (toupper ((unsigned char) hptr
[i
]) !=
1516 toupper ((unsigned char) needle
[i
]))
1527 cstrstr (const char *haystack
, const char *needle
)
1529 return strstr(haystack
, needle
);
1533 str_unconst (const char *s
)
1538 #define ASCII_A (0x40 + 1)
1539 #define ASCII_Z (0x40 + 26)
1540 #define ASCII_a (0x60 + 1)
1541 #define ASCII_z (0x60 + 26)
1544 ascii_alpha_to_cntrl (int ch
)
1546 if ((ch
>= ASCII_A
&& ch
<= ASCII_Z
)
1547 || (ch
>= ASCII_a
&& ch
<= ASCII_z
)) {
1556 const char *result
, *sep
;
1559 sep
= strchr(result
, '|');
1560 return (sep
!= NULL
) ? sep
+ 1 : result
;
1563 #define shell_escape_toesc(x) \
1564 (((x)==' ')||((x)=='!')||((x)=='#')||((x)=='$')||((x)=='%')|| \
1565 ((x)=='(')||((x)==')')||((x)=='\'')||((x)=='&')||((x)=='~')|| \
1566 ((x)=='{')||((x)=='}')||((x)=='[')||((x)==']')||((x)=='`')|| \
1567 ((x)=='?')||((x)=='|')||((x)=='<')||((x)=='>')||((x)==';')|| \
1568 ((x)=='*')||((x)=='\\')||((x)=='"'))
1570 #define shell_escape_nottoesc(x) \
1571 (((x)!=0) && (!shell_escape_toesc((x))))
1572 /** To be compatible with the general posix command lines we have to escape
1573 strings for the command line
1579 return escaped string (which needs to be freed later)
1582 shell_escape(const char* src
)
1585 char *result
= NULL
;
1587 if ((src
==NULL
)||(!(*src
)))
1590 str
= g_string_new("");
1592 /* look for the first char to escape */
1596 /* copy over all chars not to escape */
1597 while ((c
=(*src
)) && shell_escape_nottoesc(c
))
1599 g_string_append_c(str
,c
);
1603 /* at this point we either have an \0 or an char to escape */
1606 g_string_free(str
,FALSE
);
1610 g_string_append_c(str
,'\\');
1611 g_string_append_c(str
,c
);
1616 /** Unescape paths or other strings for e.g the internal cd
1617 shell-unescape within a given buffer (writing to it!)
1620 string for unescaping
1623 return unescaped string (which needs to be freed)
1626 shell_unescape(const char* text
)
1629 char *result
= NULL
;
1635 /* look for the first \ - that's quick skipover if there's nothing to escape */
1636 const char* readptr
= text
;
1637 while ((*readptr
) && ((*readptr
)!='\\')) readptr
++;
1639 result
= g_strdup(text
);
1642 str
= g_string_new_len(text
, readptr
- text
);
1644 /* if we're here, we're standing on the first '\' */
1646 while ((c
= *readptr
))
1651 switch ((c
= *readptr
))
1653 case '\0': /* end of string! malformed escape string */
1656 case 'n': g_string_append_c(str
,'\n'); break;
1657 case 'r': g_string_append_c(str
,'\r'); break;
1658 case 't': g_string_append_c(str
,'\t'); break;
1681 g_string_append_c(str
,c
); break;
1684 else /* got a normal character */
1686 g_string_append_c(str
,c
);
1693 g_string_free(str
,FALSE
);
1697 /** Check if char in pointer contain escape'd chars
1703 return TRUE if string contain escaped chars
1704 otherwise return FALSE
1707 shell_is_char_escaped ( const char *in
)
1709 if (in
== NULL
|| !*in
|| in
[0] != '\\')
1711 if (shell_escape_toesc(in
[1]))