2 Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
3 2004, 2005, 2007, 2009 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
39 #include <sys/types.h>
45 #include "../src/tty/win.h" /* xterm_flag */
47 #include "../src/search/search.h"
49 #include "main.h" /* mc_home */
50 #include "cmd.h" /* guess_message_value */
51 #include "mountlist.h"
54 #include "./src/mcconfig/mcconfig.h"
55 #include "fileopctx.h"
56 #include "file.h" /* copy_file_file() */
60 #include "../vfs/vfs.h"
66 /*In order to use everywhere the same setup
67 for the locale we use defines */
68 #define FMTYEAR _("%b %e %Y")
69 #define FMTTIME _("%b %e %H:%M")
72 int easy_patterns
= 1;
74 extern void str_replace(char *s
, char from
, char to
)
76 for (; *s
!= '\0'; s
++) {
83 is_7bit_printable (unsigned char c
)
85 return (c
> 31 && c
< 127);
89 is_iso_printable (unsigned char c
)
91 return ((c
> 31 && c
< 127) || c
>= 160);
95 is_8bit_printable (unsigned char c
)
97 /* "Full 8 bits output" doesn't work on xterm */
99 return is_iso_printable (c
);
101 return (c
> 31 && c
!= 127 && c
!= 155);
110 /* "Display bits" is ignored, since the user controls the output
111 by setting the output codepage */
112 return is_8bit_printable (c
);
114 if (!eight_bit_clean
)
115 return is_7bit_printable (c
);
117 if (full_eight_bits
) {
118 return is_8bit_printable (c
);
120 return is_iso_printable (c
);
121 #endif /* !HAVE_CHARSET */
124 /* Calculates the message dimensions (lines and columns) */
126 msglen (const char *text
, int *lines
, int *columns
)
128 int nlines
= 1; /* even the empty string takes one line */
132 for (; *text
!= '\0'; text
++) {
138 if (colindex
> ncolumns
)
148 * Copy from s to d, and trim the beginning if necessary, and prepend
149 * "..." in this case. The destination string can have at most len
150 * bytes, not counting trailing 0.
153 trim (const char *s
, char *d
, int len
)
160 source_len
= strlen (s
);
161 if (source_len
> len
) {
162 /* Cannot fit the whole line */
164 /* We only have room for the dots */
165 memset (d
, '.', len
);
169 /* Begin with ... and add the rest of the source string */
171 strcpy (d
+ 3, s
+ 3 + source_len
- len
);
174 /* We can copy the whole line */
180 * Quote the filename for the purpose of inserting it into the command
181 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
182 * processed by the mc command line.
185 name_quote (const char *s
, int quote_percent
)
189 d
= ret
= g_malloc (strlen (s
) * 2 + 2 + 1);
195 for (; *s
; s
++, d
++) {
239 fake_name_quote (const char *s
, int quote_percent
)
241 (void) quote_percent
;
246 * Remove the middle part of the string to fit given length.
247 * Use "~" to show where the string was truncated.
248 * Return static buffer, no need to free() it.
251 name_trunc (const char *txt
, size_t trunc_len
)
253 return str_trunc (txt
, trunc_len
);
257 * path_trunc() is the same as name_trunc() above but
258 * it deletes possible password from path for security
262 path_trunc (const char *path
, size_t trunc_len
) {
263 char *secure_path
= strip_password (g_strdup (path
), 1);
265 const char *ret
= str_trunc (secure_path
, trunc_len
);
266 g_free (secure_path
);
272 size_trunc (double size
)
274 static char x
[BUF_TINY
];
275 long int divisor
= 1;
276 const char *xtra
= "";
278 if (size
> 999999999L){
279 divisor
= kilobyte_si
?1000:1024;
280 xtra
= kilobyte_si
?"k":"K";
281 if (size
/divisor
> 999999999L){
282 divisor
= kilobyte_si
?(1000*1000):(1024*1024);
283 xtra
= kilobyte_si
?"m":"M";
286 g_snprintf (x
, sizeof (x
), "%.0f%s", (size
/divisor
), xtra
);
291 size_trunc_sep (double size
)
298 p
= y
= size_trunc (size
);
300 d
= x
+ sizeof (x
) - 1;
302 while (p
>= y
&& isalpha ((unsigned char) *p
))
304 for (count
= 0; p
>= y
; count
++){
318 * Print file SIZE to BUFFER, but don't exceed LEN characters,
319 * not including trailing 0. BUFFER should be at least LEN+1 long.
320 * This function is called for every file on panels, so avoid
321 * floating point by any means.
323 * Units: size units (filesystem sizes are 1K blocks)
324 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
327 size_trunc_len (char *buffer
, unsigned int len
, off_t size
, int units
)
329 /* Avoid taking power for every file. */
330 static const off_t power10
[] =
331 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
333 static const char * const suffix
[] =
334 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL
};
335 static const char * const suffix_lc
[] =
336 {"", "k", "m", "g", "t", "p", "e", "z", "y", NULL
};
344 * recalculate from 1024 base to 1000 base if units>0
345 * We can't just multiply by 1024 - that might cause overflow
346 * if off_t type is too small
348 if (units
&& kilobyte_si
) {
349 for (j
= 0; j
< units
; j
++) {
350 size_remain
=((size
% 125)*1024)/1000; /* size mod 125, recalculated */
351 size
= size
/ 125; /* 128/125 = 1024/1000 */
352 size
= size
* 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
353 size
+= size_remain
; /* Re-add remainder lost by division/multiplication */
357 for (j
= units
; suffix
[j
] != NULL
; j
++) {
360 /* Empty files will print "0" even with minimal width. */
361 g_snprintf (buffer
, len
+ 1, "0");
365 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
366 g_snprintf (buffer
, len
+ 1, (len
> 1) ? "~%s" : "%s",
367 (j
> 1) ? (kilobyte_si
? suffix_lc
[j
- 1] : suffix
[j
- 1]) : "B");
371 if (size
< power10
[len
- (j
> 0)]) {
372 g_snprintf (buffer
, len
+ 1, "%lu%s", (unsigned long) size
, kilobyte_si
? suffix_lc
[j
] : suffix
[j
]);
376 /* Powers of 1000 or 1024, with rounding. */
378 size
= (size
+ 500) / 1000;
380 size
= (size
+ 512) >> 10;
388 if ((S_IXUSR
& mode
) || (S_IXGRP
& mode
) || (S_IXOTH
& mode
))
393 #define ismode(n,m) ((n & m) == m)
396 string_perm (mode_t mode_bits
)
398 static char mode
[11];
400 strcpy (mode
, "----------");
401 if (S_ISDIR (mode_bits
))
403 if (S_ISCHR (mode_bits
))
405 if (S_ISBLK (mode_bits
))
407 if (S_ISLNK (mode_bits
))
409 if (S_ISFIFO (mode_bits
))
411 if (S_ISNAM (mode_bits
))
413 if (S_ISSOCK (mode_bits
))
415 if (S_ISDOOR (mode_bits
))
417 if (ismode (mode_bits
, S_IXOTH
))
419 if (ismode (mode_bits
, S_IWOTH
))
421 if (ismode (mode_bits
, S_IROTH
))
423 if (ismode (mode_bits
, S_IXGRP
))
425 if (ismode (mode_bits
, S_IWGRP
))
427 if (ismode (mode_bits
, S_IRGRP
))
429 if (ismode (mode_bits
, S_IXUSR
))
431 if (ismode (mode_bits
, S_IWUSR
))
433 if (ismode (mode_bits
, S_IRUSR
))
436 if (ismode (mode_bits
, S_ISUID
))
437 mode
[3] = (mode
[3] == 'x') ? 's' : 'S';
440 if (ismode (mode_bits
, S_ISGID
))
441 mode
[6] = (mode
[6] == 'x') ? 's' : 'S';
444 if (ismode (mode_bits
, S_ISVTX
))
445 mode
[9] = (mode
[9] == 'x') ? 't' : 'T';
450 /* p: string which might contain an url with a password (this parameter is
452 has_prefix = 0: The first parameter is an url without a prefix
453 (user[:pass]@]machine[:port][remote-dir). Delete
455 has_prefix = 1: Search p for known url prefixes. If found delete
456 the password from the url.
457 Caveat: only the first url is found
460 strip_password (char *p
, int has_prefix
)
462 static const struct {
465 } prefixes
[] = { {"/#ftp:", 6},
475 char *at
, *inner_colon
, *dir
;
479 for (i
= 0; i
< sizeof (prefixes
)/sizeof (prefixes
[0]); i
++) {
483 if((q
= strstr (p
, prefixes
[i
].name
)) == 0)
486 p
= q
+ prefixes
[i
].len
;
489 if ((dir
= strchr (p
, PATH_SEP
)) != NULL
)
492 /* search for any possible user */
493 at
= strrchr (p
, '@');
498 /* We have a username */
500 inner_colon
= memchr (p
, ':', at
- p
);
502 memmove (inner_colon
, at
, strlen(at
) + 1);
510 strip_home_and_password(const char *dir
)
513 static char newdir
[MC_MAXPATHLEN
];
515 if (home_dir
&& !strncmp (dir
, home_dir
, len
= strlen (home_dir
)) &&
516 (dir
[len
] == PATH_SEP
|| dir
[len
] == '\0')){
518 g_strlcpy (&newdir
[1], &dir
[len
], sizeof(newdir
) - 1);
522 /* We do not strip homes in /#ftp tree, I do not like ~'s there
524 g_strlcpy (newdir
, dir
, sizeof(newdir
));
525 strip_password (newdir
, 1);
530 extension (const char *filename
)
532 const char *d
= strrchr (filename
, '.');
533 return (d
!= NULL
) ? d
+ 1 : "";
537 exist_file (const char *name
)
539 return access (name
, R_OK
) == 0;
543 check_for_default (const char *default_file
, const char *file
)
545 if (!exist_file (file
)) {
550 if (!exist_file (default_file
))
553 ctx
= file_op_context_new (OP_COPY
);
554 file_op_context_create_ui (ctx
, 0);
555 copy_file_file (ctx
, default_file
, file
, 1, &count
, &bytes
, 1);
556 file_op_context_destroy (ctx
);
565 load_file (const char *filename
)
572 if ((data_file
= fopen (filename
, "r")) == NULL
){
575 if (fstat (fileno (data_file
), &s
) != 0){
579 data
= g_malloc (s
.st_size
+1);
580 read_size
= fread (data
, 1, s
.st_size
, data_file
);
581 data
[read_size
] = 0;
593 load_mc_home_file (const char *filename
, char **allocated_filename
)
595 char *hintfile_base
, *hintfile
;
599 hintfile_base
= concat_dir_and_file (mc_home
, filename
);
600 lang
= guess_message_value ();
602 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
603 data
= load_file (hintfile
);
607 g_free (hintfile_base
);
608 hintfile_base
= concat_dir_and_file (mc_home_alt
, filename
);
610 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
611 data
= load_file (hintfile
);
614 /* Fall back to the two-letter language code */
615 if (lang
[0] && lang
[1])
617 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
618 data
= load_file (hintfile
);
622 hintfile
= hintfile_base
;
623 data
= load_file (hintfile_base
);
630 if (hintfile
!= hintfile_base
)
631 g_free (hintfile_base
);
633 if (allocated_filename
)
634 *allocated_filename
= hintfile
;
641 /* Check strftime() results. Some systems (i.e. Solaris) have different
642 short-month-name sizes for different locales */
644 i18n_checktimelength (void)
647 time_t testtime
= time (NULL
);
648 struct tm
* lt
= localtime(&testtime
);
651 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
652 length
= str_term_width1 (_(INVALID_TIME_TEXT
));
654 char buf
[MB_LEN_MAX
* MAX_I18NTIMELENGTH
+ 1];
657 strftime (buf
, sizeof(buf
) - 1, FMTTIME
, lt
);
658 a
= str_term_width1 (buf
);
659 strftime (buf
, sizeof(buf
) - 1, FMTYEAR
, lt
);
660 b
= str_term_width1 (buf
);
663 length
= max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT
)), length
);
666 /* Don't handle big differences. Use standard value (email bug, please) */
667 if (length
> MAX_I18NTIMELENGTH
|| length
< MIN_I18NTIMELENGTH
)
668 length
= STD_I18NTIMELENGTH
;
674 file_date (time_t when
)
676 static char timebuf
[MB_LEN_MAX
* MAX_I18NTIMELENGTH
+ 1];
677 time_t current_time
= time ((time_t) 0);
680 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
681 || current_time
< when
- 60L * 60L) /* In the future. */
682 /* The file is fairly old or in the future.
683 POSIX says the cutoff is 6 months old;
684 approximate this by 6*30 days.
685 Allow a 1 hour slop factor for what is considered "the future",
686 to allow for NFS server/client clock disagreement.
687 Show the year instead of the time of day. */
693 FMT_LOCALTIME(timebuf
, sizeof (timebuf
), fmt
, when
);
699 extract_line (const char *s
, const char *top
)
701 static char tmp_line
[BUF_MEDIUM
];
704 while (*s
&& *s
!= '\n' && (size_t) (t
- tmp_line
) < sizeof (tmp_line
)-1 && s
< top
)
710 /* The basename routine */
712 x_basename (const char *s
)
715 return ((where
= strrchr (s
, PATH_SEP
))) ? where
+ 1 : s
;
720 unix_error_string (int error_num
)
722 static char buffer
[BUF_LARGE
];
723 gchar
*strerror_currentlocale
;
725 strerror_currentlocale
= g_locale_from_utf8(g_strerror (error_num
), -1, NULL
, NULL
, NULL
);
726 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
727 strerror_currentlocale
, error_num
);
728 g_free(strerror_currentlocale
);
734 skip_separators (const char *s
)
738 for (;*su
; str_cnext_char (&su
))
739 if (*su
!= ' ' && *su
!= '\t' && *su
!= ',') break;
745 skip_numbers (const char *s
)
749 for (;*su
; str_cnext_char (&su
))
750 if (!str_isdigit (su
)) break;
755 /* Remove all control sequences from the argument string. We define
756 * "control sequence", in a sort of pidgin BNF, as follows:
758 * control-seq = Esc non-'['
759 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
761 * This scheme works for all the terminals described in my termcap /
762 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
763 * terminals. If I hear from a single person who uses such a terminal
764 * with MC, I'll be glad to add support for it. (Dugan)
765 * Non-printable characters are also removed.
769 strip_ctrl_codes (char *s
)
771 char *w
; /* Current position where the stripped data is written */
772 char *r
; /* Current position where the original data is read */
778 for (w
= s
, r
= s
; *r
; ) {
779 if (*r
== ESC_CHAR
) {
780 /* Skip the control sequence's arguments */ ;
781 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
782 if (*(++r
) == '[' || *r
== '(') {
783 /* strchr() matches trailing binary 0 */
784 while (*(++r
) && strchr ("0123456789;?", *r
));
788 * Skip xterm's OSC (Operating System Command)
789 * http://www.xfree86.org/current/ctlseqs.html
795 for (; *new_r
; ++new_r
)
805 if (*(new_r
+ 1) == '\\')
816 * Now we are at the last character of the sequence.
817 * Skip it unless it's binary 0.
824 n
= str_get_next_char (r
);
825 if (str_isprint (r
)) {
826 memmove (w
, r
, n
- r
);
838 get_current_wd (char *buffer
, int size
)
843 p
= g_get_current_dir ();
851 memcpy (buffer
, p
, len
);
856 #endif /* !ENABLE_VFS */
858 enum compression_type
859 get_compression_type (int fd
, const char * name
)
861 unsigned char magic
[16];
864 /* Read the magic signature */
865 if (mc_read (fd
, (char *) magic
, 4) != 4)
866 return COMPRESSION_NONE
;
868 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
869 if (magic
[0] == 037 && (magic
[1] == 0213 || magic
[1] == 0236)) {
870 return COMPRESSION_GZIP
;
874 if (magic
[0] == 0120 && magic
[1] == 0113 && magic
[2] == 003
875 && magic
[3] == 004) {
876 /* Read compression type */
877 mc_lseek (fd
, 8, SEEK_SET
);
878 if (mc_read (fd
, (char *) magic
, 2) != 2)
879 return COMPRESSION_NONE
;
881 /* Gzip can handle only deflated (8) or stored (0) files */
882 if ((magic
[0] != 8 && magic
[0] != 0) || magic
[1] != 0)
883 return COMPRESSION_NONE
;
885 /* Compatible with gzip */
886 return COMPRESSION_GZIP
;
889 /* PACK_MAGIC and LZH_MAGIC and compress magic */
891 && (magic
[1] == 036 || magic
[1] == 0240 || magic
[1] == 0235)) {
892 /* Compatible with gzip */
893 return COMPRESSION_GZIP
;
896 /* BZIP and BZIP2 files */
897 if ((magic
[0] == 'B') && (magic
[1] == 'Z') &&
898 (magic
[3] >= '1') && (magic
[3] <= '9')) {
901 return COMPRESSION_BZIP
;
903 return COMPRESSION_BZIP2
;
907 /* Support for LZMA (only utils format with magic in header).
908 * This is the default format of LZMA utils 4.32.1 and later. */
910 if (mc_read(fd
, (char *) magic
+4, 2) != 2)
911 return COMPRESSION_NONE
;
913 /* LZMA utils format */
922 return COMPRESSION_LZMA
;
924 /* XZ compression magic */
933 return COMPRESSION_XZ
;
935 str_len
= strlen(name
);
936 /* HACK: we must belive to extention of LZMA file :) ...*/
937 if ( (str_len
> 5 && strcmp(&name
[str_len
-5],".lzma") == 0) ||
938 (str_len
> 4 && strcmp(&name
[str_len
-4],".tlz") == 0))
939 return COMPRESSION_LZMA
;
941 return COMPRESSION_NONE
;
945 decompress_extension (int type
)
948 case COMPRESSION_GZIP
: return "#ugz";
949 case COMPRESSION_BZIP
: return "#ubz";
950 case COMPRESSION_BZIP2
: return "#ubz2";
951 case COMPRESSION_LZMA
: return "#ulzma";
952 case COMPRESSION_XZ
: return "#uxz";
954 /* Should never reach this place */
955 fprintf (stderr
, "Fatal: decompress_extension called with an unknown argument\n");
961 add_hook (Hook
**hook_list
, void (*hook_fn
)(void *), void *data
)
963 Hook
*new_hook
= g_new (Hook
, 1);
965 new_hook
->hook_fn
= hook_fn
;
966 new_hook
->next
= *hook_list
;
967 new_hook
->hook_data
= data
;
969 *hook_list
= new_hook
;
973 execute_hooks (Hook
*hook_list
)
978 /* We copy the hook list first so tahat we let the hook
979 * function call delete_hook
983 add_hook (&new_hook
, hook_list
->hook_fn
, hook_list
->hook_data
);
984 hook_list
= hook_list
->next
;
989 (*new_hook
->hook_fn
)(new_hook
->hook_data
);
990 new_hook
= new_hook
->next
;
993 for (hook_list
= p
; hook_list
;){
995 hook_list
= hook_list
->next
;
1001 delete_hook (Hook
**hook_list
, void (*hook_fn
)(void *))
1003 Hook
*current
, *new_list
, *next
;
1007 for (current
= *hook_list
; current
; current
= next
){
1008 next
= current
->next
;
1009 if (current
->hook_fn
== hook_fn
)
1012 add_hook (&new_list
, current
->hook_fn
, current
->hook_data
);
1014 *hook_list
= new_list
;
1018 hook_present (Hook
*hook_list
, void (*hook_fn
)(void *))
1022 for (p
= hook_list
; p
; p
= p
->next
)
1023 if (p
->hook_fn
== hook_fn
)
1029 wipe_password (char *passwd
)
1040 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1041 /* Returns a newly allocated string */
1043 convert_controls (const char *p
)
1045 char *valcopy
= g_strdup (p
);
1048 /* Parse the escape special character */
1049 for (q
= valcopy
; *p
;){
1052 if ((*p
== 'e') || (*p
== 'E')){
1062 char c
= (*p
| 0x20);
1063 if (c
>= 'a' && c
<= 'z') {
1078 resolve_symlinks (const char *path
)
1080 char *buf
, *buf2
, *q
, *r
, c
;
1085 if (*path
!= PATH_SEP
)
1087 r
= buf
= g_malloc (MC_MAXPATHLEN
);
1088 buf2
= g_malloc (MC_MAXPATHLEN
);
1093 q
= strchr (p
+ 1, PATH_SEP
);
1095 q
= strchr (p
+ 1, 0);
1101 if (mc_lstat (path
, &mybuf
) < 0) {
1107 if (!S_ISLNK (mybuf
.st_mode
))
1110 len
= mc_readlink (path
, buf2
, MC_MAXPATHLEN
- 1);
1118 if (*buf2
== PATH_SEP
)
1123 canonicalize_pathname (buf
);
1124 r
= strchr (buf
, 0);
1125 if (!*r
|| *(r
- 1) != PATH_SEP
) {
1135 strcpy (buf
, PATH_SEP_STR
);
1136 else if (*(r
- 1) == PATH_SEP
&& r
!= buf
+ 1)
1143 mc_util_write_backup_content(const char *from_file_name
, const char *to_file_name
)
1149 if (!g_file_get_contents (from_file_name
, &contents
, &length
, NULL
))
1152 backup_fd
= fopen (to_file_name
, "w");
1153 if (backup_fd
== NULL
) {
1158 fwrite ( (const void *) contents
, length
, 1, backup_fd
);
1166 /* Finds out a relative path from first to second, i.e. goes as many ..
1167 * as needed up in first and then goes down using second */
1169 diff_two_paths (const char *first
, const char *second
)
1171 char *p
, *q
, *r
, *s
, *buf
= NULL
;
1172 int i
, j
, prevlen
= -1, currlen
;
1173 char *my_first
= NULL
, *my_second
= NULL
;
1175 my_first
= resolve_symlinks (first
);
1176 if (my_first
== NULL
)
1178 my_second
= resolve_symlinks (second
);
1179 if (my_second
== NULL
) {
1183 for (j
= 0; j
< 2; j
++) {
1187 r
= strchr (p
, PATH_SEP
);
1188 s
= strchr (q
, PATH_SEP
);
1192 if (strcmp (p
, q
)) {
1193 *r
= PATH_SEP
; *s
= PATH_SEP
;
1196 *r
= PATH_SEP
; *s
= PATH_SEP
;
1202 for (i
= 0; (p
= strchr (p
+ 1, PATH_SEP
)) != NULL
; i
++);
1203 currlen
= (i
+ 1) * 3 + strlen (q
) + 1;
1205 if (currlen
< prevlen
)
1213 p
= buf
= g_malloc (currlen
);
1215 for (; i
>= 0; i
--, p
+= 3)
1224 /* If filename is NULL, then we just append PATH_SEP to the dir */
1226 concat_dir_and_file (const char *dir
, const char *file
)
1228 int i
= strlen (dir
);
1230 if (dir
[i
-1] == PATH_SEP
)
1231 return g_strconcat (dir
, file
, (char *) NULL
);
1233 return g_strconcat (dir
, PATH_SEP_STR
, file
, (char *) NULL
);
1236 /* Append text to GList, remove all entries with the same text */
1238 list_append_unique (GList
*list
, char *text
)
1240 GList
*lc_link
, *newlink
, *tmp
;
1243 * Go to the last position and traverse the list backwards
1244 * starting from the second last entry to make sure that we
1245 * are not removing the current link.
1247 list
= g_list_append (list
, text
);
1248 list
= g_list_last (list
);
1249 lc_link
= g_list_previous (list
);
1252 newlink
= g_list_previous (lc_link
);
1253 if (!strcmp ((char *) lc_link
->data
, text
)) {
1254 g_free (lc_link
->data
);
1255 tmp
= g_list_remove_link (list
, lc_link
);
1256 g_list_free_1 (lc_link
);
1264 /* Following code heavily borrows from libiberty, mkstemps.c */
1266 /* Number of attempts to create a temporary file */
1268 #define TMP_MAX 16384
1269 #endif /* !TMP_MAX */
1273 * pname (output) - pointer to the name of the temp file (needs g_free).
1274 * NULL if the function fails.
1275 * prefix - part of the filename before the random part.
1276 * Prepend $TMPDIR or /tmp if there are no path separators.
1277 * suffix - if not NULL, part of the filename after the random part.
1280 * handle of the open file or -1 if couldn't open any.
1283 mc_mkstemps (char **pname
, const char *prefix
, const char *suffix
)
1285 static const char letters
[]
1286 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1287 static unsigned long value
;
1294 if (strchr (prefix
, PATH_SEP
) == NULL
) {
1295 /* Add prefix first to find the position of XXXXXX */
1296 tmpbase
= concat_dir_and_file (mc_tmpdir (), prefix
);
1298 tmpbase
= g_strdup (prefix
);
1301 tmpname
= g_strconcat (tmpbase
, "XXXXXX", suffix
, (char *) NULL
);
1303 XXXXXX
= &tmpname
[strlen (tmpbase
)];
1306 /* Get some more or less random data. */
1307 gettimeofday (&tv
, NULL
);
1308 value
+= (tv
.tv_usec
<< 16) ^ tv
.tv_sec
^ getpid ();
1310 for (count
= 0; count
< TMP_MAX
; ++count
) {
1311 unsigned long v
= value
;
1314 /* Fill in the random bits. */
1315 XXXXXX
[0] = letters
[v
% 62];
1317 XXXXXX
[1] = letters
[v
% 62];
1319 XXXXXX
[2] = letters
[v
% 62];
1321 XXXXXX
[3] = letters
[v
% 62];
1323 XXXXXX
[4] = letters
[v
% 62];
1325 XXXXXX
[5] = letters
[v
% 62];
1327 fd
= open (tmpname
, O_RDWR
| O_CREAT
| O_TRUNC
| O_EXCL
,
1330 /* Successfully created. */
1334 /* This is a random value. It is only necessary that the next
1335 TMP_MAX values generated by adding 7777 to VALUE are different
1336 with (module 2^32). */
1340 /* Unsuccessful. Free the filename. */
1348 * Read and restore position for the given filename.
1349 * If there is no stored data, return line 1 and col 0.
1352 load_file_position (const char *filename
, long *line
, long *column
)
1356 char buf
[MC_MAXPATHLEN
+ 20];
1363 /* open file with positions */
1364 fn
= g_build_filename (home_dir
, MC_USERCONF_DIR
, MC_FILEPOS_FILE
, NULL
);
1365 f
= fopen (fn
, "r");
1370 len
= strlen (filename
);
1372 while (fgets (buf
, sizeof (buf
), f
)) {
1375 /* check if the filename matches the beginning of string */
1376 if (strncmp (buf
, filename
, len
) != 0)
1379 /* followed by single space */
1380 if (buf
[len
] != ' ')
1383 /* and string without spaces */
1385 if (strchr (p
, ' '))
1388 *line
= strtol(p
, const_cast(char **, &p
), 10);
1390 *column
= strtol(p
+1, const_cast(char **, &p
), 10);
1399 /* Save position for the given file */
1400 #define TMP_SUFFIX ".tmp"
1402 save_file_position (const char *filename
, long line
, long column
)
1404 static int filepos_max_saved_entries
= 0;
1407 char buf
[MC_MAXPATHLEN
+ 20];
1411 if (filepos_max_saved_entries
== 0)
1412 filepos_max_saved_entries
= mc_config_get_int(mc_main_config
, CONFIG_APP_SECTION
, "filepos_max_saved_entries", 1024);
1414 fn
= g_build_filename (home_dir
, MC_USERCONF_DIR
, MC_FILEPOS_FILE
, NULL
);
1418 len
= strlen (filename
);
1420 mc_util_make_backup_if_possible (fn
, TMP_SUFFIX
);
1423 f
= fopen (fn
, "w");
1425 goto open_target_error
;
1427 tmp_fn
= g_strdup_printf("%s" TMP_SUFFIX
,fn
);
1428 tmp_f
= fopen (tmp_fn
, "r");
1430 goto open_source_error
;
1432 /* put the new record */
1433 if (line
!= 1 || column
!= 0) {
1434 if (fprintf (f
, "%s %ld;%ld\n", filename
, line
, column
) < 0)
1435 goto write_position_error
;
1438 while (fgets (buf
, sizeof (buf
), tmp_f
)) {
1441 strncmp (buf
, filename
, len
) == 0 &&
1442 !strchr (&buf
[len
+ 1], ' ')
1446 fprintf (f
, "%s", buf
);
1447 if (++i
> filepos_max_saved_entries
)
1453 mc_util_unlink_backup_if_possible (fn
, TMP_SUFFIX
);
1457 write_position_error
:
1462 mc_util_restore_from_backup_if_possible (fn
, TMP_SUFFIX
);
1470 cstrcasestr (const char *haystack
, const char *needle
)
1472 char *nee
= str_create_search_needle (needle
, 0);
1473 const char *result
= str_search_first (haystack
, nee
, 0);
1474 str_release_search_needle (nee
, 0);
1479 cstrstr (const char *haystack
, const char *needle
)
1481 return strstr(haystack
, needle
);
1485 str_unconst (const char *s
)
1490 #define ASCII_A (0x40 + 1)
1491 #define ASCII_Z (0x40 + 26)
1492 #define ASCII_a (0x60 + 1)
1493 #define ASCII_z (0x60 + 26)
1496 ascii_alpha_to_cntrl (int ch
)
1498 if ((ch
>= ASCII_A
&& ch
<= ASCII_Z
)
1499 || (ch
>= ASCII_a
&& ch
<= ASCII_z
)) {
1508 const char *result
, *sep
;
1511 sep
= strchr(result
, '|');
1512 return (sep
!= NULL
) ? sep
+ 1 : result
;
1517 mc_util_make_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1519 struct stat stat_buf
;
1522 if (!exist_file (file_name
))
1525 backup_path
= g_strdup_printf("%s%s",file_name
,backup_suffix
);
1527 if (backup_path
== NULL
)
1530 ret
= mc_util_write_backup_content (file_name
, backup_path
);
1533 /* Backup file will have same ownership with main file. */
1534 if (stat (file_name
, &stat_buf
) == 0)
1535 chmod (backup_path
, stat_buf
.st_mode
);
1537 chmod (backup_path
, S_IRUSR
| S_IWUSR
);
1540 g_free(backup_path
);
1546 mc_util_restore_from_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1551 backup_path
= g_strdup_printf("%s%s",file_name
,backup_suffix
);
1552 if (backup_path
== NULL
)
1555 ret
= mc_util_write_backup_content (backup_path
, file_name
);
1556 g_free(backup_path
);
1562 mc_util_unlink_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1566 backup_path
= g_strdup_printf("%s%s",file_name
,backup_suffix
);
1567 if (backup_path
== NULL
)
1570 if (exist_file (backup_path
))
1571 mc_unlink (backup_path
);
1573 g_free(backup_path
);