Change progressbar dialog.
[midnight-commander.git] / lib / util.c
blob42e8a0418e096f1a15e568268bff5562a70dd9f1
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 */
70 extern void str_replace(char *s, char from, char to)
72 for (; *s != '\0'; s++) {
73 if (*s == from)
74 *s = to;
78 static inline int
79 is_7bit_printable (unsigned char c)
81 return (c > 31 && c < 127);
84 static inline int
85 is_iso_printable (unsigned char c)
87 return ((c > 31 && c < 127) || c >= 160);
90 static inline int
91 is_8bit_printable (unsigned char c)
93 /* "Full 8 bits output" doesn't work on xterm */
94 if (xterm_flag)
95 return is_iso_printable (c);
97 return (c > 31 && c != 127 && c != 155);
101 is_printable (int c)
103 c &= 0xff;
105 #ifdef HAVE_CHARSET
106 /* "Display bits" is ignored, since the user controls the output
107 by setting the output codepage */
108 return is_8bit_printable (c);
109 #else
110 if (!eight_bit_clean)
111 return is_7bit_printable (c);
113 if (full_eight_bits) {
114 return is_8bit_printable (c);
115 } else
116 return is_iso_printable (c);
117 #endif /* !HAVE_CHARSET */
120 /* Calculates the message dimensions (lines and columns) */
121 void
122 msglen (const char *text, int *lines, int *columns)
124 int nlines = 1; /* even the empty string takes one line */
125 int ncolumns = 0;
126 int colindex = 0;
128 for (; *text != '\0'; text++) {
129 if (*text == '\n') {
130 nlines++;
131 colindex = 0;
132 } else {
133 colindex++;
134 if (colindex > ncolumns)
135 ncolumns = colindex;
139 *lines = nlines;
140 *columns = ncolumns;
144 * Copy from s to d, and trim the beginning if necessary, and prepend
145 * "..." in this case. The destination string can have at most len
146 * bytes, not counting trailing 0.
148 char *
149 trim (const char *s, char *d, int len)
151 int source_len;
153 /* Sanity check */
154 len = max (len, 0);
156 source_len = strlen (s);
157 if (source_len > len) {
158 /* Cannot fit the whole line */
159 if (len <= 3) {
160 /* We only have room for the dots */
161 memset (d, '.', len);
162 d[len] = 0;
163 return d;
164 } else {
165 /* Begin with ... and add the rest of the source string */
166 memset (d, '.', 3);
167 strcpy (d + 3, s + 3 + source_len - len);
169 } else
170 /* We can copy the whole line */
171 strcpy (d, s);
172 return d;
176 * Quote the filename for the purpose of inserting it into the command
177 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
178 * processed by the mc command line.
180 char *
181 name_quote (const char *s, int quote_percent)
183 char *ret, *d;
185 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
186 if (*s == '-') {
187 *d++ = '.';
188 *d++ = '/';
191 for (; *s; s++, d++) {
192 switch (*s) {
193 case '%':
194 if (quote_percent)
195 *d++ = '%';
196 break;
197 case '\'':
198 case '\\':
199 case '\r':
200 case '\n':
201 case '\t':
202 case '"':
203 case ';':
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 *d++ = '\\';
221 break;
222 case '~':
223 case '#':
224 if (d == ret)
225 *d++ = '\\';
226 break;
228 *d = *s;
230 *d = '\0';
231 return ret;
234 char *
235 fake_name_quote (const char *s, int quote_percent)
237 (void) quote_percent;
238 return g_strdup (s);
242 * Remove the middle part of the string to fit given length.
243 * Use "~" to show where the string was truncated.
244 * Return static buffer, no need to free() it.
246 const char *
247 name_trunc (const char *txt, size_t trunc_len)
249 return str_trunc (txt, trunc_len);
253 * path_trunc() is the same as name_trunc() above but
254 * it deletes possible password from path for security
255 * reasons.
257 const char *
258 path_trunc (const char *path, size_t trunc_len) {
259 char *secure_path = strip_password (g_strdup (path), 1);
261 const char *ret = str_trunc (secure_path, trunc_len);
262 g_free (secure_path);
264 return ret;
267 const char *
268 size_trunc (double size)
270 static char x [BUF_TINY];
271 long int divisor = 1;
272 const char *xtra = "";
274 if (size > 999999999L){
275 divisor = kilobyte_si?1000:1024;
276 xtra = kilobyte_si?"k":"K";
277 if (size/divisor > 999999999L){
278 divisor = kilobyte_si?(1000*1000):(1024*1024);
279 xtra = kilobyte_si?"m":"M";
282 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
283 return x;
286 const char *
287 size_trunc_sep (double size)
289 static char x [60];
290 int count;
291 const char *p, *y;
292 char *d;
294 p = y = size_trunc (size);
295 p += strlen (p) - 1;
296 d = x + sizeof (x) - 1;
297 *d-- = 0;
298 while (p >= y && isalpha ((unsigned char) *p))
299 *d-- = *p--;
300 for (count = 0; p >= y; count++){
301 if (count == 3){
302 *d-- = ',';
303 count = 0;
305 *d-- = *p--;
307 d++;
308 if (*d == ',')
309 d++;
310 return d;
314 * Print file SIZE to BUFFER, but don't exceed LEN characters,
315 * not including trailing 0. BUFFER should be at least LEN+1 long.
316 * This function is called for every file on panels, so avoid
317 * floating point by any means.
319 * Units: size units (filesystem sizes are 1K blocks)
320 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
322 void
323 size_trunc_len (char *buffer, unsigned int len, off_t size, int units)
325 /* Avoid taking power for every file. */
326 static const off_t power10 [] =
327 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
328 1000000000};
329 static const char * const suffix [] =
330 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
331 static const char * const suffix_lc [] =
332 {"", "k", "m", "g", "t", "p", "e", "z", "y", NULL};
333 int j = 0;
334 int size_remain;
336 if (len == 0)
337 len = 9;
340 * recalculate from 1024 base to 1000 base if units>0
341 * We can't just multiply by 1024 - that might cause overflow
342 * if off_t type is too small
344 if (units && kilobyte_si) {
345 for (j = 0; j < units; j++) {
346 size_remain=((size % 125)*1024)/1000; /* size mod 125, recalculated */
347 size = size / 125; /* 128/125 = 1024/1000 */
348 size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
349 size += size_remain; /* Re-add remainder lost by division/multiplication */
353 for (j = units; suffix [j] != NULL; j++) {
354 if (size == 0) {
355 if (j == units) {
356 /* Empty files will print "0" even with minimal width. */
357 g_snprintf (buffer, len + 1, "0");
358 break;
361 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
362 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
363 (j > 1) ? (kilobyte_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
364 break;
367 if (size < power10 [len - (j > 0)]) {
368 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, kilobyte_si ? suffix_lc[j] : suffix[j]);
369 break;
372 /* Powers of 1000 or 1024, with rounding. */
373 if (kilobyte_si) {
374 size = (size + 500) / 1000;
375 } else {
376 size = (size + 512) >> 10;
382 is_exe (mode_t mode)
384 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
385 return 1;
386 return 0;
389 #define ismode(n,m) ((n & m) == m)
391 const char *
392 string_perm (mode_t mode_bits)
394 static char mode[11];
396 strcpy (mode, "----------");
397 if (S_ISDIR (mode_bits))
398 mode[0] = 'd';
399 if (S_ISCHR (mode_bits))
400 mode[0] = 'c';
401 if (S_ISBLK (mode_bits))
402 mode[0] = 'b';
403 if (S_ISLNK (mode_bits))
404 mode[0] = 'l';
405 if (S_ISFIFO (mode_bits))
406 mode[0] = 'p';
407 if (S_ISNAM (mode_bits))
408 mode[0] = 'n';
409 if (S_ISSOCK (mode_bits))
410 mode[0] = 's';
411 if (S_ISDOOR (mode_bits))
412 mode[0] = 'D';
413 if (ismode (mode_bits, S_IXOTH))
414 mode[9] = 'x';
415 if (ismode (mode_bits, S_IWOTH))
416 mode[8] = 'w';
417 if (ismode (mode_bits, S_IROTH))
418 mode[7] = 'r';
419 if (ismode (mode_bits, S_IXGRP))
420 mode[6] = 'x';
421 if (ismode (mode_bits, S_IWGRP))
422 mode[5] = 'w';
423 if (ismode (mode_bits, S_IRGRP))
424 mode[4] = 'r';
425 if (ismode (mode_bits, S_IXUSR))
426 mode[3] = 'x';
427 if (ismode (mode_bits, S_IWUSR))
428 mode[2] = 'w';
429 if (ismode (mode_bits, S_IRUSR))
430 mode[1] = 'r';
431 #ifdef S_ISUID
432 if (ismode (mode_bits, S_ISUID))
433 mode[3] = (mode[3] == 'x') ? 's' : 'S';
434 #endif /* S_ISUID */
435 #ifdef S_ISGID
436 if (ismode (mode_bits, S_ISGID))
437 mode[6] = (mode[6] == 'x') ? 's' : 'S';
438 #endif /* S_ISGID */
439 #ifdef S_ISVTX
440 if (ismode (mode_bits, S_ISVTX))
441 mode[9] = (mode[9] == 'x') ? 't' : 'T';
442 #endif /* S_ISVTX */
443 return mode;
446 /* p: string which might contain an url with a password (this parameter is
447 modified in place).
448 has_prefix = 0: The first parameter is an url without a prefix
449 (user[:pass]@]machine[:port][remote-dir). Delete
450 the password.
451 has_prefix = 1: Search p for known url prefixes. If found delete
452 the password from the url.
453 Caveat: only the first url is found
455 char *
456 strip_password (char *p, int has_prefix)
458 static const struct {
459 const char *name;
460 size_t len;
461 } prefixes[] = { {"/#ftp:", 6},
462 {"ftp://", 6},
463 {"/#mc:", 5},
464 {"mc://", 5},
465 {"/#smb:", 6},
466 {"smb://", 6},
467 {"/#sh:", 5},
468 {"sh://", 5},
469 {"ssh://", 6}
471 char *at, *inner_colon, *dir;
472 size_t i;
473 char *result = p;
475 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
476 char *q;
478 if (has_prefix) {
479 if((q = strstr (p, prefixes[i].name)) == 0)
480 continue;
481 else
482 p = q + prefixes[i].len;
485 if ((dir = strchr (p, PATH_SEP)) != NULL)
486 *dir = '\0';
488 /* search for any possible user */
489 at = strrchr (p, '@');
491 if (dir)
492 *dir = PATH_SEP;
494 /* We have a username */
495 if (at) {
496 inner_colon = memchr (p, ':', at - p);
497 if (inner_colon)
498 memmove (inner_colon, at, strlen(at) + 1);
500 break;
502 return (result);
505 const char *
506 strip_home_and_password(const char *dir)
508 size_t len;
509 static char newdir [MC_MAXPATHLEN];
511 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
512 (dir[len] == PATH_SEP || dir[len] == '\0')){
513 newdir [0] = '~';
514 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
515 return newdir;
518 /* We do not strip homes in /#ftp tree, I do not like ~'s there
519 (see ftpfs.c why) */
520 g_strlcpy (newdir, dir, sizeof(newdir));
521 strip_password (newdir, 1);
522 return newdir;
525 const char *
526 extension (const char *filename)
528 const char *d = strrchr (filename, '.');
529 return (d != NULL) ? d + 1 : "";
533 exist_file (const char *name)
535 return access (name, R_OK) == 0;
539 check_for_default (const char *default_file, const char *file)
541 if (!exist_file (file)) {
542 FileOpContext *ctx;
543 FileOpTotalContext *tctx;
545 if (!exist_file (default_file))
546 return -1;
548 ctx = file_op_context_new (OP_COPY);
549 tctx = file_op_total_context_new ();
550 file_op_context_create_ui (ctx, 0, FALSE);
551 copy_file_file (tctx, ctx, default_file, file);
552 file_op_total_context_destroy (tctx);
553 file_op_context_destroy (ctx);
556 return 0;
561 char *
562 load_file (const char *filename)
564 FILE *data_file;
565 struct stat s;
566 char *data;
567 long read_size;
569 if ((data_file = fopen (filename, "r")) == NULL){
570 return 0;
572 if (fstat (fileno (data_file), &s) != 0){
573 fclose (data_file);
574 return 0;
576 data = g_malloc (s.st_size+1);
577 read_size = fread (data, 1, s.st_size, data_file);
578 data [read_size] = 0;
579 fclose (data_file);
581 if (read_size > 0)
582 return data;
583 else {
584 g_free (data);
585 return 0;
589 char *
590 load_mc_home_file (const char *_mc_home, const char *_mc_home_alt, const char *filename, char **allocated_filename)
592 char *hintfile_base, *hintfile;
593 char *lang;
594 char *data;
596 hintfile_base = concat_dir_and_file (_mc_home, filename);
597 lang = guess_message_value ();
599 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
600 data = load_file (hintfile);
602 if (!data) {
603 g_free (hintfile);
604 g_free (hintfile_base);
605 hintfile_base = concat_dir_and_file (_mc_home_alt, filename);
607 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
608 data = load_file (hintfile);
610 if (!data) {
611 /* Fall back to the two-letter language code */
612 if (lang[0] && lang[1])
613 lang[2] = 0;
614 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
615 data = load_file (hintfile);
617 if (!data) {
618 g_free (hintfile);
619 hintfile = hintfile_base;
620 data = load_file (hintfile_base);
625 g_free (lang);
627 if (hintfile != hintfile_base)
628 g_free (hintfile_base);
630 if (allocated_filename)
631 *allocated_filename = hintfile;
632 else
633 g_free (hintfile);
635 return data;
638 /* Check strftime() results. Some systems (i.e. Solaris) have different
639 short-month-name sizes for different locales */
640 size_t
641 i18n_checktimelength (void)
643 size_t length;
644 time_t testtime = time (NULL);
645 struct tm* lt = localtime(&testtime);
647 if (lt == NULL) {
648 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
649 length = str_term_width1 (_(INVALID_TIME_TEXT));
650 } else {
651 char buf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
652 size_t a, b;
654 strftime (buf, sizeof(buf) - 1, user_recent_timeformat, lt);
655 a = str_term_width1 (buf);
656 strftime (buf, sizeof(buf) - 1, user_old_timeformat, lt);
657 b = str_term_width1 (buf);
659 length = max (a, b);
660 length = max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT)), length);
663 /* Don't handle big differences. Use standard value (email bug, please) */
664 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
665 length = STD_I18NTIMELENGTH;
667 return length;
670 const char *
671 file_date (time_t when)
673 static char timebuf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
674 time_t current_time = time ((time_t) 0);
675 const char *fmt;
677 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
678 || current_time < when - 60L * 60L) /* In the future. */
679 /* The file is fairly old or in the future.
680 POSIX says the cutoff is 6 months old;
681 approximate this by 6*30 days.
682 Allow a 1 hour slop factor for what is considered "the future",
683 to allow for NFS server/client clock disagreement.
684 Show the year instead of the time of day. */
686 fmt = user_old_timeformat;
687 else
688 fmt = user_recent_timeformat;
690 FMT_LOCALTIME(timebuf, sizeof (timebuf), fmt, when);
692 return timebuf;
695 const char *
696 extract_line (const char *s, const char *top)
698 static char tmp_line [BUF_MEDIUM];
699 char *t = tmp_line;
701 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
702 *t++ = *s++;
703 *t = 0;
704 return tmp_line;
707 /* The basename routine */
708 const char *
709 x_basename (const char *s)
711 const char *where;
712 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
716 const char *
717 unix_error_string (int error_num)
719 static char buffer [BUF_LARGE];
720 gchar *strerror_currentlocale;
722 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
723 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
724 strerror_currentlocale, error_num);
725 g_free(strerror_currentlocale);
727 return buffer;
730 const char *
731 skip_separators (const char *s)
733 const char *su = s;
735 for (;*su; str_cnext_char (&su))
736 if (*su != ' ' && *su != '\t' && *su != ',') break;
738 return su;
741 const char *
742 skip_numbers (const char *s)
744 const char *su = s;
746 for (;*su; str_cnext_char (&su))
747 if (!str_isdigit (su)) break;
749 return su;
752 /* Remove all control sequences from the argument string. We define
753 * "control sequence", in a sort of pidgin BNF, as follows:
755 * control-seq = Esc non-'['
756 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
758 * This scheme works for all the terminals described in my termcap /
759 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
760 * terminals. If I hear from a single person who uses such a terminal
761 * with MC, I'll be glad to add support for it. (Dugan)
762 * Non-printable characters are also removed.
765 char *
766 strip_ctrl_codes (char *s)
768 char *w; /* Current position where the stripped data is written */
769 char *r; /* Current position where the original data is read */
770 char *n;
772 if (!s)
773 return 0;
775 for (w = s, r = s; *r; ) {
776 if (*r == ESC_CHAR) {
777 /* Skip the control sequence's arguments */ ;
778 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
779 if (*(++r) == '[' || *r == '(') {
780 /* strchr() matches trailing binary 0 */
781 while (*(++r) && strchr ("0123456789;?", *r));
782 } else
783 if (*r == ']') {
785 * Skip xterm's OSC (Operating System Command)
786 * http://www.xfree86.org/current/ctlseqs.html
787 * OSC P s ; P t ST
788 * OSC P s ; P t BEL
790 char * new_r = r;
792 for (; *new_r; ++new_r)
794 switch (*new_r)
796 /* BEL */
797 case '\a':
798 r = new_r;
799 goto osc_out;
800 case ESC_CHAR:
801 /* ST */
802 if (*(new_r + 1) == '\\')
804 r = new_r + 1;
805 goto osc_out;
809 osc_out:;
813 * Now we are at the last character of the sequence.
814 * Skip it unless it's binary 0.
816 if (*r)
817 r++;
818 continue;
821 n = str_get_next_char (r);
822 if (str_isprint (r)) {
823 memmove (w, r, n - r);
824 w+= n - r;
826 r = n;
828 *w = 0;
829 return s;
833 #ifndef ENABLE_VFS
834 char *
835 get_current_wd (char *buffer, int size)
837 char *p;
838 int len;
840 p = g_get_current_dir ();
841 len = strlen(p) + 1;
843 if (len > size) {
844 g_free (p);
845 return NULL;
848 memcpy (buffer, p, len);
849 g_free (p);
851 return buffer;
853 #endif /* !ENABLE_VFS */
855 enum compression_type
856 get_compression_type (int fd, const char * name)
858 unsigned char magic[16];
859 size_t str_len;
861 /* Read the magic signature */
862 if (mc_read (fd, (char *) magic, 4) != 4)
863 return COMPRESSION_NONE;
865 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
866 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
867 return COMPRESSION_GZIP;
870 /* PKZIP_MAGIC */
871 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
872 && magic[3] == 004) {
873 /* Read compression type */
874 mc_lseek (fd, 8, SEEK_SET);
875 if (mc_read (fd, (char *) magic, 2) != 2)
876 return COMPRESSION_NONE;
878 /* Gzip can handle only deflated (8) or stored (0) files */
879 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
880 return COMPRESSION_NONE;
882 /* Compatible with gzip */
883 return COMPRESSION_GZIP;
886 /* PACK_MAGIC and LZH_MAGIC and compress magic */
887 if (magic[0] == 037
888 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
889 /* Compatible with gzip */
890 return COMPRESSION_GZIP;
893 /* BZIP and BZIP2 files */
894 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
895 (magic[3] >= '1') && (magic[3] <= '9')) {
896 switch (magic[2]) {
897 case '0':
898 return COMPRESSION_BZIP;
899 case 'h':
900 return COMPRESSION_BZIP2;
904 /* Support for LZMA (only utils format with magic in header).
905 * This is the default format of LZMA utils 4.32.1 and later. */
907 if (mc_read(fd, (char *) magic+4, 2) != 2)
908 return COMPRESSION_NONE;
910 /* LZMA utils format */
911 if (
912 magic[0] == 0xFF
913 && magic[1] == 'L'
914 && magic[2] == 'Z'
915 && magic[3] == 'M'
916 && magic[4] == 'A'
917 && magic[5] == 0x00
919 return COMPRESSION_LZMA;
921 /* XZ compression magic */
922 if (
923 magic[0] == 0xFD
924 && magic[1] == 0x37
925 && magic[2] == 0x7A
926 && magic[3] == 0x58
927 && magic[4] == 0x5A
928 && magic[5] == 0x00
930 return COMPRESSION_XZ;
932 str_len = strlen(name);
933 /* HACK: we must belive to extention of LZMA file :) ...*/
934 if ( (str_len > 5 && strcmp(&name[str_len-5],".lzma") == 0) ||
935 (str_len > 4 && strcmp(&name[str_len-4],".tlz") == 0))
936 return COMPRESSION_LZMA;
938 return COMPRESSION_NONE;
941 const char *
942 decompress_extension (int type)
944 switch (type){
945 case COMPRESSION_GZIP: return "#ugz";
946 case COMPRESSION_BZIP: return "#ubz";
947 case COMPRESSION_BZIP2: return "#ubz2";
948 case COMPRESSION_LZMA: return "#ulzma";
949 case COMPRESSION_XZ: return "#uxz";
951 /* Should never reach this place */
952 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
953 return 0;
956 /* Hooks */
957 void
958 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
960 Hook *new_hook = g_new (Hook, 1);
962 new_hook->hook_fn = hook_fn;
963 new_hook->next = *hook_list;
964 new_hook->hook_data = data;
966 *hook_list = new_hook;
969 void
970 execute_hooks (Hook *hook_list)
972 Hook *new_hook = 0;
973 Hook *p;
975 /* We copy the hook list first so tahat we let the hook
976 * function call delete_hook
979 while (hook_list){
980 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
981 hook_list = hook_list->next;
983 p = new_hook;
985 while (new_hook){
986 (*new_hook->hook_fn)(new_hook->hook_data);
987 new_hook = new_hook->next;
990 for (hook_list = p; hook_list;){
991 p = hook_list;
992 hook_list = hook_list->next;
993 g_free (p);
997 void
998 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1000 Hook *current, *new_list, *next;
1002 new_list = 0;
1004 for (current = *hook_list; current; current = next){
1005 next = current->next;
1006 if (current->hook_fn == hook_fn)
1007 g_free (current);
1008 else
1009 add_hook (&new_list, current->hook_fn, current->hook_data);
1011 *hook_list = new_list;
1015 hook_present (Hook *hook_list, void (*hook_fn)(void *))
1017 Hook *p;
1019 for (p = hook_list; p; p = p->next)
1020 if (p->hook_fn == hook_fn)
1021 return 1;
1022 return 0;
1025 void
1026 wipe_password (char *passwd)
1028 char *p = passwd;
1030 if (!p)
1031 return;
1032 for (;*p ; p++)
1033 *p = 0;
1034 g_free (passwd);
1037 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1038 /* Returns a newly allocated string */
1039 char *
1040 convert_controls (const char *p)
1042 char *valcopy = g_strdup (p);
1043 char *q;
1045 /* Parse the escape special character */
1046 for (q = valcopy; *p;){
1047 if (*p == '\\'){
1048 p++;
1049 if ((*p == 'e') || (*p == 'E')){
1050 p++;
1051 *q++ = ESC_CHAR;
1053 } else {
1054 if (*p == '^'){
1055 p++;
1056 if (*p == '^')
1057 *q++ = *p++;
1058 else {
1059 char c = (*p | 0x20);
1060 if (c >= 'a' && c <= 'z') {
1061 *q++ = c - 'a' + 1;
1062 p++;
1063 } else if (*p)
1064 p++;
1066 } else
1067 *q++ = *p++;
1070 *q = 0;
1071 return valcopy;
1074 static char *
1075 resolve_symlinks (const char *path)
1077 char *buf, *buf2, *q, *r, c;
1078 int len;
1079 struct stat mybuf;
1080 const char *p;
1082 if (*path != PATH_SEP)
1083 return NULL;
1084 r = buf = g_malloc (MC_MAXPATHLEN);
1085 buf2 = g_malloc (MC_MAXPATHLEN);
1086 *r++ = PATH_SEP;
1087 *r = 0;
1088 p = path;
1089 for (;;) {
1090 q = strchr (p + 1, PATH_SEP);
1091 if (!q) {
1092 q = strchr (p + 1, 0);
1093 if (q == p + 1)
1094 break;
1096 c = *q;
1097 *q = 0;
1098 if (mc_lstat (path, &mybuf) < 0) {
1099 g_free (buf);
1100 g_free (buf2);
1101 *q = c;
1102 return NULL;
1104 if (!S_ISLNK (mybuf.st_mode))
1105 strcpy (r, p + 1);
1106 else {
1107 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1108 if (len < 0) {
1109 g_free (buf);
1110 g_free (buf2);
1111 *q = c;
1112 return NULL;
1114 buf2 [len] = 0;
1115 if (*buf2 == PATH_SEP)
1116 strcpy (buf, buf2);
1117 else
1118 strcpy (r, buf2);
1120 canonicalize_pathname (buf);
1121 r = strchr (buf, 0);
1122 if (!*r || *(r - 1) != PATH_SEP) {
1123 *r++ = PATH_SEP;
1124 *r = 0;
1126 *q = c;
1127 p = q;
1128 if (!c)
1129 break;
1131 if (!*buf)
1132 strcpy (buf, PATH_SEP_STR);
1133 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1134 *(r - 1) = 0;
1135 g_free (buf2);
1136 return buf;
1139 static gboolean
1140 mc_util_write_backup_content(const char *from_file_name, const char *to_file_name)
1142 FILE *backup_fd;
1143 char *contents;
1144 gsize length;
1146 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1147 return FALSE;
1149 backup_fd = fopen (to_file_name, "w");
1150 if (backup_fd == NULL) {
1151 g_free(contents);
1152 return FALSE;
1155 fwrite ( (const void *) contents, length, 1, backup_fd);
1157 fflush(backup_fd);
1158 fclose(backup_fd);
1159 g_free(contents);
1160 return TRUE;
1163 /* Finds out a relative path from first to second, i.e. goes as many ..
1164 * as needed up in first and then goes down using second */
1165 char *
1166 diff_two_paths (const char *first, const char *second)
1168 char *p, *q, *r, *s, *buf = NULL;
1169 int i, j, prevlen = -1, currlen;
1170 char *my_first = NULL, *my_second = NULL;
1172 my_first = resolve_symlinks (first);
1173 if (my_first == NULL)
1174 return NULL;
1175 my_second = resolve_symlinks (second);
1176 if (my_second == NULL) {
1177 g_free (my_first);
1178 return NULL;
1180 for (j = 0; j < 2; j++) {
1181 p = my_first;
1182 q = my_second;
1183 for (;;) {
1184 r = strchr (p, PATH_SEP);
1185 s = strchr (q, PATH_SEP);
1186 if (!r || !s)
1187 break;
1188 *r = 0; *s = 0;
1189 if (strcmp (p, q)) {
1190 *r = PATH_SEP; *s = PATH_SEP;
1191 break;
1192 } else {
1193 *r = PATH_SEP; *s = PATH_SEP;
1195 p = r + 1;
1196 q = s + 1;
1198 p--;
1199 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1200 currlen = (i + 1) * 3 + strlen (q) + 1;
1201 if (j) {
1202 if (currlen < prevlen)
1203 g_free (buf);
1204 else {
1205 g_free (my_first);
1206 g_free (my_second);
1207 return buf;
1210 p = buf = g_malloc (currlen);
1211 prevlen = currlen;
1212 for (; i >= 0; i--, p += 3)
1213 strcpy (p, "../");
1214 strcpy (p, q);
1216 g_free (my_first);
1217 g_free (my_second);
1218 return buf;
1221 /* If filename is NULL, then we just append PATH_SEP to the dir */
1222 char *
1223 concat_dir_and_file (const char *dir, const char *file)
1225 int i = strlen (dir);
1227 if (dir [i-1] == PATH_SEP)
1228 return g_strconcat (dir, file, (char *) NULL);
1229 else
1230 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1233 /* Append text to GList, remove all entries with the same text */
1234 GList *
1235 list_append_unique (GList *list, char *text)
1237 GList *lc_link;
1240 * Go to the last position and traverse the list backwards
1241 * starting from the second last entry to make sure that we
1242 * are not removing the current link.
1244 list = g_list_append (list, text);
1245 list = g_list_last (list);
1246 lc_link = g_list_previous (list);
1248 while (lc_link != NULL) {
1249 GList *newlink;
1251 newlink = g_list_previous (lc_link);
1252 if (strcmp ((char *) lc_link->data, text) == 0) {
1253 GList *tmp;
1255 g_free (lc_link->data);
1256 tmp = g_list_remove_link (list, lc_link);
1257 g_list_free_1 (lc_link);
1259 lc_link = newlink;
1262 return list;
1265 /* Following code heavily borrows from libiberty, mkstemps.c */
1267 /* Number of attempts to create a temporary file */
1268 #ifndef TMP_MAX
1269 #define TMP_MAX 16384
1270 #endif /* !TMP_MAX */
1273 * Arguments:
1274 * pname (output) - pointer to the name of the temp file (needs g_free).
1275 * NULL if the function fails.
1276 * prefix - part of the filename before the random part.
1277 * Prepend $TMPDIR or /tmp if there are no path separators.
1278 * suffix - if not NULL, part of the filename after the random part.
1280 * Result:
1281 * handle of the open file or -1 if couldn't open any.
1284 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1286 static const char letters[]
1287 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1288 static unsigned long value;
1289 struct timeval tv;
1290 char *tmpbase;
1291 char *tmpname;
1292 char *XXXXXX;
1293 int count;
1295 if (strchr (prefix, PATH_SEP) == NULL) {
1296 /* Add prefix first to find the position of XXXXXX */
1297 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1298 } else {
1299 tmpbase = g_strdup (prefix);
1302 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1303 *pname = tmpname;
1304 XXXXXX = &tmpname[strlen (tmpbase)];
1305 g_free (tmpbase);
1307 /* Get some more or less random data. */
1308 gettimeofday (&tv, NULL);
1309 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1311 for (count = 0; count < TMP_MAX; ++count) {
1312 unsigned long v = value;
1313 int fd;
1315 /* Fill in the random bits. */
1316 XXXXXX[0] = letters[v % 62];
1317 v /= 62;
1318 XXXXXX[1] = letters[v % 62];
1319 v /= 62;
1320 XXXXXX[2] = letters[v % 62];
1321 v /= 62;
1322 XXXXXX[3] = letters[v % 62];
1323 v /= 62;
1324 XXXXXX[4] = letters[v % 62];
1325 v /= 62;
1326 XXXXXX[5] = letters[v % 62];
1328 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1329 S_IRUSR | S_IWUSR);
1330 if (fd >= 0) {
1331 /* Successfully created. */
1332 return fd;
1335 /* This is a random value. It is only necessary that the next
1336 TMP_MAX values generated by adding 7777 to VALUE are different
1337 with (module 2^32). */
1338 value += 7777;
1341 /* Unsuccessful. Free the filename. */
1342 g_free (tmpname);
1343 *pname = NULL;
1345 return -1;
1349 * Read and restore position for the given filename.
1350 * If there is no stored data, return line 1 and col 0.
1352 void
1353 load_file_position (const char *filename, long *line, long *column, off_t *offset)
1355 char *fn;
1356 FILE *f;
1357 char buf[MC_MAXPATHLEN + 20];
1358 int len;
1360 /* defaults */
1361 *line = 1;
1362 *column = 0;
1363 *offset = 0;
1365 /* open file with positions */
1366 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1367 f = fopen (fn, "r");
1368 g_free (fn);
1369 if (!f)
1370 return;
1372 len = strlen (filename);
1374 while (fgets (buf, sizeof (buf), f)) {
1375 const char *p;
1376 gchar **pos_tokens;
1378 /* check if the filename matches the beginning of string */
1379 if (strncmp (buf, filename, len) != 0)
1380 continue;
1382 /* followed by single space */
1383 if (buf[len] != ' ')
1384 continue;
1386 /* and string without spaces */
1387 p = &buf[len + 1];
1388 if (strchr (p, ' '))
1389 continue;
1391 pos_tokens = g_strsplit_set (p, ";", 3);
1392 if (pos_tokens[0] != NULL) {
1393 *line = strtol (pos_tokens[0], NULL, 10);
1394 if (pos_tokens[1] != NULL) {
1395 *column = strtol (pos_tokens[1], NULL, 10);
1396 if (pos_tokens[2] != NULL)
1397 *offset = strtoll (pos_tokens[2], NULL, 10);
1398 else
1399 *offset = 0;
1400 } else {
1401 *column = 0;
1402 *offset = 0;
1404 } else {
1405 *line = 1;
1406 *column = 0;
1407 *offset = 0;
1409 g_strfreev(pos_tokens);
1411 fclose (f);
1414 /* Save position for the given file */
1415 #define TMP_SUFFIX ".tmp"
1416 void
1417 save_file_position (const char *filename, long line, long column, off_t offset)
1419 static int filepos_max_saved_entries = 0;
1420 char *fn, *tmp_fn;
1421 FILE *f, *tmp_f;
1422 char buf[MC_MAXPATHLEN + 20];
1423 int i = 1;
1424 gsize len;
1426 if (filepos_max_saved_entries == 0)
1427 filepos_max_saved_entries = mc_config_get_int(mc_main_config, CONFIG_APP_SECTION, "filepos_max_saved_entries", 1024);
1429 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1430 if (fn == NULL)
1431 goto early_error;
1433 len = strlen (filename);
1435 mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
1437 /* open file */
1438 f = fopen (fn, "w");
1439 if (f == NULL)
1440 goto open_target_error;
1442 tmp_fn = g_strdup_printf("%s" TMP_SUFFIX ,fn);
1443 tmp_f = fopen (tmp_fn, "r");
1444 if (tmp_f == NULL)
1445 goto open_source_error;
1447 /* put the new record */
1448 if (line != 1 || column != 0) {
1449 if (fprintf (f, "%s %ld;%ld;%llu\n", filename, line, column, offset) < 0)
1450 goto write_position_error;
1453 while (fgets (buf, sizeof (buf), tmp_f)) {
1454 if (
1455 buf[len] == ' ' &&
1456 strncmp (buf, filename, len) == 0 &&
1457 !strchr (&buf[len + 1], ' ')
1459 continue;
1461 fprintf (f, "%s", buf);
1462 if (++i > filepos_max_saved_entries)
1463 break;
1465 fclose (tmp_f);
1466 g_free(tmp_fn);
1467 fclose (f);
1468 mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
1469 g_free (fn);
1470 return;
1472 write_position_error:
1473 fclose (tmp_f);
1474 open_source_error:
1475 g_free(tmp_fn);
1476 fclose (f);
1477 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1478 open_target_error:
1479 g_free (fn);
1480 early_error:
1481 return;
1483 #undef TMP_SUFFIX
1484 extern const char *
1485 cstrcasestr (const char *haystack, const char *needle)
1487 char *nee = str_create_search_needle (needle, 0);
1488 const char *result = str_search_first (haystack, nee, 0);
1489 str_release_search_needle (nee, 0);
1490 return result;
1493 const char *
1494 cstrstr (const char *haystack, const char *needle)
1496 return strstr(haystack, needle);
1499 extern char *
1500 str_unconst (const char *s)
1502 return (char *) s;
1505 #define ASCII_A (0x40 + 1)
1506 #define ASCII_Z (0x40 + 26)
1507 #define ASCII_a (0x60 + 1)
1508 #define ASCII_z (0x60 + 26)
1510 extern int
1511 ascii_alpha_to_cntrl (int ch)
1513 if ((ch >= ASCII_A && ch <= ASCII_Z)
1514 || (ch >= ASCII_a && ch <= ASCII_z)) {
1515 ch &= 0x1f;
1517 return ch;
1520 const char *
1521 Q_ (const char *s)
1523 const char *result, *sep;
1525 result = _(s);
1526 sep = strchr(result, '|');
1527 return (sep != NULL) ? sep + 1 : result;
1531 gboolean
1532 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1534 struct stat stat_buf;
1535 char *backup_path;
1536 gboolean ret;
1537 if (!exist_file (file_name))
1538 return FALSE;
1540 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1542 if (backup_path == NULL)
1543 return FALSE;
1545 ret = mc_util_write_backup_content (file_name, backup_path);
1547 if (ret) {
1548 /* Backup file will have same ownership with main file. */
1549 if (stat (file_name, &stat_buf) == 0)
1550 chmod (backup_path, stat_buf.st_mode);
1551 else
1552 chmod (backup_path, S_IRUSR | S_IWUSR);
1555 g_free(backup_path);
1557 return ret;
1560 gboolean
1561 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1563 gboolean ret;
1564 char *backup_path;
1566 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1567 if (backup_path == NULL)
1568 return FALSE;
1570 ret = mc_util_write_backup_content (backup_path, file_name);
1571 g_free(backup_path);
1573 return ret;
1576 gboolean
1577 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1579 char *backup_path;
1581 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1582 if (backup_path == NULL)
1583 return FALSE;
1585 if (exist_file (backup_path))
1586 mc_unlink (backup_path);
1588 g_free(backup_path);
1589 return TRUE;
1592 /* partly taken from dcigettext.c, returns "" for default locale */
1593 /* value should be freed by calling function g_free() */
1594 char *guess_message_value (void)
1596 static const char * const var[] = {
1597 /* Setting of LC_ALL overwrites all other. */
1598 /* Do not use LANGUAGE for check user locale and drowing hints */
1599 "LC_ALL",
1600 /* Next comes the name of the desired category. */
1601 "LC_MESSAGES",
1602 /* Last possibility is the LANG environment variable. */
1603 "LANG",
1604 /* NULL exit loops */
1605 NULL
1608 unsigned i = 0;
1609 const char *locale = NULL;
1611 while (var[i] != NULL) {
1612 locale = getenv (var[i]);
1613 if (locale != NULL && locale[0] != '\0')
1614 break;
1615 i++;
1618 if (locale == NULL)
1619 locale = "";
1621 return g_strdup (locale);