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. */
26 * \brief Source: various utilities
37 #include <sys/types.h>
43 #include "main.h" /* mc_home */
44 #include "cmd.h" /* guess_message_value */
45 #include "mountlist.h"
46 #include "win.h" /* xterm_flag */
53 static const char app_text
[] = "Midnight-Commander";
54 int easy_patterns
= 1;
56 extern void str_replace(char *s
, char from
, char to
)
58 for (; *s
!= '\0'; s
++) {
65 is_7bit_printable (unsigned char c
)
67 return (c
> 31 && c
< 127);
71 is_iso_printable (unsigned char c
)
73 return ((c
> 31 && c
< 127) || c
>= 160);
77 is_8bit_printable (unsigned char c
)
79 /* "Full 8 bits output" doesn't work on xterm */
81 return is_iso_printable (c
);
83 return (c
> 31 && c
!= 127 && c
!= 155);
92 /* "Display bits" is ignored, since the user controls the output
93 by setting the output codepage */
94 return is_8bit_printable (c
);
97 return is_7bit_printable (c
);
99 if (full_eight_bits
) {
100 return is_8bit_printable (c
);
102 return is_iso_printable (c
);
103 #endif /* !HAVE_CHARSET */
106 /* Calculates the message dimensions (lines and columns) */
108 msglen (const char *text
, int *lines
, int *columns
)
110 int nlines
= 1; /* even the empty string takes one line */
114 for (; *text
!= '\0'; text
++) {
120 if (colindex
> ncolumns
)
130 * Copy from s to d, and trim the beginning if necessary, and prepend
131 * "..." in this case. The destination string can have at most len
132 * bytes, not counting trailing 0.
135 trim (const char *s
, char *d
, int len
)
142 source_len
= strlen (s
);
143 if (source_len
> len
) {
144 /* Cannot fit the whole line */
146 /* We only have room for the dots */
147 memset (d
, '.', len
);
151 /* Begin with ... and add the rest of the source string */
153 strcpy (d
+ 3, s
+ 3 + source_len
- len
);
156 /* We can copy the whole line */
162 * Quote the filename for the purpose of inserting it into the command
163 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
164 * processed by the mc command line.
167 name_quote (const char *s
, int quote_percent
)
171 d
= ret
= g_malloc (strlen (s
) * 2 + 2 + 1);
177 for (; *s
; s
++, d
++) {
221 fake_name_quote (const char *s
, int quote_percent
)
223 (void) quote_percent
;
228 * Remove the middle part of the string to fit given length.
229 * Use "~" to show where the string was truncated.
230 * Return static buffer, no need to free() it.
233 name_trunc (const char *txt
, size_t trunc_len
)
235 static char x
[MC_MAXPATHLEN
+ MC_MAXPATHLEN
];
244 if (trunc_len
> sizeof (x
) - 1) {
245 trunc_len
= sizeof (x
) - 1;
247 txt_len
= strlen (txt
);
248 if (txt_len
<= trunc_len
) {
251 size_t y
= (trunc_len
/ 2) + (trunc_len
% 2);
252 strncpy (x
, txt
, (size_t) y
);
253 strncpy (x
+ y
, txt
+ (txt_len
- (trunc_len
/ 2)), trunc_len
/ 2);
258 if (!is_printable (*p
))
264 * path_trunc() is the same as name_trunc() above but
265 * it deletes possible password from path for security
269 path_trunc (const char *path
, size_t trunc_len
) {
271 char *secure_path
= strip_password (g_strdup (path
), 1);
273 ret
= name_trunc (secure_path
, trunc_len
);
274 g_free (secure_path
);
280 size_trunc (double size
)
282 static char x
[BUF_TINY
];
283 long int divisor
= 1;
284 const char *xtra
= "";
286 if (size
> 999999999L){
289 if (size
/divisor
> 999999999L){
294 g_snprintf (x
, sizeof (x
), "%.0f%s", (size
/divisor
), xtra
);
299 size_trunc_sep (double size
)
306 p
= y
= size_trunc (size
);
308 d
= x
+ sizeof (x
) - 1;
310 while (p
>= y
&& isalpha ((unsigned char) *p
))
312 for (count
= 0; p
>= y
; count
++){
326 * Print file SIZE to BUFFER, but don't exceed LEN characters,
327 * not including trailing 0. BUFFER should be at least LEN+1 long.
328 * This function is called for every file on panels, so avoid
329 * floating point by any means.
331 * Units: size units (filesystem sizes are 1K blocks)
332 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
335 size_trunc_len (char *buffer
, int len
, off_t size
, int units
)
337 /* Avoid taking power for every file. */
338 static const off_t power10
[] =
339 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
341 static const char * const suffix
[] =
342 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL
};
345 /* Don't print more than 9 digits - use suffix. */
346 if (len
== 0 || len
> 9)
349 for (j
= units
; suffix
[j
] != NULL
; j
++) {
352 /* Empty files will print "0" even with minimal width. */
353 g_snprintf (buffer
, len
+ 1, "0");
357 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
358 g_snprintf (buffer
, len
+ 1, (len
> 1) ? "~%s" : "%s",
359 (j
> 1) ? suffix
[j
- 1] : "B");
363 if (size
< power10
[len
- (j
> 0)]) {
364 g_snprintf (buffer
, len
+ 1, "%lu%s", (unsigned long) size
, suffix
[j
]);
368 /* Powers of 1024, with rounding. */
369 size
= (size
+ 512) >> 10;
376 if ((S_IXUSR
& mode
) || (S_IXGRP
& mode
) || (S_IXOTH
& mode
))
381 #define ismode(n,m) ((n & m) == m)
384 string_perm (mode_t mode_bits
)
386 static char mode
[11];
388 strcpy (mode
, "----------");
389 if (S_ISDIR (mode_bits
))
391 if (S_ISCHR (mode_bits
))
393 if (S_ISBLK (mode_bits
))
395 if (S_ISLNK (mode_bits
))
397 if (S_ISFIFO (mode_bits
))
399 if (S_ISNAM (mode_bits
))
401 if (S_ISSOCK (mode_bits
))
403 if (S_ISDOOR (mode_bits
))
405 if (ismode (mode_bits
, S_IXOTH
))
407 if (ismode (mode_bits
, S_IWOTH
))
409 if (ismode (mode_bits
, S_IROTH
))
411 if (ismode (mode_bits
, S_IXGRP
))
413 if (ismode (mode_bits
, S_IWGRP
))
415 if (ismode (mode_bits
, S_IRGRP
))
417 if (ismode (mode_bits
, S_IXUSR
))
419 if (ismode (mode_bits
, S_IWUSR
))
421 if (ismode (mode_bits
, S_IRUSR
))
424 if (ismode (mode_bits
, S_ISUID
))
425 mode
[3] = (mode
[3] == 'x') ? 's' : 'S';
428 if (ismode (mode_bits
, S_ISGID
))
429 mode
[6] = (mode
[6] == 'x') ? 's' : 'S';
432 if (ismode (mode_bits
, S_ISVTX
))
433 mode
[9] = (mode
[9] == 'x') ? 't' : 'T';
438 /* p: string which might contain an url with a password (this parameter is
440 has_prefix = 0: The first parameter is an url without a prefix
441 (user[:pass]@]machine[:port][remote-dir). Delete
443 has_prefix = 1: Search p for known url prefixes. If found delete
444 the password from the url.
445 Caveat: only the first url is found
448 strip_password (char *p
, int has_prefix
)
450 static const struct {
453 } prefixes
[] = { {"/#ftp:", 6},
463 char *at
, *inner_colon
, *dir
;
467 for (i
= 0; i
< sizeof (prefixes
)/sizeof (prefixes
[0]); i
++) {
471 if((q
= strstr (p
, prefixes
[i
].name
)) == 0)
474 p
= q
+ prefixes
[i
].len
;
477 if ((dir
= strchr (p
, PATH_SEP
)) != NULL
)
480 /* search for any possible user */
481 at
= strrchr (p
, '@');
486 /* We have a username */
488 inner_colon
= memchr (p
, ':', at
- p
);
490 memmove (inner_colon
, at
, strlen(at
) + 1);
498 strip_home_and_password(const char *dir
)
501 static char newdir
[MC_MAXPATHLEN
];
503 if (home_dir
&& !strncmp (dir
, home_dir
, len
= strlen (home_dir
)) &&
504 (dir
[len
] == PATH_SEP
|| dir
[len
] == '\0')){
506 g_strlcpy (&newdir
[1], &dir
[len
], sizeof(newdir
) - 1);
510 /* We do not strip homes in /#ftp tree, I do not like ~'s there
512 g_strlcpy (newdir
, dir
, sizeof(newdir
));
513 strip_password (newdir
, 1);
518 maybe_start_group (char *d
, int do_group
, int *was_wildcard
)
531 maybe_end_group (char *d
, int do_group
, int *was_wildcard
)
543 /* If shell patterns are on converts a shell pattern to a regular
544 expression. Called by regexp_match and mask_rename. */
545 /* Shouldn't we support [a-fw] type wildcards as well ?? */
547 convert_pattern (const char *pattern
, int match_type
, int do_group
)
551 int was_wildcard
= 0;
554 if ((match_type
!= match_regex
) && easy_patterns
){
555 new_pattern
= g_malloc (MC_MAXPATHLEN
);
557 if (match_type
== match_file
)
559 for (s
= pattern
; *s
; s
++, d
++){
562 d
= maybe_start_group (d
, do_group
, &was_wildcard
);
568 d
= maybe_start_group (d
, do_group
, &was_wildcard
);
573 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
579 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
584 d
= maybe_end_group (d
, do_group
, &was_wildcard
);
585 if (match_type
== match_file
)
590 return g_strdup (pattern
);
594 regexp_match (const char *pattern
, const char *string
, int match_type
)
597 static char *old_pattern
= NULL
;
602 if (!old_pattern
|| STRCOMP (old_pattern
, pattern
) || old_type
!= match_type
){
605 g_free (old_pattern
);
608 my_pattern
= convert_pattern (pattern
, match_type
, 0);
609 if (regcomp (&r
, my_pattern
, REG_EXTENDED
|REG_NOSUB
|MC_ARCH_FLAGS
)) {
613 old_pattern
= my_pattern
;
614 old_type
= match_type
;
616 rval
= !regexec (&r
, string
, 0, NULL
, 0);
621 extension (const char *filename
)
623 const char *d
= strrchr (filename
, '.');
624 return (d
!= NULL
) ? d
+ 1 : "";
628 get_int (const char *file
, const char *key
, int def
)
630 return GetPrivateProfileInt (app_text
, key
, def
, file
);
634 set_int (const char *file
, const char *key
, int value
)
636 char buffer
[BUF_TINY
];
638 g_snprintf (buffer
, sizeof (buffer
), "%d", value
);
639 return WritePrivateProfileString (app_text
, key
, buffer
, file
);
643 get_config_string (const char *file
, const char *key
, const char *defval
)
646 (void)GetPrivateProfileString (app_text
, key
, defval
, buffer
, sizeof(buffer
), file
);
647 return g_strdup (buffer
);
651 set_config_string (const char *file
, const char *key
, const char *val
)
653 (void)WritePrivateProfileString (app_text
, key
, val
, file
);
657 exist_file (const char *name
)
659 return access (name
, R_OK
) == 0;
663 load_file (const char *filename
)
670 if ((data_file
= fopen (filename
, "r")) == NULL
){
673 if (fstat (fileno (data_file
), &s
) != 0){
677 data
= g_malloc (s
.st_size
+1);
678 read_size
= fread (data
, 1, s
.st_size
, data_file
);
679 data
[read_size
] = 0;
691 load_mc_home_file (const char *filename
, char **allocated_filename
)
693 char *hintfile_base
, *hintfile
;
697 hintfile_base
= concat_dir_and_file (mc_home
, filename
);
698 lang
= guess_message_value ();
700 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
701 data
= load_file (hintfile
);
705 /* Fall back to the two-letter language code */
706 if (lang
[0] && lang
[1])
708 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
709 data
= load_file (hintfile
);
713 hintfile
= hintfile_base
;
714 data
= load_file (hintfile_base
);
720 if (hintfile
!= hintfile_base
)
721 g_free (hintfile_base
);
723 if (allocated_filename
)
724 *allocated_filename
= hintfile
;
731 /* Check strftime() results. Some systems (i.e. Solaris) have different
732 short-month-name sizes for different locales */
734 i18n_checktimelength (void)
736 time_t testtime
= time (NULL
);
737 struct tm
* lt
= localtime(&testtime
);
741 // huh, localtime() doesnt seem to work ... falling back to "(invalid)"
742 length
= strlen(INVALID_TIME_TEXT
);
744 char buf
[MAX_I18NTIMELENGTH
+ 1];
746 a
= strftime (buf
, sizeof(buf
)-1, _("%b %e %H:%M"), lt
);
747 b
= strftime (buf
, sizeof(buf
)-1, _("%b %e %Y"), lt
);
751 /* Don't handle big differences. Use standard value (email bug, please) */
752 if ( length
> MAX_I18NTIMELENGTH
|| length
< MIN_I18NTIMELENGTH
)
753 length
= STD_I18NTIMELENGTH
;
759 file_date (time_t when
)
761 static char timebuf
[MAX_I18NTIMELENGTH
+ 1];
762 time_t current_time
= time ((time_t) 0);
763 static size_t i18n_timelength
= 0;
764 static const char *fmtyear
, *fmttime
;
767 if (i18n_timelength
== 0){
768 i18n_timelength
= i18n_checktimelength() + 1;
770 /* strftime() format string for old dates */
771 fmtyear
= _("%b %e %Y");
772 /* strftime() format string for recent dates */
773 fmttime
= _("%b %e %H:%M");
776 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
777 || current_time
< when
- 60L * 60L) /* In the future. */
778 /* The file is fairly old or in the future.
779 POSIX says the cutoff is 6 months old;
780 approximate this by 6*30 days.
781 Allow a 1 hour slop factor for what is considered "the future",
782 to allow for NFS server/client clock disagreement.
783 Show the year instead of the time of day. */
789 FMT_LOCALTIME(timebuf
, i18n_timelength
, fmt
, when
);
795 extract_line (const char *s
, const char *top
)
797 static char tmp_line
[BUF_MEDIUM
];
800 while (*s
&& *s
!= '\n' && (size_t) (t
- tmp_line
) < sizeof (tmp_line
)-1 && s
< top
)
806 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
808 _icase_search (const char *text
, const char *data
, int *lng
)
810 const char *d
= text
;
811 const char *e
= data
;
817 while (*(e
+1) == '\b' && *(e
+2)) {
821 if (toupper((unsigned char) *d
) == toupper((unsigned char) *e
))
830 *lng
= strlen (text
) + dlng
;
837 /* The basename routine */
839 x_basename (const char *s
)
842 return ((where
= strrchr (s
, PATH_SEP
))) ? where
+ 1 : s
;
847 unix_error_string (int error_num
)
849 static char buffer
[BUF_LARGE
];
850 #if GLIB_MAJOR_VERSION >= 2
851 gchar
*strerror_currentlocale
;
853 strerror_currentlocale
= g_locale_from_utf8(g_strerror (error_num
), -1, NULL
, NULL
, NULL
);
854 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
855 strerror_currentlocale
, error_num
);
856 g_free(strerror_currentlocale
);
858 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
859 g_strerror (error_num
), error_num
);
865 skip_separators (const char *s
)
868 if (*s
!= ' ' && *s
!= '\t' && *s
!= ',')
874 skip_numbers (const char *s
)
877 if (!isdigit ((unsigned char) *s
))
882 /* Remove all control sequences from the argument string. We define
883 * "control sequence", in a sort of pidgin BNF, as follows:
885 * control-seq = Esc non-'['
886 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
888 * This scheme works for all the terminals described in my termcap /
889 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
890 * terminals. If I hear from a single person who uses such a terminal
891 * with MC, I'll be glad to add support for it. (Dugan)
892 * Non-printable characters are also removed.
896 strip_ctrl_codes (char *s
)
898 char *w
; /* Current position where the stripped data is written */
899 char *r
; /* Current position where the original data is read */
904 for (w
= s
, r
= s
; *r
; ) {
905 if (*r
== ESC_CHAR
) {
906 /* Skip the control sequence's arguments */ ;
908 /* strchr() matches trailing binary 0 */
909 while (*(++r
) && strchr ("0123456789;?", *r
));
913 * Now we are at the last character of the sequence.
914 * Skip it unless it's binary 0.
921 if (is_printable(*r
))
932 get_current_wd (char *buffer
, int size
)
937 p
= g_get_current_dir ();
945 memcpy (buffer
, p
, len
);
950 #endif /* !USE_VFS */
952 enum compression_type
953 get_compression_type (int fd
)
955 unsigned char magic
[4];
957 /* Read the magic signature */
958 if (mc_read (fd
, (char *) magic
, 4) != 4)
959 return COMPRESSION_NONE
;
961 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
962 if (magic
[0] == 037 && (magic
[1] == 0213 || magic
[1] == 0236)) {
963 return COMPRESSION_GZIP
;
967 if (magic
[0] == 0120 && magic
[1] == 0113 && magic
[2] == 003
968 && magic
[3] == 004) {
969 /* Read compression type */
970 mc_lseek (fd
, 8, SEEK_SET
);
971 if (mc_read (fd
, (char *) magic
, 2) != 2)
972 return COMPRESSION_NONE
;
974 /* Gzip can handle only deflated (8) or stored (0) files */
975 if ((magic
[0] != 8 && magic
[0] != 0) || magic
[1] != 0)
976 return COMPRESSION_NONE
;
978 /* Compatible with gzip */
979 return COMPRESSION_GZIP
;
982 /* PACK_MAGIC and LZH_MAGIC and compress magic */
984 && (magic
[1] == 036 || magic
[1] == 0240 || magic
[1] == 0235)) {
985 /* Compatible with gzip */
986 return COMPRESSION_GZIP
;
989 /* BZIP and BZIP2 files */
990 if ((magic
[0] == 'B') && (magic
[1] == 'Z') &&
991 (magic
[3] >= '1') && (magic
[3] <= '9')) {
994 return COMPRESSION_BZIP
;
996 return COMPRESSION_BZIP2
;
1003 decompress_extension (int type
)
1006 case COMPRESSION_GZIP
: return "#ugz";
1007 case COMPRESSION_BZIP
: return "#ubz";
1008 case COMPRESSION_BZIP2
: return "#ubz2";
1010 /* Should never reach this place */
1011 fprintf (stderr
, "Fatal: decompress_extension called with an unknown argument\n");
1017 add_hook (Hook
**hook_list
, void (*hook_fn
)(void *), void *data
)
1019 Hook
*new_hook
= g_new (Hook
, 1);
1021 new_hook
->hook_fn
= hook_fn
;
1022 new_hook
->next
= *hook_list
;
1023 new_hook
->hook_data
= data
;
1025 *hook_list
= new_hook
;
1029 execute_hooks (Hook
*hook_list
)
1034 /* We copy the hook list first so tahat we let the hook
1035 * function call delete_hook
1039 add_hook (&new_hook
, hook_list
->hook_fn
, hook_list
->hook_data
);
1040 hook_list
= hook_list
->next
;
1045 (*new_hook
->hook_fn
)(new_hook
->hook_data
);
1046 new_hook
= new_hook
->next
;
1049 for (hook_list
= p
; hook_list
;){
1051 hook_list
= hook_list
->next
;
1057 delete_hook (Hook
**hook_list
, void (*hook_fn
)(void *))
1059 Hook
*current
, *new_list
, *next
;
1063 for (current
= *hook_list
; current
; current
= next
){
1064 next
= current
->next
;
1065 if (current
->hook_fn
== hook_fn
)
1068 add_hook (&new_list
, current
->hook_fn
, current
->hook_data
);
1070 *hook_list
= new_list
;
1074 hook_present (Hook
*hook_list
, void (*hook_fn
)(void *))
1078 for (p
= hook_list
; p
; p
= p
->next
)
1079 if (p
->hook_fn
== hook_fn
)
1085 wipe_password (char *passwd
)
1096 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1097 /* Returns a newly allocated string */
1099 convert_controls (const char *p
)
1101 char *valcopy
= g_strdup (p
);
1104 /* Parse the escape special character */
1105 for (q
= valcopy
; *p
;){
1108 if ((*p
== 'e') || (*p
== 'E')){
1118 char c
= (*p
| 0x20);
1119 if (c
>= 'a' && c
<= 'z') {
1134 resolve_symlinks (const char *path
)
1136 char *buf
, *buf2
, *q
, *r
, c
;
1141 if (*path
!= PATH_SEP
)
1143 r
= buf
= g_malloc (MC_MAXPATHLEN
);
1144 buf2
= g_malloc (MC_MAXPATHLEN
);
1149 q
= strchr (p
+ 1, PATH_SEP
);
1151 q
= strchr (p
+ 1, 0);
1157 if (mc_lstat (path
, &mybuf
) < 0) {
1163 if (!S_ISLNK (mybuf
.st_mode
))
1166 len
= mc_readlink (path
, buf2
, MC_MAXPATHLEN
- 1);
1174 if (*buf2
== PATH_SEP
)
1179 canonicalize_pathname (buf
);
1180 r
= strchr (buf
, 0);
1181 if (!*r
|| *(r
- 1) != PATH_SEP
) {
1191 strcpy (buf
, PATH_SEP_STR
);
1192 else if (*(r
- 1) == PATH_SEP
&& r
!= buf
+ 1)
1198 /* Finds out a relative path from first to second, i.e. goes as many ..
1199 * as needed up in first and then goes down using second */
1201 diff_two_paths (const char *first
, const char *second
)
1203 char *p
, *q
, *r
, *s
, *buf
= NULL
;
1204 int i
, j
, prevlen
= -1, currlen
;
1205 char *my_first
= NULL
, *my_second
= NULL
;
1207 my_first
= resolve_symlinks (first
);
1208 if (my_first
== NULL
)
1210 my_second
= resolve_symlinks (second
);
1211 if (my_second
== NULL
) {
1215 for (j
= 0; j
< 2; j
++) {
1219 r
= strchr (p
, PATH_SEP
);
1220 s
= strchr (q
, PATH_SEP
);
1224 if (strcmp (p
, q
)) {
1225 *r
= PATH_SEP
; *s
= PATH_SEP
;
1228 *r
= PATH_SEP
; *s
= PATH_SEP
;
1234 for (i
= 0; (p
= strchr (p
+ 1, PATH_SEP
)) != NULL
; i
++);
1235 currlen
= (i
+ 1) * 3 + strlen (q
) + 1;
1237 if (currlen
< prevlen
)
1245 p
= buf
= g_malloc (currlen
);
1247 for (; i
>= 0; i
--, p
+= 3)
1256 /* If filename is NULL, then we just append PATH_SEP to the dir */
1258 concat_dir_and_file (const char *dir
, const char *file
)
1260 int i
= strlen (dir
);
1262 if (dir
[i
-1] == PATH_SEP
)
1263 return g_strconcat (dir
, file
, (char *) NULL
);
1265 return g_strconcat (dir
, PATH_SEP_STR
, file
, (char *) NULL
);
1268 /* Append text to GList, remove all entries with the same text */
1270 list_append_unique (GList
*list
, char *text
)
1272 GList
*link
, *newlink
;
1275 * Go to the last position and traverse the list backwards
1276 * starting from the second last entry to make sure that we
1277 * are not removing the current link.
1279 list
= g_list_append (list
, text
);
1280 list
= g_list_last (list
);
1281 link
= g_list_previous (list
);
1284 newlink
= g_list_previous (link
);
1285 if (!strcmp ((char *) link
->data
, text
)) {
1286 g_free (link
->data
);
1287 g_list_remove_link (list
, link
);
1288 g_list_free_1 (link
);
1296 /* Following code heavily borrows from libiberty, mkstemps.c */
1298 /* Number of attempts to create a temporary file */
1300 #define TMP_MAX 16384
1301 #endif /* !TMP_MAX */
1305 * pname (output) - pointer to the name of the temp file (needs g_free).
1306 * NULL if the function fails.
1307 * prefix - part of the filename before the random part.
1308 * Prepend $TMPDIR or /tmp if there are no path separators.
1309 * suffix - if not NULL, part of the filename after the random part.
1312 * handle of the open file or -1 if couldn't open any.
1315 mc_mkstemps (char **pname
, const char *prefix
, const char *suffix
)
1317 static const char letters
[]
1318 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1319 static unsigned long value
;
1326 if (strchr (prefix
, PATH_SEP
) == NULL
) {
1327 /* Add prefix first to find the position of XXXXXX */
1328 tmpbase
= concat_dir_and_file (mc_tmpdir (), prefix
);
1330 tmpbase
= g_strdup (prefix
);
1333 tmpname
= g_strconcat (tmpbase
, "XXXXXX", suffix
, (char *) NULL
);
1335 XXXXXX
= &tmpname
[strlen (tmpbase
)];
1338 /* Get some more or less random data. */
1339 gettimeofday (&tv
, NULL
);
1340 value
+= (tv
.tv_usec
<< 16) ^ tv
.tv_sec
^ getpid ();
1342 for (count
= 0; count
< TMP_MAX
; ++count
) {
1343 unsigned long v
= value
;
1346 /* Fill in the random bits. */
1347 XXXXXX
[0] = letters
[v
% 62];
1349 XXXXXX
[1] = letters
[v
% 62];
1351 XXXXXX
[2] = letters
[v
% 62];
1353 XXXXXX
[3] = letters
[v
% 62];
1355 XXXXXX
[4] = letters
[v
% 62];
1357 XXXXXX
[5] = letters
[v
% 62];
1359 fd
= open (tmpname
, O_RDWR
| O_CREAT
| O_TRUNC
| O_EXCL
,
1362 /* Successfully created. */
1366 /* This is a random value. It is only necessary that the next
1367 TMP_MAX values generated by adding 7777 to VALUE are different
1368 with (module 2^32). */
1372 /* Unsuccessful. Free the filename. */
1380 * Read and restore position for the given filename.
1381 * If there is no stored data, return line 1 and col 0.
1384 load_file_position (const char *filename
, long *line
, long *column
)
1388 char buf
[MC_MAXPATHLEN
+ 20];
1395 /* open file with positions */
1396 fn
= concat_dir_and_file (home_dir
, MC_FILEPOS
);
1397 f
= fopen (fn
, "r");
1402 len
= strlen (filename
);
1404 while (fgets (buf
, sizeof (buf
), f
)) {
1407 /* check if the filename matches the beginning of string */
1408 if (strncmp (buf
, filename
, len
) != 0)
1411 /* followed by single space */
1412 if (buf
[len
] != ' ')
1415 /* and string without spaces */
1417 if (strchr (p
, ' '))
1420 *line
= strtol(p
, const_cast(char **, &p
), 10);
1422 *column
= strtol(p
+1, const_cast(char **, &p
), 10);
1431 /* Save position for the given file */
1433 save_file_position (const char *filename
, long line
, long column
)
1437 char buf
[MC_MAXPATHLEN
+ 20];
1441 len
= strlen (filename
);
1443 tmp
= concat_dir_and_file (home_dir
, MC_FILEPOS_TMP
);
1444 fn
= concat_dir_and_file (home_dir
, MC_FILEPOS
);
1446 /* open temporary file */
1447 t
= fopen (tmp
, "w");
1454 /* put the new record */
1455 if (line
!= 1 || column
!= 0) {
1456 fprintf (t
, "%s %ld;%ld\n", filename
, line
, column
);
1459 /* copy records from the old file */
1460 f
= fopen (fn
, "r");
1462 while (fgets (buf
, sizeof (buf
), f
)) {
1463 /* Skip entries for the current filename */
1464 if (strncmp (buf
, filename
, len
) == 0 && buf
[len
] == ' '
1465 && !strchr (&buf
[len
+ 1], ' '))
1468 fprintf (t
, "%s", buf
);
1469 if (++i
> MC_FILEPOS_ENTRIES
)
1482 cstrcasestr (const char *haystack
, const char *needle
)
1485 size_t i
, needle_len
;
1487 needle_len
= strlen (needle
);
1488 for (hptr
= haystack
; *hptr
!= '\0'; hptr
++) {
1489 for (i
= 0; i
< needle_len
; i
++) {
1490 if (toupper ((unsigned char) hptr
[i
]) !=
1491 toupper ((unsigned char) needle
[i
]))
1502 cstrstr (const char *haystack
, const char *needle
)
1504 return strstr(haystack
, needle
);
1508 str_unconst (const char *s
)
1513 #define ASCII_A (0x40 + 1)
1514 #define ASCII_Z (0x40 + 26)
1515 #define ASCII_a (0x60 + 1)
1516 #define ASCII_z (0x60 + 26)
1519 ascii_alpha_to_cntrl (int ch
)
1521 if ((ch
>= ASCII_A
&& ch
<= ASCII_Z
)
1522 || (ch
>= ASCII_a
&& ch
<= ASCII_z
)) {
1531 const char *result
, *sep
;
1534 sep
= strchr(result
, '|');
1535 return (sep
!= NULL
) ? sep
+ 1 : result
;
1538 #define shell_escape_toesc(x) \
1539 (((x)==' ')||((x)=='!')||((x)=='#')||((x)=='$')||((x)=='%')|| \
1540 ((x)=='(')||((x)==')')||((x)=='\'')||((x)=='&')||((x)=='~')|| \
1541 ((x)=='{')||((x)=='}')||((x)=='[')||((x)==']')||((x)=='`')|| \
1542 ((x)=='?')||((x)=='|')||((x)=='<')||((x)=='>')||((x)==';')|| \
1543 ((x)=='*')||((x)=='\\')||((x)=='"'))
1545 #define shell_escape_nottoesc(x) \
1546 (((x)!=0) && (!shell_escape_toesc((x))))
1548 /** To be compatible with the general posix command lines we have to escape
1549 strings for the command line
1555 return escaped string (which needs to be freed later)
1558 shell_escape(const char* src
)
1561 char *result
= NULL
;
1563 if ((src
==NULL
)||(!(*src
)))
1566 str
= g_string_new("");
1568 /* look for the first char to escape */
1572 /* copy over all chars not to escape */
1573 while ((c
=(*src
)) && shell_escape_nottoesc(c
))
1575 g_string_append_c(str
,c
);
1579 /* at this point we either have an \0 or an char to escape */
1582 g_string_free(str
,FALSE
);
1586 g_string_append_c(str
,'\\');
1587 g_string_append_c(str
,c
);
1592 /** Unescape paths or other strings for e.g the internal cd
1593 shell-unescape within a given buffer (writing to it!)
1596 string for unescaping
1599 return unescaped string (which needs to be freed)
1602 shell_unescape(const char* text
)
1605 char *result
= NULL
;
1611 /* look for the first \ - that's quick skipover if there's nothing to escape */
1612 const char* readptr
= text
;
1613 while ((*readptr
) && ((*readptr
)!='\\')) readptr
++;
1615 result
= g_strdup(text
);
1618 str
= g_string_new_len(text
, readptr
- text
);
1620 /* if we're here, we're standing on the first '\' */
1622 while ((c
= *readptr
))
1627 switch ((c
= *readptr
))
1629 case '\0': /* end of string! malformed escape string */
1632 case 'n': g_string_append_c(str
,'\n'); break;
1633 case 'r': g_string_append_c(str
,'\r'); break;
1634 case 't': g_string_append_c(str
,'\t'); break;
1657 g_string_append_c(str
,c
); break;
1660 else /* got a normal character */
1662 g_string_append_c(str
,c
);
1669 g_string_free(str
,FALSE
);
1673 /** Check if char in pointer contain escape'd chars
1679 return TRUE if string contain escaped chars
1680 otherwise return FALSE
1683 shell_is_char_escaped ( const char *in
)
1685 if (in
== NULL
|| !*in
|| in
[0] != '\\')
1687 if (shell_escape_toesc(in
[1]))