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/filegui.h"
53 #include "src/file.h" /* copy_file_file() */
55 #include "src/main.h" /* eight_bit_clean */
58 int easy_patterns
= 1;
60 char *user_recent_timeformat
= NULL
; /* time format string for recent dates */
61 char *user_old_timeformat
= NULL
; /* time format string for older dates */
64 * Cache variable for the i18n_checktimelength function,
65 * initially set to a clearly invalid value to show that
66 * it hasn't been initialized yet.
68 static size_t i18n_timelength_cache
= MAX_I18NTIMELENGTH
+ 1;
71 str_replace (char *s
, char from
, char to
)
73 for (; *s
!= '\0'; s
++)
81 is_7bit_printable (unsigned char c
)
83 return (c
> 31 && c
< 127);
87 is_iso_printable (unsigned char c
)
89 return ((c
> 31 && c
< 127) || c
>= 160);
93 is_8bit_printable (unsigned char c
)
95 /* "Full 8 bits output" doesn't work on xterm */
97 return is_iso_printable (c
);
99 return (c
> 31 && c
!= 127 && c
!= 155);
108 /* "Display bits" is ignored, since the user controls the output
109 by setting the output codepage */
110 return is_8bit_printable (c
);
112 if (!eight_bit_clean
)
113 return is_7bit_printable (c
);
117 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
++)
142 if (colindex
> ncolumns
)
152 * Copy from s to d, and trim the beginning if necessary, and prepend
153 * "..." in this case. The destination string can have at most len
154 * bytes, not counting trailing 0.
157 trim (const char *s
, char *d
, int len
)
164 source_len
= strlen (s
);
165 if (source_len
> len
)
167 /* Cannot fit the whole line */
170 /* We only have room for the dots */
171 memset (d
, '.', len
);
177 /* Begin with ... and add the rest of the source string */
179 strcpy (d
+ 3, s
+ 3 + source_len
- len
);
183 /* We can copy the whole line */
189 * Quote the filename for the purpose of inserting it into the command
190 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
191 * processed by the mc command line.
194 name_quote (const char *s
, int quote_percent
)
198 d
= ret
= g_malloc (strlen (s
) * 2 + 2 + 1);
251 fake_name_quote (const char *s
, int quote_percent
)
253 (void) quote_percent
;
258 * Remove the middle part of the string to fit given length.
259 * Use "~" to show where the string was truncated.
260 * Return static buffer, no need to free() it.
263 name_trunc (const char *txt
, size_t trunc_len
)
265 return str_trunc (txt
, trunc_len
);
269 * path_trunc() is the same as name_trunc() above but
270 * it deletes possible password from path for security
274 path_trunc (const char *path
, size_t trunc_len
)
276 char *secure_path
= strip_password (g_strdup (path
), 1);
278 const char *ret
= str_trunc (secure_path
, trunc_len
);
279 g_free (secure_path
);
285 size_trunc (double size
, gboolean use_si
)
287 static char x
[BUF_TINY
];
288 long int divisor
= 1;
289 const char *xtra
= "";
291 if (size
> 999999999L)
293 divisor
= use_si
? 1000 : 1024;
294 xtra
= use_si
? "k" : "K";
295 if (size
/ divisor
> 999999999L)
297 divisor
= use_si
? (1000 * 1000) : (1024 * 1024);
298 xtra
= use_si
? "m" : "M";
301 g_snprintf (x
, sizeof (x
), "%.0f%s", (size
/ divisor
), xtra
);
306 size_trunc_sep (double size
, gboolean use_si
)
313 p
= y
= size_trunc (size
, use_si
);
315 d
= x
+ sizeof (x
) - 1;
317 while (p
>= y
&& isalpha ((unsigned char) *p
))
319 for (count
= 0; p
>= y
; count
++)
335 * Print file SIZE to BUFFER, but don't exceed LEN characters,
336 * not including trailing 0. BUFFER should be at least LEN+1 long.
337 * This function is called for every file on panels, so avoid
338 * floating point by any means.
340 * Units: size units (filesystem sizes are 1K blocks)
341 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
344 size_trunc_len (char *buffer
, unsigned int len
, off_t size
, int units
, gboolean use_si
)
346 /* Avoid taking power for every file. */
347 static const off_t power10
[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
350 static const char *const suffix
[] = { "", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL
};
351 static const char *const suffix_lc
[] = { "", "k", "m", "g", "t", "p", "e", "z", "y", NULL
};
359 * recalculate from 1024 base to 1000 base if units>0
360 * We can't just multiply by 1024 - that might cause overflow
361 * if off_t type is too small
365 for (j
= 0; j
< units
; j
++)
367 size_remain
= ((size
% 125) * 1024) / 1000; /* size mod 125, recalculated */
368 size
= size
/ 125; /* 128/125 = 1024/1000 */
369 size
= size
* 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
370 size
+= size_remain
; /* Re-add remainder lost by division/multiplication */
374 for (j
= units
; suffix
[j
] != NULL
; j
++)
380 /* Empty files will print "0" even with minimal width. */
381 g_snprintf (buffer
, len
+ 1, "0");
385 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
386 g_snprintf (buffer
, len
+ 1, (len
> 1) ? "~%s" : "%s",
387 (j
> 1) ? (use_si
? suffix_lc
[j
- 1] : suffix
[j
- 1]) : "B");
391 if (size
< power10
[len
- (j
> 0)])
393 g_snprintf (buffer
, len
+ 1, "%lu%s", (unsigned long) size
,
394 use_si
? suffix_lc
[j
] : suffix
[j
]);
398 /* Powers of 1000 or 1024, with rounding. */
400 size
= (size
+ 500) / 1000;
402 size
= (size
+ 512) >> 10;
409 if ((S_IXUSR
& mode
) || (S_IXGRP
& mode
) || (S_IXOTH
& mode
))
414 #define ismode(n,m) ((n & m) == m)
417 string_perm (mode_t mode_bits
)
419 static char mode
[11];
421 strcpy (mode
, "----------");
422 if (S_ISDIR (mode_bits
))
424 if (S_ISCHR (mode_bits
))
426 if (S_ISBLK (mode_bits
))
428 if (S_ISLNK (mode_bits
))
430 if (S_ISFIFO (mode_bits
))
432 if (S_ISNAM (mode_bits
))
434 if (S_ISSOCK (mode_bits
))
436 if (S_ISDOOR (mode_bits
))
438 if (ismode (mode_bits
, S_IXOTH
))
440 if (ismode (mode_bits
, S_IWOTH
))
442 if (ismode (mode_bits
, S_IROTH
))
444 if (ismode (mode_bits
, S_IXGRP
))
446 if (ismode (mode_bits
, S_IWGRP
))
448 if (ismode (mode_bits
, S_IRGRP
))
450 if (ismode (mode_bits
, S_IXUSR
))
452 if (ismode (mode_bits
, S_IWUSR
))
454 if (ismode (mode_bits
, S_IRUSR
))
457 if (ismode (mode_bits
, S_ISUID
))
458 mode
[3] = (mode
[3] == 'x') ? 's' : 'S';
461 if (ismode (mode_bits
, S_ISGID
))
462 mode
[6] = (mode
[6] == 'x') ? 's' : 'S';
465 if (ismode (mode_bits
, S_ISVTX
))
466 mode
[9] = (mode
[9] == 'x') ? 't' : 'T';
471 /* p: string which might contain an url with a password (this parameter is
473 has_prefix = 0: The first parameter is an url without a prefix
474 (user[:pass]@]machine[:port][remote-dir). Delete
476 has_prefix = 1: Search p for known url prefixes. If found delete
477 the password from the url.
478 Caveat: only the first url is found
481 strip_password (char *p
, int has_prefix
)
500 char *at
, *inner_colon
, *dir
;
504 for (i
= 0; i
< sizeof (prefixes
) / sizeof (prefixes
[0]); i
++)
510 q
= strstr (p
, prefixes
[i
].name
);
514 p
= q
+ prefixes
[i
].len
;
517 dir
= strchr (p
, PATH_SEP
);
521 /* search for any possible user */
522 at
= strrchr (p
, '@');
527 /* We have a username */
530 inner_colon
= memchr (p
, ':', at
- p
);
532 memmove (inner_colon
, at
, strlen (at
) + 1);
540 strip_home_and_password (const char *dir
)
543 static char newdir
[MC_MAXPATHLEN
];
545 len
= strlen (home_dir
);
546 if (home_dir
!= NULL
&& strncmp (dir
, home_dir
, len
) == 0 &&
547 (dir
[len
] == PATH_SEP
|| dir
[len
] == '\0'))
550 g_strlcpy (&newdir
[1], &dir
[len
], sizeof (newdir
) - 1);
554 /* We do not strip homes in /#ftp tree, I do not like ~'s there
556 g_strlcpy (newdir
, dir
, sizeof (newdir
));
557 strip_password (newdir
, 1);
562 extension (const char *filename
)
564 const char *d
= strrchr (filename
, '.');
565 return (d
!= NULL
) ? d
+ 1 : "";
569 exist_file (const char *name
)
571 return access (name
, R_OK
) == 0;
575 check_for_default (const char *default_file
, const char *file
)
577 if (!exist_file (file
))
580 FileOpTotalContext
*tctx
;
582 if (!exist_file (default_file
))
585 ctx
= file_op_context_new (OP_COPY
);
586 tctx
= file_op_total_context_new ();
587 file_op_context_create_ui (ctx
, 0, FALSE
);
588 copy_file_file (tctx
, ctx
, default_file
, file
);
589 file_op_total_context_destroy (tctx
);
590 file_op_context_destroy (ctx
);
599 load_file (const char *filename
)
606 data_file
= fopen (filename
, "r");
607 if (data_file
== NULL
)
611 if (fstat (fileno (data_file
), &s
) != 0)
616 data
= g_malloc (s
.st_size
+ 1);
617 read_size
= fread (data
, 1, s
.st_size
, data_file
);
631 load_mc_home_file (const char *_mc_home
, const char *_mc_home_alt
, const char *filename
,
632 char **allocated_filename
)
634 char *hintfile_base
, *hintfile
;
638 hintfile_base
= concat_dir_and_file (_mc_home
, filename
);
639 lang
= guess_message_value ();
641 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
642 data
= load_file (hintfile
);
647 g_free (hintfile_base
);
648 hintfile_base
= concat_dir_and_file (_mc_home_alt
, filename
);
650 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
651 data
= load_file (hintfile
);
655 /* Fall back to the two-letter language code */
656 if (lang
[0] && lang
[1])
659 hintfile
= g_strconcat (hintfile_base
, ".", lang
, (char *) NULL
);
660 data
= load_file (hintfile
);
665 hintfile
= hintfile_base
;
666 data
= load_file (hintfile_base
);
673 if (hintfile
!= hintfile_base
)
674 g_free (hintfile_base
);
676 if (allocated_filename
)
677 *allocated_filename
= hintfile
;
684 /* Check strftime() results. Some systems (i.e. Solaris) have different
685 short-month and month name sizes for different locales */
687 i18n_checktimelength (void)
690 const time_t testtime
= time (NULL
);
691 struct tm
*lt
= localtime (&testtime
);
693 if (i18n_timelength_cache
<= MAX_I18NTIMELENGTH
)
694 return i18n_timelength_cache
;
698 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
699 length
= str_term_width1 (_(INVALID_TIME_TEXT
));
703 char buf
[MB_LEN_MAX
* MAX_I18NTIMELENGTH
+ 1];
705 /* We are interested in the longest possible date */
706 lt
->tm_sec
= lt
->tm_min
= lt
->tm_hour
= lt
->tm_mday
= 10;
708 /* Loop through all months to find out the longest one */
709 for (lt
->tm_mon
= 0; lt
->tm_mon
< 12; lt
->tm_mon
++) {
710 strftime (buf
, sizeof(buf
) - 1, user_recent_timeformat
, lt
);
711 length
= max ((size_t) str_term_width1 (buf
), length
);
712 strftime (buf
, sizeof(buf
) - 1, user_old_timeformat
, lt
);
713 length
= max ((size_t) str_term_width1 (buf
), length
);
716 length
= max ((size_t) str_term_width1 (_(INVALID_TIME_TEXT
)), length
);
719 /* Don't handle big differences. Use standard value (email bug, please) */
720 if (length
> MAX_I18NTIMELENGTH
|| length
< MIN_I18NTIMELENGTH
)
721 length
= STD_I18NTIMELENGTH
;
723 /* Save obtained value to the cache */
724 i18n_timelength_cache
= length
;
726 return i18n_timelength_cache
;
730 file_date (time_t when
)
732 static char timebuf
[MB_LEN_MAX
* MAX_I18NTIMELENGTH
+ 1];
733 time_t current_time
= time ((time_t) 0);
736 if (current_time
> when
+ 6L * 30L * 24L * 60L * 60L /* Old. */
737 || current_time
< when
- 60L * 60L) /* In the future. */
738 /* The file is fairly old or in the future.
739 POSIX says the cutoff is 6 months old;
740 approximate this by 6*30 days.
741 Allow a 1 hour slop factor for what is considered "the future",
742 to allow for NFS server/client clock disagreement.
743 Show the year instead of the time of day. */
745 fmt
= user_old_timeformat
;
747 fmt
= user_recent_timeformat
;
749 FMT_LOCALTIME (timebuf
, sizeof (timebuf
), fmt
, when
);
755 extract_line (const char *s
, const char *top
)
757 static char tmp_line
[BUF_MEDIUM
];
760 while (*s
&& *s
!= '\n' && (size_t) (t
- tmp_line
) < sizeof (tmp_line
) - 1 && s
< top
)
766 /* The basename routine */
768 x_basename (const char *s
)
771 return ((where
= strrchr (s
, PATH_SEP
))) ? where
+ 1 : s
;
776 unix_error_string (int error_num
)
778 static char buffer
[BUF_LARGE
];
779 gchar
*strerror_currentlocale
;
781 strerror_currentlocale
= g_locale_from_utf8 (g_strerror (error_num
), -1, NULL
, NULL
, NULL
);
782 g_snprintf (buffer
, sizeof (buffer
), "%s (%d)", strerror_currentlocale
, error_num
);
783 g_free (strerror_currentlocale
);
789 skip_separators (const char *s
)
793 for (; *su
; str_cnext_char (&su
))
794 if (*su
!= ' ' && *su
!= '\t' && *su
!= ',')
801 skip_numbers (const char *s
)
805 for (; *su
; str_cnext_char (&su
))
806 if (!str_isdigit (su
))
812 /* Remove all control sequences from the argument string. We define
813 * "control sequence", in a sort of pidgin BNF, as follows:
815 * control-seq = Esc non-'['
816 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
818 * This scheme works for all the terminals described in my termcap /
819 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
820 * terminals. If I hear from a single person who uses such a terminal
821 * with MC, I'll be glad to add support for it. (Dugan)
822 * Non-printable characters are also removed.
826 strip_ctrl_codes (char *s
)
828 char *w
; /* Current position where the stripped data is written */
829 char *r
; /* Current position where the original data is read */
835 for (w
= s
, r
= s
; *r
;)
839 /* Skip the control sequence's arguments */ ;
840 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
841 if (*(++r
) == '[' || *r
== '(')
843 /* strchr() matches trailing binary 0 */
844 while (*(++r
) && strchr ("0123456789;?", *r
));
849 * Skip xterm's OSC (Operating System Command)
850 * http://www.xfree86.org/current/ctlseqs.html
856 for (; *new_r
; ++new_r
)
866 if (*(new_r
+ 1) == '\\')
877 * Now we are at the last character of the sequence.
878 * Skip it unless it's binary 0.
885 n
= str_get_next_char (r
);
888 memmove (w
, r
, n
- r
);
900 get_current_wd (char *buffer
, size_t size
)
905 p
= g_get_current_dir ();
906 len
= strlen (p
) + 1;
914 memcpy (buffer
, p
, len
);
919 #endif /* !ENABLE_VFS */
921 enum compression_type
922 get_compression_type (int fd
, const char *name
)
924 unsigned char magic
[16];
927 /* Read the magic signature */
928 if (mc_read (fd
, (char *) magic
, 4) != 4)
929 return COMPRESSION_NONE
;
931 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
932 if (magic
[0] == 037 && (magic
[1] == 0213 || magic
[1] == 0236))
934 return COMPRESSION_GZIP
;
938 if (magic
[0] == 0120 && magic
[1] == 0113 && magic
[2] == 003 && magic
[3] == 004)
940 /* Read compression type */
941 mc_lseek (fd
, 8, SEEK_SET
);
942 if (mc_read (fd
, (char *) magic
, 2) != 2)
943 return COMPRESSION_NONE
;
945 /* Gzip can handle only deflated (8) or stored (0) files */
946 if ((magic
[0] != 8 && magic
[0] != 0) || magic
[1] != 0)
947 return COMPRESSION_NONE
;
949 /* Compatible with gzip */
950 return COMPRESSION_GZIP
;
953 /* PACK_MAGIC and LZH_MAGIC and compress magic */
954 if (magic
[0] == 037 && (magic
[1] == 036 || magic
[1] == 0240 || magic
[1] == 0235))
956 /* Compatible with gzip */
957 return COMPRESSION_GZIP
;
960 /* BZIP and BZIP2 files */
961 if ((magic
[0] == 'B') && (magic
[1] == 'Z') && (magic
[3] >= '1') && (magic
[3] <= '9'))
966 return COMPRESSION_BZIP
;
968 return COMPRESSION_BZIP2
;
972 /* Support for LZMA (only utils format with magic in header).
973 * This is the default format of LZMA utils 4.32.1 and later. */
975 if (mc_read (fd
, (char *) magic
+ 4, 2) != 2)
976 return COMPRESSION_NONE
;
978 /* LZMA utils format */
981 && magic
[2] == 'Z' && magic
[3] == 'M' && magic
[4] == 'A' && magic
[5] == 0x00)
982 return COMPRESSION_LZMA
;
984 /* XZ compression magic */
987 && magic
[2] == 0x7A && magic
[3] == 0x58 && magic
[4] == 0x5A && magic
[5] == 0x00)
988 return COMPRESSION_XZ
;
990 str_len
= strlen (name
);
991 /* HACK: we must belive to extention of LZMA file :) ... */
992 if ((str_len
> 5 && strcmp (&name
[str_len
- 5], ".lzma") == 0) ||
993 (str_len
> 4 && strcmp (&name
[str_len
- 4], ".tlz") == 0))
994 return COMPRESSION_LZMA
;
996 return COMPRESSION_NONE
;
1000 decompress_extension (int type
)
1004 case COMPRESSION_GZIP
:
1006 case COMPRESSION_BZIP
:
1008 case COMPRESSION_BZIP2
:
1010 case COMPRESSION_LZMA
:
1012 case COMPRESSION_XZ
:
1015 /* Should never reach this place */
1016 fprintf (stderr
, "Fatal: decompress_extension called with an unknown argument\n");
1022 add_hook (Hook
** hook_list
, void (*hook_fn
) (void *), void *data
)
1024 Hook
*new_hook
= g_new (Hook
, 1);
1026 new_hook
->hook_fn
= hook_fn
;
1027 new_hook
->next
= *hook_list
;
1028 new_hook
->hook_data
= data
;
1030 *hook_list
= new_hook
;
1034 execute_hooks (Hook
* hook_list
)
1039 /* We copy the hook list first so tahat we let the hook
1040 * function call delete_hook
1045 add_hook (&new_hook
, hook_list
->hook_fn
, hook_list
->hook_data
);
1046 hook_list
= hook_list
->next
;
1052 (*new_hook
->hook_fn
) (new_hook
->hook_data
);
1053 new_hook
= new_hook
->next
;
1056 for (hook_list
= p
; hook_list
;)
1059 hook_list
= hook_list
->next
;
1065 delete_hook (Hook
** hook_list
, void (*hook_fn
) (void *))
1067 Hook
*current
, *new_list
, *next
;
1071 for (current
= *hook_list
; current
; current
= next
)
1073 next
= current
->next
;
1074 if (current
->hook_fn
== hook_fn
)
1077 add_hook (&new_list
, current
->hook_fn
, current
->hook_data
);
1079 *hook_list
= new_list
;
1083 hook_present (Hook
* hook_list
, void (*hook_fn
) (void *))
1087 for (p
= hook_list
; p
; p
= p
->next
)
1088 if (p
->hook_fn
== hook_fn
)
1094 wipe_password (char *passwd
)
1105 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1106 /* Returns a newly allocated string */
1108 convert_controls (const char *p
)
1110 char *valcopy
= g_strdup (p
);
1113 /* Parse the escape special character */
1114 for (q
= valcopy
; *p
;)
1119 if ((*p
== 'e') || (*p
== 'E'))
1134 char c
= (*p
| 0x20);
1135 if (c
>= 'a' && c
<= 'z')
1153 resolve_symlinks (const char *path
)
1155 char *buf
, *buf2
, *q
, *r
, c
;
1160 if (*path
!= PATH_SEP
)
1162 r
= buf
= g_malloc (MC_MAXPATHLEN
);
1163 buf2
= g_malloc (MC_MAXPATHLEN
);
1169 q
= strchr (p
+ 1, PATH_SEP
);
1172 q
= strchr (p
+ 1, 0);
1178 if (mc_lstat (path
, &mybuf
) < 0)
1185 if (!S_ISLNK (mybuf
.st_mode
))
1189 len
= mc_readlink (path
, buf2
, MC_MAXPATHLEN
- 1);
1198 if (*buf2
== PATH_SEP
)
1203 canonicalize_pathname (buf
);
1204 r
= strchr (buf
, 0);
1205 if (!*r
|| *(r
- 1) != PATH_SEP
)
1216 strcpy (buf
, PATH_SEP_STR
);
1217 else if (*(r
- 1) == PATH_SEP
&& r
!= buf
+ 1)
1224 mc_util_write_backup_content (const char *from_file_name
, const char *to_file_name
)
1229 gboolean ret1
= TRUE
;
1231 if (!g_file_get_contents (from_file_name
, &contents
, &length
, NULL
))
1234 backup_fd
= fopen (to_file_name
, "w");
1235 if (backup_fd
== NULL
)
1241 if (fwrite ((const void *) contents
, 1, length
, backup_fd
) != length
)
1245 ret2
= fflush (backup_fd
);
1246 ret2
= fclose (backup_fd
);
1252 /* Finds out a relative path from first to second, i.e. goes as many ..
1253 * as needed up in first and then goes down using second */
1255 diff_two_paths (const char *first
, const char *second
)
1257 char *p
, *q
, *r
, *s
, *buf
= NULL
;
1258 int i
, j
, prevlen
= -1, currlen
;
1259 char *my_first
= NULL
, *my_second
= NULL
;
1261 my_first
= resolve_symlinks (first
);
1262 if (my_first
== NULL
)
1264 my_second
= resolve_symlinks (second
);
1265 if (my_second
== NULL
)
1270 for (j
= 0; j
< 2; j
++)
1276 r
= strchr (p
, PATH_SEP
);
1277 s
= strchr (q
, PATH_SEP
);
1297 for (i
= 0; (p
= strchr (p
+ 1, PATH_SEP
)) != NULL
; i
++);
1298 currlen
= (i
+ 1) * 3 + strlen (q
) + 1;
1301 if (currlen
< prevlen
)
1310 p
= buf
= g_malloc (currlen
);
1312 for (; i
>= 0; i
--, p
+= 3)
1321 /* If filename is NULL, then we just append PATH_SEP to the dir */
1323 concat_dir_and_file (const char *dir
, const char *file
)
1325 int i
= strlen (dir
);
1327 if (dir
[i
- 1] == PATH_SEP
)
1328 return g_strconcat (dir
, file
, (char *) NULL
);
1330 return g_strconcat (dir
, PATH_SEP_STR
, file
, (char *) NULL
);
1333 /* Append text to GList, remove all entries with the same text */
1335 list_append_unique (GList
* list
, char *text
)
1340 * Go to the last position and traverse the list backwards
1341 * starting from the second last entry to make sure that we
1342 * are not removing the current link.
1344 list
= g_list_append (list
, text
);
1345 list
= g_list_last (list
);
1346 lc_link
= g_list_previous (list
);
1348 while (lc_link
!= NULL
)
1352 newlink
= g_list_previous (lc_link
);
1353 if (strcmp ((char *) lc_link
->data
, text
) == 0)
1357 g_free (lc_link
->data
);
1358 tmp
= g_list_remove_link (list
, lc_link
);
1359 g_list_free_1 (lc_link
);
1367 /* Following code heavily borrows from libiberty, mkstemps.c */
1369 /* Number of attempts to create a temporary file */
1371 #define TMP_MAX 16384
1372 #endif /* !TMP_MAX */
1376 * pname (output) - pointer to the name of the temp file (needs g_free).
1377 * NULL if the function fails.
1378 * prefix - part of the filename before the random part.
1379 * Prepend $TMPDIR or /tmp if there are no path separators.
1380 * suffix - if not NULL, part of the filename after the random part.
1383 * handle of the open file or -1 if couldn't open any.
1386 mc_mkstemps (char **pname
, const char *prefix
, const char *suffix
)
1388 static const char letters
[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1389 static unsigned long value
;
1396 if (strchr (prefix
, PATH_SEP
) == NULL
)
1398 /* Add prefix first to find the position of XXXXXX */
1399 tmpbase
= concat_dir_and_file (mc_tmpdir (), prefix
);
1403 tmpbase
= g_strdup (prefix
);
1406 tmpname
= g_strconcat (tmpbase
, "XXXXXX", suffix
, (char *) NULL
);
1408 XXXXXX
= &tmpname
[strlen (tmpbase
)];
1411 /* Get some more or less random data. */
1412 gettimeofday (&tv
, NULL
);
1413 value
+= (tv
.tv_usec
<< 16) ^ tv
.tv_sec
^ getpid ();
1415 for (count
= 0; count
< TMP_MAX
; ++count
)
1417 unsigned long v
= value
;
1420 /* Fill in the random bits. */
1421 XXXXXX
[0] = letters
[v
% 62];
1423 XXXXXX
[1] = letters
[v
% 62];
1425 XXXXXX
[2] = letters
[v
% 62];
1427 XXXXXX
[3] = letters
[v
% 62];
1429 XXXXXX
[4] = letters
[v
% 62];
1431 XXXXXX
[5] = letters
[v
% 62];
1433 fd
= open (tmpname
, O_RDWR
| O_CREAT
| O_TRUNC
| O_EXCL
, S_IRUSR
| S_IWUSR
);
1436 /* Successfully created. */
1440 /* This is a random value. It is only necessary that the next
1441 TMP_MAX values generated by adding 7777 to VALUE are different
1442 with (module 2^32). */
1446 /* Unsuccessful. Free the filename. */
1454 * Read and restore position for the given filename.
1455 * If there is no stored data, return line 1 and col 0.
1458 load_file_position (const char *filename
, long *line
, long *column
, off_t
* offset
)
1462 char buf
[MC_MAXPATHLEN
+ 20];
1470 /* open file with positions */
1471 fn
= g_build_filename (home_dir
, MC_USERCONF_DIR
, MC_FILEPOS_FILE
, NULL
);
1472 f
= fopen (fn
, "r");
1477 len
= strlen (filename
);
1479 while (fgets (buf
, sizeof (buf
), f
))
1484 /* check if the filename matches the beginning of string */
1485 if (strncmp (buf
, filename
, len
) != 0)
1488 /* followed by single space */
1489 if (buf
[len
] != ' ')
1492 /* and string without spaces */
1494 if (strchr (p
, ' '))
1497 pos_tokens
= g_strsplit_set (p
, ";", 3);
1498 if (pos_tokens
[0] != NULL
)
1500 *line
= strtol (pos_tokens
[0], NULL
, 10);
1501 if (pos_tokens
[1] != NULL
)
1503 *column
= strtol (pos_tokens
[1], NULL
, 10);
1504 if (pos_tokens
[2] != NULL
)
1505 *offset
= strtoll (pos_tokens
[2], NULL
, 10);
1521 g_strfreev (pos_tokens
);
1526 /* Save position for the given file */
1527 #define TMP_SUFFIX ".tmp"
1529 save_file_position (const char *filename
, long line
, long column
, off_t offset
)
1531 static int filepos_max_saved_entries
= 0;
1534 char buf
[MC_MAXPATHLEN
+ 20];
1538 if (filepos_max_saved_entries
== 0)
1539 filepos_max_saved_entries
=
1540 mc_config_get_int (mc_main_config
, CONFIG_APP_SECTION
, "filepos_max_saved_entries",
1543 fn
= g_build_filename (home_dir
, MC_USERCONF_DIR
, MC_FILEPOS_FILE
, NULL
);
1547 len
= strlen (filename
);
1549 mc_util_make_backup_if_possible (fn
, TMP_SUFFIX
);
1552 f
= fopen (fn
, "w");
1554 goto open_target_error
;
1556 tmp_fn
= g_strdup_printf ("%s" TMP_SUFFIX
, fn
);
1557 tmp_f
= fopen (tmp_fn
, "r");
1559 goto open_source_error
;
1561 /* put the new record */
1562 if (line
!= 1 || column
!= 0)
1564 if (fprintf (f
, "%s %ld;%ld;%llu\n", filename
, line
, column
, (unsigned long long) offset
) <
1566 goto write_position_error
;
1569 while (fgets (buf
, sizeof (buf
), tmp_f
))
1571 if (buf
[len
] == ' ' && strncmp (buf
, filename
, len
) == 0 && !strchr (&buf
[len
+ 1], ' '))
1574 fprintf (f
, "%s", buf
);
1575 if (++i
> filepos_max_saved_entries
)
1581 mc_util_unlink_backup_if_possible (fn
, TMP_SUFFIX
);
1585 write_position_error
:
1590 mc_util_restore_from_backup_if_possible (fn
, TMP_SUFFIX
);
1599 cstrcasestr (const char *haystack
, const char *needle
)
1601 char *nee
= str_create_search_needle (needle
, 0);
1602 const char *result
= str_search_first (haystack
, nee
, 0);
1603 str_release_search_needle (nee
, 0);
1608 cstrstr (const char *haystack
, const char *needle
)
1610 return strstr (haystack
, needle
);
1614 str_unconst (const char *s
)
1619 #define ASCII_A (0x40 + 1)
1620 #define ASCII_Z (0x40 + 26)
1621 #define ASCII_a (0x60 + 1)
1622 #define ASCII_z (0x60 + 26)
1625 ascii_alpha_to_cntrl (int ch
)
1627 if ((ch
>= ASCII_A
&& ch
<= ASCII_Z
) || (ch
>= ASCII_a
&& ch
<= ASCII_z
))
1637 const char *result
, *sep
;
1640 sep
= strchr (result
, '|');
1641 return (sep
!= NULL
) ? sep
+ 1 : result
;
1646 mc_util_make_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1648 struct stat stat_buf
;
1651 if (!exist_file (file_name
))
1654 backup_path
= g_strdup_printf ("%s%s", file_name
, backup_suffix
);
1656 if (backup_path
== NULL
)
1659 ret
= mc_util_write_backup_content (file_name
, backup_path
);
1663 /* Backup file will have same ownership with main file. */
1664 if (stat (file_name
, &stat_buf
) == 0)
1665 chmod (backup_path
, stat_buf
.st_mode
);
1667 chmod (backup_path
, S_IRUSR
| S_IWUSR
);
1670 g_free (backup_path
);
1676 mc_util_restore_from_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1681 backup_path
= g_strdup_printf ("%s%s", file_name
, backup_suffix
);
1682 if (backup_path
== NULL
)
1685 ret
= mc_util_write_backup_content (backup_path
, file_name
);
1686 g_free (backup_path
);
1692 mc_util_unlink_backup_if_possible (const char *file_name
, const char *backup_suffix
)
1696 backup_path
= g_strdup_printf ("%s%s", file_name
, backup_suffix
);
1697 if (backup_path
== NULL
)
1700 if (exist_file (backup_path
))
1701 mc_unlink (backup_path
);
1703 g_free (backup_path
);
1707 /* partly taken from dcigettext.c, returns "" for default locale */
1708 /* value should be freed by calling function g_free() */
1710 guess_message_value (void)
1712 static const char *const var
[] = {
1713 /* Setting of LC_ALL overwrites all other. */
1714 /* Do not use LANGUAGE for check user locale and drowing hints */
1716 /* Next comes the name of the desired category. */
1718 /* Last possibility is the LANG environment variable. */
1720 /* NULL exit loops */
1725 const char *locale
= NULL
;
1727 while (var
[i
] != NULL
)
1729 locale
= getenv (var
[i
]);
1730 if (locale
!= NULL
&& locale
[0] != '\0')
1738 return g_strdup (locale
);