Ticket #1897: Build breaks on ignored return values
[midnight-commander.git] / lib / util.c
blob77cc74384b3919b65a2c8d570a44423ca83d2283
1 /* Various utilities
2 Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
3 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
4 Written 1994, 1995, 1996 by:
5 Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
6 Jakub Jelinek, Mauricio Plaza.
8 The file_date routine is mostly from GNU's fileutils package,
9 written by Richard Stallman and David MacKenzie.
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
25 /** \file
26 * \brief Source: various utilities
29 #include <config.h>
31 #include <ctype.h>
32 #include <limits.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <fcntl.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
43 #include "lib/global.h"
44 #include "lib/tty/win.h" /* xterm_flag */
45 #include "lib/search.h"
46 #include "lib/mcconfig.h"
47 #include "lib/timefmt.h"
48 #include "lib/fileloc.h"
49 #include "lib/vfs/mc-vfs/vfs.h"
50 #include "lib/strutil.h"
52 #include "src/filegui.h"
53 #include "src/file.h" /* copy_file_file() */
54 #ifndef HAVE_CHARSET
55 #include "src/main.h" /* eight_bit_clean */
56 #endif
58 int easy_patterns = 1;
61 * If true, SI units (1000 based) will be used for
62 * larger units (kilobyte, megabyte, ...).
63 * If false binary units (1024 based) will be used.
65 int kilobyte_si = 0;
67 char *user_recent_timeformat = NULL; /* time format string for recent dates */
68 char *user_old_timeformat = NULL; /* time format string for older dates */
71 * Cache variable for the i18n_checktimelength function,
72 * initially set to a clearly invalid value to show that
73 * it hasn't been initialized yet.
75 static size_t i18n_timelength_cache = MAX_I18NTIMELENGTH + 1;
77 extern void
78 str_replace (char *s, char from, char to)
80 for (; *s != '\0'; s++)
82 if (*s == from)
83 *s = to;
87 static inline int
88 is_7bit_printable (unsigned char c)
90 return (c > 31 && c < 127);
93 static inline int
94 is_iso_printable (unsigned char c)
96 return ((c > 31 && c < 127) || c >= 160);
99 static inline int
100 is_8bit_printable (unsigned char c)
102 /* "Full 8 bits output" doesn't work on xterm */
103 if (xterm_flag)
104 return is_iso_printable (c);
106 return (c > 31 && c != 127 && c != 155);
110 is_printable (int c)
112 c &= 0xff;
114 #ifdef HAVE_CHARSET
115 /* "Display bits" is ignored, since the user controls the output
116 by setting the output codepage */
117 return is_8bit_printable (c);
118 #else
119 if (!eight_bit_clean)
120 return is_7bit_printable (c);
122 if (full_eight_bits)
124 return is_8bit_printable (c);
126 else
127 return is_iso_printable (c);
128 #endif /* !HAVE_CHARSET */
131 /* Calculates the message dimensions (lines and columns) */
132 void
133 msglen (const char *text, int *lines, int *columns)
135 int nlines = 1; /* even the empty string takes one line */
136 int ncolumns = 0;
137 int colindex = 0;
139 for (; *text != '\0'; text++)
141 if (*text == '\n')
143 nlines++;
144 colindex = 0;
146 else
148 colindex++;
149 if (colindex > ncolumns)
150 ncolumns = colindex;
154 *lines = nlines;
155 *columns = ncolumns;
159 * Copy from s to d, and trim the beginning if necessary, and prepend
160 * "..." in this case. The destination string can have at most len
161 * bytes, not counting trailing 0.
163 char *
164 trim (const char *s, char *d, int len)
166 int source_len;
168 /* Sanity check */
169 len = max (len, 0);
171 source_len = strlen (s);
172 if (source_len > len)
174 /* Cannot fit the whole line */
175 if (len <= 3)
177 /* We only have room for the dots */
178 memset (d, '.', len);
179 d[len] = 0;
180 return d;
182 else
184 /* Begin with ... and add the rest of the source string */
185 memset (d, '.', 3);
186 strcpy (d + 3, s + 3 + source_len - len);
189 else
190 /* We can copy the whole line */
191 strcpy (d, s);
192 return d;
196 * Quote the filename for the purpose of inserting it into the command
197 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
198 * processed by the mc command line.
200 char *
201 name_quote (const char *s, int quote_percent)
203 char *ret, *d;
205 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
206 if (*s == '-')
208 *d++ = '.';
209 *d++ = '/';
212 for (; *s; s++, d++)
214 switch (*s)
216 case '%':
217 if (quote_percent)
218 *d++ = '%';
219 break;
220 case '\'':
221 case '\\':
222 case '\r':
223 case '\n':
224 case '\t':
225 case '"':
226 case ';':
227 case ' ':
228 case '?':
229 case '|':
230 case '[':
231 case ']':
232 case '{':
233 case '}':
234 case '<':
235 case '>':
236 case '`':
237 case '!':
238 case '$':
239 case '&':
240 case '*':
241 case '(':
242 case ')':
243 *d++ = '\\';
244 break;
245 case '~':
246 case '#':
247 if (d == ret)
248 *d++ = '\\';
249 break;
251 *d = *s;
253 *d = '\0';
254 return ret;
257 char *
258 fake_name_quote (const char *s, int quote_percent)
260 (void) quote_percent;
261 return g_strdup (s);
265 * Remove the middle part of the string to fit given length.
266 * Use "~" to show where the string was truncated.
267 * Return static buffer, no need to free() it.
269 const char *
270 name_trunc (const char *txt, size_t trunc_len)
272 return str_trunc (txt, trunc_len);
276 * path_trunc() is the same as name_trunc() above but
277 * it deletes possible password from path for security
278 * reasons.
280 const char *
281 path_trunc (const char *path, size_t trunc_len)
283 char *secure_path = strip_password (g_strdup (path), 1);
285 const char *ret = str_trunc (secure_path, trunc_len);
286 g_free (secure_path);
288 return ret;
291 const char *
292 size_trunc (double size)
294 static char x[BUF_TINY];
295 long int divisor = 1;
296 const char *xtra = "";
298 if (size > 999999999L)
300 divisor = kilobyte_si ? 1000 : 1024;
301 xtra = kilobyte_si ? "k" : "K";
302 if (size / divisor > 999999999L)
304 divisor = kilobyte_si ? (1000 * 1000) : (1024 * 1024);
305 xtra = kilobyte_si ? "m" : "M";
308 g_snprintf (x, sizeof (x), "%.0f%s", (size / divisor), xtra);
309 return x;
312 const char *
313 size_trunc_sep (double size)
315 static char x[60];
316 int count;
317 const char *p, *y;
318 char *d;
320 p = y = size_trunc (size);
321 p += strlen (p) - 1;
322 d = x + sizeof (x) - 1;
323 *d-- = 0;
324 while (p >= y && isalpha ((unsigned char) *p))
325 *d-- = *p--;
326 for (count = 0; p >= y; count++)
328 if (count == 3)
330 *d-- = ',';
331 count = 0;
333 *d-- = *p--;
335 d++;
336 if (*d == ',')
337 d++;
338 return d;
342 * Print file SIZE to BUFFER, but don't exceed LEN characters,
343 * not including trailing 0. BUFFER should be at least LEN+1 long.
344 * This function is called for every file on panels, so avoid
345 * floating point by any means.
347 * Units: size units (filesystem sizes are 1K blocks)
348 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
350 void
351 size_trunc_len (char *buffer, unsigned int len, off_t size, int units)
353 /* Avoid taking power for every file. */
354 static const off_t power10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
355 1000000000
357 static const char *const suffix[] = { "", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL };
358 static const char *const suffix_lc[] = { "", "k", "m", "g", "t", "p", "e", "z", "y", NULL };
359 int j = 0;
360 int size_remain;
362 if (len == 0)
363 len = 9;
366 * recalculate from 1024 base to 1000 base if units>0
367 * We can't just multiply by 1024 - that might cause overflow
368 * if off_t type is too small
370 if (units && kilobyte_si)
372 for (j = 0; j < units; j++)
374 size_remain = ((size % 125) * 1024) / 1000; /* size mod 125, recalculated */
375 size = size / 125; /* 128/125 = 1024/1000 */
376 size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
377 size += size_remain; /* Re-add remainder lost by division/multiplication */
381 for (j = units; suffix[j] != NULL; j++)
383 if (size == 0)
385 if (j == units)
387 /* Empty files will print "0" even with minimal width. */
388 g_snprintf (buffer, len + 1, "0");
389 break;
392 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
393 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
394 (j > 1) ? (kilobyte_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
395 break;
398 if (size < power10[len - (j > 0)])
400 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size,
401 kilobyte_si ? suffix_lc[j] : suffix[j]);
402 break;
405 /* Powers of 1000 or 1024, with rounding. */
406 if (kilobyte_si)
408 size = (size + 500) / 1000;
410 else
412 size = (size + 512) >> 10;
418 is_exe (mode_t mode)
420 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
421 return 1;
422 return 0;
425 #define ismode(n,m) ((n & m) == m)
427 const char *
428 string_perm (mode_t mode_bits)
430 static char mode[11];
432 strcpy (mode, "----------");
433 if (S_ISDIR (mode_bits))
434 mode[0] = 'd';
435 if (S_ISCHR (mode_bits))
436 mode[0] = 'c';
437 if (S_ISBLK (mode_bits))
438 mode[0] = 'b';
439 if (S_ISLNK (mode_bits))
440 mode[0] = 'l';
441 if (S_ISFIFO (mode_bits))
442 mode[0] = 'p';
443 if (S_ISNAM (mode_bits))
444 mode[0] = 'n';
445 if (S_ISSOCK (mode_bits))
446 mode[0] = 's';
447 if (S_ISDOOR (mode_bits))
448 mode[0] = 'D';
449 if (ismode (mode_bits, S_IXOTH))
450 mode[9] = 'x';
451 if (ismode (mode_bits, S_IWOTH))
452 mode[8] = 'w';
453 if (ismode (mode_bits, S_IROTH))
454 mode[7] = 'r';
455 if (ismode (mode_bits, S_IXGRP))
456 mode[6] = 'x';
457 if (ismode (mode_bits, S_IWGRP))
458 mode[5] = 'w';
459 if (ismode (mode_bits, S_IRGRP))
460 mode[4] = 'r';
461 if (ismode (mode_bits, S_IXUSR))
462 mode[3] = 'x';
463 if (ismode (mode_bits, S_IWUSR))
464 mode[2] = 'w';
465 if (ismode (mode_bits, S_IRUSR))
466 mode[1] = 'r';
467 #ifdef S_ISUID
468 if (ismode (mode_bits, S_ISUID))
469 mode[3] = (mode[3] == 'x') ? 's' : 'S';
470 #endif /* S_ISUID */
471 #ifdef S_ISGID
472 if (ismode (mode_bits, S_ISGID))
473 mode[6] = (mode[6] == 'x') ? 's' : 'S';
474 #endif /* S_ISGID */
475 #ifdef S_ISVTX
476 if (ismode (mode_bits, S_ISVTX))
477 mode[9] = (mode[9] == 'x') ? 't' : 'T';
478 #endif /* S_ISVTX */
479 return mode;
482 /* p: string which might contain an url with a password (this parameter is
483 modified in place).
484 has_prefix = 0: The first parameter is an url without a prefix
485 (user[:pass]@]machine[:port][remote-dir). Delete
486 the password.
487 has_prefix = 1: Search p for known url prefixes. If found delete
488 the password from the url.
489 Caveat: only the first url is found
491 char *
492 strip_password (char *p, int has_prefix)
494 static const struct
496 const char *name;
497 size_t len;
498 } prefixes[] =
501 "/#ftp:", 6},
503 "ftp://", 6},
505 "/#mc:", 5},
507 "mc://", 5},
509 "/#smb:", 6},
511 "smb://", 6},
513 "/#sh:", 5},
515 "sh://", 5},
517 "ssh://", 6}
519 char *at, *inner_colon, *dir;
520 size_t i;
521 char *result = p;
523 for (i = 0; i < sizeof (prefixes) / sizeof (prefixes[0]); i++)
525 char *q;
527 if (has_prefix)
529 if ((q = strstr (p, prefixes[i].name)) == 0)
530 continue;
531 else
532 p = q + prefixes[i].len;
535 if ((dir = strchr (p, PATH_SEP)) != NULL)
536 *dir = '\0';
538 /* search for any possible user */
539 at = strrchr (p, '@');
541 if (dir)
542 *dir = PATH_SEP;
544 /* We have a username */
545 if (at)
547 inner_colon = memchr (p, ':', at - p);
548 if (inner_colon)
549 memmove (inner_colon, at, strlen (at) + 1);
551 break;
553 return (result);
556 const char *
557 strip_home_and_password (const char *dir)
559 size_t len;
560 static char newdir[MC_MAXPATHLEN];
562 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
563 (dir[len] == PATH_SEP || dir[len] == '\0'))
565 newdir[0] = '~';
566 g_strlcpy (&newdir[1], &dir[len], sizeof (newdir) - 1);
567 return newdir;
570 /* We do not strip homes in /#ftp tree, I do not like ~'s there
571 (see ftpfs.c why) */
572 g_strlcpy (newdir, dir, sizeof (newdir));
573 strip_password (newdir, 1);
574 return newdir;
577 const char *
578 extension (const char *filename)
580 const char *d = strrchr (filename, '.');
581 return (d != NULL) ? d + 1 : "";
585 exist_file (const char *name)
587 return access (name, R_OK) == 0;
591 check_for_default (const char *default_file, const char *file)
593 if (!exist_file (file))
595 FileOpContext *ctx;
596 FileOpTotalContext *tctx;
598 if (!exist_file (default_file))
599 return -1;
601 ctx = file_op_context_new (OP_COPY);
602 tctx = file_op_total_context_new ();
603 file_op_context_create_ui (ctx, 0, FALSE);
604 copy_file_file (tctx, ctx, default_file, file);
605 file_op_total_context_destroy (tctx);
606 file_op_context_destroy (ctx);
609 return 0;
614 char *
615 load_file (const char *filename)
617 FILE *data_file;
618 struct stat s;
619 char *data;
620 long read_size;
622 if ((data_file = fopen (filename, "r")) == NULL)
624 return 0;
626 if (fstat (fileno (data_file), &s) != 0)
628 fclose (data_file);
629 return 0;
631 data = g_malloc (s.st_size + 1);
632 read_size = fread (data, 1, s.st_size, data_file);
633 data[read_size] = 0;
634 fclose (data_file);
636 if (read_size > 0)
637 return data;
638 else
640 g_free (data);
641 return 0;
645 char *
646 load_mc_home_file (const char *_mc_home, const char *_mc_home_alt, const char *filename,
647 char **allocated_filename)
649 char *hintfile_base, *hintfile;
650 char *lang;
651 char *data;
653 hintfile_base = concat_dir_and_file (_mc_home, filename);
654 lang = guess_message_value ();
656 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
657 data = load_file (hintfile);
659 if (!data)
661 g_free (hintfile);
662 g_free (hintfile_base);
663 hintfile_base = concat_dir_and_file (_mc_home_alt, filename);
665 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
666 data = load_file (hintfile);
668 if (!data)
670 /* Fall back to the two-letter language code */
671 if (lang[0] && lang[1])
672 lang[2] = 0;
673 g_free (hintfile);
674 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
675 data = load_file (hintfile);
677 if (!data)
679 g_free (hintfile);
680 hintfile = hintfile_base;
681 data = load_file (hintfile_base);
686 g_free (lang);
688 if (hintfile != hintfile_base)
689 g_free (hintfile_base);
691 if (allocated_filename)
692 *allocated_filename = hintfile;
693 else
694 g_free (hintfile);
696 return data;
699 /* Check strftime() results. Some systems (i.e. Solaris) have different
700 short-month and month name sizes for different locales */
701 size_t
702 i18n_checktimelength (void)
704 size_t length = 0;
705 const time_t testtime = time (NULL);
706 struct tm *lt = localtime (&testtime);
708 if (i18n_timelength_cache <= MAX_I18NTIMELENGTH)
709 return i18n_timelength_cache;
711 if (lt == NULL)
713 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
714 length = str_term_width1 (_(INVALID_TIME_TEXT));
716 else
718 char buf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
720 /* We are interested in the longest possible date */
721 lt->tm_sec = lt->tm_min = lt->tm_hour = lt->tm_mday = 10;
723 /* Loop through all months to find out the longest one */
724 for (lt->tm_mon = 0; lt->tm_mon < 12; lt->tm_mon++) {
725 strftime (buf, sizeof(buf) - 1, user_recent_timeformat, lt);
726 length = max ((size_t) str_term_width1 (buf), length);
727 strftime (buf, sizeof(buf) - 1, user_old_timeformat, lt);
728 length = max ((size_t) str_term_width1 (buf), length);
731 length = max ((size_t) str_term_width1 (_(INVALID_TIME_TEXT)), length);
734 /* Don't handle big differences. Use standard value (email bug, please) */
735 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
736 length = STD_I18NTIMELENGTH;
738 /* Save obtained value to the cache */
739 i18n_timelength_cache = length;
741 return i18n_timelength_cache;
744 const char *
745 file_date (time_t when)
747 static char timebuf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
748 time_t current_time = time ((time_t) 0);
749 const char *fmt;
751 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
752 || current_time < when - 60L * 60L) /* In the future. */
753 /* The file is fairly old or in the future.
754 POSIX says the cutoff is 6 months old;
755 approximate this by 6*30 days.
756 Allow a 1 hour slop factor for what is considered "the future",
757 to allow for NFS server/client clock disagreement.
758 Show the year instead of the time of day. */
760 fmt = user_old_timeformat;
761 else
762 fmt = user_recent_timeformat;
764 FMT_LOCALTIME (timebuf, sizeof (timebuf), fmt, when);
766 return timebuf;
769 const char *
770 extract_line (const char *s, const char *top)
772 static char tmp_line[BUF_MEDIUM];
773 char *t = tmp_line;
775 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line) - 1 && s < top)
776 *t++ = *s++;
777 *t = 0;
778 return tmp_line;
781 /* The basename routine */
782 const char *
783 x_basename (const char *s)
785 const char *where;
786 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
790 const char *
791 unix_error_string (int error_num)
793 static char buffer[BUF_LARGE];
794 gchar *strerror_currentlocale;
796 strerror_currentlocale = g_locale_from_utf8 (g_strerror (error_num), -1, NULL, NULL, NULL);
797 g_snprintf (buffer, sizeof (buffer), "%s (%d)", strerror_currentlocale, error_num);
798 g_free (strerror_currentlocale);
800 return buffer;
803 const char *
804 skip_separators (const char *s)
806 const char *su = s;
808 for (; *su; str_cnext_char (&su))
809 if (*su != ' ' && *su != '\t' && *su != ',')
810 break;
812 return su;
815 const char *
816 skip_numbers (const char *s)
818 const char *su = s;
820 for (; *su; str_cnext_char (&su))
821 if (!str_isdigit (su))
822 break;
824 return su;
827 /* Remove all control sequences from the argument string. We define
828 * "control sequence", in a sort of pidgin BNF, as follows:
830 * control-seq = Esc non-'['
831 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
833 * This scheme works for all the terminals described in my termcap /
834 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
835 * terminals. If I hear from a single person who uses such a terminal
836 * with MC, I'll be glad to add support for it. (Dugan)
837 * Non-printable characters are also removed.
840 char *
841 strip_ctrl_codes (char *s)
843 char *w; /* Current position where the stripped data is written */
844 char *r; /* Current position where the original data is read */
845 char *n;
847 if (!s)
848 return 0;
850 for (w = s, r = s; *r;)
852 if (*r == ESC_CHAR)
854 /* Skip the control sequence's arguments */ ;
855 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
856 if (*(++r) == '[' || *r == '(')
858 /* strchr() matches trailing binary 0 */
859 while (*(++r) && strchr ("0123456789;?", *r));
861 else if (*r == ']')
864 * Skip xterm's OSC (Operating System Command)
865 * http://www.xfree86.org/current/ctlseqs.html
866 * OSC P s ; P t ST
867 * OSC P s ; P t BEL
869 char *new_r = r;
871 for (; *new_r; ++new_r)
873 switch (*new_r)
875 /* BEL */
876 case '\a':
877 r = new_r;
878 goto osc_out;
879 case ESC_CHAR:
880 /* ST */
881 if (*(new_r + 1) == '\\')
883 r = new_r + 1;
884 goto osc_out;
888 osc_out:;
892 * Now we are at the last character of the sequence.
893 * Skip it unless it's binary 0.
895 if (*r)
896 r++;
897 continue;
900 n = str_get_next_char (r);
901 if (str_isprint (r))
903 memmove (w, r, n - r);
904 w += n - r;
906 r = n;
908 *w = 0;
909 return s;
913 #ifndef ENABLE_VFS
914 char *
915 get_current_wd (char *buffer, int size)
917 char *p;
918 int len;
920 p = g_get_current_dir ();
921 len = strlen (p) + 1;
923 if (len > size)
925 g_free (p);
926 return NULL;
929 memcpy (buffer, p, len);
930 g_free (p);
932 return buffer;
934 #endif /* !ENABLE_VFS */
936 enum compression_type
937 get_compression_type (int fd, const char *name)
939 unsigned char magic[16];
940 size_t str_len;
942 /* Read the magic signature */
943 if (mc_read (fd, (char *) magic, 4) != 4)
944 return COMPRESSION_NONE;
946 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
947 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236))
949 return COMPRESSION_GZIP;
952 /* PKZIP_MAGIC */
953 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003 && magic[3] == 004)
955 /* Read compression type */
956 mc_lseek (fd, 8, SEEK_SET);
957 if (mc_read (fd, (char *) magic, 2) != 2)
958 return COMPRESSION_NONE;
960 /* Gzip can handle only deflated (8) or stored (0) files */
961 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
962 return COMPRESSION_NONE;
964 /* Compatible with gzip */
965 return COMPRESSION_GZIP;
968 /* PACK_MAGIC and LZH_MAGIC and compress magic */
969 if (magic[0] == 037 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235))
971 /* Compatible with gzip */
972 return COMPRESSION_GZIP;
975 /* BZIP and BZIP2 files */
976 if ((magic[0] == 'B') && (magic[1] == 'Z') && (magic[3] >= '1') && (magic[3] <= '9'))
978 switch (magic[2])
980 case '0':
981 return COMPRESSION_BZIP;
982 case 'h':
983 return COMPRESSION_BZIP2;
987 /* Support for LZMA (only utils format with magic in header).
988 * This is the default format of LZMA utils 4.32.1 and later. */
990 if (mc_read (fd, (char *) magic + 4, 2) != 2)
991 return COMPRESSION_NONE;
993 /* LZMA utils format */
994 if (magic[0] == 0xFF
995 && magic[1] == 'L'
996 && magic[2] == 'Z' && magic[3] == 'M' && magic[4] == 'A' && magic[5] == 0x00)
997 return COMPRESSION_LZMA;
999 /* XZ compression magic */
1000 if (magic[0] == 0xFD
1001 && magic[1] == 0x37
1002 && magic[2] == 0x7A && magic[3] == 0x58 && magic[4] == 0x5A && magic[5] == 0x00)
1003 return COMPRESSION_XZ;
1005 str_len = strlen (name);
1006 /* HACK: we must belive to extention of LZMA file :) ... */
1007 if ((str_len > 5 && strcmp (&name[str_len - 5], ".lzma") == 0) ||
1008 (str_len > 4 && strcmp (&name[str_len - 4], ".tlz") == 0))
1009 return COMPRESSION_LZMA;
1011 return COMPRESSION_NONE;
1014 const char *
1015 decompress_extension (int type)
1017 switch (type)
1019 case COMPRESSION_GZIP:
1020 return "#ugz";
1021 case COMPRESSION_BZIP:
1022 return "#ubz";
1023 case COMPRESSION_BZIP2:
1024 return "#ubz2";
1025 case COMPRESSION_LZMA:
1026 return "#ulzma";
1027 case COMPRESSION_XZ:
1028 return "#uxz";
1030 /* Should never reach this place */
1031 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
1032 return 0;
1035 /* Hooks */
1036 void
1037 add_hook (Hook ** hook_list, void (*hook_fn) (void *), void *data)
1039 Hook *new_hook = g_new (Hook, 1);
1041 new_hook->hook_fn = hook_fn;
1042 new_hook->next = *hook_list;
1043 new_hook->hook_data = data;
1045 *hook_list = new_hook;
1048 void
1049 execute_hooks (Hook * hook_list)
1051 Hook *new_hook = 0;
1052 Hook *p;
1054 /* We copy the hook list first so tahat we let the hook
1055 * function call delete_hook
1058 while (hook_list)
1060 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
1061 hook_list = hook_list->next;
1063 p = new_hook;
1065 while (new_hook)
1067 (*new_hook->hook_fn) (new_hook->hook_data);
1068 new_hook = new_hook->next;
1071 for (hook_list = p; hook_list;)
1073 p = hook_list;
1074 hook_list = hook_list->next;
1075 g_free (p);
1079 void
1080 delete_hook (Hook ** hook_list, void (*hook_fn) (void *))
1082 Hook *current, *new_list, *next;
1084 new_list = 0;
1086 for (current = *hook_list; current; current = next)
1088 next = current->next;
1089 if (current->hook_fn == hook_fn)
1090 g_free (current);
1091 else
1092 add_hook (&new_list, current->hook_fn, current->hook_data);
1094 *hook_list = new_list;
1098 hook_present (Hook * hook_list, void (*hook_fn) (void *))
1100 Hook *p;
1102 for (p = hook_list; p; p = p->next)
1103 if (p->hook_fn == hook_fn)
1104 return 1;
1105 return 0;
1108 void
1109 wipe_password (char *passwd)
1111 char *p = passwd;
1113 if (!p)
1114 return;
1115 for (; *p; p++)
1116 *p = 0;
1117 g_free (passwd);
1120 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1121 /* Returns a newly allocated string */
1122 char *
1123 convert_controls (const char *p)
1125 char *valcopy = g_strdup (p);
1126 char *q;
1128 /* Parse the escape special character */
1129 for (q = valcopy; *p;)
1131 if (*p == '\\')
1133 p++;
1134 if ((*p == 'e') || (*p == 'E'))
1136 p++;
1137 *q++ = ESC_CHAR;
1140 else
1142 if (*p == '^')
1144 p++;
1145 if (*p == '^')
1146 *q++ = *p++;
1147 else
1149 char c = (*p | 0x20);
1150 if (c >= 'a' && c <= 'z')
1152 *q++ = c - 'a' + 1;
1153 p++;
1155 else if (*p)
1156 p++;
1159 else
1160 *q++ = *p++;
1163 *q = 0;
1164 return valcopy;
1167 static char *
1168 resolve_symlinks (const char *path)
1170 char *buf, *buf2, *q, *r, c;
1171 int len;
1172 struct stat mybuf;
1173 const char *p;
1175 if (*path != PATH_SEP)
1176 return NULL;
1177 r = buf = g_malloc (MC_MAXPATHLEN);
1178 buf2 = g_malloc (MC_MAXPATHLEN);
1179 *r++ = PATH_SEP;
1180 *r = 0;
1181 p = path;
1182 for (;;)
1184 q = strchr (p + 1, PATH_SEP);
1185 if (!q)
1187 q = strchr (p + 1, 0);
1188 if (q == p + 1)
1189 break;
1191 c = *q;
1192 *q = 0;
1193 if (mc_lstat (path, &mybuf) < 0)
1195 g_free (buf);
1196 g_free (buf2);
1197 *q = c;
1198 return NULL;
1200 if (!S_ISLNK (mybuf.st_mode))
1201 strcpy (r, p + 1);
1202 else
1204 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1205 if (len < 0)
1207 g_free (buf);
1208 g_free (buf2);
1209 *q = c;
1210 return NULL;
1212 buf2[len] = 0;
1213 if (*buf2 == PATH_SEP)
1214 strcpy (buf, buf2);
1215 else
1216 strcpy (r, buf2);
1218 canonicalize_pathname (buf);
1219 r = strchr (buf, 0);
1220 if (!*r || *(r - 1) != PATH_SEP)
1222 *r++ = PATH_SEP;
1223 *r = 0;
1225 *q = c;
1226 p = q;
1227 if (!c)
1228 break;
1230 if (!*buf)
1231 strcpy (buf, PATH_SEP_STR);
1232 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1233 *(r - 1) = 0;
1234 g_free (buf2);
1235 return buf;
1238 static gboolean
1239 mc_util_write_backup_content (const char *from_file_name, const char *to_file_name)
1241 FILE *backup_fd;
1242 char *contents;
1243 gsize length;
1244 gboolean ret1 = TRUE;
1246 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1247 return FALSE;
1249 backup_fd = fopen (to_file_name, "w");
1250 if (backup_fd == NULL)
1252 g_free (contents);
1253 return FALSE;
1256 if (fwrite ((const void *) contents, length, 1, backup_fd) != length)
1257 ret1 = FALSE;
1259 int ret2;
1260 ret2 = fflush (backup_fd);
1261 ret2 = fclose (backup_fd);
1263 g_free (contents);
1264 return ret1;
1267 /* Finds out a relative path from first to second, i.e. goes as many ..
1268 * as needed up in first and then goes down using second */
1269 char *
1270 diff_two_paths (const char *first, const char *second)
1272 char *p, *q, *r, *s, *buf = NULL;
1273 int i, j, prevlen = -1, currlen;
1274 char *my_first = NULL, *my_second = NULL;
1276 my_first = resolve_symlinks (first);
1277 if (my_first == NULL)
1278 return NULL;
1279 my_second = resolve_symlinks (second);
1280 if (my_second == NULL)
1282 g_free (my_first);
1283 return NULL;
1285 for (j = 0; j < 2; j++)
1287 p = my_first;
1288 q = my_second;
1289 for (;;)
1291 r = strchr (p, PATH_SEP);
1292 s = strchr (q, PATH_SEP);
1293 if (!r || !s)
1294 break;
1295 *r = 0;
1296 *s = 0;
1297 if (strcmp (p, q))
1299 *r = PATH_SEP;
1300 *s = PATH_SEP;
1301 break;
1303 else
1305 *r = PATH_SEP;
1306 *s = PATH_SEP;
1308 p = r + 1;
1309 q = s + 1;
1311 p--;
1312 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1313 currlen = (i + 1) * 3 + strlen (q) + 1;
1314 if (j)
1316 if (currlen < prevlen)
1317 g_free (buf);
1318 else
1320 g_free (my_first);
1321 g_free (my_second);
1322 return buf;
1325 p = buf = g_malloc (currlen);
1326 prevlen = currlen;
1327 for (; i >= 0; i--, p += 3)
1328 strcpy (p, "../");
1329 strcpy (p, q);
1331 g_free (my_first);
1332 g_free (my_second);
1333 return buf;
1336 /* If filename is NULL, then we just append PATH_SEP to the dir */
1337 char *
1338 concat_dir_and_file (const char *dir, const char *file)
1340 int i = strlen (dir);
1342 if (dir[i - 1] == PATH_SEP)
1343 return g_strconcat (dir, file, (char *) NULL);
1344 else
1345 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1348 /* Append text to GList, remove all entries with the same text */
1349 GList *
1350 list_append_unique (GList * list, char *text)
1352 GList *lc_link;
1355 * Go to the last position and traverse the list backwards
1356 * starting from the second last entry to make sure that we
1357 * are not removing the current link.
1359 list = g_list_append (list, text);
1360 list = g_list_last (list);
1361 lc_link = g_list_previous (list);
1363 while (lc_link != NULL)
1365 GList *newlink;
1367 newlink = g_list_previous (lc_link);
1368 if (strcmp ((char *) lc_link->data, text) == 0)
1370 GList *tmp;
1372 g_free (lc_link->data);
1373 tmp = g_list_remove_link (list, lc_link);
1374 g_list_free_1 (lc_link);
1376 lc_link = newlink;
1379 return list;
1382 /* Following code heavily borrows from libiberty, mkstemps.c */
1384 /* Number of attempts to create a temporary file */
1385 #ifndef TMP_MAX
1386 #define TMP_MAX 16384
1387 #endif /* !TMP_MAX */
1390 * Arguments:
1391 * pname (output) - pointer to the name of the temp file (needs g_free).
1392 * NULL if the function fails.
1393 * prefix - part of the filename before the random part.
1394 * Prepend $TMPDIR or /tmp if there are no path separators.
1395 * suffix - if not NULL, part of the filename after the random part.
1397 * Result:
1398 * handle of the open file or -1 if couldn't open any.
1401 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1403 static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1404 static unsigned long value;
1405 struct timeval tv;
1406 char *tmpbase;
1407 char *tmpname;
1408 char *XXXXXX;
1409 int count;
1411 if (strchr (prefix, PATH_SEP) == NULL)
1413 /* Add prefix first to find the position of XXXXXX */
1414 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1416 else
1418 tmpbase = g_strdup (prefix);
1421 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1422 *pname = tmpname;
1423 XXXXXX = &tmpname[strlen (tmpbase)];
1424 g_free (tmpbase);
1426 /* Get some more or less random data. */
1427 gettimeofday (&tv, NULL);
1428 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1430 for (count = 0; count < TMP_MAX; ++count)
1432 unsigned long v = value;
1433 int fd;
1435 /* Fill in the random bits. */
1436 XXXXXX[0] = letters[v % 62];
1437 v /= 62;
1438 XXXXXX[1] = letters[v % 62];
1439 v /= 62;
1440 XXXXXX[2] = letters[v % 62];
1441 v /= 62;
1442 XXXXXX[3] = letters[v % 62];
1443 v /= 62;
1444 XXXXXX[4] = letters[v % 62];
1445 v /= 62;
1446 XXXXXX[5] = letters[v % 62];
1448 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, S_IRUSR | S_IWUSR);
1449 if (fd >= 0)
1451 /* Successfully created. */
1452 return fd;
1455 /* This is a random value. It is only necessary that the next
1456 TMP_MAX values generated by adding 7777 to VALUE are different
1457 with (module 2^32). */
1458 value += 7777;
1461 /* Unsuccessful. Free the filename. */
1462 g_free (tmpname);
1463 *pname = NULL;
1465 return -1;
1469 * Read and restore position for the given filename.
1470 * If there is no stored data, return line 1 and col 0.
1472 void
1473 load_file_position (const char *filename, long *line, long *column, off_t * offset)
1475 char *fn;
1476 FILE *f;
1477 char buf[MC_MAXPATHLEN + 20];
1478 int len;
1480 /* defaults */
1481 *line = 1;
1482 *column = 0;
1483 *offset = 0;
1485 /* open file with positions */
1486 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1487 f = fopen (fn, "r");
1488 g_free (fn);
1489 if (!f)
1490 return;
1492 len = strlen (filename);
1494 while (fgets (buf, sizeof (buf), f))
1496 const char *p;
1497 gchar **pos_tokens;
1499 /* check if the filename matches the beginning of string */
1500 if (strncmp (buf, filename, len) != 0)
1501 continue;
1503 /* followed by single space */
1504 if (buf[len] != ' ')
1505 continue;
1507 /* and string without spaces */
1508 p = &buf[len + 1];
1509 if (strchr (p, ' '))
1510 continue;
1512 pos_tokens = g_strsplit_set (p, ";", 3);
1513 if (pos_tokens[0] != NULL)
1515 *line = strtol (pos_tokens[0], NULL, 10);
1516 if (pos_tokens[1] != NULL)
1518 *column = strtol (pos_tokens[1], NULL, 10);
1519 if (pos_tokens[2] != NULL)
1520 *offset = strtoll (pos_tokens[2], NULL, 10);
1521 else
1522 *offset = 0;
1524 else
1526 *column = 0;
1527 *offset = 0;
1530 else
1532 *line = 1;
1533 *column = 0;
1534 *offset = 0;
1536 g_strfreev (pos_tokens);
1538 fclose (f);
1541 /* Save position for the given file */
1542 #define TMP_SUFFIX ".tmp"
1543 void
1544 save_file_position (const char *filename, long line, long column, off_t offset)
1546 static int filepos_max_saved_entries = 0;
1547 char *fn, *tmp_fn;
1548 FILE *f, *tmp_f;
1549 char buf[MC_MAXPATHLEN + 20];
1550 int i = 1;
1551 gsize len;
1553 if (filepos_max_saved_entries == 0)
1554 filepos_max_saved_entries =
1555 mc_config_get_int (mc_main_config, CONFIG_APP_SECTION, "filepos_max_saved_entries",
1556 1024);
1558 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1559 if (fn == NULL)
1560 goto early_error;
1562 len = strlen (filename);
1564 mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
1566 /* open file */
1567 f = fopen (fn, "w");
1568 if (f == NULL)
1569 goto open_target_error;
1571 tmp_fn = g_strdup_printf ("%s" TMP_SUFFIX, fn);
1572 tmp_f = fopen (tmp_fn, "r");
1573 if (tmp_f == NULL)
1574 goto open_source_error;
1576 /* put the new record */
1577 if (line != 1 || column != 0)
1579 if (fprintf (f, "%s %ld;%ld;%llu\n", filename, line, column, (unsigned long long) offset) <
1581 goto write_position_error;
1584 while (fgets (buf, sizeof (buf), tmp_f))
1586 if (buf[len] == ' ' && strncmp (buf, filename, len) == 0 && !strchr (&buf[len + 1], ' '))
1587 continue;
1589 fprintf (f, "%s", buf);
1590 if (++i > filepos_max_saved_entries)
1591 break;
1593 fclose (tmp_f);
1594 g_free (tmp_fn);
1595 fclose (f);
1596 mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
1597 g_free (fn);
1598 return;
1600 write_position_error:
1601 fclose (tmp_f);
1602 open_source_error:
1603 g_free (tmp_fn);
1604 fclose (f);
1605 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1606 open_target_error:
1607 g_free (fn);
1608 early_error:
1609 return;
1612 #undef TMP_SUFFIX
1613 extern const char *
1614 cstrcasestr (const char *haystack, const char *needle)
1616 char *nee = str_create_search_needle (needle, 0);
1617 const char *result = str_search_first (haystack, nee, 0);
1618 str_release_search_needle (nee, 0);
1619 return result;
1622 const char *
1623 cstrstr (const char *haystack, const char *needle)
1625 return strstr (haystack, needle);
1628 extern char *
1629 str_unconst (const char *s)
1631 return (char *) s;
1634 #define ASCII_A (0x40 + 1)
1635 #define ASCII_Z (0x40 + 26)
1636 #define ASCII_a (0x60 + 1)
1637 #define ASCII_z (0x60 + 26)
1639 extern int
1640 ascii_alpha_to_cntrl (int ch)
1642 if ((ch >= ASCII_A && ch <= ASCII_Z) || (ch >= ASCII_a && ch <= ASCII_z))
1644 ch &= 0x1f;
1646 return ch;
1649 const char *
1650 Q_ (const char *s)
1652 const char *result, *sep;
1654 result = _(s);
1655 sep = strchr (result, '|');
1656 return (sep != NULL) ? sep + 1 : result;
1660 gboolean
1661 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1663 struct stat stat_buf;
1664 char *backup_path;
1665 gboolean ret;
1666 if (!exist_file (file_name))
1667 return FALSE;
1669 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1671 if (backup_path == NULL)
1672 return FALSE;
1674 ret = mc_util_write_backup_content (file_name, backup_path);
1676 if (ret)
1678 /* Backup file will have same ownership with main file. */
1679 if (stat (file_name, &stat_buf) == 0)
1680 chmod (backup_path, stat_buf.st_mode);
1681 else
1682 chmod (backup_path, S_IRUSR | S_IWUSR);
1685 g_free (backup_path);
1687 return ret;
1690 gboolean
1691 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1693 gboolean ret;
1694 char *backup_path;
1696 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1697 if (backup_path == NULL)
1698 return FALSE;
1700 ret = mc_util_write_backup_content (backup_path, file_name);
1701 g_free (backup_path);
1703 return ret;
1706 gboolean
1707 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1709 char *backup_path;
1711 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1712 if (backup_path == NULL)
1713 return FALSE;
1715 if (exist_file (backup_path))
1716 mc_unlink (backup_path);
1718 g_free (backup_path);
1719 return TRUE;
1722 /* partly taken from dcigettext.c, returns "" for default locale */
1723 /* value should be freed by calling function g_free() */
1724 char *
1725 guess_message_value (void)
1727 static const char *const var[] = {
1728 /* Setting of LC_ALL overwrites all other. */
1729 /* Do not use LANGUAGE for check user locale and drowing hints */
1730 "LC_ALL",
1731 /* Next comes the name of the desired category. */
1732 "LC_MESSAGES",
1733 /* Last possibility is the LANG environment variable. */
1734 "LANG",
1735 /* NULL exit loops */
1736 NULL
1739 unsigned i = 0;
1740 const char *locale = NULL;
1742 while (var[i] != NULL)
1744 locale = getenv (var[i]);
1745 if (locale != NULL && locale[0] != '\0')
1746 break;
1747 i++;
1750 if (locale == NULL)
1751 locale = "";
1753 return g_strdup (locale);