Original patch as attached on the bugreport
[midnight-commander.git] / src / util.c
blobdf46b2b404c937ce6c88d37cc15c83ab9a7d43ce
1 /* Various utilities
2 Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
3 2004, 2005, 2007 Free Software Foundation, Inc.
4 Written 1994, 1995, 1996 by:
5 Miguel de Icaza, Janne Kukonlehto, Dugan Porter,
6 Jakub Jelinek, Mauricio Plaza.
8 The file_date routine is mostly from GNU's fileutils package,
9 written by Richard Stallman and David MacKenzie.
11 This program is free software; you can redistribute it and/or modify
12 it under the terms of the GNU General Public License as published by
13 the Free Software Foundation; either version 2 of the License, or
14 (at your option) any later version.
16 This program is distributed in the hope that it will be useful,
17 but WITHOUT ANY WARRANTY; without even the implied warranty of
18 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 GNU General Public License for more details.
21 You should have received a copy of the GNU General Public License
22 along with this program; if not, write to the Free Software
23 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
25 #include <config.h>
27 #include <ctype.h>
28 #include <limits.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <unistd.h>
38 #include "global.h"
39 #include "profile.h"
40 #include "main.h" /* mc_home */
41 #include "cmd.h" /* guess_message_value */
42 #include "mountlist.h"
43 #include "win.h" /* xterm_flag */
44 #include "timefmt.h"
46 #ifdef HAVE_CHARSET
47 #include "charsets.h"
48 #endif
50 static const char app_text [] = "Midnight-Commander";
51 int easy_patterns = 1;
53 extern void str_replace(char *s, char from, char to)
55 for (; *s != '\0'; s++) {
56 if (*s == from)
57 *s = to;
61 static inline int
62 is_7bit_printable (unsigned char c)
64 return (c > 31 && c < 127);
67 static inline int
68 is_iso_printable (unsigned char c)
70 return ((c > 31 && c < 127) || c >= 160);
73 static inline int
74 is_8bit_printable (unsigned char c)
76 /* "Full 8 bits output" doesn't work on xterm */
77 if (xterm_flag)
78 return is_iso_printable (c);
80 return (c > 31 && c != 127 && c != 155);
83 int
84 is_printable (int c)
86 c &= 0xff;
88 #ifdef HAVE_CHARSET
89 /* "Display bits" is ignored, since the user controls the output
90 by setting the output codepage */
91 return is_8bit_printable (c);
92 #else
93 if (!eight_bit_clean)
94 return is_7bit_printable (c);
96 if (full_eight_bits) {
97 return is_8bit_printable (c);
98 } else
99 return is_iso_printable (c);
100 #endif /* !HAVE_CHARSET */
103 /* Calculates the message dimensions (lines and columns) */
104 void
105 msglen (const char *text, int *lines, int *columns)
107 int nlines = 1; /* even the empty string takes one line */
108 int ncolumns = 0;
109 int colindex = 0;
111 for (; *text != '\0'; text++) {
112 if (*text == '\n') {
113 nlines++;
114 colindex = 0;
115 } else {
116 colindex++;
117 if (colindex > ncolumns)
118 ncolumns = colindex;
122 *lines = nlines;
123 *columns = ncolumns;
127 * Copy from s to d, and trim the beginning if necessary, and prepend
128 * "..." in this case. The destination string can have at most len
129 * bytes, not counting trailing 0.
131 char *
132 trim (const char *s, char *d, int len)
134 int source_len;
136 /* Sanity check */
137 len = max (len, 0);
139 source_len = strlen (s);
140 if (source_len > len) {
141 /* Cannot fit the whole line */
142 if (len <= 3) {
143 /* We only have room for the dots */
144 memset (d, '.', len);
145 d[len] = 0;
146 return d;
147 } else {
148 /* Begin with ... and add the rest of the source string */
149 memset (d, '.', 3);
150 strcpy (d + 3, s + 3 + source_len - len);
152 } else
153 /* We can copy the whole line */
154 strcpy (d, s);
155 return d;
159 * Quote the filename for the purpose of inserting it into the command
160 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
161 * processed by the mc command line.
163 char *
164 name_quote (const char *s, int quote_percent)
166 char *ret, *d;
168 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
169 if (*s == '-') {
170 *d++ = '.';
171 *d++ = '/';
174 for (; *s; s++, d++) {
175 switch (*s) {
176 case '%':
177 if (quote_percent)
178 *d++ = '%';
179 break;
180 case '\'':
181 case '\\':
182 case '\r':
183 case '\n':
184 case '\t':
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 case '*':
201 case '(':
202 case ')':
203 *d++ = '\\';
204 break;
205 case '~':
206 case '#':
207 if (d == ret)
208 *d++ = '\\';
209 break;
211 *d = *s;
213 *d = '\0';
214 return ret;
217 char *
218 fake_name_quote (const char *s, int quote_percent)
220 (void) quote_percent;
221 return g_strdup (s);
225 * Remove the middle part of the string to fit given length.
226 * Use "~" to show where the string was truncated.
227 * Return static buffer, no need to free() it.
229 const char *
230 name_trunc (const char *txt, int trunc_len)
232 static char x[MC_MAXPATHLEN + MC_MAXPATHLEN];
233 int txt_len;
234 char *p;
236 if ((size_t) trunc_len > sizeof (x) - 1) {
237 trunc_len = sizeof (x) - 1;
239 txt_len = strlen (txt);
240 if (txt_len <= trunc_len) {
241 strcpy (x, txt);
242 } else {
243 int y = (trunc_len / 2) + (trunc_len % 2);
244 strncpy (x, txt, y);
245 strncpy (x + y, txt + txt_len - (trunc_len / 2), trunc_len / 2);
246 x[y] = '~';
248 x[trunc_len] = 0;
249 for (p = x; *p; p++)
250 if (!is_printable (*p))
251 *p = '?';
252 return x;
256 * path_trunc() is the same as name_trunc() above but
257 * it deletes possible password from path for security
258 * reasons.
260 const char *
261 path_trunc (const char *path, int trunc_len) {
262 const char *ret;
263 char *secure_path = strip_password (g_strdup (path), 1);
265 ret = name_trunc (secure_path, trunc_len);
266 g_free (secure_path);
268 return ret;
271 const char *
272 size_trunc (double size)
274 static char x [BUF_TINY];
275 long int divisor = 1;
276 const char *xtra = "";
278 if (size > 999999999L){
279 divisor = 1024;
280 xtra = "K";
281 if (size/divisor > 999999999L){
282 divisor = 1024*1024;
283 xtra = "M";
286 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
287 return x;
290 const char *
291 size_trunc_sep (double size)
293 static char x [60];
294 int count;
295 const char *p, *y;
296 char *d;
298 p = y = size_trunc (size);
299 p += strlen (p) - 1;
300 d = x + sizeof (x) - 1;
301 *d-- = 0;
302 while (p >= y && isalpha ((unsigned char) *p))
303 *d-- = *p--;
304 for (count = 0; p >= y; count++){
305 if (count == 3){
306 *d-- = ',';
307 count = 0;
309 *d-- = *p--;
311 d++;
312 if (*d == ',')
313 d++;
314 return d;
318 * Print file SIZE to BUFFER, but don't exceed LEN characters,
319 * not including trailing 0. BUFFER should be at least LEN+1 long.
320 * This function is called for every file on panels, so avoid
321 * floating point by any means.
323 * Units: size units (filesystem sizes are 1K blocks)
324 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
326 void
327 size_trunc_len (char *buffer, int len, off_t size, int units)
329 /* Avoid taking power for every file. */
330 static const off_t power10 [] =
331 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
332 1000000000};
333 static const char * const suffix [] =
334 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
335 int j = 0;
337 /* Don't print more than 9 digits - use suffix. */
338 if (len == 0 || len > 9)
339 len = 9;
341 for (j = units; suffix [j] != NULL; j++) {
342 if (size == 0) {
343 if (j == units) {
344 /* Empty files will print "0" even with minimal width. */
345 g_snprintf (buffer, len + 1, "0");
346 break;
349 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
350 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
351 (j > 1) ? suffix[j - 1] : "B");
352 break;
355 if (size < power10 [len - (j > 0)]) {
356 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
357 break;
360 /* Powers of 1024, with rounding. */
361 size = (size + 512) >> 10;
366 is_exe (mode_t mode)
368 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
369 return 1;
370 return 0;
373 #define ismode(n,m) ((n & m) == m)
375 const char *
376 string_perm (mode_t mode_bits)
378 static char mode[11];
380 strcpy (mode, "----------");
381 if (S_ISDIR (mode_bits))
382 mode[0] = 'd';
383 if (S_ISCHR (mode_bits))
384 mode[0] = 'c';
385 if (S_ISBLK (mode_bits))
386 mode[0] = 'b';
387 if (S_ISLNK (mode_bits))
388 mode[0] = 'l';
389 if (S_ISFIFO (mode_bits))
390 mode[0] = 'p';
391 if (S_ISNAM (mode_bits))
392 mode[0] = 'n';
393 if (S_ISSOCK (mode_bits))
394 mode[0] = 's';
395 if (S_ISDOOR (mode_bits))
396 mode[0] = 'D';
397 if (ismode (mode_bits, S_IXOTH))
398 mode[9] = 'x';
399 if (ismode (mode_bits, S_IWOTH))
400 mode[8] = 'w';
401 if (ismode (mode_bits, S_IROTH))
402 mode[7] = 'r';
403 if (ismode (mode_bits, S_IXGRP))
404 mode[6] = 'x';
405 if (ismode (mode_bits, S_IWGRP))
406 mode[5] = 'w';
407 if (ismode (mode_bits, S_IRGRP))
408 mode[4] = 'r';
409 if (ismode (mode_bits, S_IXUSR))
410 mode[3] = 'x';
411 if (ismode (mode_bits, S_IWUSR))
412 mode[2] = 'w';
413 if (ismode (mode_bits, S_IRUSR))
414 mode[1] = 'r';
415 #ifdef S_ISUID
416 if (ismode (mode_bits, S_ISUID))
417 mode[3] = (mode[3] == 'x') ? 's' : 'S';
418 #endif /* S_ISUID */
419 #ifdef S_ISGID
420 if (ismode (mode_bits, S_ISGID))
421 mode[6] = (mode[6] == 'x') ? 's' : 'S';
422 #endif /* S_ISGID */
423 #ifdef S_ISVTX
424 if (ismode (mode_bits, S_ISVTX))
425 mode[9] = (mode[9] == 'x') ? 't' : 'T';
426 #endif /* S_ISVTX */
427 return mode;
430 /* p: string which might contain an url with a password (this parameter is
431 modified in place).
432 has_prefix = 0: The first parameter is an url without a prefix
433 (user[:pass]@]machine[:port][remote-dir). Delete
434 the password.
435 has_prefix = 1: Search p for known url prefixes. If found delete
436 the password from the url.
437 Caveat: only the first url is found
439 char *
440 strip_password (char *p, int has_prefix)
442 static const struct {
443 const char *name;
444 size_t len;
445 } prefixes[] = { {"/#ftp:", 6},
446 {"ftp://", 6},
447 {"/#mc:", 5},
448 {"mc://", 5},
449 {"/#smb:", 6},
450 {"smb://", 6},
451 {"/#sh:", 5},
452 {"sh://", 5},
453 {"ssh://", 6}
455 char *at, *inner_colon, *dir;
456 size_t i;
457 char *result = p;
459 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
460 char *q;
462 if (has_prefix) {
463 if((q = strstr (p, prefixes[i].name)) == 0)
464 continue;
465 else
466 p = q + prefixes[i].len;
469 if ((dir = strchr (p, PATH_SEP)) != NULL)
470 *dir = '\0';
472 /* search for any possible user */
473 at = strrchr (p, '@');
475 if (dir)
476 *dir = PATH_SEP;
478 /* We have a username */
479 if (at) {
480 inner_colon = memchr (p, ':', at - p);
481 if (inner_colon)
482 memmove (inner_colon, at, strlen(at) + 1);
484 break;
486 return (result);
489 const char *
490 strip_home_and_password(const char *dir)
492 size_t len;
493 static char newdir [MC_MAXPATHLEN];
495 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
496 (dir[len] == PATH_SEP || dir[len] == '\0')){
497 newdir [0] = '~';
498 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
499 return newdir;
502 /* We do not strip homes in /#ftp tree, I do not like ~'s there
503 (see ftpfs.c why) */
504 g_strlcpy (newdir, dir, sizeof(newdir));
505 strip_password (newdir, 1);
506 return newdir;
509 static char *
510 maybe_start_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 = 1;
517 *d++ = '\\';
518 *d++ = '(';
519 return d;
522 static char *
523 maybe_end_group (char *d, int do_group, int *was_wildcard)
525 if (!do_group)
526 return d;
527 if (!*was_wildcard)
528 return d;
529 *was_wildcard = 0;
530 *d++ = '\\';
531 *d++ = ')';
532 return d;
535 /* If shell patterns are on converts a shell pattern to a regular
536 expression. Called by regexp_match and mask_rename. */
537 /* Shouldn't we support [a-fw] type wildcards as well ?? */
538 char *
539 convert_pattern (const char *pattern, int match_type, int do_group)
541 char *d;
542 char *new_pattern;
543 int was_wildcard = 0;
544 const char *s;
546 if ((match_type != match_regex) && easy_patterns){
547 new_pattern = g_malloc (MC_MAXPATHLEN);
548 d = new_pattern;
549 if (match_type == match_file)
550 *d++ = '^';
551 for (s = pattern; *s; s++, d++){
552 switch (*s){
553 case '*':
554 d = maybe_start_group (d, do_group, &was_wildcard);
555 *d++ = '.';
556 *d = '*';
557 break;
559 case '?':
560 d = maybe_start_group (d, do_group, &was_wildcard);
561 *d = '.';
562 break;
564 case '.':
565 d = maybe_end_group (d, do_group, &was_wildcard);
566 *d++ = '\\';
567 *d = '.';
568 break;
570 default:
571 d = maybe_end_group (d, do_group, &was_wildcard);
572 *d = *s;
573 break;
576 d = maybe_end_group (d, do_group, &was_wildcard);
577 if (match_type == match_file)
578 *d++ = '$';
579 *d = 0;
580 return new_pattern;
581 } else
582 return g_strdup (pattern);
586 regexp_match (const char *pattern, const char *string, int match_type)
588 static regex_t r;
589 static char *old_pattern = NULL;
590 static int old_type;
591 int rval;
592 char *my_pattern;
594 if (!old_pattern || STRCOMP (old_pattern, pattern) || old_type != match_type){
595 if (old_pattern){
596 regfree (&r);
597 g_free (old_pattern);
598 old_pattern = NULL;
600 my_pattern = convert_pattern (pattern, match_type, 0);
601 if (regcomp (&r, my_pattern, REG_EXTENDED|REG_NOSUB|MC_ARCH_FLAGS)) {
602 g_free (my_pattern);
603 return -1;
605 old_pattern = my_pattern;
606 old_type = match_type;
608 rval = !regexec (&r, string, 0, NULL, 0);
609 return rval;
612 const char *
613 extension (const char *filename)
615 const char *d = strrchr (filename, '.');
616 return (d != NULL) ? d + 1 : "";
620 get_int (const char *file, const char *key, int def)
622 return GetPrivateProfileInt (app_text, key, def, file);
626 set_int (const char *file, const char *key, int value)
628 char buffer [BUF_TINY];
630 g_snprintf (buffer, sizeof (buffer), "%d", value);
631 return WritePrivateProfileString (app_text, key, buffer, file);
634 extern char *
635 get_config_string (const char *file, const char *key, const char *defval)
637 char buffer[1024];
638 (void)GetPrivateProfileString (app_text, key, defval, buffer, sizeof(buffer), file);
639 return g_strdup (buffer);
642 extern void
643 set_config_string (const char *file, const char *key, const char *val)
645 (void)WritePrivateProfileString (app_text, key, val, file);
649 exist_file (const char *name)
651 return access (name, R_OK) == 0;
654 char *
655 load_file (const char *filename)
657 FILE *data_file;
658 struct stat s;
659 char *data;
660 long read_size;
662 if ((data_file = fopen (filename, "r")) == NULL){
663 return 0;
665 if (fstat (fileno (data_file), &s) != 0){
666 fclose (data_file);
667 return 0;
669 data = g_malloc (s.st_size+1);
670 read_size = fread (data, 1, s.st_size, data_file);
671 data [read_size] = 0;
672 fclose (data_file);
674 if (read_size > 0)
675 return data;
676 else {
677 g_free (data);
678 return 0;
682 char *
683 load_mc_home_file (const char *filename, char **allocated_filename)
685 char *hintfile_base, *hintfile;
686 char *lang;
687 char *data;
689 hintfile_base = concat_dir_and_file (mc_home, filename);
690 lang = guess_message_value ();
692 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
693 data = load_file (hintfile);
695 if (!data) {
696 g_free (hintfile);
697 /* Fall back to the two-letter language code */
698 if (lang[0] && lang[1])
699 lang[2] = 0;
700 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
701 data = load_file (hintfile);
703 if (!data) {
704 g_free (hintfile);
705 hintfile = hintfile_base;
706 data = load_file (hintfile_base);
710 g_free (lang);
712 if (hintfile != hintfile_base)
713 g_free (hintfile_base);
715 if (allocated_filename)
716 *allocated_filename = hintfile;
717 else
718 g_free (hintfile);
720 return data;
723 /* Check strftime() results. Some systems (i.e. Solaris) have different
724 short-month-name sizes for different locales */
725 size_t
726 i18n_checktimelength (void)
728 time_t testtime = time (NULL);
729 struct tm* lt = localtime(&testtime);
730 size_t length;
732 if (lt == NULL) {
733 // huh, localtime() doesnt seem to work ... falling back to "(invalid)"
734 length = strlen(INVALID_TIME_TEXT);
735 } else {
736 char buf [MAX_I18NTIMELENGTH + 1];
737 size_t a, b;
738 a = strftime (buf, sizeof(buf)-1, _("%b %e %H:%M"), lt);
739 b = strftime (buf, sizeof(buf)-1, _("%b %e %Y"), lt);
740 length = max (a, b);
743 /* Don't handle big differences. Use standard value (email bug, please) */
744 if ( length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH )
745 length = STD_I18NTIMELENGTH;
747 return length;
750 const char *
751 file_date (time_t when)
753 static char timebuf [MAX_I18NTIMELENGTH + 1];
754 time_t current_time = time ((time_t) 0);
755 static size_t i18n_timelength = 0;
756 static const char *fmtyear, *fmttime;
757 const char *fmt;
759 if (i18n_timelength == 0){
760 i18n_timelength = i18n_checktimelength() + 1;
762 /* strftime() format string for old dates */
763 fmtyear = _("%b %e %Y");
764 /* strftime() format string for recent dates */
765 fmttime = _("%b %e %H:%M");
768 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
769 || current_time < when - 60L * 60L) /* In the future. */
770 /* The file is fairly old or in the future.
771 POSIX says the cutoff is 6 months old;
772 approximate this by 6*30 days.
773 Allow a 1 hour slop factor for what is considered "the future",
774 to allow for NFS server/client clock disagreement.
775 Show the year instead of the time of day. */
777 fmt = fmtyear;
778 else
779 fmt = fmttime;
781 FMT_LOCALTIME(timebuf, i18n_timelength, fmt, when);
783 return timebuf;
786 const char *
787 extract_line (const char *s, const char *top)
789 static char tmp_line [BUF_MEDIUM];
790 char *t = tmp_line;
792 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
793 *t++ = *s++;
794 *t = 0;
795 return tmp_line;
798 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
799 const char *
800 _icase_search (const char *text, const char *data, int *lng)
802 const char *d = text;
803 const char *e = data;
804 int dlng = 0;
806 if (lng)
807 *lng = 0;
808 for (;*e; e++) {
809 while (*(e+1) == '\b' && *(e+2)) {
810 e += 2;
811 dlng += 2;
813 if (toupper((unsigned char) *d) == toupper((unsigned char) *e))
814 d++;
815 else {
816 e -= d - text;
817 d = text;
818 dlng = 0;
820 if (!*d) {
821 if (lng)
822 *lng = strlen (text) + dlng;
823 return e+1;
826 return 0;
829 /* The basename routine */
830 const char *
831 x_basename (const char *s)
833 const char *where;
834 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
838 const char *
839 unix_error_string (int error_num)
841 static char buffer [BUF_LARGE];
842 #if GLIB_MAJOR_VERSION >= 2
843 gchar *strerror_currentlocale;
845 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
846 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
847 strerror_currentlocale, error_num);
848 g_free(strerror_currentlocale);
849 #else
850 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
851 g_strerror (error_num), error_num);
852 #endif
853 return buffer;
856 const char *
857 skip_separators (const char *s)
859 for (;*s; s++)
860 if (*s != ' ' && *s != '\t' && *s != ',')
861 break;
862 return s;
865 const char *
866 skip_numbers (const char *s)
868 for (;*s; s++)
869 if (!isdigit ((unsigned char) *s))
870 break;
871 return s;
874 /* Remove all control sequences from the argument string. We define
875 * "control sequence", in a sort of pidgin BNF, as follows:
877 * control-seq = Esc non-'['
878 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
880 * This scheme works for all the terminals described in my termcap /
881 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
882 * terminals. If I hear from a single person who uses such a terminal
883 * with MC, I'll be glad to add support for it. (Dugan)
884 * Non-printable characters are also removed.
887 char *
888 strip_ctrl_codes (char *s)
890 char *w; /* Current position where the stripped data is written */
891 char *r; /* Current position where the original data is read */
893 if (!s)
894 return 0;
896 for (w = s, r = s; *r; ) {
897 if (*r == ESC_CHAR) {
898 /* Skip the control sequence's arguments */ ;
899 if (*(++r) == '[') {
900 /* strchr() matches trailing binary 0 */
901 while (*(++r) && strchr ("0123456789;?", *r));
905 * Now we are at the last character of the sequence.
906 * Skip it unless it's binary 0.
908 if (*r)
909 r++;
910 continue;
913 if (is_printable(*r))
914 *w++ = *r;
915 ++r;
917 *w = 0;
918 return s;
922 #ifndef USE_VFS
923 char *
924 get_current_wd (char *buffer, int size)
926 char *p;
927 int len;
929 p = g_get_current_dir ();
930 len = strlen(p) + 1;
932 if (len > size) {
933 g_free (p);
934 return NULL;
937 memcpy (buffer, p, len);
938 g_free (p);
940 return buffer;
942 #endif /* !USE_VFS */
944 enum compression_type
945 get_compression_type (int fd)
947 unsigned char magic[4];
949 /* Read the magic signature */
950 if (mc_read (fd, (char *) magic, 4) != 4)
951 return COMPRESSION_NONE;
953 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
954 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
955 return COMPRESSION_GZIP;
958 /* PKZIP_MAGIC */
959 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
960 && magic[3] == 004) {
961 /* Read compression type */
962 mc_lseek (fd, 8, SEEK_SET);
963 if (mc_read (fd, (char *) magic, 2) != 2)
964 return COMPRESSION_NONE;
966 /* Gzip can handle only deflated (8) or stored (0) files */
967 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
968 return COMPRESSION_NONE;
970 /* Compatible with gzip */
971 return COMPRESSION_GZIP;
974 /* PACK_MAGIC and LZH_MAGIC and compress magic */
975 if (magic[0] == 037
976 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
977 /* Compatible with gzip */
978 return COMPRESSION_GZIP;
981 /* BZIP and BZIP2 files */
982 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
983 (magic[3] >= '1') && (magic[3] <= '9')) {
984 switch (magic[2]) {
985 case '0':
986 return COMPRESSION_BZIP;
987 case 'h':
988 return COMPRESSION_BZIP2;
991 return 0;
994 const char *
995 decompress_extension (int type)
997 switch (type){
998 case COMPRESSION_GZIP: return "#ugz";
999 case COMPRESSION_BZIP: return "#ubz";
1000 case COMPRESSION_BZIP2: return "#ubz2";
1002 /* Should never reach this place */
1003 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
1004 return 0;
1007 /* Hooks */
1008 void
1009 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
1011 Hook *new_hook = g_new (Hook, 1);
1013 new_hook->hook_fn = hook_fn;
1014 new_hook->next = *hook_list;
1015 new_hook->hook_data = data;
1017 *hook_list = new_hook;
1020 void
1021 execute_hooks (Hook *hook_list)
1023 Hook *new_hook = 0;
1024 Hook *p;
1026 /* We copy the hook list first so tahat we let the hook
1027 * function call delete_hook
1030 while (hook_list){
1031 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
1032 hook_list = hook_list->next;
1034 p = new_hook;
1036 while (new_hook){
1037 (*new_hook->hook_fn)(new_hook->hook_data);
1038 new_hook = new_hook->next;
1041 for (hook_list = p; hook_list;){
1042 p = hook_list;
1043 hook_list = hook_list->next;
1044 g_free (p);
1048 void
1049 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1051 Hook *current, *new_list, *next;
1053 new_list = 0;
1055 for (current = *hook_list; current; current = next){
1056 next = current->next;
1057 if (current->hook_fn == hook_fn)
1058 g_free (current);
1059 else
1060 add_hook (&new_list, current->hook_fn, current->hook_data);
1062 *hook_list = new_list;
1066 hook_present (Hook *hook_list, void (*hook_fn)(void *))
1068 Hook *p;
1070 for (p = hook_list; p; p = p->next)
1071 if (p->hook_fn == hook_fn)
1072 return 1;
1073 return 0;
1076 void
1077 wipe_password (char *passwd)
1079 char *p = passwd;
1081 if (!p)
1082 return;
1083 for (;*p ; p++)
1084 *p = 0;
1085 g_free (passwd);
1088 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1089 /* Returns a newly allocated string */
1090 char *
1091 convert_controls (const char *p)
1093 char *valcopy = g_strdup (p);
1094 char *q;
1096 /* Parse the escape special character */
1097 for (q = valcopy; *p;){
1098 if (*p == '\\'){
1099 p++;
1100 if ((*p == 'e') || (*p == 'E')){
1101 p++;
1102 *q++ = ESC_CHAR;
1104 } else {
1105 if (*p == '^'){
1106 p++;
1107 if (*p == '^')
1108 *q++ = *p++;
1109 else {
1110 char c = (*p | 0x20);
1111 if (c >= 'a' && c <= 'z') {
1112 *q++ = c - 'a' + 1;
1113 p++;
1114 } else if (*p)
1115 p++;
1117 } else
1118 *q++ = *p++;
1121 *q = 0;
1122 return valcopy;
1125 static char *
1126 resolve_symlinks (const char *path)
1128 char *buf, *buf2, *q, *r, c;
1129 int len;
1130 struct stat mybuf;
1131 const char *p;
1133 if (*path != PATH_SEP)
1134 return NULL;
1135 r = buf = g_malloc (MC_MAXPATHLEN);
1136 buf2 = g_malloc (MC_MAXPATHLEN);
1137 *r++ = PATH_SEP;
1138 *r = 0;
1139 p = path;
1140 for (;;) {
1141 q = strchr (p + 1, PATH_SEP);
1142 if (!q) {
1143 q = strchr (p + 1, 0);
1144 if (q == p + 1)
1145 break;
1147 c = *q;
1148 *q = 0;
1149 if (mc_lstat (path, &mybuf) < 0) {
1150 g_free (buf);
1151 g_free (buf2);
1152 *q = c;
1153 return NULL;
1155 if (!S_ISLNK (mybuf.st_mode))
1156 strcpy (r, p + 1);
1157 else {
1158 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1159 if (len < 0) {
1160 g_free (buf);
1161 g_free (buf2);
1162 *q = c;
1163 return NULL;
1165 buf2 [len] = 0;
1166 if (*buf2 == PATH_SEP)
1167 strcpy (buf, buf2);
1168 else
1169 strcpy (r, buf2);
1171 canonicalize_pathname (buf);
1172 r = strchr (buf, 0);
1173 if (!*r || *(r - 1) != PATH_SEP) {
1174 *r++ = PATH_SEP;
1175 *r = 0;
1177 *q = c;
1178 p = q;
1179 if (!c)
1180 break;
1182 if (!*buf)
1183 strcpy (buf, PATH_SEP_STR);
1184 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1185 *(r - 1) = 0;
1186 g_free (buf2);
1187 return buf;
1190 /* Finds out a relative path from first to second, i.e. goes as many ..
1191 * as needed up in first and then goes down using second */
1192 char *
1193 diff_two_paths (const char *first, const char *second)
1195 char *p, *q, *r, *s, *buf = NULL;
1196 int i, j, prevlen = -1, currlen;
1197 char *my_first = NULL, *my_second = NULL;
1199 my_first = resolve_symlinks (first);
1200 if (my_first == NULL)
1201 return NULL;
1202 my_second = resolve_symlinks (second);
1203 if (my_second == NULL) {
1204 g_free (my_first);
1205 return NULL;
1207 for (j = 0; j < 2; j++) {
1208 p = my_first;
1209 q = my_second;
1210 for (;;) {
1211 r = strchr (p, PATH_SEP);
1212 s = strchr (q, PATH_SEP);
1213 if (!r || !s)
1214 break;
1215 *r = 0; *s = 0;
1216 if (strcmp (p, q)) {
1217 *r = PATH_SEP; *s = PATH_SEP;
1218 break;
1219 } else {
1220 *r = PATH_SEP; *s = PATH_SEP;
1222 p = r + 1;
1223 q = s + 1;
1225 p--;
1226 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1227 currlen = (i + 1) * 3 + strlen (q) + 1;
1228 if (j) {
1229 if (currlen < prevlen)
1230 g_free (buf);
1231 else {
1232 g_free (my_first);
1233 g_free (my_second);
1234 return buf;
1237 p = buf = g_malloc (currlen);
1238 prevlen = currlen;
1239 for (; i >= 0; i--, p += 3)
1240 strcpy (p, "../");
1241 strcpy (p, q);
1243 g_free (my_first);
1244 g_free (my_second);
1245 return buf;
1248 /* If filename is NULL, then we just append PATH_SEP to the dir */
1249 char *
1250 concat_dir_and_file (const char *dir, const char *file)
1252 int i = strlen (dir);
1254 if (dir [i-1] == PATH_SEP)
1255 return g_strconcat (dir, file, (char *) NULL);
1256 else
1257 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1260 /* Append text to GList, remove all entries with the same text */
1261 GList *
1262 list_append_unique (GList *list, char *text)
1264 GList *link, *newlink;
1267 * Go to the last position and traverse the list backwards
1268 * starting from the second last entry to make sure that we
1269 * are not removing the current link.
1271 list = g_list_append (list, text);
1272 list = g_list_last (list);
1273 link = g_list_previous (list);
1275 while (link) {
1276 newlink = g_list_previous (link);
1277 if (!strcmp ((char *) link->data, text)) {
1278 g_free (link->data);
1279 g_list_remove_link (list, link);
1280 g_list_free_1 (link);
1282 link = newlink;
1285 return list;
1288 /* Following code heavily borrows from libiberty, mkstemps.c */
1290 /* Number of attempts to create a temporary file */
1291 #ifndef TMP_MAX
1292 #define TMP_MAX 16384
1293 #endif /* !TMP_MAX */
1296 * Arguments:
1297 * pname (output) - pointer to the name of the temp file (needs g_free).
1298 * NULL if the function fails.
1299 * prefix - part of the filename before the random part.
1300 * Prepend $TMPDIR or /tmp if there are no path separators.
1301 * suffix - if not NULL, part of the filename after the random part.
1303 * Result:
1304 * handle of the open file or -1 if couldn't open any.
1307 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1309 static const char letters[]
1310 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1311 static unsigned long value;
1312 struct timeval tv;
1313 char *tmpbase;
1314 char *tmpname;
1315 char *XXXXXX;
1316 int count;
1318 if (strchr (prefix, PATH_SEP) == NULL) {
1319 /* Add prefix first to find the position of XXXXXX */
1320 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1321 } else {
1322 tmpbase = g_strdup (prefix);
1325 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1326 *pname = tmpname;
1327 XXXXXX = &tmpname[strlen (tmpbase)];
1328 g_free (tmpbase);
1330 /* Get some more or less random data. */
1331 gettimeofday (&tv, NULL);
1332 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1334 for (count = 0; count < TMP_MAX; ++count) {
1335 unsigned long v = value;
1336 int fd;
1338 /* Fill in the random bits. */
1339 XXXXXX[0] = letters[v % 62];
1340 v /= 62;
1341 XXXXXX[1] = letters[v % 62];
1342 v /= 62;
1343 XXXXXX[2] = letters[v % 62];
1344 v /= 62;
1345 XXXXXX[3] = letters[v % 62];
1346 v /= 62;
1347 XXXXXX[4] = letters[v % 62];
1348 v /= 62;
1349 XXXXXX[5] = letters[v % 62];
1351 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1352 S_IRUSR | S_IWUSR);
1353 if (fd >= 0) {
1354 /* Successfully created. */
1355 return fd;
1358 /* This is a random value. It is only necessary that the next
1359 TMP_MAX values generated by adding 7777 to VALUE are different
1360 with (module 2^32). */
1361 value += 7777;
1364 /* Unsuccessful. Free the filename. */
1365 g_free (tmpname);
1366 *pname = NULL;
1368 return -1;
1372 * Read and restore position for the given filename.
1373 * If there is no stored data, return line 1 and col 0.
1375 void
1376 load_file_position (const char *filename, long *line, long *column)
1378 char *fn;
1379 FILE *f;
1380 char buf[MC_MAXPATHLEN + 20];
1381 int len;
1383 /* defaults */
1384 *line = 1;
1385 *column = 0;
1387 /* open file with positions */
1388 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1389 f = fopen (fn, "r");
1390 g_free (fn);
1391 if (!f)
1392 return;
1394 len = strlen (filename);
1396 while (fgets (buf, sizeof (buf), f)) {
1397 const char *p;
1399 /* check if the filename matches the beginning of string */
1400 if (strncmp (buf, filename, len) != 0)
1401 continue;
1403 /* followed by single space */
1404 if (buf[len] != ' ')
1405 continue;
1407 /* and string without spaces */
1408 p = &buf[len + 1];
1409 if (strchr (p, ' '))
1410 continue;
1412 *line = strtol(p, const_cast(char **, &p), 10);
1413 if (*p == ';') {
1414 *column = strtol(p+1, const_cast(char **, &p), 10);
1415 if (*p != '\n')
1416 *column = 0;
1417 } else
1418 *line = 1;
1420 fclose (f);
1423 /* Save position for the given file */
1424 void
1425 save_file_position (const char *filename, long line, long column)
1427 char *tmp, *fn;
1428 FILE *f, *t;
1429 char buf[MC_MAXPATHLEN + 20];
1430 int i = 1;
1431 int len;
1433 len = strlen (filename);
1435 tmp = concat_dir_and_file (home_dir, MC_FILEPOS_TMP);
1436 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1438 /* open temporary file */
1439 t = fopen (tmp, "w");
1440 if (!t) {
1441 g_free (tmp);
1442 g_free (fn);
1443 return;
1446 /* put the new record */
1447 if (line != 1 || column != 0) {
1448 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1451 /* copy records from the old file */
1452 f = fopen (fn, "r");
1453 if (f) {
1454 while (fgets (buf, sizeof (buf), f)) {
1455 /* Skip entries for the current filename */
1456 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1457 && !strchr (&buf[len + 1], ' '))
1458 continue;
1460 fprintf (t, "%s", buf);
1461 if (++i > MC_FILEPOS_ENTRIES)
1462 break;
1464 fclose (f);
1467 fclose (t);
1468 rename (tmp, fn);
1469 g_free (tmp);
1470 g_free (fn);
1473 extern const char *
1474 cstrcasestr (const char *haystack, const char *needle)
1476 const char *hptr;
1477 size_t i, needle_len;
1479 needle_len = strlen (needle);
1480 for (hptr = haystack; *hptr != '\0'; hptr++) {
1481 for (i = 0; i < needle_len; i++) {
1482 if (toupper ((unsigned char) hptr[i]) !=
1483 toupper ((unsigned char) needle[i]))
1484 goto next_try;
1486 return hptr;
1487 next_try:
1488 (void) 0;
1490 return NULL;
1493 const char *
1494 cstrstr (const char *haystack, const char *needle)
1496 return strstr(haystack, needle);
1499 extern char *
1500 str_unconst (const char *s)
1502 return (char *) s;
1505 #define ASCII_A (0x40 + 1)
1506 #define ASCII_Z (0x40 + 26)
1507 #define ASCII_a (0x60 + 1)
1508 #define ASCII_z (0x60 + 26)
1510 extern int
1511 ascii_alpha_to_cntrl (int ch)
1513 if ((ch >= ASCII_A && ch <= ASCII_Z)
1514 || (ch >= ASCII_a && ch <= ASCII_z)) {
1515 ch &= 0x1f;
1517 return ch;
1520 const char *
1521 Q_ (const char *s)
1523 const char *result, *sep;
1525 result = _(s);
1526 sep = strchr(result, '|');
1527 return (sep != NULL) ? sep + 1 : result;
1530 /* Unescape paths or other strings for e.g the internal cd */
1531 char *
1532 unescape_string ( const char * in ) {
1533 char * local = NULL;
1534 int i = 0;
1535 int j = 20;
1536 int k = 0;
1538 local = g_malloc(j);
1540 for (i=0;i<=strlen(in);i++) {
1541 if (i-k+1 >= j ) {
1542 j = j + 20;
1543 local = g_realloc(local,j);
1545 if ( (strchr(" \t*|;<>~#()?[]{}&",in[i])) && ( strchr("\\",in[i-1])) ) {
1546 k++;
1547 local[i-k] = in[i];
1548 } else {
1549 local[i-k] = in[i];
1552 local[i-k] = '\0';
1554 return local;
1557 /* To be compatible with the general posix command lines we have to escape *
1558 * strings for the command line */
1559 char *
1560 escape_string ( const char * in ) {
1561 char * local = NULL;
1562 int i = 0;
1563 int j = 20;
1564 int k = 0;
1566 local = g_malloc(j);
1568 for (i=0;i<strlen(in);i++) {
1569 if (i+k+1 >= j ) { //If 20 chars is too low for the path
1570 j = j + 20;
1571 local = g_realloc(local,j);
1573 if ( (strchr(" \t*|;<>~#()?[]{}&",in[i])) && (! strchr("\\",in[i-1])) ) {
1574 local[i+k] = 92; // Ascii for "\"
1575 k = k+1;
1576 local[i+k] = in[i];
1577 } else {
1578 local[i+k] = in[i];
1581 local[i+k] = '\0';
1583 return local;