* glibcompat.c: Add g_strlcat() declaration for glib 1.2.x
[midnight-commander.git] / src / util.c
blob8ce02abf56fc3aaa7085fe3a5f2049471275c3b3
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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 {"/#mc:", 5},
441 {"ftp://", 6},
442 {"/#smb:", 6},
443 {"/#sh:", 5}
445 char *at, *inner_colon, *dir;
446 size_t i;
447 char *result = p;
449 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
450 char *q;
452 if (has_prefix) {
453 if((q = strstr (p, prefixes[i].name)) == 0)
454 continue;
455 else
456 p = q + prefixes[i].len;
459 if ((dir = strchr (p, PATH_SEP)) != NULL)
460 *dir = '\0';
462 /* search for any possible user */
463 at = strrchr (p, '@');
465 if (dir)
466 *dir = PATH_SEP;
468 /* We have a username */
469 if (at) {
470 inner_colon = memchr (p, ':', at - p);
471 if (inner_colon)
472 memmove (inner_colon, at, strlen(at) + 1);
474 break;
476 return (result);
479 const char *strip_home_and_password(const char *dir)
481 size_t len;
482 static char newdir [MC_MAXPATHLEN];
484 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
485 (dir[len] == PATH_SEP || dir[len] == '\0')){
486 newdir [0] = '~';
487 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
488 return newdir;
491 /* We do not strip homes in /#ftp tree, I do not like ~'s there
492 (see ftpfs.c why) */
493 g_strlcpy (newdir, dir, sizeof(newdir));
494 strip_password (newdir, 1);
495 return newdir;
498 static char *maybe_start_group (char *d, int do_group, int *was_wildcard)
500 if (!do_group)
501 return d;
502 if (*was_wildcard)
503 return d;
504 *was_wildcard = 1;
505 *d++ = '\\';
506 *d++ = '(';
507 return d;
510 static char *maybe_end_group (char *d, int do_group, int *was_wildcard)
512 if (!do_group)
513 return d;
514 if (!*was_wildcard)
515 return d;
516 *was_wildcard = 0;
517 *d++ = '\\';
518 *d++ = ')';
519 return d;
522 /* If shell patterns are on converts a shell pattern to a regular
523 expression. Called by regexp_match and mask_rename. */
524 /* Shouldn't we support [a-fw] type wildcards as well ?? */
525 char *convert_pattern (const char *pattern, int match_type, int do_group)
527 char *d;
528 char *new_pattern;
529 int was_wildcard = 0;
530 const char *s;
532 if ((match_type != match_regex) && easy_patterns){
533 new_pattern = g_malloc (MC_MAXPATHLEN);
534 d = new_pattern;
535 if (match_type == match_file)
536 *d++ = '^';
537 for (s = pattern; *s; s++, d++){
538 switch (*s){
539 case '*':
540 d = maybe_start_group (d, do_group, &was_wildcard);
541 *d++ = '.';
542 *d = '*';
543 break;
545 case '?':
546 d = maybe_start_group (d, do_group, &was_wildcard);
547 *d = '.';
548 break;
550 case '.':
551 d = maybe_end_group (d, do_group, &was_wildcard);
552 *d++ = '\\';
553 *d = '.';
554 break;
556 default:
557 d = maybe_end_group (d, do_group, &was_wildcard);
558 *d = *s;
559 break;
562 d = maybe_end_group (d, do_group, &was_wildcard);
563 if (match_type == match_file)
564 *d++ = '$';
565 *d = 0;
566 return new_pattern;
567 } else
568 return g_strdup (pattern);
571 int regexp_match (const char *pattern, const char *string, int match_type)
573 static regex_t r;
574 static char *old_pattern = NULL;
575 static int old_type;
576 int rval;
577 char *my_pattern;
579 if (!old_pattern || STRCOMP (old_pattern, pattern) || old_type != match_type){
580 if (old_pattern){
581 regfree (&r);
582 g_free (old_pattern);
583 old_pattern = NULL;
585 my_pattern = convert_pattern (pattern, match_type, 0);
586 if (regcomp (&r, my_pattern, REG_EXTENDED|REG_NOSUB|MC_ARCH_FLAGS)) {
587 g_free (my_pattern);
588 return -1;
590 old_pattern = my_pattern;
591 old_type = match_type;
593 rval = !regexec (&r, string, 0, NULL, 0);
594 return rval;
597 const char *extension (const char *filename)
599 const char *d = strrchr (filename, '.');
600 return (d != NULL) ? d + 1 : "";
603 int get_int (const char *file, const char *key, int def)
605 return GetPrivateProfileInt (app_text, key, def, file);
608 int set_int (const char *file, const char *key, int value)
610 char buffer [BUF_TINY];
612 g_snprintf (buffer, sizeof (buffer), "%d", value);
613 return WritePrivateProfileString (app_text, key, buffer, file);
616 int exist_file (const char *name)
618 return access (name, R_OK) == 0;
621 char *load_file (const char *filename)
623 FILE *data_file;
624 struct stat s;
625 char *data;
626 long read_size;
628 if ((data_file = fopen (filename, "r")) == NULL){
629 return 0;
631 if (fstat (fileno (data_file), &s) != 0){
632 fclose (data_file);
633 return 0;
635 data = g_malloc (s.st_size+1);
636 read_size = fread (data, 1, s.st_size, data_file);
637 data [read_size] = 0;
638 fclose (data_file);
640 if (read_size > 0)
641 return data;
642 else {
643 g_free (data);
644 return 0;
648 char *
649 load_mc_home_file (const char *filename, char **allocated_filename)
651 char *hintfile_base, *hintfile;
652 char *lang;
653 char *data;
655 hintfile_base = concat_dir_and_file (mc_home, filename);
656 lang = guess_message_value ();
658 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
659 data = load_file (hintfile);
661 if (!data) {
662 g_free (hintfile);
663 /* Fall back to the two-letter language code */
664 if (lang[0] && lang[1])
665 lang[2] = 0;
666 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
667 data = load_file (hintfile);
669 if (!data) {
670 g_free (hintfile);
671 hintfile = hintfile_base;
672 data = load_file (hintfile_base);
676 g_free (lang);
678 if (hintfile != hintfile_base)
679 g_free (hintfile_base);
681 if (allocated_filename)
682 *allocated_filename = hintfile;
683 else
684 g_free (hintfile);
686 return data;
689 /* Check strftime() results. Some systems (i.e. Solaris) have different
690 short-month-name sizes for different locales */
691 size_t i18n_checktimelength (void)
693 size_t length, a, b;
694 char buf [MAX_I18NTIMELENGTH + 1];
695 time_t testtime = time (NULL);
697 a = strftime (buf, sizeof(buf)-1, _("%b %e %H:%M"), localtime(&testtime));
698 b = strftime (buf, sizeof(buf)-1, _("%b %e %Y"), localtime(&testtime));
700 length = max (a, b);
702 /* Don't handle big differences. Use standard value (email bug, please) */
703 if ( length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH )
704 length = STD_I18NTIMELENGTH;
706 return length;
709 const char *file_date (time_t when)
711 static char timebuf [MAX_I18NTIMELENGTH + 1];
712 time_t current_time = time ((time_t) 0);
713 static size_t i18n_timelength = 0;
714 static const char *fmtyear, *fmttime;
715 const char *fmt;
717 if (i18n_timelength == 0){
718 i18n_timelength = i18n_checktimelength() + 1;
720 /* strftime() format string for old dates */
721 fmtyear = _("%b %e %Y");
722 /* strftime() format string for recent dates */
723 fmttime = _("%b %e %H:%M");
726 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
727 || current_time < when - 60L * 60L) /* In the future. */
728 /* The file is fairly old or in the future.
729 POSIX says the cutoff is 6 months old;
730 approximate this by 6*30 days.
731 Allow a 1 hour slop factor for what is considered "the future",
732 to allow for NFS server/client clock disagreement.
733 Show the year instead of the time of day. */
735 fmt = fmtyear;
736 else
737 fmt = fmttime;
739 strftime (timebuf, i18n_timelength, fmt, localtime(&when));
740 return timebuf;
743 const char *extract_line (const char *s, const char *top)
745 static char tmp_line [BUF_MEDIUM];
746 char *t = tmp_line;
748 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
749 *t++ = *s++;
750 *t = 0;
751 return tmp_line;
754 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
755 const char * _icase_search (const char *text, const char *data, int *lng)
757 const char *d = text;
758 const char *e = data;
759 int dlng = 0;
761 if (lng)
762 *lng = 0;
763 for (;*e; e++) {
764 while (*(e+1) == '\b' && *(e+2)) {
765 e += 2;
766 dlng += 2;
768 if (toupper((unsigned char) *d) == toupper((unsigned char) *e))
769 d++;
770 else {
771 e -= d - text;
772 d = text;
773 dlng = 0;
775 if (!*d) {
776 if (lng)
777 *lng = strlen (text) + dlng;
778 return e+1;
781 return 0;
784 /* The basename routine */
785 const char *x_basename (const char *s)
787 const char *where;
788 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
792 const char *unix_error_string (int error_num)
794 static char buffer [BUF_LARGE];
795 #if GLIB_MAJOR_VERSION >= 2
796 gchar *strerror_currentlocale;
798 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
799 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
800 strerror_currentlocale, error_num);
801 g_free(strerror_currentlocale);
802 #else
803 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
804 g_strerror (error_num), error_num);
805 #endif
806 return buffer;
809 const char *skip_separators (const char *s)
811 for (;*s; s++)
812 if (*s != ' ' && *s != '\t' && *s != ',')
813 break;
814 return s;
817 const char *skip_numbers (const char *s)
819 for (;*s; s++)
820 if (!isdigit ((int) (unsigned char) *s))
821 break;
822 return s;
825 /* Remove all control sequences from the argument string. We define
826 * "control sequence", in a sort of pidgin BNF, as follows:
828 * control-seq = Esc non-'['
829 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
831 * This scheme works for all the terminals described in my termcap /
832 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
833 * terminals. If I hear from a single person who uses such a terminal
834 * with MC, I'll be glad to add support for it. (Dugan)
835 * Non-printable characters are also removed.
838 char *strip_ctrl_codes (char *s)
840 char *w; /* Current position where the stripped data is written */
841 char *r; /* Current position where the original data is read */
843 if (!s)
844 return 0;
846 for (w = s, r = s; *r; ) {
847 if (*r == ESC_CHAR) {
848 /* Skip the control sequence's arguments */ ;
849 if (*(++r) == '[') {
850 /* strchr() matches trailing binary 0 */
851 while (*(++r) && strchr ("0123456789;?", *r));
855 * Now we are at the last character of the sequence.
856 * Skip it unless it's binary 0.
858 if (*r)
859 r++;
860 continue;
863 if (is_printable(*r))
864 *w++ = *r;
865 ++r;
867 *w = 0;
868 return s;
872 #ifndef USE_VFS
873 char *get_current_wd (char *buffer, int size)
875 char *p;
876 int len;
878 p = g_get_current_dir ();
879 len = strlen(p) + 1;
881 if (len > size) {
882 g_free (p);
883 return NULL;
886 memcpy (buffer, p, len);
887 g_free (p);
889 return buffer;
891 #endif /* !USE_VFS */
893 /* This function returns 0 if the file is not in not compressed by
894 * one of the supported compressors (gzip, bzip, bzip2). Otherwise,
895 * the compression type is returned, as defined in util.h
896 * Warning: this function moves the current file pointer */
897 int get_compression_type (int fd)
899 unsigned char magic[4];
901 /* Read the magic signature */
902 if (mc_read (fd, (char *) magic, 4) != 4)
903 return COMPRESSION_NONE;
905 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
906 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
907 return COMPRESSION_GZIP;
910 /* PKZIP_MAGIC */
911 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
912 && magic[3] == 004) {
913 /* Read compression type */
914 mc_lseek (fd, 8, SEEK_SET);
915 if (mc_read (fd, (char *) magic, 2) != 2)
916 return COMPRESSION_NONE;
918 /* Gzip can handle only deflated (8) or stored (0) files */
919 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
920 return COMPRESSION_NONE;
922 /* Compatible with gzip */
923 return COMPRESSION_GZIP;
926 /* PACK_MAGIC and LZH_MAGIC and compress magic */
927 if (magic[0] == 037
928 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
929 /* Compatible with gzip */
930 return COMPRESSION_GZIP;
933 /* BZIP and BZIP2 files */
934 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
935 (magic[3] >= '1') && (magic[3] <= '9')) {
936 switch (magic[2]) {
937 case '0':
938 return COMPRESSION_BZIP;
939 case 'h':
940 return COMPRESSION_BZIP2;
943 return 0;
946 const char *
947 decompress_extension (int type)
949 switch (type){
950 case COMPRESSION_GZIP: return "#ugz";
951 case COMPRESSION_BZIP: return "#ubz";
952 case COMPRESSION_BZIP2: return "#ubz2";
954 /* Should never reach this place */
955 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
956 return 0;
959 /* Hooks */
960 void add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
962 Hook *new_hook = g_new (Hook, 1);
964 new_hook->hook_fn = hook_fn;
965 new_hook->next = *hook_list;
966 new_hook->hook_data = data;
968 *hook_list = new_hook;
971 void execute_hooks (Hook *hook_list)
973 Hook *new_hook = 0;
974 Hook *p;
976 /* We copy the hook list first so tahat we let the hook
977 * function call delete_hook
980 while (hook_list){
981 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
982 hook_list = hook_list->next;
984 p = new_hook;
986 while (new_hook){
987 (*new_hook->hook_fn)(new_hook->hook_data);
988 new_hook = new_hook->next;
991 for (hook_list = p; hook_list;){
992 p = hook_list;
993 hook_list = hook_list->next;
994 g_free (p);
998 void delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1000 Hook *current, *new_list, *next;
1002 new_list = 0;
1004 for (current = *hook_list; current; current = next){
1005 next = current->next;
1006 if (current->hook_fn == hook_fn)
1007 g_free (current);
1008 else
1009 add_hook (&new_list, current->hook_fn, current->hook_data);
1011 *hook_list = new_list;
1014 int hook_present (Hook *hook_list, void (*hook_fn)(void *))
1016 Hook *p;
1018 for (p = hook_list; p; p = p->next)
1019 if (p->hook_fn == hook_fn)
1020 return 1;
1021 return 0;
1024 void wipe_password (char *passwd)
1026 char *p = passwd;
1028 if (!p)
1029 return;
1030 for (;*p ; p++)
1031 *p = 0;
1032 g_free (passwd);
1035 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1036 /* Returns a newly allocated string */
1037 char *convert_controls (const char *p)
1039 char *valcopy = g_strdup (p);
1040 char *q;
1042 /* Parse the escape special character */
1043 for (q = valcopy; *p;){
1044 if (*p == '\\'){
1045 p++;
1046 if ((*p == 'e') || (*p == 'E')){
1047 p++;
1048 *q++ = ESC_CHAR;
1050 } else {
1051 if (*p == '^'){
1052 p++;
1053 if (*p == '^')
1054 *q++ = *p++;
1055 else {
1056 char c = (*p | 0x20);
1057 if (c >= 'a' && c <= 'z') {
1058 *q++ = c - 'a' + 1;
1059 p++;
1060 } else if (*p)
1061 p++;
1063 } else
1064 *q++ = *p++;
1067 *q = 0;
1068 return valcopy;
1071 static char *resolve_symlinks (const char *path)
1073 char *buf, *buf2, *q, *r, c;
1074 int len;
1075 struct stat mybuf;
1076 const char *p;
1078 if (*path != PATH_SEP)
1079 return NULL;
1080 r = buf = g_malloc (MC_MAXPATHLEN);
1081 buf2 = g_malloc (MC_MAXPATHLEN);
1082 *r++ = PATH_SEP;
1083 *r = 0;
1084 p = path;
1085 for (;;) {
1086 q = strchr (p + 1, PATH_SEP);
1087 if (!q) {
1088 q = strchr (p + 1, 0);
1089 if (q == p + 1)
1090 break;
1092 c = *q;
1093 *q = 0;
1094 if (mc_lstat (path, &mybuf) < 0) {
1095 g_free (buf);
1096 g_free (buf2);
1097 *q = c;
1098 return NULL;
1100 if (!S_ISLNK (mybuf.st_mode))
1101 strcpy (r, p + 1);
1102 else {
1103 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1104 if (len < 0) {
1105 g_free (buf);
1106 g_free (buf2);
1107 *q = c;
1108 return NULL;
1110 buf2 [len] = 0;
1111 if (*buf2 == PATH_SEP)
1112 strcpy (buf, buf2);
1113 else
1114 strcpy (r, buf2);
1116 canonicalize_pathname (buf);
1117 r = strchr (buf, 0);
1118 if (!*r || *(r - 1) != PATH_SEP) {
1119 *r++ = PATH_SEP;
1120 *r = 0;
1122 *q = c;
1123 p = q;
1124 if (!c)
1125 break;
1127 if (!*buf)
1128 strcpy (buf, PATH_SEP_STR);
1129 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1130 *(r - 1) = 0;
1131 g_free (buf2);
1132 return buf;
1135 /* Finds out a relative path from first to second, i.e. goes as many ..
1136 * as needed up in first and then goes down using second */
1137 char *diff_two_paths (const char *first, const char *second)
1139 char *p, *q, *r, *s, *buf = 0;
1140 int i, j, prevlen = -1, currlen;
1141 char *my_first = NULL, *my_second = NULL;
1143 my_first = resolve_symlinks (first);
1144 if (my_first == NULL)
1145 return NULL;
1146 for (j = 0; j < 2; j++) {
1147 p = my_first;
1148 if (j) {
1149 my_second = resolve_symlinks (second);
1150 if (my_second == NULL) {
1151 g_free (my_first);
1152 return buf;
1155 q = my_second;
1156 for (;;) {
1157 r = strchr (p, PATH_SEP);
1158 s = strchr (q, PATH_SEP);
1159 if (!r || !s)
1160 break;
1161 *r = 0; *s = 0;
1162 if (strcmp (p, q)) {
1163 *r = PATH_SEP; *s = PATH_SEP;
1164 break;
1165 } else {
1166 *r = PATH_SEP; *s = PATH_SEP;
1168 p = r + 1;
1169 q = s + 1;
1171 p--;
1172 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1173 currlen = (i + 1) * 3 + strlen (q) + 1;
1174 if (j) {
1175 if (currlen < prevlen)
1176 g_free (buf);
1177 else {
1178 g_free (my_first);
1179 g_free (my_second);
1180 return buf;
1183 p = buf = g_malloc (currlen);
1184 prevlen = currlen;
1185 for (; i >= 0; i--, p += 3)
1186 strcpy (p, "../");
1187 strcpy (p, q);
1189 g_free (my_first);
1190 g_free (my_second);
1191 return buf;
1194 /* If filename is NULL, then we just append PATH_SEP to the dir */
1195 char *
1196 concat_dir_and_file (const char *dir, const char *file)
1198 int i = strlen (dir);
1200 if (dir [i-1] == PATH_SEP)
1201 return g_strconcat (dir, file, (char *) NULL);
1202 else
1203 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1207 /* Append text to GList, remove all entries with the same text */
1208 GList *
1209 list_append_unique (GList *list, char *text)
1211 GList *link, *newlink;
1214 * Go to the last position and traverse the list backwards
1215 * starting from the second last entry to make sure that we
1216 * are not removing the current link.
1218 list = g_list_append (list, text);
1219 list = g_list_last (list);
1220 link = g_list_previous (list);
1222 while (link) {
1223 newlink = g_list_previous (link);
1224 if (!strcmp ((char *) link->data, text)) {
1225 g_free (link->data);
1226 g_list_remove_link (list, link);
1227 g_list_free_1 (link);
1229 link = newlink;
1232 return list;
1236 /* Following code heavily borrows from libiberty, mkstemps.c */
1238 /* Number of attempts to create a temporary file */
1239 #ifndef TMP_MAX
1240 #define TMP_MAX 16384
1241 #endif /* !TMP_MAX */
1244 * Arguments:
1245 * pname (output) - pointer to the name of the temp file (needs g_free).
1246 * NULL if the function fails.
1247 * prefix - part of the filename before the random part.
1248 * Prepend $TMPDIR or /tmp if there are no path separators.
1249 * suffix - if not NULL, part of the filename after the random part.
1251 * Result:
1252 * handle of the open file or -1 if couldn't open any.
1255 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1257 static const char letters[]
1258 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1259 static unsigned long value;
1260 struct timeval tv;
1261 char *tmpbase;
1262 char *tmpname;
1263 char *XXXXXX;
1264 int count;
1266 if (strchr (prefix, PATH_SEP) == NULL) {
1267 /* Add prefix first to find the position of XXXXXX */
1268 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1269 } else {
1270 tmpbase = g_strdup (prefix);
1273 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1274 *pname = tmpname;
1275 XXXXXX = &tmpname[strlen (tmpbase)];
1276 g_free (tmpbase);
1278 /* Get some more or less random data. */
1279 gettimeofday (&tv, NULL);
1280 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1282 for (count = 0; count < TMP_MAX; ++count) {
1283 unsigned long v = value;
1284 int fd;
1286 /* Fill in the random bits. */
1287 XXXXXX[0] = letters[v % 62];
1288 v /= 62;
1289 XXXXXX[1] = letters[v % 62];
1290 v /= 62;
1291 XXXXXX[2] = letters[v % 62];
1292 v /= 62;
1293 XXXXXX[3] = letters[v % 62];
1294 v /= 62;
1295 XXXXXX[4] = letters[v % 62];
1296 v /= 62;
1297 XXXXXX[5] = letters[v % 62];
1299 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1300 S_IRUSR | S_IWUSR);
1301 if (fd >= 0) {
1302 /* Successfully created. */
1303 return fd;
1306 /* This is a random value. It is only necessary that the next
1307 TMP_MAX values generated by adding 7777 to VALUE are different
1308 with (module 2^32). */
1309 value += 7777;
1312 /* Unsuccessful. Free the filename. */
1313 g_free (tmpname);
1314 *pname = NULL;
1316 return -1;
1321 * Read and restore position for the given filename.
1322 * If there is no stored data, return line 1 and col 0.
1324 void
1325 load_file_position (const char *filename, long *line, long *column)
1327 char *fn;
1328 FILE *f;
1329 char buf[MC_MAXPATHLEN + 20];
1330 int len;
1332 /* defaults */
1333 *line = 1;
1334 *column = 0;
1336 /* open file with positions */
1337 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1338 f = fopen (fn, "r");
1339 g_free (fn);
1340 if (!f)
1341 return;
1343 len = strlen (filename);
1345 while (fgets (buf, sizeof (buf), f)) {
1346 const char *p;
1348 /* check if the filename matches the beginning of string */
1349 if (strncmp (buf, filename, len) != 0)
1350 continue;
1352 /* followed by single space */
1353 if (buf[len] != ' ')
1354 continue;
1356 /* and string without spaces */
1357 p = &buf[len + 1];
1358 if (strchr (p, ' '))
1359 continue;
1361 *line = strtol(p, const_cast(char **, &p), 10);
1362 if (*p == ';') {
1363 *column = strtol(p, const_cast(char **, &p), 10);
1364 if (*p != '\n')
1365 *column = 0;
1366 } else
1367 *line = 1;
1369 fclose (f);
1372 /* Save position for the given file */
1373 void
1374 save_file_position (const char *filename, long line, long column)
1376 char *tmp, *fn;
1377 FILE *f, *t;
1378 char buf[MC_MAXPATHLEN + 20];
1379 int i = 1;
1380 int len;
1382 len = strlen (filename);
1384 tmp = concat_dir_and_file (home_dir, MC_FILEPOS_TMP);
1385 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1387 /* open temporary file */
1388 t = fopen (tmp, "w");
1389 if (!t) {
1390 g_free (tmp);
1391 g_free (fn);
1392 return;
1395 /* put the new record */
1396 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1398 /* copy records from the old file */
1399 f = fopen (fn, "r");
1400 if (f) {
1401 while (fgets (buf, sizeof (buf), f)) {
1402 /* Skip entries for the current filename */
1403 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1404 && !strchr (&buf[len + 1], ' '))
1405 continue;
1407 fprintf (t, "%s", buf);
1408 if (++i > MC_FILEPOS_ENTRIES)
1409 break;
1411 fclose (f);
1414 fclose (t);
1415 rename (tmp, fn);
1416 g_free (tmp);
1417 g_free (fn);
1420 extern const char *
1421 cstrcasestr (const char *haystack, const char *needle)
1423 const unsigned char *uhaystack = (const unsigned char *) haystack;
1424 const unsigned char *uneedle = (const unsigned char *) needle;
1425 const unsigned char *hptr;
1426 size_t i, needle_len;
1428 needle_len = strlen(needle);
1429 for (hptr = uhaystack; *hptr != '\0'; hptr++) {
1430 for (i = 0; i < needle_len; i++) {
1431 if (toupper(hptr[i]) != toupper(uneedle[i]))
1432 goto next_try;
1434 return hptr;
1435 next_try:
1436 (void) 0;
1438 return NULL;