Ticket #1395 (Copying to fish is broken)
[midnight-commander.git] / src / util.c
blob28ebf4533cf1417b2001362d8be810dd35e24fc2
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"
44 #include "main.h" /* mc_home */
45 #include "cmd.h" /* guess_message_value */
46 #include "mountlist.h"
47 #include "win.h" /* xterm_flag */
48 #include "timefmt.h"
49 #include "strutil.h"
50 #include "fileopctx.h"
51 #include "file.h" /* copy_file_file() */
52 #include "../src/search/search.h"
54 #ifdef HAVE_CHARSET
55 #include "charsets.h"
56 #endif
58 int easy_patterns = 1;
60 extern void str_replace(char *s, char from, char to)
62 for (; *s != '\0'; s++) {
63 if (*s == from)
64 *s = to;
68 static inline int
69 is_7bit_printable (unsigned char c)
71 return (c > 31 && c < 127);
74 static inline int
75 is_iso_printable (unsigned char c)
77 return ((c > 31 && c < 127) || c >= 160);
80 static inline int
81 is_8bit_printable (unsigned char c)
83 /* "Full 8 bits output" doesn't work on xterm */
84 if (xterm_flag)
85 return is_iso_printable (c);
87 return (c > 31 && c != 127 && c != 155);
90 int
91 is_printable (int c)
93 c &= 0xff;
95 #ifdef HAVE_CHARSET
96 /* "Display bits" is ignored, since the user controls the output
97 by setting the output codepage */
98 return is_8bit_printable (c);
99 #else
100 if (!eight_bit_clean)
101 return is_7bit_printable (c);
103 if (full_eight_bits) {
104 return is_8bit_printable (c);
105 } else
106 return is_iso_printable (c);
107 #endif /* !HAVE_CHARSET */
110 /* Calculates the message dimensions (lines and columns) */
111 void
112 msglen (const char *text, int *lines, int *columns)
114 int nlines = 1; /* even the empty string takes one line */
115 int ncolumns = 0;
116 int colindex = 0;
118 for (; *text != '\0'; text++) {
119 if (*text == '\n') {
120 nlines++;
121 colindex = 0;
122 } else {
123 colindex++;
124 if (colindex > ncolumns)
125 ncolumns = colindex;
129 *lines = nlines;
130 *columns = ncolumns;
134 * Copy from s to d, and trim the beginning if necessary, and prepend
135 * "..." in this case. The destination string can have at most len
136 * bytes, not counting trailing 0.
138 char *
139 trim (const char *s, char *d, int len)
141 int source_len;
143 /* Sanity check */
144 len = max (len, 0);
146 source_len = strlen (s);
147 if (source_len > len) {
148 /* Cannot fit the whole line */
149 if (len <= 3) {
150 /* We only have room for the dots */
151 memset (d, '.', len);
152 d[len] = 0;
153 return d;
154 } else {
155 /* Begin with ... and add the rest of the source string */
156 memset (d, '.', 3);
157 strcpy (d + 3, s + 3 + source_len - len);
159 } else
160 /* We can copy the whole line */
161 strcpy (d, s);
162 return d;
166 * Quote the filename for the purpose of inserting it into the command
167 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
168 * processed by the mc command line.
170 char *
171 name_quote (const char *s, int quote_percent)
173 char *ret, *d;
175 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
176 if (*s == '-') {
177 *d++ = '.';
178 *d++ = '/';
181 for (; *s; s++, d++) {
182 switch (*s) {
183 case '%':
184 if (quote_percent)
185 *d++ = '%';
186 break;
187 case '\'':
188 case '\\':
189 case '\r':
190 case '\n':
191 case '\t':
192 case '"':
193 case ';':
194 case ' ':
195 case '?':
196 case '|':
197 case '[':
198 case ']':
199 case '{':
200 case '}':
201 case '<':
202 case '>':
203 case '`':
204 case '!':
205 case '$':
206 case '&':
207 case '*':
208 case '(':
209 case ')':
210 *d++ = '\\';
211 break;
212 case '~':
213 case '#':
214 if (d == ret)
215 *d++ = '\\';
216 break;
218 *d = *s;
220 *d = '\0';
221 return ret;
224 char *
225 fake_name_quote (const char *s, int quote_percent)
227 (void) quote_percent;
228 return g_strdup (s);
232 * Remove the middle part of the string to fit given length.
233 * Use "~" to show where the string was truncated.
234 * Return static buffer, no need to free() it.
236 const char *
237 name_trunc (const char *txt, size_t trunc_len)
239 return str_trunc (txt, trunc_len);
243 * path_trunc() is the same as name_trunc() above but
244 * it deletes possible password from path for security
245 * reasons.
247 const char *
248 path_trunc (const char *path, size_t trunc_len) {
249 char *secure_path = strip_password (g_strdup (path), 1);
251 const char *ret = str_trunc (secure_path, trunc_len);
252 g_free (secure_path);
254 return ret;
257 const char *
258 size_trunc (double size)
260 static char x [BUF_TINY];
261 long int divisor = 1;
262 const char *xtra = "";
264 if (size > 999999999L){
265 divisor = 1024;
266 xtra = "K";
267 if (size/divisor > 999999999L){
268 divisor = 1024*1024;
269 xtra = "M";
272 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
273 return x;
276 const char *
277 size_trunc_sep (double size)
279 static char x [60];
280 int count;
281 const char *p, *y;
282 char *d;
284 p = y = size_trunc (size);
285 p += strlen (p) - 1;
286 d = x + sizeof (x) - 1;
287 *d-- = 0;
288 while (p >= y && isalpha ((unsigned char) *p))
289 *d-- = *p--;
290 for (count = 0; p >= y; count++){
291 if (count == 3){
292 *d-- = ',';
293 count = 0;
295 *d-- = *p--;
297 d++;
298 if (*d == ',')
299 d++;
300 return d;
304 * Print file SIZE to BUFFER, but don't exceed LEN characters,
305 * not including trailing 0. BUFFER should be at least LEN+1 long.
306 * This function is called for every file on panels, so avoid
307 * floating point by any means.
309 * Units: size units (filesystem sizes are 1K blocks)
310 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
312 void
313 size_trunc_len (char *buffer, int len, off_t size, int units)
315 /* Avoid taking power for every file. */
316 static const off_t power10 [] =
317 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
318 1000000000};
319 static const char * const suffix [] =
320 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
321 int j = 0;
323 /* Don't print more than 9 digits - use suffix. */
324 if (len == 0 || len > 9)
325 len = 9;
327 for (j = units; suffix [j] != NULL; j++) {
328 if (size == 0) {
329 if (j == units) {
330 /* Empty files will print "0" even with minimal width. */
331 g_snprintf (buffer, len + 1, "0");
332 break;
335 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
336 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
337 (j > 1) ? suffix[j - 1] : "B");
338 break;
341 if (size < power10 [len - (j > 0)]) {
342 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
343 break;
346 /* Powers of 1024, with rounding. */
347 size = (size + 512) >> 10;
352 is_exe (mode_t mode)
354 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
355 return 1;
356 return 0;
359 #define ismode(n,m) ((n & m) == m)
361 const char *
362 string_perm (mode_t mode_bits)
364 static char mode[11];
366 strcpy (mode, "----------");
367 if (S_ISDIR (mode_bits))
368 mode[0] = 'd';
369 if (S_ISCHR (mode_bits))
370 mode[0] = 'c';
371 if (S_ISBLK (mode_bits))
372 mode[0] = 'b';
373 if (S_ISLNK (mode_bits))
374 mode[0] = 'l';
375 if (S_ISFIFO (mode_bits))
376 mode[0] = 'p';
377 if (S_ISNAM (mode_bits))
378 mode[0] = 'n';
379 if (S_ISSOCK (mode_bits))
380 mode[0] = 's';
381 if (S_ISDOOR (mode_bits))
382 mode[0] = 'D';
383 if (ismode (mode_bits, S_IXOTH))
384 mode[9] = 'x';
385 if (ismode (mode_bits, S_IWOTH))
386 mode[8] = 'w';
387 if (ismode (mode_bits, S_IROTH))
388 mode[7] = 'r';
389 if (ismode (mode_bits, S_IXGRP))
390 mode[6] = 'x';
391 if (ismode (mode_bits, S_IWGRP))
392 mode[5] = 'w';
393 if (ismode (mode_bits, S_IRGRP))
394 mode[4] = 'r';
395 if (ismode (mode_bits, S_IXUSR))
396 mode[3] = 'x';
397 if (ismode (mode_bits, S_IWUSR))
398 mode[2] = 'w';
399 if (ismode (mode_bits, S_IRUSR))
400 mode[1] = 'r';
401 #ifdef S_ISUID
402 if (ismode (mode_bits, S_ISUID))
403 mode[3] = (mode[3] == 'x') ? 's' : 'S';
404 #endif /* S_ISUID */
405 #ifdef S_ISGID
406 if (ismode (mode_bits, S_ISGID))
407 mode[6] = (mode[6] == 'x') ? 's' : 'S';
408 #endif /* S_ISGID */
409 #ifdef S_ISVTX
410 if (ismode (mode_bits, S_ISVTX))
411 mode[9] = (mode[9] == 'x') ? 't' : 'T';
412 #endif /* S_ISVTX */
413 return mode;
416 /* p: string which might contain an url with a password (this parameter is
417 modified in place).
418 has_prefix = 0: The first parameter is an url without a prefix
419 (user[:pass]@]machine[:port][remote-dir). Delete
420 the password.
421 has_prefix = 1: Search p for known url prefixes. If found delete
422 the password from the url.
423 Caveat: only the first url is found
425 char *
426 strip_password (char *p, int has_prefix)
428 static const struct {
429 const char *name;
430 size_t len;
431 } prefixes[] = { {"/#ftp:", 6},
432 {"ftp://", 6},
433 {"/#mc:", 5},
434 {"mc://", 5},
435 {"/#smb:", 6},
436 {"smb://", 6},
437 {"/#sh:", 5},
438 {"sh://", 5},
439 {"ssh://", 6}
441 char *at, *inner_colon, *dir;
442 size_t i;
443 char *result = p;
445 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
446 char *q;
448 if (has_prefix) {
449 if((q = strstr (p, prefixes[i].name)) == 0)
450 continue;
451 else
452 p = q + prefixes[i].len;
455 if ((dir = strchr (p, PATH_SEP)) != NULL)
456 *dir = '\0';
458 /* search for any possible user */
459 at = strrchr (p, '@');
461 if (dir)
462 *dir = PATH_SEP;
464 /* We have a username */
465 if (at) {
466 inner_colon = memchr (p, ':', at - p);
467 if (inner_colon)
468 memmove (inner_colon, at, strlen(at) + 1);
470 break;
472 return (result);
475 const char *
476 strip_home_and_password(const char *dir)
478 size_t len;
479 static char newdir [MC_MAXPATHLEN];
481 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
482 (dir[len] == PATH_SEP || dir[len] == '\0')){
483 newdir [0] = '~';
484 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
485 return newdir;
488 /* We do not strip homes in /#ftp tree, I do not like ~'s there
489 (see ftpfs.c why) */
490 g_strlcpy (newdir, dir, sizeof(newdir));
491 strip_password (newdir, 1);
492 return newdir;
495 const char *
496 extension (const char *filename)
498 const char *d = strrchr (filename, '.');
499 return (d != NULL) ? d + 1 : "";
503 exist_file (const char *name)
505 return access (name, R_OK) == 0;
509 check_for_default (const char *default_file, const char *file)
511 if (!exist_file (file)) {
512 FileOpContext *ctx;
513 off_t count = 0;
514 double bytes = 0.0;
516 if (!exist_file (default_file))
517 return -1;
519 ctx = file_op_context_new (OP_COPY);
520 file_op_context_create_ui (ctx, 0);
521 copy_file_file (ctx, default_file, file, 1, &count, &bytes, 1);
522 file_op_context_destroy (ctx);
525 return 0;
530 char *
531 load_file (const char *filename)
533 FILE *data_file;
534 struct stat s;
535 char *data;
536 long read_size;
538 if ((data_file = fopen (filename, "r")) == NULL){
539 return 0;
541 if (fstat (fileno (data_file), &s) != 0){
542 fclose (data_file);
543 return 0;
545 data = g_malloc (s.st_size+1);
546 read_size = fread (data, 1, s.st_size, data_file);
547 data [read_size] = 0;
548 fclose (data_file);
550 if (read_size > 0)
551 return data;
552 else {
553 g_free (data);
554 return 0;
558 char *
559 load_mc_home_file (const char *filename, char **allocated_filename)
561 char *hintfile_base, *hintfile;
562 char *lang;
563 char *data;
565 hintfile_base = concat_dir_and_file (mc_home, filename);
566 lang = guess_message_value ();
568 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
569 data = load_file (hintfile);
571 if (!data) {
572 g_free (hintfile);
573 g_free (hintfile_base);
574 hintfile_base = concat_dir_and_file (mc_home_alt, filename);
576 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
577 data = load_file (hintfile);
579 if (!data) {
580 /* Fall back to the two-letter language code */
581 if (lang[0] && lang[1])
582 lang[2] = 0;
583 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
584 data = load_file (hintfile);
586 if (!data) {
587 g_free (hintfile);
588 hintfile = hintfile_base;
589 data = load_file (hintfile_base);
594 g_free (lang);
596 if (hintfile != hintfile_base)
597 g_free (hintfile_base);
599 if (allocated_filename)
600 *allocated_filename = hintfile;
601 else
602 g_free (hintfile);
604 return data;
607 /* Check strftime() results. Some systems (i.e. Solaris) have different
608 short-month-name sizes for different locales */
609 size_t
610 i18n_checktimelength (void)
612 size_t length;
613 time_t testtime = time (NULL);
614 struct tm* lt = localtime(&testtime);
616 if (lt == NULL) {
617 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
618 length = str_term_width1 (_(INVALID_TIME_TEXT));
619 } else {
620 char buf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
621 size_t a, b;
623 strftime (buf, sizeof(buf) - 1, _("%b %d %H:%M"), lt);
624 a = str_term_width1 (buf);
625 strftime (buf, sizeof(buf) - 1, _("%b %d %Y"), lt);
626 b = str_term_width1 (buf);
628 length = max (a, b);
629 length = max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT)), length);
632 /* Don't handle big differences. Use standard value (email bug, please) */
633 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
634 length = STD_I18NTIMELENGTH;
636 return length;
639 const char *
640 file_date (time_t when)
642 static char timebuf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
643 time_t current_time = time ((time_t) 0);
644 static int i18n = 0;
645 static const char *fmtyear, *fmttime;
646 const char *fmt;
648 if (!i18n){
649 /* strftime() format string for old dates */
650 fmtyear = _("%b %e %Y");
651 /* strftime() format string for recent dates */
652 fmttime = _("%b %e %H:%M");
653 i18n = 1;
656 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
657 || current_time < when - 60L * 60L) /* In the future. */
658 /* The file is fairly old or in the future.
659 POSIX says the cutoff is 6 months old;
660 approximate this by 6*30 days.
661 Allow a 1 hour slop factor for what is considered "the future",
662 to allow for NFS server/client clock disagreement.
663 Show the year instead of the time of day. */
665 fmt = fmtyear;
666 else
667 fmt = fmttime;
669 FMT_LOCALTIME(timebuf, sizeof (timebuf), fmt, when);
671 return timebuf;
674 const char *
675 extract_line (const char *s, const char *top)
677 static char tmp_line [BUF_MEDIUM];
678 char *t = tmp_line;
680 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
681 *t++ = *s++;
682 *t = 0;
683 return tmp_line;
686 /* The basename routine */
687 const char *
688 x_basename (const char *s)
690 const char *where;
691 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
695 const char *
696 unix_error_string (int error_num)
698 static char buffer [BUF_LARGE];
699 #if GLIB_MAJOR_VERSION >= 2
700 gchar *strerror_currentlocale;
702 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
703 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
704 strerror_currentlocale, error_num);
705 g_free(strerror_currentlocale);
706 #else
707 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
708 g_strerror (error_num), error_num);
709 #endif
710 return buffer;
713 const char *
714 skip_separators (const char *s)
716 const char *su = s;
718 for (;*su; str_cnext_char (&su))
719 if (*su != ' ' && *su != '\t' && *su != ',') break;
721 return su;
724 const char *
725 skip_numbers (const char *s)
727 const char *su = s;
729 for (;*su; str_cnext_char (&su))
730 if (!str_isdigit (su)) break;
732 return su;
735 /* Remove all control sequences from the argument string. We define
736 * "control sequence", in a sort of pidgin BNF, as follows:
738 * control-seq = Esc non-'['
739 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
741 * This scheme works for all the terminals described in my termcap /
742 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
743 * terminals. If I hear from a single person who uses such a terminal
744 * with MC, I'll be glad to add support for it. (Dugan)
745 * Non-printable characters are also removed.
748 char *
749 strip_ctrl_codes (char *s)
751 char *w; /* Current position where the stripped data is written */
752 char *r; /* Current position where the original data is read */
753 char *n;
755 if (!s)
756 return 0;
758 for (w = s, r = s; *r; ) {
759 if (*r == ESC_CHAR) {
760 /* Skip the control sequence's arguments */ ;
761 if (*(++r) == '[') {
762 /* strchr() matches trailing binary 0 */
763 while (*(++r) && strchr ("0123456789;?", *r));
764 } else
765 if (*r == ']') {
767 * Skip xterm's OSC (Operating System Command)
768 * http://www.xfree86.org/current/ctlseqs.html
769 * OSC P s ; P t ST
770 * OSC P s ; P t BEL
772 char * new_r = r;
774 for (; *new_r; ++new_r)
776 switch (*new_r)
778 /* BEL */
779 case '\a':
780 r = new_r;
781 goto osc_out;
782 case ESC_CHAR:
783 /* ST */
784 if (*(new_r + 1) == '\\')
786 r = new_r + 1;
787 goto osc_out;
791 osc_out:;
795 * Now we are at the last character of the sequence.
796 * Skip it unless it's binary 0.
798 if (*r)
799 r++;
800 continue;
803 n = str_get_next_char (r);
804 if (str_isprint (r)) {
805 memmove (w, r, n - r);
806 w+= n - r;
808 r = n;
810 *w = 0;
811 return s;
815 #ifndef USE_VFS
816 char *
817 get_current_wd (char *buffer, int size)
819 char *p;
820 int len;
822 p = g_get_current_dir ();
823 len = strlen(p) + 1;
825 if (len > size) {
826 g_free (p);
827 return NULL;
830 memcpy (buffer, p, len);
831 g_free (p);
833 return buffer;
835 #endif /* !USE_VFS */
837 enum compression_type
838 get_compression_type (int fd)
840 unsigned char magic[16];
842 /* Read the magic signature */
843 if (mc_read (fd, (char *) magic, 4) != 4)
844 return COMPRESSION_NONE;
846 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
847 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
848 return COMPRESSION_GZIP;
851 /* PKZIP_MAGIC */
852 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
853 && magic[3] == 004) {
854 /* Read compression type */
855 mc_lseek (fd, 8, SEEK_SET);
856 if (mc_read (fd, (char *) magic, 2) != 2)
857 return COMPRESSION_NONE;
859 /* Gzip can handle only deflated (8) or stored (0) files */
860 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
861 return COMPRESSION_NONE;
863 /* Compatible with gzip */
864 return COMPRESSION_GZIP;
867 /* PACK_MAGIC and LZH_MAGIC and compress magic */
868 if (magic[0] == 037
869 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
870 /* Compatible with gzip */
871 return COMPRESSION_GZIP;
874 /* BZIP and BZIP2 files */
875 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
876 (magic[3] >= '1') && (magic[3] <= '9')) {
877 switch (magic[2]) {
878 case '0':
879 return COMPRESSION_BZIP;
880 case 'h':
881 return COMPRESSION_BZIP2;
885 /* LZMA files; both LZMA_Alone and LZMA utils formats. The LZMA_Alone
886 * format is used by the LZMA_Alone tool from LZMA SDK. The LZMA utils
887 * format is the default format of LZMA utils 4.32.1 and later. */
888 if (magic[0] < 0xE1 || (magic[0] == 0xFF && magic[1] == 'L' &&
889 magic[2] == 'Z' && magic[3] == 'M')) {
890 if (mc_read (fd, (char *) magic + 4, 9) == 9) {
891 /* LZMA utils format */
892 if (magic[0] == 0xFF && magic[4] == 'A' && magic[5] == 0x00)
893 return COMPRESSION_LZMA;
894 /* The LZMA_Alone format has no magic bytes, thus we
895 * need to play a wizard. This can give false positives,
896 * thus the detection below should be removed when
897 * the newer LZMA utils format has got popular. */
898 if (magic[0] < 0xE1 && magic[4] < 0x20 &&
899 ((magic[10] == 0x00 && magic[11] == 0x00 &&
900 magic[12] == 0x00) ||
901 (magic[5] == 0xFF && magic[6] == 0xFF &&
902 magic[7] == 0xFF && magic[8] == 0xFF &&
903 magic[9] == 0xFF && magic[10] == 0xFF &&
904 magic[11] == 0xFF && magic[12] == 0xFF)))
905 return COMPRESSION_LZMA;
909 /* XZ compression magic */
910 if (magic[0] == 0xFD
911 && magic[1] == 0x37 && magic[2] == 0x7A && magic[3] == 0x58) {
912 if (mc_read (fd, (char *) magic + 4, 2) == 2) {
913 if (magic[4] == 0x5A && magic[5] == 0x00) {
914 return COMPRESSION_XZ;
919 return 0;
922 const char *
923 decompress_extension (int type)
925 switch (type){
926 case COMPRESSION_GZIP: return "#ugz";
927 case COMPRESSION_BZIP: return "#ubz";
928 case COMPRESSION_BZIP2: return "#ubz2";
929 case COMPRESSION_LZMA: return "#ulzma";
930 case COMPRESSION_XZ: return "#uxz";
932 /* Should never reach this place */
933 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
934 return 0;
937 /* Hooks */
938 void
939 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
941 Hook *new_hook = g_new (Hook, 1);
943 new_hook->hook_fn = hook_fn;
944 new_hook->next = *hook_list;
945 new_hook->hook_data = data;
947 *hook_list = new_hook;
950 void
951 execute_hooks (Hook *hook_list)
953 Hook *new_hook = 0;
954 Hook *p;
956 /* We copy the hook list first so tahat we let the hook
957 * function call delete_hook
960 while (hook_list){
961 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
962 hook_list = hook_list->next;
964 p = new_hook;
966 while (new_hook){
967 (*new_hook->hook_fn)(new_hook->hook_data);
968 new_hook = new_hook->next;
971 for (hook_list = p; hook_list;){
972 p = hook_list;
973 hook_list = hook_list->next;
974 g_free (p);
978 void
979 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
981 Hook *current, *new_list, *next;
983 new_list = 0;
985 for (current = *hook_list; current; current = next){
986 next = current->next;
987 if (current->hook_fn == hook_fn)
988 g_free (current);
989 else
990 add_hook (&new_list, current->hook_fn, current->hook_data);
992 *hook_list = new_list;
996 hook_present (Hook *hook_list, void (*hook_fn)(void *))
998 Hook *p;
1000 for (p = hook_list; p; p = p->next)
1001 if (p->hook_fn == hook_fn)
1002 return 1;
1003 return 0;
1006 void
1007 wipe_password (char *passwd)
1009 char *p = passwd;
1011 if (!p)
1012 return;
1013 for (;*p ; p++)
1014 *p = 0;
1015 g_free (passwd);
1018 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1019 /* Returns a newly allocated string */
1020 char *
1021 convert_controls (const char *p)
1023 char *valcopy = g_strdup (p);
1024 char *q;
1026 /* Parse the escape special character */
1027 for (q = valcopy; *p;){
1028 if (*p == '\\'){
1029 p++;
1030 if ((*p == 'e') || (*p == 'E')){
1031 p++;
1032 *q++ = ESC_CHAR;
1034 } else {
1035 if (*p == '^'){
1036 p++;
1037 if (*p == '^')
1038 *q++ = *p++;
1039 else {
1040 char c = (*p | 0x20);
1041 if (c >= 'a' && c <= 'z') {
1042 *q++ = c - 'a' + 1;
1043 p++;
1044 } else if (*p)
1045 p++;
1047 } else
1048 *q++ = *p++;
1051 *q = 0;
1052 return valcopy;
1055 static char *
1056 resolve_symlinks (const char *path)
1058 char *buf, *buf2, *q, *r, c;
1059 int len;
1060 struct stat mybuf;
1061 const char *p;
1063 if (*path != PATH_SEP)
1064 return NULL;
1065 r = buf = g_malloc (MC_MAXPATHLEN);
1066 buf2 = g_malloc (MC_MAXPATHLEN);
1067 *r++ = PATH_SEP;
1068 *r = 0;
1069 p = path;
1070 for (;;) {
1071 q = strchr (p + 1, PATH_SEP);
1072 if (!q) {
1073 q = strchr (p + 1, 0);
1074 if (q == p + 1)
1075 break;
1077 c = *q;
1078 *q = 0;
1079 if (mc_lstat (path, &mybuf) < 0) {
1080 g_free (buf);
1081 g_free (buf2);
1082 *q = c;
1083 return NULL;
1085 if (!S_ISLNK (mybuf.st_mode))
1086 strcpy (r, p + 1);
1087 else {
1088 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1089 if (len < 0) {
1090 g_free (buf);
1091 g_free (buf2);
1092 *q = c;
1093 return NULL;
1095 buf2 [len] = 0;
1096 if (*buf2 == PATH_SEP)
1097 strcpy (buf, buf2);
1098 else
1099 strcpy (r, buf2);
1101 canonicalize_pathname (buf);
1102 r = strchr (buf, 0);
1103 if (!*r || *(r - 1) != PATH_SEP) {
1104 *r++ = PATH_SEP;
1105 *r = 0;
1107 *q = c;
1108 p = q;
1109 if (!c)
1110 break;
1112 if (!*buf)
1113 strcpy (buf, PATH_SEP_STR);
1114 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1115 *(r - 1) = 0;
1116 g_free (buf2);
1117 return buf;
1120 /* Finds out a relative path from first to second, i.e. goes as many ..
1121 * as needed up in first and then goes down using second */
1122 char *
1123 diff_two_paths (const char *first, const char *second)
1125 char *p, *q, *r, *s, *buf = NULL;
1126 int i, j, prevlen = -1, currlen;
1127 char *my_first = NULL, *my_second = NULL;
1129 my_first = resolve_symlinks (first);
1130 if (my_first == NULL)
1131 return NULL;
1132 my_second = resolve_symlinks (second);
1133 if (my_second == NULL) {
1134 g_free (my_first);
1135 return NULL;
1137 for (j = 0; j < 2; j++) {
1138 p = my_first;
1139 q = my_second;
1140 for (;;) {
1141 r = strchr (p, PATH_SEP);
1142 s = strchr (q, PATH_SEP);
1143 if (!r || !s)
1144 break;
1145 *r = 0; *s = 0;
1146 if (strcmp (p, q)) {
1147 *r = PATH_SEP; *s = PATH_SEP;
1148 break;
1149 } else {
1150 *r = PATH_SEP; *s = PATH_SEP;
1152 p = r + 1;
1153 q = s + 1;
1155 p--;
1156 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1157 currlen = (i + 1) * 3 + strlen (q) + 1;
1158 if (j) {
1159 if (currlen < prevlen)
1160 g_free (buf);
1161 else {
1162 g_free (my_first);
1163 g_free (my_second);
1164 return buf;
1167 p = buf = g_malloc (currlen);
1168 prevlen = currlen;
1169 for (; i >= 0; i--, p += 3)
1170 strcpy (p, "../");
1171 strcpy (p, q);
1173 g_free (my_first);
1174 g_free (my_second);
1175 return buf;
1178 /* If filename is NULL, then we just append PATH_SEP to the dir */
1179 char *
1180 concat_dir_and_file (const char *dir, const char *file)
1182 int i = strlen (dir);
1184 if (dir [i-1] == PATH_SEP)
1185 return g_strconcat (dir, file, (char *) NULL);
1186 else
1187 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1190 /* Append text to GList, remove all entries with the same text */
1191 GList *
1192 list_append_unique (GList *list, char *text)
1194 GList *link, *newlink, *tmp;
1197 * Go to the last position and traverse the list backwards
1198 * starting from the second last entry to make sure that we
1199 * are not removing the current link.
1201 list = g_list_append (list, text);
1202 list = g_list_last (list);
1203 link = g_list_previous (list);
1205 while (link) {
1206 newlink = g_list_previous (link);
1207 if (!strcmp ((char *) link->data, text)) {
1208 g_free (link->data);
1209 tmp = g_list_remove_link (list, link);
1210 g_list_free_1 (link);
1212 link = newlink;
1215 return list;
1218 /* Following code heavily borrows from libiberty, mkstemps.c */
1220 /* Number of attempts to create a temporary file */
1221 #ifndef TMP_MAX
1222 #define TMP_MAX 16384
1223 #endif /* !TMP_MAX */
1226 * Arguments:
1227 * pname (output) - pointer to the name of the temp file (needs g_free).
1228 * NULL if the function fails.
1229 * prefix - part of the filename before the random part.
1230 * Prepend $TMPDIR or /tmp if there are no path separators.
1231 * suffix - if not NULL, part of the filename after the random part.
1233 * Result:
1234 * handle of the open file or -1 if couldn't open any.
1237 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1239 static const char letters[]
1240 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1241 static unsigned long value;
1242 struct timeval tv;
1243 char *tmpbase;
1244 char *tmpname;
1245 char *XXXXXX;
1246 int count;
1248 if (strchr (prefix, PATH_SEP) == NULL) {
1249 /* Add prefix first to find the position of XXXXXX */
1250 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1251 } else {
1252 tmpbase = g_strdup (prefix);
1255 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1256 *pname = tmpname;
1257 XXXXXX = &tmpname[strlen (tmpbase)];
1258 g_free (tmpbase);
1260 /* Get some more or less random data. */
1261 gettimeofday (&tv, NULL);
1262 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1264 for (count = 0; count < TMP_MAX; ++count) {
1265 unsigned long v = value;
1266 int fd;
1268 /* Fill in the random bits. */
1269 XXXXXX[0] = letters[v % 62];
1270 v /= 62;
1271 XXXXXX[1] = letters[v % 62];
1272 v /= 62;
1273 XXXXXX[2] = letters[v % 62];
1274 v /= 62;
1275 XXXXXX[3] = letters[v % 62];
1276 v /= 62;
1277 XXXXXX[4] = letters[v % 62];
1278 v /= 62;
1279 XXXXXX[5] = letters[v % 62];
1281 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1282 S_IRUSR | S_IWUSR);
1283 if (fd >= 0) {
1284 /* Successfully created. */
1285 return fd;
1288 /* This is a random value. It is only necessary that the next
1289 TMP_MAX values generated by adding 7777 to VALUE are different
1290 with (module 2^32). */
1291 value += 7777;
1294 /* Unsuccessful. Free the filename. */
1295 g_free (tmpname);
1296 *pname = NULL;
1298 return -1;
1302 * Read and restore position for the given filename.
1303 * If there is no stored data, return line 1 and col 0.
1305 void
1306 load_file_position (const char *filename, long *line, long *column)
1308 char *fn;
1309 FILE *f;
1310 char buf[MC_MAXPATHLEN + 20];
1311 int len;
1313 /* defaults */
1314 *line = 1;
1315 *column = 0;
1317 /* open file with positions */
1318 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1319 f = fopen (fn, "r");
1320 g_free (fn);
1321 if (!f)
1322 return;
1324 len = strlen (filename);
1326 while (fgets (buf, sizeof (buf), f)) {
1327 const char *p;
1329 /* check if the filename matches the beginning of string */
1330 if (strncmp (buf, filename, len) != 0)
1331 continue;
1333 /* followed by single space */
1334 if (buf[len] != ' ')
1335 continue;
1337 /* and string without spaces */
1338 p = &buf[len + 1];
1339 if (strchr (p, ' '))
1340 continue;
1342 *line = strtol(p, const_cast(char **, &p), 10);
1343 if (*p == ';') {
1344 *column = strtol(p+1, const_cast(char **, &p), 10);
1345 if (*p != '\n')
1346 *column = 0;
1347 } else
1348 *line = 1;
1350 fclose (f);
1353 /* Save position for the given file */
1354 void
1355 save_file_position (const char *filename, long line, long column)
1357 char *tmp, *fn;
1358 FILE *f, *t;
1359 char buf[MC_MAXPATHLEN + 20];
1360 int i = 1;
1361 int len;
1363 len = strlen (filename);
1365 tmp = concat_dir_and_file (home_dir, MC_FILEPOS_TMP);
1366 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1368 /* open temporary file */
1369 t = fopen (tmp, "w");
1370 if (!t) {
1371 g_free (tmp);
1372 g_free (fn);
1373 return;
1376 /* put the new record */
1377 if (line != 1 || column != 0) {
1378 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1381 /* copy records from the old file */
1382 f = fopen (fn, "r");
1383 if (f) {
1384 while (fgets (buf, sizeof (buf), f)) {
1385 /* Skip entries for the current filename */
1386 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1387 && !strchr (&buf[len + 1], ' '))
1388 continue;
1390 fprintf (t, "%s", buf);
1391 if (++i > MC_FILEPOS_ENTRIES)
1392 break;
1394 fclose (f);
1397 fclose (t);
1398 rename (tmp, fn);
1399 g_free (tmp);
1400 g_free (fn);
1403 extern const char *
1404 cstrcasestr (const char *haystack, const char *needle)
1406 char *nee = str_create_search_needle (needle, 0);
1407 const char *result = str_search_first (haystack, nee, 0);
1408 str_release_search_needle (nee, 0);
1409 return result;
1412 const char *
1413 cstrstr (const char *haystack, const char *needle)
1415 return strstr(haystack, needle);
1418 extern char *
1419 str_unconst (const char *s)
1421 return (char *) s;
1424 #define ASCII_A (0x40 + 1)
1425 #define ASCII_Z (0x40 + 26)
1426 #define ASCII_a (0x60 + 1)
1427 #define ASCII_z (0x60 + 26)
1429 extern int
1430 ascii_alpha_to_cntrl (int ch)
1432 if ((ch >= ASCII_A && ch <= ASCII_Z)
1433 || (ch >= ASCII_a && ch <= ASCII_z)) {
1434 ch &= 0x1f;
1436 return ch;
1439 const char *
1440 Q_ (const char *s)
1442 const char *result, *sep;
1444 result = _(s);
1445 sep = strchr(result, '|');
1446 return (sep != NULL) ? sep + 1 : result;