Merge branch '1680_exit_on_non_local_vfs'
[midnight-commander.git] / src / util.c
blob66ffd894dcbeac32c08d995d6aca278874067c55
1 /* Various utilities
2 Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
3 2004, 2005, 2007, 2009 Free Software Foundation, Inc.
4 Written 1994, 1995, 1996 by:
5 Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
6 Jakub Jelinek, Mauricio Plaza.
8 The file_date routine is mostly from GNU's fileutils package,
9 written by Richard Stallman and David MacKenzie.
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
25 /** \file
26 * \brief Source: various utilities
29 #include <config.h>
31 #include <ctype.h>
32 #include <limits.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <fcntl.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
43 #include "global.h"
45 #include "../src/tty/win.h" /* xterm_flag */
47 #include "../src/search/search.h"
49 #include "main.h" /* mc_home */
50 #include "cmd.h" /* guess_message_value */
51 #include "mountlist.h"
52 #include "timefmt.h"
53 #include "strutil.h"
54 #include "fileopctx.h"
55 #include "file.h" /* copy_file_file() */
56 #include "dir.h"
57 #include "fileloc.h"
59 #ifdef HAVE_CHARSET
60 #include "charsets.h"
61 #endif
63 /*In order to use everywhere the same setup
64 for the locale we use defines */
65 #define FMTYEAR _("%b %e %Y")
66 #define FMTTIME _("%b %e %H:%M")
69 int easy_patterns = 1;
71 extern void str_replace(char *s, char from, char to)
73 for (; *s != '\0'; s++) {
74 if (*s == from)
75 *s = to;
79 static inline int
80 is_7bit_printable (unsigned char c)
82 return (c > 31 && c < 127);
85 static inline int
86 is_iso_printable (unsigned char c)
88 return ((c > 31 && c < 127) || c >= 160);
91 static inline int
92 is_8bit_printable (unsigned char c)
94 /* "Full 8 bits output" doesn't work on xterm */
95 if (xterm_flag)
96 return is_iso_printable (c);
98 return (c > 31 && c != 127 && c != 155);
102 is_printable (int c)
104 c &= 0xff;
106 #ifdef HAVE_CHARSET
107 /* "Display bits" is ignored, since the user controls the output
108 by setting the output codepage */
109 return is_8bit_printable (c);
110 #else
111 if (!eight_bit_clean)
112 return is_7bit_printable (c);
114 if (full_eight_bits) {
115 return is_8bit_printable (c);
116 } else
117 return is_iso_printable (c);
118 #endif /* !HAVE_CHARSET */
121 /* Calculates the message dimensions (lines and columns) */
122 void
123 msglen (const char *text, int *lines, int *columns)
125 int nlines = 1; /* even the empty string takes one line */
126 int ncolumns = 0;
127 int colindex = 0;
129 for (; *text != '\0'; text++) {
130 if (*text == '\n') {
131 nlines++;
132 colindex = 0;
133 } else {
134 colindex++;
135 if (colindex > ncolumns)
136 ncolumns = colindex;
140 *lines = nlines;
141 *columns = ncolumns;
145 * Copy from s to d, and trim the beginning if necessary, and prepend
146 * "..." in this case. The destination string can have at most len
147 * bytes, not counting trailing 0.
149 char *
150 trim (const char *s, char *d, int len)
152 int source_len;
154 /* Sanity check */
155 len = max (len, 0);
157 source_len = strlen (s);
158 if (source_len > len) {
159 /* Cannot fit the whole line */
160 if (len <= 3) {
161 /* We only have room for the dots */
162 memset (d, '.', len);
163 d[len] = 0;
164 return d;
165 } else {
166 /* Begin with ... and add the rest of the source string */
167 memset (d, '.', 3);
168 strcpy (d + 3, s + 3 + source_len - len);
170 } else
171 /* We can copy the whole line */
172 strcpy (d, s);
173 return d;
177 * Quote the filename for the purpose of inserting it into the command
178 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
179 * processed by the mc command line.
181 char *
182 name_quote (const char *s, int quote_percent)
184 char *ret, *d;
186 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
187 if (*s == '-') {
188 *d++ = '.';
189 *d++ = '/';
192 for (; *s; s++, d++) {
193 switch (*s) {
194 case '%':
195 if (quote_percent)
196 *d++ = '%';
197 break;
198 case '\'':
199 case '\\':
200 case '\r':
201 case '\n':
202 case '\t':
203 case '"':
204 case ';':
205 case ' ':
206 case '?':
207 case '|':
208 case '[':
209 case ']':
210 case '{':
211 case '}':
212 case '<':
213 case '>':
214 case '`':
215 case '!':
216 case '$':
217 case '&':
218 case '*':
219 case '(':
220 case ')':
221 *d++ = '\\';
222 break;
223 case '~':
224 case '#':
225 if (d == ret)
226 *d++ = '\\';
227 break;
229 *d = *s;
231 *d = '\0';
232 return ret;
235 char *
236 fake_name_quote (const char *s, int quote_percent)
238 (void) quote_percent;
239 return g_strdup (s);
243 * Remove the middle part of the string to fit given length.
244 * Use "~" to show where the string was truncated.
245 * Return static buffer, no need to free() it.
247 const char *
248 name_trunc (const char *txt, size_t trunc_len)
250 return str_trunc (txt, trunc_len);
254 * path_trunc() is the same as name_trunc() above but
255 * it deletes possible password from path for security
256 * reasons.
258 const char *
259 path_trunc (const char *path, size_t trunc_len) {
260 char *secure_path = strip_password (g_strdup (path), 1);
262 const char *ret = str_trunc (secure_path, trunc_len);
263 g_free (secure_path);
265 return ret;
268 const char *
269 size_trunc (double size)
271 static char x [BUF_TINY];
272 long int divisor = 1;
273 const char *xtra = "";
275 if (size > 999999999L){
276 divisor = kilobyte_si?1000:1024;
277 xtra = kilobyte_si?"k":"K";
278 if (size/divisor > 999999999L){
279 divisor = kilobyte_si?(1000*1000):(1024*1024);
280 xtra = kilobyte_si?"m":"M";
283 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
284 return x;
287 const char *
288 size_trunc_sep (double size)
290 static char x [60];
291 int count;
292 const char *p, *y;
293 char *d;
295 p = y = size_trunc (size);
296 p += strlen (p) - 1;
297 d = x + sizeof (x) - 1;
298 *d-- = 0;
299 while (p >= y && isalpha ((unsigned char) *p))
300 *d-- = *p--;
301 for (count = 0; p >= y; count++){
302 if (count == 3){
303 *d-- = ',';
304 count = 0;
306 *d-- = *p--;
308 d++;
309 if (*d == ',')
310 d++;
311 return d;
315 * Print file SIZE to BUFFER, but don't exceed LEN characters,
316 * not including trailing 0. BUFFER should be at least LEN+1 long.
317 * This function is called for every file on panels, so avoid
318 * floating point by any means.
320 * Units: size units (filesystem sizes are 1K blocks)
321 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
323 void
324 size_trunc_len (char *buffer, unsigned int len, off_t size, int units)
326 /* Avoid taking power for every file. */
327 static const off_t power10 [] =
328 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
329 1000000000};
330 static const char * const suffix [] =
331 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
332 static const char * const suffix_lc [] =
333 {"", "k", "m", "g", "t", "p", "e", "z", "y", NULL};
334 int j = 0;
335 int size_remain;
337 if (len == 0)
338 len = 9;
341 * recalculate from 1024 base to 1000 base if units>0
342 * We can't just multiply by 1024 - that might cause overflow
343 * if off_t type is too small
345 if (units && kilobyte_si) {
346 for (j = 0; j < units; j++) {
347 size_remain=((size % 125)*1024)/1000; /* size mod 125, recalculated */
348 size = size / 125; /* 128/125 = 1024/1000 */
349 size = size * 128; /* This will convert size from multiple of 1024 to multiple of 1000 */
350 size += size_remain; /* Re-add remainder lost by division/multiplication */
354 for (j = units; suffix [j] != NULL; j++) {
355 if (size == 0) {
356 if (j == units) {
357 /* Empty files will print "0" even with minimal width. */
358 g_snprintf (buffer, len + 1, "0");
359 break;
362 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
363 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
364 (j > 1) ? (kilobyte_si ? suffix_lc[j - 1] : suffix[j - 1]) : "B");
365 break;
368 if (size < power10 [len - (j > 0)]) {
369 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, kilobyte_si ? suffix_lc[j] : suffix[j]);
370 break;
373 /* Powers of 1000 or 1024, with rounding. */
374 if (kilobyte_si) {
375 size = (size + 500) / 1000;
376 } else {
377 size = (size + 512) >> 10;
383 is_exe (mode_t mode)
385 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
386 return 1;
387 return 0;
390 #define ismode(n,m) ((n & m) == m)
392 const char *
393 string_perm (mode_t mode_bits)
395 static char mode[11];
397 strcpy (mode, "----------");
398 if (S_ISDIR (mode_bits))
399 mode[0] = 'd';
400 if (S_ISCHR (mode_bits))
401 mode[0] = 'c';
402 if (S_ISBLK (mode_bits))
403 mode[0] = 'b';
404 if (S_ISLNK (mode_bits))
405 mode[0] = 'l';
406 if (S_ISFIFO (mode_bits))
407 mode[0] = 'p';
408 if (S_ISNAM (mode_bits))
409 mode[0] = 'n';
410 if (S_ISSOCK (mode_bits))
411 mode[0] = 's';
412 if (S_ISDOOR (mode_bits))
413 mode[0] = 'D';
414 if (ismode (mode_bits, S_IXOTH))
415 mode[9] = 'x';
416 if (ismode (mode_bits, S_IWOTH))
417 mode[8] = 'w';
418 if (ismode (mode_bits, S_IROTH))
419 mode[7] = 'r';
420 if (ismode (mode_bits, S_IXGRP))
421 mode[6] = 'x';
422 if (ismode (mode_bits, S_IWGRP))
423 mode[5] = 'w';
424 if (ismode (mode_bits, S_IRGRP))
425 mode[4] = 'r';
426 if (ismode (mode_bits, S_IXUSR))
427 mode[3] = 'x';
428 if (ismode (mode_bits, S_IWUSR))
429 mode[2] = 'w';
430 if (ismode (mode_bits, S_IRUSR))
431 mode[1] = 'r';
432 #ifdef S_ISUID
433 if (ismode (mode_bits, S_ISUID))
434 mode[3] = (mode[3] == 'x') ? 's' : 'S';
435 #endif /* S_ISUID */
436 #ifdef S_ISGID
437 if (ismode (mode_bits, S_ISGID))
438 mode[6] = (mode[6] == 'x') ? 's' : 'S';
439 #endif /* S_ISGID */
440 #ifdef S_ISVTX
441 if (ismode (mode_bits, S_ISVTX))
442 mode[9] = (mode[9] == 'x') ? 't' : 'T';
443 #endif /* S_ISVTX */
444 return mode;
447 /* p: string which might contain an url with a password (this parameter is
448 modified in place).
449 has_prefix = 0: The first parameter is an url without a prefix
450 (user[:pass]@]machine[:port][remote-dir). Delete
451 the password.
452 has_prefix = 1: Search p for known url prefixes. If found delete
453 the password from the url.
454 Caveat: only the first url is found
456 char *
457 strip_password (char *p, int has_prefix)
459 static const struct {
460 const char *name;
461 size_t len;
462 } prefixes[] = { {"/#ftp:", 6},
463 {"ftp://", 6},
464 {"/#mc:", 5},
465 {"mc://", 5},
466 {"/#smb:", 6},
467 {"smb://", 6},
468 {"/#sh:", 5},
469 {"sh://", 5},
470 {"ssh://", 6}
472 char *at, *inner_colon, *dir;
473 size_t i;
474 char *result = p;
476 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
477 char *q;
479 if (has_prefix) {
480 if((q = strstr (p, prefixes[i].name)) == 0)
481 continue;
482 else
483 p = q + prefixes[i].len;
486 if ((dir = strchr (p, PATH_SEP)) != NULL)
487 *dir = '\0';
489 /* search for any possible user */
490 at = strrchr (p, '@');
492 if (dir)
493 *dir = PATH_SEP;
495 /* We have a username */
496 if (at) {
497 inner_colon = memchr (p, ':', at - p);
498 if (inner_colon)
499 memmove (inner_colon, at, strlen(at) + 1);
501 break;
503 return (result);
506 const char *
507 strip_home_and_password(const char *dir)
509 size_t len;
510 static char newdir [MC_MAXPATHLEN];
512 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
513 (dir[len] == PATH_SEP || dir[len] == '\0')){
514 newdir [0] = '~';
515 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
516 return newdir;
519 /* We do not strip homes in /#ftp tree, I do not like ~'s there
520 (see ftpfs.c why) */
521 g_strlcpy (newdir, dir, sizeof(newdir));
522 strip_password (newdir, 1);
523 return newdir;
526 const char *
527 extension (const char *filename)
529 const char *d = strrchr (filename, '.');
530 return (d != NULL) ? d + 1 : "";
534 exist_file (const char *name)
536 return access (name, R_OK) == 0;
540 check_for_default (const char *default_file, const char *file)
542 if (!exist_file (file)) {
543 FileOpContext *ctx;
544 off_t count = 0;
545 double bytes = 0.0;
547 if (!exist_file (default_file))
548 return -1;
550 ctx = file_op_context_new (OP_COPY);
551 file_op_context_create_ui (ctx, 0);
552 copy_file_file (ctx, default_file, file, 1, &count, &bytes, 1);
553 file_op_context_destroy (ctx);
556 return 0;
561 char *
562 load_file (const char *filename)
564 FILE *data_file;
565 struct stat s;
566 char *data;
567 long read_size;
569 if ((data_file = fopen (filename, "r")) == NULL){
570 return 0;
572 if (fstat (fileno (data_file), &s) != 0){
573 fclose (data_file);
574 return 0;
576 data = g_malloc (s.st_size+1);
577 read_size = fread (data, 1, s.st_size, data_file);
578 data [read_size] = 0;
579 fclose (data_file);
581 if (read_size > 0)
582 return data;
583 else {
584 g_free (data);
585 return 0;
589 char *
590 load_mc_home_file (const char *filename, char **allocated_filename)
592 char *hintfile_base, *hintfile;
593 char *lang;
594 char *data;
596 hintfile_base = concat_dir_and_file (mc_home, filename);
597 lang = guess_message_value ();
599 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
600 data = load_file (hintfile);
602 if (!data) {
603 g_free (hintfile);
604 g_free (hintfile_base);
605 hintfile_base = concat_dir_and_file (mc_home_alt, filename);
607 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
608 data = load_file (hintfile);
610 if (!data) {
611 /* Fall back to the two-letter language code */
612 if (lang[0] && lang[1])
613 lang[2] = 0;
614 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
615 data = load_file (hintfile);
617 if (!data) {
618 g_free (hintfile);
619 hintfile = hintfile_base;
620 data = load_file (hintfile_base);
625 g_free (lang);
627 if (hintfile != hintfile_base)
628 g_free (hintfile_base);
630 if (allocated_filename)
631 *allocated_filename = hintfile;
632 else
633 g_free (hintfile);
635 return data;
638 /* Check strftime() results. Some systems (i.e. Solaris) have different
639 short-month-name sizes for different locales */
640 size_t
641 i18n_checktimelength (void)
643 size_t length;
644 time_t testtime = time (NULL);
645 struct tm* lt = localtime(&testtime);
647 if (lt == NULL) {
648 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
649 length = str_term_width1 (_(INVALID_TIME_TEXT));
650 } else {
651 char buf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
652 size_t a, b;
654 strftime (buf, sizeof(buf) - 1, FMTTIME, lt);
655 a = str_term_width1 (buf);
656 strftime (buf, sizeof(buf) - 1, FMTYEAR, lt);
657 b = str_term_width1 (buf);
659 length = max (a, b);
660 length = max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT)), length);
663 /* Don't handle big differences. Use standard value (email bug, please) */
664 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
665 length = STD_I18NTIMELENGTH;
667 return length;
670 const char *
671 file_date (time_t when)
673 static char timebuf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
674 time_t current_time = time ((time_t) 0);
675 const char *fmt;
677 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
678 || current_time < when - 60L * 60L) /* In the future. */
679 /* The file is fairly old or in the future.
680 POSIX says the cutoff is 6 months old;
681 approximate this by 6*30 days.
682 Allow a 1 hour slop factor for what is considered "the future",
683 to allow for NFS server/client clock disagreement.
684 Show the year instead of the time of day. */
686 fmt = FMTYEAR;
687 else
688 fmt = FMTTIME;
690 FMT_LOCALTIME(timebuf, sizeof (timebuf), fmt, when);
692 return timebuf;
695 const char *
696 extract_line (const char *s, const char *top)
698 static char tmp_line [BUF_MEDIUM];
699 char *t = tmp_line;
701 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
702 *t++ = *s++;
703 *t = 0;
704 return tmp_line;
707 /* The basename routine */
708 const char *
709 x_basename (const char *s)
711 const char *where;
712 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
716 const char *
717 unix_error_string (int error_num)
719 static char buffer [BUF_LARGE];
720 #if GLIB_MAJOR_VERSION >= 2
721 gchar *strerror_currentlocale;
723 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
724 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
725 strerror_currentlocale, error_num);
726 g_free(strerror_currentlocale);
727 #else
728 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
729 g_strerror (error_num), error_num);
730 #endif
731 return buffer;
734 const char *
735 skip_separators (const char *s)
737 const char *su = s;
739 for (;*su; str_cnext_char (&su))
740 if (*su != ' ' && *su != '\t' && *su != ',') break;
742 return su;
745 const char *
746 skip_numbers (const char *s)
748 const char *su = s;
750 for (;*su; str_cnext_char (&su))
751 if (!str_isdigit (su)) break;
753 return su;
756 /* Remove all control sequences from the argument string. We define
757 * "control sequence", in a sort of pidgin BNF, as follows:
759 * control-seq = Esc non-'['
760 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
762 * This scheme works for all the terminals described in my termcap /
763 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
764 * terminals. If I hear from a single person who uses such a terminal
765 * with MC, I'll be glad to add support for it. (Dugan)
766 * Non-printable characters are also removed.
769 char *
770 strip_ctrl_codes (char *s)
772 char *w; /* Current position where the stripped data is written */
773 char *r; /* Current position where the original data is read */
774 char *n;
776 if (!s)
777 return 0;
779 for (w = s, r = s; *r; ) {
780 if (*r == ESC_CHAR) {
781 /* Skip the control sequence's arguments */ ;
782 if (*(++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 USE_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 /* !USE_VFS */
858 enum compression_type
859 get_compression_type (int fd, const char * name)
861 unsigned char magic[16];
863 /* Read the magic signature */
864 if (mc_read (fd, (char *) magic, 4) != 4)
865 return COMPRESSION_NONE;
867 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
868 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
869 return COMPRESSION_GZIP;
872 /* PKZIP_MAGIC */
873 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
874 && magic[3] == 004) {
875 /* Read compression type */
876 mc_lseek (fd, 8, SEEK_SET);
877 if (mc_read (fd, (char *) magic, 2) != 2)
878 return COMPRESSION_NONE;
880 /* Gzip can handle only deflated (8) or stored (0) files */
881 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
882 return COMPRESSION_NONE;
884 /* Compatible with gzip */
885 return COMPRESSION_GZIP;
888 /* PACK_MAGIC and LZH_MAGIC and compress magic */
889 if (magic[0] == 037
890 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
891 /* Compatible with gzip */
892 return COMPRESSION_GZIP;
895 /* BZIP and BZIP2 files */
896 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
897 (magic[3] >= '1') && (magic[3] <= '9')) {
898 switch (magic[2]) {
899 case '0':
900 return COMPRESSION_BZIP;
901 case 'h':
902 return COMPRESSION_BZIP2;
906 /* Support for LZMA (only utils format with magic in header).
907 * This is the default format of LZMA utils 4.32.1 and later. */
909 if (mc_read(fd, (char *) magic+4, 1) == 1)
911 /* LZMA utils format */
913 ( magic[0] == 0xFF
914 && magic[1] == 'L'
915 && magic[2] == 'Z'
916 && magic[3] == 'M'
917 && magic[4] == 'A'
918 && magic[5] == 0x00
920 return COMPRESSION_LZMA;
923 /* XZ compression magic */
924 if (mc_read(fd, (char *) magic+5, 1) == 1)
926 if (
927 magic[0] == 0xFD
928 && magic[1] == 0x37
929 && magic[2] == 0x7A
930 && magic[3] == 0x58
931 && magic[4] == 0x5A
932 && magic[5] == 0x00
934 return COMPRESSION_XZ;
938 /* HACK: we must belive to extention of LZMA file :) ...*/
939 if (strlen(name) > 5 && strcmp(&name[strlen(name)-5],".lzma") == 0)
940 return COMPRESSION_LZMA;
942 return COMPRESSION_NONE;
945 const char *
946 decompress_extension (int type)
948 switch (type){
949 case COMPRESSION_GZIP: return "#ugz";
950 case COMPRESSION_BZIP: return "#ubz";
951 case COMPRESSION_BZIP2: return "#ubz2";
952 case COMPRESSION_LZMA: return "#ulzma";
953 case COMPRESSION_XZ: return "#uxz";
955 /* Should never reach this place */
956 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
957 return 0;
960 /* Hooks */
961 void
962 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
964 Hook *new_hook = g_new (Hook, 1);
966 new_hook->hook_fn = hook_fn;
967 new_hook->next = *hook_list;
968 new_hook->hook_data = data;
970 *hook_list = new_hook;
973 void
974 execute_hooks (Hook *hook_list)
976 Hook *new_hook = 0;
977 Hook *p;
979 /* We copy the hook list first so tahat we let the hook
980 * function call delete_hook
983 while (hook_list){
984 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
985 hook_list = hook_list->next;
987 p = new_hook;
989 while (new_hook){
990 (*new_hook->hook_fn)(new_hook->hook_data);
991 new_hook = new_hook->next;
994 for (hook_list = p; hook_list;){
995 p = hook_list;
996 hook_list = hook_list->next;
997 g_free (p);
1001 void
1002 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1004 Hook *current, *new_list, *next;
1006 new_list = 0;
1008 for (current = *hook_list; current; current = next){
1009 next = current->next;
1010 if (current->hook_fn == hook_fn)
1011 g_free (current);
1012 else
1013 add_hook (&new_list, current->hook_fn, current->hook_data);
1015 *hook_list = new_list;
1019 hook_present (Hook *hook_list, void (*hook_fn)(void *))
1021 Hook *p;
1023 for (p = hook_list; p; p = p->next)
1024 if (p->hook_fn == hook_fn)
1025 return 1;
1026 return 0;
1029 void
1030 wipe_password (char *passwd)
1032 char *p = passwd;
1034 if (!p)
1035 return;
1036 for (;*p ; p++)
1037 *p = 0;
1038 g_free (passwd);
1041 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1042 /* Returns a newly allocated string */
1043 char *
1044 convert_controls (const char *p)
1046 char *valcopy = g_strdup (p);
1047 char *q;
1049 /* Parse the escape special character */
1050 for (q = valcopy; *p;){
1051 if (*p == '\\'){
1052 p++;
1053 if ((*p == 'e') || (*p == 'E')){
1054 p++;
1055 *q++ = ESC_CHAR;
1057 } else {
1058 if (*p == '^'){
1059 p++;
1060 if (*p == '^')
1061 *q++ = *p++;
1062 else {
1063 char c = (*p | 0x20);
1064 if (c >= 'a' && c <= 'z') {
1065 *q++ = c - 'a' + 1;
1066 p++;
1067 } else if (*p)
1068 p++;
1070 } else
1071 *q++ = *p++;
1074 *q = 0;
1075 return valcopy;
1078 static char *
1079 resolve_symlinks (const char *path)
1081 char *buf, *buf2, *q, *r, c;
1082 int len;
1083 struct stat mybuf;
1084 const char *p;
1086 if (*path != PATH_SEP)
1087 return NULL;
1088 r = buf = g_malloc (MC_MAXPATHLEN);
1089 buf2 = g_malloc (MC_MAXPATHLEN);
1090 *r++ = PATH_SEP;
1091 *r = 0;
1092 p = path;
1093 for (;;) {
1094 q = strchr (p + 1, PATH_SEP);
1095 if (!q) {
1096 q = strchr (p + 1, 0);
1097 if (q == p + 1)
1098 break;
1100 c = *q;
1101 *q = 0;
1102 if (mc_lstat (path, &mybuf) < 0) {
1103 g_free (buf);
1104 g_free (buf2);
1105 *q = c;
1106 return NULL;
1108 if (!S_ISLNK (mybuf.st_mode))
1109 strcpy (r, p + 1);
1110 else {
1111 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1112 if (len < 0) {
1113 g_free (buf);
1114 g_free (buf2);
1115 *q = c;
1116 return NULL;
1118 buf2 [len] = 0;
1119 if (*buf2 == PATH_SEP)
1120 strcpy (buf, buf2);
1121 else
1122 strcpy (r, buf2);
1124 canonicalize_pathname (buf);
1125 r = strchr (buf, 0);
1126 if (!*r || *(r - 1) != PATH_SEP) {
1127 *r++ = PATH_SEP;
1128 *r = 0;
1130 *q = c;
1131 p = q;
1132 if (!c)
1133 break;
1135 if (!*buf)
1136 strcpy (buf, PATH_SEP_STR);
1137 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1138 *(r - 1) = 0;
1139 g_free (buf2);
1140 return buf;
1143 static gboolean
1144 mc_util_write_backup_content(const char *from_file_name, const char *to_file_name)
1146 FILE *backup_fd;
1147 char *contents;
1148 gsize length;
1150 if (!g_file_get_contents (from_file_name, &contents, &length, NULL))
1151 return FALSE;
1153 backup_fd = fopen (to_file_name, "w");
1154 if (backup_fd == NULL) {
1155 g_free(contents);
1156 return FALSE;
1159 fwrite ( (const void *) contents, length, 1, backup_fd);
1161 fflush(backup_fd);
1162 fclose(backup_fd);
1163 g_free(contents);
1164 return TRUE;
1167 /* Finds out a relative path from first to second, i.e. goes as many ..
1168 * as needed up in first and then goes down using second */
1169 char *
1170 diff_two_paths (const char *first, const char *second)
1172 char *p, *q, *r, *s, *buf = NULL;
1173 int i, j, prevlen = -1, currlen;
1174 char *my_first = NULL, *my_second = NULL;
1176 my_first = resolve_symlinks (first);
1177 if (my_first == NULL)
1178 return NULL;
1179 my_second = resolve_symlinks (second);
1180 if (my_second == NULL) {
1181 g_free (my_first);
1182 return NULL;
1184 for (j = 0; j < 2; j++) {
1185 p = my_first;
1186 q = my_second;
1187 for (;;) {
1188 r = strchr (p, PATH_SEP);
1189 s = strchr (q, PATH_SEP);
1190 if (!r || !s)
1191 break;
1192 *r = 0; *s = 0;
1193 if (strcmp (p, q)) {
1194 *r = PATH_SEP; *s = PATH_SEP;
1195 break;
1196 } else {
1197 *r = PATH_SEP; *s = PATH_SEP;
1199 p = r + 1;
1200 q = s + 1;
1202 p--;
1203 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1204 currlen = (i + 1) * 3 + strlen (q) + 1;
1205 if (j) {
1206 if (currlen < prevlen)
1207 g_free (buf);
1208 else {
1209 g_free (my_first);
1210 g_free (my_second);
1211 return buf;
1214 p = buf = g_malloc (currlen);
1215 prevlen = currlen;
1216 for (; i >= 0; i--, p += 3)
1217 strcpy (p, "../");
1218 strcpy (p, q);
1220 g_free (my_first);
1221 g_free (my_second);
1222 return buf;
1225 /* If filename is NULL, then we just append PATH_SEP to the dir */
1226 char *
1227 concat_dir_and_file (const char *dir, const char *file)
1229 int i = strlen (dir);
1231 if (dir [i-1] == PATH_SEP)
1232 return g_strconcat (dir, file, (char *) NULL);
1233 else
1234 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1237 /* Append text to GList, remove all entries with the same text */
1238 GList *
1239 list_append_unique (GList *list, char *text)
1241 GList *link, *newlink, *tmp;
1244 * Go to the last position and traverse the list backwards
1245 * starting from the second last entry to make sure that we
1246 * are not removing the current link.
1248 list = g_list_append (list, text);
1249 list = g_list_last (list);
1250 link = g_list_previous (list);
1252 while (link) {
1253 newlink = g_list_previous (link);
1254 if (!strcmp ((char *) link->data, text)) {
1255 g_free (link->data);
1256 tmp = g_list_remove_link (list, link);
1257 g_list_free_1 (link);
1259 link = newlink;
1262 return list;
1265 /* Following code heavily borrows from libiberty, mkstemps.c */
1267 /* Number of attempts to create a temporary file */
1268 #ifndef TMP_MAX
1269 #define TMP_MAX 16384
1270 #endif /* !TMP_MAX */
1273 * Arguments:
1274 * pname (output) - pointer to the name of the temp file (needs g_free).
1275 * NULL if the function fails.
1276 * prefix - part of the filename before the random part.
1277 * Prepend $TMPDIR or /tmp if there are no path separators.
1278 * suffix - if not NULL, part of the filename after the random part.
1280 * Result:
1281 * handle of the open file or -1 if couldn't open any.
1284 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1286 static const char letters[]
1287 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1288 static unsigned long value;
1289 struct timeval tv;
1290 char *tmpbase;
1291 char *tmpname;
1292 char *XXXXXX;
1293 int count;
1295 if (strchr (prefix, PATH_SEP) == NULL) {
1296 /* Add prefix first to find the position of XXXXXX */
1297 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1298 } else {
1299 tmpbase = g_strdup (prefix);
1302 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1303 *pname = tmpname;
1304 XXXXXX = &tmpname[strlen (tmpbase)];
1305 g_free (tmpbase);
1307 /* Get some more or less random data. */
1308 gettimeofday (&tv, NULL);
1309 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1311 for (count = 0; count < TMP_MAX; ++count) {
1312 unsigned long v = value;
1313 int fd;
1315 /* Fill in the random bits. */
1316 XXXXXX[0] = letters[v % 62];
1317 v /= 62;
1318 XXXXXX[1] = letters[v % 62];
1319 v /= 62;
1320 XXXXXX[2] = letters[v % 62];
1321 v /= 62;
1322 XXXXXX[3] = letters[v % 62];
1323 v /= 62;
1324 XXXXXX[4] = letters[v % 62];
1325 v /= 62;
1326 XXXXXX[5] = letters[v % 62];
1328 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1329 S_IRUSR | S_IWUSR);
1330 if (fd >= 0) {
1331 /* Successfully created. */
1332 return fd;
1335 /* This is a random value. It is only necessary that the next
1336 TMP_MAX values generated by adding 7777 to VALUE are different
1337 with (module 2^32). */
1338 value += 7777;
1341 /* Unsuccessful. Free the filename. */
1342 g_free (tmpname);
1343 *pname = NULL;
1345 return -1;
1349 * Read and restore position for the given filename.
1350 * If there is no stored data, return line 1 and col 0.
1352 void
1353 load_file_position (const char *filename, long *line, long *column)
1355 char *fn;
1356 FILE *f;
1357 char buf[MC_MAXPATHLEN + 20];
1358 int len;
1360 /* defaults */
1361 *line = 1;
1362 *column = 0;
1364 /* open file with positions */
1365 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1366 f = fopen (fn, "r");
1367 g_free (fn);
1368 if (!f)
1369 return;
1371 len = strlen (filename);
1373 while (fgets (buf, sizeof (buf), f)) {
1374 const char *p;
1376 /* check if the filename matches the beginning of string */
1377 if (strncmp (buf, filename, len) != 0)
1378 continue;
1380 /* followed by single space */
1381 if (buf[len] != ' ')
1382 continue;
1384 /* and string without spaces */
1385 p = &buf[len + 1];
1386 if (strchr (p, ' '))
1387 continue;
1389 *line = strtol(p, const_cast(char **, &p), 10);
1390 if (*p == ';') {
1391 *column = strtol(p+1, const_cast(char **, &p), 10);
1392 if (*p != '\n')
1393 *column = 0;
1394 } else
1395 *line = 1;
1397 fclose (f);
1400 /* Save position for the given file */
1401 void
1402 save_file_position (const char *filename, long line, long column)
1404 char *fn;
1405 FILE *f;
1408 fn = g_build_filename (home_dir, MC_USERCONF_DIR, MC_FILEPOS_FILE, NULL);
1409 if (fn == NULL)
1410 return;
1412 if (! mc_util_make_backup_if_possible (fn, ".tmp"))
1413 return;
1415 /* open file */
1416 f = fopen (fn, "a");
1417 if (f == NULL) {
1418 g_free (fn);
1419 return;
1422 /* put the new record */
1423 if (line != 1 || column != 0) {
1424 if (fprintf (f, "%s %ld;%ld\n", filename, line, column) < 0) {
1425 fclose (f);
1426 mc_util_restore_from_backup_if_possible (fn, ".tmp");
1428 } else
1429 fclose (f);
1431 mc_util_unlink_backup_if_possible (fn, ".tmp");
1432 g_free (fn);
1436 extern const char *
1437 cstrcasestr (const char *haystack, const char *needle)
1439 char *nee = str_create_search_needle (needle, 0);
1440 const char *result = str_search_first (haystack, nee, 0);
1441 str_release_search_needle (nee, 0);
1442 return result;
1445 const char *
1446 cstrstr (const char *haystack, const char *needle)
1448 return strstr(haystack, needle);
1451 extern char *
1452 str_unconst (const char *s)
1454 return (char *) s;
1457 #define ASCII_A (0x40 + 1)
1458 #define ASCII_Z (0x40 + 26)
1459 #define ASCII_a (0x60 + 1)
1460 #define ASCII_z (0x60 + 26)
1462 extern int
1463 ascii_alpha_to_cntrl (int ch)
1465 if ((ch >= ASCII_A && ch <= ASCII_Z)
1466 || (ch >= ASCII_a && ch <= ASCII_z)) {
1467 ch &= 0x1f;
1469 return ch;
1472 const char *
1473 Q_ (const char *s)
1475 const char *result, *sep;
1477 result = _(s);
1478 sep = strchr(result, '|');
1479 return (sep != NULL) ? sep + 1 : result;
1483 gboolean
1484 mc_util_make_backup_if_possible (const char *file_name, const char *backup_suffix)
1486 struct stat stat_buf;
1487 char *backup_path;
1488 gboolean ret;
1490 if (!exist_file (file_name))
1491 return FALSE;
1493 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1495 if (backup_path == NULL)
1496 return FALSE;
1498 ret = mc_util_write_backup_content (file_name, backup_path);
1500 if (ret) {
1501 /* Backup file will have same ownership with main file. */
1502 if (stat (file_name, &stat_buf) == 0)
1503 chmod (backup_path, stat_buf.st_mode);
1504 else
1505 chmod (backup_path, S_IRUSR | S_IWUSR);
1508 g_free(backup_path);
1510 return ret;
1513 gboolean
1514 mc_util_restore_from_backup_if_possible (const char *file_name, const char *backup_suffix)
1516 gboolean ret;
1517 char *backup_path;
1519 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1520 if (backup_path == NULL)
1521 return FALSE;
1523 ret = mc_util_write_backup_content (backup_path, file_name);
1524 g_free(backup_path);
1526 return ret;
1529 gboolean
1530 mc_util_unlink_backup_if_possible (const char *file_name, const char *backup_suffix)
1532 char *backup_path;
1534 backup_path = g_strdup_printf("%s%s",file_name,backup_suffix);
1535 if (backup_path == NULL)
1536 return FALSE;
1538 if (exist_file (backup_path))
1539 mc_unlink (backup_path);
1541 g_free(backup_path);
1542 return TRUE;