Ticket #2097: clean up before 4.7.2 release.
[midnight-commander.git] / lib / util.c
blobccfcb24036b215a855b1701ac1a95ee0806c4a2f
1 /* Various utilities
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. */
25 /** \file
26 * \brief Source: various utilities
29 #include <config.h>
31 #include <ctype.h>
32 #include <limits.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <fcntl.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.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() */
54 #ifndef HAVE_CHARSET
55 #include "src/main.h" /* eight_bit_clean */
56 #endif
58 int easy_patterns = 1;
61 * If true, SI units (1000 based) will be used for
62 * larger units (kilobyte, megabyte, ...).
63 * If false binary units (1024 based) will be used.
65 int kilobyte_si = 0;
67 char *user_recent_timeformat = NULL; /* time format string for recent dates */
68 char *user_old_timeformat = NULL; /* time format string for older dates */
71 * Cache variable for the i18n_checktimelength function,
72 * initially set to a clearly invalid value to show that
73 * it hasn't been initialized yet.
75 static size_t i18n_timelength_cache = MAX_I18NTIMELENGTH + 1;
77 extern void
78 str_replace (char *s, char from, char to)
80 for (; *s != '\0'; s++)
82 if (*s == from)
83 *s = to;
87 static inline int
88 is_7bit_printable (unsigned char c)
90 return (c > 31 && c < 127);
93 static inline int
94 is_iso_printable (unsigned char c)
96 return ((c > 31 && c < 127) || c >= 160);
99 static inline int
100 is_8bit_printable (unsigned char c)
102 /* "Full 8 bits output" doesn't work on xterm */
103 if (xterm_flag)
104 return is_iso_printable (c);
106 return (c > 31 && c != 127 && c != 155);
110 is_printable (int c)
112 c &= 0xff;
114 #ifdef HAVE_CHARSET
115 /* "Display bits" is ignored, since the user controls the output
116 by setting the output codepage */
117 return is_8bit_printable (c);
118 #else
119 if (!eight_bit_clean)
120 return is_7bit_printable (c);
122 if (full_eight_bits)
124 return is_8bit_printable (c);
126 else
127 return is_iso_printable (c);
128 #endif /* !HAVE_CHARSET */
131 /* Calculates the message dimensions (lines and columns) */
132 void
133 msglen (const char *text, int *lines, int *columns)
135 int nlines = 1; /* even the empty string takes one line */
136 int ncolumns = 0;
137 int colindex = 0;
139 for (; *text != '\0'; text++)
141 if (*text == '\n')
143 nlines++;
144 colindex = 0;
146 else
148 colindex++;
149 if (colindex > ncolumns)
150 ncolumns = colindex;
154 *lines = nlines;
155 *columns = ncolumns;
159 * Copy from s to d, and trim the beginning if necessary, and prepend
160 * "..." in this case. The destination string can have at most len
161 * bytes, not counting trailing 0.
163 char *
164 trim (const char *s, char *d, int len)
166 int source_len;
168 /* Sanity check */
169 len = max (len, 0);
171 source_len = strlen (s);
172 if (source_len > len)
174 /* Cannot fit the whole line */
175 if (len <= 3)
177 /* We only have room for the dots */
178 memset (d, '.', len);
179 d[len] = 0;
180 return d;
182 else
184 /* Begin with ... and add the rest of the source string */
185 memset (d, '.', 3);
186 strcpy (d + 3, s + 3 + source_len - len);
189 else
190 /* We can copy the whole line */
191 strcpy (d, s);
192 return d;
196 * Quote the filename for the purpose of inserting it into the command
197 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
198 * processed by the mc command line.
200 char *
201 name_quote (const char *s, int quote_percent)
203 char *ret, *d;
205 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
206 if (*s == '-')
208 *d++ = '.';
209 *d++ = '/';
212 for (; *s; s++, d++)
214 switch (*s)
216 case '%':
217 if (quote_percent)
218 *d++ = '%';
219 break;
220 case '\'':
221 case '\\':
222 case '\r':
223 case '\n':
224 case '\t':
225 case '"':
226 case ';':
227 case ' ':
228 case '?':
229 case '|':
230 case '[':
231 case ']':
232 case '{':
233 case '}':
234 case '<':
235 case '>':
236 case '`':
237 case '!':
238 case '$':
239 case '&':
240 case '*':
241 case '(':
242 case ')':
243 *d++ = '\\';
244 break;
245 case '~':
246 case '#':
247 if (d == ret)
248 *d++ = '\\';
249 break;
251 *d = *s;
253 *d = '\0';
254 return ret;
257 char *
258 fake_name_quote (const char *s, int quote_percent)
260 (void) quote_percent;
261 return g_strdup (s);
265 * Remove the middle part of the string to fit given length.
266 * Use "~" to show where the string was truncated.
267 * Return static buffer, no need to free() it.
269 const char *
270 name_trunc (const char *txt, size_t trunc_len)
272 return str_trunc (txt, trunc_len);
276 * path_trunc() is the same as name_trunc() above but
277 * it deletes possible password from path for security
278 * reasons.
280 const char *
281 path_trunc (const char *path, size_t trunc_len)
283 char *secure_path = strip_password (g_strdup (path), 1);
285 const char *ret = str_trunc (secure_path, trunc_len);
286 g_free (secure_path);
288 return ret;
291 const char *
292 size_trunc (double size)
294 static char x[BUF_TINY];
295 long int divisor = 1;
296 const char *xtra = "";
298 if (size > 999999999L)
300 divisor = kilobyte_si ? 1000 : 1024;
301 xtra = kilobyte_si ? "k" : "K";
302 if (size / divisor > 999999999L)
304 divisor = kilobyte_si ? (1000 * 1000) : (1024 * 1024);
305 xtra = kilobyte_si ? "m" : "M";
308 g_snprintf (x, sizeof (x), "%.0f%s", (size / divisor), xtra);
309 return x;
312 const char *
313 size_trunc_sep (double size)
315 static char x[60];
316 int count;
317 const char *p, *y;
318 char *d;
320 p = y = size_trunc (size);
321 p += strlen (p) - 1;
322 d = x + sizeof (x) - 1;
323 *d-- = 0;
324 while (p >= y && isalpha ((unsigned char) *p))
325 *d-- = *p--;
326 for (count = 0; p >= y; count++)
328 if (count == 3)
330 *d-- = ',';
331 count = 0;
333 *d-- = *p--;
335 d++;
336 if (*d == ',')
337 d++;
338 return d;
342 * Print file SIZE to BUFFER, but don't exceed LEN characters,
343 * not including trailing 0. BUFFER should be at least LEN+1 long.
344 * This function is called for every file on panels, so avoid
345 * floating point by any means.
347 * Units: size units (filesystem sizes are 1K blocks)
348 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
350 void
351 size_trunc_len (char *buffer, unsigned int len, off_t size, int units)
353 /* Avoid taking power for every file. */
354 static const off_t power10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
355 1000000000
357 static const char *const suffix[] = { "", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL };
358 static const char *const suffix_lc[] = { "", "k", "m", "g", "t", "p", "e", "z", "y", NULL };
359 int j = 0;
360 int size_remain;
362 if (len == 0)
363 len = 9;
366 * recalculate from 1024 base to 1000 base if units>0
367 * We can't just multiply by 1024 - that might cause overflow
368 * if off_t type is too small
370 if (units && kilobyte_si)
372 for (j = 0; j < units; j++)
374 size_remain = ((size % 125) * 1024) / 1000; /* size mod 125, recalculated */
375 size = size / 125; /* 128/125 = 1024/1000 */
376 size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
377 size += size_remain; /* Re-add remainder lost by division/multiplication */
381 for (j = units; suffix[j] != NULL; j++)
383 if (size == 0)
385 if (j == units)
387 /* Empty files will print "0" even with minimal width. */
388 g_snprintf (buffer, len + 1, "0");
389 break;
392 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
393 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
394 (j > 1) ? (kilobyte_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
395 break;
398 if (size < power10[len - (j > 0)])
400 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size,
401 kilobyte_si ? suffix_lc[j] : suffix[j]);
402 break;
405 /* Powers of 1000 or 1024, with rounding. */
406 if (kilobyte_si)
408 size = (size + 500) / 1000;
410 else
412 size = (size + 512) >> 10;
418 is_exe (mode_t mode)
420 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
421 return 1;
422 return 0;
425 #define ismode(n,m) ((n & m) == m)
427 const char *
428 string_perm (mode_t mode_bits)
430 static char mode[11];
432 strcpy (mode, "----------");
433 if (S_ISDIR (mode_bits))
434 mode[0] = 'd';
435 if (S_ISCHR (mode_bits))
436 mode[0] = 'c';
437 if (S_ISBLK (mode_bits))
438 mode[0] = 'b';
439 if (S_ISLNK (mode_bits))
440 mode[0] = 'l';
441 if (S_ISFIFO (mode_bits))
442 mode[0] = 'p';
443 if (S_ISNAM (mode_bits))
444 mode[0] = 'n';
445 if (S_ISSOCK (mode_bits))
446 mode[0] = 's';
447 if (S_ISDOOR (mode_bits))
448 mode[0] = 'D';
449 if (ismode (mode_bits, S_IXOTH))
450 mode[9] = 'x';
451 if (ismode (mode_bits, S_IWOTH))
452 mode[8] = 'w';
453 if (ismode (mode_bits, S_IROTH))
454 mode[7] = 'r';
455 if (ismode (mode_bits, S_IXGRP))
456 mode[6] = 'x';
457 if (ismode (mode_bits, S_IWGRP))
458 mode[5] = 'w';
459 if (ismode (mode_bits, S_IRGRP))
460 mode[4] = 'r';
461 if (ismode (mode_bits, S_IXUSR))
462 mode[3] = 'x';
463 if (ismode (mode_bits, S_IWUSR))
464 mode[2] = 'w';
465 if (ismode (mode_bits, S_IRUSR))
466 mode[1] = 'r';
467 #ifdef S_ISUID
468 if (ismode (mode_bits, S_ISUID))
469 mode[3] = (mode[3] == 'x') ? 's' : 'S';
470 #endif /* S_ISUID */
471 #ifdef S_ISGID
472 if (ismode (mode_bits, S_ISGID))
473 mode[6] = (mode[6] == 'x') ? 's' : 'S';
474 #endif /* S_ISGID */
475 #ifdef S_ISVTX
476 if (ismode (mode_bits, S_ISVTX))
477 mode[9] = (mode[9] == 'x') ? 't' : 'T';
478 #endif /* S_ISVTX */
479 return mode;
482 /* p: string which might contain an url with a password (this parameter is
483 modified in place).
484 has_prefix = 0: The first parameter is an url without a prefix
485 (user[:pass]@]machine[:port][remote-dir). Delete
486 the password.
487 has_prefix = 1: Search p for known url prefixes. If found delete
488 the password from the url.
489 Caveat: only the first url is found
491 char *
492 strip_password (char *p, int has_prefix)
494 static const struct
496 const char *name;
497 size_t len;
498 } prefixes[] =
501 "/#ftp:", 6},
503 "ftp://", 6},
505 "/#mc:", 5},
507 "mc://", 5},
509 "/#smb:", 6},
511 "smb://", 6},
513 "/#sh:", 5},
515 "sh://", 5},
517 "ssh://", 6}
519 char *at, *inner_colon, *dir;
520 size_t i;
521 char *result = p;
523 for (i = 0; i < sizeof (prefixes) / sizeof (prefixes[0]); i++)
525 char *q;
527 if (has_prefix)
529 q = strstr (p, prefixes[i].name);
530 if (q == NULL)
531 continue;
532 else
533 p = q + prefixes[i].len;
536 dir = strchr (p, PATH_SEP);
537 if (dir != NULL)
538 *dir = '\0';
540 /* search for any possible user */
541 at = strrchr (p, '@');
543 if (dir)
544 *dir = PATH_SEP;
546 /* We have a username */
547 if (at)
549 inner_colon = memchr (p, ':', at - p);
550 if (inner_colon)
551 memmove (inner_colon, at, strlen (at) + 1);
553 break;
555 return (result);
558 const char *
559 strip_home_and_password (const char *dir)
561 size_t len;
562 static char newdir[MC_MAXPATHLEN];
564 len = strlen (home_dir);
565 if (home_dir != NULL && strncmp (dir, home_dir, len) == 0 &&
566 (dir[len] == PATH_SEP || dir[len] == '\0'))
568 newdir[0] = '~';
569 g_strlcpy (&newdir[1], &dir[len], sizeof (newdir) - 1);
570 return newdir;
573 /* We do not strip homes in /#ftp tree, I do not like ~'s there
574 (see ftpfs.c why) */
575 g_strlcpy (newdir, dir, sizeof (newdir));
576 strip_password (newdir, 1);
577 return newdir;
580 const char *
581 extension (const char *filename)
583 const char *d = strrchr (filename, '.');
584 return (d != NULL) ? d + 1 : "";
588 exist_file (const char *name)
590 return access (name, R_OK) == 0;
594 check_for_default (const char *default_file, const char *file)
596 if (!exist_file (file))
598 FileOpContext *ctx;
599 FileOpTotalContext *tctx;
601 if (!exist_file (default_file))
602 return -1;
604 ctx = file_op_context_new (OP_COPY);
605 tctx = file_op_total_context_new ();
606 file_op_context_create_ui (ctx, 0, FALSE);
607 copy_file_file (tctx, ctx, default_file, file);
608 file_op_total_context_destroy (tctx);
609 file_op_context_destroy (ctx);
612 return 0;
617 char *
618 load_file (const char *filename)
620 FILE *data_file;
621 struct stat s;
622 char *data;
623 long read_size;
625 data_file = fopen (filename, "r");
626 if (data_file == NULL)
628 return 0;
630 if (fstat (fileno (data_file), &s) != 0)
632 fclose (data_file);
633 return 0;
635 data = g_malloc (s.st_size + 1);
636 read_size = fread (data, 1, s.st_size, data_file);
637 data[read_size] = 0;
638 fclose (data_file);
640 if (read_size > 0)
641 return data;
642 else
644 g_free (data);
645 return 0;
649 char *
650 load_mc_home_file (const char *_mc_home, const char *_mc_home_alt, const char *filename,
651 char **allocated_filename)
653 char *hintfile_base, *hintfile;
654 char *lang;
655 char *data;
657 hintfile_base = concat_dir_and_file (_mc_home, filename);
658 lang = guess_message_value ();
660 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
661 data = load_file (hintfile);
663 if (!data)
665 g_free (hintfile);
666 g_free (hintfile_base);
667 hintfile_base = concat_dir_and_file (_mc_home_alt, filename);
669 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
670 data = load_file (hintfile);
672 if (!data)
674 /* Fall back to the two-letter language code */
675 if (lang[0] && lang[1])
676 lang[2] = 0;
677 g_free (hintfile);
678 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
679 data = load_file (hintfile);
681 if (!data)
683 g_free (hintfile);
684 hintfile = hintfile_base;
685 data = load_file (hintfile_base);
690 g_free (lang);
692 if (hintfile != hintfile_base)
693 g_free (hintfile_base);
695 if (allocated_filename)
696 *allocated_filename = hintfile;
697 else
698 g_free (hintfile);
700 return data;
703 /* Check strftime() results. Some systems (i.e. Solaris) have different
704 short-month and month name sizes for different locales */
705 size_t
706 i18n_checktimelength (void)
708 size_t length = 0;
709 const time_t testtime = time (NULL);
710 struct tm *lt = localtime (&testtime);
712 if (i18n_timelength_cache <= MAX_I18NTIMELENGTH)
713 return i18n_timelength_cache;
715 if (lt == NULL)
717 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
718 length = str_term_width1 (_(INVALID_TIME_TEXT));
720 else
722 char buf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
724 /* We are interested in the longest possible date */
725 lt->tm_sec = lt->tm_min = lt->tm_hour = lt->tm_mday = 10;
727 /* Loop through all months to find out the longest one */
728 for (lt->tm_mon = 0; lt->tm_mon < 12; lt->tm_mon++) {
729 strftime (buf, sizeof(buf) - 1, user_recent_timeformat, lt);
730 length = max ((size_t) str_term_width1 (buf), length);
731 strftime (buf, sizeof(buf) - 1, user_old_timeformat, lt);
732 length = max ((size_t) str_term_width1 (buf), length);
735 length = max ((size_t) str_term_width1 (_(INVALID_TIME_TEXT)), length);
738 /* Don't handle big differences. Use standard value (email bug, please) */
739 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
740 length = STD_I18NTIMELENGTH;
742 /* Save obtained value to the cache */
743 i18n_timelength_cache = length;
745 return i18n_timelength_cache;
748 const char *
749 file_date (time_t when)
751 static char timebuf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
752 time_t current_time = time ((time_t) 0);
753 const char *fmt;
755 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
756 || current_time < when - 60L * 60L) /* In the future. */
757 /* The file is fairly old or in the future.
758 POSIX says the cutoff is 6 months old;
759 approximate this by 6*30 days.
760 Allow a 1 hour slop factor for what is considered "the future",
761 to allow for NFS server/client clock disagreement.
762 Show the year instead of the time of day. */
764 fmt = user_old_timeformat;
765 else
766 fmt = user_recent_timeformat;
768 FMT_LOCALTIME (timebuf, sizeof (timebuf), fmt, when);
770 return timebuf;
773 const char *
774 extract_line (const char *s, const char *top)
776 static char tmp_line[BUF_MEDIUM];
777 char *t = tmp_line;
779 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line) - 1 && s < top)
780 *t++ = *s++;
781 *t = 0;
782 return tmp_line;
785 /* The basename routine */
786 const char *
787 x_basename (const char *s)
789 const char *where;
790 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
794 const char *
795 unix_error_string (int error_num)
797 static char buffer[BUF_LARGE];
798 gchar *strerror_currentlocale;
800 strerror_currentlocale = g_locale_from_utf8 (g_strerror (error_num), -1, NULL, NULL, NULL);
801 g_snprintf (buffer, sizeof (buffer), "%s (%d)", strerror_currentlocale, error_num);
802 g_free (strerror_currentlocale);
804 return buffer;
807 const char *
808 skip_separators (const char *s)
810 const char *su = s;
812 for (; *su; str_cnext_char (&su))
813 if (*su != ' ' && *su != '\t' && *su != ',')
814 break;
816 return su;
819 const char *
820 skip_numbers (const char *s)
822 const char *su = s;
824 for (; *su; str_cnext_char (&su))
825 if (!str_isdigit (su))
826 break;
828 return su;
831 /* Remove all control sequences from the argument string. We define
832 * "control sequence", in a sort of pidgin BNF, as follows:
834 * control-seq = Esc non-'['
835 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
837 * This scheme works for all the terminals described in my termcap /
838 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
839 * terminals. If I hear from a single person who uses such a terminal
840 * with MC, I'll be glad to add support for it. (Dugan)
841 * Non-printable characters are also removed.
844 char *
845 strip_ctrl_codes (char *s)
847 char *w; /* Current position where the stripped data is written */
848 char *r; /* Current position where the original data is read */
849 char *n;
851 if (!s)
852 return 0;
854 for (w = s, r = s; *r;)
856 if (*r == ESC_CHAR)
858 /* Skip the control sequence's arguments */ ;
859 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
860 if (*(++r) == '[' || *r == '(')
862 /* strchr() matches trailing binary 0 */
863 while (*(++r) && strchr ("0123456789;?", *r));
865 else if (*r == ']')
868 * Skip xterm's OSC (Operating System Command)
869 * http://www.xfree86.org/current/ctlseqs.html
870 * OSC P s ; P t ST
871 * OSC P s ; P t BEL
873 char *new_r = r;
875 for (; *new_r; ++new_r)
877 switch (*new_r)
879 /* BEL */
880 case '\a':
881 r = new_r;
882 goto osc_out;
883 case ESC_CHAR:
884 /* ST */
885 if (*(new_r + 1) == '\\')
887 r = new_r + 1;
888 goto osc_out;
892 osc_out:;
896 * Now we are at the last character of the sequence.
897 * Skip it unless it's binary 0.
899 if (*r)
900 r++;
901 continue;
904 n = str_get_next_char (r);
905 if (str_isprint (r))
907 memmove (w, r, n - r);
908 w += n - r;
910 r = n;
912 *w = 0;
913 return s;
917 #ifndef ENABLE_VFS
918 char *
919 get_current_wd (char *buffer, int size)
921 char *p;
922 int len;
924 p = g_get_current_dir ();
925 len = strlen (p) + 1;
927 if (len > size)
929 g_free (p);
930 return NULL;
933 memcpy (buffer, p, len);
934 g_free (p);
936 return buffer;
938 #endif /* !ENABLE_VFS */
940 enum compression_type
941 get_compression_type (int fd, const char *name)
943 unsigned char magic[16];
944 size_t str_len;
946 /* Read the magic signature */
947 if (mc_read (fd, (char *) magic, 4) != 4)
948 return COMPRESSION_NONE;
950 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
951 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236))
953 return COMPRESSION_GZIP;
956 /* PKZIP_MAGIC */
957 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003 && magic[3] == 004)
959 /* Read compression type */
960 mc_lseek (fd, 8, SEEK_SET);
961 if (mc_read (fd, (char *) magic, 2) != 2)
962 return COMPRESSION_NONE;
964 /* Gzip can handle only deflated (8) or stored (0) files */
965 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
966 return COMPRESSION_NONE;
968 /* Compatible with gzip */
969 return COMPRESSION_GZIP;
972 /* PACK_MAGIC and LZH_MAGIC and compress magic */
973 if (magic[0] == 037 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235))
975 /* Compatible with gzip */
976 return COMPRESSION_GZIP;
979 /* BZIP and BZIP2 files */
980 if ((magic[0] == 'B') && (magic[1] == 'Z') && (magic[3] >= '1') && (magic[3] <= '9'))
982 switch (magic[2])
984 case '0':
985 return COMPRESSION_BZIP;
986 case 'h':
987 return COMPRESSION_BZIP2;
991 /* Support for LZMA (only utils format with magic in header).
992 * This is the default format of LZMA utils 4.32.1 and later. */
994 if (mc_read (fd, (char *) magic + 4, 2) != 2)
995 return COMPRESSION_NONE;
997 /* LZMA utils format */
998 if (magic[0] == 0xFF
999 && magic[1] == 'L'
1000 && magic[2] == 'Z' && magic[3] == 'M' && magic[4] == 'A' && magic[5] == 0x00)
1001 return COMPRESSION_LZMA;
1003 /* XZ compression magic */
1004 if (magic[0] == 0xFD
1005 && magic[1] == 0x37
1006 && magic[2] == 0x7A && magic[3] == 0x58 && magic[4] == 0x5A && magic[5] == 0x00)
1007 return COMPRESSION_XZ;
1009 str_len = strlen (name);
1010 /* HACK: we must belive to extention of LZMA file :) ... */
1011 if ((str_len > 5 && strcmp (&name[str_len - 5], ".lzma") == 0) ||
1012 (str_len > 4 && strcmp (&name[str_len - 4], ".tlz") == 0))
1013 return COMPRESSION_LZMA;
1015 return COMPRESSION_NONE;
1018 const char *
1019 decompress_extension (int type)
1021 switch (type)
1023 case COMPRESSION_GZIP:
1024 return "#ugz";
1025 case COMPRESSION_BZIP:
1026 return "#ubz";
1027 case COMPRESSION_BZIP2:
1028 return "#ubz2";
1029 case COMPRESSION_LZMA:
1030 return "#ulzma";
1031 case COMPRESSION_XZ:
1032 return "#uxz";
1034 /* Should never reach this place */
1035 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
1036 return 0;
1039 /* Hooks */
1040 void
1041 add_hook (Hook ** hook_list, void (*hook_fn) (void *), void *data)
1043 Hook *new_hook = g_new (Hook, 1);
1045 new_hook->hook_fn = hook_fn;
1046 new_hook->next = *hook_list;
1047 new_hook->hook_data = data;
1049 *hook_list = new_hook;
1052 void
1053 execute_hooks (Hook * hook_list)
1055 Hook *new_hook = 0;
1056 Hook *p;
1058 /* We copy the hook list first so tahat we let the hook
1059 * function call delete_hook
1062 while (hook_list)
1064 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
1065 hook_list = hook_list->next;
1067 p = new_hook;
1069 while (new_hook)
1071 (*new_hook->hook_fn) (new_hook->hook_data);
1072 new_hook = new_hook->next;
1075 for (hook_list = p; hook_list;)
1077 p = hook_list;
1078 hook_list = hook_list->next;
1079 g_free (p);
1083 void
1084 delete_hook (Hook ** hook_list, void (*hook_fn) (void *))
1086 Hook *current, *new_list, *next;
1088 new_list = 0;
1090 for (current = *hook_list; current; current = next)
1092 next = current->next;
1093 if (current->hook_fn == hook_fn)
1094 g_free (current);
1095 else
1096 add_hook (&new_list, current->hook_fn, current->hook_data);
1098 *hook_list = new_list;
1102 hook_present (Hook * hook_list, void (*hook_fn) (void *))
1104 Hook *p;
1106 for (p = hook_list; p; p = p->next)
1107 if (p->hook_fn == hook_fn)
1108 return 1;
1109 return 0;
1112 void
1113 wipe_password (char *passwd)
1115 char *p = passwd;
1117 if (!p)
1118 return;
1119 for (; *p; p++)
1120 *p = 0;
1121 g_free (passwd);
1124 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1125 /* Returns a newly allocated string */
1126 char *
1127 convert_controls (const char *p)
1129 char *valcopy = g_strdup (p);
1130 char *q;
1132 /* Parse the escape special character */
1133 for (q = valcopy; *p;)
1135 if (*p == '\\')
1137 p++;
1138 if ((*p == 'e') || (*p == 'E'))
1140 p++;
1141 *q++ = ESC_CHAR;
1144 else
1146 if (*p == '^')
1148 p++;
1149 if (*p == '^')
1150 *q++ = *p++;
1151 else
1153 char c = (*p | 0x20);
1154 if (c >= 'a' && c <= 'z')
1156 *q++ = c - 'a' + 1;
1157 p++;
1159 else if (*p)
1160 p++;
1163 else
1164 *q++ = *p++;
1167 *q = 0;
1168 return valcopy;
1171 static char *
1172 resolve_symlinks (const char *path)
1174 char *buf, *buf2, *q, *r, c;
1175 int len;
1176 struct stat mybuf;
1177 const char *p;
1179 if (*path != PATH_SEP)
1180 return NULL;
1181 r = buf = g_malloc (MC_MAXPATHLEN);
1182 buf2 = g_malloc (MC_MAXPATHLEN);
1183 *r++ = PATH_SEP;
1184 *r = 0;
1185 p = path;
1186 for (;;)
1188 q = strchr (p + 1, PATH_SEP);
1189 if (!q)
1191 q = strchr (p + 1, 0);
1192 if (q == p + 1)
1193 break;
1195 c = *q;
1196 *q = 0;
1197 if (mc_lstat (path, &mybuf) < 0)
1199 g_free (buf);
1200 g_free (buf2);
1201 *q = c;
1202 return NULL;
1204 if (!S_ISLNK (mybuf.st_mode))
1205 strcpy (r, p + 1);
1206 else
1208 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1209 if (len < 0)
1211 g_free (buf);
1212 g_free (buf2);
1213 *q = c;
1214 return NULL;
1216 buf2[len] = 0;
1217 if (*buf2 == PATH_SEP)
1218 strcpy (buf, buf2);
1219 else
1220 strcpy (r, buf2);
1222 canonicalize_pathname (buf);
1223 r = strchr (buf, 0);
1224 if (!*r || *(r - 1) != PATH_SEP)
1226 *r++ = PATH_SEP;
1227 *r = 0;
1229 *q = c;
1230 p = q;
1231 if (!c)
1232 break;
1234 if (!*buf)
1235 strcpy (buf, PATH_SEP_STR);
1236 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1237 *(r - 1) = 0;
1238 g_free (buf2);
1239 return buf;
1242 static gboolean
1243 mc_util_write_backup_content (const char *from_file_name, const char *to_file_name)
1245 FILE *backup_fd;
1246 char *contents;
1247 gsize length;
1248 gboolean ret1 = TRUE;
1250 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1251 return FALSE;
1253 backup_fd = fopen (to_file_name, "w");
1254 if (backup_fd == NULL)
1256 g_free (contents);
1257 return FALSE;
1260 if (fwrite ((const void *) contents, length, 1, backup_fd) != length)
1261 ret1 = FALSE;
1263 int ret2;
1264 ret2 = fflush (backup_fd);
1265 ret2 = fclose (backup_fd);
1267 g_free (contents);
1268 return ret1;
1271 /* Finds out a relative path from first to second, i.e. goes as many ..
1272 * as needed up in first and then goes down using second */
1273 char *
1274 diff_two_paths (const char *first, const char *second)
1276 char *p, *q, *r, *s, *buf = NULL;
1277 int i, j, prevlen = -1, currlen;
1278 char *my_first = NULL, *my_second = NULL;
1280 my_first = resolve_symlinks (first);
1281 if (my_first == NULL)
1282 return NULL;
1283 my_second = resolve_symlinks (second);
1284 if (my_second == NULL)
1286 g_free (my_first);
1287 return NULL;
1289 for (j = 0; j < 2; j++)
1291 p = my_first;
1292 q = my_second;
1293 for (;;)
1295 r = strchr (p, PATH_SEP);
1296 s = strchr (q, PATH_SEP);
1297 if (!r || !s)
1298 break;
1299 *r = 0;
1300 *s = 0;
1301 if (strcmp (p, q))
1303 *r = PATH_SEP;
1304 *s = PATH_SEP;
1305 break;
1307 else
1309 *r = PATH_SEP;
1310 *s = PATH_SEP;
1312 p = r + 1;
1313 q = s + 1;
1315 p--;
1316 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1317 currlen = (i + 1) * 3 + strlen (q) + 1;
1318 if (j)
1320 if (currlen < prevlen)
1321 g_free (buf);
1322 else
1324 g_free (my_first);
1325 g_free (my_second);
1326 return buf;
1329 p = buf = g_malloc (currlen);
1330 prevlen = currlen;
1331 for (; i >= 0; i--, p += 3)
1332 strcpy (p, "../");
1333 strcpy (p, q);
1335 g_free (my_first);
1336 g_free (my_second);
1337 return buf;
1340 /* If filename is NULL, then we just append PATH_SEP to the dir */
1341 char *
1342 concat_dir_and_file (const char *dir, const char *file)
1344 int i = strlen (dir);
1346 if (dir[i - 1] == PATH_SEP)
1347 return g_strconcat (dir, file, (char *) NULL);
1348 else
1349 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1352 /* Append text to GList, remove all entries with the same text */
1353 GList *
1354 list_append_unique (GList * list, char *text)
1356 GList *lc_link;
1359 * Go to the last position and traverse the list backwards
1360 * starting from the second last entry to make sure that we
1361 * are not removing the current link.
1363 list = g_list_append (list, text);
1364 list = g_list_last (list);
1365 lc_link = g_list_previous (list);
1367 while (lc_link != NULL)
1369 GList *newlink;
1371 newlink = g_list_previous (lc_link);
1372 if (strcmp ((char *) lc_link->data, text) == 0)
1374 GList *tmp;
1376 g_free (lc_link->data);
1377 tmp = g_list_remove_link (list, lc_link);
1378 g_list_free_1 (lc_link);
1380 lc_link = newlink;
1383 return list;
1386 /* Following code heavily borrows from libiberty, mkstemps.c */
1388 /* Number of attempts to create a temporary file */
1389 #ifndef TMP_MAX
1390 #define TMP_MAX 16384
1391 #endif /* !TMP_MAX */
1394 * Arguments:
1395 * pname (output) - pointer to the name of the temp file (needs g_free).
1396 * NULL if the function fails.
1397 * prefix - part of the filename before the random part.
1398 * Prepend $TMPDIR or /tmp if there are no path separators.
1399 * suffix - if not NULL, part of the filename after the random part.
1401 * Result:
1402 * handle of the open file or -1 if couldn't open any.
1405 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1407 static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1408 static unsigned long value;
1409 struct timeval tv;
1410 char *tmpbase;
1411 char *tmpname;
1412 char *XXXXXX;
1413 int count;
1415 if (strchr (prefix, PATH_SEP) == NULL)
1417 /* Add prefix first to find the position of XXXXXX */
1418 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1420 else
1422 tmpbase = g_strdup (prefix);
1425 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1426 *pname = tmpname;
1427 XXXXXX = &tmpname[strlen (tmpbase)];
1428 g_free (tmpbase);
1430 /* Get some more or less random data. */
1431 gettimeofday (&tv, NULL);
1432 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1434 for (count = 0; count < TMP_MAX; ++count)
1436 unsigned long v = value;
1437 int fd;
1439 /* Fill in the random bits. */
1440 XXXXXX[0] = letters[v % 62];
1441 v /= 62;
1442 XXXXXX[1] = letters[v % 62];
1443 v /= 62;
1444 XXXXXX[2] = letters[v % 62];
1445 v /= 62;
1446 XXXXXX[3] = letters[v % 62];
1447 v /= 62;
1448 XXXXXX[4] = letters[v % 62];
1449 v /= 62;
1450 XXXXXX[5] = letters[v % 62];
1452 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, S_IRUSR | S_IWUSR);
1453 if (fd >= 0)
1455 /* Successfully created. */
1456 return fd;
1459 /* This is a random value. It is only necessary that the next
1460 TMP_MAX values generated by adding 7777 to VALUE are different
1461 with (module 2^32). */
1462 value += 7777;
1465 /* Unsuccessful. Free the filename. */
1466 g_free (tmpname);
1467 *pname = NULL;
1469 return -1;
1473 * Read and restore position for the given filename.
1474 * If there is no stored data, return line 1 and col 0.
1476 void
1477 load_file_position (const char *filename, long *line, long *column, off_t * offset)
1479 char *fn;
1480 FILE *f;
1481 char buf[MC_MAXPATHLEN + 20];
1482 int len;
1484 /* defaults */
1485 *line = 1;
1486 *column = 0;
1487 *offset = 0;
1489 /* open file with positions */
1490 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1491 f = fopen (fn, "r");
1492 g_free (fn);
1493 if (!f)
1494 return;
1496 len = strlen (filename);
1498 while (fgets (buf, sizeof (buf), f))
1500 const char *p;
1501 gchar **pos_tokens;
1503 /* check if the filename matches the beginning of string */
1504 if (strncmp (buf, filename, len) != 0)
1505 continue;
1507 /* followed by single space */
1508 if (buf[len] != ' ')
1509 continue;
1511 /* and string without spaces */
1512 p = &buf[len + 1];
1513 if (strchr (p, ' '))
1514 continue;
1516 pos_tokens = g_strsplit_set (p, ";", 3);
1517 if (pos_tokens[0] != NULL)
1519 *line = strtol (pos_tokens[0], NULL, 10);
1520 if (pos_tokens[1] != NULL)
1522 *column = strtol (pos_tokens[1], NULL, 10);
1523 if (pos_tokens[2] != NULL)
1524 *offset = strtoll (pos_tokens[2], NULL, 10);
1525 else
1526 *offset = 0;
1528 else
1530 *column = 0;
1531 *offset = 0;
1534 else
1536 *line = 1;
1537 *column = 0;
1538 *offset = 0;
1540 g_strfreev (pos_tokens);
1542 fclose (f);
1545 /* Save position for the given file */
1546 #define TMP_SUFFIX ".tmp"
1547 void
1548 save_file_position (const char *filename, long line, long column, off_t offset)
1550 static int filepos_max_saved_entries = 0;
1551 char *fn, *tmp_fn;
1552 FILE *f, *tmp_f;
1553 char buf[MC_MAXPATHLEN + 20];
1554 int i = 1;
1555 gsize len;
1557 if (filepos_max_saved_entries == 0)
1558 filepos_max_saved_entries =
1559 mc_config_get_int (mc_main_config, CONFIG_APP_SECTION, "filepos_max_saved_entries",
1560 1024);
1562 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1563 if (fn == NULL)
1564 goto early_error;
1566 len = strlen (filename);
1568 mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
1570 /* open file */
1571 f = fopen (fn, "w");
1572 if (f == NULL)
1573 goto open_target_error;
1575 tmp_fn = g_strdup_printf ("%s" TMP_SUFFIX, fn);
1576 tmp_f = fopen (tmp_fn, "r");
1577 if (tmp_f == NULL)
1578 goto open_source_error;
1580 /* put the new record */
1581 if (line != 1 || column != 0)
1583 if (fprintf (f, "%s %ld;%ld;%llu\n", filename, line, column, (unsigned long long) offset) <
1585 goto write_position_error;
1588 while (fgets (buf, sizeof (buf), tmp_f))
1590 if (buf[len] == ' ' && strncmp (buf, filename, len) == 0 && !strchr (&buf[len + 1], ' '))
1591 continue;
1593 fprintf (f, "%s", buf);
1594 if (++i > filepos_max_saved_entries)
1595 break;
1597 fclose (tmp_f);
1598 g_free (tmp_fn);
1599 fclose (f);
1600 mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
1601 g_free (fn);
1602 return;
1604 write_position_error:
1605 fclose (tmp_f);
1606 open_source_error:
1607 g_free (tmp_fn);
1608 fclose (f);
1609 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1610 open_target_error:
1611 g_free (fn);
1612 early_error:
1613 return;
1616 #undef TMP_SUFFIX
1617 extern const char *
1618 cstrcasestr (const char *haystack, const char *needle)
1620 char *nee = str_create_search_needle (needle, 0);
1621 const char *result = str_search_first (haystack, nee, 0);
1622 str_release_search_needle (nee, 0);
1623 return result;
1626 const char *
1627 cstrstr (const char *haystack, const char *needle)
1629 return strstr (haystack, needle);
1632 extern char *
1633 str_unconst (const char *s)
1635 return (char *) s;
1638 #define ASCII_A (0x40 + 1)
1639 #define ASCII_Z (0x40 + 26)
1640 #define ASCII_a (0x60 + 1)
1641 #define ASCII_z (0x60 + 26)
1643 extern int
1644 ascii_alpha_to_cntrl (int ch)
1646 if ((ch >= ASCII_A && ch <= ASCII_Z) || (ch >= ASCII_a && ch <= ASCII_z))
1648 ch &= 0x1f;
1650 return ch;
1653 const char *
1654 Q_ (const char *s)
1656 const char *result, *sep;
1658 result = _(s);
1659 sep = strchr (result, '|');
1660 return (sep != NULL) ? sep + 1 : result;
1664 gboolean
1665 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1667 struct stat stat_buf;
1668 char *backup_path;
1669 gboolean ret;
1670 if (!exist_file (file_name))
1671 return FALSE;
1673 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1675 if (backup_path == NULL)
1676 return FALSE;
1678 ret = mc_util_write_backup_content (file_name, backup_path);
1680 if (ret)
1682 /* Backup file will have same ownership with main file. */
1683 if (stat (file_name, &stat_buf) == 0)
1684 chmod (backup_path, stat_buf.st_mode);
1685 else
1686 chmod (backup_path, S_IRUSR | S_IWUSR);
1689 g_free (backup_path);
1691 return ret;
1694 gboolean
1695 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1697 gboolean ret;
1698 char *backup_path;
1700 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1701 if (backup_path == NULL)
1702 return FALSE;
1704 ret = mc_util_write_backup_content (backup_path, file_name);
1705 g_free (backup_path);
1707 return ret;
1710 gboolean
1711 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1713 char *backup_path;
1715 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1716 if (backup_path == NULL)
1717 return FALSE;
1719 if (exist_file (backup_path))
1720 mc_unlink (backup_path);
1722 g_free (backup_path);
1723 return TRUE;
1726 /* partly taken from dcigettext.c, returns "" for default locale */
1727 /* value should be freed by calling function g_free() */
1728 char *
1729 guess_message_value (void)
1731 static const char *const var[] = {
1732 /* Setting of LC_ALL overwrites all other. */
1733 /* Do not use LANGUAGE for check user locale and drowing hints */
1734 "LC_ALL",
1735 /* Next comes the name of the desired category. */
1736 "LC_MESSAGES",
1737 /* Last possibility is the LANG environment variable. */
1738 "LANG",
1739 /* NULL exit loops */
1740 NULL
1743 unsigned i = 0;
1744 const char *locale = NULL;
1746 while (var[i] != NULL)
1748 locale = getenv (var[i]);
1749 if (locale != NULL && locale[0] != '\0')
1750 break;
1751 i++;
1754 if (locale == NULL)
1755 locale = "";
1757 return g_strdup (locale);