Ticket #1017: added missing #include.
[midnight-commander.git] / lib / util.c
blobdd40aa82aba4ceba355fdc3bb4d1f4b6f592ce31
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/file.h" /* copy_file_file() */
53 #ifndef HAVE_CHARSET
54 #include "src/main.h" /* eight_bit_clean */
55 #endif
57 /*In order to use everywhere the same setup
58 for the locale we use defines */
59 #define FMTYEAR _("%b %e %Y")
60 #define FMTTIME _("%b %e %H:%M")
63 int easy_patterns = 1;
66 * If true, SI units (1000 based) will be used for
67 * larger units (kilobyte, megabyte, ...).
68 * If false binary units (1024 based) will be used.
70 int kilobyte_si = 0;
74 extern void str_replace(char *s, char from, char to)
76 for (; *s != '\0'; s++) {
77 if (*s == from)
78 *s = to;
82 static inline int
83 is_7bit_printable (unsigned char c)
85 return (c > 31 && c < 127);
88 static inline int
89 is_iso_printable (unsigned char c)
91 return ((c > 31 && c < 127) || c >= 160);
94 static inline int
95 is_8bit_printable (unsigned char c)
97 /* "Full 8 bits output" doesn't work on xterm */
98 if (xterm_flag)
99 return is_iso_printable (c);
101 return (c > 31 && c != 127 && c != 155);
105 is_printable (int c)
107 c &= 0xff;
109 #ifdef HAVE_CHARSET
110 /* "Display bits" is ignored, since the user controls the output
111 by setting the output codepage */
112 return is_8bit_printable (c);
113 #else
114 if (!eight_bit_clean)
115 return is_7bit_printable (c);
117 if (full_eight_bits) {
118 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++) {
133 if (*text == '\n') {
134 nlines++;
135 colindex = 0;
136 } else {
137 colindex++;
138 if (colindex > ncolumns)
139 ncolumns = colindex;
143 *lines = nlines;
144 *columns = ncolumns;
148 * Copy from s to d, and trim the beginning if necessary, and prepend
149 * "..." in this case. The destination string can have at most len
150 * bytes, not counting trailing 0.
152 char *
153 trim (const char *s, char *d, int len)
155 int source_len;
157 /* Sanity check */
158 len = max (len, 0);
160 source_len = strlen (s);
161 if (source_len > len) {
162 /* Cannot fit the whole line */
163 if (len <= 3) {
164 /* We only have room for the dots */
165 memset (d, '.', len);
166 d[len] = 0;
167 return d;
168 } else {
169 /* Begin with ... and add the rest of the source string */
170 memset (d, '.', 3);
171 strcpy (d + 3, s + 3 + source_len - len);
173 } else
174 /* We can copy the whole line */
175 strcpy (d, s);
176 return d;
180 * Quote the filename for the purpose of inserting it into the command
181 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
182 * processed by the mc command line.
184 char *
185 name_quote (const char *s, int quote_percent)
187 char *ret, *d;
189 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
190 if (*s == '-') {
191 *d++ = '.';
192 *d++ = '/';
195 for (; *s; s++, d++) {
196 switch (*s) {
197 case '%':
198 if (quote_percent)
199 *d++ = '%';
200 break;
201 case '\'':
202 case '\\':
203 case '\r':
204 case '\n':
205 case '\t':
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 case '(':
223 case ')':
224 *d++ = '\\';
225 break;
226 case '~':
227 case '#':
228 if (d == ret)
229 *d++ = '\\';
230 break;
232 *d = *s;
234 *d = '\0';
235 return ret;
238 char *
239 fake_name_quote (const char *s, int quote_percent)
241 (void) quote_percent;
242 return g_strdup (s);
246 * Remove the middle part of the string to fit given length.
247 * Use "~" to show where the string was truncated.
248 * Return static buffer, no need to free() it.
250 const char *
251 name_trunc (const char *txt, size_t trunc_len)
253 return str_trunc (txt, trunc_len);
257 * path_trunc() is the same as name_trunc() above but
258 * it deletes possible password from path for security
259 * reasons.
261 const char *
262 path_trunc (const char *path, size_t trunc_len) {
263 char *secure_path = strip_password (g_strdup (path), 1);
265 const char *ret = str_trunc (secure_path, trunc_len);
266 g_free (secure_path);
268 return ret;
271 const char *
272 size_trunc (double size)
274 static char x [BUF_TINY];
275 long int divisor = 1;
276 const char *xtra = "";
278 if (size > 999999999L){
279 divisor = kilobyte_si?1000:1024;
280 xtra = kilobyte_si?"k":"K";
281 if (size/divisor > 999999999L){
282 divisor = kilobyte_si?(1000*1000):(1024*1024);
283 xtra = kilobyte_si?"m":"M";
286 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
287 return x;
290 const char *
291 size_trunc_sep (double size)
293 static char x [60];
294 int count;
295 const char *p, *y;
296 char *d;
298 p = y = size_trunc (size);
299 p += strlen (p) - 1;
300 d = x + sizeof (x) - 1;
301 *d-- = 0;
302 while (p >= y && isalpha ((unsigned char) *p))
303 *d-- = *p--;
304 for (count = 0; p >= y; count++){
305 if (count == 3){
306 *d-- = ',';
307 count = 0;
309 *d-- = *p--;
311 d++;
312 if (*d == ',')
313 d++;
314 return d;
318 * Print file SIZE to BUFFER, but don't exceed LEN characters,
319 * not including trailing 0. BUFFER should be at least LEN+1 long.
320 * This function is called for every file on panels, so avoid
321 * floating point by any means.
323 * Units: size units (filesystem sizes are 1K blocks)
324 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
326 void
327 size_trunc_len (char *buffer, unsigned int len, off_t size, int units)
329 /* Avoid taking power for every file. */
330 static const off_t power10 [] =
331 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
332 1000000000};
333 static const char * const suffix [] =
334 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
335 static const char * const suffix_lc [] =
336 {"", "k", "m", "g", "t", "p", "e", "z", "y", NULL};
337 int j = 0;
338 int size_remain;
340 if (len == 0)
341 len = 9;
344 * recalculate from 1024 base to 1000 base if units>0
345 * We can't just multiply by 1024 - that might cause overflow
346 * if off_t type is too small
348 if (units && kilobyte_si) {
349 for (j = 0; j < units; j++) {
350 size_remain=((size % 125)*1024)/1000; /* size mod 125, recalculated */
351 size = size / 125; /* 128/125 = 1024/1000 */
352 size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
353 size += size_remain; /* Re-add remainder lost by division/multiplication */
357 for (j = units; suffix [j] != NULL; j++) {
358 if (size == 0) {
359 if (j == units) {
360 /* Empty files will print "0" even with minimal width. */
361 g_snprintf (buffer, len + 1, "0");
362 break;
365 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
366 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
367 (j > 1) ? (kilobyte_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
368 break;
371 if (size < power10 [len - (j > 0)]) {
372 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, kilobyte_si ? suffix_lc[j] : suffix[j]);
373 break;
376 /* Powers of 1000 or 1024, with rounding. */
377 if (kilobyte_si) {
378 size = (size + 500) / 1000;
379 } else {
380 size = (size + 512) >> 10;
386 is_exe (mode_t mode)
388 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
389 return 1;
390 return 0;
393 #define ismode(n,m) ((n & m) == m)
395 const char *
396 string_perm (mode_t mode_bits)
398 static char mode[11];
400 strcpy (mode, "----------");
401 if (S_ISDIR (mode_bits))
402 mode[0] = 'd';
403 if (S_ISCHR (mode_bits))
404 mode[0] = 'c';
405 if (S_ISBLK (mode_bits))
406 mode[0] = 'b';
407 if (S_ISLNK (mode_bits))
408 mode[0] = 'l';
409 if (S_ISFIFO (mode_bits))
410 mode[0] = 'p';
411 if (S_ISNAM (mode_bits))
412 mode[0] = 'n';
413 if (S_ISSOCK (mode_bits))
414 mode[0] = 's';
415 if (S_ISDOOR (mode_bits))
416 mode[0] = 'D';
417 if (ismode (mode_bits, S_IXOTH))
418 mode[9] = 'x';
419 if (ismode (mode_bits, S_IWOTH))
420 mode[8] = 'w';
421 if (ismode (mode_bits, S_IROTH))
422 mode[7] = 'r';
423 if (ismode (mode_bits, S_IXGRP))
424 mode[6] = 'x';
425 if (ismode (mode_bits, S_IWGRP))
426 mode[5] = 'w';
427 if (ismode (mode_bits, S_IRGRP))
428 mode[4] = 'r';
429 if (ismode (mode_bits, S_IXUSR))
430 mode[3] = 'x';
431 if (ismode (mode_bits, S_IWUSR))
432 mode[2] = 'w';
433 if (ismode (mode_bits, S_IRUSR))
434 mode[1] = 'r';
435 #ifdef S_ISUID
436 if (ismode (mode_bits, S_ISUID))
437 mode[3] = (mode[3] == 'x') ? 's' : 'S';
438 #endif /* S_ISUID */
439 #ifdef S_ISGID
440 if (ismode (mode_bits, S_ISGID))
441 mode[6] = (mode[6] == 'x') ? 's' : 'S';
442 #endif /* S_ISGID */
443 #ifdef S_ISVTX
444 if (ismode (mode_bits, S_ISVTX))
445 mode[9] = (mode[9] == 'x') ? 't' : 'T';
446 #endif /* S_ISVTX */
447 return mode;
450 /* p: string which might contain an url with a password (this parameter is
451 modified in place).
452 has_prefix = 0: The first parameter is an url without a prefix
453 (user[:pass]@]machine[:port][remote-dir). Delete
454 the password.
455 has_prefix = 1: Search p for known url prefixes. If found delete
456 the password from the url.
457 Caveat: only the first url is found
459 char *
460 strip_password (char *p, int has_prefix)
462 static const struct {
463 const char *name;
464 size_t len;
465 } prefixes[] = { {"/#ftp:", 6},
466 {"ftp://", 6},
467 {"/#mc:", 5},
468 {"mc://", 5},
469 {"/#smb:", 6},
470 {"smb://", 6},
471 {"/#sh:", 5},
472 {"sh://", 5},
473 {"ssh://", 6}
475 char *at, *inner_colon, *dir;
476 size_t i;
477 char *result = p;
479 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
480 char *q;
482 if (has_prefix) {
483 if((q = strstr (p, prefixes[i].name)) == 0)
484 continue;
485 else
486 p = q + prefixes[i].len;
489 if ((dir = strchr (p, PATH_SEP)) != NULL)
490 *dir = '\0';
492 /* search for any possible user */
493 at = strrchr (p, '@');
495 if (dir)
496 *dir = PATH_SEP;
498 /* We have a username */
499 if (at) {
500 inner_colon = memchr (p, ':', at - p);
501 if (inner_colon)
502 memmove (inner_colon, at, strlen(at) + 1);
504 break;
506 return (result);
509 const char *
510 strip_home_and_password(const char *dir)
512 size_t len;
513 static char newdir [MC_MAXPATHLEN];
515 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
516 (dir[len] == PATH_SEP || dir[len] == '\0')){
517 newdir [0] = '~';
518 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
519 return newdir;
522 /* We do not strip homes in /#ftp tree, I do not like ~'s there
523 (see ftpfs.c why) */
524 g_strlcpy (newdir, dir, sizeof(newdir));
525 strip_password (newdir, 1);
526 return newdir;
529 const char *
530 extension (const char *filename)
532 const char *d = strrchr (filename, '.');
533 return (d != NULL) ? d + 1 : "";
537 exist_file (const char *name)
539 return access (name, R_OK) == 0;
543 check_for_default (const char *default_file, const char *file)
545 if (!exist_file (file)) {
546 FileOpContext *ctx;
547 off_t count = 0;
548 double bytes = 0.0;
550 if (!exist_file (default_file))
551 return -1;
553 ctx = file_op_context_new (OP_COPY);
554 file_op_context_create_ui (ctx, 0);
555 copy_file_file (ctx, default_file, file, 1, &count, &bytes, 1);
556 file_op_context_destroy (ctx);
559 return 0;
564 char *
565 load_file (const char *filename)
567 FILE *data_file;
568 struct stat s;
569 char *data;
570 long read_size;
572 if ((data_file = fopen (filename, "r")) == NULL){
573 return 0;
575 if (fstat (fileno (data_file), &s) != 0){
576 fclose (data_file);
577 return 0;
579 data = g_malloc (s.st_size+1);
580 read_size = fread (data, 1, s.st_size, data_file);
581 data [read_size] = 0;
582 fclose (data_file);
584 if (read_size > 0)
585 return data;
586 else {
587 g_free (data);
588 return 0;
592 char *
593 load_mc_home_file (const char *_mc_home, const char *_mc_home_alt, const char *filename, char **allocated_filename)
595 char *hintfile_base, *hintfile;
596 char *lang;
597 char *data;
599 hintfile_base = concat_dir_and_file (_mc_home, filename);
600 lang = guess_message_value ();
602 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
603 data = load_file (hintfile);
605 if (!data) {
606 g_free (hintfile);
607 g_free (hintfile_base);
608 hintfile_base = concat_dir_and_file (_mc_home_alt, filename);
610 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
611 data = load_file (hintfile);
613 if (!data) {
614 /* Fall back to the two-letter language code */
615 if (lang[0] && lang[1])
616 lang[2] = 0;
617 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
618 data = load_file (hintfile);
620 if (!data) {
621 g_free (hintfile);
622 hintfile = hintfile_base;
623 data = load_file (hintfile_base);
628 g_free (lang);
630 if (hintfile != hintfile_base)
631 g_free (hintfile_base);
633 if (allocated_filename)
634 *allocated_filename = hintfile;
635 else
636 g_free (hintfile);
638 return data;
641 /* Check strftime() results. Some systems (i.e. Solaris) have different
642 short-month-name sizes for different locales */
643 size_t
644 i18n_checktimelength (void)
646 size_t length;
647 time_t testtime = time (NULL);
648 struct tm* lt = localtime(&testtime);
650 if (lt == NULL) {
651 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
652 length = str_term_width1 (_(INVALID_TIME_TEXT));
653 } else {
654 char buf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
655 size_t a, b;
657 strftime (buf, sizeof(buf) - 1, FMTTIME, lt);
658 a = str_term_width1 (buf);
659 strftime (buf, sizeof(buf) - 1, FMTYEAR, lt);
660 b = str_term_width1 (buf);
662 length = max (a, b);
663 length = max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT)), length);
666 /* Don't handle big differences. Use standard value (email bug, please) */
667 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
668 length = STD_I18NTIMELENGTH;
670 return length;
673 const char *
674 file_date (time_t when)
676 static char timebuf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
677 time_t current_time = time ((time_t) 0);
678 const char *fmt;
680 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
681 || current_time < when - 60L * 60L) /* In the future. */
682 /* The file is fairly old or in the future.
683 POSIX says the cutoff is 6 months old;
684 approximate this by 6*30 days.
685 Allow a 1 hour slop factor for what is considered "the future",
686 to allow for NFS server/client clock disagreement.
687 Show the year instead of the time of day. */
689 fmt = FMTYEAR;
690 else
691 fmt = FMTTIME;
693 FMT_LOCALTIME(timebuf, sizeof (timebuf), fmt, when);
695 return timebuf;
698 const char *
699 extract_line (const char *s, const char *top)
701 static char tmp_line [BUF_MEDIUM];
702 char *t = tmp_line;
704 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
705 *t++ = *s++;
706 *t = 0;
707 return tmp_line;
710 /* The basename routine */
711 const char *
712 x_basename (const char *s)
714 const char *where;
715 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
719 const char *
720 unix_error_string (int error_num)
722 static char buffer [BUF_LARGE];
723 gchar *strerror_currentlocale;
725 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
726 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
727 strerror_currentlocale, error_num);
728 g_free(strerror_currentlocale);
730 return buffer;
733 const char *
734 skip_separators (const char *s)
736 const char *su = s;
738 for (;*su; str_cnext_char (&su))
739 if (*su != ' ' && *su != '\t' && *su != ',') break;
741 return su;
744 const char *
745 skip_numbers (const char *s)
747 const char *su = s;
749 for (;*su; str_cnext_char (&su))
750 if (!str_isdigit (su)) break;
752 return su;
755 /* Remove all control sequences from the argument string. We define
756 * "control sequence", in a sort of pidgin BNF, as follows:
758 * control-seq = Esc non-'['
759 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
761 * This scheme works for all the terminals described in my termcap /
762 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
763 * terminals. If I hear from a single person who uses such a terminal
764 * with MC, I'll be glad to add support for it. (Dugan)
765 * Non-printable characters are also removed.
768 char *
769 strip_ctrl_codes (char *s)
771 char *w; /* Current position where the stripped data is written */
772 char *r; /* Current position where the original data is read */
773 char *n;
775 if (!s)
776 return 0;
778 for (w = s, r = s; *r; ) {
779 if (*r == ESC_CHAR) {
780 /* Skip the control sequence's arguments */ ;
781 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
782 if (*(++r) == '[' || *r == '(') {
783 /* strchr() matches trailing binary 0 */
784 while (*(++r) && strchr ("0123456789;?", *r));
785 } else
786 if (*r == ']') {
788 * Skip xterm's OSC (Operating System Command)
789 * http://www.xfree86.org/current/ctlseqs.html
790 * OSC P s ; P t ST
791 * OSC P s ; P t BEL
793 char * new_r = r;
795 for (; *new_r; ++new_r)
797 switch (*new_r)
799 /* BEL */
800 case '\a':
801 r = new_r;
802 goto osc_out;
803 case ESC_CHAR:
804 /* ST */
805 if (*(new_r + 1) == '\\')
807 r = new_r + 1;
808 goto osc_out;
812 osc_out:;
816 * Now we are at the last character of the sequence.
817 * Skip it unless it's binary 0.
819 if (*r)
820 r++;
821 continue;
824 n = str_get_next_char (r);
825 if (str_isprint (r)) {
826 memmove (w, r, n - r);
827 w+= n - r;
829 r = n;
831 *w = 0;
832 return s;
836 #ifndef ENABLE_VFS
837 char *
838 get_current_wd (char *buffer, int size)
840 char *p;
841 int len;
843 p = g_get_current_dir ();
844 len = strlen(p) + 1;
846 if (len > size) {
847 g_free (p);
848 return NULL;
851 memcpy (buffer, p, len);
852 g_free (p);
854 return buffer;
856 #endif /* !ENABLE_VFS */
858 enum compression_type
859 get_compression_type (int fd, const char * name)
861 unsigned char magic[16];
862 size_t str_len;
864 /* Read the magic signature */
865 if (mc_read (fd, (char *) magic, 4) != 4)
866 return COMPRESSION_NONE;
868 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
869 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
870 return COMPRESSION_GZIP;
873 /* PKZIP_MAGIC */
874 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
875 && magic[3] == 004) {
876 /* Read compression type */
877 mc_lseek (fd, 8, SEEK_SET);
878 if (mc_read (fd, (char *) magic, 2) != 2)
879 return COMPRESSION_NONE;
881 /* Gzip can handle only deflated (8) or stored (0) files */
882 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
883 return COMPRESSION_NONE;
885 /* Compatible with gzip */
886 return COMPRESSION_GZIP;
889 /* PACK_MAGIC and LZH_MAGIC and compress magic */
890 if (magic[0] == 037
891 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
892 /* Compatible with gzip */
893 return COMPRESSION_GZIP;
896 /* BZIP and BZIP2 files */
897 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
898 (magic[3] >= '1') && (magic[3] <= '9')) {
899 switch (magic[2]) {
900 case '0':
901 return COMPRESSION_BZIP;
902 case 'h':
903 return COMPRESSION_BZIP2;
907 /* Support for LZMA (only utils format with magic in header).
908 * This is the default format of LZMA utils 4.32.1 and later. */
910 if (mc_read(fd, (char *) magic+4, 2) != 2)
911 return COMPRESSION_NONE;
913 /* LZMA utils format */
914 if (
915 magic[0] == 0xFF
916 && magic[1] == 'L'
917 && magic[2] == 'Z'
918 && magic[3] == 'M'
919 && magic[4] == 'A'
920 && magic[5] == 0x00
922 return COMPRESSION_LZMA;
924 /* XZ compression magic */
925 if (
926 magic[0] == 0xFD
927 && magic[1] == 0x37
928 && magic[2] == 0x7A
929 && magic[3] == 0x58
930 && magic[4] == 0x5A
931 && magic[5] == 0x00
933 return COMPRESSION_XZ;
935 str_len = strlen(name);
936 /* HACK: we must belive to extention of LZMA file :) ...*/
937 if ( (str_len > 5 && strcmp(&name[str_len-5],".lzma") == 0) ||
938 (str_len > 4 && strcmp(&name[str_len-4],".tlz") == 0))
939 return COMPRESSION_LZMA;
941 return COMPRESSION_NONE;
944 const char *
945 decompress_extension (int type)
947 switch (type){
948 case COMPRESSION_GZIP: return "#ugz";
949 case COMPRESSION_BZIP: return "#ubz";
950 case COMPRESSION_BZIP2: return "#ubz2";
951 case COMPRESSION_LZMA: return "#ulzma";
952 case COMPRESSION_XZ: return "#uxz";
954 /* Should never reach this place */
955 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
956 return 0;
959 /* Hooks */
960 void
961 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
963 Hook *new_hook = g_new (Hook, 1);
965 new_hook->hook_fn = hook_fn;
966 new_hook->next = *hook_list;
967 new_hook->hook_data = data;
969 *hook_list = new_hook;
972 void
973 execute_hooks (Hook *hook_list)
975 Hook *new_hook = 0;
976 Hook *p;
978 /* We copy the hook list first so tahat we let the hook
979 * function call delete_hook
982 while (hook_list){
983 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
984 hook_list = hook_list->next;
986 p = new_hook;
988 while (new_hook){
989 (*new_hook->hook_fn)(new_hook->hook_data);
990 new_hook = new_hook->next;
993 for (hook_list = p; hook_list;){
994 p = hook_list;
995 hook_list = hook_list->next;
996 g_free (p);
1000 void
1001 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1003 Hook *current, *new_list, *next;
1005 new_list = 0;
1007 for (current = *hook_list; current; current = next){
1008 next = current->next;
1009 if (current->hook_fn == hook_fn)
1010 g_free (current);
1011 else
1012 add_hook (&new_list, current->hook_fn, current->hook_data);
1014 *hook_list = new_list;
1018 hook_present (Hook *hook_list, void (*hook_fn)(void *))
1020 Hook *p;
1022 for (p = hook_list; p; p = p->next)
1023 if (p->hook_fn == hook_fn)
1024 return 1;
1025 return 0;
1028 void
1029 wipe_password (char *passwd)
1031 char *p = passwd;
1033 if (!p)
1034 return;
1035 for (;*p ; p++)
1036 *p = 0;
1037 g_free (passwd);
1040 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1041 /* Returns a newly allocated string */
1042 char *
1043 convert_controls (const char *p)
1045 char *valcopy = g_strdup (p);
1046 char *q;
1048 /* Parse the escape special character */
1049 for (q = valcopy; *p;){
1050 if (*p == '\\'){
1051 p++;
1052 if ((*p == 'e') || (*p == 'E')){
1053 p++;
1054 *q++ = ESC_CHAR;
1056 } else {
1057 if (*p == '^'){
1058 p++;
1059 if (*p == '^')
1060 *q++ = *p++;
1061 else {
1062 char c = (*p | 0x20);
1063 if (c >= 'a' && c <= 'z') {
1064 *q++ = c - 'a' + 1;
1065 p++;
1066 } else if (*p)
1067 p++;
1069 } else
1070 *q++ = *p++;
1073 *q = 0;
1074 return valcopy;
1077 static char *
1078 resolve_symlinks (const char *path)
1080 char *buf, *buf2, *q, *r, c;
1081 int len;
1082 struct stat mybuf;
1083 const char *p;
1085 if (*path != PATH_SEP)
1086 return NULL;
1087 r = buf = g_malloc (MC_MAXPATHLEN);
1088 buf2 = g_malloc (MC_MAXPATHLEN);
1089 *r++ = PATH_SEP;
1090 *r = 0;
1091 p = path;
1092 for (;;) {
1093 q = strchr (p + 1, PATH_SEP);
1094 if (!q) {
1095 q = strchr (p + 1, 0);
1096 if (q == p + 1)
1097 break;
1099 c = *q;
1100 *q = 0;
1101 if (mc_lstat (path, &mybuf) < 0) {
1102 g_free (buf);
1103 g_free (buf2);
1104 *q = c;
1105 return NULL;
1107 if (!S_ISLNK (mybuf.st_mode))
1108 strcpy (r, p + 1);
1109 else {
1110 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1111 if (len < 0) {
1112 g_free (buf);
1113 g_free (buf2);
1114 *q = c;
1115 return NULL;
1117 buf2 [len] = 0;
1118 if (*buf2 == PATH_SEP)
1119 strcpy (buf, buf2);
1120 else
1121 strcpy (r, buf2);
1123 canonicalize_pathname (buf);
1124 r = strchr (buf, 0);
1125 if (!*r || *(r - 1) != PATH_SEP) {
1126 *r++ = PATH_SEP;
1127 *r = 0;
1129 *q = c;
1130 p = q;
1131 if (!c)
1132 break;
1134 if (!*buf)
1135 strcpy (buf, PATH_SEP_STR);
1136 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1137 *(r - 1) = 0;
1138 g_free (buf2);
1139 return buf;
1142 static gboolean
1143 mc_util_write_backup_content(const char *from_file_name, const char *to_file_name)
1145 FILE *backup_fd;
1146 char *contents;
1147 gsize length;
1149 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1150 return FALSE;
1152 backup_fd = fopen (to_file_name, "w");
1153 if (backup_fd == NULL) {
1154 g_free(contents);
1155 return FALSE;
1158 fwrite ( (const void *) contents, length, 1, backup_fd);
1160 fflush(backup_fd);
1161 fclose(backup_fd);
1162 g_free(contents);
1163 return TRUE;
1166 /* Finds out a relative path from first to second, i.e. goes as many ..
1167 * as needed up in first and then goes down using second */
1168 char *
1169 diff_two_paths (const char *first, const char *second)
1171 char *p, *q, *r, *s, *buf = NULL;
1172 int i, j, prevlen = -1, currlen;
1173 char *my_first = NULL, *my_second = NULL;
1175 my_first = resolve_symlinks (first);
1176 if (my_first == NULL)
1177 return NULL;
1178 my_second = resolve_symlinks (second);
1179 if (my_second == NULL) {
1180 g_free (my_first);
1181 return NULL;
1183 for (j = 0; j < 2; j++) {
1184 p = my_first;
1185 q = my_second;
1186 for (;;) {
1187 r = strchr (p, PATH_SEP);
1188 s = strchr (q, PATH_SEP);
1189 if (!r || !s)
1190 break;
1191 *r = 0; *s = 0;
1192 if (strcmp (p, q)) {
1193 *r = PATH_SEP; *s = PATH_SEP;
1194 break;
1195 } else {
1196 *r = PATH_SEP; *s = PATH_SEP;
1198 p = r + 1;
1199 q = s + 1;
1201 p--;
1202 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1203 currlen = (i + 1) * 3 + strlen (q) + 1;
1204 if (j) {
1205 if (currlen < prevlen)
1206 g_free (buf);
1207 else {
1208 g_free (my_first);
1209 g_free (my_second);
1210 return buf;
1213 p = buf = g_malloc (currlen);
1214 prevlen = currlen;
1215 for (; i >= 0; i--, p += 3)
1216 strcpy (p, "../");
1217 strcpy (p, q);
1219 g_free (my_first);
1220 g_free (my_second);
1221 return buf;
1224 /* If filename is NULL, then we just append PATH_SEP to the dir */
1225 char *
1226 concat_dir_and_file (const char *dir, const char *file)
1228 int i = strlen (dir);
1230 if (dir [i-1] == PATH_SEP)
1231 return g_strconcat (dir, file, (char *) NULL);
1232 else
1233 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1236 /* Append text to GList, remove all entries with the same text */
1237 GList *
1238 list_append_unique (GList *list, char *text)
1240 GList *lc_link;
1243 * Go to the last position and traverse the list backwards
1244 * starting from the second last entry to make sure that we
1245 * are not removing the current link.
1247 list = g_list_append (list, text);
1248 list = g_list_last (list);
1249 lc_link = g_list_previous (list);
1251 while (lc_link != NULL) {
1252 GList *newlink;
1254 newlink = g_list_previous (lc_link);
1255 if (strcmp ((char *) lc_link->data, text) == 0) {
1256 GList *tmp;
1258 g_free (lc_link->data);
1259 tmp = g_list_remove_link (list, lc_link);
1260 g_list_free_1 (lc_link);
1262 lc_link = newlink;
1265 return list;
1268 /* Following code heavily borrows from libiberty, mkstemps.c */
1270 /* Number of attempts to create a temporary file */
1271 #ifndef TMP_MAX
1272 #define TMP_MAX 16384
1273 #endif /* !TMP_MAX */
1276 * Arguments:
1277 * pname (output) - pointer to the name of the temp file (needs g_free).
1278 * NULL if the function fails.
1279 * prefix - part of the filename before the random part.
1280 * Prepend $TMPDIR or /tmp if there are no path separators.
1281 * suffix - if not NULL, part of the filename after the random part.
1283 * Result:
1284 * handle of the open file or -1 if couldn't open any.
1287 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1289 static const char letters[]
1290 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1291 static unsigned long value;
1292 struct timeval tv;
1293 char *tmpbase;
1294 char *tmpname;
1295 char *XXXXXX;
1296 int count;
1298 if (strchr (prefix, PATH_SEP) == NULL) {
1299 /* Add prefix first to find the position of XXXXXX */
1300 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1301 } else {
1302 tmpbase = g_strdup (prefix);
1305 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1306 *pname = tmpname;
1307 XXXXXX = &tmpname[strlen (tmpbase)];
1308 g_free (tmpbase);
1310 /* Get some more or less random data. */
1311 gettimeofday (&tv, NULL);
1312 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1314 for (count = 0; count < TMP_MAX; ++count) {
1315 unsigned long v = value;
1316 int fd;
1318 /* Fill in the random bits. */
1319 XXXXXX[0] = letters[v % 62];
1320 v /= 62;
1321 XXXXXX[1] = letters[v % 62];
1322 v /= 62;
1323 XXXXXX[2] = letters[v % 62];
1324 v /= 62;
1325 XXXXXX[3] = letters[v % 62];
1326 v /= 62;
1327 XXXXXX[4] = letters[v % 62];
1328 v /= 62;
1329 XXXXXX[5] = letters[v % 62];
1331 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1332 S_IRUSR | S_IWUSR);
1333 if (fd >= 0) {
1334 /* Successfully created. */
1335 return fd;
1338 /* This is a random value. It is only necessary that the next
1339 TMP_MAX values generated by adding 7777 to VALUE are different
1340 with (module 2^32). */
1341 value += 7777;
1344 /* Unsuccessful. Free the filename. */
1345 g_free (tmpname);
1346 *pname = NULL;
1348 return -1;
1352 * Read and restore position for the given filename.
1353 * If there is no stored data, return line 1 and col 0.
1355 void
1356 load_file_position (const char *filename, long *line, long *column, off_t *offset)
1358 char *fn;
1359 FILE *f;
1360 char buf[MC_MAXPATHLEN + 20];
1361 int len;
1363 /* defaults */
1364 *line = 1;
1365 *column = 0;
1366 *offset = 0;
1368 /* open file with positions */
1369 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1370 f = fopen (fn, "r");
1371 g_free (fn);
1372 if (!f)
1373 return;
1375 len = strlen (filename);
1377 while (fgets (buf, sizeof (buf), f)) {
1378 const char *p;
1379 gchar **pos_tokens;
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 pos_tokens = g_strsplit_set (p, ";", 3);
1395 if (pos_tokens[0] != NULL) {
1396 *line = strtol (pos_tokens[0], NULL, 10);
1397 if (pos_tokens[1] != NULL) {
1398 *column = strtol (pos_tokens[1], NULL, 10);
1399 if (pos_tokens[2] != NULL)
1400 *offset = strtoll (pos_tokens[2], NULL, 10);
1401 else
1402 *offset = 0;
1403 } else {
1404 *column = 0;
1405 *offset = 0;
1407 } else {
1408 *line = 1;
1409 *column = 0;
1410 *offset = 0;
1412 g_strfreev(pos_tokens);
1414 fclose (f);
1417 /* Save position for the given file */
1418 #define TMP_SUFFIX ".tmp"
1419 void
1420 save_file_position (const char *filename, long line, long column, off_t offset)
1422 static int filepos_max_saved_entries = 0;
1423 char *fn, *tmp_fn;
1424 FILE *f, *tmp_f;
1425 char buf[MC_MAXPATHLEN + 20];
1426 int i = 1;
1427 gsize len;
1429 if (filepos_max_saved_entries == 0)
1430 filepos_max_saved_entries = mc_config_get_int(mc_main_config, CONFIG_APP_SECTION, "filepos_max_saved_entries", 1024);
1432 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1433 if (fn == NULL)
1434 goto early_error;
1436 len = strlen (filename);
1438 mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
1440 /* open file */
1441 f = fopen (fn, "w");
1442 if (f == NULL)
1443 goto open_target_error;
1445 tmp_fn = g_strdup_printf("%s" TMP_SUFFIX ,fn);
1446 tmp_f = fopen (tmp_fn, "r");
1447 if (tmp_f == NULL)
1448 goto open_source_error;
1450 /* put the new record */
1451 if (line != 1 || column != 0) {
1452 if (fprintf (f, "%s %ld;%ld;%lli\n", filename, line, column, offset) < 0)
1453 goto write_position_error;
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);
1473 return;
1475 write_position_error:
1476 fclose (tmp_f);
1477 open_source_error:
1478 g_free(tmp_fn);
1479 fclose (f);
1480 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1481 open_target_error:
1482 g_free (fn);
1483 early_error:
1484 return;
1486 #undef TMP_SUFFIX
1487 extern const char *
1488 cstrcasestr (const char *haystack, const char *needle)
1490 char *nee = str_create_search_needle (needle, 0);
1491 const char *result = str_search_first (haystack, nee, 0);
1492 str_release_search_needle (nee, 0);
1493 return result;
1496 const char *
1497 cstrstr (const char *haystack, const char *needle)
1499 return strstr(haystack, needle);
1502 extern char *
1503 str_unconst (const char *s)
1505 return (char *) s;
1508 #define ASCII_A (0x40 + 1)
1509 #define ASCII_Z (0x40 + 26)
1510 #define ASCII_a (0x60 + 1)
1511 #define ASCII_z (0x60 + 26)
1513 extern int
1514 ascii_alpha_to_cntrl (int ch)
1516 if ((ch >= ASCII_A && ch <= ASCII_Z)
1517 || (ch >= ASCII_a && ch <= ASCII_z)) {
1518 ch &= 0x1f;
1520 return ch;
1523 const char *
1524 Q_ (const char *s)
1526 const char *result, *sep;
1528 result = _(s);
1529 sep = strchr(result, '|');
1530 return (sep != NULL) ? sep + 1 : result;
1534 gboolean
1535 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1537 struct stat stat_buf;
1538 char *backup_path;
1539 gboolean ret;
1540 if (!exist_file (file_name))
1541 return FALSE;
1543 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1545 if (backup_path == NULL)
1546 return FALSE;
1548 ret = mc_util_write_backup_content (file_name, backup_path);
1550 if (ret) {
1551 /* Backup file will have same ownership with main file. */
1552 if (stat (file_name, &stat_buf) == 0)
1553 chmod (backup_path, stat_buf.st_mode);
1554 else
1555 chmod (backup_path, S_IRUSR | S_IWUSR);
1558 g_free(backup_path);
1560 return ret;
1563 gboolean
1564 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1566 gboolean ret;
1567 char *backup_path;
1569 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1570 if (backup_path == NULL)
1571 return FALSE;
1573 ret = mc_util_write_backup_content (backup_path, file_name);
1574 g_free(backup_path);
1576 return ret;
1579 gboolean
1580 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1582 char *backup_path;
1584 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1585 if (backup_path == NULL)
1586 return FALSE;
1588 if (exist_file (backup_path))
1589 mc_unlink (backup_path);
1591 g_free(backup_path);
1592 return TRUE;
1595 /* partly taken from dcigettext.c, returns "" for default locale */
1596 /* value should be freed by calling function g_free() */
1597 char *guess_message_value (void)
1599 static const char * const var[] = {
1600 /* Setting of LC_ALL overwrites all other. */
1601 /* Do not use LANGUAGE for check user locale and drowing hints */
1602 "LC_ALL",
1603 /* Next comes the name of the desired category. */
1604 "LC_MESSAGES",
1605 /* Last possibility is the LANG environment variable. */
1606 "LANG",
1607 /* NULL exit loops */
1608 NULL
1611 unsigned i = 0;
1612 const char *locale = NULL;
1614 while (var[i] != NULL) {
1615 locale = getenv (var[i]);
1616 if (locale != NULL && locale[0] != '\0')
1617 break;
1618 i++;
1621 if (locale == NULL)
1622 locale = "";
1624 return g_strdup (locale);