Optimization of mcview_hexedit_save_changes() function.
[kaloumi3.git] / lib / util.c
blob26d1e6885d2747bf56ef5c2a4c76fe23e79010f7
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
71 str_replace (char *s, char from, char to)
73 for (; *s != '\0'; s++)
75 if (*s == from)
76 *s = to;
80 static inline int
81 is_7bit_printable (unsigned char c)
83 return (c > 31 && c < 127);
86 static inline int
87 is_iso_printable (unsigned char c)
89 return ((c > 31 && c < 127) || c >= 160);
92 static inline int
93 is_8bit_printable (unsigned char c)
95 /* "Full 8 bits output" doesn't work on xterm */
96 if (xterm_flag)
97 return is_iso_printable (c);
99 return (c > 31 && c != 127 && c != 155);
103 is_printable (int c)
105 c &= 0xff;
107 #ifdef HAVE_CHARSET
108 /* "Display bits" is ignored, since the user controls the output
109 by setting the output codepage */
110 return is_8bit_printable (c);
111 #else
112 if (!eight_bit_clean)
113 return is_7bit_printable (c);
115 if (full_eight_bits)
117 return is_8bit_printable (c);
119 else
120 return is_iso_printable (c);
121 #endif /* !HAVE_CHARSET */
124 /* Calculates the message dimensions (lines and columns) */
125 void
126 msglen (const char *text, int *lines, int *columns)
128 int nlines = 1; /* even the empty string takes one line */
129 int ncolumns = 0;
130 int colindex = 0;
132 for (; *text != '\0'; text++)
134 if (*text == '\n')
136 nlines++;
137 colindex = 0;
139 else
141 colindex++;
142 if (colindex > ncolumns)
143 ncolumns = colindex;
147 *lines = nlines;
148 *columns = ncolumns;
152 * Copy from s to d, and trim the beginning if necessary, and prepend
153 * "..." in this case. The destination string can have at most len
154 * bytes, not counting trailing 0.
156 char *
157 trim (const char *s, char *d, int len)
159 int source_len;
161 /* Sanity check */
162 len = max (len, 0);
164 source_len = strlen (s);
165 if (source_len > len)
167 /* Cannot fit the whole line */
168 if (len <= 3)
170 /* We only have room for the dots */
171 memset (d, '.', len);
172 d[len] = 0;
173 return d;
175 else
177 /* Begin with ... and add the rest of the source string */
178 memset (d, '.', 3);
179 strcpy (d + 3, s + 3 + source_len - len);
182 else
183 /* We can copy the whole line */
184 strcpy (d, s);
185 return d;
189 * Quote the filename for the purpose of inserting it into the command
190 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
191 * processed by the mc command line.
193 char *
194 name_quote (const char *s, int quote_percent)
196 char *ret, *d;
198 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
199 if (*s == '-')
201 *d++ = '.';
202 *d++ = '/';
205 for (; *s; s++, d++)
207 switch (*s)
209 case '%':
210 if (quote_percent)
211 *d++ = '%';
212 break;
213 case '\'':
214 case '\\':
215 case '\r':
216 case '\n':
217 case '\t':
218 case '"':
219 case ';':
220 case ' ':
221 case '?':
222 case '|':
223 case '[':
224 case ']':
225 case '{':
226 case '}':
227 case '<':
228 case '>':
229 case '`':
230 case '!':
231 case '$':
232 case '&':
233 case '*':
234 case '(':
235 case ')':
236 *d++ = '\\';
237 break;
238 case '~':
239 case '#':
240 if (d == ret)
241 *d++ = '\\';
242 break;
244 *d = *s;
246 *d = '\0';
247 return ret;
250 char *
251 fake_name_quote (const char *s, int quote_percent)
253 (void) quote_percent;
254 return g_strdup (s);
258 * Remove the middle part of the string to fit given length.
259 * Use "~" to show where the string was truncated.
260 * Return static buffer, no need to free() it.
262 const char *
263 name_trunc (const char *txt, size_t trunc_len)
265 return str_trunc (txt, trunc_len);
269 * path_trunc() is the same as name_trunc() above but
270 * it deletes possible password from path for security
271 * reasons.
273 const char *
274 path_trunc (const char *path, size_t trunc_len)
276 char *secure_path = strip_password (g_strdup (path), 1);
278 const char *ret = str_trunc (secure_path, trunc_len);
279 g_free (secure_path);
281 return ret;
284 const char *
285 size_trunc (double size)
287 static char x[BUF_TINY];
288 long int divisor = 1;
289 const char *xtra = "";
291 if (size > 999999999L)
293 divisor = kilobyte_si ? 1000 : 1024;
294 xtra = kilobyte_si ? "k" : "K";
295 if (size / divisor > 999999999L)
297 divisor = kilobyte_si ? (1000 * 1000) : (1024 * 1024);
298 xtra = kilobyte_si ? "m" : "M";
301 g_snprintf (x, sizeof (x), "%.0f%s", (size / divisor), xtra);
302 return x;
305 const char *
306 size_trunc_sep (double size)
308 static char x[60];
309 int count;
310 const char *p, *y;
311 char *d;
313 p = y = size_trunc (size);
314 p += strlen (p) - 1;
315 d = x + sizeof (x) - 1;
316 *d-- = 0;
317 while (p >= y && isalpha ((unsigned char) *p))
318 *d-- = *p--;
319 for (count = 0; p >= y; count++)
321 if (count == 3)
323 *d-- = ',';
324 count = 0;
326 *d-- = *p--;
328 d++;
329 if (*d == ',')
330 d++;
331 return d;
335 * Print file SIZE to BUFFER, but don't exceed LEN characters,
336 * not including trailing 0. BUFFER should be at least LEN+1 long.
337 * This function is called for every file on panels, so avoid
338 * floating point by any means.
340 * Units: size units (filesystem sizes are 1K blocks)
341 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
343 void
344 size_trunc_len (char *buffer, unsigned int len, off_t size, int units)
346 /* Avoid taking power for every file. */
347 static const off_t power10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
348 1000000000
350 static const char *const suffix[] = { "", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL };
351 static const char *const suffix_lc[] = { "", "k", "m", "g", "t", "p", "e", "z", "y", NULL };
352 int j = 0;
353 int size_remain;
355 if (len == 0)
356 len = 9;
359 * recalculate from 1024 base to 1000 base if units>0
360 * We can't just multiply by 1024 - that might cause overflow
361 * if off_t type is too small
363 if (units && kilobyte_si)
365 for (j = 0; j < units; j++)
367 size_remain = ((size % 125) * 1024) / 1000; /* size mod 125, recalculated */
368 size = size / 125; /* 128/125 = 1024/1000 */
369 size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
370 size += size_remain; /* Re-add remainder lost by division/multiplication */
374 for (j = units; suffix[j] != NULL; j++)
376 if (size == 0)
378 if (j == units)
380 /* Empty files will print "0" even with minimal width. */
381 g_snprintf (buffer, len + 1, "0");
382 break;
385 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
386 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
387 (j > 1) ? (kilobyte_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
388 break;
391 if (size < power10[len - (j > 0)])
393 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size,
394 kilobyte_si ? suffix_lc[j] : suffix[j]);
395 break;
398 /* Powers of 1000 or 1024, with rounding. */
399 if (kilobyte_si)
401 size = (size + 500) / 1000;
403 else
405 size = (size + 512) >> 10;
411 is_exe (mode_t mode)
413 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
414 return 1;
415 return 0;
418 #define ismode(n,m) ((n & m) == m)
420 const char *
421 string_perm (mode_t mode_bits)
423 static char mode[11];
425 strcpy (mode, "----------");
426 if (S_ISDIR (mode_bits))
427 mode[0] = 'd';
428 if (S_ISCHR (mode_bits))
429 mode[0] = 'c';
430 if (S_ISBLK (mode_bits))
431 mode[0] = 'b';
432 if (S_ISLNK (mode_bits))
433 mode[0] = 'l';
434 if (S_ISFIFO (mode_bits))
435 mode[0] = 'p';
436 if (S_ISNAM (mode_bits))
437 mode[0] = 'n';
438 if (S_ISSOCK (mode_bits))
439 mode[0] = 's';
440 if (S_ISDOOR (mode_bits))
441 mode[0] = 'D';
442 if (ismode (mode_bits, S_IXOTH))
443 mode[9] = 'x';
444 if (ismode (mode_bits, S_IWOTH))
445 mode[8] = 'w';
446 if (ismode (mode_bits, S_IROTH))
447 mode[7] = 'r';
448 if (ismode (mode_bits, S_IXGRP))
449 mode[6] = 'x';
450 if (ismode (mode_bits, S_IWGRP))
451 mode[5] = 'w';
452 if (ismode (mode_bits, S_IRGRP))
453 mode[4] = 'r';
454 if (ismode (mode_bits, S_IXUSR))
455 mode[3] = 'x';
456 if (ismode (mode_bits, S_IWUSR))
457 mode[2] = 'w';
458 if (ismode (mode_bits, S_IRUSR))
459 mode[1] = 'r';
460 #ifdef S_ISUID
461 if (ismode (mode_bits, S_ISUID))
462 mode[3] = (mode[3] == 'x') ? 's' : 'S';
463 #endif /* S_ISUID */
464 #ifdef S_ISGID
465 if (ismode (mode_bits, S_ISGID))
466 mode[6] = (mode[6] == 'x') ? 's' : 'S';
467 #endif /* S_ISGID */
468 #ifdef S_ISVTX
469 if (ismode (mode_bits, S_ISVTX))
470 mode[9] = (mode[9] == 'x') ? 't' : 'T';
471 #endif /* S_ISVTX */
472 return mode;
475 /* p: string which might contain an url with a password (this parameter is
476 modified in place).
477 has_prefix = 0: The first parameter is an url without a prefix
478 (user[:pass]@]machine[:port][remote-dir). Delete
479 the password.
480 has_prefix = 1: Search p for known url prefixes. If found delete
481 the password from the url.
482 Caveat: only the first url is found
484 char *
485 strip_password (char *p, int has_prefix)
487 static const struct
489 const char *name;
490 size_t len;
491 } prefixes[] =
494 "/#ftp:", 6},
496 "ftp://", 6},
498 "/#mc:", 5},
500 "mc://", 5},
502 "/#smb:", 6},
504 "smb://", 6},
506 "/#sh:", 5},
508 "sh://", 5},
510 "ssh://", 6}
512 char *at, *inner_colon, *dir;
513 size_t i;
514 char *result = p;
516 for (i = 0; i < sizeof (prefixes) / sizeof (prefixes[0]); i++)
518 char *q;
520 if (has_prefix)
522 if ((q = strstr (p, prefixes[i].name)) == 0)
523 continue;
524 else
525 p = q + prefixes[i].len;
528 if ((dir = strchr (p, PATH_SEP)) != NULL)
529 *dir = '\0';
531 /* search for any possible user */
532 at = strrchr (p, '@');
534 if (dir)
535 *dir = PATH_SEP;
537 /* We have a username */
538 if (at)
540 inner_colon = memchr (p, ':', at - p);
541 if (inner_colon)
542 memmove (inner_colon, at, strlen (at) + 1);
544 break;
546 return (result);
549 const char *
550 strip_home_and_password (const char *dir)
552 size_t len;
553 static char newdir[MC_MAXPATHLEN];
555 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
556 (dir[len] == PATH_SEP || dir[len] == '\0'))
558 newdir[0] = '~';
559 g_strlcpy (&newdir[1], &dir[len], sizeof (newdir) - 1);
560 return newdir;
563 /* We do not strip homes in /#ftp tree, I do not like ~'s there
564 (see ftpfs.c why) */
565 g_strlcpy (newdir, dir, sizeof (newdir));
566 strip_password (newdir, 1);
567 return newdir;
570 const char *
571 extension (const char *filename)
573 const char *d = strrchr (filename, '.');
574 return (d != NULL) ? d + 1 : "";
578 exist_file (const char *name)
580 return access (name, R_OK) == 0;
584 check_for_default (const char *default_file, const char *file)
586 if (!exist_file (file))
588 FileOpContext *ctx;
589 FileOpTotalContext *tctx;
591 if (!exist_file (default_file))
592 return -1;
594 ctx = file_op_context_new (OP_COPY);
595 tctx = file_op_total_context_new ();
596 file_op_context_create_ui (ctx, 0, FALSE);
597 copy_file_file (tctx, ctx, default_file, file);
598 file_op_total_context_destroy (tctx);
599 file_op_context_destroy (ctx);
602 return 0;
607 char *
608 load_file (const char *filename)
610 FILE *data_file;
611 struct stat s;
612 char *data;
613 long read_size;
615 if ((data_file = fopen (filename, "r")) == NULL)
617 return 0;
619 if (fstat (fileno (data_file), &s) != 0)
621 fclose (data_file);
622 return 0;
624 data = g_malloc (s.st_size + 1);
625 read_size = fread (data, 1, s.st_size, data_file);
626 data[read_size] = 0;
627 fclose (data_file);
629 if (read_size > 0)
630 return data;
631 else
633 g_free (data);
634 return 0;
638 char *
639 load_mc_home_file (const char *_mc_home, const char *_mc_home_alt, const char *filename,
640 char **allocated_filename)
642 char *hintfile_base, *hintfile;
643 char *lang;
644 char *data;
646 hintfile_base = concat_dir_and_file (_mc_home, filename);
647 lang = guess_message_value ();
649 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
650 data = load_file (hintfile);
652 if (!data)
654 g_free (hintfile);
655 g_free (hintfile_base);
656 hintfile_base = concat_dir_and_file (_mc_home_alt, filename);
658 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
659 data = load_file (hintfile);
661 if (!data)
663 /* Fall back to the two-letter language code */
664 if (lang[0] && lang[1])
665 lang[2] = 0;
666 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
667 data = load_file (hintfile);
669 if (!data)
671 g_free (hintfile);
672 hintfile = hintfile_base;
673 data = load_file (hintfile_base);
678 g_free (lang);
680 if (hintfile != hintfile_base)
681 g_free (hintfile_base);
683 if (allocated_filename)
684 *allocated_filename = hintfile;
685 else
686 g_free (hintfile);
688 return data;
691 /* Check strftime() results. Some systems (i.e. Solaris) have different
692 short-month-name sizes for different locales */
693 size_t
694 i18n_checktimelength (void)
696 size_t length;
697 time_t testtime = time (NULL);
698 struct tm *lt = localtime (&testtime);
700 if (lt == NULL)
702 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
703 length = str_term_width1 (_(INVALID_TIME_TEXT));
705 else
707 char buf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
708 size_t a, b;
710 strftime (buf, sizeof (buf) - 1, user_recent_timeformat, lt);
711 a = str_term_width1 (buf);
712 strftime (buf, sizeof (buf) - 1, user_old_timeformat, lt);
713 b = str_term_width1 (buf);
715 length = max (a, b);
716 length = max ((size_t) str_term_width1 (_(INVALID_TIME_TEXT)), length);
719 /* Don't handle big differences. Use standard value (email bug, please) */
720 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
721 length = STD_I18NTIMELENGTH;
723 return length;
726 const char *
727 file_date (time_t when)
729 static char timebuf[MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
730 time_t current_time = time ((time_t) 0);
731 const char *fmt;
733 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
734 || current_time < when - 60L * 60L) /* In the future. */
735 /* The file is fairly old or in the future.
736 POSIX says the cutoff is 6 months old;
737 approximate this by 6*30 days.
738 Allow a 1 hour slop factor for what is considered "the future",
739 to allow for NFS server/client clock disagreement.
740 Show the year instead of the time of day. */
742 fmt = user_old_timeformat;
743 else
744 fmt = user_recent_timeformat;
746 FMT_LOCALTIME (timebuf, sizeof (timebuf), fmt, when);
748 return timebuf;
751 const char *
752 extract_line (const char *s, const char *top)
754 static char tmp_line[BUF_MEDIUM];
755 char *t = tmp_line;
757 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line) - 1 && s < top)
758 *t++ = *s++;
759 *t = 0;
760 return tmp_line;
763 /* The basename routine */
764 const char *
765 x_basename (const char *s)
767 const char *where;
768 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
772 const char *
773 unix_error_string (int error_num)
775 static char buffer[BUF_LARGE];
776 gchar *strerror_currentlocale;
778 strerror_currentlocale = g_locale_from_utf8 (g_strerror (error_num), -1, NULL, NULL, NULL);
779 g_snprintf (buffer, sizeof (buffer), "%s (%d)", strerror_currentlocale, error_num);
780 g_free (strerror_currentlocale);
782 return buffer;
785 const char *
786 skip_separators (const char *s)
788 const char *su = s;
790 for (; *su; str_cnext_char (&su))
791 if (*su != ' ' && *su != '\t' && *su != ',')
792 break;
794 return su;
797 const char *
798 skip_numbers (const char *s)
800 const char *su = s;
802 for (; *su; str_cnext_char (&su))
803 if (!str_isdigit (su))
804 break;
806 return su;
809 /* Remove all control sequences from the argument string. We define
810 * "control sequence", in a sort of pidgin BNF, as follows:
812 * control-seq = Esc non-'['
813 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
815 * This scheme works for all the terminals described in my termcap /
816 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
817 * terminals. If I hear from a single person who uses such a terminal
818 * with MC, I'll be glad to add support for it. (Dugan)
819 * Non-printable characters are also removed.
822 char *
823 strip_ctrl_codes (char *s)
825 char *w; /* Current position where the stripped data is written */
826 char *r; /* Current position where the original data is read */
827 char *n;
829 if (!s)
830 return 0;
832 for (w = s, r = s; *r;)
834 if (*r == ESC_CHAR)
836 /* Skip the control sequence's arguments */ ;
837 /* '(' need to avoid strange 'B' letter in *Suse (if mc runs under root user) */
838 if (*(++r) == '[' || *r == '(')
840 /* strchr() matches trailing binary 0 */
841 while (*(++r) && strchr ("0123456789;?", *r));
843 else if (*r == ']')
846 * Skip xterm's OSC (Operating System Command)
847 * http://www.xfree86.org/current/ctlseqs.html
848 * OSC P s ; P t ST
849 * OSC P s ; P t BEL
851 char *new_r = r;
853 for (; *new_r; ++new_r)
855 switch (*new_r)
857 /* BEL */
858 case '\a':
859 r = new_r;
860 goto osc_out;
861 case ESC_CHAR:
862 /* ST */
863 if (*(new_r + 1) == '\\')
865 r = new_r + 1;
866 goto osc_out;
870 osc_out:;
874 * Now we are at the last character of the sequence.
875 * Skip it unless it's binary 0.
877 if (*r)
878 r++;
879 continue;
882 n = str_get_next_char (r);
883 if (str_isprint (r))
885 memmove (w, r, n - r);
886 w += n - r;
888 r = n;
890 *w = 0;
891 return s;
895 #ifndef ENABLE_VFS
896 char *
897 get_current_wd (char *buffer, int size)
899 char *p;
900 int len;
902 p = g_get_current_dir ();
903 len = strlen (p) + 1;
905 if (len > size)
907 g_free (p);
908 return NULL;
911 memcpy (buffer, p, len);
912 g_free (p);
914 return buffer;
916 #endif /* !ENABLE_VFS */
918 enum compression_type
919 get_compression_type (int fd, const char *name)
921 unsigned char magic[16];
922 size_t str_len;
924 /* Read the magic signature */
925 if (mc_read (fd, (char *) magic, 4) != 4)
926 return COMPRESSION_NONE;
928 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
929 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236))
931 return COMPRESSION_GZIP;
934 /* PKZIP_MAGIC */
935 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003 && magic[3] == 004)
937 /* Read compression type */
938 mc_lseek (fd, 8, SEEK_SET);
939 if (mc_read (fd, (char *) magic, 2) != 2)
940 return COMPRESSION_NONE;
942 /* Gzip can handle only deflated (8) or stored (0) files */
943 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
944 return COMPRESSION_NONE;
946 /* Compatible with gzip */
947 return COMPRESSION_GZIP;
950 /* PACK_MAGIC and LZH_MAGIC and compress magic */
951 if (magic[0] == 037 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235))
953 /* Compatible with gzip */
954 return COMPRESSION_GZIP;
957 /* BZIP and BZIP2 files */
958 if ((magic[0] == 'B') && (magic[1] == 'Z') && (magic[3] >= '1') && (magic[3] <= '9'))
960 switch (magic[2])
962 case '0':
963 return COMPRESSION_BZIP;
964 case 'h':
965 return COMPRESSION_BZIP2;
969 /* Support for LZMA (only utils format with magic in header).
970 * This is the default format of LZMA utils 4.32.1 and later. */
972 if (mc_read (fd, (char *) magic + 4, 2) != 2)
973 return COMPRESSION_NONE;
975 /* LZMA utils format */
976 if (magic[0] == 0xFF
977 && magic[1] == 'L'
978 && magic[2] == 'Z' && magic[3] == 'M' && magic[4] == 'A' && magic[5] == 0x00)
979 return COMPRESSION_LZMA;
981 /* XZ compression magic */
982 if (magic[0] == 0xFD
983 && magic[1] == 0x37
984 && magic[2] == 0x7A && magic[3] == 0x58 && magic[4] == 0x5A && magic[5] == 0x00)
985 return COMPRESSION_XZ;
987 str_len = strlen (name);
988 /* HACK: we must belive to extention of LZMA file :) ... */
989 if ((str_len > 5 && strcmp (&name[str_len - 5], ".lzma") == 0) ||
990 (str_len > 4 && strcmp (&name[str_len - 4], ".tlz") == 0))
991 return COMPRESSION_LZMA;
993 return COMPRESSION_NONE;
996 const char *
997 decompress_extension (int type)
999 switch (type)
1001 case COMPRESSION_GZIP:
1002 return "#ugz";
1003 case COMPRESSION_BZIP:
1004 return "#ubz";
1005 case COMPRESSION_BZIP2:
1006 return "#ubz2";
1007 case COMPRESSION_LZMA:
1008 return "#ulzma";
1009 case COMPRESSION_XZ:
1010 return "#uxz";
1012 /* Should never reach this place */
1013 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
1014 return 0;
1017 /* Hooks */
1018 void
1019 add_hook (Hook ** hook_list, void (*hook_fn) (void *), void *data)
1021 Hook *new_hook = g_new (Hook, 1);
1023 new_hook->hook_fn = hook_fn;
1024 new_hook->next = *hook_list;
1025 new_hook->hook_data = data;
1027 *hook_list = new_hook;
1030 void
1031 execute_hooks (Hook * hook_list)
1033 Hook *new_hook = 0;
1034 Hook *p;
1036 /* We copy the hook list first so tahat we let the hook
1037 * function call delete_hook
1040 while (hook_list)
1042 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
1043 hook_list = hook_list->next;
1045 p = new_hook;
1047 while (new_hook)
1049 (*new_hook->hook_fn) (new_hook->hook_data);
1050 new_hook = new_hook->next;
1053 for (hook_list = p; hook_list;)
1055 p = hook_list;
1056 hook_list = hook_list->next;
1057 g_free (p);
1061 void
1062 delete_hook (Hook ** hook_list, void (*hook_fn) (void *))
1064 Hook *current, *new_list, *next;
1066 new_list = 0;
1068 for (current = *hook_list; current; current = next)
1070 next = current->next;
1071 if (current->hook_fn == hook_fn)
1072 g_free (current);
1073 else
1074 add_hook (&new_list, current->hook_fn, current->hook_data);
1076 *hook_list = new_list;
1080 hook_present (Hook * hook_list, void (*hook_fn) (void *))
1082 Hook *p;
1084 for (p = hook_list; p; p = p->next)
1085 if (p->hook_fn == hook_fn)
1086 return 1;
1087 return 0;
1090 void
1091 wipe_password (char *passwd)
1093 char *p = passwd;
1095 if (!p)
1096 return;
1097 for (; *p; p++)
1098 *p = 0;
1099 g_free (passwd);
1102 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1103 /* Returns a newly allocated string */
1104 char *
1105 convert_controls (const char *p)
1107 char *valcopy = g_strdup (p);
1108 char *q;
1110 /* Parse the escape special character */
1111 for (q = valcopy; *p;)
1113 if (*p == '\\')
1115 p++;
1116 if ((*p == 'e') || (*p == 'E'))
1118 p++;
1119 *q++ = ESC_CHAR;
1122 else
1124 if (*p == '^')
1126 p++;
1127 if (*p == '^')
1128 *q++ = *p++;
1129 else
1131 char c = (*p | 0x20);
1132 if (c >= 'a' && c <= 'z')
1134 *q++ = c - 'a' + 1;
1135 p++;
1137 else if (*p)
1138 p++;
1141 else
1142 *q++ = *p++;
1145 *q = 0;
1146 return valcopy;
1149 static char *
1150 resolve_symlinks (const char *path)
1152 char *buf, *buf2, *q, *r, c;
1153 int len;
1154 struct stat mybuf;
1155 const char *p;
1157 if (*path != PATH_SEP)
1158 return NULL;
1159 r = buf = g_malloc (MC_MAXPATHLEN);
1160 buf2 = g_malloc (MC_MAXPATHLEN);
1161 *r++ = PATH_SEP;
1162 *r = 0;
1163 p = path;
1164 for (;;)
1166 q = strchr (p + 1, PATH_SEP);
1167 if (!q)
1169 q = strchr (p + 1, 0);
1170 if (q == p + 1)
1171 break;
1173 c = *q;
1174 *q = 0;
1175 if (mc_lstat (path, &mybuf) < 0)
1177 g_free (buf);
1178 g_free (buf2);
1179 *q = c;
1180 return NULL;
1182 if (!S_ISLNK (mybuf.st_mode))
1183 strcpy (r, p + 1);
1184 else
1186 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1187 if (len < 0)
1189 g_free (buf);
1190 g_free (buf2);
1191 *q = c;
1192 return NULL;
1194 buf2[len] = 0;
1195 if (*buf2 == PATH_SEP)
1196 strcpy (buf, buf2);
1197 else
1198 strcpy (r, buf2);
1200 canonicalize_pathname (buf);
1201 r = strchr (buf, 0);
1202 if (!*r || *(r - 1) != PATH_SEP)
1204 *r++ = PATH_SEP;
1205 *r = 0;
1207 *q = c;
1208 p = q;
1209 if (!c)
1210 break;
1212 if (!*buf)
1213 strcpy (buf, PATH_SEP_STR);
1214 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1215 *(r - 1) = 0;
1216 g_free (buf2);
1217 return buf;
1220 static gboolean
1221 mc_util_write_backup_content (const char *from_file_name, const char *to_file_name)
1223 FILE *backup_fd;
1224 char *contents;
1225 gsize length;
1227 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1228 return FALSE;
1230 backup_fd = fopen (to_file_name, "w");
1231 if (backup_fd == NULL)
1233 g_free (contents);
1234 return FALSE;
1237 fwrite ((const void *) contents, length, 1, backup_fd);
1239 fflush (backup_fd);
1240 fclose (backup_fd);
1241 g_free (contents);
1242 return TRUE;
1245 /* Finds out a relative path from first to second, i.e. goes as many ..
1246 * as needed up in first and then goes down using second */
1247 char *
1248 diff_two_paths (const char *first, const char *second)
1250 char *p, *q, *r, *s, *buf = NULL;
1251 int i, j, prevlen = -1, currlen;
1252 char *my_first = NULL, *my_second = NULL;
1254 my_first = resolve_symlinks (first);
1255 if (my_first == NULL)
1256 return NULL;
1257 my_second = resolve_symlinks (second);
1258 if (my_second == NULL)
1260 g_free (my_first);
1261 return NULL;
1263 for (j = 0; j < 2; j++)
1265 p = my_first;
1266 q = my_second;
1267 for (;;)
1269 r = strchr (p, PATH_SEP);
1270 s = strchr (q, PATH_SEP);
1271 if (!r || !s)
1272 break;
1273 *r = 0;
1274 *s = 0;
1275 if (strcmp (p, q))
1277 *r = PATH_SEP;
1278 *s = PATH_SEP;
1279 break;
1281 else
1283 *r = PATH_SEP;
1284 *s = PATH_SEP;
1286 p = r + 1;
1287 q = s + 1;
1289 p--;
1290 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1291 currlen = (i + 1) * 3 + strlen (q) + 1;
1292 if (j)
1294 if (currlen < prevlen)
1295 g_free (buf);
1296 else
1298 g_free (my_first);
1299 g_free (my_second);
1300 return buf;
1303 p = buf = g_malloc (currlen);
1304 prevlen = currlen;
1305 for (; i >= 0; i--, p += 3)
1306 strcpy (p, "../");
1307 strcpy (p, q);
1309 g_free (my_first);
1310 g_free (my_second);
1311 return buf;
1314 /* If filename is NULL, then we just append PATH_SEP to the dir */
1315 char *
1316 concat_dir_and_file (const char *dir, const char *file)
1318 int i = strlen (dir);
1320 if (dir[i - 1] == PATH_SEP)
1321 return g_strconcat (dir, file, (char *) NULL);
1322 else
1323 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1326 /* Append text to GList, remove all entries with the same text */
1327 GList *
1328 list_append_unique (GList * list, char *text)
1330 GList *lc_link;
1333 * Go to the last position and traverse the list backwards
1334 * starting from the second last entry to make sure that we
1335 * are not removing the current link.
1337 list = g_list_append (list, text);
1338 list = g_list_last (list);
1339 lc_link = g_list_previous (list);
1341 while (lc_link != NULL)
1343 GList *newlink;
1345 newlink = g_list_previous (lc_link);
1346 if (strcmp ((char *) lc_link->data, text) == 0)
1348 GList *tmp;
1350 g_free (lc_link->data);
1351 tmp = g_list_remove_link (list, lc_link);
1352 g_list_free_1 (lc_link);
1354 lc_link = newlink;
1357 return list;
1360 /* Following code heavily borrows from libiberty, mkstemps.c */
1362 /* Number of attempts to create a temporary file */
1363 #ifndef TMP_MAX
1364 #define TMP_MAX 16384
1365 #endif /* !TMP_MAX */
1368 * Arguments:
1369 * pname (output) - pointer to the name of the temp file (needs g_free).
1370 * NULL if the function fails.
1371 * prefix - part of the filename before the random part.
1372 * Prepend $TMPDIR or /tmp if there are no path separators.
1373 * suffix - if not NULL, part of the filename after the random part.
1375 * Result:
1376 * handle of the open file or -1 if couldn't open any.
1379 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1381 static const char letters[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1382 static unsigned long value;
1383 struct timeval tv;
1384 char *tmpbase;
1385 char *tmpname;
1386 char *XXXXXX;
1387 int count;
1389 if (strchr (prefix, PATH_SEP) == NULL)
1391 /* Add prefix first to find the position of XXXXXX */
1392 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1394 else
1396 tmpbase = g_strdup (prefix);
1399 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1400 *pname = tmpname;
1401 XXXXXX = &tmpname[strlen (tmpbase)];
1402 g_free (tmpbase);
1404 /* Get some more or less random data. */
1405 gettimeofday (&tv, NULL);
1406 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1408 for (count = 0; count < TMP_MAX; ++count)
1410 unsigned long v = value;
1411 int fd;
1413 /* Fill in the random bits. */
1414 XXXXXX[0] = letters[v % 62];
1415 v /= 62;
1416 XXXXXX[1] = letters[v % 62];
1417 v /= 62;
1418 XXXXXX[2] = letters[v % 62];
1419 v /= 62;
1420 XXXXXX[3] = letters[v % 62];
1421 v /= 62;
1422 XXXXXX[4] = letters[v % 62];
1423 v /= 62;
1424 XXXXXX[5] = letters[v % 62];
1426 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, S_IRUSR | S_IWUSR);
1427 if (fd >= 0)
1429 /* Successfully created. */
1430 return fd;
1433 /* This is a random value. It is only necessary that the next
1434 TMP_MAX values generated by adding 7777 to VALUE are different
1435 with (module 2^32). */
1436 value += 7777;
1439 /* Unsuccessful. Free the filename. */
1440 g_free (tmpname);
1441 *pname = NULL;
1443 return -1;
1447 * Read and restore position for the given filename.
1448 * If there is no stored data, return line 1 and col 0.
1450 void
1451 load_file_position (const char *filename, long *line, long *column, off_t * offset)
1453 char *fn;
1454 FILE *f;
1455 char buf[MC_MAXPATHLEN + 20];
1456 int len;
1458 /* defaults */
1459 *line = 1;
1460 *column = 0;
1461 *offset = 0;
1463 /* open file with positions */
1464 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1465 f = fopen (fn, "r");
1466 g_free (fn);
1467 if (!f)
1468 return;
1470 len = strlen (filename);
1472 while (fgets (buf, sizeof (buf), f))
1474 const char *p;
1475 gchar **pos_tokens;
1477 /* check if the filename matches the beginning of string */
1478 if (strncmp (buf, filename, len) != 0)
1479 continue;
1481 /* followed by single space */
1482 if (buf[len] != ' ')
1483 continue;
1485 /* and string without spaces */
1486 p = &buf[len + 1];
1487 if (strchr (p, ' '))
1488 continue;
1490 pos_tokens = g_strsplit_set (p, ";", 3);
1491 if (pos_tokens[0] != NULL)
1493 *line = strtol (pos_tokens[0], NULL, 10);
1494 if (pos_tokens[1] != NULL)
1496 *column = strtol (pos_tokens[1], NULL, 10);
1497 if (pos_tokens[2] != NULL)
1498 *offset = strtoll (pos_tokens[2], NULL, 10);
1499 else
1500 *offset = 0;
1502 else
1504 *column = 0;
1505 *offset = 0;
1508 else
1510 *line = 1;
1511 *column = 0;
1512 *offset = 0;
1514 g_strfreev (pos_tokens);
1516 fclose (f);
1519 /* Save position for the given file */
1520 #define TMP_SUFFIX ".tmp"
1521 void
1522 save_file_position (const char *filename, long line, long column, off_t offset)
1524 static int filepos_max_saved_entries = 0;
1525 char *fn, *tmp_fn;
1526 FILE *f, *tmp_f;
1527 char buf[MC_MAXPATHLEN + 20];
1528 int i = 1;
1529 gsize len;
1531 if (filepos_max_saved_entries == 0)
1532 filepos_max_saved_entries =
1533 mc_config_get_int (mc_main_config, CONFIG_APP_SECTION, "filepos_max_saved_entries",
1534 1024);
1536 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1537 if (fn == NULL)
1538 goto early_error;
1540 len = strlen (filename);
1542 mc_util_make_backup_if_possible (fn, TMP_SUFFIX);
1544 /* open file */
1545 f = fopen (fn, "w");
1546 if (f == NULL)
1547 goto open_target_error;
1549 tmp_fn = g_strdup_printf ("%s" TMP_SUFFIX, fn);
1550 tmp_f = fopen (tmp_fn, "r");
1551 if (tmp_f == NULL)
1552 goto open_source_error;
1554 /* put the new record */
1555 if (line != 1 || column != 0)
1557 if (fprintf (f, "%s %ld;%ld;%llu\n", filename, line, column, (unsigned long long) offset) <
1559 goto write_position_error;
1562 while (fgets (buf, sizeof (buf), tmp_f))
1564 if (buf[len] == ' ' && strncmp (buf, filename, len) == 0 && !strchr (&buf[len + 1], ' '))
1565 continue;
1567 fprintf (f, "%s", buf);
1568 if (++i > filepos_max_saved_entries)
1569 break;
1571 fclose (tmp_f);
1572 g_free (tmp_fn);
1573 fclose (f);
1574 mc_util_unlink_backup_if_possible (fn, TMP_SUFFIX);
1575 g_free (fn);
1576 return;
1578 write_position_error:
1579 fclose (tmp_f);
1580 open_source_error:
1581 g_free (tmp_fn);
1582 fclose (f);
1583 mc_util_restore_from_backup_if_possible (fn, TMP_SUFFIX);
1584 open_target_error:
1585 g_free (fn);
1586 early_error:
1587 return;
1590 #undef TMP_SUFFIX
1591 extern const char *
1592 cstrcasestr (const char *haystack, const char *needle)
1594 char *nee = str_create_search_needle (needle, 0);
1595 const char *result = str_search_first (haystack, nee, 0);
1596 str_release_search_needle (nee, 0);
1597 return result;
1600 const char *
1601 cstrstr (const char *haystack, const char *needle)
1603 return strstr (haystack, needle);
1606 extern char *
1607 str_unconst (const char *s)
1609 return (char *) s;
1612 #define ASCII_A (0x40 + 1)
1613 #define ASCII_Z (0x40 + 26)
1614 #define ASCII_a (0x60 + 1)
1615 #define ASCII_z (0x60 + 26)
1617 extern int
1618 ascii_alpha_to_cntrl (int ch)
1620 if ((ch >= ASCII_A && ch <= ASCII_Z) || (ch >= ASCII_a && ch <= ASCII_z))
1622 ch &= 0x1f;
1624 return ch;
1627 const char *
1628 Q_ (const char *s)
1630 const char *result, *sep;
1632 result = _(s);
1633 sep = strchr (result, '|');
1634 return (sep != NULL) ? sep + 1 : result;
1638 gboolean
1639 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1641 struct stat stat_buf;
1642 char *backup_path;
1643 gboolean ret;
1644 if (!exist_file (file_name))
1645 return FALSE;
1647 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1649 if (backup_path == NULL)
1650 return FALSE;
1652 ret = mc_util_write_backup_content (file_name, backup_path);
1654 if (ret)
1656 /* Backup file will have same ownership with main file. */
1657 if (stat (file_name, &stat_buf) == 0)
1658 chmod (backup_path, stat_buf.st_mode);
1659 else
1660 chmod (backup_path, S_IRUSR | S_IWUSR);
1663 g_free (backup_path);
1665 return ret;
1668 gboolean
1669 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1671 gboolean ret;
1672 char *backup_path;
1674 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1675 if (backup_path == NULL)
1676 return FALSE;
1678 ret = mc_util_write_backup_content (backup_path, file_name);
1679 g_free (backup_path);
1681 return ret;
1684 gboolean
1685 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1687 char *backup_path;
1689 backup_path = g_strdup_printf ("%s%s", file_name, backup_suffix);
1690 if (backup_path == NULL)
1691 return FALSE;
1693 if (exist_file (backup_path))
1694 mc_unlink (backup_path);
1696 g_free (backup_path);
1697 return TRUE;
1700 /* partly taken from dcigettext.c, returns "" for default locale */
1701 /* value should be freed by calling function g_free() */
1702 char *
1703 guess_message_value (void)
1705 static const char *const var[] = {
1706 /* Setting of LC_ALL overwrites all other. */
1707 /* Do not use LANGUAGE for check user locale and drowing hints */
1708 "LC_ALL",
1709 /* Next comes the name of the desired category. */
1710 "LC_MESSAGES",
1711 /* Last possibility is the LANG environment variable. */
1712 "LANG",
1713 /* NULL exit loops */
1714 NULL
1717 unsigned i = 0;
1718 const char *locale = NULL;
1720 while (var[i] != NULL)
1722 locale = getenv (var[i]);
1723 if (locale != NULL && locale[0] != '\0')
1724 break;
1725 i++;
1728 if (locale == NULL)
1729 locale = "";
1731 return g_strdup (locale);