Fix of directory ignorance in file find engine.
[pantumic.git] / lib / util.c
blobd9bc91355dc0561d0d9f8afb76c08233324861dd
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;
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;
70 extern void
71 str_replace (char *s, char from, char to)
73 for (; *s != '\0'; s++)
75 if (*s == from)
76 *s = to;
80 static inline int
81 is_7bit_printable (unsigned char c)
83 return (c > 31 && c < 127);
86 static inline int
87 is_iso_printable (unsigned char c)
89 return ((c > 31 && c < 127) || c >= 160);
92 static inline int
93 is_8bit_printable (unsigned char c)
95 /* "Full 8 bits output" doesn't work on xterm */
96 if (xterm_flag)
97 return is_iso_printable (c);
99 return (c > 31 && c != 127 && c != 155);
103 is_printable (int c)
105 c &= 0xff;
107 #ifdef HAVE_CHARSET
108 /* "Display bits" is ignored, since the user controls the output
109 by setting the output codepage */
110 return is_8bit_printable (c);
111 #else
112 if (!eight_bit_clean)
113 return is_7bit_printable (c);
115 if (full_eight_bits)
117 return is_8bit_printable (c);
119 else
120 return is_iso_printable (c);
121 #endif /* !HAVE_CHARSET */
124 /* Calculates the message dimensions (lines and columns) */
125 void
126 msglen (const char *text, int *lines, int *columns)
128 int nlines = 1; /* even the empty string takes one line */
129 int ncolumns = 0;
130 int colindex = 0;
132 for (; *text != '\0'; text++)
134 if (*text == '\n')
136 nlines++;
137 colindex = 0;
139 else
141 colindex++;
142 if (colindex > ncolumns)
143 ncolumns = colindex;
147 *lines = nlines;
148 *columns = 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.
156 char *
157 trim (const char *s, char *d, int len)
159 int source_len;
161 /* Sanity check */
162 len = max (len, 0);
164 source_len = strlen (s);
165 if (source_len > len)
167 /* Cannot fit the whole line */
168 if (len <= 3)
170 /* We only have room for the dots */
171 memset (d, '.', len);
172 d[len] = 0;
173 return d;
175 else
177 /* Begin with ... and add the rest of the source string */
178 memset (d, '.', 3);
179 strcpy (d + 3, s + 3 + source_len - len);
182 else
183 /* We can copy the whole line */
184 strcpy (d, s);
185 return d;
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.
193 char *
194 name_quote (const char *s, int quote_percent)
196 char *ret, *d;
198 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
199 if (*s == '-')
201 *d++ = '.';
202 *d++ = '/';
205 for (; *s; s++, d++)
207 switch (*s)
209 case '%':
210 if (quote_percent)
211 *d++ = '%';
212 break;
213 case '\'':
214 case '\\':
215 case '\r':
216 case '\n':
217 case '\t':
218 case '"':
219 case ';':
220 case ' ':
221 case '?':
222 case '|':
223 case '[':
224 case ']':
225 case '{':
226 case '}':
227 case '<':
228 case '>':
229 case '`':
230 case '!':
231 case '$':
232 case '&':
233 case '*':
234 case '(':
235 case ')':
236 *d++ = '\\';
237 break;
238 case '~':
239 case '#':
240 if (d == ret)
241 *d++ = '\\';
242 break;
244 *d = *s;
246 *d = '\0';
247 return ret;
250 char *
251 fake_name_quote (const char *s, int quote_percent)
253 (void) quote_percent;
254 return g_strdup (s);
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.
262 const char *
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
271 * reasons.
273 const char *
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);
281 return ret;
284 const char *
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);
302 return x;
305 const char *
306 size_trunc_sep (double size, gboolean use_si)
308 static char x[60];
309 int count;
310 const char *p, *y;
311 char *d;
313 p = y = size_trunc (size, use_si);
314 p += strlen (p) - 1;
315 d = x + sizeof (x) - 1;
316 *d-- = 0;
317 while (p >= y && isalpha ((unsigned char) *p))
318 *d-- = *p--;
319 for (count = 0; p >= y; count++)
321 if (count == 3)
323 *d-- = ',';
324 count = 0;
326 *d-- = *p--;
328 d++;
329 if (*d == ',')
330 d++;
331 return d;
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.
343 void
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,
348 1000000000
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 };
352 int j = 0;
353 int size_remain;
355 if (len == 0)
356 len = 9;
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
363 if (units && use_si)
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++)
376 if (size == 0)
378 if (j == units)
380 /* Empty files will print "0" even with minimal width. */
381 g_snprintf (buffer, len + 1, "0");
382 break;
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");
388 break;
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]);
395 break;
398 /* Powers of 1000 or 1024, with rounding. */
399 if (use_si)
400 size = (size + 500) / 1000;
401 else
402 size = (size + 512) >> 10;
407 is_exe (mode_t mode)
409 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
410 return 1;
411 return 0;
414 #define ismode(n,m) ((n & m) == m)
416 const char *
417 string_perm (mode_t mode_bits)
419 static char mode[11];
421 strcpy (mode, "----------");
422 if (S_ISDIR (mode_bits))
423 mode[0] = 'd';
424 if (S_ISCHR (mode_bits))
425 mode[0] = 'c';
426 if (S_ISBLK (mode_bits))
427 mode[0] = 'b';
428 if (S_ISLNK (mode_bits))
429 mode[0] = 'l';
430 if (S_ISFIFO (mode_bits))
431 mode[0] = 'p';
432 if (S_ISNAM (mode_bits))
433 mode[0] = 'n';
434 if (S_ISSOCK (mode_bits))
435 mode[0] = 's';
436 if (S_ISDOOR (mode_bits))
437 mode[0] = 'D';
438 if (ismode (mode_bits, S_IXOTH))
439 mode[9] = 'x';
440 if (ismode (mode_bits, S_IWOTH))
441 mode[8] = 'w';
442 if (ismode (mode_bits, S_IROTH))
443 mode[7] = 'r';
444 if (ismode (mode_bits, S_IXGRP))
445 mode[6] = 'x';
446 if (ismode (mode_bits, S_IWGRP))
447 mode[5] = 'w';
448 if (ismode (mode_bits, S_IRGRP))
449 mode[4] = 'r';
450 if (ismode (mode_bits, S_IXUSR))
451 mode[3] = 'x';
452 if (ismode (mode_bits, S_IWUSR))
453 mode[2] = 'w';
454 if (ismode (mode_bits, S_IRUSR))
455 mode[1] = 'r';
456 #ifdef S_ISUID
457 if (ismode (mode_bits, S_ISUID))
458 mode[3] = (mode[3] == 'x') ? 's' : 'S';
459 #endif /* S_ISUID */
460 #ifdef S_ISGID
461 if (ismode (mode_bits, S_ISGID))
462 mode[6] = (mode[6] == 'x') ? 's' : 'S';
463 #endif /* S_ISGID */
464 #ifdef S_ISVTX
465 if (ismode (mode_bits, S_ISVTX))
466 mode[9] = (mode[9] == 'x') ? 't' : 'T';
467 #endif /* S_ISVTX */
468 return mode;
471 /* p: string which might contain an url with a password (this parameter is
472 modified in place).
473 has_prefix = 0: The first parameter is an url without a prefix
474 (user[:pass]@]machine[:port][remote-dir). Delete
475 the password.
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
480 char *
481 strip_password (char *p, int has_prefix)
483 static const struct
485 const char *name;
486 size_t len;
487 } prefixes[] =
489 /* *INDENT-OFF* */
490 { "/#ftp:", 6 },
491 { "ftp://", 6 },
492 { "/#smb:", 6 },
493 { "smb://", 6 },
494 { "/#sh:", 5 },
495 { "sh://", 5 },
496 { "ssh://", 6 }
497 /* *INDENT-ON* */
500 char *at, *inner_colon, *dir;
501 size_t i;
502 char *result = p;
504 for (i = 0; i < sizeof (prefixes) / sizeof (prefixes[0]); i++)
506 char *q;
508 if (has_prefix)
510 q = strstr (p, prefixes[i].name);
511 if (q == NULL)
512 continue;
513 else
514 p = q + prefixes[i].len;
517 dir = strchr (p, PATH_SEP);
518 if (dir != NULL)
519 *dir = '\0';
521 /* search for any possible user */
522 at = strrchr (p, '@');
524 if (dir)
525 *dir = PATH_SEP;
527 /* We have a username */
528 if (at)
530 inner_colon = memchr (p, ':', at - p);
531 if (inner_colon)
532 memmove (inner_colon, at, strlen (at) + 1);
534 break;
536 return (result);
539 const char *
540 strip_home_and_password (const char *dir)
542 size_t len;
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'))
549 newdir[0] = '~';
550 g_strlcpy (&newdir[1], &dir[len], sizeof (newdir) - 1);
551 return newdir;
554 /* We do not strip homes in /#ftp tree, I do not like ~'s there
555 (see ftpfs.c why) */
556 g_strlcpy (newdir, dir, sizeof (newdir));
557 strip_password (newdir, 1);
558 return newdir;
561 const char *
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))
579 FileOpContext *ctx;
580 FileOpTotalContext *tctx;
582 if (!exist_file (default_file))
583 return -1;
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);
593 return 0;
598 char *
599 load_file (const char *filename)
601 FILE *data_file;
602 struct stat s;
603 char *data;
604 long read_size;
606 data_file = fopen (filename, "r");
607 if (data_file == NULL)
609 return 0;
611 if (fstat (fileno (data_file), &s) != 0)
613 fclose (data_file);
614 return 0;
616 data = g_malloc (s.st_size + 1);
617 read_size = fread (data, 1, s.st_size, data_file);
618 data[read_size] = 0;
619 fclose (data_file);
621 if (read_size > 0)
622 return data;
623 else
625 g_free (data);
626 return 0;
630 char *
631 load_mc_home_file (const char *from, const char *filename, char **allocated_filename)
633 char *hintfile_base, *hintfile;
634 char *lang;
635 char *data;
637 hintfile_base = g_build_filename (from, filename, (char *) NULL);
638 lang = guess_message_value ();
640 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
641 data = load_file (hintfile);
643 if (data == NULL)
645 /* Fall back to the two-letter language code */
646 if (lang[0] != '\0' && lang[1] != '\0')
647 lang[2] = '\0';
648 g_free (hintfile);
649 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
650 data = load_file (hintfile);
652 if (data == NULL)
654 g_free (hintfile);
655 hintfile = hintfile_base;
656 data = load_file (hintfile_base);
660 g_free (lang);
662 if (hintfile != hintfile_base)
663 g_free (hintfile_base);
665 if (allocated_filename != NULL)
666 *allocated_filename = hintfile;
667 else
668 g_free (hintfile);
670 return data;
673 /* Check strftime() results. Some systems (i.e. Solaris) have different
674 short-month and month name sizes for different locales */
675 size_t
676 i18n_checktimelength (void)
678 size_t length = 0;
679 const time_t testtime = time (NULL);
680 struct tm *lt = localtime (&testtime);
682 if (i18n_timelength_cache <= MAX_I18NTIMELENGTH)
683 return i18n_timelength_cache;
685 if (lt == NULL)
687 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
688 length = str_term_width1 (_(INVALID_TIME_TEXT));
690 else
692 char buf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
694 /* We are interested in the longest possible date */
695 lt->tm_sec = lt->tm_min = lt->tm_hour = lt->tm_mday = 10;
697 /* Loop through all months to find out the longest one */
698 for (lt->tm_mon = 0; lt->tm_mon < 12; lt->tm_mon++) {
699 strftime (buf, sizeof(buf) - 1, user_recent_timeformat, lt);
700 length = max ((size_t) str_term_width1 (buf), length);
701 strftime (buf, sizeof(buf) - 1, user_old_timeformat, lt);
702 length = max ((size_t) str_term_width1 (buf), length);
705 length = max ((size_t) str_term_width1 (_(INVALID_TIME_TEXT)), length);
708 /* Don't handle big differences. Use standard value (email bug, please) */
709 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
710 length = STD_I18NTIMELENGTH;
712 /* Save obtained value to the cache */
713 i18n_timelength_cache = length;
715 return i18n_timelength_cache;
718 const char *
719 file_date (time_t when)
721 static char timebuf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
722 time_t current_time = time ((time_t) 0);
723 const char *fmt;
725 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
726 || current_time < when - 60L * 60L) /* In the future. */
727 /* The file is fairly old or in the future.
728 POSIX says the cutoff is 6 months old;
729 approximate this by 6*30 days.
730 Allow a 1 hour slop factor for what is considered "the future",
731 to allow for NFS server/client clock disagreement.
732 Show the year instead of the time of day. */
734 fmt = user_old_timeformat;
735 else
736 fmt = user_recent_timeformat;
738 FMT_LOCALTIME (timebuf, sizeof (timebuf), fmt, when);
740 return timebuf;
743 const char *
744 extract_line (const char *s, const char *top)
746 static char tmp_line[BUF_MEDIUM];
747 char *t = tmp_line;
749 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line) - 1 && s < top)
750 *t++ = *s++;
751 *t = 0;
752 return tmp_line;
755 /* The basename routine */
756 const char *
757 x_basename (const char *s)
759 const char *where;
760 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
764 const char *
765 unix_error_string (int error_num)
767 static char buffer[BUF_LARGE];
768 gchar *strerror_currentlocale;
770 strerror_currentlocale = g_locale_from_utf8 (g_strerror (error_num), -1, NULL, NULL, NULL);
771 g_snprintf (buffer, sizeof (buffer), "%s (%d)", strerror_currentlocale, error_num);
772 g_free (strerror_currentlocale);
774 return buffer;
777 const char *
778 skip_separators (const char *s)
780 const char *su = s;
782 for (; *su; str_cnext_char (&su))
783 if (*su != ' ' && *su != '\t' && *su != ',')
784 break;
786 return su;
789 const char *
790 skip_numbers (const char *s)
792 const char *su = s;
794 for (; *su; str_cnext_char (&su))
795 if (!str_isdigit (su))
796 break;
798 return su;
801 /* Remove all control sequences from the argument string. We define
802 * "control sequence", in a sort of pidgin BNF, as follows:
804 * control-seq = Esc non-'['
805 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
807 * This scheme works for all the terminals described in my termcap /
808 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
809 * terminals. If I hear from a single person who uses such a terminal
810 * with MC, I'll be glad to add support for it. (Dugan)
811 * Non-printable characters are also removed.
814 char *
815 strip_ctrl_codes (char *s)
817 char *w; /* Current position where the stripped data is written */
818 char *r; /* Current position where the original data is read */
819 char *n;
821 if (!s)
822 return 0;
824 for (w = s, r = s; *r;)
826 if (*r == ESC_CHAR)
828 /* Skip the control sequence's arguments */ ;
829 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
830 if (*(++r) == '[' || *r == '(')
832 /* strchr() matches trailing binary 0 */
833 while (*(++r) && strchr ("0123456789;?", *r));
835 else if (*r == ']')
838 * Skip xterm's OSC (Operating System Command)
839 * http://www.xfree86.org/current/ctlseqs.html
840 * OSC P s ; P t ST
841 * OSC P s ; P t BEL
843 char *new_r = r;
845 for (; *new_r; ++new_r)
847 switch (*new_r)
849 /* BEL */
850 case '\a':
851 r = new_r;
852 goto osc_out;
853 case ESC_CHAR:
854 /* ST */
855 if (*(new_r + 1) == '\\')
857 r = new_r + 1;
858 goto osc_out;
862 osc_out:;
866 * Now we are at the last character of the sequence.
867 * Skip it unless it's binary 0.
869 if (*r)
870 r++;
871 continue;
874 n = str_get_next_char (r);
875 if (str_isprint (r))
877 memmove (w, r, n - r);
878 w += n - r;
880 r = n;
882 *w = 0;
883 return s;
886 enum compression_type
887 get_compression_type (int fd, const char *name)
889 unsigned char magic[16];
890 size_t str_len;
892 /* Read the magic signature */
893 if (mc_read (fd, (char *) magic, 4) != 4)
894 return COMPRESSION_NONE;
896 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
897 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236))
899 return COMPRESSION_GZIP;
902 /* PKZIP_MAGIC */
903 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003 && magic[3] == 004)
905 /* Read compression type */
906 mc_lseek (fd, 8, SEEK_SET);
907 if (mc_read (fd, (char *) magic, 2) != 2)
908 return COMPRESSION_NONE;
910 /* Gzip can handle only deflated (8) or stored (0) files */
911 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
912 return COMPRESSION_NONE;
914 /* Compatible with gzip */
915 return COMPRESSION_GZIP;
918 /* PACK_MAGIC and LZH_MAGIC and compress magic */
919 if (magic[0] == 037 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235))
921 /* Compatible with gzip */
922 return COMPRESSION_GZIP;
925 /* BZIP and BZIP2 files */
926 if ((magic[0] == 'B') && (magic[1] == 'Z') && (magic[3] >= '1') && (magic[3] <= '9'))
928 switch (magic[2])
930 case '0':
931 return COMPRESSION_BZIP;
932 case 'h':
933 return COMPRESSION_BZIP2;
937 /* Support for LZMA (only utils format with magic in header).
938 * This is the default format of LZMA utils 4.32.1 and later. */
940 if (mc_read (fd, (char *) magic + 4, 2) != 2)
941 return COMPRESSION_NONE;
943 /* LZMA utils format */
944 if (magic[0] == 0xFF
945 && magic[1] == 'L'
946 && magic[2] == 'Z' && magic[3] == 'M' && magic[4] == 'A' && magic[5] == 0x00)
947 return COMPRESSION_LZMA;
949 /* XZ compression magic */
950 if (magic[0] == 0xFD
951 && magic[1] == 0x37
952 && magic[2] == 0x7A && magic[3] == 0x58 && magic[4] == 0x5A && magic[5] == 0x00)
953 return COMPRESSION_XZ;
955 str_len = strlen (name);
956 /* HACK: we must belive to extention of LZMA file :) ... */
957 if ((str_len > 5 && strcmp (&name[str_len - 5], ".lzma") == 0) ||
958 (str_len > 4 && strcmp (&name[str_len - 4], ".tlz") == 0))
959 return COMPRESSION_LZMA;
961 return COMPRESSION_NONE;
964 const char *
965 decompress_extension (int type)
967 switch (type)
969 case COMPRESSION_GZIP:
970 return "#ugz";
971 case COMPRESSION_BZIP:
972 return "#ubz";
973 case COMPRESSION_BZIP2:
974 return "#ubz2";
975 case COMPRESSION_LZMA:
976 return "#ulzma";
977 case COMPRESSION_XZ:
978 return "#uxz";
980 /* Should never reach this place */
981 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
982 return 0;
985 /* Hooks */
986 void
987 add_hook (Hook ** hook_list, void (*hook_fn) (void *), void *data)
989 Hook *new_hook = g_new (Hook, 1);
991 new_hook->hook_fn = hook_fn;
992 new_hook->next = *hook_list;
993 new_hook->hook_data = data;
995 *hook_list = new_hook;
998 void
999 execute_hooks (Hook * hook_list)
1001 Hook *new_hook = 0;
1002 Hook *p;
1004 /* We copy the hook list first so tahat we let the hook
1005 * function call delete_hook
1008 while (hook_list)
1010 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
1011 hook_list = hook_list->next;
1013 p = new_hook;
1015 while (new_hook)
1017 (*new_hook->hook_fn) (new_hook->hook_data);
1018 new_hook = new_hook->next;
1021 for (hook_list = p; hook_list;)
1023 p = hook_list;
1024 hook_list = hook_list->next;
1025 g_free (p);
1029 void
1030 delete_hook (Hook ** hook_list, void (*hook_fn) (void *))
1032 Hook *current, *new_list, *next;
1034 new_list = 0;
1036 for (current = *hook_list; current; current = next)
1038 next = current->next;
1039 if (current->hook_fn == hook_fn)
1040 g_free (current);
1041 else
1042 add_hook (&new_list, current->hook_fn, current->hook_data);
1044 *hook_list = new_list;
1048 hook_present (Hook * hook_list, void (*hook_fn) (void *))
1050 Hook *p;
1052 for (p = hook_list; p; p = p->next)
1053 if (p->hook_fn == hook_fn)
1054 return 1;
1055 return 0;
1058 void
1059 wipe_password (char *passwd)
1061 char *p = passwd;
1063 if (!p)
1064 return;
1065 for (; *p; p++)
1066 *p = 0;
1067 g_free (passwd);
1070 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1071 /* Returns a newly allocated string */
1072 char *
1073 convert_controls (const char *p)
1075 char *valcopy = g_strdup (p);
1076 char *q;
1078 /* Parse the escape special character */
1079 for (q = valcopy; *p;)
1081 if (*p == '\\')
1083 p++;
1084 if ((*p == 'e') || (*p == 'E'))
1086 p++;
1087 *q++ = ESC_CHAR;
1090 else
1092 if (*p == '^')
1094 p++;
1095 if (*p == '^')
1096 *q++ = *p++;
1097 else
1099 char c = (*p | 0x20);
1100 if (c >= 'a' && c <= 'z')
1102 *q++ = c - 'a' + 1;
1103 p++;
1105 else if (*p)
1106 p++;
1109 else
1110 *q++ = *p++;
1113 *q = 0;
1114 return valcopy;
1117 static char *
1118 resolve_symlinks (const char *path)
1120 char *buf, *buf2, *q, *r, c;
1121 int len;
1122 struct stat mybuf;
1123 const char *p;
1125 if (*path != PATH_SEP)
1126 return NULL;
1127 r = buf = g_malloc (MC_MAXPATHLEN);
1128 buf2 = g_malloc (MC_MAXPATHLEN);
1129 *r++ = PATH_SEP;
1130 *r = 0;
1131 p = path;
1132 for (;;)
1134 q = strchr (p + 1, PATH_SEP);
1135 if (!q)
1137 q = strchr (p + 1, 0);
1138 if (q == p + 1)
1139 break;
1141 c = *q;
1142 *q = 0;
1143 if (mc_lstat (path, &mybuf) < 0)
1145 g_free (buf);
1146 g_free (buf2);
1147 *q = c;
1148 return NULL;
1150 if (!S_ISLNK (mybuf.st_mode))
1151 strcpy (r, p + 1);
1152 else
1154 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1155 if (len < 0)
1157 g_free (buf);
1158 g_free (buf2);
1159 *q = c;
1160 return NULL;
1162 buf2[len] = 0;
1163 if (*buf2 == PATH_SEP)
1164 strcpy (buf, buf2);
1165 else
1166 strcpy (r, buf2);
1168 canonicalize_pathname (buf);
1169 r = strchr (buf, 0);
1170 if (!*r || *(r - 1) != PATH_SEP)
1172 *r++ = PATH_SEP;
1173 *r = 0;
1175 *q = c;
1176 p = q;
1177 if (!c)
1178 break;
1180 if (!*buf)
1181 strcpy (buf, PATH_SEP_STR);
1182 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1183 *(r - 1) = 0;
1184 g_free (buf2);
1185 return buf;
1188 static gboolean
1189 mc_util_write_backup_content (const char *from_file_name, const char *to_file_name)
1191 FILE *backup_fd;
1192 char *contents;
1193 gsize length;
1194 gboolean ret1 = TRUE;
1196 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1197 return FALSE;
1199 backup_fd = fopen (to_file_name, "w");
1200 if (backup_fd == NULL)
1202 g_free (contents);
1203 return FALSE;
1206 if (fwrite ((const void *) contents, 1, length, backup_fd) != length)
1207 ret1 = FALSE;
1209 int ret2;
1210 ret2 = fflush (backup_fd);
1211 ret2 = fclose (backup_fd);
1213 g_free (contents);
1214 return ret1;
1217 /* Finds out a relative path from first to second, i.e. goes as many ..
1218 * as needed up in first and then goes down using second */
1219 char *
1220 diff_two_paths (const char *first, const char *second)
1222 char *p, *q, *r, *s, *buf = NULL;
1223 int i, j, prevlen = -1, currlen;
1224 char *my_first = NULL, *my_second = NULL;
1226 my_first = resolve_symlinks (first);
1227 if (my_first == NULL)
1228 return NULL;
1229 my_second = resolve_symlinks (second);
1230 if (my_second == NULL)
1232 g_free (my_first);
1233 return NULL;
1235 for (j = 0; j < 2; j++)
1237 p = my_first;
1238 q = my_second;
1239 for (;;)
1241 r = strchr (p, PATH_SEP);
1242 s = strchr (q, PATH_SEP);
1243 if (!r || !s)
1244 break;
1245 *r = 0;
1246 *s = 0;
1247 if (strcmp (p, q))
1249 *r = PATH_SEP;
1250 *s = PATH_SEP;
1251 break;
1253 else
1255 *r = PATH_SEP;
1256 *s = PATH_SEP;
1258 p = r + 1;
1259 q = s + 1;
1261 p--;
1262 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1263 currlen = (i + 1) * 3 + strlen (q) + 1;
1264 if (j)
1266 if (currlen < prevlen)
1267 g_free (buf);
1268 else
1270 g_free (my_first);
1271 g_free (my_second);
1272 return buf;
1275 p = buf = g_malloc (currlen);
1276 prevlen = currlen;
1277 for (; i >= 0; i--, p += 3)
1278 strcpy (p, "../");
1279 strcpy (p, q);
1281 g_free (my_first);
1282 g_free (my_second);
1283 return buf;
1286 /* If filename is NULL, then we just append PATH_SEP to the dir */
1287 char *
1288 concat_dir_and_file (const char *dir, const char *file)
1290 int i = strlen (dir);
1292 if (dir[i - 1] == PATH_SEP)
1293 return g_strconcat (dir, file, (char *) NULL);
1294 else
1295 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1298 /* Append text to GList, remove all entries with the same text */
1299 GList *
1300 list_append_unique (GList * list, char *text)
1302 GList *lc_link;
1305 * Go to the last position and traverse the list backwards
1306 * starting from the second last entry to make sure that we
1307 * are not removing the current link.
1309 list = g_list_append (list, text);
1310 list = g_list_last (list);
1311 lc_link = g_list_previous (list);
1313 while (lc_link != NULL)
1315 GList *newlink;
1317 newlink = g_list_previous (lc_link);
1318 if (strcmp ((char *) lc_link->data, text) == 0)
1320 GList *tmp;
1322 g_free (lc_link->data);
1323 tmp = g_list_remove_link (list, lc_link);
1324 g_list_free_1 (lc_link);
1326 lc_link = newlink;
1329 return list;
1332 /* Following code heavily borrows from libiberty, mkstemps.c */
1334 /* Number of attempts to create a temporary file */
1335 #ifndef TMP_MAX
1336 #define TMP_MAX 16384
1337 #endif /* !TMP_MAX */
1340 * Arguments:
1341 * pname (output) - pointer to the name of the temp file (needs g_free).
1342 * NULL if the function fails.
1343 * prefix - part of the filename before the random part.
1344 * Prepend $TMPDIR or /tmp if there are no path separators.
1345 * suffix - if not NULL, part of the filename after the random part.
1347 * Result:
1348 * handle of the open file or -1 if couldn't open any.
1351 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1353 static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1354 static unsigned long value;
1355 struct timeval tv;
1356 char *tmpbase;
1357 char *tmpname;
1358 char *XXXXXX;
1359 int count;
1361 if (strchr (prefix, PATH_SEP) == NULL)
1363 /* Add prefix first to find the position of XXXXXX */
1364 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1366 else
1368 tmpbase = g_strdup (prefix);
1371 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1372 *pname = tmpname;
1373 XXXXXX = &tmpname[strlen (tmpbase)];
1374 g_free (tmpbase);
1376 /* Get some more or less random data. */
1377 gettimeofday (&tv, NULL);
1378 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1380 for (count = 0; count < TMP_MAX; ++count)
1382 unsigned long v = value;
1383 int fd;
1385 /* Fill in the random bits. */
1386 XXXXXX[0] = letters[v % 62];
1387 v /= 62;
1388 XXXXXX[1] = letters[v % 62];
1389 v /= 62;
1390 XXXXXX[2] = letters[v % 62];
1391 v /= 62;
1392 XXXXXX[3] = letters[v % 62];
1393 v /= 62;
1394 XXXXXX[4] = letters[v % 62];
1395 v /= 62;
1396 XXXXXX[5] = letters[v % 62];
1398 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, S_IRUSR | S_IWUSR);
1399 if (fd >= 0)
1401 /* Successfully created. */
1402 return fd;
1405 /* This is a random value. It is only necessary that the next
1406 TMP_MAX values generated by adding 7777 to VALUE are different
1407 with (module 2^32). */
1408 value += 7777;
1411 /* Unsuccessful. Free the filename. */
1412 g_free (tmpname);
1413 *pname = NULL;
1415 return -1;
1419 * Read and restore position for the given filename.
1420 * If there is no stored data, return line 1 and col 0.
1422 void
1423 load_file_position (const char *filename, long *line, long *column, off_t * offset, GArray **bookmarks)
1425 char *fn;
1426 FILE *f;
1427 char buf[MC_MAXPATHLEN + 100];
1428 const size_t len = strlen (filename);
1430 /* defaults */
1431 *line = 1;
1432 *column = 0;
1433 *offset = 0;
1435 /* open file with positions */
1436 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1437 f = fopen (fn, "r");
1438 g_free (fn);
1439 if (f == NULL)
1440 return;
1442 /* prepare array for serialized bookmarks */
1443 *bookmarks = g_array_sized_new (FALSE, FALSE, sizeof (size_t), MAX_SAVED_BOOKMARKS);
1445 while (fgets (buf, sizeof (buf), f) != NULL)
1447 const char *p;
1448 gchar **pos_tokens;
1450 /* check if the filename matches the beginning of string */
1451 if (strncmp (buf, filename, len) != 0)
1452 continue;
1454 /* followed by single space */
1455 if (buf[len] != ' ')
1456 continue;
1458 /* and string without spaces */
1459 p = &buf[len + 1];
1460 if (strchr (p, ' ') != NULL)
1461 continue;
1463 pos_tokens = g_strsplit (p, ";", 3 + MAX_SAVED_BOOKMARKS);
1464 if (pos_tokens[0] == NULL)
1466 *line = 1;
1467 *column = 0;
1468 *offset = 0;
1470 else
1472 *line = strtol (pos_tokens[0], NULL, 10);
1473 if (pos_tokens[1] == NULL)
1475 *column = 0;
1476 *offset = 0;
1478 else
1480 *column = strtol (pos_tokens[1], NULL, 10);
1481 if (pos_tokens[2] == NULL)
1482 *offset = 0;
1483 else
1485 size_t i;
1487 *offset = strtoll (pos_tokens[2], NULL, 10);
1489 for (i = 0; i < MAX_SAVED_BOOKMARKS && pos_tokens[3 + i] != NULL; i++)
1491 size_t val;
1493 val = strtoul (pos_tokens[3 + i], NULL, 10);
1494 g_array_append_val (*bookmarks, val);
1500 g_strfreev (pos_tokens);
1503 fclose (f);
1506 /* Save position for the given file */
1507 #define TMP_SUFFIX ".tmp"
1508 void
1509 save_file_position (const char *filename, long line, long column, off_t offset, GArray *bookmarks)
1511 static size_t filepos_max_saved_entries = 0;
1512 char *fn, *tmp_fn;
1513 FILE *f, *tmp_f;
1514 char buf[MC_MAXPATHLEN + 100];
1515 size_t i;
1516 const size_t len = strlen (filename);
1517 gboolean src_error = FALSE;
1519 if (filepos_max_saved_entries == 0)
1520 filepos_max_saved_entries = mc_config_get_int (mc_main_config, CONFIG_APP_SECTION,
1521 "filepos_max_saved_entries", 1024);
1523 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1524 if (fn == NULL)
1525 goto early_error;
1527 mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
1529 /* open file */
1530 f = fopen (fn, "w");
1531 if (f == NULL)
1532 goto open_target_error;
1534 tmp_fn = g_strdup_printf ("%s" TMP_SUFFIX, fn);
1535 tmp_f = fopen (tmp_fn, "r");
1536 if (tmp_f == NULL)
1538 src_error = TRUE;
1539 goto open_source_error;
1542 /* put the new record */
1543 if (line != 1 || column != 0 || bookmarks != NULL)
1545 if (fprintf (f, "%s %ld;%ld;%ju", filename, line, column, offset) < 0)
1546 goto write_position_error;
1547 if (bookmarks != NULL)
1548 for (i = 0; i < bookmarks->len && i < MAX_SAVED_BOOKMARKS; i++)
1549 if (fprintf (f, ";%zu", g_array_index (bookmarks, size_t, i)) < 0)
1550 goto write_position_error;
1552 if (fprintf (f, "\n") < 0)
1553 goto write_position_error;
1556 i = 1;
1557 while (fgets (buf, sizeof (buf), tmp_f) != NULL)
1559 if (buf[len] == ' ' && strncmp (buf, filename, len) == 0 && strchr (&buf[len + 1], ' ') == NULL)
1560 continue;
1562 fprintf (f, "%s", buf);
1563 if (++i > filepos_max_saved_entries)
1564 break;
1567 write_position_error:
1568 fclose (tmp_f);
1569 open_source_error:
1570 g_free (tmp_fn);
1571 fclose (f);
1572 if (src_error)
1573 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1574 else
1575 mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
1576 open_target_error:
1577 g_free (fn);
1578 early_error:
1579 g_array_free (bookmarks, TRUE);
1582 #undef TMP_SUFFIX
1583 extern const char *
1584 cstrcasestr (const char *haystack, const char *needle)
1586 char *nee = str_create_search_needle (needle, 0);
1587 const char *result = str_search_first (haystack, nee, 0);
1588 str_release_search_needle (nee, 0);
1589 return result;
1592 const char *
1593 cstrstr (const char *haystack, const char *needle)
1595 return strstr (haystack, needle);
1598 extern char *
1599 str_unconst (const char *s)
1601 return (char *) s;
1604 #define ASCII_A (0x40 + 1)
1605 #define ASCII_Z (0x40 + 26)
1606 #define ASCII_a (0x60 + 1)
1607 #define ASCII_z (0x60 + 26)
1609 extern int
1610 ascii_alpha_to_cntrl (int ch)
1612 if ((ch >= ASCII_A && ch <= ASCII_Z) || (ch >= ASCII_a && ch <= ASCII_z))
1614 ch &= 0x1f;
1616 return ch;
1619 const char *
1620 Q_ (const char *s)
1622 const char *result, *sep;
1624 result = _(s);
1625 sep = strchr (result, '|');
1626 return (sep != NULL) ? sep + 1 : result;
1630 gboolean
1631 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1633 struct stat stat_buf;
1634 char *backup_path;
1635 gboolean ret;
1636 if (!exist_file (file_name))
1637 return FALSE;
1639 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1641 if (backup_path == NULL)
1642 return FALSE;
1644 ret = mc_util_write_backup_content (file_name, backup_path);
1646 if (ret)
1648 /* Backup file will have same ownership with main file. */
1649 if (stat (file_name, &stat_buf) == 0)
1650 chmod (backup_path, stat_buf.st_mode);
1651 else
1652 chmod (backup_path, S_IRUSR | S_IWUSR);
1655 g_free (backup_path);
1657 return ret;
1660 gboolean
1661 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1663 gboolean ret;
1664 char *backup_path;
1666 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1667 if (backup_path == NULL)
1668 return FALSE;
1670 ret = mc_util_write_backup_content (backup_path, file_name);
1671 g_free (backup_path);
1673 return ret;
1676 gboolean
1677 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1679 char *backup_path;
1681 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1682 if (backup_path == NULL)
1683 return FALSE;
1685 if (exist_file (backup_path))
1686 mc_unlink (backup_path);
1688 g_free (backup_path);
1689 return TRUE;
1692 /* partly taken from dcigettext.c, returns "" for default locale */
1693 /* value should be freed by calling function g_free() */
1694 char *
1695 guess_message_value (void)
1697 static const char *const var[] = {
1698 /* Setting of LC_ALL overwrites all other. */
1699 /* Do not use LANGUAGE for check user locale and drowing hints */
1700 "LC_ALL",
1701 /* Next comes the name of the desired category. */
1702 "LC_MESSAGES",
1703 /* Last possibility is the LANG environment variable. */
1704 "LANG",
1705 /* NULL exit loops */
1706 NULL
1709 unsigned i = 0;
1710 const char *locale = NULL;
1712 while (var[i] != NULL)
1714 locale = getenv (var[i]);
1715 if (locale != NULL && locale[0] != '\0')
1716 break;
1717 i++;
1720 if (locale == NULL)
1721 locale = "";
1723 return g_strdup (locale);