small typo
[midnight-commander.git] / src / util.c
blob25121d26461b9213f3d4947361d301da30d711f4
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 <signal.h> /* my_system */
31 #include <limits.h> /* INT_MAX */
32 #include <sys/stat.h>
33 #include <stdarg.h>
34 #include <errno.h> /* my_system */
35 #include <string.h>
36 #include <ctype.h>
38 #include "global.h"
39 #include "profile.h"
40 #include "main.h" /* mc_home */
41 #include "cmd.h" /* guess_message_value */
42 #include "../vfs/vfs.h"
43 #include "mountlist.h"
44 #include "win.h" /* xterm_flag */
46 #ifdef HAVE_CHARSET
47 #include "charsets.h"
48 #endif
50 /* "$Id$" */
52 static const char app_text [] = "Midnight-Commander";
53 int easy_patterns = 1;
55 static inline int
56 is_7bit_printable (unsigned char c)
58 return (c > 31 && c < 127);
61 static inline int
62 is_iso_printable (unsigned char c)
64 return ((c > 31 && c < 127) || c >= 160);
67 static inline int
68 is_8bit_printable (unsigned char c)
70 /* "Full 8 bits output" doesn't work on xterm */
71 if (xterm_flag)
72 return is_iso_printable (c);
74 return (c > 31 && c != 127 && c != 155);
77 int
78 is_printable (int c)
80 c &= 0xff;
82 #ifdef HAVE_CHARSET
83 /* "Display bits" is ignored, since the user controls the output
84 by setting the output codepage */
85 return is_8bit_printable (c);
86 #else
87 if (!eight_bit_clean)
88 return is_7bit_printable (c);
90 if (full_eight_bits) {
91 return is_8bit_printable (c);
92 } else
93 return is_iso_printable (c);
94 #endif /* !HAVE_CHARSET */
97 /* Returns the message dimensions (lines and columns) */
98 int msglen (char *text, int *lines)
100 int max = 0;
101 int line_len = 0;
103 for (*lines = 1;*text; text++){
104 if (*text == '\n'){
105 line_len = 0;
106 (*lines)++;
107 } else {
108 line_len++;
109 if (line_len > max)
110 max = line_len;
113 return max;
117 * Copy from s to d, and trim the beginning if necessary, and prepend
118 * "..." in this case. The destination string can have at most len
119 * bytes, not counting trailing 0.
121 char *
122 trim (char *s, char *d, int len)
124 int source_len;
126 /* Sanity check */
127 len = max (len, 0);
129 source_len = strlen (s);
130 if (source_len > len) {
131 /* Cannot fit the whole line */
132 if (len <= 3) {
133 /* We only have room for the dots */
134 memset (d, '.', len);
135 d[len] = 0;
136 return d;
137 } else {
138 /* Begin with ... and add the rest of the source string */
139 memset (d, '.', 3);
140 strcpy (d + 3, s + 3 + source_len - len);
142 } else
143 /* We can copy the whole line */
144 strcpy (d, s);
145 return d;
148 char *
149 name_quote (const char *s, int quote_percent)
151 char *ret, *d;
153 d = ret = g_malloc (strlen (s)*2 + 2 + 1);
154 if (*s == '-') {
155 *d++ = '.';
156 *d++ = '/';
159 for (; *s; s++, d++) {
160 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 case '^':
190 case '&':
191 case '*':
192 case '(':
193 case ')':
194 *d++ = '\\';
196 *d = *s;
198 *d = '\0';
199 return ret;
202 char *
203 fake_name_quote (const char *s, int quote_percent)
205 return g_strdup (s);
208 /* If passed an empty txt (this usually means that there is an error)
209 * in the upper layers, we return "/"
211 char *name_trunc (const char *txt, int trunc_len)
213 static char x [MC_MAXPATHLEN+MC_MAXPATHLEN];
214 int txt_len;
215 char *p;
216 const int tilde_trunc = 1;
218 if (!txt)
219 txt = PATH_SEP_STR;
221 if (trunc_len > sizeof (x)-1){
222 fprintf (stderr, _("name_trunc: too big"));
223 trunc_len = sizeof (x)-1;
225 txt_len = strlen (txt);
226 if (txt_len <= trunc_len)
227 strcpy (x, txt);
228 else if (tilde_trunc){
229 int y = (trunc_len/2) + (trunc_len % 2);
230 strncpy (x, txt, y);
231 strncpy (x+y, txt+txt_len-(trunc_len/2), trunc_len/2);
232 x [y] = '~';
233 } else {
234 strncpy (x, txt, trunc_len-1);
235 x [trunc_len-1] = '>';
237 x [trunc_len] = 0;
238 for (p = x; *p; p++)
239 if (!is_printable (*p))
240 *p = '?';
241 return x;
244 char *size_trunc (double size)
246 static char x [BUF_TINY];
247 long int divisor = 1;
248 char *xtra = "";
250 if (size > 999999999L){
251 divisor = 1024;
252 xtra = "Kb";
253 if (size/divisor > 999999999L){
254 divisor = 1024*1024;
255 xtra = "Mb";
258 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
259 return x;
262 char *size_trunc_sep (double size)
264 static char x [60];
265 int count;
266 char *p, *d, *y;
268 p = y = size_trunc (size);
269 p += strlen (p) - 1;
270 d = x + sizeof (x) - 1;
271 *d-- = 0;
272 while (p >= y && isalpha ((unsigned char) *p))
273 *d-- = *p--;
274 for (count = 0; p >= y; count++){
275 if (count == 3){
276 *d-- = ',';
277 count = 0;
279 *d-- = *p--;
281 d++;
282 if (*d == ',')
283 d++;
284 return d;
288 * Print file SIZE to BUFFER, but don't exceed LEN characters,
289 * not including trailing 0. BUFFER should be at least LEN+1 long.
290 * This function is called for every file on panels, so avoid
291 * floating point by any means.
293 * Units: size units (filesystem sizes are 1K blocks)
294 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
296 void
297 size_trunc_len (char *buffer, int len, off_t size, int units)
299 /* Avoid taking power for every file. */
300 static const off_t power10 [] =
301 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
302 1000000000};
303 static const char * const suffix [] =
304 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
305 int j = 0;
307 /* Don't print more than 9 digits - use suffix. */
308 if (len == 0 || len > 9)
309 len = 9;
311 for (j = units; suffix [j] != NULL; j++) {
312 if (size == 0) {
313 if (j == units) {
314 /* Empty files will print "0" even with minimal width. */
315 g_snprintf (buffer, len + 1, "0");
316 break;
319 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
320 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
321 (j > 1) ? suffix[j - 1] : "B");
322 break;
325 if (size < power10 [len - (j > 0)]) {
326 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
327 break;
330 /* Powers of 1024, with rounding. */
331 size = (size + 512) >> 10;
335 int is_exe (mode_t mode)
337 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
338 return 1;
339 return 0;
342 #define ismode(n,m) ((n & m) == m)
344 char *
345 string_perm (mode_t mode_bits)
347 static char mode[11];
349 strcpy (mode, "----------");
350 if (S_ISDIR (mode_bits))
351 mode[0] = 'd';
352 if (S_ISCHR (mode_bits))
353 mode[0] = 'c';
354 if (S_ISBLK (mode_bits))
355 mode[0] = 'b';
356 if (S_ISLNK (mode_bits))
357 mode[0] = 'l';
358 if (S_ISFIFO (mode_bits))
359 mode[0] = 'p';
360 if (S_ISSOCK (mode_bits))
361 mode[0] = 's';
362 if (S_ISDOOR (mode_bits))
363 mode[0] = 'D';
364 if (ismode (mode_bits, S_IXOTH))
365 mode[9] = 'x';
366 if (ismode (mode_bits, S_IWOTH))
367 mode[8] = 'w';
368 if (ismode (mode_bits, S_IROTH))
369 mode[7] = 'r';
370 if (ismode (mode_bits, S_IXGRP))
371 mode[6] = 'x';
372 if (ismode (mode_bits, S_IWGRP))
373 mode[5] = 'w';
374 if (ismode (mode_bits, S_IRGRP))
375 mode[4] = 'r';
376 if (ismode (mode_bits, S_IXUSR))
377 mode[3] = 'x';
378 if (ismode (mode_bits, S_IWUSR))
379 mode[2] = 'w';
380 if (ismode (mode_bits, S_IRUSR))
381 mode[1] = 'r';
382 #ifdef S_ISUID
383 if (ismode (mode_bits, S_ISUID))
384 mode[3] = (mode[3] == 'x') ? 's' : 'S';
385 #endif /* S_ISUID */
386 #ifdef S_ISGID
387 if (ismode (mode_bits, S_ISGID))
388 mode[6] = (mode[6] == 'x') ? 's' : 'S';
389 #endif /* S_ISGID */
390 #ifdef S_ISVTX
391 if (ismode (mode_bits, S_ISVTX))
392 mode[9] = (mode[9] == 'x') ? 't' : 'T';
393 #endif /* S_ISVTX */
394 return mode;
397 /* p: string which might contain an url with a password (this parameter is
398 modified in place).
399 has_prefix = 0: The first parameter is an url without a prefix
400 (user[:pass]@]machine[:port][remote-dir). Delete
401 the password.
402 has_prefix = 1: Search p for known url prefixes. If found delete
403 the password from the url.
404 Cavevat: only the first url is found
406 char *
407 strip_password (char *p, int has_prefix)
409 static const struct {
410 char *name;
411 size_t len;
412 } prefixes[] = { {"/#ftp:", 6},
413 {"/#mc:", 5},
414 {"ftp://", 6},
415 {"/#smb:", 6},
417 char *at, *inner_colon, *dir;
418 int i;
419 char *result = p;
421 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
422 char *q;
424 if (has_prefix) {
425 if((q = strstr (p, prefixes[i].name)) == 0)
426 continue;
427 else
428 p = q + prefixes[i].len;
431 if ((dir = strchr (p, PATH_SEP)) != NULL)
432 *dir = '\0';
433 /* search for any possible user */
434 at = strchr (p, '@');
436 /* We have a username */
437 if (at) {
438 *at = 0;
439 inner_colon = strchr (p, ':');
440 *at = '@';
441 if (inner_colon)
442 strcpy (inner_colon, at);
444 if (dir)
445 *dir = PATH_SEP;
446 break;
448 return (result);
451 char *strip_home_and_password(char *dir)
453 size_t len;
454 static char newdir [MC_MAXPATHLEN];
456 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
457 (dir[len] == PATH_SEP || dir[len] == '\0')){
458 newdir [0] = '~';
459 strcpy (&newdir [1], &dir [strlen (home_dir)]);
460 return newdir;
463 /* We do not strip homes in /#ftp tree, I do not like ~'s there
464 (see ftpfs.c why) */
465 strcpy (newdir, dir);
466 strip_password (newdir, 1);
467 return newdir;
470 static char *maybe_start_group (char *d, int do_group, int *was_wildcard)
472 if (!do_group)
473 return d;
474 if (*was_wildcard)
475 return d;
476 *was_wildcard = 1;
477 *d++ = '\\';
478 *d++ = '(';
479 return d;
482 static char *maybe_end_group (char *d, int do_group, int *was_wildcard)
484 if (!do_group)
485 return d;
486 if (!*was_wildcard)
487 return d;
488 *was_wildcard = 0;
489 *d++ = '\\';
490 *d++ = ')';
491 return d;
494 /* If shell patterns are on converts a shell pattern to a regular
495 expression. Called by regexp_match and mask_rename. */
496 /* Shouldn't we support [a-fw] type wildcards as well ?? */
497 char *convert_pattern (char *pattern, int match_type, int do_group)
499 char *s, *d;
500 char *new_pattern;
501 int was_wildcard = 0;
503 if (easy_patterns){
504 new_pattern = g_malloc (MC_MAXPATHLEN);
505 d = new_pattern;
506 if (match_type == match_file)
507 *d++ = '^';
508 for (s = pattern; *s; s++, d++){
509 switch (*s){
510 case '*':
511 d = maybe_start_group (d, do_group, &was_wildcard);
512 *d++ = '.';
513 *d = '*';
514 break;
516 case '?':
517 d = maybe_start_group (d, do_group, &was_wildcard);
518 *d = '.';
519 break;
521 case '.':
522 d = maybe_end_group (d, do_group, &was_wildcard);
523 *d++ = '\\';
524 *d = '.';
525 break;
527 default:
528 d = maybe_end_group (d, do_group, &was_wildcard);
529 *d = *s;
530 break;
533 d = maybe_end_group (d, do_group, &was_wildcard);
534 if (match_type == match_file)
535 *d++ = '$';
536 *d = 0;
537 return new_pattern;
538 } else
539 return g_strdup (pattern);
542 int regexp_match (char *pattern, char *string, int match_type)
544 static regex_t r;
545 static char *old_pattern = NULL;
546 static int old_type;
547 int rval;
549 if (!old_pattern || STRCOMP (old_pattern, pattern) || old_type != match_type){
550 if (old_pattern){
551 regfree (&r);
552 g_free (old_pattern);
553 old_pattern = NULL;
555 pattern = convert_pattern (pattern, match_type, 0);
556 if (regcomp (&r, pattern, REG_EXTENDED|REG_NOSUB|MC_ARCH_FLAGS)) {
557 g_free (pattern);
558 return -1;
560 old_pattern = pattern;
561 old_type = match_type;
563 rval = !regexec (&r, string, 0, NULL, 0);
564 return rval;
567 char *extension (char *filename)
569 char *d;
571 if (!(*filename))
572 return "";
574 d = filename + strlen (filename) - 1;
575 for (;d >= filename; d--){
576 if (*d == '.')
577 return d+1;
579 return "";
582 int get_int (char *file, char *key, int def)
584 return GetPrivateProfileInt (app_text, key, def, file);
587 int set_int (char *file, char *key, int value)
589 char buffer [BUF_TINY];
591 g_snprintf (buffer, sizeof (buffer), "%d", value);
592 return WritePrivateProfileString (app_text, key, buffer, file);
595 int exist_file (char *name)
597 return access (name, R_OK) == 0;
600 char *load_file (char *filename)
602 FILE *data_file;
603 struct stat s;
604 char *data;
605 long read_size;
607 if ((data_file = fopen (filename, "r")) == NULL){
608 return 0;
610 if (fstat (fileno (data_file), &s) != 0){
611 fclose (data_file);
612 return 0;
614 data = (char *) g_malloc (s.st_size+1);
615 read_size = fread (data, 1, s.st_size, data_file);
616 data [read_size] = 0;
617 fclose (data_file);
619 if (read_size > 0)
620 return data;
621 else {
622 g_free (data);
623 return 0;
627 char *load_mc_home_file (const char *filename, char ** allocated_filename)
629 char *hintfile_base, *hintfile;
630 char *lang;
631 char *data;
633 hintfile_base = concat_dir_and_file (mc_home, filename);
634 lang = guess_message_value ();
636 hintfile = g_strdup_printf ("%s.%s", hintfile_base, lang);
637 data = load_file (hintfile);
639 if (!data) {
640 g_free (hintfile);
641 hintfile = g_strdup_printf ("%s.%.2s", hintfile_base, lang);
642 data = load_file (hintfile);
644 if (!data) {
645 g_free (hintfile);
646 hintfile = hintfile_base;
647 data = load_file (hintfile_base);
651 g_free (lang);
653 if (hintfile != hintfile_base)
654 g_free (hintfile_base);
656 if (allocated_filename)
657 *allocated_filename = hintfile;
658 else
659 g_free (hintfile);
661 return data;
664 /* Check strftime() results. Some systems (i.e. Solaris) have different
665 short-month-name sizes for different locales */
666 size_t i18n_checktimelength (void)
668 size_t length, a, b;
669 char buf [MAX_I18NTIMELENGTH + 1];
670 time_t testtime = time (NULL);
672 a = strftime (buf, sizeof(buf)-1, _("%b %e %H:%M"), localtime(&testtime));
673 b = strftime (buf, sizeof(buf)-1, _("%b %e %Y"), localtime(&testtime));
675 length = max (a, b);
677 /* Don't handle big differences. Use standard value (email bug, please) */
678 if ( length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH )
679 length = STD_I18NTIMELENGTH;
681 return length;
684 char *file_date (time_t when)
686 static char timebuf [MAX_I18NTIMELENGTH + 1];
687 time_t current_time = time ((time_t) 0);
688 static size_t i18n_timelength = 0;
689 static char *fmtyear, *fmttime;
690 char *fmt;
692 if (i18n_timelength == 0){
693 i18n_timelength = i18n_checktimelength() + 1;
695 /* strftime() format string for old dates */
696 fmtyear = _("%b %e %Y");
697 /* strftime() format string for recent dates */
698 fmttime = _("%b %e %H:%M");
701 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
702 || current_time < when - 60L * 60L) /* In the future. */
703 /* The file is fairly old or in the future.
704 POSIX says the cutoff is 6 months old;
705 approximate this by 6*30 days.
706 Allow a 1 hour slop factor for what is considered "the future",
707 to allow for NFS server/client clock disagreement.
708 Show the year instead of the time of day. */
710 fmt = fmtyear;
711 else
712 fmt = fmttime;
714 strftime (timebuf, i18n_timelength, fmt, localtime(&when));
715 return timebuf;
718 char *extract_line (char *s, char *top)
720 static char tmp_line [BUF_MEDIUM];
721 char *t = tmp_line;
723 while (*s && *s != '\n' && (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
724 *t++ = *s++;
725 *t = 0;
726 return tmp_line;
729 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
730 char * _icase_search (char *text, char *data, int *lng)
732 char *d = text;
733 char *e = data;
734 int dlng = 0;
736 if (lng)
737 *lng = 0;
738 for (;*e; e++) {
739 while (*(e+1) == '\b' && *(e+2)) {
740 e += 2;
741 dlng += 2;
743 if (toupper((unsigned char) *d) == toupper((unsigned char) *e))
744 d++;
745 else {
746 e -= d - text;
747 d = text;
748 dlng = 0;
750 if (!*d) {
751 if (lng)
752 *lng = strlen (text) + dlng;
753 return e+1;
756 return 0;
759 /* The basename routine */
760 char *x_basename (char *s)
762 char *where;
763 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
767 char *unix_error_string (int error_num)
769 static char buffer [BUF_LARGE];
771 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
772 g_strerror (error_num), error_num);
773 return buffer;
776 char *skip_separators (char *s)
778 for (;*s; s++)
779 if (*s != ' ' && *s != '\t' && *s != ',')
780 break;
781 return s;
784 char *skip_numbers (char *s)
786 for (;*s; s++)
787 if (!isdigit ((unsigned int) *s))
788 break;
789 return s;
792 /* Remove all control sequences from the argument string. We define
793 * "control sequence", in a sort of pidgin BNF, as follows:
795 * control-seq = Esc non-'['
796 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
798 * This scheme works for all the terminals described in my termcap /
799 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
800 * terminals. If I hear from a single person who uses such a terminal
801 * with MC, I'll be glad to add support for it. (Dugan)
802 * Non-printable characters are also removed.
805 char *strip_ctrl_codes (char *s)
807 char *w; /* Current position where the stripped data is written */
808 char *r; /* Current position where the original data is read */
810 if (!s)
811 return 0;
813 for (w = s, r = s; *r; ) {
814 if (*r == ESC_CHAR) {
815 /* Skip the control sequence's arguments */ ;
816 if (*(++r) == '[') {
817 /* strchr() matches trailing binary 0 */
818 while (*(++r) && strchr ("0123456789;?", *r));
822 * Now we are at the last character of the sequence.
823 * Skip it unless it's binary 0.
825 if (*r)
826 r++;
827 continue;
830 if (is_printable(*r))
831 *w++ = *r;
832 ++r;
834 *w = 0;
835 return s;
839 #ifndef USE_VFS
840 char *get_current_wd (char *buffer, int size)
842 char *p;
843 int len;
845 p = g_get_current_dir ();
846 len = strlen(p) + 1;
848 if (len > size) {
849 g_free (p);
850 return NULL;
853 strncpy (buffer, p, len);
854 g_free (p);
856 return buffer;
858 #endif /* !USE_VFS */
860 /* This function returns 0 if the file is not in not compressed by
861 * one of the supported compressors (gzip, bzip, bzip2). Otherwise,
862 * the compression type is returned, as defined in util.h
863 * Warning: this function moves the current file pointer */
864 int get_compression_type (int fd)
866 unsigned char magic[4];
868 /* Read the magic signature */
869 if (mc_read (fd, &magic[0], 4) != 4)
870 return COMPRESSION_NONE;
872 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
873 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
874 return COMPRESSION_GZIP;
877 /* PKZIP_MAGIC */
878 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
879 && magic[3] == 004) {
880 /* Read compression type */
881 mc_lseek (fd, 8, SEEK_SET);
882 if (mc_read (fd, &magic[0], 2) != 2)
883 return COMPRESSION_NONE;
885 /* Gzip can handle only deflated (8) or stored (0) files */
886 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
887 return COMPRESSION_NONE;
889 /* Compatible with gzip */
890 return COMPRESSION_GZIP;
893 /* PACK_MAGIC and LZH_MAGIC and compress magic */
894 if (magic[0] == 037
895 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
896 /* Compatible with gzip */
897 return COMPRESSION_GZIP;
900 /* BZIP and BZIP2 files */
901 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
902 (magic[3] >= '1') && (magic[3] <= '9')) {
903 switch (magic[2]) {
904 case '0':
905 return COMPRESSION_BZIP;
906 case 'h':
907 return COMPRESSION_BZIP2;
910 return 0;
913 char *
914 decompress_extension (int type)
916 switch (type){
917 case COMPRESSION_GZIP: return "#ugz";
918 case COMPRESSION_BZIP: return "#ubz";
919 case COMPRESSION_BZIP2: return "#ubz2";
921 /* Should never reach this place */
922 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
923 return 0;
926 /* Hooks */
927 void add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
929 Hook *new_hook = g_new (Hook, 1);
931 new_hook->hook_fn = hook_fn;
932 new_hook->next = *hook_list;
933 new_hook->hook_data = data;
935 *hook_list = new_hook;
938 void execute_hooks (Hook *hook_list)
940 Hook *new_hook = 0;
941 Hook *p;
943 /* We copy the hook list first so tahat we let the hook
944 * function call delete_hook
947 while (hook_list){
948 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
949 hook_list = hook_list->next;
951 p = new_hook;
953 while (new_hook){
954 (*new_hook->hook_fn)(new_hook->hook_data);
955 new_hook = new_hook->next;
958 for (hook_list = p; hook_list;){
959 p = hook_list;
960 hook_list = hook_list->next;
961 g_free (p);
965 void delete_hook (Hook **hook_list, void (*hook_fn)(void *))
967 Hook *current, *new_list, *next;
969 new_list = 0;
971 for (current = *hook_list; current; current = next){
972 next = current->next;
973 if (current->hook_fn == hook_fn)
974 g_free (current);
975 else
976 add_hook (&new_list, current->hook_fn, current->hook_data);
978 *hook_list = new_list;
981 int hook_present (Hook *hook_list, void (*hook_fn)(void *))
983 Hook *p;
985 for (p = hook_list; p; p = p->next)
986 if (p->hook_fn == hook_fn)
987 return 1;
988 return 0;
991 void wipe_password (char *passwd)
993 char *p = passwd;
995 if (!p)
996 return;
997 for (;*p ; p++)
998 *p = 0;
999 g_free (passwd);
1002 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1003 /* Returns a newly allocated string */
1004 char *convert_controls (char *s)
1006 char *valcopy = g_strdup (s);
1007 char *p, *q;
1009 /* Parse the escape special character */
1010 for (p = s, q = valcopy; *p;){
1011 if (*p == '\\'){
1012 p++;
1013 if ((*p == 'e') || (*p == 'E')){
1014 p++;
1015 *q++ = ESC_CHAR;
1017 } else {
1018 if (*p == '^'){
1019 p++;
1020 if (*p == '^')
1021 *q++ = *p++;
1022 else {
1023 *p = (*p | 0x20);
1024 if (*p >= 'a' && *p <= 'z') {
1025 *q++ = *p++ - 'a' + 1;
1026 } else
1027 p++;
1029 } else
1030 *q++ = *p++;
1033 *q = 0;
1034 return valcopy;
1037 /* Reverse the string */
1038 char *reverse_string (char *string)
1040 char *str_beg = string;
1041 char *str_end = string + strlen (string);
1043 while (--str_end > str_beg){
1044 char c = *str_end;
1046 *str_end = *str_beg;
1047 *str_beg++ = c;
1049 return string;
1052 static char *resolve_symlinks (char *path)
1054 char *buf, *buf2, *p, *q, *r, c;
1055 int len;
1056 struct stat mybuf;
1058 if (*path != PATH_SEP)
1059 return NULL;
1060 r = buf = g_malloc (MC_MAXPATHLEN);
1061 buf2 = g_malloc (MC_MAXPATHLEN);
1062 *r++ = PATH_SEP;
1063 *r = 0;
1064 p = path;
1065 for (;;) {
1066 q = strchr (p + 1, PATH_SEP);
1067 if (!q) {
1068 q = strchr (p + 1, 0);
1069 if (q == p + 1)
1070 break;
1072 c = *q;
1073 *q = 0;
1074 if (mc_lstat (path, &mybuf) < 0) {
1075 g_free (buf);
1076 g_free (buf2);
1077 *q = c;
1078 return NULL;
1080 if (!S_ISLNK (mybuf.st_mode))
1081 strcpy (r, p + 1);
1082 else {
1083 len = mc_readlink (path, buf2, MC_MAXPATHLEN);
1084 if (len < 0) {
1085 g_free (buf);
1086 g_free (buf2);
1087 *q = c;
1088 return NULL;
1090 buf2 [len] = 0;
1091 if (*buf2 == PATH_SEP)
1092 strcpy (buf, buf2);
1093 else
1094 strcpy (r, buf2);
1096 canonicalize_pathname (buf);
1097 r = strchr (buf, 0);
1098 if (!*r || *(r - 1) != PATH_SEP) {
1099 *r++ = PATH_SEP;
1100 *r = 0;
1102 *q = c;
1103 p = q;
1104 if (!c)
1105 break;
1107 if (!*buf)
1108 strcpy (buf, PATH_SEP_STR);
1109 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1110 *(r - 1) = 0;
1111 g_free (buf2);
1112 return buf;
1115 /* Finds out a relative path from first to second, i.e. goes as many ..
1116 * as needed up in first and then goes down using second */
1117 char *diff_two_paths (char *first, char *second)
1119 char *p, *q, *r, *s, *buf = 0;
1120 int i, j, prevlen = -1, currlen;
1122 first = resolve_symlinks (first);
1123 if (first == NULL)
1124 return NULL;
1125 for (j = 0; j < 2; j++) {
1126 p = first;
1127 if (j) {
1128 second = resolve_symlinks (second);
1129 if (second == NULL) {
1130 g_free (first);
1131 return buf;
1134 q = second;
1135 for (;;) {
1136 r = strchr (p, PATH_SEP);
1137 s = strchr (q, PATH_SEP);
1138 if (!r || !s)
1139 break;
1140 *r = 0; *s = 0;
1141 if (strcmp (p, q)) {
1142 *r = PATH_SEP; *s = PATH_SEP;
1143 break;
1144 } else {
1145 *r = PATH_SEP; *s = PATH_SEP;
1147 p = r + 1;
1148 q = s + 1;
1150 p--;
1151 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1152 currlen = (i + 1) * 3 + strlen (q) + 1;
1153 if (j) {
1154 if (currlen < prevlen)
1155 g_free (buf);
1156 else {
1157 g_free (first);
1158 g_free (second);
1159 return buf;
1162 p = buf = g_malloc (currlen);
1163 prevlen = currlen;
1164 for (; i >= 0; i--, p += 3)
1165 strcpy (p, "../");
1166 strcpy (p, q);
1168 g_free (first);
1169 g_free (second);
1170 return buf;
1173 /* If filename is NULL, then we just append PATH_SEP to the dir */
1174 char *
1175 concat_dir_and_file (const char *dir, const char *file)
1177 int i = strlen (dir);
1179 if (dir [i-1] == PATH_SEP)
1180 return g_strconcat (dir, file, NULL);
1181 else
1182 return g_strconcat (dir, PATH_SEP_STR, file, NULL);
1185 /* Following code heavily borrows from libiberty, mkstemps.c */
1187 /* Number of attempts to create a temporary file */
1188 #ifndef TMP_MAX
1189 #define TMP_MAX 16384
1190 #endif /* !TMP_MAX */
1193 * Arguments:
1194 * pname (output) - pointer to the name of the temp file (needs g_free).
1195 * NULL if the function fails.
1196 * prefix - part of the filename before the random part.
1197 * Prepend $TMPDIR or /tmp if there are no path separators.
1198 * suffix - if not NULL, part of the filename after the random part.
1200 * Result:
1201 * handle of the open file or -1 if couldn't open any.
1203 int mc_mkstemps(char **pname, const char *prefix, const char *suffix)
1205 static const char letters[]
1206 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1207 static unsigned long value;
1208 struct timeval tv;
1209 char *tmpbase;
1210 char *tmpname;
1211 char *XXXXXX;
1212 int count;
1214 if (strchr(prefix, PATH_SEP) == NULL) {
1215 /* Add prefix first to find the position of XXXXXX */
1216 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1217 } else {
1218 tmpbase = g_strdup (prefix);
1221 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, NULL);
1222 *pname = tmpname;
1223 XXXXXX = &tmpname[strlen (tmpbase)];
1224 g_free(tmpbase);
1226 /* Get some more or less random data. */
1227 gettimeofday (&tv, NULL);
1228 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1230 for (count = 0; count < TMP_MAX; ++count) {
1231 unsigned long v = value;
1232 int fd;
1234 /* Fill in the random bits. */
1235 XXXXXX[0] = letters[v % 62];
1236 v /= 62;
1237 XXXXXX[1] = letters[v % 62];
1238 v /= 62;
1239 XXXXXX[2] = letters[v % 62];
1240 v /= 62;
1241 XXXXXX[3] = letters[v % 62];
1242 v /= 62;
1243 XXXXXX[4] = letters[v % 62];
1244 v /= 62;
1245 XXXXXX[5] = letters[v % 62];
1247 fd = open (tmpname, O_RDWR|O_CREAT|O_EXCL, 0600);
1248 if (fd >= 0) {
1249 /* Successfully created. */
1250 return fd;
1253 /* This is a random value. It is only necessary that the next
1254 TMP_MAX values generated by adding 7777 to VALUE are different
1255 with (module 2^32). */
1256 value += 7777;
1259 /* Unsuccessful. Free the filename. */
1260 g_free (tmpname);
1261 tmpname = NULL;
1263 return -1;