Ticket #305 (dont work rename/copy on some chars)
[midnight-commander.git] / src / util.c
bloba1f1ddee1643f1bf4aad72607e508184f1cf230e
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 <sys/types.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
41 #include "global.h"
42 #include "main.h" /* mc_home */
43 #include "cmd.h" /* guess_message_value */
44 #include "mountlist.h"
45 #include "win.h" /* xterm_flag */
46 #include "timefmt.h"
47 #include "strutil.h"
48 #include "fileopctx.h"
49 #include "file.h" /* copy_file_file() */
50 #include "../src/search/search.h"
52 #ifdef HAVE_CHARSET
53 #include "charsets.h"
54 #endif
56 int easy_patterns = 1;
58 extern void str_replace(char *s, char from, char to)
60 for (; *s != '\0'; s++) {
61 if (*s == from)
62 *s = to;
66 static inline int
67 is_7bit_printable (unsigned char c)
69 return (c > 31 && c < 127);
72 static inline int
73 is_iso_printable (unsigned char c)
75 return ((c > 31 && c < 127) || c >= 160);
78 static inline int
79 is_8bit_printable (unsigned char c)
81 /* "Full 8 bits output" doesn't work on xterm */
82 if (xterm_flag)
83 return is_iso_printable (c);
85 return (c > 31 && c != 127 && c != 155);
88 int
89 is_printable (int c)
91 c &= 0xff;
93 #ifdef HAVE_CHARSET
94 /* "Display bits" is ignored, since the user controls the output
95 by setting the output codepage */
96 return is_8bit_printable (c);
97 #else
98 if (!eight_bit_clean)
99 return is_7bit_printable (c);
101 if (full_eight_bits) {
102 return is_8bit_printable (c);
103 } else
104 return is_iso_printable (c);
105 #endif /* !HAVE_CHARSET */
108 /* Calculates the message dimensions (lines and columns) */
109 void
110 msglen (const char *text, int *lines, int *columns)
112 int nlines = 1; /* even the empty string takes one line */
113 int ncolumns = 0;
114 int colindex = 0;
116 for (; *text != '\0'; text++) {
117 if (*text == '\n') {
118 nlines++;
119 colindex = 0;
120 } else {
121 colindex++;
122 if (colindex > ncolumns)
123 ncolumns = colindex;
127 *lines = nlines;
128 *columns = ncolumns;
132 * Copy from s to d, and trim the beginning if necessary, and prepend
133 * "..." in this case. The destination string can have at most len
134 * bytes, not counting trailing 0.
136 char *
137 trim (const char *s, char *d, int len)
139 int source_len;
141 /* Sanity check */
142 len = max (len, 0);
144 source_len = strlen (s);
145 if (source_len > len) {
146 /* Cannot fit the whole line */
147 if (len <= 3) {
148 /* We only have room for the dots */
149 memset (d, '.', len);
150 d[len] = 0;
151 return d;
152 } else {
153 /* Begin with ... and add the rest of the source string */
154 memset (d, '.', 3);
155 strcpy (d + 3, s + 3 + source_len - len);
157 } else
158 /* We can copy the whole line */
159 strcpy (d, s);
160 return d;
164 * Quote the filename for the purpose of inserting it into the command
165 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
166 * processed by the mc command line.
168 char *
169 name_quote (const char *s, int quote_percent)
171 char *ret, *d;
173 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
174 if (*s == '-') {
175 *d++ = '.';
176 *d++ = '/';
179 for (; *s; s++, d++) {
180 switch (*s) {
181 case '%':
182 if (quote_percent)
183 *d++ = '%';
184 break;
185 case '\'':
186 case '\\':
187 case '\r':
188 case '\n':
189 case '\t':
190 case '"':
191 case ';':
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 *d++ = '\\';
209 break;
210 case '~':
211 case '#':
212 if (d == ret)
213 *d++ = '\\';
214 break;
216 *d = *s;
218 *d = '\0';
219 return ret;
222 char *
223 fake_name_quote (const char *s, int quote_percent)
225 (void) quote_percent;
226 return g_strdup (s);
230 * Remove the middle part of the string to fit given length.
231 * Use "~" to show where the string was truncated.
232 * Return static buffer, no need to free() it.
234 const char *
235 name_trunc (const char *txt, size_t trunc_len)
237 return str_trunc (txt, trunc_len);
241 * path_trunc() is the same as name_trunc() above but
242 * it deletes possible password from path for security
243 * reasons.
245 const char *
246 path_trunc (const char *path, size_t trunc_len) {
247 char *secure_path = strip_password (g_strdup (path), 1);
249 const char *ret = str_trunc (secure_path, trunc_len);
250 g_free (secure_path);
252 return ret;
255 const char *
256 size_trunc (double size)
258 static char x [BUF_TINY];
259 long int divisor = 1;
260 const char *xtra = "";
262 if (size > 999999999L){
263 divisor = 1024;
264 xtra = "K";
265 if (size/divisor > 999999999L){
266 divisor = 1024*1024;
267 xtra = "M";
270 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
271 return x;
274 const char *
275 size_trunc_sep (double size)
277 static char x [60];
278 int count;
279 const char *p, *y;
280 char *d;
282 p = y = size_trunc (size);
283 p += strlen (p) - 1;
284 d = x + sizeof (x) - 1;
285 *d-- = 0;
286 while (p >= y && isalpha ((unsigned char) *p))
287 *d-- = *p--;
288 for (count = 0; p >= y; count++){
289 if (count == 3){
290 *d-- = ',';
291 count = 0;
293 *d-- = *p--;
295 d++;
296 if (*d == ',')
297 d++;
298 return d;
302 * Print file SIZE to BUFFER, but don't exceed LEN characters,
303 * not including trailing 0. BUFFER should be at least LEN+1 long.
304 * This function is called for every file on panels, so avoid
305 * floating point by any means.
307 * Units: size units (filesystem sizes are 1K blocks)
308 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
310 void
311 size_trunc_len (char *buffer, int len, off_t size, int units)
313 /* Avoid taking power for every file. */
314 static const off_t power10 [] =
315 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
316 1000000000};
317 static const char * const suffix [] =
318 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
319 int j = 0;
321 /* Don't print more than 9 digits - use suffix. */
322 if (len == 0 || len > 9)
323 len = 9;
325 for (j = units; suffix [j] != NULL; j++) {
326 if (size == 0) {
327 if (j == units) {
328 /* Empty files will print "0" even with minimal width. */
329 g_snprintf (buffer, len + 1, "0");
330 break;
333 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
334 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
335 (j > 1) ? suffix[j - 1] : "B");
336 break;
339 if (size < power10 [len - (j > 0)]) {
340 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
341 break;
344 /* Powers of 1024, with rounding. */
345 size = (size + 512) >> 10;
350 is_exe (mode_t mode)
352 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
353 return 1;
354 return 0;
357 #define ismode(n,m) ((n & m) == m)
359 const char *
360 string_perm (mode_t mode_bits)
362 static char mode[11];
364 strcpy (mode, "----------");
365 if (S_ISDIR (mode_bits))
366 mode[0] = 'd';
367 if (S_ISCHR (mode_bits))
368 mode[0] = 'c';
369 if (S_ISBLK (mode_bits))
370 mode[0] = 'b';
371 if (S_ISLNK (mode_bits))
372 mode[0] = 'l';
373 if (S_ISFIFO (mode_bits))
374 mode[0] = 'p';
375 if (S_ISNAM (mode_bits))
376 mode[0] = 'n';
377 if (S_ISSOCK (mode_bits))
378 mode[0] = 's';
379 if (S_ISDOOR (mode_bits))
380 mode[0] = 'D';
381 if (ismode (mode_bits, S_IXOTH))
382 mode[9] = 'x';
383 if (ismode (mode_bits, S_IWOTH))
384 mode[8] = 'w';
385 if (ismode (mode_bits, S_IROTH))
386 mode[7] = 'r';
387 if (ismode (mode_bits, S_IXGRP))
388 mode[6] = 'x';
389 if (ismode (mode_bits, S_IWGRP))
390 mode[5] = 'w';
391 if (ismode (mode_bits, S_IRGRP))
392 mode[4] = 'r';
393 if (ismode (mode_bits, S_IXUSR))
394 mode[3] = 'x';
395 if (ismode (mode_bits, S_IWUSR))
396 mode[2] = 'w';
397 if (ismode (mode_bits, S_IRUSR))
398 mode[1] = 'r';
399 #ifdef S_ISUID
400 if (ismode (mode_bits, S_ISUID))
401 mode[3] = (mode[3] == 'x') ? 's' : 'S';
402 #endif /* S_ISUID */
403 #ifdef S_ISGID
404 if (ismode (mode_bits, S_ISGID))
405 mode[6] = (mode[6] == 'x') ? 's' : 'S';
406 #endif /* S_ISGID */
407 #ifdef S_ISVTX
408 if (ismode (mode_bits, S_ISVTX))
409 mode[9] = (mode[9] == 'x') ? 't' : 'T';
410 #endif /* S_ISVTX */
411 return mode;
414 /* p: string which might contain an url with a password (this parameter is
415 modified in place).
416 has_prefix = 0: The first parameter is an url without a prefix
417 (user[:pass]@]machine[:port][remote-dir). Delete
418 the password.
419 has_prefix = 1: Search p for known url prefixes. If found delete
420 the password from the url.
421 Caveat: only the first url is found
423 char *
424 strip_password (char *p, int has_prefix)
426 static const struct {
427 const char *name;
428 size_t len;
429 } prefixes[] = { {"/#ftp:", 6},
430 {"ftp://", 6},
431 {"/#mc:", 5},
432 {"mc://", 5},
433 {"/#smb:", 6},
434 {"smb://", 6},
435 {"/#sh:", 5},
436 {"sh://", 5},
437 {"ssh://", 6}
439 char *at, *inner_colon, *dir;
440 size_t i;
441 char *result = p;
443 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
444 char *q;
446 if (has_prefix) {
447 if((q = strstr (p, prefixes[i].name)) == 0)
448 continue;
449 else
450 p = q + prefixes[i].len;
453 if ((dir = strchr (p, PATH_SEP)) != NULL)
454 *dir = '\0';
456 /* search for any possible user */
457 at = strrchr (p, '@');
459 if (dir)
460 *dir = PATH_SEP;
462 /* We have a username */
463 if (at) {
464 inner_colon = memchr (p, ':', at - p);
465 if (inner_colon)
466 memmove (inner_colon, at, strlen(at) + 1);
468 break;
470 return (result);
473 const char *
474 strip_home_and_password(const char *dir)
476 size_t len;
477 static char newdir [MC_MAXPATHLEN];
479 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
480 (dir[len] == PATH_SEP || dir[len] == '\0')){
481 newdir [0] = '~';
482 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
483 return newdir;
486 /* We do not strip homes in /#ftp tree, I do not like ~'s there
487 (see ftpfs.c why) */
488 g_strlcpy (newdir, dir, sizeof(newdir));
489 strip_password (newdir, 1);
490 return newdir;
493 const char *
494 extension (const char *filename)
496 const char *d = strrchr (filename, '.');
497 return (d != NULL) ? d + 1 : "";
501 exist_file (const char *name)
503 return access (name, R_OK) == 0;
507 check_for_default (const char *default_file, const char *file)
509 if (!exist_file (file)) {
510 FileOpContext *ctx;
511 off_t count = 0;
512 double bytes = 0.0;
514 if (!exist_file (default_file))
515 return -1;
517 ctx = file_op_context_new (OP_COPY);
518 file_op_context_create_ui (ctx, 0);
519 copy_file_file (ctx, default_file, file, 1, &count, &bytes, 1);
520 file_op_context_destroy (ctx);
523 return 0;
528 char *
529 load_file (const char *filename)
531 FILE *data_file;
532 struct stat s;
533 char *data;
534 long read_size;
536 if ((data_file = fopen (filename, "r")) == NULL){
537 return 0;
539 if (fstat (fileno (data_file), &s) != 0){
540 fclose (data_file);
541 return 0;
543 data = g_malloc (s.st_size+1);
544 read_size = fread (data, 1, s.st_size, data_file);
545 data [read_size] = 0;
546 fclose (data_file);
548 if (read_size > 0)
549 return data;
550 else {
551 g_free (data);
552 return 0;
556 char *
557 load_mc_home_file (const char *filename, char **allocated_filename)
559 char *hintfile_base, *hintfile;
560 char *lang;
561 char *data;
563 hintfile_base = concat_dir_and_file (mc_home, filename);
564 lang = guess_message_value ();
566 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
567 data = load_file (hintfile);
569 if (!data) {
570 g_free (hintfile);
571 g_free (hintfile_base);
572 hintfile_base = concat_dir_and_file (mc_home_alt, filename);
574 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
575 data = load_file (hintfile);
577 if (!data) {
578 /* Fall back to the two-letter language code */
579 if (lang[0] && lang[1])
580 lang[2] = 0;
581 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
582 data = load_file (hintfile);
584 if (!data) {
585 g_free (hintfile);
586 hintfile = hintfile_base;
587 data = load_file (hintfile_base);
592 g_free (lang);
594 if (hintfile != hintfile_base)
595 g_free (hintfile_base);
597 if (allocated_filename)
598 *allocated_filename = hintfile;
599 else
600 g_free (hintfile);
602 return data;
605 /* Check strftime() results. Some systems (i.e. Solaris) have different
606 short-month-name sizes for different locales */
607 size_t
608 i18n_checktimelength (void)
610 size_t length;
611 time_t testtime = time (NULL);
612 struct tm* lt = localtime(&testtime);
614 if (lt == NULL) {
615 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
616 length = str_term_width1 (_(INVALID_TIME_TEXT));
617 } else {
618 char buf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
619 size_t a, b;
621 strftime (buf, sizeof(buf) - 1, _("%b %d %H:%M"), lt);
622 a = str_term_width1 (buf);
623 strftime (buf, sizeof(buf) - 1, _("%b %d %Y"), lt);
624 b = str_term_width1 (buf);
626 length = max (a, b);
627 length = max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT)), length);
630 /* Don't handle big differences. Use standard value (email bug, please) */
631 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
632 length = STD_I18NTIMELENGTH;
634 return length;
637 const char *
638 file_date (time_t when)
640 static char timebuf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
641 time_t current_time = time ((time_t) 0);
642 static int i18n = 0;
643 static const char *fmtyear, *fmttime;
644 const char *fmt;
646 if (!i18n){
647 /* strftime() format string for old dates */
648 fmtyear = _("%b %e %Y");
649 /* strftime() format string for recent dates */
650 fmttime = _("%b %e %H:%M");
651 i18n = 1;
654 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
655 || current_time < when - 60L * 60L) /* In the future. */
656 /* The file is fairly old or in the future.
657 POSIX says the cutoff is 6 months old;
658 approximate this by 6*30 days.
659 Allow a 1 hour slop factor for what is considered "the future",
660 to allow for NFS server/client clock disagreement.
661 Show the year instead of the time of day. */
663 fmt = fmtyear;
664 else
665 fmt = fmttime;
667 FMT_LOCALTIME(timebuf, sizeof (timebuf), fmt, when);
669 return timebuf;
672 const char *
673 extract_line (const char *s, const char *top)
675 static char tmp_line [BUF_MEDIUM];
676 char *t = tmp_line;
678 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
679 *t++ = *s++;
680 *t = 0;
681 return tmp_line;
684 /* The basename routine */
685 const char *
686 x_basename (const char *s)
688 const char *where;
689 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
693 const char *
694 unix_error_string (int error_num)
696 static char buffer [BUF_LARGE];
697 #if GLIB_MAJOR_VERSION >= 2
698 gchar *strerror_currentlocale;
700 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
701 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
702 strerror_currentlocale, error_num);
703 g_free(strerror_currentlocale);
704 #else
705 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
706 g_strerror (error_num), error_num);
707 #endif
708 return buffer;
711 const char *
712 skip_separators (const char *s)
714 const char *su = s;
716 for (;*su; str_cnext_char (&su))
717 if (*su != ' ' && *su != '\t' && *su != ',') break;
719 return su;
722 const char *
723 skip_numbers (const char *s)
725 const char *su = s;
727 for (;*su; str_cnext_char (&su))
728 if (!str_isdigit (su)) break;
730 return su;
733 /* Remove all control sequences from the argument string. We define
734 * "control sequence", in a sort of pidgin BNF, as follows:
736 * control-seq = Esc non-'['
737 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
739 * This scheme works for all the terminals described in my termcap /
740 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
741 * terminals. If I hear from a single person who uses such a terminal
742 * with MC, I'll be glad to add support for it. (Dugan)
743 * Non-printable characters are also removed.
746 char *
747 strip_ctrl_codes (char *s)
749 char *w; /* Current position where the stripped data is written */
750 char *r; /* Current position where the original data is read */
751 char *n;
753 if (!s)
754 return 0;
756 for (w = s, r = s; *r; ) {
757 if (*r == ESC_CHAR) {
758 /* Skip the control sequence's arguments */ ;
759 if (*(++r) == '[') {
760 /* strchr() matches trailing binary 0 */
761 while (*(++r) && strchr ("0123456789;?", *r));
762 } else
763 if (*r == ']') {
765 * Skip xterm's OSC (Operating System Command)
766 * http://www.xfree86.org/current/ctlseqs.html
767 * OSC P s ; P t ST
768 * OSC P s ; P t BEL
770 char * new_r = r;
772 for (; *new_r; ++new_r)
774 switch (*new_r)
776 /* BEL */
777 case '\a':
778 r = new_r;
779 goto osc_out;
780 case ESC_CHAR:
781 /* ST */
782 if (*(new_r + 1) == '\\')
784 r = new_r + 1;
785 goto osc_out;
789 osc_out:;
793 * Now we are at the last character of the sequence.
794 * Skip it unless it's binary 0.
796 if (*r)
797 r++;
798 continue;
801 n = str_get_next_char (r);
802 if (str_isprint (r)) {
803 memmove (w, r, n - r);
804 w+= n - r;
806 r = n;
808 *w = 0;
809 return s;
813 #ifndef USE_VFS
814 char *
815 get_current_wd (char *buffer, int size)
817 char *p;
818 int len;
820 p = g_get_current_dir ();
821 len = strlen(p) + 1;
823 if (len > size) {
824 g_free (p);
825 return NULL;
828 memcpy (buffer, p, len);
829 g_free (p);
831 return buffer;
833 #endif /* !USE_VFS */
835 enum compression_type
836 get_compression_type (int fd)
838 unsigned char magic[16];
840 /* Read the magic signature */
841 if (mc_read (fd, (char *) magic, 4) != 4)
842 return COMPRESSION_NONE;
844 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
845 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
846 return COMPRESSION_GZIP;
849 /* PKZIP_MAGIC */
850 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
851 && magic[3] == 004) {
852 /* Read compression type */
853 mc_lseek (fd, 8, SEEK_SET);
854 if (mc_read (fd, (char *) magic, 2) != 2)
855 return COMPRESSION_NONE;
857 /* Gzip can handle only deflated (8) or stored (0) files */
858 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
859 return COMPRESSION_NONE;
861 /* Compatible with gzip */
862 return COMPRESSION_GZIP;
865 /* PACK_MAGIC and LZH_MAGIC and compress magic */
866 if (magic[0] == 037
867 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
868 /* Compatible with gzip */
869 return COMPRESSION_GZIP;
872 /* BZIP and BZIP2 files */
873 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
874 (magic[3] >= '1') && (magic[3] <= '9')) {
875 switch (magic[2]) {
876 case '0':
877 return COMPRESSION_BZIP;
878 case 'h':
879 return COMPRESSION_BZIP2;
883 /* LZMA files; both LZMA_Alone and LZMA utils formats. The LZMA_Alone
884 * format is used by the LZMA_Alone tool from LZMA SDK. The LZMA utils
885 * format is the default format of LZMA utils 4.32.1 and later. */
886 if (magic[0] < 0xE1 || (magic[0] == 0xFF && magic[1] == 'L' &&
887 magic[2] == 'Z' && magic[3] == 'M')) {
888 if (mc_read (fd, (char *) magic + 4, 9) == 9) {
889 /* LZMA utils format */
890 if (magic[0] == 0xFF && magic[4] == 'A' && magic[5] == 0x00)
891 return COMPRESSION_LZMA;
892 /* The LZMA_Alone format has no magic bytes, thus we
893 * need to play a wizard. This can give false positives,
894 * thus the detection below should be removed when
895 * the newer LZMA utils format has got popular. */
896 if (magic[0] < 0xE1 && magic[4] < 0x20 &&
897 ((magic[10] == 0x00 && magic[11] == 0x00 &&
898 magic[12] == 0x00) ||
899 (magic[5] == 0xFF && magic[6] == 0xFF &&
900 magic[7] == 0xFF && magic[8] == 0xFF &&
901 magic[9] == 0xFF && magic[10] == 0xFF &&
902 magic[11] == 0xFF && magic[12] == 0xFF)))
903 return COMPRESSION_LZMA;
907 /* XZ compression magic */
908 if (magic[0] == 0xFD
909 && magic[1] == 0x37 && magic[2] == 0x7A && magic[3] == 0x58) {
910 if (mc_read (fd, (char *) magic + 4, 2) == 2) {
911 if (magic[4] == 0x5A && magic[5] == 0x00) {
912 return COMPRESSION_XZ;
917 return 0;
920 const char *
921 decompress_extension (int type)
923 switch (type){
924 case COMPRESSION_GZIP: return "#ugz";
925 case COMPRESSION_BZIP: return "#ubz";
926 case COMPRESSION_BZIP2: return "#ubz2";
927 case COMPRESSION_LZMA: return "#ulzma";
928 case COMPRESSION_XZ: return "#uxz";
930 /* Should never reach this place */
931 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
932 return 0;
935 /* Hooks */
936 void
937 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
939 Hook *new_hook = g_new (Hook, 1);
941 new_hook->hook_fn = hook_fn;
942 new_hook->next = *hook_list;
943 new_hook->hook_data = data;
945 *hook_list = new_hook;
948 void
949 execute_hooks (Hook *hook_list)
951 Hook *new_hook = 0;
952 Hook *p;
954 /* We copy the hook list first so tahat we let the hook
955 * function call delete_hook
958 while (hook_list){
959 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
960 hook_list = hook_list->next;
962 p = new_hook;
964 while (new_hook){
965 (*new_hook->hook_fn)(new_hook->hook_data);
966 new_hook = new_hook->next;
969 for (hook_list = p; hook_list;){
970 p = hook_list;
971 hook_list = hook_list->next;
972 g_free (p);
976 void
977 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
979 Hook *current, *new_list, *next;
981 new_list = 0;
983 for (current = *hook_list; current; current = next){
984 next = current->next;
985 if (current->hook_fn == hook_fn)
986 g_free (current);
987 else
988 add_hook (&new_list, current->hook_fn, current->hook_data);
990 *hook_list = new_list;
994 hook_present (Hook *hook_list, void (*hook_fn)(void *))
996 Hook *p;
998 for (p = hook_list; p; p = p->next)
999 if (p->hook_fn == hook_fn)
1000 return 1;
1001 return 0;
1004 void
1005 wipe_password (char *passwd)
1007 char *p = passwd;
1009 if (!p)
1010 return;
1011 for (;*p ; p++)
1012 *p = 0;
1013 g_free (passwd);
1016 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1017 /* Returns a newly allocated string */
1018 char *
1019 convert_controls (const char *p)
1021 char *valcopy = g_strdup (p);
1022 char *q;
1024 /* Parse the escape special character */
1025 for (q = valcopy; *p;){
1026 if (*p == '\\'){
1027 p++;
1028 if ((*p == 'e') || (*p == 'E')){
1029 p++;
1030 *q++ = ESC_CHAR;
1032 } else {
1033 if (*p == '^'){
1034 p++;
1035 if (*p == '^')
1036 *q++ = *p++;
1037 else {
1038 char c = (*p | 0x20);
1039 if (c >= 'a' && c <= 'z') {
1040 *q++ = c - 'a' + 1;
1041 p++;
1042 } else if (*p)
1043 p++;
1045 } else
1046 *q++ = *p++;
1049 *q = 0;
1050 return valcopy;
1053 static char *
1054 resolve_symlinks (const char *path)
1056 char *buf, *buf2, *q, *r, c;
1057 int len;
1058 struct stat mybuf;
1059 const char *p;
1061 if (*path != PATH_SEP)
1062 return NULL;
1063 r = buf = g_malloc (MC_MAXPATHLEN);
1064 buf2 = g_malloc (MC_MAXPATHLEN);
1065 *r++ = PATH_SEP;
1066 *r = 0;
1067 p = path;
1068 for (;;) {
1069 q = strchr (p + 1, PATH_SEP);
1070 if (!q) {
1071 q = strchr (p + 1, 0);
1072 if (q == p + 1)
1073 break;
1075 c = *q;
1076 *q = 0;
1077 if (mc_lstat (path, &mybuf) < 0) {
1078 g_free (buf);
1079 g_free (buf2);
1080 *q = c;
1081 return NULL;
1083 if (!S_ISLNK (mybuf.st_mode))
1084 strcpy (r, p + 1);
1085 else {
1086 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1087 if (len < 0) {
1088 g_free (buf);
1089 g_free (buf2);
1090 *q = c;
1091 return NULL;
1093 buf2 [len] = 0;
1094 if (*buf2 == PATH_SEP)
1095 strcpy (buf, buf2);
1096 else
1097 strcpy (r, buf2);
1099 canonicalize_pathname (buf);
1100 r = strchr (buf, 0);
1101 if (!*r || *(r - 1) != PATH_SEP) {
1102 *r++ = PATH_SEP;
1103 *r = 0;
1105 *q = c;
1106 p = q;
1107 if (!c)
1108 break;
1110 if (!*buf)
1111 strcpy (buf, PATH_SEP_STR);
1112 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1113 *(r - 1) = 0;
1114 g_free (buf2);
1115 return buf;
1118 /* Finds out a relative path from first to second, i.e. goes as many ..
1119 * as needed up in first and then goes down using second */
1120 char *
1121 diff_two_paths (const char *first, const char *second)
1123 char *p, *q, *r, *s, *buf = NULL;
1124 int i, j, prevlen = -1, currlen;
1125 char *my_first = NULL, *my_second = NULL;
1127 my_first = resolve_symlinks (first);
1128 if (my_first == NULL)
1129 return NULL;
1130 my_second = resolve_symlinks (second);
1131 if (my_second == NULL) {
1132 g_free (my_first);
1133 return NULL;
1135 for (j = 0; j < 2; j++) {
1136 p = my_first;
1137 q = my_second;
1138 for (;;) {
1139 r = strchr (p, PATH_SEP);
1140 s = strchr (q, PATH_SEP);
1141 if (!r || !s)
1142 break;
1143 *r = 0; *s = 0;
1144 if (strcmp (p, q)) {
1145 *r = PATH_SEP; *s = PATH_SEP;
1146 break;
1147 } else {
1148 *r = PATH_SEP; *s = PATH_SEP;
1150 p = r + 1;
1151 q = s + 1;
1153 p--;
1154 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1155 currlen = (i + 1) * 3 + strlen (q) + 1;
1156 if (j) {
1157 if (currlen < prevlen)
1158 g_free (buf);
1159 else {
1160 g_free (my_first);
1161 g_free (my_second);
1162 return buf;
1165 p = buf = g_malloc (currlen);
1166 prevlen = currlen;
1167 for (; i >= 0; i--, p += 3)
1168 strcpy (p, "../");
1169 strcpy (p, q);
1171 g_free (my_first);
1172 g_free (my_second);
1173 return buf;
1176 /* If filename is NULL, then we just append PATH_SEP to the dir */
1177 char *
1178 concat_dir_and_file (const char *dir, const char *file)
1180 int i = strlen (dir);
1182 if (dir [i-1] == PATH_SEP)
1183 return g_strconcat (dir, file, (char *) NULL);
1184 else
1185 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1188 /* Append text to GList, remove all entries with the same text */
1189 GList *
1190 list_append_unique (GList *list, char *text)
1192 GList *link, *newlink, *tmp;
1195 * Go to the last position and traverse the list backwards
1196 * starting from the second last entry to make sure that we
1197 * are not removing the current link.
1199 list = g_list_append (list, text);
1200 list = g_list_last (list);
1201 link = g_list_previous (list);
1203 while (link) {
1204 newlink = g_list_previous (link);
1205 if (!strcmp ((char *) link->data, text)) {
1206 g_free (link->data);
1207 tmp = g_list_remove_link (list, link);
1208 g_list_free_1 (link);
1210 link = newlink;
1213 return list;
1216 /* Following code heavily borrows from libiberty, mkstemps.c */
1218 /* Number of attempts to create a temporary file */
1219 #ifndef TMP_MAX
1220 #define TMP_MAX 16384
1221 #endif /* !TMP_MAX */
1224 * Arguments:
1225 * pname (output) - pointer to the name of the temp file (needs g_free).
1226 * NULL if the function fails.
1227 * prefix - part of the filename before the random part.
1228 * Prepend $TMPDIR or /tmp if there are no path separators.
1229 * suffix - if not NULL, part of the filename after the random part.
1231 * Result:
1232 * handle of the open file or -1 if couldn't open any.
1235 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1237 static const char letters[]
1238 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1239 static unsigned long value;
1240 struct timeval tv;
1241 char *tmpbase;
1242 char *tmpname;
1243 char *XXXXXX;
1244 int count;
1246 if (strchr (prefix, PATH_SEP) == NULL) {
1247 /* Add prefix first to find the position of XXXXXX */
1248 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1249 } else {
1250 tmpbase = g_strdup (prefix);
1253 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1254 *pname = tmpname;
1255 XXXXXX = &tmpname[strlen (tmpbase)];
1256 g_free (tmpbase);
1258 /* Get some more or less random data. */
1259 gettimeofday (&tv, NULL);
1260 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1262 for (count = 0; count < TMP_MAX; ++count) {
1263 unsigned long v = value;
1264 int fd;
1266 /* Fill in the random bits. */
1267 XXXXXX[0] = letters[v % 62];
1268 v /= 62;
1269 XXXXXX[1] = letters[v % 62];
1270 v /= 62;
1271 XXXXXX[2] = letters[v % 62];
1272 v /= 62;
1273 XXXXXX[3] = letters[v % 62];
1274 v /= 62;
1275 XXXXXX[4] = letters[v % 62];
1276 v /= 62;
1277 XXXXXX[5] = letters[v % 62];
1279 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1280 S_IRUSR | S_IWUSR);
1281 if (fd >= 0) {
1282 /* Successfully created. */
1283 return fd;
1286 /* This is a random value. It is only necessary that the next
1287 TMP_MAX values generated by adding 7777 to VALUE are different
1288 with (module 2^32). */
1289 value += 7777;
1292 /* Unsuccessful. Free the filename. */
1293 g_free (tmpname);
1294 *pname = NULL;
1296 return -1;
1300 * Read and restore position for the given filename.
1301 * If there is no stored data, return line 1 and col 0.
1303 void
1304 load_file_position (const char *filename, long *line, long *column)
1306 char *fn;
1307 FILE *f;
1308 char buf[MC_MAXPATHLEN + 20];
1309 int len;
1311 /* defaults */
1312 *line = 1;
1313 *column = 0;
1315 /* open file with positions */
1316 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1317 f = fopen (fn, "r");
1318 g_free (fn);
1319 if (!f)
1320 return;
1322 len = strlen (filename);
1324 while (fgets (buf, sizeof (buf), f)) {
1325 const char *p;
1327 /* check if the filename matches the beginning of string */
1328 if (strncmp (buf, filename, len) != 0)
1329 continue;
1331 /* followed by single space */
1332 if (buf[len] != ' ')
1333 continue;
1335 /* and string without spaces */
1336 p = &buf[len + 1];
1337 if (strchr (p, ' '))
1338 continue;
1340 *line = strtol(p, const_cast(char **, &p), 10);
1341 if (*p == ';') {
1342 *column = strtol(p+1, const_cast(char **, &p), 10);
1343 if (*p != '\n')
1344 *column = 0;
1345 } else
1346 *line = 1;
1348 fclose (f);
1351 /* Save position for the given file */
1352 void
1353 save_file_position (const char *filename, long line, long column)
1355 char *tmp, *fn;
1356 FILE *f, *t;
1357 char buf[MC_MAXPATHLEN + 20];
1358 int i = 1;
1359 int len;
1361 len = strlen (filename);
1363 tmp = concat_dir_and_file (home_dir, MC_FILEPOS_TMP);
1364 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1366 /* open temporary file */
1367 t = fopen (tmp, "w");
1368 if (!t) {
1369 g_free (tmp);
1370 g_free (fn);
1371 return;
1374 /* put the new record */
1375 if (line != 1 || column != 0) {
1376 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1379 /* copy records from the old file */
1380 f = fopen (fn, "r");
1381 if (f) {
1382 while (fgets (buf, sizeof (buf), f)) {
1383 /* Skip entries for the current filename */
1384 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1385 && !strchr (&buf[len + 1], ' '))
1386 continue;
1388 fprintf (t, "%s", buf);
1389 if (++i > MC_FILEPOS_ENTRIES)
1390 break;
1392 fclose (f);
1395 fclose (t);
1396 rename (tmp, fn);
1397 g_free (tmp);
1398 g_free (fn);
1401 extern const char *
1402 cstrcasestr (const char *haystack, const char *needle)
1404 char *nee = str_create_search_needle (needle, 0);
1405 const char *result = str_search_first (haystack, nee, 0);
1406 str_release_search_needle (nee, 0);
1407 return result;
1410 const char *
1411 cstrstr (const char *haystack, const char *needle)
1413 return strstr(haystack, needle);
1416 extern char *
1417 str_unconst (const char *s)
1419 return (char *) s;
1422 #define ASCII_A (0x40 + 1)
1423 #define ASCII_Z (0x40 + 26)
1424 #define ASCII_a (0x60 + 1)
1425 #define ASCII_z (0x60 + 26)
1427 extern int
1428 ascii_alpha_to_cntrl (int ch)
1430 if ((ch >= ASCII_A && ch <= ASCII_Z)
1431 || (ch >= ASCII_a && ch <= ASCII_z)) {
1432 ch &= 0x1f;
1434 return ch;
1437 const char *
1438 Q_ (const char *s)
1440 const char *result, *sep;
1442 result = _(s);
1443 sep = strchr(result, '|');
1444 return (sep != NULL) ? sep + 1 : result;