replaced buggy concat_dir_and_file() by mhl_str_dir_plus_file()
[free-mc.git] / src / util.c
blob0b4a7efdf2d00c048432e30f86fe2e990ffc6bee
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 <mhl/string.h>
40 #include "global.h"
41 #include "profile.h"
42 #include "main.h" /* mc_home */
43 #include "cmd.h" /* guess_message_value */
44 #include "mountlist.h"
45 #include "win.h" /* xterm_flag */
46 #include "timefmt.h"
48 #ifdef HAVE_CHARSET
49 #include "charsets.h"
50 #endif
52 static const char app_text [] = "Midnight-Commander";
53 int easy_patterns = 1;
55 extern void str_replace(char *s, char from, char to)
57 for (; *s != '\0'; s++) {
58 if (*s == from)
59 *s = to;
63 static inline int
64 is_7bit_printable (unsigned char c)
66 return (c > 31 && c < 127);
69 static inline int
70 is_iso_printable (unsigned char c)
72 return ((c > 31 && c < 127) || c >= 160);
75 static inline int
76 is_8bit_printable (unsigned char c)
78 /* "Full 8 bits output" doesn't work on xterm */
79 if (xterm_flag)
80 return is_iso_printable (c);
82 return (c > 31 && c != 127 && c != 155);
85 int
86 is_printable (int c)
88 c &= 0xff;
90 #ifdef HAVE_CHARSET
91 /* "Display bits" is ignored, since the user controls the output
92 by setting the output codepage */
93 return is_8bit_printable (c);
94 #else
95 if (!eight_bit_clean)
96 return is_7bit_printable (c);
98 if (full_eight_bits) {
99 return is_8bit_printable (c);
100 } else
101 return is_iso_printable (c);
102 #endif /* !HAVE_CHARSET */
105 /* Calculates the message dimensions (lines and columns) */
106 void
107 msglen (const char *text, int *lines, int *columns)
109 int nlines = 1; /* even the empty string takes one line */
110 int ncolumns = 0;
111 int colindex = 0;
113 for (; *text != '\0'; text++) {
114 if (*text == '\n') {
115 nlines++;
116 colindex = 0;
117 } else {
118 colindex++;
119 if (colindex > ncolumns)
120 ncolumns = colindex;
124 *lines = nlines;
125 *columns = ncolumns;
129 * Copy from s to d, and trim the beginning if necessary, and prepend
130 * "..." in this case. The destination string can have at most len
131 * bytes, not counting trailing 0.
133 char *
134 trim (const char *s, char *d, int len)
136 int source_len;
138 /* Sanity check */
139 len = max (len, 0);
141 source_len = strlen (s);
142 if (source_len > len) {
143 /* Cannot fit the whole line */
144 if (len <= 3) {
145 /* We only have room for the dots */
146 memset (d, '.', len);
147 d[len] = 0;
148 return d;
149 } else {
150 /* Begin with ... and add the rest of the source string */
151 memset (d, '.', 3);
152 strcpy (d + 3, s + 3 + source_len - len);
154 } else
155 /* We can copy the whole line */
156 strcpy (d, s);
157 return d;
161 * Quote the filename for the purpose of inserting it into the command
162 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
163 * processed by the mc command line.
165 char *
166 name_quote (const char *s, int quote_percent)
168 char *ret, *d;
170 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
171 if (*s == '-') {
172 *d++ = '.';
173 *d++ = '/';
176 for (; *s; s++, d++) {
177 switch (*s) {
178 case '%':
179 if (quote_percent)
180 *d++ = '%';
181 break;
182 case '\'':
183 case '\\':
184 case '\r':
185 case '\n':
186 case '\t':
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 case '(':
204 case ')':
205 *d++ = '\\';
206 break;
207 case '~':
208 case '#':
209 if (d == ret)
210 *d++ = '\\';
211 break;
213 *d = *s;
215 *d = '\0';
216 return ret;
219 char *
220 fake_name_quote (const char *s, int quote_percent)
222 (void) quote_percent;
223 return g_strdup (s);
227 * Remove the middle part of the string to fit given length.
228 * Use "~" to show where the string was truncated.
229 * Return static buffer, no need to free() it.
231 const char *
232 name_trunc (const char *txt, int trunc_len)
234 static char x[MC_MAXPATHLEN + MC_MAXPATHLEN];
235 int txt_len;
236 char *p;
238 if ((size_t) trunc_len > sizeof (x) - 1) {
239 trunc_len = sizeof (x) - 1;
241 txt_len = strlen (txt);
242 if (txt_len <= trunc_len) {
243 strcpy (x, txt);
244 } else {
245 int y = (trunc_len / 2) + (trunc_len % 2);
246 strncpy (x, txt, y);
247 strncpy (x + y, txt + txt_len - (trunc_len / 2), trunc_len / 2);
248 x[y] = '~';
250 x[trunc_len] = 0;
251 for (p = x; *p; p++)
252 if (!is_printable (*p))
253 *p = '?';
254 return x;
258 * path_trunc() is the same as name_trunc() above but
259 * it deletes possible password from path for security
260 * reasons.
262 const char *
263 path_trunc (const char *path, int trunc_len) {
264 const char *ret;
265 char *secure_path = strip_password (g_strdup (path), 1);
267 ret = name_trunc (secure_path, trunc_len);
268 g_free (secure_path);
270 return ret;
273 const char *
274 size_trunc (double size)
276 static char x [BUF_TINY];
277 long int divisor = 1;
278 const char *xtra = "";
280 if (size > 999999999L){
281 divisor = 1024;
282 xtra = "K";
283 if (size/divisor > 999999999L){
284 divisor = 1024*1024;
285 xtra = "M";
288 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
289 return x;
292 const char *
293 size_trunc_sep (double size)
295 static char x [60];
296 int count;
297 const char *p, *y;
298 char *d;
300 p = y = size_trunc (size);
301 p += strlen (p) - 1;
302 d = x + sizeof (x) - 1;
303 *d-- = 0;
304 while (p >= y && isalpha ((unsigned char) *p))
305 *d-- = *p--;
306 for (count = 0; p >= y; count++){
307 if (count == 3){
308 *d-- = ',';
309 count = 0;
311 *d-- = *p--;
313 d++;
314 if (*d == ',')
315 d++;
316 return d;
320 * Print file SIZE to BUFFER, but don't exceed LEN characters,
321 * not including trailing 0. BUFFER should be at least LEN+1 long.
322 * This function is called for every file on panels, so avoid
323 * floating point by any means.
325 * Units: size units (filesystem sizes are 1K blocks)
326 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
328 void
329 size_trunc_len (char *buffer, int len, off_t size, int units)
331 /* Avoid taking power for every file. */
332 static const off_t power10 [] =
333 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
334 1000000000};
335 static const char * const suffix [] =
336 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
337 int j = 0;
339 /* Don't print more than 9 digits - use suffix. */
340 if (len == 0 || len > 9)
341 len = 9;
343 for (j = units; suffix [j] != NULL; j++) {
344 if (size == 0) {
345 if (j == units) {
346 /* Empty files will print "0" even with minimal width. */
347 g_snprintf (buffer, len + 1, "0");
348 break;
351 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
352 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
353 (j > 1) ? suffix[j - 1] : "B");
354 break;
357 if (size < power10 [len - (j > 0)]) {
358 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
359 break;
362 /* Powers of 1024, with rounding. */
363 size = (size + 512) >> 10;
368 is_exe (mode_t mode)
370 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
371 return 1;
372 return 0;
375 #define ismode(n,m) ((n & m) == m)
377 const char *
378 string_perm (mode_t mode_bits)
380 static char mode[11];
382 strcpy (mode, "----------");
383 if (S_ISDIR (mode_bits))
384 mode[0] = 'd';
385 if (S_ISCHR (mode_bits))
386 mode[0] = 'c';
387 if (S_ISBLK (mode_bits))
388 mode[0] = 'b';
389 if (S_ISLNK (mode_bits))
390 mode[0] = 'l';
391 if (S_ISFIFO (mode_bits))
392 mode[0] = 'p';
393 if (S_ISNAM (mode_bits))
394 mode[0] = 'n';
395 if (S_ISSOCK (mode_bits))
396 mode[0] = 's';
397 if (S_ISDOOR (mode_bits))
398 mode[0] = 'D';
399 if (ismode (mode_bits, S_IXOTH))
400 mode[9] = 'x';
401 if (ismode (mode_bits, S_IWOTH))
402 mode[8] = 'w';
403 if (ismode (mode_bits, S_IROTH))
404 mode[7] = 'r';
405 if (ismode (mode_bits, S_IXGRP))
406 mode[6] = 'x';
407 if (ismode (mode_bits, S_IWGRP))
408 mode[5] = 'w';
409 if (ismode (mode_bits, S_IRGRP))
410 mode[4] = 'r';
411 if (ismode (mode_bits, S_IXUSR))
412 mode[3] = 'x';
413 if (ismode (mode_bits, S_IWUSR))
414 mode[2] = 'w';
415 if (ismode (mode_bits, S_IRUSR))
416 mode[1] = 'r';
417 #ifdef S_ISUID
418 if (ismode (mode_bits, S_ISUID))
419 mode[3] = (mode[3] == 'x') ? 's' : 'S';
420 #endif /* S_ISUID */
421 #ifdef S_ISGID
422 if (ismode (mode_bits, S_ISGID))
423 mode[6] = (mode[6] == 'x') ? 's' : 'S';
424 #endif /* S_ISGID */
425 #ifdef S_ISVTX
426 if (ismode (mode_bits, S_ISVTX))
427 mode[9] = (mode[9] == 'x') ? 't' : 'T';
428 #endif /* S_ISVTX */
429 return mode;
432 /* p: string which might contain an url with a password (this parameter is
433 modified in place).
434 has_prefix = 0: The first parameter is an url without a prefix
435 (user[:pass]@]machine[:port][remote-dir). Delete
436 the password.
437 has_prefix = 1: Search p for known url prefixes. If found delete
438 the password from the url.
439 Caveat: only the first url is found
441 char *
442 strip_password (char *p, int has_prefix)
444 static const struct {
445 const char *name;
446 size_t len;
447 } prefixes[] = { {"/#ftp:", 6},
448 {"ftp://", 6},
449 {"/#mc:", 5},
450 {"mc://", 5},
451 {"/#smb:", 6},
452 {"smb://", 6},
453 {"/#sh:", 5},
454 {"sh://", 5},
455 {"ssh://", 6}
457 char *at, *inner_colon, *dir;
458 size_t i;
459 char *result = p;
461 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
462 char *q;
464 if (has_prefix) {
465 if((q = strstr (p, prefixes[i].name)) == 0)
466 continue;
467 else
468 p = q + prefixes[i].len;
471 if ((dir = strchr (p, PATH_SEP)) != NULL)
472 *dir = '\0';
474 /* search for any possible user */
475 at = strrchr (p, '@');
477 if (dir)
478 *dir = PATH_SEP;
480 /* We have a username */
481 if (at) {
482 inner_colon = memchr (p, ':', at - p);
483 if (inner_colon)
484 memmove (inner_colon, at, strlen(at) + 1);
486 break;
488 return (result);
491 const char *
492 strip_home_and_password(const char *dir)
494 size_t len;
495 static char newdir [MC_MAXPATHLEN];
497 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
498 (dir[len] == PATH_SEP || dir[len] == '\0')){
499 newdir [0] = '~';
500 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
501 return newdir;
504 /* We do not strip homes in /#ftp tree, I do not like ~'s there
505 (see ftpfs.c why) */
506 g_strlcpy (newdir, dir, sizeof(newdir));
507 strip_password (newdir, 1);
508 return newdir;
511 static char *
512 maybe_start_group (char *d, int do_group, int *was_wildcard)
514 if (!do_group)
515 return d;
516 if (*was_wildcard)
517 return d;
518 *was_wildcard = 1;
519 *d++ = '\\';
520 *d++ = '(';
521 return d;
524 static char *
525 maybe_end_group (char *d, int do_group, int *was_wildcard)
527 if (!do_group)
528 return d;
529 if (!*was_wildcard)
530 return d;
531 *was_wildcard = 0;
532 *d++ = '\\';
533 *d++ = ')';
534 return d;
537 /* If shell patterns are on converts a shell pattern to a regular
538 expression. Called by regexp_match and mask_rename. */
539 /* Shouldn't we support [a-fw] type wildcards as well ?? */
540 char *
541 convert_pattern (const char *pattern, int match_type, int do_group)
543 char *d;
544 char *new_pattern;
545 int was_wildcard = 0;
546 const char *s;
548 if ((match_type != match_regex) && easy_patterns){
549 new_pattern = g_malloc (MC_MAXPATHLEN);
550 d = new_pattern;
551 if (match_type == match_file)
552 *d++ = '^';
553 for (s = pattern; *s; s++, d++){
554 switch (*s){
555 case '*':
556 d = maybe_start_group (d, do_group, &was_wildcard);
557 *d++ = '.';
558 *d = '*';
559 break;
561 case '?':
562 d = maybe_start_group (d, do_group, &was_wildcard);
563 *d = '.';
564 break;
566 case '.':
567 d = maybe_end_group (d, do_group, &was_wildcard);
568 *d++ = '\\';
569 *d = '.';
570 break;
572 default:
573 d = maybe_end_group (d, do_group, &was_wildcard);
574 *d = *s;
575 break;
578 d = maybe_end_group (d, do_group, &was_wildcard);
579 if (match_type == match_file)
580 *d++ = '$';
581 *d = 0;
582 return new_pattern;
583 } else
584 return g_strdup (pattern);
588 regexp_match (const char *pattern, const char *string, int match_type)
590 static regex_t r;
591 static char *old_pattern = NULL;
592 static int old_type;
593 int rval;
594 char *my_pattern;
596 if (!old_pattern || STRCOMP (old_pattern, pattern) || old_type != match_type){
597 if (old_pattern){
598 regfree (&r);
599 g_free (old_pattern);
600 old_pattern = NULL;
602 my_pattern = convert_pattern (pattern, match_type, 0);
603 if (regcomp (&r, my_pattern, REG_EXTENDED|REG_NOSUB|MC_ARCH_FLAGS)) {
604 g_free (my_pattern);
605 return -1;
607 old_pattern = my_pattern;
608 old_type = match_type;
610 rval = !regexec (&r, string, 0, NULL, 0);
611 return rval;
614 const char *
615 extension (const char *filename)
617 const char *d = strrchr (filename, '.');
618 return (d != NULL) ? d + 1 : "";
622 get_int (const char *file, const char *key, int def)
624 return GetPrivateProfileInt (app_text, key, def, file);
628 set_int (const char *file, const char *key, int value)
630 char buffer [BUF_TINY];
632 g_snprintf (buffer, sizeof (buffer), "%d", value);
633 return WritePrivateProfileString (app_text, key, buffer, file);
636 extern char *
637 get_config_string (const char *file, const char *key, const char *defval)
639 char buffer[1024];
640 (void)GetPrivateProfileString (app_text, key, defval, buffer, sizeof(buffer), file);
641 return g_strdup (buffer);
644 extern void
645 set_config_string (const char *file, const char *key, const char *val)
647 (void)WritePrivateProfileString (app_text, key, val, file);
651 exist_file (const char *name)
653 return access (name, R_OK) == 0;
656 char *
657 load_file (const char *filename)
659 FILE *data_file;
660 struct stat s;
661 char *data;
662 long read_size;
664 if ((data_file = fopen (filename, "r")) == NULL){
665 return 0;
667 if (fstat (fileno (data_file), &s) != 0){
668 fclose (data_file);
669 return 0;
671 data = g_malloc (s.st_size+1);
672 read_size = fread (data, 1, s.st_size, data_file);
673 data [read_size] = 0;
674 fclose (data_file);
676 if (read_size > 0)
677 return data;
678 else {
679 g_free (data);
680 return 0;
684 char *
685 load_mc_home_file (const char *filename, char **allocated_filename)
687 char *hintfile_base, *hintfile;
688 char *lang;
689 char *data;
691 hintfile_base = mhl_str_dir_plus_file (mc_home, filename);
692 lang = guess_message_value ();
694 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
695 data = load_file (hintfile);
697 if (!data) {
698 g_free (hintfile);
699 /* Fall back to the two-letter language code */
700 if (lang[0] && lang[1])
701 lang[2] = 0;
702 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
703 data = load_file (hintfile);
705 if (!data) {
706 g_free (hintfile);
707 hintfile = hintfile_base;
708 data = load_file (hintfile_base);
712 g_free (lang);
714 if (hintfile != hintfile_base)
715 g_free (hintfile_base);
717 if (allocated_filename)
718 *allocated_filename = hintfile;
719 else
720 g_free (hintfile);
722 return data;
725 /* Check strftime() results. Some systems (i.e. Solaris) have different
726 short-month-name sizes for different locales */
727 size_t
728 i18n_checktimelength (void)
730 time_t testtime = time (NULL);
731 struct tm* lt = localtime(&testtime);
732 size_t length;
734 if (lt == NULL) {
735 // huh, localtime() doesnt seem to work ... falling back to "(invalid)"
736 length = strlen(INVALID_TIME_TEXT);
737 } else {
738 char buf [MAX_I18NTIMELENGTH + 1];
739 size_t a, b;
740 a = strftime (buf, sizeof(buf)-1, _("%b %e %H:%M"), lt);
741 b = strftime (buf, sizeof(buf)-1, _("%b %e %Y"), lt);
742 length = max (a, b);
745 /* Don't handle big differences. Use standard value (email bug, please) */
746 if ( length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH )
747 length = STD_I18NTIMELENGTH;
749 return length;
752 const char *
753 file_date (time_t when)
755 static char timebuf [MAX_I18NTIMELENGTH + 1];
756 time_t current_time = time ((time_t) 0);
757 static size_t i18n_timelength = 0;
758 static const char *fmtyear, *fmttime;
759 const char *fmt;
761 if (i18n_timelength == 0){
762 i18n_timelength = i18n_checktimelength() + 1;
764 /* strftime() format string for old dates */
765 fmtyear = _("%b %e %Y");
766 /* strftime() format string for recent dates */
767 fmttime = _("%b %e %H:%M");
770 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
771 || current_time < when - 60L * 60L) /* In the future. */
772 /* The file is fairly old or in the future.
773 POSIX says the cutoff is 6 months old;
774 approximate this by 6*30 days.
775 Allow a 1 hour slop factor for what is considered "the future",
776 to allow for NFS server/client clock disagreement.
777 Show the year instead of the time of day. */
779 fmt = fmtyear;
780 else
781 fmt = fmttime;
783 FMT_LOCALTIME(timebuf, i18n_timelength, fmt, when);
785 return timebuf;
788 const char *
789 extract_line (const char *s, const char *top)
791 static char tmp_line [BUF_MEDIUM];
792 char *t = tmp_line;
794 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
795 *t++ = *s++;
796 *t = 0;
797 return tmp_line;
800 /* FIXME: I should write a faster version of this (Aho-Corasick stuff) */
801 const char *
802 _icase_search (const char *text, const char *data, int *lng)
804 const char *d = text;
805 const char *e = data;
806 int dlng = 0;
808 if (lng)
809 *lng = 0;
810 for (;*e; e++) {
811 while (*(e+1) == '\b' && *(e+2)) {
812 e += 2;
813 dlng += 2;
815 if (toupper((unsigned char) *d) == toupper((unsigned char) *e))
816 d++;
817 else {
818 e -= d - text;
819 d = text;
820 dlng = 0;
822 if (!*d) {
823 if (lng)
824 *lng = strlen (text) + dlng;
825 return e+1;
828 return 0;
831 /* The basename routine */
832 const char *
833 x_basename (const char *s)
835 const char *where;
836 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
840 const char *
841 unix_error_string (int error_num)
843 static char buffer [BUF_LARGE];
844 #if GLIB_MAJOR_VERSION >= 2
845 gchar *strerror_currentlocale;
847 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
848 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
849 strerror_currentlocale, error_num);
850 g_free(strerror_currentlocale);
851 #else
852 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
853 g_strerror (error_num), error_num);
854 #endif
855 return buffer;
858 const char *
859 skip_separators (const char *s)
861 for (;*s; s++)
862 if (*s != ' ' && *s != '\t' && *s != ',')
863 break;
864 return s;
867 const char *
868 skip_numbers (const char *s)
870 for (;*s; s++)
871 if (!isdigit ((unsigned char) *s))
872 break;
873 return s;
876 /* Remove all control sequences from the argument string. We define
877 * "control sequence", in a sort of pidgin BNF, as follows:
879 * control-seq = Esc non-'['
880 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
882 * This scheme works for all the terminals described in my termcap /
883 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
884 * terminals. If I hear from a single person who uses such a terminal
885 * with MC, I'll be glad to add support for it. (Dugan)
886 * Non-printable characters are also removed.
889 char *
890 strip_ctrl_codes (char *s)
892 char *w; /* Current position where the stripped data is written */
893 char *r; /* Current position where the original data is read */
895 if (!s)
896 return 0;
898 for (w = s, r = s; *r; ) {
899 if (*r == ESC_CHAR) {
900 /* Skip the control sequence's arguments */ ;
901 if (*(++r) == '[') {
902 /* strchr() matches trailing binary 0 */
903 while (*(++r) && strchr ("0123456789;?", *r));
907 * Now we are at the last character of the sequence.
908 * Skip it unless it's binary 0.
910 if (*r)
911 r++;
912 continue;
915 if (is_printable(*r))
916 *w++ = *r;
917 ++r;
919 *w = 0;
920 return s;
924 #ifndef USE_VFS
925 char *
926 get_current_wd (char *buffer, int size)
928 char *p;
929 int len;
931 p = g_get_current_dir ();
932 len = strlen(p) + 1;
934 if (len > size) {
935 g_free (p);
936 return NULL;
939 memcpy (buffer, p, len);
940 g_free (p);
942 return buffer;
944 #endif /* !USE_VFS */
946 enum compression_type
947 get_compression_type (int fd)
949 unsigned char magic[4];
951 /* Read the magic signature */
952 if (mc_read (fd, (char *) magic, 4) != 4)
953 return COMPRESSION_NONE;
955 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
956 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
957 return COMPRESSION_GZIP;
960 /* PKZIP_MAGIC */
961 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
962 && magic[3] == 004) {
963 /* Read compression type */
964 mc_lseek (fd, 8, SEEK_SET);
965 if (mc_read (fd, (char *) magic, 2) != 2)
966 return COMPRESSION_NONE;
968 /* Gzip can handle only deflated (8) or stored (0) files */
969 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
970 return COMPRESSION_NONE;
972 /* Compatible with gzip */
973 return COMPRESSION_GZIP;
976 /* PACK_MAGIC and LZH_MAGIC and compress magic */
977 if (magic[0] == 037
978 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
979 /* Compatible with gzip */
980 return COMPRESSION_GZIP;
983 /* BZIP and BZIP2 files */
984 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
985 (magic[3] >= '1') && (magic[3] <= '9')) {
986 switch (magic[2]) {
987 case '0':
988 return COMPRESSION_BZIP;
989 case 'h':
990 return COMPRESSION_BZIP2;
993 return 0;
996 const char *
997 decompress_extension (int type)
999 switch (type){
1000 case COMPRESSION_GZIP: return "#ugz";
1001 case COMPRESSION_BZIP: return "#ubz";
1002 case COMPRESSION_BZIP2: return "#ubz2";
1004 /* Should never reach this place */
1005 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
1006 return 0;
1009 /* Hooks */
1010 void
1011 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
1013 Hook *new_hook = g_new (Hook, 1);
1015 new_hook->hook_fn = hook_fn;
1016 new_hook->next = *hook_list;
1017 new_hook->hook_data = data;
1019 *hook_list = new_hook;
1022 void
1023 execute_hooks (Hook *hook_list)
1025 Hook *new_hook = 0;
1026 Hook *p;
1028 /* We copy the hook list first so tahat we let the hook
1029 * function call delete_hook
1032 while (hook_list){
1033 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
1034 hook_list = hook_list->next;
1036 p = new_hook;
1038 while (new_hook){
1039 (*new_hook->hook_fn)(new_hook->hook_data);
1040 new_hook = new_hook->next;
1043 for (hook_list = p; hook_list;){
1044 p = hook_list;
1045 hook_list = hook_list->next;
1046 g_free (p);
1050 void
1051 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
1053 Hook *current, *new_list, *next;
1055 new_list = 0;
1057 for (current = *hook_list; current; current = next){
1058 next = current->next;
1059 if (current->hook_fn == hook_fn)
1060 g_free (current);
1061 else
1062 add_hook (&new_list, current->hook_fn, current->hook_data);
1064 *hook_list = new_list;
1068 hook_present (Hook *hook_list, void (*hook_fn)(void *))
1070 Hook *p;
1072 for (p = hook_list; p; p = p->next)
1073 if (p->hook_fn == hook_fn)
1074 return 1;
1075 return 0;
1078 void
1079 wipe_password (char *passwd)
1081 char *p = passwd;
1083 if (!p)
1084 return;
1085 for (;*p ; p++)
1086 *p = 0;
1087 g_free (passwd);
1090 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1091 /* Returns a newly allocated string */
1092 char *
1093 convert_controls (const char *p)
1095 char *valcopy = g_strdup (p);
1096 char *q;
1098 /* Parse the escape special character */
1099 for (q = valcopy; *p;){
1100 if (*p == '\\'){
1101 p++;
1102 if ((*p == 'e') || (*p == 'E')){
1103 p++;
1104 *q++ = ESC_CHAR;
1106 } else {
1107 if (*p == '^'){
1108 p++;
1109 if (*p == '^')
1110 *q++ = *p++;
1111 else {
1112 char c = (*p | 0x20);
1113 if (c >= 'a' && c <= 'z') {
1114 *q++ = c - 'a' + 1;
1115 p++;
1116 } else if (*p)
1117 p++;
1119 } else
1120 *q++ = *p++;
1123 *q = 0;
1124 return valcopy;
1127 static char *
1128 resolve_symlinks (const char *path)
1130 char *buf, *buf2, *q, *r, c;
1131 int len;
1132 struct stat mybuf;
1133 const char *p;
1135 if (*path != PATH_SEP)
1136 return NULL;
1137 r = buf = g_malloc (MC_MAXPATHLEN);
1138 buf2 = g_malloc (MC_MAXPATHLEN);
1139 *r++ = PATH_SEP;
1140 *r = 0;
1141 p = path;
1142 for (;;) {
1143 q = strchr (p + 1, PATH_SEP);
1144 if (!q) {
1145 q = strchr (p + 1, 0);
1146 if (q == p + 1)
1147 break;
1149 c = *q;
1150 *q = 0;
1151 if (mc_lstat (path, &mybuf) < 0) {
1152 g_free (buf);
1153 g_free (buf2);
1154 *q = c;
1155 return NULL;
1157 if (!S_ISLNK (mybuf.st_mode))
1158 strcpy (r, p + 1);
1159 else {
1160 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1161 if (len < 0) {
1162 g_free (buf);
1163 g_free (buf2);
1164 *q = c;
1165 return NULL;
1167 buf2 [len] = 0;
1168 if (*buf2 == PATH_SEP)
1169 strcpy (buf, buf2);
1170 else
1171 strcpy (r, buf2);
1173 canonicalize_pathname (buf);
1174 r = strchr (buf, 0);
1175 if (!*r || *(r - 1) != PATH_SEP) {
1176 *r++ = PATH_SEP;
1177 *r = 0;
1179 *q = c;
1180 p = q;
1181 if (!c)
1182 break;
1184 if (!*buf)
1185 strcpy (buf, PATH_SEP_STR);
1186 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1187 *(r - 1) = 0;
1188 g_free (buf2);
1189 return buf;
1192 /* Finds out a relative path from first to second, i.e. goes as many ..
1193 * as needed up in first and then goes down using second */
1194 char *
1195 diff_two_paths (const char *first, const char *second)
1197 char *p, *q, *r, *s, *buf = NULL;
1198 int i, j, prevlen = -1, currlen;
1199 char *my_first = NULL, *my_second = NULL;
1201 my_first = resolve_symlinks (first);
1202 if (my_first == NULL)
1203 return NULL;
1204 my_second = resolve_symlinks (second);
1205 if (my_second == NULL) {
1206 g_free (my_first);
1207 return NULL;
1209 for (j = 0; j < 2; j++) {
1210 p = my_first;
1211 q = my_second;
1212 for (;;) {
1213 r = strchr (p, PATH_SEP);
1214 s = strchr (q, PATH_SEP);
1215 if (!r || !s)
1216 break;
1217 *r = 0; *s = 0;
1218 if (strcmp (p, q)) {
1219 *r = PATH_SEP; *s = PATH_SEP;
1220 break;
1221 } else {
1222 *r = PATH_SEP; *s = PATH_SEP;
1224 p = r + 1;
1225 q = s + 1;
1227 p--;
1228 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1229 currlen = (i + 1) * 3 + strlen (q) + 1;
1230 if (j) {
1231 if (currlen < prevlen)
1232 g_free (buf);
1233 else {
1234 g_free (my_first);
1235 g_free (my_second);
1236 return buf;
1239 p = buf = g_malloc (currlen);
1240 prevlen = currlen;
1241 for (; i >= 0; i--, p += 3)
1242 strcpy (p, "../");
1243 strcpy (p, q);
1245 g_free (my_first);
1246 g_free (my_second);
1247 return buf;
1250 /* Append text to GList, remove all entries with the same text */
1251 GList *
1252 list_append_unique (GList *list, char *text)
1254 GList *link, *newlink;
1257 * Go to the last position and traverse the list backwards
1258 * starting from the second last entry to make sure that we
1259 * are not removing the current link.
1261 list = g_list_append (list, text);
1262 list = g_list_last (list);
1263 link = g_list_previous (list);
1265 while (link) {
1266 newlink = g_list_previous (link);
1267 if (!strcmp ((char *) link->data, text)) {
1268 g_free (link->data);
1269 g_list_remove_link (list, link);
1270 g_list_free_1 (link);
1272 link = newlink;
1275 return list;
1278 /* Following code heavily borrows from libiberty, mkstemps.c */
1280 /* Number of attempts to create a temporary file */
1281 #ifndef TMP_MAX
1282 #define TMP_MAX 16384
1283 #endif /* !TMP_MAX */
1286 * Arguments:
1287 * pname (output) - pointer to the name of the temp file (needs g_free).
1288 * NULL if the function fails.
1289 * prefix - part of the filename before the random part.
1290 * Prepend $TMPDIR or /tmp if there are no path separators.
1291 * suffix - if not NULL, part of the filename after the random part.
1293 * Result:
1294 * handle of the open file or -1 if couldn't open any.
1297 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1299 static const char letters[]
1300 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1301 static unsigned long value;
1302 struct timeval tv;
1303 char *tmpbase;
1304 char *tmpname;
1305 char *XXXXXX;
1306 int count;
1308 if (strchr (prefix, PATH_SEP) == NULL) {
1309 /* Add prefix first to find the position of XXXXXX */
1310 tmpbase = mhl_str_dir_plus_file (mc_tmpdir (), prefix);
1311 } else {
1312 tmpbase = g_strdup (prefix);
1315 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1316 *pname = tmpname;
1317 XXXXXX = &tmpname[strlen (tmpbase)];
1318 g_free (tmpbase);
1320 /* Get some more or less random data. */
1321 gettimeofday (&tv, NULL);
1322 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1324 for (count = 0; count < TMP_MAX; ++count) {
1325 unsigned long v = value;
1326 int fd;
1328 /* Fill in the random bits. */
1329 XXXXXX[0] = letters[v % 62];
1330 v /= 62;
1331 XXXXXX[1] = letters[v % 62];
1332 v /= 62;
1333 XXXXXX[2] = letters[v % 62];
1334 v /= 62;
1335 XXXXXX[3] = letters[v % 62];
1336 v /= 62;
1337 XXXXXX[4] = letters[v % 62];
1338 v /= 62;
1339 XXXXXX[5] = letters[v % 62];
1341 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1342 S_IRUSR | S_IWUSR);
1343 if (fd >= 0) {
1344 /* Successfully created. */
1345 return fd;
1348 /* This is a random value. It is only necessary that the next
1349 TMP_MAX values generated by adding 7777 to VALUE are different
1350 with (module 2^32). */
1351 value += 7777;
1354 /* Unsuccessful. Free the filename. */
1355 g_free (tmpname);
1356 *pname = NULL;
1358 return -1;
1362 * Read and restore position for the given filename.
1363 * If there is no stored data, return line 1 and col 0.
1365 void
1366 load_file_position (const char *filename, long *line, long *column)
1368 char *fn;
1369 FILE *f;
1370 char buf[MC_MAXPATHLEN + 20];
1371 int len;
1373 /* defaults */
1374 *line = 1;
1375 *column = 0;
1377 /* open file with positions */
1378 fn = mhl_str_dir_plus_file (home_dir, MC_FILEPOS);
1379 f = fopen (fn, "r");
1380 g_free (fn);
1381 if (!f)
1382 return;
1384 len = strlen (filename);
1386 while (fgets (buf, sizeof (buf), f)) {
1387 const char *p;
1389 /* check if the filename matches the beginning of string */
1390 if (strncmp (buf, filename, len) != 0)
1391 continue;
1393 /* followed by single space */
1394 if (buf[len] != ' ')
1395 continue;
1397 /* and string without spaces */
1398 p = &buf[len + 1];
1399 if (strchr (p, ' '))
1400 continue;
1402 *line = strtol(p, const_cast(char **, &p), 10);
1403 if (*p == ';') {
1404 *column = strtol(p+1, const_cast(char **, &p), 10);
1405 if (*p != '\n')
1406 *column = 0;
1407 } else
1408 *line = 1;
1410 fclose (f);
1413 /* Save position for the given file */
1414 void
1415 save_file_position (const char *filename, long line, long column)
1417 char *tmp, *fn;
1418 FILE *f, *t;
1419 char buf[MC_MAXPATHLEN + 20];
1420 int i = 1;
1421 int len;
1423 len = strlen (filename);
1425 tmp = mhl_str_dir_plus_file (home_dir, MC_FILEPOS_TMP);
1426 fn = mhl_str_dir_plus_file (home_dir, MC_FILEPOS);
1428 /* open temporary file */
1429 t = fopen (tmp, "w");
1430 if (!t) {
1431 g_free (tmp);
1432 g_free (fn);
1433 return;
1436 /* put the new record */
1437 if (line != 1 || column != 0) {
1438 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1441 /* copy records from the old file */
1442 f = fopen (fn, "r");
1443 if (f) {
1444 while (fgets (buf, sizeof (buf), f)) {
1445 /* Skip entries for the current filename */
1446 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1447 && !strchr (&buf[len + 1], ' '))
1448 continue;
1450 fprintf (t, "%s", buf);
1451 if (++i > MC_FILEPOS_ENTRIES)
1452 break;
1454 fclose (f);
1457 fclose (t);
1458 rename (tmp, fn);
1459 g_free (tmp);
1460 g_free (fn);
1463 extern const char *
1464 cstrcasestr (const char *haystack, const char *needle)
1466 const char *hptr;
1467 size_t i, needle_len;
1469 needle_len = strlen (needle);
1470 for (hptr = haystack; *hptr != '\0'; hptr++) {
1471 for (i = 0; i < needle_len; i++) {
1472 if (toupper ((unsigned char) hptr[i]) !=
1473 toupper ((unsigned char) needle[i]))
1474 goto next_try;
1476 return hptr;
1477 next_try:
1478 (void) 0;
1480 return NULL;
1483 const char *
1484 cstrstr (const char *haystack, const char *needle)
1486 return strstr(haystack, needle);
1489 extern char *
1490 str_unconst (const char *s)
1492 return (char *) s;
1495 #define ASCII_A (0x40 + 1)
1496 #define ASCII_Z (0x40 + 26)
1497 #define ASCII_a (0x60 + 1)
1498 #define ASCII_z (0x60 + 26)
1500 extern int
1501 ascii_alpha_to_cntrl (int ch)
1503 if ((ch >= ASCII_A && ch <= ASCII_Z)
1504 || (ch >= ASCII_a && ch <= ASCII_z)) {
1505 ch &= 0x1f;
1507 return ch;
1510 const char *
1511 Q_ (const char *s)
1513 const char *result, *sep;
1515 result = _(s);
1516 sep = strchr(result, '|');
1517 return (sep != NULL) ? sep + 1 : result;