Just a little correction at the it.po file.
[midnight-commander.git] / src / util.c
blob31b5e2d08b6751a9da28603bc5eed5ef6347e4b6
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>
25 #include <stdio.h>
26 #include <sys/types.h>
27 #ifdef HAVE_UNISTD_H
28 # include <unistd.h>
29 #endif
30 #include <limits.h> /* INT_MAX */
31 #include <sys/stat.h>
32 #include <stdarg.h>
33 #include <string.h>
34 #include <ctype.h>
36 #include "global.h"
37 #include "profile.h"
38 #include "main.h" /* mc_home */
39 #include "cmd.h" /* guess_message_value */
40 #include "../vfs/vfs.h"
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 static inline int
52 is_7bit_printable (unsigned char c)
54 return (c > 31 && c < 127);
57 static inline int
58 is_iso_printable (unsigned char c)
60 return ((c > 31 && c < 127) || c >= 160);
63 static inline int
64 is_8bit_printable (unsigned char c)
66 /* "Full 8 bits output" doesn't work on xterm */
67 if (xterm_flag)
68 return is_iso_printable (c);
70 return (c > 31 && c != 127 && c != 155);
73 int
74 is_printable (int c)
76 c &= 0xff;
78 #ifdef HAVE_CHARSET
79 /* "Display bits" is ignored, since the user controls the output
80 by setting the output codepage */
81 return is_8bit_printable (c);
82 #else
83 if (!eight_bit_clean)
84 return is_7bit_printable (c);
86 if (full_eight_bits) {
87 return is_8bit_printable (c);
88 } else
89 return is_iso_printable (c);
90 #endif /* !HAVE_CHARSET */
93 /* Returns the message dimensions (lines and columns) */
94 int msglen (char *text, int *lines)
96 int max = 0;
97 int line_len = 0;
99 for (*lines = 1;*text; text++){
100 if (*text == '\n'){
101 line_len = 0;
102 (*lines)++;
103 } else {
104 line_len++;
105 if (line_len > max)
106 max = line_len;
109 return max;
113 * Copy from s to d, and trim the beginning if necessary, and prepend
114 * "..." in this case. The destination string can have at most len
115 * bytes, not counting trailing 0.
117 char *
118 trim (char *s, char *d, int len)
120 int source_len;
122 /* Sanity check */
123 len = max (len, 0);
125 source_len = strlen (s);
126 if (source_len > len) {
127 /* Cannot fit the whole line */
128 if (len <= 3) {
129 /* We only have room for the dots */
130 memset (d, '.', len);
131 d[len] = 0;
132 return d;
133 } else {
134 /* Begin with ... and add the rest of the source string */
135 memset (d, '.', 3);
136 strcpy (d + 3, s + 3 + source_len - len);
138 } else
139 /* We can copy the whole line */
140 strcpy (d, s);
141 return d;
145 * Quote the filename for the purpose of inserting it into the command
146 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
147 * processed by the mc command line.
149 char *
150 name_quote (const char *s, int quote_percent)
152 char *ret, *d;
154 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
155 if (*s == '-') {
156 *d++ = '.';
157 *d++ = '/';
160 for (; *s; s++, d++) {
161 switch (*s) {
162 case '%':
163 if (quote_percent)
164 *d++ = '%';
165 break;
166 case '\'':
167 case '\\':
168 case '\r':
169 case '\n':
170 case '\t':
171 case '"':
172 case ';':
173 case ' ':
174 case '?':
175 case '|':
176 case '[':
177 case ']':
178 case '{':
179 case '}':
180 case '<':
181 case '>':
182 case '`':
183 case '!':
184 case '$':
185 case '&':
186 case '*':
187 case '(':
188 case ')':
189 *d++ = '\\';
190 break;
191 case '~':
192 case '#':
193 if (d == ret)
194 *d++ = '\\';
195 break;
197 *d = *s;
199 *d = '\0';
200 return ret;
203 char *
204 fake_name_quote (const char *s, int quote_percent)
206 return g_strdup (s);
210 * Remove the middle part of the string to fit given length.
211 * Use "~" to show where the string was truncated.
212 * Return static buffer, no need to free() it.
214 char *
215 name_trunc (const char *txt, int trunc_len)
217 static char x[MC_MAXPATHLEN + MC_MAXPATHLEN];
218 int txt_len;
219 char *p;
221 if (trunc_len > sizeof (x) - 1) {
222 trunc_len = sizeof (x) - 1;
224 txt_len = strlen (txt);
225 if (txt_len <= trunc_len) {
226 strcpy (x, txt);
227 } else {
228 int y = (trunc_len / 2) + (trunc_len % 2);
229 strncpy (x, txt, y);
230 strncpy (x + y, txt + txt_len - (trunc_len / 2), trunc_len / 2);
231 x[y] = '~';
233 x[trunc_len] = 0;
234 for (p = x; *p; p++)
235 if (!is_printable (*p))
236 *p = '?';
237 return x;
240 char *size_trunc (double size)
242 static char x [BUF_TINY];
243 long int divisor = 1;
244 char *xtra = "";
246 if (size > 999999999L){
247 divisor = 1024;
248 xtra = "K";
249 if (size/divisor > 999999999L){
250 divisor = 1024*1024;
251 xtra = "M";
254 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
255 return x;
258 char *size_trunc_sep (double size)
260 static char x [60];
261 int count;
262 char *p, *d, *y;
264 p = y = size_trunc (size);
265 p += strlen (p) - 1;
266 d = x + sizeof (x) - 1;
267 *d-- = 0;
268 while (p >= y && isalpha ((unsigned char) *p))
269 *d-- = *p--;
270 for (count = 0; p >= y; count++){
271 if (count == 3){
272 *d-- = ',';
273 count = 0;
275 *d-- = *p--;
277 d++;
278 if (*d == ',')
279 d++;
280 return d;
284 * Print file SIZE to BUFFER, but don't exceed LEN characters,
285 * not including trailing 0. BUFFER should be at least LEN+1 long.
286 * This function is called for every file on panels, so avoid
287 * floating point by any means.
289 * Units: size units (filesystem sizes are 1K blocks)
290 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
292 void
293 size_trunc_len (char *buffer, int len, off_t size, int units)
295 /* Avoid taking power for every file. */
296 static const off_t power10 [] =
297 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
298 1000000000};
299 static const char * const suffix [] =
300 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
301 int j = 0;
303 /* Don't print more than 9 digits - use suffix. */
304 if (len == 0 || len > 9)
305 len = 9;
307 for (j = units; suffix [j] != NULL; j++) {
308 if (size == 0) {
309 if (j == units) {
310 /* Empty files will print "0" even with minimal width. */
311 g_snprintf (buffer, len + 1, "0");
312 break;
315 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
316 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
317 (j > 1) ? suffix[j - 1] : "B");
318 break;
321 if (size < power10 [len - (j > 0)]) {
322 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
323 break;
326 /* Powers of 1024, with rounding. */
327 size = (size + 512) >> 10;
331 int is_exe (mode_t mode)
333 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
334 return 1;
335 return 0;
338 #define ismode(n,m) ((n & m) == m)
340 char *
341 string_perm (mode_t mode_bits)
343 static char mode[11];
345 strcpy (mode, "----------");
346 if (S_ISDIR (mode_bits))
347 mode[0] = 'd';
348 if (S_ISCHR (mode_bits))
349 mode[0] = 'c';
350 if (S_ISBLK (mode_bits))
351 mode[0] = 'b';
352 if (S_ISLNK (mode_bits))
353 mode[0] = 'l';
354 if (S_ISFIFO (mode_bits))
355 mode[0] = 'p';
356 if (S_ISSOCK (mode_bits))
357 mode[0] = 's';
358 if (S_ISDOOR (mode_bits))
359 mode[0] = 'D';
360 if (ismode (mode_bits, S_IXOTH))
361 mode[9] = 'x';
362 if (ismode (mode_bits, S_IWOTH))
363 mode[8] = 'w';
364 if (ismode (mode_bits, S_IROTH))
365 mode[7] = 'r';
366 if (ismode (mode_bits, S_IXGRP))
367 mode[6] = 'x';
368 if (ismode (mode_bits, S_IWGRP))
369 mode[5] = 'w';
370 if (ismode (mode_bits, S_IRGRP))
371 mode[4] = 'r';
372 if (ismode (mode_bits, S_IXUSR))
373 mode[3] = 'x';
374 if (ismode (mode_bits, S_IWUSR))
375 mode[2] = 'w';
376 if (ismode (mode_bits, S_IRUSR))
377 mode[1] = 'r';
378 #ifdef S_ISUID
379 if (ismode (mode_bits, S_ISUID))
380 mode[3] = (mode[3] == 'x') ? 's' : 'S';
381 #endif /* S_ISUID */
382 #ifdef S_ISGID
383 if (ismode (mode_bits, S_ISGID))
384 mode[6] = (mode[6] == 'x') ? 's' : 'S';
385 #endif /* S_ISGID */
386 #ifdef S_ISVTX
387 if (ismode (mode_bits, S_ISVTX))
388 mode[9] = (mode[9] == 'x') ? 't' : 'T';
389 #endif /* S_ISVTX */
390 return mode;
393 /* p: string which might contain an url with a password (this parameter is
394 modified in place).
395 has_prefix = 0: The first parameter is an url without a prefix
396 (user[:pass]@]machine[:port][remote-dir). Delete
397 the password.
398 has_prefix = 1: Search p for known url prefixes. If found delete
399 the password from the url.
400 Cavevat: only the first url is found
402 char *
403 strip_password (char *p, int has_prefix)
405 static const struct {
406 char *name;
407 size_t len;
408 } prefixes[] = { {"/#ftp:", 6},
409 {"/#mc:", 5},
410 {"ftp://", 6},
411 {"/#smb:", 6},
413 char *at, *inner_colon, *dir;
414 int i;
415 char *result = p;
417 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
418 char *q;
420 if (has_prefix) {
421 if((q = strstr (p, prefixes[i].name)) == 0)
422 continue;
423 else
424 p = q + prefixes[i].len;
427 if ((dir = strchr (p, PATH_SEP)) != NULL)
428 *dir = '\0';
429 /* search for any possible user */
430 at = strchr (p, '@');
432 /* We have a username */
433 if (at) {
434 *at = 0;
435 inner_colon = strchr (p, ':');
436 *at = '@';
437 if (inner_colon)
438 strcpy (inner_colon, at);
440 if (dir)
441 *dir = PATH_SEP;
442 break;
444 return (result);
447 char *strip_home_and_password(const char *dir)
449 size_t len;
450 static char newdir [MC_MAXPATHLEN];
452 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
453 (dir[len] == PATH_SEP || dir[len] == '\0')){
454 newdir [0] = '~';
455 strcpy (&newdir [1], &dir [len]);
456 return newdir;
459 /* We do not strip homes in /#ftp tree, I do not like ~'s there
460 (see ftpfs.c why) */
461 strcpy (newdir, dir);
462 strip_password (newdir, 1);
463 return newdir;
466 static char *maybe_start_group (char *d, int do_group, int *was_wildcard)
468 if (!do_group)
469 return d;
470 if (*was_wildcard)
471 return d;
472 *was_wildcard = 1;
473 *d++ = '\\';
474 *d++ = '(';
475 return d;
478 static char *maybe_end_group (char *d, int do_group, int *was_wildcard)
480 if (!do_group)
481 return d;
482 if (!*was_wildcard)
483 return d;
484 *was_wildcard = 0;
485 *d++ = '\\';
486 *d++ = ')';
487 return d;
490 /* If shell patterns are on converts a shell pattern to a regular
491 expression. Called by regexp_match and mask_rename. */
492 /* Shouldn't we support [a-fw] type wildcards as well ?? */
493 char *convert_pattern (char *pattern, int match_type, int do_group)
495 char *s, *d;
496 char *new_pattern;
497 int was_wildcard = 0;
499 if (easy_patterns){
500 new_pattern = g_malloc (MC_MAXPATHLEN);
501 d = new_pattern;
502 if (match_type == match_file)
503 *d++ = '^';
504 for (s = pattern; *s; s++, d++){
505 switch (*s){
506 case '*':
507 d = maybe_start_group (d, do_group, &was_wildcard);
508 *d++ = '.';
509 *d = '*';
510 break;
512 case '?':
513 d = maybe_start_group (d, do_group, &was_wildcard);
514 *d = '.';
515 break;
517 case '.':
518 d = maybe_end_group (d, do_group, &was_wildcard);
519 *d++ = '\\';
520 *d = '.';
521 break;
523 default:
524 d = maybe_end_group (d, do_group, &was_wildcard);
525 *d = *s;
526 break;
529 d = maybe_end_group (d, do_group, &was_wildcard);
530 if (match_type == match_file)
531 *d++ = '$';
532 *d = 0;
533 return new_pattern;
534 } else
535 return g_strdup (pattern);
538 int regexp_match (char *pattern, char *string, int match_type)
540 static regex_t r;
541 static char *old_pattern = NULL;
542 static int old_type;
543 int rval;
545 if (!old_pattern || STRCOMP (old_pattern, pattern) || old_type != match_type){
546 if (old_pattern){
547 regfree (&r);
548 g_free (old_pattern);
549 old_pattern = NULL;
551 pattern = convert_pattern (pattern, match_type, 0);
552 if (regcomp (&r, pattern, REG_EXTENDED|REG_NOSUB|MC_ARCH_FLAGS)) {
553 g_free (pattern);
554 return -1;
556 old_pattern = pattern;
557 old_type = match_type;
559 rval = !regexec (&r, string, 0, NULL, 0);
560 return rval;
563 char *extension (char *filename)
565 char *d;
567 if (!(*filename))
568 return "";
570 d = filename + strlen (filename) - 1;
571 for (;d >= filename; d--){
572 if (*d == '.')
573 return d+1;
575 return "";
578 int get_int (char *file, char *key, int def)
580 return GetPrivateProfileInt (app_text, key, def, file);
583 int set_int (char *file, char *key, int value)
585 char buffer [BUF_TINY];
587 g_snprintf (buffer, sizeof (buffer), "%d", value);
588 return WritePrivateProfileString (app_text, key, buffer, file);
591 int exist_file (char *name)
593 return access (name, R_OK) == 0;
596 char *load_file (char *filename)
598 FILE *data_file;
599 struct stat s;
600 char *data;
601 long read_size;
603 if ((data_file = fopen (filename, "r")) == NULL){
604 return 0;
606 if (fstat (fileno (data_file), &s) != 0){
607 fclose (data_file);
608 return 0;
610 data = (char *) g_malloc (s.st_size+1);
611 read_size = fread (data, 1, s.st_size, data_file);
612 data [read_size] = 0;
613 fclose (data_file);
615 if (read_size > 0)
616 return data;
617 else {
618 g_free (data);
619 return 0;
623 char *load_mc_home_file (const char *filename, char ** allocated_filename)
625 char *hintfile_base, *hintfile;
626 char *lang;
627 char *data;
629 hintfile_base = concat_dir_and_file (mc_home, filename);
630 lang = guess_message_value ();
632 hintfile = g_strdup_printf ("%s.%s", hintfile_base, lang);
633 data = load_file (hintfile);
635 if (!data) {
636 g_free (hintfile);
637 hintfile = g_strdup_printf ("%s.%.2s", hintfile_base, lang);
638 data = load_file (hintfile);
640 if (!data) {
641 g_free (hintfile);
642 hintfile = hintfile_base;
643 data = load_file (hintfile_base);
647 g_free (lang);
649 if (hintfile != hintfile_base)
650 g_free (hintfile_base);
652 if (allocated_filename)
653 *allocated_filename = hintfile;
654 else
655 g_free (hintfile);
657 return data;
660 /* Check strftime() results. Some systems (i.e. Solaris) have different
661 short-month-name sizes for different locales */
662 size_t i18n_checktimelength (void)
664 size_t length, a, b;
665 char buf [MAX_I18NTIMELENGTH + 1];
666 time_t testtime = time (NULL);
668 a = strftime (buf, sizeof(buf)-1, _("%b %e %H:%M"), localtime(&testtime));
669 b = strftime (buf, sizeof(buf)-1, _("%b %e %Y"), localtime(&testtime));
671 length = max (a, b);
673 /* Don't handle big differences. Use standard value (email bug, please) */
674 if ( length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH )
675 length = STD_I18NTIMELENGTH;
677 return length;
680 char *file_date (time_t when)
682 static char timebuf [MAX_I18NTIMELENGTH + 1];
683 time_t current_time = time ((time_t) 0);
684 static size_t i18n_timelength = 0;
685 static char *fmtyear, *fmttime;
686 char *fmt;
688 if (i18n_timelength == 0){
689 i18n_timelength = i18n_checktimelength() + 1;
691 /* strftime() format string for old dates */
692 fmtyear = _("%b %e %Y");
693 /* strftime() format string for recent dates */
694 fmttime = _("%b %e %H:%M");
697 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
698 || current_time < when - 60L * 60L) /* In the future. */
699 /* The file is fairly old or in the future.
700 POSIX says the cutoff is 6 months old;
701 approximate this by 6*30 days.
702 Allow a 1 hour slop factor for what is considered "the future",
703 to allow for NFS server/client clock disagreement.
704 Show the year instead of the time of day. */
706 fmt = fmtyear;
707 else
708 fmt = fmttime;
710 strftime (timebuf, i18n_timelength, fmt, localtime(&when));
711 return timebuf;
714 char *extract_line (char *s, char *top)
716 static char tmp_line [BUF_MEDIUM];
717 char *t = tmp_line;
719 while (*s && *s != '\n' && (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
720 *t++ = *s++;
721 *t = 0;
722 return tmp_line;
725 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
726 char * _icase_search (char *text, char *data, int *lng)
728 char *d = text;
729 char *e = data;
730 int dlng = 0;
732 if (lng)
733 *lng = 0;
734 for (;*e; e++) {
735 while (*(e+1) == '\b' && *(e+2)) {
736 e += 2;
737 dlng += 2;
739 if (toupper((unsigned char) *d) == toupper((unsigned char) *e))
740 d++;
741 else {
742 e -= d - text;
743 d = text;
744 dlng = 0;
746 if (!*d) {
747 if (lng)
748 *lng = strlen (text) + dlng;
749 return e+1;
752 return 0;
755 /* The basename routine */
756 char *x_basename (char *s)
758 char *where;
759 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
763 char *unix_error_string (int error_num)
765 static char buffer [BUF_LARGE];
767 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
768 g_strerror (error_num), error_num);
769 return buffer;
772 char *skip_separators (char *s)
774 for (;*s; s++)
775 if (*s != ' ' && *s != '\t' && *s != ',')
776 break;
777 return s;
780 char *skip_numbers (char *s)
782 for (;*s; s++)
783 if (!isdigit ((unsigned int) *s))
784 break;
785 return s;
788 /* Remove all control sequences from the argument string. We define
789 * "control sequence", in a sort of pidgin BNF, as follows:
791 * control-seq = Esc non-'['
792 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
794 * This scheme works for all the terminals described in my termcap /
795 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
796 * terminals. If I hear from a single person who uses such a terminal
797 * with MC, I'll be glad to add support for it. (Dugan)
798 * Non-printable characters are also removed.
801 char *strip_ctrl_codes (char *s)
803 char *w; /* Current position where the stripped data is written */
804 char *r; /* Current position where the original data is read */
806 if (!s)
807 return 0;
809 for (w = s, r = s; *r; ) {
810 if (*r == ESC_CHAR) {
811 /* Skip the control sequence's arguments */ ;
812 if (*(++r) == '[') {
813 /* strchr() matches trailing binary 0 */
814 while (*(++r) && strchr ("0123456789;?", *r));
818 * Now we are at the last character of the sequence.
819 * Skip it unless it's binary 0.
821 if (*r)
822 r++;
823 continue;
826 if (is_printable(*r))
827 *w++ = *r;
828 ++r;
830 *w = 0;
831 return s;
835 #ifndef USE_VFS
836 char *get_current_wd (char *buffer, int size)
838 char *p;
839 int len;
841 p = g_get_current_dir ();
842 len = strlen(p) + 1;
844 if (len > size) {
845 g_free (p);
846 return NULL;
849 strncpy (buffer, p, len);
850 g_free (p);
852 return buffer;
854 #endif /* !USE_VFS */
856 /* This function returns 0 if the file is not in not compressed by
857 * one of the supported compressors (gzip, bzip, bzip2). Otherwise,
858 * the compression type is returned, as defined in util.h
859 * Warning: this function moves the current file pointer */
860 int get_compression_type (int fd)
862 unsigned char magic[4];
864 /* Read the magic signature */
865 if (mc_read (fd, (char *) magic, 4) != 4)
866 return COMPRESSION_NONE;
868 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
869 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
870 return COMPRESSION_GZIP;
873 /* PKZIP_MAGIC */
874 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
875 && magic[3] == 004) {
876 /* Read compression type */
877 mc_lseek (fd, 8, SEEK_SET);
878 if (mc_read (fd, (char *) magic, 2) != 2)
879 return COMPRESSION_NONE;
881 /* Gzip can handle only deflated (8) or stored (0) files */
882 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
883 return COMPRESSION_NONE;
885 /* Compatible with gzip */
886 return COMPRESSION_GZIP;
889 /* PACK_MAGIC and LZH_MAGIC and compress magic */
890 if (magic[0] == 037
891 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
892 /* Compatible with gzip */
893 return COMPRESSION_GZIP;
896 /* BZIP and BZIP2 files */
897 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
898 (magic[3] >= '1') && (magic[3] <= '9')) {
899 switch (magic[2]) {
900 case '0':
901 return COMPRESSION_BZIP;
902 case 'h':
903 return COMPRESSION_BZIP2;
906 return 0;
909 const char *
910 decompress_extension (int type)
912 switch (type){
913 case COMPRESSION_GZIP: return "#ugz";
914 case COMPRESSION_BZIP: return "#ubz";
915 case COMPRESSION_BZIP2: return "#ubz2";
917 /* Should never reach this place */
918 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
919 return 0;
922 /* Hooks */
923 void add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
925 Hook *new_hook = g_new (Hook, 1);
927 new_hook->hook_fn = hook_fn;
928 new_hook->next = *hook_list;
929 new_hook->hook_data = data;
931 *hook_list = new_hook;
934 void execute_hooks (Hook *hook_list)
936 Hook *new_hook = 0;
937 Hook *p;
939 /* We copy the hook list first so tahat we let the hook
940 * function call delete_hook
943 while (hook_list){
944 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
945 hook_list = hook_list->next;
947 p = new_hook;
949 while (new_hook){
950 (*new_hook->hook_fn)(new_hook->hook_data);
951 new_hook = new_hook->next;
954 for (hook_list = p; hook_list;){
955 p = hook_list;
956 hook_list = hook_list->next;
957 g_free (p);
961 void delete_hook (Hook **hook_list, void (*hook_fn)(void *))
963 Hook *current, *new_list, *next;
965 new_list = 0;
967 for (current = *hook_list; current; current = next){
968 next = current->next;
969 if (current->hook_fn == hook_fn)
970 g_free (current);
971 else
972 add_hook (&new_list, current->hook_fn, current->hook_data);
974 *hook_list = new_list;
977 int hook_present (Hook *hook_list, void (*hook_fn)(void *))
979 Hook *p;
981 for (p = hook_list; p; p = p->next)
982 if (p->hook_fn == hook_fn)
983 return 1;
984 return 0;
987 void wipe_password (char *passwd)
989 char *p = passwd;
991 if (!p)
992 return;
993 for (;*p ; p++)
994 *p = 0;
995 g_free (passwd);
998 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
999 /* Returns a newly allocated string */
1000 char *convert_controls (char *s)
1002 char *valcopy = g_strdup (s);
1003 char *p, *q;
1005 /* Parse the escape special character */
1006 for (p = s, q = valcopy; *p;){
1007 if (*p == '\\'){
1008 p++;
1009 if ((*p == 'e') || (*p == 'E')){
1010 p++;
1011 *q++ = ESC_CHAR;
1013 } else {
1014 if (*p == '^'){
1015 p++;
1016 if (*p == '^')
1017 *q++ = *p++;
1018 else {
1019 *p = (*p | 0x20);
1020 if (*p >= 'a' && *p <= 'z') {
1021 *q++ = *p++ - 'a' + 1;
1022 } else
1023 p++;
1025 } else
1026 *q++ = *p++;
1029 *q = 0;
1030 return valcopy;
1033 static char *resolve_symlinks (char *path)
1035 char *buf, *buf2, *p, *q, *r, c;
1036 int len;
1037 struct stat mybuf;
1039 if (*path != PATH_SEP)
1040 return NULL;
1041 r = buf = g_malloc (MC_MAXPATHLEN);
1042 buf2 = g_malloc (MC_MAXPATHLEN);
1043 *r++ = PATH_SEP;
1044 *r = 0;
1045 p = path;
1046 for (;;) {
1047 q = strchr (p + 1, PATH_SEP);
1048 if (!q) {
1049 q = strchr (p + 1, 0);
1050 if (q == p + 1)
1051 break;
1053 c = *q;
1054 *q = 0;
1055 if (mc_lstat (path, &mybuf) < 0) {
1056 g_free (buf);
1057 g_free (buf2);
1058 *q = c;
1059 return NULL;
1061 if (!S_ISLNK (mybuf.st_mode))
1062 strcpy (r, p + 1);
1063 else {
1064 len = mc_readlink (path, buf2, MC_MAXPATHLEN);
1065 if (len < 0) {
1066 g_free (buf);
1067 g_free (buf2);
1068 *q = c;
1069 return NULL;
1071 buf2 [len] = 0;
1072 if (*buf2 == PATH_SEP)
1073 strcpy (buf, buf2);
1074 else
1075 strcpy (r, buf2);
1077 canonicalize_pathname (buf);
1078 r = strchr (buf, 0);
1079 if (!*r || *(r - 1) != PATH_SEP) {
1080 *r++ = PATH_SEP;
1081 *r = 0;
1083 *q = c;
1084 p = q;
1085 if (!c)
1086 break;
1088 if (!*buf)
1089 strcpy (buf, PATH_SEP_STR);
1090 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1091 *(r - 1) = 0;
1092 g_free (buf2);
1093 return buf;
1096 /* Finds out a relative path from first to second, i.e. goes as many ..
1097 * as needed up in first and then goes down using second */
1098 char *diff_two_paths (char *first, char *second)
1100 char *p, *q, *r, *s, *buf = 0;
1101 int i, j, prevlen = -1, currlen;
1103 first = resolve_symlinks (first);
1104 if (first == NULL)
1105 return NULL;
1106 for (j = 0; j < 2; j++) {
1107 p = first;
1108 if (j) {
1109 second = resolve_symlinks (second);
1110 if (second == NULL) {
1111 g_free (first);
1112 return buf;
1115 q = second;
1116 for (;;) {
1117 r = strchr (p, PATH_SEP);
1118 s = strchr (q, PATH_SEP);
1119 if (!r || !s)
1120 break;
1121 *r = 0; *s = 0;
1122 if (strcmp (p, q)) {
1123 *r = PATH_SEP; *s = PATH_SEP;
1124 break;
1125 } else {
1126 *r = PATH_SEP; *s = PATH_SEP;
1128 p = r + 1;
1129 q = s + 1;
1131 p--;
1132 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1133 currlen = (i + 1) * 3 + strlen (q) + 1;
1134 if (j) {
1135 if (currlen < prevlen)
1136 g_free (buf);
1137 else {
1138 g_free (first);
1139 g_free (second);
1140 return buf;
1143 p = buf = g_malloc (currlen);
1144 prevlen = currlen;
1145 for (; i >= 0; i--, p += 3)
1146 strcpy (p, "../");
1147 strcpy (p, q);
1149 g_free (first);
1150 g_free (second);
1151 return buf;
1154 /* If filename is NULL, then we just append PATH_SEP to the dir */
1155 char *
1156 concat_dir_and_file (const char *dir, const char *file)
1158 int i = strlen (dir);
1160 if (dir [i-1] == PATH_SEP)
1161 return g_strconcat (dir, file, NULL);
1162 else
1163 return g_strconcat (dir, PATH_SEP_STR, file, NULL);
1167 /* Append text to GList, remove all entries with the same text */
1168 GList *
1169 list_append_unique (GList *list, char *text)
1171 GList *link, *newlink;
1174 * Go to the last position and traverse the list backwards
1175 * starting from the second last entry to make sure that we
1176 * are not removing the current link.
1178 list = g_list_append (list, text);
1179 list = g_list_last (list);
1180 link = g_list_previous (list);
1182 while (link) {
1183 newlink = g_list_previous (link);
1184 if (!strcmp ((char *) link->data, text)) {
1185 g_list_remove_link (list, link);
1186 g_list_free_1 (link);
1188 link = newlink;
1191 return list;
1195 /* Following code heavily borrows from libiberty, mkstemps.c */
1197 /* Number of attempts to create a temporary file */
1198 #ifndef TMP_MAX
1199 #define TMP_MAX 16384
1200 #endif /* !TMP_MAX */
1203 * Arguments:
1204 * pname (output) - pointer to the name of the temp file (needs g_free).
1205 * NULL if the function fails.
1206 * prefix - part of the filename before the random part.
1207 * Prepend $TMPDIR or /tmp if there are no path separators.
1208 * suffix - if not NULL, part of the filename after the random part.
1210 * Result:
1211 * handle of the open file or -1 if couldn't open any.
1214 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1216 static const char letters[]
1217 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1218 static unsigned long value;
1219 struct timeval tv;
1220 char *tmpbase;
1221 char *tmpname;
1222 char *XXXXXX;
1223 int count;
1225 if (strchr (prefix, PATH_SEP) == NULL) {
1226 /* Add prefix first to find the position of XXXXXX */
1227 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1228 } else {
1229 tmpbase = g_strdup (prefix);
1232 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, NULL);
1233 *pname = tmpname;
1234 XXXXXX = &tmpname[strlen (tmpbase)];
1235 g_free (tmpbase);
1237 /* Get some more or less random data. */
1238 gettimeofday (&tv, NULL);
1239 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1241 for (count = 0; count < TMP_MAX; ++count) {
1242 unsigned long v = value;
1243 int fd;
1245 /* Fill in the random bits. */
1246 XXXXXX[0] = letters[v % 62];
1247 v /= 62;
1248 XXXXXX[1] = letters[v % 62];
1249 v /= 62;
1250 XXXXXX[2] = letters[v % 62];
1251 v /= 62;
1252 XXXXXX[3] = letters[v % 62];
1253 v /= 62;
1254 XXXXXX[4] = letters[v % 62];
1255 v /= 62;
1256 XXXXXX[5] = letters[v % 62];
1258 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1259 S_IRUSR | S_IWUSR);
1260 if (fd >= 0) {
1261 /* Successfully created. */
1262 return fd;
1265 /* This is a random value. It is only necessary that the next
1266 TMP_MAX values generated by adding 7777 to VALUE are different
1267 with (module 2^32). */
1268 value += 7777;
1271 /* Unsuccessful. Free the filename. */
1272 g_free (tmpname);
1273 *pname = NULL;
1275 return -1;
1280 * Read and restore position for the given filename.
1281 * If there is no stored data, return line 1 and col 0.
1283 void
1284 load_file_position (char *filename, long *line, long *column)
1286 char *fn;
1287 FILE *f;
1288 char buf[MC_MAXPATHLEN + 20];
1289 int len;
1291 /* defaults */
1292 *line = 1;
1293 *column = 0;
1295 /* open file with positions */
1296 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1297 f = fopen (fn, "r");
1298 g_free (fn);
1299 if (!f)
1300 return;
1302 len = strlen (filename);
1304 while (fgets (buf, sizeof (buf), f)) {
1305 char *p;
1307 /* check if the filename matches the beginning of string */
1308 if (strncmp (buf, filename, len) != 0)
1309 continue;
1311 /* followed by single space */
1312 if (buf[len] != ' ')
1313 continue;
1315 /* and string without spaces */
1316 p = &buf[len + 1];
1317 if (strchr (p, ' '))
1318 continue;
1320 *line = atol (p);
1321 p = strchr (buf, ';');
1322 *column = atol (&p[1]);
1324 fclose (f);
1327 /* Save position for the given file */
1328 void
1329 save_file_position (char *filename, long line, long column)
1331 char *tmp, *fn;
1332 FILE *f, *t;
1333 char buf[MC_MAXPATHLEN + 20];
1334 int i = 1;
1335 int len;
1337 len = strlen (filename);
1339 tmp = concat_dir_and_file (home_dir, MC_FILEPOS_TMP);
1340 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1342 /* open temporary file */
1343 t = fopen (tmp, "w");
1344 if (!t) {
1345 g_free (tmp);
1346 g_free (fn);
1347 return;
1350 /* put the new record */
1351 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1353 /* copy records from the old file */
1354 f = fopen (fn, "r");
1355 if (f) {
1356 while (fgets (buf, sizeof (buf), f)) {
1357 /* Skip entries for the current filename */
1358 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1359 && !strchr (&buf[len + 1], ' '))
1360 continue;
1362 fprintf (t, "%s", buf);
1363 if (++i > MC_FILEPOS_ENTRIES)
1364 break;
1366 fclose (f);
1369 fclose (t);
1370 rename (tmp, fn);
1371 g_free (tmp);
1372 g_free (fn);