Ticket #1790: mc crashes on start
[midnight-commander.git] / src / util.c
blob44e21d9ea751beef99e29b6692340a9599818337
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 "global.h"
45 #include "../src/tty/win.h" /* xterm_flag */
47 #include "../src/search/search.h"
49 #include "main.h" /* mc_home */
50 #include "cmd.h" /* guess_message_value */
51 #include "mountlist.h"
52 #include "timefmt.h"
53 #include "strutil.h"
54 #include "./src/mcconfig/mcconfig.h"
55 #include "fileopctx.h"
56 #include "file.h" /* copy_file_file() */
57 #include "dir.h"
58 #include "fileloc.h"
60 #ifdef HAVE_CHARSET
61 #include "charsets.h"
62 #endif
64 /*In order to use everywhere the same setup
65 for the locale we use defines */
66 #define FMTYEAR _("%b %e %Y")
67 #define FMTTIME _("%b %e %H:%M")
70 int easy_patterns = 1;
72 extern void str_replace(char *s, char from, char to)
74 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) {
116 return is_8bit_printable (c);
117 } else
118 return is_iso_printable (c);
119 #endif /* !HAVE_CHARSET */
122 /* Calculates the message dimensions (lines and columns) */
123 void
124 msglen (const char *text, int *lines, int *columns)
126 int nlines = 1; /* even the empty string takes one line */
127 int ncolumns = 0;
128 int colindex = 0;
130 for (; *text != '\0'; text++) {
131 if (*text == '\n') {
132 nlines++;
133 colindex = 0;
134 } else {
135 colindex++;
136 if (colindex > ncolumns)
137 ncolumns = colindex;
141 *lines = nlines;
142 *columns = ncolumns;
146 * Copy from s to d, and trim the beginning if necessary, and prepend
147 * "..." in this case. The destination string can have at most len
148 * bytes, not counting trailing 0.
150 char *
151 trim (const char *s, char *d, int len)
153 int source_len;
155 /* Sanity check */
156 len = max (len, 0);
158 source_len = strlen (s);
159 if (source_len > len) {
160 /* Cannot fit the whole line */
161 if (len <= 3) {
162 /* We only have room for the dots */
163 memset (d, '.', len);
164 d[len] = 0;
165 return d;
166 } else {
167 /* Begin with ... and add the rest of the source string */
168 memset (d, '.', 3);
169 strcpy (d + 3, s + 3 + source_len - len);
171 } else
172 /* We can copy the whole line */
173 strcpy (d, s);
174 return d;
178 * Quote the filename for the purpose of inserting it into the command
179 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
180 * processed by the mc command line.
182 char *
183 name_quote (const char *s, int quote_percent)
185 char *ret, *d;
187 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
188 if (*s == '-') {
189 *d++ = '.';
190 *d++ = '/';
193 for (; *s; s++, d++) {
194 switch (*s) {
195 case '%':
196 if (quote_percent)
197 *d++ = '%';
198 break;
199 case '\'':
200 case '\\':
201 case '\r':
202 case '\n':
203 case '\t':
204 case '"':
205 case ';':
206 case ' ':
207 case '?':
208 case '|':
209 case '[':
210 case ']':
211 case '{':
212 case '}':
213 case '<':
214 case '>':
215 case '`':
216 case '!':
217 case '$':
218 case '&':
219 case '*':
220 case '(':
221 case ')':
222 *d++ = '\\';
223 break;
224 case '~':
225 case '#':
226 if (d == ret)
227 *d++ = '\\';
228 break;
230 *d = *s;
232 *d = '\0';
233 return ret;
236 char *
237 fake_name_quote (const char *s, int quote_percent)
239 (void) quote_percent;
240 return g_strdup (s);
244 * Remove the middle part of the string to fit given length.
245 * Use "~" to show where the string was truncated.
246 * Return static buffer, no need to free() it.
248 const char *
249 name_trunc (const char *txt, size_t trunc_len)
251 return str_trunc (txt, trunc_len);
255 * path_trunc() is the same as name_trunc() above but
256 * it deletes possible password from path for security
257 * reasons.
259 const char *
260 path_trunc (const char *path, size_t trunc_len) {
261 char *secure_path = strip_password (g_strdup (path), 1);
263 const char *ret = str_trunc (secure_path, trunc_len);
264 g_free (secure_path);
266 return ret;
269 const char *
270 size_trunc (double size)
272 static char x [BUF_TINY];
273 long int divisor = 1;
274 const char *xtra = "";
276 if (size > 999999999L){
277 divisor = kilobyte_si?1000:1024;
278 xtra = kilobyte_si?"k":"K";
279 if (size/divisor > 999999999L){
280 divisor = kilobyte_si?(1000*1000):(1024*1024);
281 xtra = kilobyte_si?"m":"M";
284 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
285 return x;
288 const char *
289 size_trunc_sep (double size)
291 static char x [60];
292 int count;
293 const char *p, *y;
294 char *d;
296 p = y = size_trunc (size);
297 p += strlen (p) - 1;
298 d = x + sizeof (x) - 1;
299 *d-- = 0;
300 while (p >= y && isalpha ((unsigned char) *p))
301 *d-- = *p--;
302 for (count = 0; p >= y; count++){
303 if (count == 3){
304 *d-- = ',';
305 count = 0;
307 *d-- = *p--;
309 d++;
310 if (*d == ',')
311 d++;
312 return d;
316 * Print file SIZE to BUFFER, but don't exceed LEN characters,
317 * not including trailing 0. BUFFER should be at least LEN+1 long.
318 * This function is called for every file on panels, so avoid
319 * floating point by any means.
321 * Units: size units (filesystem sizes are 1K blocks)
322 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
324 void
325 size_trunc_len (char *buffer, unsigned int len, off_t size, int units)
327 /* Avoid taking power for every file. */
328 static const off_t power10 [] =
329 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
330 1000000000};
331 static const char * const suffix [] =
332 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
333 static const char * const suffix_lc [] =
334 {"", "k", "m", "g", "t", "p", "e", "z", "y", NULL};
335 int j = 0;
336 int size_remain;
338 if (len == 0)
339 len = 9;
342 * recalculate from 1024 base to 1000 base if units>0
343 * We can't just multiply by 1024 - that might cause overflow
344 * if off_t type is too small
346 if (units && kilobyte_si) {
347 for (j = 0; j < units; j++) {
348 size_remain=((size % 125)*1024)/1000; /* size mod 125, recalculated */
349 size = size / 125; /* 128/125 = 1024/1000 */
350 size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
351 size += size_remain; /* Re-add remainder lost by division/multiplication */
355 for (j = units; suffix [j] != NULL; j++) {
356 if (size == 0) {
357 if (j == units) {
358 /* Empty files will print "0" even with minimal width. */
359 g_snprintf (buffer, len + 1, "0");
360 break;
363 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
364 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
365 (j > 1) ? (kilobyte_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
366 break;
369 if (size < power10 [len - (j > 0)]) {
370 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, kilobyte_si ? suffix_lc[j] : suffix[j]);
371 break;
374 /* Powers of 1000 or 1024, with rounding. */
375 if (kilobyte_si) {
376 size = (size + 500) / 1000;
377 } else {
378 size = (size + 512) >> 10;
384 is_exe (mode_t mode)
386 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
387 return 1;
388 return 0;
391 #define ismode(n,m) ((n & m) == m)
393 const char *
394 string_perm (mode_t mode_bits)
396 static char mode[11];
398 strcpy (mode, "----------");
399 if (S_ISDIR (mode_bits))
400 mode[0] = 'd';
401 if (S_ISCHR (mode_bits))
402 mode[0] = 'c';
403 if (S_ISBLK (mode_bits))
404 mode[0] = 'b';
405 if (S_ISLNK (mode_bits))
406 mode[0] = 'l';
407 if (S_ISFIFO (mode_bits))
408 mode[0] = 'p';
409 if (S_ISNAM (mode_bits))
410 mode[0] = 'n';
411 if (S_ISSOCK (mode_bits))
412 mode[0] = 's';
413 if (S_ISDOOR (mode_bits))
414 mode[0] = 'D';
415 if (ismode (mode_bits, S_IXOTH))
416 mode[9] = 'x';
417 if (ismode (mode_bits, S_IWOTH))
418 mode[8] = 'w';
419 if (ismode (mode_bits, S_IROTH))
420 mode[7] = 'r';
421 if (ismode (mode_bits, S_IXGRP))
422 mode[6] = 'x';
423 if (ismode (mode_bits, S_IWGRP))
424 mode[5] = 'w';
425 if (ismode (mode_bits, S_IRGRP))
426 mode[4] = 'r';
427 if (ismode (mode_bits, S_IXUSR))
428 mode[3] = 'x';
429 if (ismode (mode_bits, S_IWUSR))
430 mode[2] = 'w';
431 if (ismode (mode_bits, S_IRUSR))
432 mode[1] = 'r';
433 #ifdef S_ISUID
434 if (ismode (mode_bits, S_ISUID))
435 mode[3] = (mode[3] == 'x') ? 's' : 'S';
436 #endif /* S_ISUID */
437 #ifdef S_ISGID
438 if (ismode (mode_bits, S_ISGID))
439 mode[6] = (mode[6] == 'x') ? 's' : 'S';
440 #endif /* S_ISGID */
441 #ifdef S_ISVTX
442 if (ismode (mode_bits, S_ISVTX))
443 mode[9] = (mode[9] == 'x') ? 't' : 'T';
444 #endif /* S_ISVTX */
445 return mode;
448 /* p: string which might contain an url with a password (this parameter is
449 modified in place).
450 has_prefix = 0: The first parameter is an url without a prefix
451 (user[:pass]@]machine[:port][remote-dir). Delete
452 the password.
453 has_prefix = 1: Search p for known url prefixes. If found delete
454 the password from the url.
455 Caveat: only the first url is found
457 char *
458 strip_password (char *p, int has_prefix)
460 static const struct {
461 const char *name;
462 size_t len;
463 } prefixes[] = { {"/#ftp:", 6},
464 {"ftp://", 6},
465 {"/#mc:", 5},
466 {"mc://", 5},
467 {"/#smb:", 6},
468 {"smb://", 6},
469 {"/#sh:", 5},
470 {"sh://", 5},
471 {"ssh://", 6}
473 char *at, *inner_colon, *dir;
474 size_t i;
475 char *result = p;
477 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
478 char *q;
480 if (has_prefix) {
481 if((q = strstr (p, prefixes[i].name)) == 0)
482 continue;
483 else
484 p = q + prefixes[i].len;
487 if ((dir = strchr (p, PATH_SEP)) != NULL)
488 *dir = '\0';
490 /* search for any possible user */
491 at = strrchr (p, '@');
493 if (dir)
494 *dir = PATH_SEP;
496 /* We have a username */
497 if (at) {
498 inner_colon = memchr (p, ':', at - p);
499 if (inner_colon)
500 memmove (inner_colon, at, strlen(at) + 1);
502 break;
504 return (result);
507 const char *
508 strip_home_and_password(const char *dir)
510 size_t len;
511 static char newdir [MC_MAXPATHLEN];
513 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
514 (dir[len] == PATH_SEP || dir[len] == '\0')){
515 newdir [0] = '~';
516 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
517 return newdir;
520 /* We do not strip homes in /#ftp tree, I do not like ~'s there
521 (see ftpfs.c why) */
522 g_strlcpy (newdir, dir, sizeof(newdir));
523 strip_password (newdir, 1);
524 return newdir;
527 const char *
528 extension (const char *filename)
530 const char *d = strrchr (filename, '.');
531 return (d != NULL) ? d + 1 : "";
535 exist_file (const char *name)
537 return access (name, R_OK) == 0;
541 check_for_default (const char *default_file, const char *file)
543 if (!exist_file (file)) {
544 FileOpContext *ctx;
545 off_t count = 0;
546 double bytes = 0.0;
548 if (!exist_file (default_file))
549 return -1;
551 ctx = file_op_context_new (OP_COPY);
552 file_op_context_create_ui (ctx, 0);
553 copy_file_file (ctx, default_file, file, 1, &count, &bytes, 1);
554 file_op_context_destroy (ctx);
557 return 0;
562 char *
563 load_file (const char *filename)
565 FILE *data_file;
566 struct stat s;
567 char *data;
568 long read_size;
570 if ((data_file = fopen (filename, "r")) == NULL){
571 return 0;
573 if (fstat (fileno (data_file), &s) != 0){
574 fclose (data_file);
575 return 0;
577 data = g_malloc (s.st_size+1);
578 read_size = fread (data, 1, s.st_size, data_file);
579 data [read_size] = 0;
580 fclose (data_file);
582 if (read_size > 0)
583 return data;
584 else {
585 g_free (data);
586 return 0;
590 char *
591 load_mc_home_file (const char *filename, char **allocated_filename)
593 char *hintfile_base, *hintfile;
594 char *lang;
595 char *data;
597 hintfile_base = concat_dir_and_file (mc_home, filename);
598 lang = guess_message_value ();
600 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
601 data = load_file (hintfile);
603 if (!data) {
604 g_free (hintfile);
605 g_free (hintfile_base);
606 hintfile_base = concat_dir_and_file (mc_home_alt, filename);
608 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
609 data = load_file (hintfile);
611 if (!data) {
612 /* Fall back to the two-letter language code */
613 if (lang[0] && lang[1])
614 lang[2] = 0;
615 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
616 data = load_file (hintfile);
618 if (!data) {
619 g_free (hintfile);
620 hintfile = hintfile_base;
621 data = load_file (hintfile_base);
626 g_free (lang);
628 if (hintfile != hintfile_base)
629 g_free (hintfile_base);
631 if (allocated_filename)
632 *allocated_filename = hintfile;
633 else
634 g_free (hintfile);
636 return data;
639 /* Check strftime() results. Some systems (i.e. Solaris) have different
640 short-month-name sizes for different locales */
641 size_t
642 i18n_checktimelength (void)
644 size_t length;
645 time_t testtime = time (NULL);
646 struct tm* lt = localtime(&testtime);
648 if (lt == NULL) {
649 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
650 length = str_term_width1 (_(INVALID_TIME_TEXT));
651 } else {
652 char buf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
653 size_t a, b;
655 strftime (buf, sizeof(buf) - 1, FMTTIME, lt);
656 a = str_term_width1 (buf);
657 strftime (buf, sizeof(buf) - 1, FMTYEAR, lt);
658 b = str_term_width1 (buf);
660 length = max (a, b);
661 length = max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT)), length);
664 /* Don't handle big differences. Use standard value (email bug, please) */
665 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
666 length = STD_I18NTIMELENGTH;
668 return length;
671 const char *
672 file_date (time_t when)
674 static char timebuf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
675 time_t current_time = time ((time_t) 0);
676 const char *fmt;
678 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
679 || current_time < when - 60L * 60L) /* In the future. */
680 /* The file is fairly old or in the future.
681 POSIX says the cutoff is 6 months old;
682 approximate this by 6*30 days.
683 Allow a 1 hour slop factor for what is considered "the future",
684 to allow for NFS server/client clock disagreement.
685 Show the year instead of the time of day. */
687 fmt = FMTYEAR;
688 else
689 fmt = FMTTIME;
691 FMT_LOCALTIME(timebuf, sizeof (timebuf), fmt, when);
693 return timebuf;
696 const char *
697 extract_line (const char *s, const char *top)
699 static char tmp_line [BUF_MEDIUM];
700 char *t = tmp_line;
702 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
703 *t++ = *s++;
704 *t = 0;
705 return tmp_line;
708 /* The basename routine */
709 const char *
710 x_basename (const char *s)
712 const char *where;
713 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
717 const char *
718 unix_error_string (int error_num)
720 static char buffer [BUF_LARGE];
721 #if GLIB_MAJOR_VERSION >= 2
722 gchar *strerror_currentlocale;
724 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
725 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
726 strerror_currentlocale, error_num);
727 g_free(strerror_currentlocale);
728 #else
729 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
730 g_strerror (error_num), error_num);
731 #endif
732 return buffer;
735 const char *
736 skip_separators (const char *s)
738 const char *su = s;
740 for (;*su; str_cnext_char (&su))
741 if (*su != ' ' && *su != '\t' && *su != ',') break;
743 return su;
746 const char *
747 skip_numbers (const char *s)
749 const char *su = s;
751 for (;*su; str_cnext_char (&su))
752 if (!str_isdigit (su)) break;
754 return su;
757 /* Remove all control sequences from the argument string. We define
758 * "control sequence", in a sort of pidgin BNF, as follows:
760 * control-seq = Esc non-'['
761 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
763 * This scheme works for all the terminals described in my termcap /
764 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
765 * terminals. If I hear from a single person who uses such a terminal
766 * with MC, I'll be glad to add support for it. (Dugan)
767 * Non-printable characters are also removed.
770 char *
771 strip_ctrl_codes (char *s)
773 char *w; /* Current position where the stripped data is written */
774 char *r; /* Current position where the original data is read */
775 char *n;
777 if (!s)
778 return 0;
780 for (w = s, r = s; *r; ) {
781 if (*r == ESC_CHAR) {
782 /* Skip the control sequence's arguments */ ;
783 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
784 if (*(++r) == '[' || *r == '(') {
785 /* strchr() matches trailing binary 0 */
786 while (*(++r) && strchr ("0123456789;?", *r));
787 } else
788 if (*r == ']') {
790 * Skip xterm's OSC (Operating System Command)
791 * http://www.xfree86.org/current/ctlseqs.html
792 * OSC P s ; P t ST
793 * OSC P s ; P t BEL
795 char * new_r = r;
797 for (; *new_r; ++new_r)
799 switch (*new_r)
801 /* BEL */
802 case '\a':
803 r = new_r;
804 goto osc_out;
805 case ESC_CHAR:
806 /* ST */
807 if (*(new_r + 1) == '\\')
809 r = new_r + 1;
810 goto osc_out;
814 osc_out:;
818 * Now we are at the last character of the sequence.
819 * Skip it unless it's binary 0.
821 if (*r)
822 r++;
823 continue;
826 n = str_get_next_char (r);
827 if (str_isprint (r)) {
828 memmove (w, r, n - r);
829 w+= n - r;
831 r = n;
833 *w = 0;
834 return s;
838 #ifndef USE_VFS
839 char *
840 get_current_wd (char *buffer, int size)
842 char *p;
843 int len;
845 p = g_get_current_dir ();
846 len = strlen(p) + 1;
848 if (len > size) {
849 g_free (p);
850 return NULL;
853 memcpy (buffer, p, len);
854 g_free (p);
856 return buffer;
858 #endif /* !USE_VFS */
860 enum compression_type
861 get_compression_type (int fd, const char * name)
863 unsigned char magic[16];
864 size_t str_len;
866 /* Read the magic signature */
867 if (mc_read (fd, (char *) magic, 4) != 4)
868 return COMPRESSION_NONE;
870 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
871 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
872 return COMPRESSION_GZIP;
875 /* PKZIP_MAGIC */
876 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
877 && magic[3] == 004) {
878 /* Read compression type */
879 mc_lseek (fd, 8, SEEK_SET);
880 if (mc_read (fd, (char *) magic, 2) != 2)
881 return COMPRESSION_NONE;
883 /* Gzip can handle only deflated (8) or stored (0) files */
884 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
885 return COMPRESSION_NONE;
887 /* Compatible with gzip */
888 return COMPRESSION_GZIP;
891 /* PACK_MAGIC and LZH_MAGIC and compress magic */
892 if (magic[0] == 037
893 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
894 /* Compatible with gzip */
895 return COMPRESSION_GZIP;
898 /* BZIP and BZIP2 files */
899 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
900 (magic[3] >= '1') && (magic[3] <= '9')) {
901 switch (magic[2]) {
902 case '0':
903 return COMPRESSION_BZIP;
904 case 'h':
905 return COMPRESSION_BZIP2;
909 /* Support for LZMA (only utils format with magic in header).
910 * This is the default format of LZMA utils 4.32.1 and later. */
912 if (mc_read(fd, (char *) magic+4, 1) == 1)
914 /* LZMA utils format */
916 ( magic[0] == 0xFF
917 && magic[1] == 'L'
918 && magic[2] == 'Z'
919 && magic[3] == 'M'
920 && magic[4] == 'A'
921 && magic[5] == 0x00
923 return COMPRESSION_LZMA;
926 /* XZ compression magic */
927 if (mc_read(fd, (char *) magic+5, 1) == 1)
929 if (
930 magic[0] == 0xFD
931 && magic[1] == 0x37
932 && magic[2] == 0x7A
933 && magic[3] == 0x58
934 && magic[4] == 0x5A
935 && magic[5] == 0x00
937 return COMPRESSION_XZ;
941 str_len = strlen(name);
942 /* HACK: we must belive to extention of LZMA file :) ...*/
943 if ( (str_len > 5 && strcmp(&name[str_len-5],".lzma") == 0) ||
944 (str_len > 4 && strcmp(&name[str_len-4],".tlz") == 0))
945 return COMPRESSION_LZMA;
947 return COMPRESSION_NONE;
950 const char *
951 decompress_extension (int type)
953 switch (type){
954 case COMPRESSION_GZIP: return "#ugz";
955 case COMPRESSION_BZIP: return "#ubz";
956 case COMPRESSION_BZIP2: return "#ubz2";
957 case COMPRESSION_LZMA: return "#ulzma";
958 case COMPRESSION_XZ: return "#uxz";
960 /* Should never reach this place */
961 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
962 return 0;
965 /* Hooks */
966 void
967 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
969 Hook *new_hook = g_new (Hook, 1);
971 new_hook->hook_fn = hook_fn;
972 new_hook->next = *hook_list;
973 new_hook->hook_data = data;
975 *hook_list = new_hook;
978 void
979 execute_hooks (Hook *hook_list)
981 Hook *new_hook = 0;
982 Hook *p;
984 /* We copy the hook list first so tahat we let the hook
985 * function call delete_hook
988 while (hook_list){
989 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
990 hook_list = hook_list->next;
992 p = new_hook;
994 while (new_hook){
995 (*new_hook->hook_fn)(new_hook->hook_data);
996 new_hook = new_hook->next;
999 for (hook_list = p; hook_list;){
1000 p = hook_list;
1001 hook_list = hook_list->next;
1002 g_free (p);
1006 void
1007 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1009 Hook *current, *new_list, *next;
1011 new_list = 0;
1013 for (current = *hook_list; current; current = next){
1014 next = current->next;
1015 if (current->hook_fn == hook_fn)
1016 g_free (current);
1017 else
1018 add_hook (&new_list, current->hook_fn, current->hook_data);
1020 *hook_list = new_list;
1024 hook_present (Hook *hook_list, void (*hook_fn)(void *))
1026 Hook *p;
1028 for (p = hook_list; p; p = p->next)
1029 if (p->hook_fn == hook_fn)
1030 return 1;
1031 return 0;
1034 void
1035 wipe_password (char *passwd)
1037 char *p = passwd;
1039 if (!p)
1040 return;
1041 for (;*p ; p++)
1042 *p = 0;
1043 g_free (passwd);
1046 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1047 /* Returns a newly allocated string */
1048 char *
1049 convert_controls (const char *p)
1051 char *valcopy = g_strdup (p);
1052 char *q;
1054 /* Parse the escape special character */
1055 for (q = valcopy; *p;){
1056 if (*p == '\\'){
1057 p++;
1058 if ((*p == 'e') || (*p == 'E')){
1059 p++;
1060 *q++ = ESC_CHAR;
1062 } else {
1063 if (*p == '^'){
1064 p++;
1065 if (*p == '^')
1066 *q++ = *p++;
1067 else {
1068 char c = (*p | 0x20);
1069 if (c >= 'a' && c <= 'z') {
1070 *q++ = c - 'a' + 1;
1071 p++;
1072 } else if (*p)
1073 p++;
1075 } else
1076 *q++ = *p++;
1079 *q = 0;
1080 return valcopy;
1083 static char *
1084 resolve_symlinks (const char *path)
1086 char *buf, *buf2, *q, *r, c;
1087 int len;
1088 struct stat mybuf;
1089 const char *p;
1091 if (*path != PATH_SEP)
1092 return NULL;
1093 r = buf = g_malloc (MC_MAXPATHLEN);
1094 buf2 = g_malloc (MC_MAXPATHLEN);
1095 *r++ = PATH_SEP;
1096 *r = 0;
1097 p = path;
1098 for (;;) {
1099 q = strchr (p + 1, PATH_SEP);
1100 if (!q) {
1101 q = strchr (p + 1, 0);
1102 if (q == p + 1)
1103 break;
1105 c = *q;
1106 *q = 0;
1107 if (mc_lstat (path, &mybuf) < 0) {
1108 g_free (buf);
1109 g_free (buf2);
1110 *q = c;
1111 return NULL;
1113 if (!S_ISLNK (mybuf.st_mode))
1114 strcpy (r, p + 1);
1115 else {
1116 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1117 if (len < 0) {
1118 g_free (buf);
1119 g_free (buf2);
1120 *q = c;
1121 return NULL;
1123 buf2 [len] = 0;
1124 if (*buf2 == PATH_SEP)
1125 strcpy (buf, buf2);
1126 else
1127 strcpy (r, buf2);
1129 canonicalize_pathname (buf);
1130 r = strchr (buf, 0);
1131 if (!*r || *(r - 1) != PATH_SEP) {
1132 *r++ = PATH_SEP;
1133 *r = 0;
1135 *q = c;
1136 p = q;
1137 if (!c)
1138 break;
1140 if (!*buf)
1141 strcpy (buf, PATH_SEP_STR);
1142 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1143 *(r - 1) = 0;
1144 g_free (buf2);
1145 return buf;
1148 static gboolean
1149 mc_util_write_backup_content(const char *from_file_name, const char *to_file_name)
1151 FILE *backup_fd;
1152 char *contents;
1153 gsize length;
1155 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1156 return FALSE;
1158 backup_fd = fopen (to_file_name, "w");
1159 if (backup_fd == NULL) {
1160 g_free(contents);
1161 return FALSE;
1164 fwrite ( (const void *) contents, length, 1, backup_fd);
1166 fflush(backup_fd);
1167 fclose(backup_fd);
1168 g_free(contents);
1169 return TRUE;
1172 /* Finds out a relative path from first to second, i.e. goes as many ..
1173 * as needed up in first and then goes down using second */
1174 char *
1175 diff_two_paths (const char *first, const char *second)
1177 char *p, *q, *r, *s, *buf = NULL;
1178 int i, j, prevlen = -1, currlen;
1179 char *my_first = NULL, *my_second = NULL;
1181 my_first = resolve_symlinks (first);
1182 if (my_first == NULL)
1183 return NULL;
1184 my_second = resolve_symlinks (second);
1185 if (my_second == NULL) {
1186 g_free (my_first);
1187 return NULL;
1189 for (j = 0; j < 2; j++) {
1190 p = my_first;
1191 q = my_second;
1192 for (;;) {
1193 r = strchr (p, PATH_SEP);
1194 s = strchr (q, PATH_SEP);
1195 if (!r || !s)
1196 break;
1197 *r = 0; *s = 0;
1198 if (strcmp (p, q)) {
1199 *r = PATH_SEP; *s = PATH_SEP;
1200 break;
1201 } else {
1202 *r = PATH_SEP; *s = PATH_SEP;
1204 p = r + 1;
1205 q = s + 1;
1207 p--;
1208 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1209 currlen = (i + 1) * 3 + strlen (q) + 1;
1210 if (j) {
1211 if (currlen < prevlen)
1212 g_free (buf);
1213 else {
1214 g_free (my_first);
1215 g_free (my_second);
1216 return buf;
1219 p = buf = g_malloc (currlen);
1220 prevlen = currlen;
1221 for (; i >= 0; i--, p += 3)
1222 strcpy (p, "../");
1223 strcpy (p, q);
1225 g_free (my_first);
1226 g_free (my_second);
1227 return buf;
1230 /* If filename is NULL, then we just append PATH_SEP to the dir */
1231 char *
1232 concat_dir_and_file (const char *dir, const char *file)
1234 int i = strlen (dir);
1236 if (dir [i-1] == PATH_SEP)
1237 return g_strconcat (dir, file, (char *) NULL);
1238 else
1239 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1242 /* Append text to GList, remove all entries with the same text */
1243 GList *
1244 list_append_unique (GList *list, char *text)
1246 GList *lc_link, *newlink, *tmp;
1249 * Go to the last position and traverse the list backwards
1250 * starting from the second last entry to make sure that we
1251 * are not removing the current link.
1253 list = g_list_append (list, text);
1254 list = g_list_last (list);
1255 lc_link = g_list_previous (list);
1257 while (lc_link) {
1258 newlink = g_list_previous (lc_link);
1259 if (!strcmp ((char *) lc_link->data, text)) {
1260 g_free (lc_link->data);
1261 tmp = g_list_remove_link (list, lc_link);
1262 g_list_free_1 (lc_link);
1264 lc_link = newlink;
1267 return list;
1270 /* Following code heavily borrows from libiberty, mkstemps.c */
1272 /* Number of attempts to create a temporary file */
1273 #ifndef TMP_MAX
1274 #define TMP_MAX 16384
1275 #endif /* !TMP_MAX */
1278 * Arguments:
1279 * pname (output) - pointer to the name of the temp file (needs g_free).
1280 * NULL if the function fails.
1281 * prefix - part of the filename before the random part.
1282 * Prepend $TMPDIR or /tmp if there are no path separators.
1283 * suffix - if not NULL, part of the filename after the random part.
1285 * Result:
1286 * handle of the open file or -1 if couldn't open any.
1289 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1291 static const char letters[]
1292 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1293 static unsigned long value;
1294 struct timeval tv;
1295 char *tmpbase;
1296 char *tmpname;
1297 char *XXXXXX;
1298 int count;
1300 if (strchr (prefix, PATH_SEP) == NULL) {
1301 /* Add prefix first to find the position of XXXXXX */
1302 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1303 } else {
1304 tmpbase = g_strdup (prefix);
1307 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1308 *pname = tmpname;
1309 XXXXXX = &tmpname[strlen (tmpbase)];
1310 g_free (tmpbase);
1312 /* Get some more or less random data. */
1313 gettimeofday (&tv, NULL);
1314 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1316 for (count = 0; count < TMP_MAX; ++count) {
1317 unsigned long v = value;
1318 int fd;
1320 /* Fill in the random bits. */
1321 XXXXXX[0] = letters[v % 62];
1322 v /= 62;
1323 XXXXXX[1] = letters[v % 62];
1324 v /= 62;
1325 XXXXXX[2] = letters[v % 62];
1326 v /= 62;
1327 XXXXXX[3] = letters[v % 62];
1328 v /= 62;
1329 XXXXXX[4] = letters[v % 62];
1330 v /= 62;
1331 XXXXXX[5] = letters[v % 62];
1333 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1334 S_IRUSR | S_IWUSR);
1335 if (fd >= 0) {
1336 /* Successfully created. */
1337 return fd;
1340 /* This is a random value. It is only necessary that the next
1341 TMP_MAX values generated by adding 7777 to VALUE are different
1342 with (module 2^32). */
1343 value += 7777;
1346 /* Unsuccessful. Free the filename. */
1347 g_free (tmpname);
1348 *pname = NULL;
1350 return -1;
1354 * Read and restore position for the given filename.
1355 * If there is no stored data, return line 1 and col 0.
1357 void
1358 load_file_position (const char *filename, long *line, long *column)
1360 char *fn;
1361 FILE *f;
1362 char buf[MC_MAXPATHLEN + 20];
1363 int len;
1365 /* defaults */
1366 *line = 1;
1367 *column = 0;
1369 /* open file with positions */
1370 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1371 f = fopen (fn, "r");
1372 g_free (fn);
1373 if (!f)
1374 return;
1376 len = strlen (filename);
1378 while (fgets (buf, sizeof (buf), f)) {
1379 const char *p;
1381 /* check if the filename matches the beginning of string */
1382 if (strncmp (buf, filename, len) != 0)
1383 continue;
1385 /* followed by single space */
1386 if (buf[len] != ' ')
1387 continue;
1389 /* and string without spaces */
1390 p = &buf[len + 1];
1391 if (strchr (p, ' '))
1392 continue;
1394 *line = strtol(p, const_cast(char **, &p), 10);
1395 if (*p == ';') {
1396 *column = strtol(p+1, const_cast(char **, &p), 10);
1397 if (*p != '\n')
1398 *column = 0;
1399 } else
1400 *line = 1;
1402 fclose (f);
1405 /* Save position for the given file */
1406 #define TMP_SUFFIX ".tmp"
1407 void
1408 save_file_position (const char *filename, long line, long column)
1410 static int filepos_max_saved_entries = 0;
1411 char *fn, *tmp_fn;
1412 FILE *f, *tmp_f;
1413 char buf[MC_MAXPATHLEN + 20];
1414 int i = 1;
1415 gsize len;
1417 if (filepos_max_saved_entries == 0)
1418 filepos_max_saved_entries = mc_config_get_int(mc_main_config, CONFIG_APP_SECTION, "filepos_max_saved_entries", 1024);
1420 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1421 if (fn == NULL)
1422 return;
1424 len = strlen (filename);
1426 mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
1428 /* open file */
1429 f = fopen (fn, "w");
1430 if (f == NULL) {
1431 g_free (fn);
1432 return;
1435 tmp_fn = g_strdup_printf("%s" TMP_SUFFIX ,fn);
1436 tmp_f = fopen (tmp_fn, "r");
1437 if (tmp_f == NULL) {
1438 g_free(tmp_fn);
1439 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1440 g_free (fn);
1441 return;
1444 /* put the new record */
1445 if (line != 1 || column != 0) {
1446 if (fprintf (f, "%s %ld;%ld\n", filename, line, column) < 0) {
1447 g_free(tmp_fn);
1448 fclose (tmp_f);
1449 fclose (f);
1450 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1451 g_free (fn);
1452 return;
1456 while (fgets (buf, sizeof (buf), tmp_f)) {
1457 if (
1458 buf[len] == ' ' &&
1459 strncmp (buf, filename, len) == 0 &&
1460 !strchr (&buf[len + 1], ' ')
1462 continue;
1464 fprintf (f, "%s", buf);
1465 if (++i > filepos_max_saved_entries)
1466 break;
1468 fclose (tmp_f);
1469 g_free(tmp_fn);
1470 fclose (f);
1471 mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
1472 g_free (fn);
1474 #undef TMP_SUFFIX
1475 extern const char *
1476 cstrcasestr (const char *haystack, const char *needle)
1478 char *nee = str_create_search_needle (needle, 0);
1479 const char *result = str_search_first (haystack, nee, 0);
1480 str_release_search_needle (nee, 0);
1481 return result;
1484 const char *
1485 cstrstr (const char *haystack, const char *needle)
1487 return strstr(haystack, needle);
1490 extern char *
1491 str_unconst (const char *s)
1493 return (char *) s;
1496 #define ASCII_A (0x40 + 1)
1497 #define ASCII_Z (0x40 + 26)
1498 #define ASCII_a (0x60 + 1)
1499 #define ASCII_z (0x60 + 26)
1501 extern int
1502 ascii_alpha_to_cntrl (int ch)
1504 if ((ch >= ASCII_A && ch <= ASCII_Z)
1505 || (ch >= ASCII_a && ch <= ASCII_z)) {
1506 ch &= 0x1f;
1508 return ch;
1511 const char *
1512 Q_ (const char *s)
1514 const char *result, *sep;
1516 result = _(s);
1517 sep = strchr(result, '|');
1518 return (sep != NULL) ? sep + 1 : result;
1522 gboolean
1523 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1525 struct stat stat_buf;
1526 char *backup_path;
1527 gboolean ret;
1528 if (!exist_file (file_name))
1529 return FALSE;
1531 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1533 if (backup_path == NULL)
1534 return FALSE;
1536 ret = mc_util_write_backup_content (file_name, backup_path);
1538 if (ret) {
1539 /* Backup file will have same ownership with main file. */
1540 if (stat (file_name, &stat_buf) == 0)
1541 chmod (backup_path, stat_buf.st_mode);
1542 else
1543 chmod (backup_path, S_IRUSR | S_IWUSR);
1546 g_free(backup_path);
1548 return ret;
1551 gboolean
1552 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1554 gboolean ret;
1555 char *backup_path;
1557 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1558 if (backup_path == NULL)
1559 return FALSE;
1561 ret = mc_util_write_backup_content (backup_path, file_name);
1562 g_free(backup_path);
1564 return ret;
1567 gboolean
1568 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1570 char *backup_path;
1572 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1573 if (backup_path == NULL)
1574 return FALSE;
1576 if (exist_file (backup_path))
1577 mc_unlink (backup_path);
1579 g_free(backup_path);
1580 return TRUE;