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>
43 #include "lib/global.h"
44 #include "lib/tty/win.h" /* xterm_flag */
45 #include "lib/search.h"
46 #include "lib/mcconfig.h"
47 #include "lib/timefmt.h"
48 #include "lib/fileloc.h"
49 #include "lib/vfs/mc-vfs/vfs.h"
50 #include "lib/strutil.h"
52 #include "src/file.h" /* copy_file_file() */
54 /*In order to use everywhere the same setup
55 for the locale we use defines */
56 #define FMTYEAR _("%b %e %Y")
57 #define FMTTIME _("%b %e %H:%M")
60 int easy_patterns
= 1;
63 * If true, SI units (1000 based) will be used for
64 * larger units (kilobyte, megabyte, ...).
65 * If false binary units (1024 based) will be used.
71 extern void str_replace(char *s
, char from
, char to
)
73 for (; *s
!= '\0'; s
++) {
80 is_7bit_printable (unsigned char c
)
82 return (c
> 31 && c
< 127);
86 is_iso_printable (unsigned char c
)
88 return ((c
> 31 && c
< 127) || c
>= 160);
92 is_8bit_printable (unsigned char c
)
94 /* "Full 8 bits output" doesn't work on xterm */
96 return is_iso_printable (c
);
98 return (c
> 31 && c
!= 127 && c
!= 155);
107 /* "Display bits" is ignored, since the user controls the output
108 by setting the output codepage */
109 return is_8bit_printable (c
);
111 if (!eight_bit_clean
)
112 return is_7bit_printable (c
);
114 if (full_eight_bits
) {
115 return is_8bit_printable (c
);
117 return is_iso_printable (c
);
118 #endif /* !HAVE_CHARSET */
121 /* Calculates the message dimensions (lines and columns) */
123 msglen (const char *text
, int *lines
, int *columns
)
125 int nlines
= 1; /* even the empty string takes one line */
129 for (; *text
!= '\0'; text
++) {
135 if (colindex
> ncolumns
)
145 * Copy from s to d, and trim the beginning if necessary, and prepend
146 * "..." in this case. The destination string can have at most len
147 * bytes, not counting trailing 0.
150 trim (const char *s
, char *d
, int len
)
157 source_len
= strlen (s
);
158 if (source_len
> len
) {
159 /* Cannot fit the whole line */
161 /* We only have room for the dots */
162 memset (d
, '.', len
);
166 /* Begin with ... and add the rest of the source string */
168 strcpy (d
+ 3, s
+ 3 + source_len
- len
);
171 /* We can copy the whole line */
177 * Quote the filename for the purpose of inserting it into the command
178 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
179 * processed by the mc command line.
182 name_quote (const char *s
, int quote_percent
)
186 d
= ret
= g_malloc (strlen (s
) * 2 + 2 + 1);
192 for (; *s
; s
++, d
++) {
236 fake_name_quote (const char *s
, int quote_percent
)
238 (void) quote_percent
;
243 * Remove the middle part of the string to fit given length.
244 * Use "~" to show where the string was truncated.
245 * Return static buffer, no need to free() it.
248 name_trunc (const char *txt
, size_t trunc_len
)
250 return str_trunc (txt
, trunc_len
);
254 * path_trunc() is the same as name_trunc() above but
255 * it deletes possible password from path for security
259 path_trunc (const char *path
, size_t trunc_len
) {
260 char *secure_path
= strip_password (g_strdup (path
), 1);
262 const char *ret
= str_trunc (secure_path
, trunc_len
);
263 g_free (secure_path
);
269 size_trunc (double size
)
271 static char x
[BUF_TINY
];
272 long int divisor
= 1;
273 const char *xtra
= "";
275 if (size
> 999999999L){
276 divisor
= kilobyte_si
?1000:1024;
277 xtra
= kilobyte_si
?"k":"K";
278 if (size
/divisor
> 999999999L){
279 divisor
= kilobyte_si
?(1000*1000):(1024*1024);
280 xtra
= kilobyte_si
?"m":"M";
283 g_snprintf (x
, sizeof (x
), "%.0f%s", (size
/divisor
), xtra
);
288 size_trunc_sep (double size
)
295 p
= y
= size_trunc (size
);
297 d
= x
+ sizeof (x
) - 1;
299 while (p
>= y
&& isalpha ((unsigned char) *p
))
301 for (count
= 0; p
>= y
; count
++){
315 * Print file SIZE to BUFFER, but don't exceed LEN characters,
316 * not including trailing 0. BUFFER should be at least LEN+1 long.
317 * This function is called for every file on panels, so avoid
318 * floating point by any means.
320 * Units: size units (filesystem sizes are 1K blocks)
321 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
324 size_trunc_len (char *buffer
, unsigned int len
, off_t size
, int units
)
326 /* Avoid taking power for every file. */
327 static const off_t power10
[] =
328 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
330 static const char * const suffix
[] =
331 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL
};
332 static const char * const suffix_lc
[] =
333 {"", "k", "m", "g", "t", "p", "e", "z", "y", NULL
};
341 * recalculate from 1024 base to 1000 base if units>0
342 * We can't just multiply by 1024 - that might cause overflow
343 * if off_t type is too small
345 if (units
&& kilobyte_si
) {
346 for (j
= 0; j
< units
; j
++) {
347 size_remain
=((size
% 125)*1024)/1000; /* size mod 125, recalculated */
348 size
= size
/ 125; /* 128/125 = 1024/1000 */
349 size
= size
* 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
350 size
+= size_remain
; /* Re-add remainder lost by division/multiplication */
354 for (j
= units
; suffix
[j
] != NULL
; j
++) {
357 /* Empty files will print "0" even with minimal width. */
358 g_snprintf (buffer
, len
+ 1, "0");
362 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
363 g_snprintf (buffer
, len
+ 1, (len
> 1) ? "~%s" : "%s",
364 (j
> 1) ? (kilobyte_si
? suffix_lc
[j
- 1] : suffix
[j
- 1]) : "B");
368 if (size
< power10
[len
- (j
> 0)]) {
369 g_snprintf (buffer
, len
+ 1, "%lu%s", (unsigned long) size
, kilobyte_si
? suffix_lc
[j
] : suffix
[j
]);
373 /* Powers of 1000 or 1024, with rounding. */
375 size
= (size
+ 500) / 1000;
377 size
= (size
+ 512) >> 10;
385 if ((S_IXUSR
& mode
) || (S_IXGRP
& mode
) || (S_IXOTH
& mode
))
390 #define ismode(n,m) ((n & m) == m)
393 string_perm (mode_t mode_bits
)
395 static char mode
[11];
397 strcpy (mode
, "----------");
398 if (S_ISDIR (mode_bits
))
400 if (S_ISCHR (mode_bits
))
402 if (S_ISBLK (mode_bits
))
404 if (S_ISLNK (mode_bits
))
406 if (S_ISFIFO (mode_bits
))
408 if (S_ISNAM (mode_bits
))
410 if (S_ISSOCK (mode_bits
))
412 if (S_ISDOOR (mode_bits
))
414 if (ismode (mode_bits
, S_IXOTH
))
416 if (ismode (mode_bits
, S_IWOTH
))
418 if (ismode (mode_bits
, S_IROTH
))
420 if (ismode (mode_bits
, S_IXGRP
))
422 if (ismode (mode_bits
, S_IWGRP
))
424 if (ismode (mode_bits
, S_IRGRP
))
426 if (ismode (mode_bits
, S_IXUSR
))
428 if (ismode (mode_bits
, S_IWUSR
))
430 if (ismode (mode_bits
, S_IRUSR
))
433 if (ismode (mode_bits
, S_ISUID
))
434 mode
[3] = (mode
[3] == 'x') ? 's' : 'S';
437 if (ismode (mode_bits
, S_ISGID
))
438 mode
[6] = (mode
[6] == 'x') ? 's' : 'S';
441 if (ismode (mode_bits
, S_ISVTX
))
442 mode
[9] = (mode
[9] == 'x') ? 't' : 'T';
447 /* p: string which might contain an url with a password (this parameter is
449 has_prefix = 0: The first parameter is an url without a prefix
450 (user[:pass]@]machine[:port][remote-dir). Delete
452 has_prefix = 1: Search p for known url prefixes. If found delete
453 the password from the url.
454 Caveat: only the first url is found
457 strip_password (char *p
, int has_prefix
)
459 static const struct {
462 } prefixes
[] = { {"/#ftp:", 6},
472 char *at
, *inner_colon
, *dir
;
476 for (i
= 0; i
< sizeof (prefixes
)/sizeof (prefixes
[0]); i
++) {
480 if((q
= strstr (p
, prefixes
[i
].name
)) == 0)
483 p
= q
+ prefixes
[i
].len
;
486 if ((dir
= strchr (p
, PATH_SEP
)) != NULL
)
489 /* search for any possible user */
490 at
= strrchr (p
, '@');
495 /* We have a username */
497 inner_colon
= memchr (p
, ':', at
- p
);
499 memmove (inner_colon
, at
, strlen(at
) + 1);
507 strip_home_and_password(const char *dir
)
510 static char newdir
[MC_MAXPATHLEN
];
512 if (home_dir
&& !strncmp (dir
, home_dir
, len
= strlen (home_dir
)) &&
513 (dir
[len
] == PATH_SEP
|| dir
[len
] == '\0')){
515 g_strlcpy (&newdir
[1], &dir
[len
], sizeof(newdir
) - 1);
519 /* We do not strip homes in /#ftp tree, I do not like ~'s there
521 g_strlcpy (newdir
, dir
, sizeof(newdir
));
522 strip_password (newdir
, 1);
527 extension (const char *filename
)
529 const char *d
= strrchr (filename
, '.');
530 return (d
!= NULL
) ? d
+ 1 : "";
534 exist_file (const char *name
)
536 return access (name
, R_OK
) == 0;
540 check_for_default (const char *default_file
, const char *file
)
542 if (!exist_file (file
)) {
547 if (!exist_file (default_file
))
550 ctx
= file_op_context_new (OP_COPY
);
551 file_op_context_create_ui (ctx
, 0);
552 copy_file_file (ctx
, default_file
, file
, 1, &count
, &bytes
, 1);
553 file_op_context_destroy (ctx
);
562 load_file (const char *filename
)
569 if ((data_file
= fopen (filename
, "r")) == NULL
){
572 if (fstat (fileno (data_file
), &s
) != 0){
576 data
= g_malloc (s
.st_size
+1);
577 read_size
= fread (data
, 1, s
.st_size
, data_file
);
578 data
[read_size
] = 0;
590 load_mc_home_file (const char *_mc_home
, const char *_mc_home_alt
, const char *filename
, char **allocated_filename
)
592 char *hintfile_base
, *hintfile
;
596 hintfile_base
= concat_dir_and_file (_mc_home
, filename
);
597 lang
= guess_message_value ();
599 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
600 data
= load_file (hintfile
);
604 g_free (hintfile_base
);
605 hintfile_base
= concat_dir_and_file (_mc_home_alt
, filename
);
607 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
608 data
= load_file (hintfile
);
611 /* Fall back to the two-letter language code */
612 if (lang
[0] && lang
[1])
614 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
615 data
= load_file (hintfile
);
619 hintfile
= hintfile_base
;
620 data
= load_file (hintfile_base
);
627 if (hintfile
!= hintfile_base
)
628 g_free (hintfile_base
);
630 if (allocated_filename
)
631 *allocated_filename
= hintfile
;
638 /* Check strftime() results. Some systems (i.e. Solaris) have different
639 short-month-name sizes for different locales */
641 i18n_checktimelength (void)
644 time_t testtime
= time (NULL
);
645 struct tm
* lt
= localtime(&testtime
);
648 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
649 length
= str_term_width1 (_(INVALID_TIME_TEXT
));
651 char buf
[MB_LEN_MAX
* MAX_I18NTIMELENGTH
+ 1];
654 strftime (buf
, sizeof(buf
) - 1, FMTTIME
, lt
);
655 a
= str_term_width1 (buf
);
656 strftime (buf
, sizeof(buf
) - 1, FMTYEAR
, lt
);
657 b
= str_term_width1 (buf
);
660 length
= max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT
)), length
);
663 /* Don't handle big differences. Use standard value (email bug, please) */
664 if (length
> MAX_I18NTIMELENGTH
|| length
< MIN_I18NTIMELENGTH
)
665 length
= STD_I18NTIMELENGTH
;
671 file_date (time_t when
)
673 static char timebuf
[MB_LEN_MAX
* MAX_I18NTIMELENGTH
+ 1];
674 time_t current_time
= time ((time_t) 0);
677 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
678 || current_time
< when
- 60L * 60L) /* In the future. */
679 /* The file is fairly old or in the future.
680 POSIX says the cutoff is 6 months old;
681 approximate this by 6*30 days.
682 Allow a 1 hour slop factor for what is considered "the future",
683 to allow for NFS server/client clock disagreement.
684 Show the year instead of the time of day. */
690 FMT_LOCALTIME(timebuf
, sizeof (timebuf
), fmt
, when
);
696 extract_line (const char *s
, const char *top
)
698 static char tmp_line
[BUF_MEDIUM
];
701 while (*s
&& *s
!= '\n' && (size_t) (t
- tmp_line
) < sizeof (tmp_line
)-1 && s
< top
)
707 /* The basename routine */
709 x_basename (const char *s
)
712 return ((where
= strrchr (s
, PATH_SEP
))) ? where
+ 1 : s
;
717 unix_error_string (int error_num
)
719 static char buffer
[BUF_LARGE
];
720 gchar
*strerror_currentlocale
;
722 strerror_currentlocale
= g_locale_from_utf8(g_strerror (error_num
), -1, NULL
, NULL
, NULL
);
723 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)",
724 strerror_currentlocale
, error_num
);
725 g_free(strerror_currentlocale
);
731 skip_separators (const char *s
)
735 for (;*su
; str_cnext_char (&su
))
736 if (*su
!= ' ' && *su
!= '\t' && *su
!= ',') break;
742 skip_numbers (const char *s
)
746 for (;*su
; str_cnext_char (&su
))
747 if (!str_isdigit (su
)) break;
752 /* Remove all control sequences from the argument string. We define
753 * "control sequence", in a sort of pidgin BNF, as follows:
755 * control-seq = Esc non-'['
756 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
758 * This scheme works for all the terminals described in my termcap /
759 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
760 * terminals. If I hear from a single person who uses such a terminal
761 * with MC, I'll be glad to add support for it. (Dugan)
762 * Non-printable characters are also removed.
766 strip_ctrl_codes (char *s
)
768 char *w
; /* Current position where the stripped data is written */
769 char *r
; /* Current position where the original data is read */
775 for (w
= s
, r
= s
; *r
; ) {
776 if (*r
== ESC_CHAR
) {
777 /* Skip the control sequence's arguments */ ;
778 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
779 if (*(++r
) == '[' || *r
== '(') {
780 /* strchr() matches trailing binary 0 */
781 while (*(++r
) && strchr ("0123456789;?", *r
));
785 * Skip xterm's OSC (Operating System Command)
786 * http://www.xfree86.org/current/ctlseqs.html
792 for (; *new_r
; ++new_r
)
802 if (*(new_r
+ 1) == '\\')
813 * Now we are at the last character of the sequence.
814 * Skip it unless it's binary 0.
821 n
= str_get_next_char (r
);
822 if (str_isprint (r
)) {
823 memmove (w
, r
, n
- r
);
835 get_current_wd (char *buffer
, int size
)
840 p
= g_get_current_dir ();
848 memcpy (buffer
, p
, len
);
853 #endif /* !ENABLE_VFS */
855 enum compression_type
856 get_compression_type (int fd
, const char * name
)
858 unsigned char magic
[16];
861 /* Read the magic signature */
862 if (mc_read (fd
, (char *) magic
, 4) != 4)
863 return COMPRESSION_NONE
;
865 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
866 if (magic
[0] == 037 && (magic
[1] == 0213 || magic
[1] == 0236)) {
867 return COMPRESSION_GZIP
;
871 if (magic
[0] == 0120 && magic
[1] == 0113 && magic
[2] == 003
872 && magic
[3] == 004) {
873 /* Read compression type */
874 mc_lseek (fd
, 8, SEEK_SET
);
875 if (mc_read (fd
, (char *) magic
, 2) != 2)
876 return COMPRESSION_NONE
;
878 /* Gzip can handle only deflated (8) or stored (0) files */
879 if ((magic
[0] != 8 && magic
[0] != 0) || magic
[1] != 0)
880 return COMPRESSION_NONE
;
882 /* Compatible with gzip */
883 return COMPRESSION_GZIP
;
886 /* PACK_MAGIC and LZH_MAGIC and compress magic */
888 && (magic
[1] == 036 || magic
[1] == 0240 || magic
[1] == 0235)) {
889 /* Compatible with gzip */
890 return COMPRESSION_GZIP
;
893 /* BZIP and BZIP2 files */
894 if ((magic
[0] == 'B') && (magic
[1] == 'Z') &&
895 (magic
[3] >= '1') && (magic
[3] <= '9')) {
898 return COMPRESSION_BZIP
;
900 return COMPRESSION_BZIP2
;
904 /* Support for LZMA (only utils format with magic in header).
905 * This is the default format of LZMA utils 4.32.1 and later. */
907 if (mc_read(fd
, (char *) magic
+4, 2) != 2)
908 return COMPRESSION_NONE
;
910 /* LZMA utils format */
919 return COMPRESSION_LZMA
;
921 /* XZ compression magic */
930 return COMPRESSION_XZ
;
932 str_len
= strlen(name
);
933 /* HACK: we must belive to extention of LZMA file :) ...*/
934 if ( (str_len
> 5 && strcmp(&name
[str_len
-5],".lzma") == 0) ||
935 (str_len
> 4 && strcmp(&name
[str_len
-4],".tlz") == 0))
936 return COMPRESSION_LZMA
;
938 return COMPRESSION_NONE
;
942 decompress_extension (int type
)
945 case COMPRESSION_GZIP
: return "#ugz";
946 case COMPRESSION_BZIP
: return "#ubz";
947 case COMPRESSION_BZIP2
: return "#ubz2";
948 case COMPRESSION_LZMA
: return "#ulzma";
949 case COMPRESSION_XZ
: return "#uxz";
951 /* Should never reach this place */
952 fprintf (stderr
, "Fatal: decompress_extension called with an unknown argument\n");
958 add_hook (Hook
**hook_list
, void (*hook_fn
)(void *), void *data
)
960 Hook
*new_hook
= g_new (Hook
, 1);
962 new_hook
->hook_fn
= hook_fn
;
963 new_hook
->next
= *hook_list
;
964 new_hook
->hook_data
= data
;
966 *hook_list
= new_hook
;
970 execute_hooks (Hook
*hook_list
)
975 /* We copy the hook list first so tahat we let the hook
976 * function call delete_hook
980 add_hook (&new_hook
, hook_list
->hook_fn
, hook_list
->hook_data
);
981 hook_list
= hook_list
->next
;
986 (*new_hook
->hook_fn
)(new_hook
->hook_data
);
987 new_hook
= new_hook
->next
;
990 for (hook_list
= p
; hook_list
;){
992 hook_list
= hook_list
->next
;
998 delete_hook (Hook
**hook_list
, void (*hook_fn
)(void *))
1000 Hook
*current
, *new_list
, *next
;
1004 for (current
= *hook_list
; current
; current
= next
){
1005 next
= current
->next
;
1006 if (current
->hook_fn
== hook_fn
)
1009 add_hook (&new_list
, current
->hook_fn
, current
->hook_data
);
1011 *hook_list
= new_list
;
1015 hook_present (Hook
*hook_list
, void (*hook_fn
)(void *))
1019 for (p
= hook_list
; p
; p
= p
->next
)
1020 if (p
->hook_fn
== hook_fn
)
1026 wipe_password (char *passwd
)
1037 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1038 /* Returns a newly allocated string */
1040 convert_controls (const char *p
)
1042 char *valcopy
= g_strdup (p
);
1045 /* Parse the escape special character */
1046 for (q
= valcopy
; *p
;){
1049 if ((*p
== 'e') || (*p
== 'E')){
1059 char c
= (*p
| 0x20);
1060 if (c
>= 'a' && c
<= 'z') {
1075 resolve_symlinks (const char *path
)
1077 char *buf
, *buf2
, *q
, *r
, c
;
1082 if (*path
!= PATH_SEP
)
1084 r
= buf
= g_malloc (MC_MAXPATHLEN
);
1085 buf2
= g_malloc (MC_MAXPATHLEN
);
1090 q
= strchr (p
+ 1, PATH_SEP
);
1092 q
= strchr (p
+ 1, 0);
1098 if (mc_lstat (path
, &mybuf
) < 0) {
1104 if (!S_ISLNK (mybuf
.st_mode
))
1107 len
= mc_readlink (path
, buf2
, MC_MAXPATHLEN
- 1);
1115 if (*buf2
== PATH_SEP
)
1120 canonicalize_pathname (buf
);
1121 r
= strchr (buf
, 0);
1122 if (!*r
|| *(r
- 1) != PATH_SEP
) {
1132 strcpy (buf
, PATH_SEP_STR
);
1133 else if (*(r
- 1) == PATH_SEP
&& r
!= buf
+ 1)
1140 mc_util_write_backup_content(const char *from_file_name
, const char *to_file_name
)
1146 if (!g_file_get_contents (from_file_name
, &contents
, &length
, NULL
))
1149 backup_fd
= fopen (to_file_name
, "w");
1150 if (backup_fd
== NULL
) {
1155 fwrite ( (const void *) contents
, length
, 1, backup_fd
);
1163 /* Finds out a relative path from first to second, i.e. goes as many ..
1164 * as needed up in first and then goes down using second */
1166 diff_two_paths (const char *first
, const char *second
)
1168 char *p
, *q
, *r
, *s
, *buf
= NULL
;
1169 int i
, j
, prevlen
= -1, currlen
;
1170 char *my_first
= NULL
, *my_second
= NULL
;
1172 my_first
= resolve_symlinks (first
);
1173 if (my_first
== NULL
)
1175 my_second
= resolve_symlinks (second
);
1176 if (my_second
== NULL
) {
1180 for (j
= 0; j
< 2; j
++) {
1184 r
= strchr (p
, PATH_SEP
);
1185 s
= strchr (q
, PATH_SEP
);
1189 if (strcmp (p
, q
)) {
1190 *r
= PATH_SEP
; *s
= PATH_SEP
;
1193 *r
= PATH_SEP
; *s
= PATH_SEP
;
1199 for (i
= 0; (p
= strchr (p
+ 1, PATH_SEP
)) != NULL
; i
++);
1200 currlen
= (i
+ 1) * 3 + strlen (q
) + 1;
1202 if (currlen
< prevlen
)
1210 p
= buf
= g_malloc (currlen
);
1212 for (; i
>= 0; i
--, p
+= 3)
1221 /* If filename is NULL, then we just append PATH_SEP to the dir */
1223 concat_dir_and_file (const char *dir
, const char *file
)
1225 int i
= strlen (dir
);
1227 if (dir
[i
-1] == PATH_SEP
)
1228 return g_strconcat (dir
, file
, (char *) NULL
);
1230 return g_strconcat (dir
, PATH_SEP_STR
, file
, (char *) NULL
);
1233 /* Append text to GList, remove all entries with the same text */
1235 list_append_unique (GList
*list
, char *text
)
1237 GList
*lc_link
, *newlink
, *tmp
;
1240 * Go to the last position and traverse the list backwards
1241 * starting from the second last entry to make sure that we
1242 * are not removing the current link.
1244 list
= g_list_append (list
, text
);
1245 list
= g_list_last (list
);
1246 lc_link
= g_list_previous (list
);
1249 newlink
= g_list_previous (lc_link
);
1250 if (!strcmp ((char *) lc_link
->data
, text
)) {
1251 g_free (lc_link
->data
);
1252 tmp
= g_list_remove_link (list
, lc_link
);
1253 g_list_free_1 (lc_link
);
1261 /* Following code heavily borrows from libiberty, mkstemps.c */
1263 /* Number of attempts to create a temporary file */
1265 #define TMP_MAX 16384
1266 #endif /* !TMP_MAX */
1270 * pname (output) - pointer to the name of the temp file (needs g_free).
1271 * NULL if the function fails.
1272 * prefix - part of the filename before the random part.
1273 * Prepend $TMPDIR or /tmp if there are no path separators.
1274 * suffix - if not NULL, part of the filename after the random part.
1277 * handle of the open file or -1 if couldn't open any.
1280 mc_mkstemps (char **pname
, const char *prefix
, const char *suffix
)
1282 static const char letters
[]
1283 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1284 static unsigned long value
;
1291 if (strchr (prefix
, PATH_SEP
) == NULL
) {
1292 /* Add prefix first to find the position of XXXXXX */
1293 tmpbase
= concat_dir_and_file (mc_tmpdir (), prefix
);
1295 tmpbase
= g_strdup (prefix
);
1298 tmpname
= g_strconcat (tmpbase
, "XXXXXX", suffix
, (char *) NULL
);
1300 XXXXXX
= &tmpname
[strlen (tmpbase
)];
1303 /* Get some more or less random data. */
1304 gettimeofday (&tv
, NULL
);
1305 value
+= (tv
.tv_usec
<< 16) ^ tv
.tv_sec
^ getpid ();
1307 for (count
= 0; count
< TMP_MAX
; ++count
) {
1308 unsigned long v
= value
;
1311 /* Fill in the random bits. */
1312 XXXXXX
[0] = letters
[v
% 62];
1314 XXXXXX
[1] = letters
[v
% 62];
1316 XXXXXX
[2] = letters
[v
% 62];
1318 XXXXXX
[3] = letters
[v
% 62];
1320 XXXXXX
[4] = letters
[v
% 62];
1322 XXXXXX
[5] = letters
[v
% 62];
1324 fd
= open (tmpname
, O_RDWR
| O_CREAT
| O_TRUNC
| O_EXCL
,
1327 /* Successfully created. */
1331 /* This is a random value. It is only necessary that the next
1332 TMP_MAX values generated by adding 7777 to VALUE are different
1333 with (module 2^32). */
1337 /* Unsuccessful. Free the filename. */
1345 * Read and restore position for the given filename.
1346 * If there is no stored data, return line 1 and col 0.
1349 load_file_position (const char *filename
, long *line
, long *column
, off_t
*offset
)
1353 char buf
[MC_MAXPATHLEN
+ 20];
1361 /* open file with positions */
1362 fn
= g_build_filename (home_dir
, MC_USERCONF_DIR
, MC_FILEPOS_FILE
, NULL
);
1363 f
= fopen (fn
, "r");
1368 len
= strlen (filename
);
1370 while (fgets (buf
, sizeof (buf
), f
)) {
1374 /* check if the filename matches the beginning of string */
1375 if (strncmp (buf
, filename
, len
) != 0)
1378 /* followed by single space */
1379 if (buf
[len
] != ' ')
1382 /* and string without spaces */
1384 if (strchr (p
, ' '))
1387 pos_tokens
= g_strsplit_set (p
, ";", 3);
1388 if (pos_tokens
[0] != NULL
) {
1389 *line
= strtol (pos_tokens
[0], NULL
, 10);
1390 if (pos_tokens
[1] != NULL
) {
1391 *column
= strtol (pos_tokens
[1], NULL
, 10);
1392 if (pos_tokens
[2] != NULL
)
1393 *offset
= strtoll (pos_tokens
[2], NULL
, 10);
1405 g_strfreev(pos_tokens
);
1410 /* Save position for the given file */
1411 #define TMP_SUFFIX ".tmp"
1413 save_file_position (const char *filename
, long line
, long column
, off_t offset
)
1415 static int filepos_max_saved_entries
= 0;
1418 char buf
[MC_MAXPATHLEN
+ 20];
1422 if (filepos_max_saved_entries
== 0)
1423 filepos_max_saved_entries
= mc_config_get_int(mc_main_config
, CONFIG_APP_SECTION
, "filepos_max_saved_entries", 1024);
1425 fn
= g_build_filename (home_dir
, MC_USERCONF_DIR
, MC_FILEPOS_FILE
, NULL
);
1429 len
= strlen (filename
);
1431 mc_util_make_backup_if_possible (fn
, TMP_SUFFIX
);
1434 f
= fopen (fn
, "w");
1436 goto open_target_error
;
1438 tmp_fn
= g_strdup_printf("%s" TMP_SUFFIX
,fn
);
1439 tmp_f
= fopen (tmp_fn
, "r");
1441 goto open_source_error
;
1443 /* put the new record */
1444 if (line
!= 1 || column
!= 0) {
1445 if (fprintf (f
, "%s %ld;%ld;%lli\n", filename
, line
, column
, offset
) < 0)
1446 goto write_position_error
;
1449 while (fgets (buf
, sizeof (buf
), tmp_f
)) {
1452 strncmp (buf
, filename
, len
) == 0 &&
1453 !strchr (&buf
[len
+ 1], ' ')
1457 fprintf (f
, "%s", buf
);
1458 if (++i
> filepos_max_saved_entries
)
1464 mc_util_unlink_backup_if_possible (fn
, TMP_SUFFIX
);
1468 write_position_error
:
1473 mc_util_restore_from_backup_if_possible (fn
, TMP_SUFFIX
);
1481 cstrcasestr (const char *haystack
, const char *needle
)
1483 char *nee
= str_create_search_needle (needle
, 0);
1484 const char *result
= str_search_first (haystack
, nee
, 0);
1485 str_release_search_needle (nee
, 0);
1490 cstrstr (const char *haystack
, const char *needle
)
1492 return strstr(haystack
, needle
);
1496 str_unconst (const char *s
)
1501 #define ASCII_A (0x40 + 1)
1502 #define ASCII_Z (0x40 + 26)
1503 #define ASCII_a (0x60 + 1)
1504 #define ASCII_z (0x60 + 26)
1507 ascii_alpha_to_cntrl (int ch
)
1509 if ((ch
>= ASCII_A
&& ch
<= ASCII_Z
)
1510 || (ch
>= ASCII_a
&& ch
<= ASCII_z
)) {
1519 const char *result
, *sep
;
1522 sep
= strchr(result
, '|');
1523 return (sep
!= NULL
) ? sep
+ 1 : result
;
1528 mc_util_make_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1530 struct stat stat_buf
;
1533 if (!exist_file (file_name
))
1536 backup_path
= g_strdup_printf("%s%s",file_name
,backup_suffix
);
1538 if (backup_path
== NULL
)
1541 ret
= mc_util_write_backup_content (file_name
, backup_path
);
1544 /* Backup file will have same ownership with main file. */
1545 if (stat (file_name
, &stat_buf
) == 0)
1546 chmod (backup_path
, stat_buf
.st_mode
);
1548 chmod (backup_path
, S_IRUSR
| S_IWUSR
);
1551 g_free(backup_path
);
1557 mc_util_restore_from_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1562 backup_path
= g_strdup_printf("%s%s",file_name
,backup_suffix
);
1563 if (backup_path
== NULL
)
1566 ret
= mc_util_write_backup_content (backup_path
, file_name
);
1567 g_free(backup_path
);
1573 mc_util_unlink_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1577 backup_path
= g_strdup_printf("%s%s",file_name
,backup_suffix
);
1578 if (backup_path
== NULL
)
1581 if (exist_file (backup_path
))
1582 mc_unlink (backup_path
);
1584 g_free(backup_path
);
1588 /* partly taken from dcigettext.c, returns "" for default locale */
1589 /* value should be freed by calling function g_free() */
1590 char *guess_message_value (void)
1592 static const char * const var
[] = {
1593 /* Setting of LC_ALL overwrites all other. */
1594 /* Do not use LANGUAGE for check user locale and drowing hints */
1596 /* Next comes the name of the desired category. */
1598 /* Last possibility is the LANG environment variable. */
1600 /* NULL exit loops */
1605 const char *locale
= NULL
;
1607 while (var
[i
] != NULL
) {
1608 locale
= getenv (var
[i
]);
1609 if (locale
!= NULL
&& locale
[0] != '\0')
1617 return g_strdup (locale
);