Update base version to 4.6.1.
[midnight-commander.git] / src / util.c
blob3e7cd37e41eda729867296088a8883016447810d
1 /* Various utilities
2 Copyright (C) 1994, 1995, 1996 the Free Software Foundation.
3 Written 1994, 1995, 1996 by:
4 Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
5 Jakub Jelinek, Mauricio Plaza.
7 The file_date routine is mostly from GNU's fileutils package,
8 written by Richard Stallman and David MacKenzie.
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
24 #include <config.h>
26 #include <ctype.h>
27 #include <limits.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <unistd.h>
37 #include "global.h"
38 #include "profile.h"
39 #include "main.h" /* mc_home */
40 #include "cmd.h" /* guess_message_value */
41 #include "mountlist.h"
42 #include "win.h" /* xterm_flag */
44 #ifdef HAVE_CHARSET
45 #include "charsets.h"
46 #endif
48 static const char app_text [] = "Midnight-Commander";
49 int easy_patterns = 1;
51 extern void str_replace(char *s, char from, char to)
53 for (; *s != '\0'; s++) {
54 if (*s == from)
55 *s = to;
59 static inline int
60 is_7bit_printable (unsigned char c)
62 return (c > 31 && c < 127);
65 static inline int
66 is_iso_printable (unsigned char c)
68 return ((c > 31 && c < 127) || c >= 160);
71 static inline int
72 is_8bit_printable (unsigned char c)
74 /* "Full 8 bits output" doesn't work on xterm */
75 if (xterm_flag)
76 return is_iso_printable (c);
78 return (c > 31 && c != 127 && c != 155);
81 int
82 is_printable (int c)
84 c &= 0xff;
86 #ifdef HAVE_CHARSET
87 /* "Display bits" is ignored, since the user controls the output
88 by setting the output codepage */
89 return is_8bit_printable (c);
90 #else
91 if (!eight_bit_clean)
92 return is_7bit_printable (c);
94 if (full_eight_bits) {
95 return is_8bit_printable (c);
96 } else
97 return is_iso_printable (c);
98 #endif /* !HAVE_CHARSET */
101 /* Calculates the message dimensions (lines and columns) */
102 void msglen (const char *text, int *lines, int *columns)
104 int nlines = 1; /* even the empty string takes one line */
105 int ncolumns = 0;
106 int colindex = 0;
108 for (; *text != '\0'; text++) {
109 if (*text == '\n') {
110 nlines++;
111 colindex = 0;
112 } else {
113 colindex++;
114 if (colindex > ncolumns)
115 ncolumns = colindex;
119 *lines = nlines;
120 *columns = ncolumns;
124 * Copy from s to d, and trim the beginning if necessary, and prepend
125 * "..." in this case. The destination string can have at most len
126 * bytes, not counting trailing 0.
128 char *
129 trim (const char *s, char *d, int len)
131 int source_len;
133 /* Sanity check */
134 len = max (len, 0);
136 source_len = strlen (s);
137 if (source_len > len) {
138 /* Cannot fit the whole line */
139 if (len <= 3) {
140 /* We only have room for the dots */
141 memset (d, '.', len);
142 d[len] = 0;
143 return d;
144 } else {
145 /* Begin with ... and add the rest of the source string */
146 memset (d, '.', 3);
147 strcpy (d + 3, s + 3 + source_len - len);
149 } else
150 /* We can copy the whole line */
151 strcpy (d, s);
152 return d;
156 * Quote the filename for the purpose of inserting it into the command
157 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
158 * processed by the mc command line.
160 char *
161 name_quote (const char *s, int quote_percent)
163 char *ret, *d;
165 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
166 if (*s == '-') {
167 *d++ = '.';
168 *d++ = '/';
171 for (; *s; s++, d++) {
172 switch (*s) {
173 case '%':
174 if (quote_percent)
175 *d++ = '%';
176 break;
177 case '\'':
178 case '\\':
179 case '\r':
180 case '\n':
181 case '\t':
182 case '"':
183 case ';':
184 case ' ':
185 case '?':
186 case '|':
187 case '[':
188 case ']':
189 case '{':
190 case '}':
191 case '<':
192 case '>':
193 case '`':
194 case '!':
195 case '$':
196 case '&':
197 case '*':
198 case '(':
199 case ')':
200 *d++ = '\\';
201 break;
202 case '~':
203 case '#':
204 if (d == ret)
205 *d++ = '\\';
206 break;
208 *d = *s;
210 *d = '\0';
211 return ret;
214 char *
215 fake_name_quote (const char *s, int quote_percent)
217 (void) quote_percent;
218 return g_strdup (s);
222 * Remove the middle part of the string to fit given length.
223 * Use "~" to show where the string was truncated.
224 * Return static buffer, no need to free() it.
226 const char *
227 name_trunc (const char *txt, int trunc_len)
229 static char x[MC_MAXPATHLEN + MC_MAXPATHLEN];
230 int txt_len;
231 char *p;
233 if ((size_t) trunc_len > sizeof (x) - 1) {
234 trunc_len = sizeof (x) - 1;
236 txt_len = strlen (txt);
237 if (txt_len <= trunc_len) {
238 strcpy (x, txt);
239 } else {
240 int y = (trunc_len / 2) + (trunc_len % 2);
241 strncpy (x, txt, y);
242 strncpy (x + y, txt + txt_len - (trunc_len / 2), trunc_len / 2);
243 x[y] = '~';
245 x[trunc_len] = 0;
246 for (p = x; *p; p++)
247 if (!is_printable (*p))
248 *p = '?';
249 return x;
253 * path_trunc() is the same as name_trunc() above but
254 * it deletes possible password from path for security
255 * reasons.
257 const char *
258 path_trunc (const char *path, int trunc_len) {
259 const char *ret;
260 char *secure_path = strip_password (g_strdup (path), 1);
262 ret = name_trunc (secure_path, trunc_len);
263 g_free (secure_path);
265 return ret;
268 const char *size_trunc (double size)
270 static char x [BUF_TINY];
271 long int divisor = 1;
272 const char *xtra = "";
274 if (size > 999999999L){
275 divisor = 1024;
276 xtra = "K";
277 if (size/divisor > 999999999L){
278 divisor = 1024*1024;
279 xtra = "M";
282 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
283 return x;
286 const char *size_trunc_sep (double size)
288 static char x [60];
289 int count;
290 const char *p, *y;
291 char *d;
293 p = y = size_trunc (size);
294 p += strlen (p) - 1;
295 d = x + sizeof (x) - 1;
296 *d-- = 0;
297 while (p >= y && isalpha ((unsigned char) *p))
298 *d-- = *p--;
299 for (count = 0; p >= y; count++){
300 if (count == 3){
301 *d-- = ',';
302 count = 0;
304 *d-- = *p--;
306 d++;
307 if (*d == ',')
308 d++;
309 return d;
313 * Print file SIZE to BUFFER, but don't exceed LEN characters,
314 * not including trailing 0. BUFFER should be at least LEN+1 long.
315 * This function is called for every file on panels, so avoid
316 * floating point by any means.
318 * Units: size units (filesystem sizes are 1K blocks)
319 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
321 void
322 size_trunc_len (char *buffer, int len, off_t size, int units)
324 /* Avoid taking power for every file. */
325 static const off_t power10 [] =
326 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
327 1000000000};
328 static const char * const suffix [] =
329 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
330 int j = 0;
332 /* Don't print more than 9 digits - use suffix. */
333 if (len == 0 || len > 9)
334 len = 9;
336 for (j = units; suffix [j] != NULL; j++) {
337 if (size == 0) {
338 if (j == units) {
339 /* Empty files will print "0" even with minimal width. */
340 g_snprintf (buffer, len + 1, "0");
341 break;
344 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
345 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
346 (j > 1) ? suffix[j - 1] : "B");
347 break;
350 if (size < power10 [len - (j > 0)]) {
351 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
352 break;
355 /* Powers of 1024, with rounding. */
356 size = (size + 512) >> 10;
360 int is_exe (mode_t mode)
362 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
363 return 1;
364 return 0;
367 #define ismode(n,m) ((n & m) == m)
369 const char *
370 string_perm (mode_t mode_bits)
372 static char mode[11];
374 strcpy (mode, "----------");
375 if (S_ISDIR (mode_bits))
376 mode[0] = 'd';
377 if (S_ISCHR (mode_bits))
378 mode[0] = 'c';
379 if (S_ISBLK (mode_bits))
380 mode[0] = 'b';
381 if (S_ISLNK (mode_bits))
382 mode[0] = 'l';
383 if (S_ISFIFO (mode_bits))
384 mode[0] = 'p';
385 if (S_ISNAM (mode_bits))
386 mode[0] = 'n';
387 if (S_ISSOCK (mode_bits))
388 mode[0] = 's';
389 if (S_ISDOOR (mode_bits))
390 mode[0] = 'D';
391 if (ismode (mode_bits, S_IXOTH))
392 mode[9] = 'x';
393 if (ismode (mode_bits, S_IWOTH))
394 mode[8] = 'w';
395 if (ismode (mode_bits, S_IROTH))
396 mode[7] = 'r';
397 if (ismode (mode_bits, S_IXGRP))
398 mode[6] = 'x';
399 if (ismode (mode_bits, S_IWGRP))
400 mode[5] = 'w';
401 if (ismode (mode_bits, S_IRGRP))
402 mode[4] = 'r';
403 if (ismode (mode_bits, S_IXUSR))
404 mode[3] = 'x';
405 if (ismode (mode_bits, S_IWUSR))
406 mode[2] = 'w';
407 if (ismode (mode_bits, S_IRUSR))
408 mode[1] = 'r';
409 #ifdef S_ISUID
410 if (ismode (mode_bits, S_ISUID))
411 mode[3] = (mode[3] == 'x') ? 's' : 'S';
412 #endif /* S_ISUID */
413 #ifdef S_ISGID
414 if (ismode (mode_bits, S_ISGID))
415 mode[6] = (mode[6] == 'x') ? 's' : 'S';
416 #endif /* S_ISGID */
417 #ifdef S_ISVTX
418 if (ismode (mode_bits, S_ISVTX))
419 mode[9] = (mode[9] == 'x') ? 't' : 'T';
420 #endif /* S_ISVTX */
421 return mode;
424 /* p: string which might contain an url with a password (this parameter is
425 modified in place).
426 has_prefix = 0: The first parameter is an url without a prefix
427 (user[:pass]@]machine[:port][remote-dir). Delete
428 the password.
429 has_prefix = 1: Search p for known url prefixes. If found delete
430 the password from the url.
431 Caveat: only the first url is found
433 char *
434 strip_password (char *p, int has_prefix)
436 static const struct {
437 const char *name;
438 size_t len;
439 } prefixes[] = { {"/#ftp:", 6},
440 {"ftp://", 6},
441 {"/#mc:", 5},
442 {"mc://", 5},
443 {"/#smb:", 6},
444 {"smb://", 6},
445 {"/#sh:", 5},
446 {"sh://", 5},
447 {"ssh://", 6}
449 char *at, *inner_colon, *dir;
450 size_t i;
451 char *result = p;
453 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
454 char *q;
456 if (has_prefix) {
457 if((q = strstr (p, prefixes[i].name)) == 0)
458 continue;
459 else
460 p = q + prefixes[i].len;
463 if ((dir = strchr (p, PATH_SEP)) != NULL)
464 *dir = '\0';
466 /* search for any possible user */
467 at = strrchr (p, '@');
469 if (dir)
470 *dir = PATH_SEP;
472 /* We have a username */
473 if (at) {
474 inner_colon = memchr (p, ':', at - p);
475 if (inner_colon)
476 memmove (inner_colon, at, strlen(at) + 1);
478 break;
480 return (result);
483 const char *strip_home_and_password(const char *dir)
485 size_t len;
486 static char newdir [MC_MAXPATHLEN];
488 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
489 (dir[len] == PATH_SEP || dir[len] == '\0')){
490 newdir [0] = '~';
491 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
492 return newdir;
495 /* We do not strip homes in /#ftp tree, I do not like ~'s there
496 (see ftpfs.c why) */
497 g_strlcpy (newdir, dir, sizeof(newdir));
498 strip_password (newdir, 1);
499 return newdir;
502 static char *maybe_start_group (char *d, int do_group, int *was_wildcard)
504 if (!do_group)
505 return d;
506 if (*was_wildcard)
507 return d;
508 *was_wildcard = 1;
509 *d++ = '\\';
510 *d++ = '(';
511 return d;
514 static char *maybe_end_group (char *d, int do_group, int *was_wildcard)
516 if (!do_group)
517 return d;
518 if (!*was_wildcard)
519 return d;
520 *was_wildcard = 0;
521 *d++ = '\\';
522 *d++ = ')';
523 return d;
526 /* If shell patterns are on converts a shell pattern to a regular
527 expression. Called by regexp_match and mask_rename. */
528 /* Shouldn't we support [a-fw] type wildcards as well ?? */
529 char *convert_pattern (const char *pattern, int match_type, int do_group)
531 char *d;
532 char *new_pattern;
533 int was_wildcard = 0;
534 const char *s;
536 if ((match_type != match_regex) && easy_patterns){
537 new_pattern = g_malloc (MC_MAXPATHLEN);
538 d = new_pattern;
539 if (match_type == match_file)
540 *d++ = '^';
541 for (s = pattern; *s; s++, d++){
542 switch (*s){
543 case '*':
544 d = maybe_start_group (d, do_group, &was_wildcard);
545 *d++ = '.';
546 *d = '*';
547 break;
549 case '?':
550 d = maybe_start_group (d, do_group, &was_wildcard);
551 *d = '.';
552 break;
554 case '.':
555 d = maybe_end_group (d, do_group, &was_wildcard);
556 *d++ = '\\';
557 *d = '.';
558 break;
560 default:
561 d = maybe_end_group (d, do_group, &was_wildcard);
562 *d = *s;
563 break;
566 d = maybe_end_group (d, do_group, &was_wildcard);
567 if (match_type == match_file)
568 *d++ = '$';
569 *d = 0;
570 return new_pattern;
571 } else
572 return g_strdup (pattern);
575 int regexp_match (const char *pattern, const char *string, int match_type)
577 static regex_t r;
578 static char *old_pattern = NULL;
579 static int old_type;
580 int rval;
581 char *my_pattern;
583 if (!old_pattern || STRCOMP (old_pattern, pattern) || old_type != match_type){
584 if (old_pattern){
585 regfree (&r);
586 g_free (old_pattern);
587 old_pattern = NULL;
589 my_pattern = convert_pattern (pattern, match_type, 0);
590 if (regcomp (&r, my_pattern, REG_EXTENDED|REG_NOSUB|MC_ARCH_FLAGS)) {
591 g_free (my_pattern);
592 return -1;
594 old_pattern = my_pattern;
595 old_type = match_type;
597 rval = !regexec (&r, string, 0, NULL, 0);
598 return rval;
601 const char *extension (const char *filename)
603 const char *d = strrchr (filename, '.');
604 return (d != NULL) ? d + 1 : "";
607 int get_int (const char *file, const char *key, int def)
609 return GetPrivateProfileInt (app_text, key, def, file);
612 int set_int (const char *file, const char *key, int value)
614 char buffer [BUF_TINY];
616 g_snprintf (buffer, sizeof (buffer), "%d", value);
617 return WritePrivateProfileString (app_text, key, buffer, file);
620 int exist_file (const char *name)
622 return access (name, R_OK) == 0;
625 char *load_file (const char *filename)
627 FILE *data_file;
628 struct stat s;
629 char *data;
630 long read_size;
632 if ((data_file = fopen (filename, "r")) == NULL){
633 return 0;
635 if (fstat (fileno (data_file), &s) != 0){
636 fclose (data_file);
637 return 0;
639 data = g_malloc (s.st_size+1);
640 read_size = fread (data, 1, s.st_size, data_file);
641 data [read_size] = 0;
642 fclose (data_file);
644 if (read_size > 0)
645 return data;
646 else {
647 g_free (data);
648 return 0;
652 char *
653 load_mc_home_file (const char *filename, char **allocated_filename)
655 char *hintfile_base, *hintfile;
656 char *lang;
657 char *data;
659 hintfile_base = concat_dir_and_file (mc_home, filename);
660 lang = guess_message_value ();
662 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
663 data = load_file (hintfile);
665 if (!data) {
666 g_free (hintfile);
667 /* Fall back to the two-letter language code */
668 if (lang[0] && lang[1])
669 lang[2] = 0;
670 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
671 data = load_file (hintfile);
673 if (!data) {
674 g_free (hintfile);
675 hintfile = hintfile_base;
676 data = load_file (hintfile_base);
680 g_free (lang);
682 if (hintfile != hintfile_base)
683 g_free (hintfile_base);
685 if (allocated_filename)
686 *allocated_filename = hintfile;
687 else
688 g_free (hintfile);
690 return data;
693 /* Check strftime() results. Some systems (i.e. Solaris) have different
694 short-month-name sizes for different locales */
695 size_t i18n_checktimelength (void)
697 size_t length, a, b;
698 char buf [MAX_I18NTIMELENGTH + 1];
699 time_t testtime = time (NULL);
701 a = strftime (buf, sizeof(buf)-1, _("%b %e %H:%M"), localtime(&testtime));
702 b = strftime (buf, sizeof(buf)-1, _("%b %e %Y"), localtime(&testtime));
704 length = max (a, b);
706 /* Don't handle big differences. Use standard value (email bug, please) */
707 if ( length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH )
708 length = STD_I18NTIMELENGTH;
710 return length;
713 const char *file_date (time_t when)
715 static char timebuf [MAX_I18NTIMELENGTH + 1];
716 time_t current_time = time ((time_t) 0);
717 static size_t i18n_timelength = 0;
718 static const char *fmtyear, *fmttime;
719 const char *fmt;
721 if (i18n_timelength == 0){
722 i18n_timelength = i18n_checktimelength() + 1;
724 /* strftime() format string for old dates */
725 fmtyear = _("%b %e %Y");
726 /* strftime() format string for recent dates */
727 fmttime = _("%b %e %H:%M");
730 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
731 || current_time < when - 60L * 60L) /* In the future. */
732 /* The file is fairly old or in the future.
733 POSIX says the cutoff is 6 months old;
734 approximate this by 6*30 days.
735 Allow a 1 hour slop factor for what is considered "the future",
736 to allow for NFS server/client clock disagreement.
737 Show the year instead of the time of day. */
739 fmt = fmtyear;
740 else
741 fmt = fmttime;
743 strftime (timebuf, i18n_timelength, fmt, localtime(&when));
744 return timebuf;
747 const char *extract_line (const char *s, const char *top)
749 static char tmp_line [BUF_MEDIUM];
750 char *t = tmp_line;
752 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
753 *t++ = *s++;
754 *t = 0;
755 return tmp_line;
758 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
759 const char * _icase_search (const char *text, const char *data, int *lng)
761 const char *d = text;
762 const char *e = data;
763 int dlng = 0;
765 if (lng)
766 *lng = 0;
767 for (;*e; e++) {
768 while (*(e+1) == '\b' && *(e+2)) {
769 e += 2;
770 dlng += 2;
772 if (toupper((unsigned char) *d) == toupper((unsigned char) *e))
773 d++;
774 else {
775 e -= d - text;
776 d = text;
777 dlng = 0;
779 if (!*d) {
780 if (lng)
781 *lng = strlen (text) + dlng;
782 return e+1;
785 return 0;
788 /* The basename routine */
789 const char *x_basename (const char *s)
791 const char *where;
792 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
796 const char *unix_error_string (int error_num)
798 static char buffer [BUF_LARGE];
799 #if GLIB_MAJOR_VERSION >= 2
800 gchar *strerror_currentlocale;
802 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
803 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
804 strerror_currentlocale, error_num);
805 g_free(strerror_currentlocale);
806 #else
807 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
808 g_strerror (error_num), error_num);
809 #endif
810 return buffer;
813 const char *skip_separators (const char *s)
815 for (;*s; s++)
816 if (*s != ' ' && *s != '\t' && *s != ',')
817 break;
818 return s;
821 const char *skip_numbers (const char *s)
823 for (;*s; s++)
824 if (!isdigit ((unsigned char) *s))
825 break;
826 return s;
829 /* Remove all control sequences from the argument string. We define
830 * "control sequence", in a sort of pidgin BNF, as follows:
832 * control-seq = Esc non-'['
833 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
835 * This scheme works for all the terminals described in my termcap /
836 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
837 * terminals. If I hear from a single person who uses such a terminal
838 * with MC, I'll be glad to add support for it. (Dugan)
839 * Non-printable characters are also removed.
842 char *strip_ctrl_codes (char *s)
844 char *w; /* Current position where the stripped data is written */
845 char *r; /* Current position where the original data is read */
847 if (!s)
848 return 0;
850 for (w = s, r = s; *r; ) {
851 if (*r == ESC_CHAR) {
852 /* Skip the control sequence's arguments */ ;
853 if (*(++r) == '[') {
854 /* strchr() matches trailing binary 0 */
855 while (*(++r) && strchr ("0123456789;?", *r));
859 * Now we are at the last character of the sequence.
860 * Skip it unless it's binary 0.
862 if (*r)
863 r++;
864 continue;
867 if (is_printable(*r))
868 *w++ = *r;
869 ++r;
871 *w = 0;
872 return s;
876 #ifndef USE_VFS
877 char *get_current_wd (char *buffer, int size)
879 char *p;
880 int len;
882 p = g_get_current_dir ();
883 len = strlen(p) + 1;
885 if (len > size) {
886 g_free (p);
887 return NULL;
890 memcpy (buffer, p, len);
891 g_free (p);
893 return buffer;
895 #endif /* !USE_VFS */
897 enum compression_type
898 get_compression_type (int fd)
900 unsigned char magic[4];
902 /* Read the magic signature */
903 if (mc_read (fd, (char *) magic, 4) != 4)
904 return COMPRESSION_NONE;
906 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
907 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
908 return COMPRESSION_GZIP;
911 /* PKZIP_MAGIC */
912 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
913 && magic[3] == 004) {
914 /* Read compression type */
915 mc_lseek (fd, 8, SEEK_SET);
916 if (mc_read (fd, (char *) magic, 2) != 2)
917 return COMPRESSION_NONE;
919 /* Gzip can handle only deflated (8) or stored (0) files */
920 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
921 return COMPRESSION_NONE;
923 /* Compatible with gzip */
924 return COMPRESSION_GZIP;
927 /* PACK_MAGIC and LZH_MAGIC and compress magic */
928 if (magic[0] == 037
929 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
930 /* Compatible with gzip */
931 return COMPRESSION_GZIP;
934 /* BZIP and BZIP2 files */
935 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
936 (magic[3] >= '1') && (magic[3] <= '9')) {
937 switch (magic[2]) {
938 case '0':
939 return COMPRESSION_BZIP;
940 case 'h':
941 return COMPRESSION_BZIP2;
944 return 0;
947 const char *
948 decompress_extension (int type)
950 switch (type){
951 case COMPRESSION_GZIP: return "#ugz";
952 case COMPRESSION_BZIP: return "#ubz";
953 case COMPRESSION_BZIP2: return "#ubz2";
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 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
963 Hook *new_hook = g_new (Hook, 1);
965 new_hook->hook_fn = hook_fn;
966 new_hook->next = *hook_list;
967 new_hook->hook_data = data;
969 *hook_list = new_hook;
972 void execute_hooks (Hook *hook_list)
974 Hook *new_hook = 0;
975 Hook *p;
977 /* We copy the hook list first so tahat we let the hook
978 * function call delete_hook
981 while (hook_list){
982 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
983 hook_list = hook_list->next;
985 p = new_hook;
987 while (new_hook){
988 (*new_hook->hook_fn)(new_hook->hook_data);
989 new_hook = new_hook->next;
992 for (hook_list = p; hook_list;){
993 p = hook_list;
994 hook_list = hook_list->next;
995 g_free (p);
999 void delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1001 Hook *current, *new_list, *next;
1003 new_list = 0;
1005 for (current = *hook_list; current; current = next){
1006 next = current->next;
1007 if (current->hook_fn == hook_fn)
1008 g_free (current);
1009 else
1010 add_hook (&new_list, current->hook_fn, current->hook_data);
1012 *hook_list = new_list;
1015 int hook_present (Hook *hook_list, void (*hook_fn)(void *))
1017 Hook *p;
1019 for (p = hook_list; p; p = p->next)
1020 if (p->hook_fn == hook_fn)
1021 return 1;
1022 return 0;
1025 void wipe_password (char *passwd)
1027 char *p = passwd;
1029 if (!p)
1030 return;
1031 for (;*p ; p++)
1032 *p = 0;
1033 g_free (passwd);
1036 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1037 /* Returns a newly allocated string */
1038 char *convert_controls (const char *p)
1040 char *valcopy = g_strdup (p);
1041 char *q;
1043 /* Parse the escape special character */
1044 for (q = valcopy; *p;){
1045 if (*p == '\\'){
1046 p++;
1047 if ((*p == 'e') || (*p == 'E')){
1048 p++;
1049 *q++ = ESC_CHAR;
1051 } else {
1052 if (*p == '^'){
1053 p++;
1054 if (*p == '^')
1055 *q++ = *p++;
1056 else {
1057 char c = (*p | 0x20);
1058 if (c >= 'a' && c <= 'z') {
1059 *q++ = c - 'a' + 1;
1060 p++;
1061 } else if (*p)
1062 p++;
1064 } else
1065 *q++ = *p++;
1068 *q = 0;
1069 return valcopy;
1072 static char *resolve_symlinks (const char *path)
1074 char *buf, *buf2, *q, *r, c;
1075 int len;
1076 struct stat mybuf;
1077 const char *p;
1079 if (*path != PATH_SEP)
1080 return NULL;
1081 r = buf = g_malloc (MC_MAXPATHLEN);
1082 buf2 = g_malloc (MC_MAXPATHLEN);
1083 *r++ = PATH_SEP;
1084 *r = 0;
1085 p = path;
1086 for (;;) {
1087 q = strchr (p + 1, PATH_SEP);
1088 if (!q) {
1089 q = strchr (p + 1, 0);
1090 if (q == p + 1)
1091 break;
1093 c = *q;
1094 *q = 0;
1095 if (mc_lstat (path, &mybuf) < 0) {
1096 g_free (buf);
1097 g_free (buf2);
1098 *q = c;
1099 return NULL;
1101 if (!S_ISLNK (mybuf.st_mode))
1102 strcpy (r, p + 1);
1103 else {
1104 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1105 if (len < 0) {
1106 g_free (buf);
1107 g_free (buf2);
1108 *q = c;
1109 return NULL;
1111 buf2 [len] = 0;
1112 if (*buf2 == PATH_SEP)
1113 strcpy (buf, buf2);
1114 else
1115 strcpy (r, buf2);
1117 canonicalize_pathname (buf);
1118 r = strchr (buf, 0);
1119 if (!*r || *(r - 1) != PATH_SEP) {
1120 *r++ = PATH_SEP;
1121 *r = 0;
1123 *q = c;
1124 p = q;
1125 if (!c)
1126 break;
1128 if (!*buf)
1129 strcpy (buf, PATH_SEP_STR);
1130 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1131 *(r - 1) = 0;
1132 g_free (buf2);
1133 return buf;
1136 /* Finds out a relative path from first to second, i.e. goes as many ..
1137 * as needed up in first and then goes down using second */
1138 char *diff_two_paths (const char *first, const char *second)
1140 char *p, *q, *r, *s, *buf = 0;
1141 int i, j, prevlen = -1, currlen;
1142 char *my_first = NULL, *my_second = NULL;
1144 my_first = resolve_symlinks (first);
1145 if (my_first == NULL)
1146 return NULL;
1147 for (j = 0; j < 2; j++) {
1148 p = my_first;
1149 if (j) {
1150 my_second = resolve_symlinks (second);
1151 if (my_second == NULL) {
1152 g_free (my_first);
1153 return buf;
1156 q = my_second;
1157 for (;;) {
1158 r = strchr (p, PATH_SEP);
1159 s = strchr (q, PATH_SEP);
1160 if (!r || !s)
1161 break;
1162 *r = 0; *s = 0;
1163 if (strcmp (p, q)) {
1164 *r = PATH_SEP; *s = PATH_SEP;
1165 break;
1166 } else {
1167 *r = PATH_SEP; *s = PATH_SEP;
1169 p = r + 1;
1170 q = s + 1;
1172 p--;
1173 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1174 currlen = (i + 1) * 3 + strlen (q) + 1;
1175 if (j) {
1176 if (currlen < prevlen)
1177 g_free (buf);
1178 else {
1179 g_free (my_first);
1180 g_free (my_second);
1181 return buf;
1184 p = buf = g_malloc (currlen);
1185 prevlen = currlen;
1186 for (; i >= 0; i--, p += 3)
1187 strcpy (p, "../");
1188 strcpy (p, q);
1190 g_free (my_first);
1191 g_free (my_second);
1192 return buf;
1195 /* If filename is NULL, then we just append PATH_SEP to the dir */
1196 char *
1197 concat_dir_and_file (const char *dir, const char *file)
1199 int i = strlen (dir);
1201 if (dir [i-1] == PATH_SEP)
1202 return g_strconcat (dir, file, (char *) NULL);
1203 else
1204 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1208 /* Append text to GList, remove all entries with the same text */
1209 GList *
1210 list_append_unique (GList *list, char *text)
1212 GList *link, *newlink;
1215 * Go to the last position and traverse the list backwards
1216 * starting from the second last entry to make sure that we
1217 * are not removing the current link.
1219 list = g_list_append (list, text);
1220 list = g_list_last (list);
1221 link = g_list_previous (list);
1223 while (link) {
1224 newlink = g_list_previous (link);
1225 if (!strcmp ((char *) link->data, text)) {
1226 g_free (link->data);
1227 g_list_remove_link (list, link);
1228 g_list_free_1 (link);
1230 link = newlink;
1233 return list;
1237 /* Following code heavily borrows from libiberty, mkstemps.c */
1239 /* Number of attempts to create a temporary file */
1240 #ifndef TMP_MAX
1241 #define TMP_MAX 16384
1242 #endif /* !TMP_MAX */
1245 * Arguments:
1246 * pname (output) - pointer to the name of the temp file (needs g_free).
1247 * NULL if the function fails.
1248 * prefix - part of the filename before the random part.
1249 * Prepend $TMPDIR or /tmp if there are no path separators.
1250 * suffix - if not NULL, part of the filename after the random part.
1252 * Result:
1253 * handle of the open file or -1 if couldn't open any.
1256 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1258 static const char letters[]
1259 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1260 static unsigned long value;
1261 struct timeval tv;
1262 char *tmpbase;
1263 char *tmpname;
1264 char *XXXXXX;
1265 int count;
1267 if (strchr (prefix, PATH_SEP) == NULL) {
1268 /* Add prefix first to find the position of XXXXXX */
1269 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1270 } else {
1271 tmpbase = g_strdup (prefix);
1274 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1275 *pname = tmpname;
1276 XXXXXX = &tmpname[strlen (tmpbase)];
1277 g_free (tmpbase);
1279 /* Get some more or less random data. */
1280 gettimeofday (&tv, NULL);
1281 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1283 for (count = 0; count < TMP_MAX; ++count) {
1284 unsigned long v = value;
1285 int fd;
1287 /* Fill in the random bits. */
1288 XXXXXX[0] = letters[v % 62];
1289 v /= 62;
1290 XXXXXX[1] = letters[v % 62];
1291 v /= 62;
1292 XXXXXX[2] = letters[v % 62];
1293 v /= 62;
1294 XXXXXX[3] = letters[v % 62];
1295 v /= 62;
1296 XXXXXX[4] = letters[v % 62];
1297 v /= 62;
1298 XXXXXX[5] = letters[v % 62];
1300 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1301 S_IRUSR | S_IWUSR);
1302 if (fd >= 0) {
1303 /* Successfully created. */
1304 return fd;
1307 /* This is a random value. It is only necessary that the next
1308 TMP_MAX values generated by adding 7777 to VALUE are different
1309 with (module 2^32). */
1310 value += 7777;
1313 /* Unsuccessful. Free the filename. */
1314 g_free (tmpname);
1315 *pname = NULL;
1317 return -1;
1322 * Read and restore position for the given filename.
1323 * If there is no stored data, return line 1 and col 0.
1325 void
1326 load_file_position (const char *filename, long *line, long *column)
1328 char *fn;
1329 FILE *f;
1330 char buf[MC_MAXPATHLEN + 20];
1331 int len;
1333 /* defaults */
1334 *line = 1;
1335 *column = 0;
1337 /* open file with positions */
1338 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1339 f = fopen (fn, "r");
1340 g_free (fn);
1341 if (!f)
1342 return;
1344 len = strlen (filename);
1346 while (fgets (buf, sizeof (buf), f)) {
1347 const char *p;
1349 /* check if the filename matches the beginning of string */
1350 if (strncmp (buf, filename, len) != 0)
1351 continue;
1353 /* followed by single space */
1354 if (buf[len] != ' ')
1355 continue;
1357 /* and string without spaces */
1358 p = &buf[len + 1];
1359 if (strchr (p, ' '))
1360 continue;
1362 *line = strtol(p, const_cast(char **, &p), 10);
1363 if (*p == ';') {
1364 *column = strtol(p+1, const_cast(char **, &p), 10);
1365 if (*p != '\n')
1366 *column = 0;
1367 } else
1368 *line = 1;
1370 fclose (f);
1373 /* Save position for the given file */
1374 void
1375 save_file_position (const char *filename, long line, long column)
1377 char *tmp, *fn;
1378 FILE *f, *t;
1379 char buf[MC_MAXPATHLEN + 20];
1380 int i = 1;
1381 int len;
1383 len = strlen (filename);
1385 tmp = concat_dir_and_file (home_dir, MC_FILEPOS_TMP);
1386 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1388 /* open temporary file */
1389 t = fopen (tmp, "w");
1390 if (!t) {
1391 g_free (tmp);
1392 g_free (fn);
1393 return;
1396 /* put the new record */
1397 if (line != 1 || column != 0) {
1398 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1401 /* copy records from the old file */
1402 f = fopen (fn, "r");
1403 if (f) {
1404 while (fgets (buf, sizeof (buf), f)) {
1405 /* Skip entries for the current filename */
1406 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1407 && !strchr (&buf[len + 1], ' '))
1408 continue;
1410 fprintf (t, "%s", buf);
1411 if (++i > MC_FILEPOS_ENTRIES)
1412 break;
1414 fclose (f);
1417 fclose (t);
1418 rename (tmp, fn);
1419 g_free (tmp);
1420 g_free (fn);
1423 extern const char *
1424 cstrcasestr (const char *haystack, const char *needle)
1426 const char *hptr;
1427 size_t i, needle_len;
1429 needle_len = strlen (needle);
1430 for (hptr = haystack; *hptr != '\0'; hptr++) {
1431 for (i = 0; i < needle_len; i++) {
1432 if (toupper ((unsigned char) hptr[i]) !=
1433 toupper ((unsigned char) needle[i]))
1434 goto next_try;
1436 return hptr;
1437 next_try:
1438 (void) 0;
1440 return NULL;
1443 const char *
1444 cstrstr (const char *haystack, const char *needle)
1446 return strstr(haystack, needle);
1449 extern char *
1450 str_unconst (const char *s)
1452 return (char *) s;
1455 #define ASCII_A (0x40 + 1)
1456 #define ASCII_Z (0x40 + 26)
1457 #define ASCII_a (0x60 + 1)
1458 #define ASCII_z (0x60 + 26)
1460 extern int
1461 ascii_alpha_to_cntrl (int ch)
1463 if ((ch >= ASCII_A && ch <= ASCII_Z)
1464 || (ch >= ASCII_a && ch <= ASCII_z)) {
1465 ch &= 0x1f;
1467 return ch;
1470 extern const char *
1471 gettext_ui (const char *s)
1473 const char *result, *sep;
1475 result = _(s);
1476 sep = strchr(result, '|');
1477 return (sep != NULL) ? sep + 1 : result;