Added Copyringt information. Corrected 'Written by' field.
[midnight-commander.git] / src / util.c
blob213a2867477e33de21cb2d6c5ebfea2f8e8f08a7
1 /* Various utilities
2 Copyright (C) 1994, 1995, 1996, 1998, 1999, 2000, 2001, 2002, 2003,
3 2004, 2005, 2007, 2009 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 /** \file
26 * \brief Source: various utilities
29 #include <config.h>
31 #include <ctype.h>
32 #include <limits.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <fcntl.h>
38 #include <sys/time.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <unistd.h>
43 #include "global.h"
45 #include "../src/tty/win.h" /* xterm_flag */
47 #include "../src/search/search.h"
49 #include "main.h" /* mc_home */
50 #include "cmd.h" /* guess_message_value */
51 #include "mountlist.h"
52 #include "timefmt.h"
53 #include "strutil.h"
54 #include "fileopctx.h"
55 #include "file.h" /* copy_file_file() */
57 #ifdef HAVE_CHARSET
58 #include "charsets.h"
59 #endif
61 int easy_patterns = 1;
63 extern void str_replace(char *s, char from, char to)
65 for (; *s != '\0'; s++) {
66 if (*s == from)
67 *s = to;
71 static inline int
72 is_7bit_printable (unsigned char c)
74 return (c > 31 && c < 127);
77 static inline int
78 is_iso_printable (unsigned char c)
80 return ((c > 31 && c < 127) || c >= 160);
83 static inline int
84 is_8bit_printable (unsigned char c)
86 /* "Full 8 bits output" doesn't work on xterm */
87 if (xterm_flag)
88 return is_iso_printable (c);
90 return (c > 31 && c != 127 && c != 155);
93 int
94 is_printable (int c)
96 c &= 0xff;
98 #ifdef HAVE_CHARSET
99 /* "Display bits" is ignored, since the user controls the output
100 by setting the output codepage */
101 return is_8bit_printable (c);
102 #else
103 if (!eight_bit_clean)
104 return is_7bit_printable (c);
106 if (full_eight_bits) {
107 return is_8bit_printable (c);
108 } else
109 return is_iso_printable (c);
110 #endif /* !HAVE_CHARSET */
113 /* Calculates the message dimensions (lines and columns) */
114 void
115 msglen (const char *text, int *lines, int *columns)
117 int nlines = 1; /* even the empty string takes one line */
118 int ncolumns = 0;
119 int colindex = 0;
121 for (; *text != '\0'; text++) {
122 if (*text == '\n') {
123 nlines++;
124 colindex = 0;
125 } else {
126 colindex++;
127 if (colindex > ncolumns)
128 ncolumns = colindex;
132 *lines = nlines;
133 *columns = ncolumns;
137 * Copy from s to d, and trim the beginning if necessary, and prepend
138 * "..." in this case. The destination string can have at most len
139 * bytes, not counting trailing 0.
141 char *
142 trim (const char *s, char *d, int len)
144 int source_len;
146 /* Sanity check */
147 len = max (len, 0);
149 source_len = strlen (s);
150 if (source_len > len) {
151 /* Cannot fit the whole line */
152 if (len <= 3) {
153 /* We only have room for the dots */
154 memset (d, '.', len);
155 d[len] = 0;
156 return d;
157 } else {
158 /* Begin with ... and add the rest of the source string */
159 memset (d, '.', 3);
160 strcpy (d + 3, s + 3 + source_len - len);
162 } else
163 /* We can copy the whole line */
164 strcpy (d, s);
165 return d;
169 * Quote the filename for the purpose of inserting it into the command
170 * line. If quote_percent is 1, replace "%" with "%%" - the percent is
171 * processed by the mc command line.
173 char *
174 name_quote (const char *s, int quote_percent)
176 char *ret, *d;
178 d = ret = g_malloc (strlen (s) * 2 + 2 + 1);
179 if (*s == '-') {
180 *d++ = '.';
181 *d++ = '/';
184 for (; *s; s++, d++) {
185 switch (*s) {
186 case '%':
187 if (quote_percent)
188 *d++ = '%';
189 break;
190 case '\'':
191 case '\\':
192 case '\r':
193 case '\n':
194 case '\t':
195 case '"':
196 case ';':
197 case ' ':
198 case '?':
199 case '|':
200 case '[':
201 case ']':
202 case '{':
203 case '}':
204 case '<':
205 case '>':
206 case '`':
207 case '!':
208 case '$':
209 case '&':
210 case '*':
211 case '(':
212 case ')':
213 *d++ = '\\';
214 break;
215 case '~':
216 case '#':
217 if (d == ret)
218 *d++ = '\\';
219 break;
221 *d = *s;
223 *d = '\0';
224 return ret;
227 char *
228 fake_name_quote (const char *s, int quote_percent)
230 (void) quote_percent;
231 return g_strdup (s);
235 * Remove the middle part of the string to fit given length.
236 * Use "~" to show where the string was truncated.
237 * Return static buffer, no need to free() it.
239 const char *
240 name_trunc (const char *txt, size_t trunc_len)
242 return str_trunc (txt, trunc_len);
246 * path_trunc() is the same as name_trunc() above but
247 * it deletes possible password from path for security
248 * reasons.
250 const char *
251 path_trunc (const char *path, size_t trunc_len) {
252 char *secure_path = strip_password (g_strdup (path), 1);
254 const char *ret = str_trunc (secure_path, trunc_len);
255 g_free (secure_path);
257 return ret;
260 const char *
261 size_trunc (double size)
263 static char x [BUF_TINY];
264 long int divisor = 1;
265 const char *xtra = "";
267 if (size > 999999999L){
268 divisor = 1024;
269 xtra = "K";
270 if (size/divisor > 999999999L){
271 divisor = 1024*1024;
272 xtra = "M";
275 g_snprintf (x, sizeof (x), "%.0f%s", (size/divisor), xtra);
276 return x;
279 const char *
280 size_trunc_sep (double size)
282 static char x [60];
283 int count;
284 const char *p, *y;
285 char *d;
287 p = y = size_trunc (size);
288 p += strlen (p) - 1;
289 d = x + sizeof (x) - 1;
290 *d-- = 0;
291 while (p >= y && isalpha ((unsigned char) *p))
292 *d-- = *p--;
293 for (count = 0; p >= y; count++){
294 if (count == 3){
295 *d-- = ',';
296 count = 0;
298 *d-- = *p--;
300 d++;
301 if (*d == ',')
302 d++;
303 return d;
307 * Print file SIZE to BUFFER, but don't exceed LEN characters,
308 * not including trailing 0. BUFFER should be at least LEN+1 long.
309 * This function is called for every file on panels, so avoid
310 * floating point by any means.
312 * Units: size units (filesystem sizes are 1K blocks)
313 * 0=bytes, 1=Kbytes, 2=Mbytes, etc.
315 void
316 size_trunc_len (char *buffer, int len, off_t size, int units)
318 /* Avoid taking power for every file. */
319 static const off_t power10 [] =
320 {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000,
321 1000000000};
322 static const char * const suffix [] =
323 {"", "K", "M", "G", "T", "P", "E", "Z", "Y", NULL};
324 int j = 0;
326 /* Don't print more than 9 digits - use suffix. */
327 if (len == 0 || len > 9)
328 len = 9;
330 for (j = units; suffix [j] != NULL; j++) {
331 if (size == 0) {
332 if (j == units) {
333 /* Empty files will print "0" even with minimal width. */
334 g_snprintf (buffer, len + 1, "0");
335 break;
338 /* Use "~K" or just "K" if len is 1. Use "B" for bytes. */
339 g_snprintf (buffer, len + 1, (len > 1) ? "~%s" : "%s",
340 (j > 1) ? suffix[j - 1] : "B");
341 break;
344 if (size < power10 [len - (j > 0)]) {
345 g_snprintf (buffer, len + 1, "%lu%s", (unsigned long) size, suffix[j]);
346 break;
349 /* Powers of 1024, with rounding. */
350 size = (size + 512) >> 10;
355 is_exe (mode_t mode)
357 if ((S_IXUSR & mode) || (S_IXGRP & mode) || (S_IXOTH & mode))
358 return 1;
359 return 0;
362 #define ismode(n,m) ((n & m) == m)
364 const char *
365 string_perm (mode_t mode_bits)
367 static char mode[11];
369 strcpy (mode, "----------");
370 if (S_ISDIR (mode_bits))
371 mode[0] = 'd';
372 if (S_ISCHR (mode_bits))
373 mode[0] = 'c';
374 if (S_ISBLK (mode_bits))
375 mode[0] = 'b';
376 if (S_ISLNK (mode_bits))
377 mode[0] = 'l';
378 if (S_ISFIFO (mode_bits))
379 mode[0] = 'p';
380 if (S_ISNAM (mode_bits))
381 mode[0] = 'n';
382 if (S_ISSOCK (mode_bits))
383 mode[0] = 's';
384 if (S_ISDOOR (mode_bits))
385 mode[0] = 'D';
386 if (ismode (mode_bits, S_IXOTH))
387 mode[9] = 'x';
388 if (ismode (mode_bits, S_IWOTH))
389 mode[8] = 'w';
390 if (ismode (mode_bits, S_IROTH))
391 mode[7] = 'r';
392 if (ismode (mode_bits, S_IXGRP))
393 mode[6] = 'x';
394 if (ismode (mode_bits, S_IWGRP))
395 mode[5] = 'w';
396 if (ismode (mode_bits, S_IRGRP))
397 mode[4] = 'r';
398 if (ismode (mode_bits, S_IXUSR))
399 mode[3] = 'x';
400 if (ismode (mode_bits, S_IWUSR))
401 mode[2] = 'w';
402 if (ismode (mode_bits, S_IRUSR))
403 mode[1] = 'r';
404 #ifdef S_ISUID
405 if (ismode (mode_bits, S_ISUID))
406 mode[3] = (mode[3] == 'x') ? 's' : 'S';
407 #endif /* S_ISUID */
408 #ifdef S_ISGID
409 if (ismode (mode_bits, S_ISGID))
410 mode[6] = (mode[6] == 'x') ? 's' : 'S';
411 #endif /* S_ISGID */
412 #ifdef S_ISVTX
413 if (ismode (mode_bits, S_ISVTX))
414 mode[9] = (mode[9] == 'x') ? 't' : 'T';
415 #endif /* S_ISVTX */
416 return mode;
419 /* p: string which might contain an url with a password (this parameter is
420 modified in place).
421 has_prefix = 0: The first parameter is an url without a prefix
422 (user[:pass]@]machine[:port][remote-dir). Delete
423 the password.
424 has_prefix = 1: Search p for known url prefixes. If found delete
425 the password from the url.
426 Caveat: only the first url is found
428 char *
429 strip_password (char *p, int has_prefix)
431 static const struct {
432 const char *name;
433 size_t len;
434 } prefixes[] = { {"/#ftp:", 6},
435 {"ftp://", 6},
436 {"/#mc:", 5},
437 {"mc://", 5},
438 {"/#smb:", 6},
439 {"smb://", 6},
440 {"/#sh:", 5},
441 {"sh://", 5},
442 {"ssh://", 6}
444 char *at, *inner_colon, *dir;
445 size_t i;
446 char *result = p;
448 for (i = 0; i < sizeof (prefixes)/sizeof (prefixes[0]); i++) {
449 char *q;
451 if (has_prefix) {
452 if((q = strstr (p, prefixes[i].name)) == 0)
453 continue;
454 else
455 p = q + prefixes[i].len;
458 if ((dir = strchr (p, PATH_SEP)) != NULL)
459 *dir = '\0';
461 /* search for any possible user */
462 at = strrchr (p, '@');
464 if (dir)
465 *dir = PATH_SEP;
467 /* We have a username */
468 if (at) {
469 inner_colon = memchr (p, ':', at - p);
470 if (inner_colon)
471 memmove (inner_colon, at, strlen(at) + 1);
473 break;
475 return (result);
478 const char *
479 strip_home_and_password(const char *dir)
481 size_t len;
482 static char newdir [MC_MAXPATHLEN];
484 if (home_dir && !strncmp (dir, home_dir, len = strlen (home_dir)) &&
485 (dir[len] == PATH_SEP || dir[len] == '\0')){
486 newdir [0] = '~';
487 g_strlcpy (&newdir [1], &dir [len], sizeof(newdir) - 1);
488 return newdir;
491 /* We do not strip homes in /#ftp tree, I do not like ~'s there
492 (see ftpfs.c why) */
493 g_strlcpy (newdir, dir, sizeof(newdir));
494 strip_password (newdir, 1);
495 return newdir;
498 const char *
499 extension (const char *filename)
501 const char *d = strrchr (filename, '.');
502 return (d != NULL) ? d + 1 : "";
506 exist_file (const char *name)
508 return access (name, R_OK) == 0;
512 check_for_default (const char *default_file, const char *file)
514 if (!exist_file (file)) {
515 FileOpContext *ctx;
516 off_t count = 0;
517 double bytes = 0.0;
519 if (!exist_file (default_file))
520 return -1;
522 ctx = file_op_context_new (OP_COPY);
523 file_op_context_create_ui (ctx, 0);
524 copy_file_file (ctx, default_file, file, 1, &count, &bytes, 1);
525 file_op_context_destroy (ctx);
528 return 0;
533 char *
534 load_file (const char *filename)
536 FILE *data_file;
537 struct stat s;
538 char *data;
539 long read_size;
541 if ((data_file = fopen (filename, "r")) == NULL){
542 return 0;
544 if (fstat (fileno (data_file), &s) != 0){
545 fclose (data_file);
546 return 0;
548 data = g_malloc (s.st_size+1);
549 read_size = fread (data, 1, s.st_size, data_file);
550 data [read_size] = 0;
551 fclose (data_file);
553 if (read_size > 0)
554 return data;
555 else {
556 g_free (data);
557 return 0;
561 char *
562 load_mc_home_file (const char *filename, char **allocated_filename)
564 char *hintfile_base, *hintfile;
565 char *lang;
566 char *data;
568 hintfile_base = concat_dir_and_file (mc_home, filename);
569 lang = guess_message_value ();
571 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
572 data = load_file (hintfile);
574 if (!data) {
575 g_free (hintfile);
576 g_free (hintfile_base);
577 hintfile_base = concat_dir_and_file (mc_home_alt, filename);
579 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
580 data = load_file (hintfile);
582 if (!data) {
583 /* Fall back to the two-letter language code */
584 if (lang[0] && lang[1])
585 lang[2] = 0;
586 hintfile = g_strconcat (hintfile_base, ".", lang, (char *) NULL);
587 data = load_file (hintfile);
589 if (!data) {
590 g_free (hintfile);
591 hintfile = hintfile_base;
592 data = load_file (hintfile_base);
597 g_free (lang);
599 if (hintfile != hintfile_base)
600 g_free (hintfile_base);
602 if (allocated_filename)
603 *allocated_filename = hintfile;
604 else
605 g_free (hintfile);
607 return data;
610 /* Check strftime() results. Some systems (i.e. Solaris) have different
611 short-month-name sizes for different locales */
612 size_t
613 i18n_checktimelength (void)
615 size_t length;
616 time_t testtime = time (NULL);
617 struct tm* lt = localtime(&testtime);
619 if (lt == NULL) {
620 /* huh, localtime() doesnt seem to work ... falling back to "(invalid)" */
621 length = str_term_width1 (_(INVALID_TIME_TEXT));
622 } else {
623 char buf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
624 size_t a, b;
626 strftime (buf, sizeof(buf) - 1, _("%b %d %H:%M"), lt);
627 a = str_term_width1 (buf);
628 strftime (buf, sizeof(buf) - 1, _("%b %d %Y"), lt);
629 b = str_term_width1 (buf);
631 length = max (a, b);
632 length = max ((size_t)str_term_width1 (_(INVALID_TIME_TEXT)), length);
635 /* Don't handle big differences. Use standard value (email bug, please) */
636 if (length > MAX_I18NTIMELENGTH || length < MIN_I18NTIMELENGTH)
637 length = STD_I18NTIMELENGTH;
639 return length;
642 const char *
643 file_date (time_t when)
645 static char timebuf [MB_LEN_MAX * MAX_I18NTIMELENGTH + 1];
646 time_t current_time = time ((time_t) 0);
647 static int i18n = 0;
648 static const char *fmtyear, *fmttime;
649 const char *fmt;
651 if (!i18n){
652 /* strftime() format string for old dates */
653 fmtyear = _("%b %e %Y");
654 /* strftime() format string for recent dates */
655 fmttime = _("%b %e %H:%M");
656 i18n = 1;
659 if (current_time > when + 6L * 30L * 24L * 60L * 60L /* Old. */
660 || current_time < when - 60L * 60L) /* In the future. */
661 /* The file is fairly old or in the future.
662 POSIX says the cutoff is 6 months old;
663 approximate this by 6*30 days.
664 Allow a 1 hour slop factor for what is considered "the future",
665 to allow for NFS server/client clock disagreement.
666 Show the year instead of the time of day. */
668 fmt = fmtyear;
669 else
670 fmt = fmttime;
672 FMT_LOCALTIME(timebuf, sizeof (timebuf), fmt, when);
674 return timebuf;
677 const char *
678 extract_line (const char *s, const char *top)
680 static char tmp_line [BUF_MEDIUM];
681 char *t = tmp_line;
683 while (*s && *s != '\n' && (size_t) (t - tmp_line) < sizeof (tmp_line)-1 && s < top)
684 *t++ = *s++;
685 *t = 0;
686 return tmp_line;
689 /* The basename routine */
690 const char *
691 x_basename (const char *s)
693 const char *where;
694 return ((where = strrchr (s, PATH_SEP))) ? where + 1 : s;
698 const char *
699 unix_error_string (int error_num)
701 static char buffer [BUF_LARGE];
702 #if GLIB_MAJOR_VERSION >= 2
703 gchar *strerror_currentlocale;
705 strerror_currentlocale = g_locale_from_utf8(g_strerror (error_num), -1, NULL, NULL, NULL);
706 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
707 strerror_currentlocale, error_num);
708 g_free(strerror_currentlocale);
709 #else
710 g_snprintf (buffer, sizeof (buffer), "%s (%d)",
711 g_strerror (error_num), error_num);
712 #endif
713 return buffer;
716 const char *
717 skip_separators (const char *s)
719 const char *su = s;
721 for (;*su; str_cnext_char (&su))
722 if (*su != ' ' && *su != '\t' && *su != ',') break;
724 return su;
727 const char *
728 skip_numbers (const char *s)
730 const char *su = s;
732 for (;*su; str_cnext_char (&su))
733 if (!str_isdigit (su)) break;
735 return su;
738 /* Remove all control sequences from the argument string. We define
739 * "control sequence", in a sort of pidgin BNF, as follows:
741 * control-seq = Esc non-'['
742 * | Esc '[' (0 or more digits or ';' or '?') (any other char)
744 * This scheme works for all the terminals described in my termcap /
745 * terminfo databases, except the Hewlett-Packard 70092 and some Wyse
746 * terminals. If I hear from a single person who uses such a terminal
747 * with MC, I'll be glad to add support for it. (Dugan)
748 * Non-printable characters are also removed.
751 char *
752 strip_ctrl_codes (char *s)
754 char *w; /* Current position where the stripped data is written */
755 char *r; /* Current position where the original data is read */
756 char *n;
758 if (!s)
759 return 0;
761 for (w = s, r = s; *r; ) {
762 if (*r == ESC_CHAR) {
763 /* Skip the control sequence's arguments */ ;
764 if (*(++r) == '[') {
765 /* strchr() matches trailing binary 0 */
766 while (*(++r) && strchr ("0123456789;?", *r));
767 } else
768 if (*r == ']') {
770 * Skip xterm's OSC (Operating System Command)
771 * http://www.xfree86.org/current/ctlseqs.html
772 * OSC P s ; P t ST
773 * OSC P s ; P t BEL
775 char * new_r = r;
777 for (; *new_r; ++new_r)
779 switch (*new_r)
781 /* BEL */
782 case '\a':
783 r = new_r;
784 goto osc_out;
785 case ESC_CHAR:
786 /* ST */
787 if (*(new_r + 1) == '\\')
789 r = new_r + 1;
790 goto osc_out;
794 osc_out:;
798 * Now we are at the last character of the sequence.
799 * Skip it unless it's binary 0.
801 if (*r)
802 r++;
803 continue;
806 n = str_get_next_char (r);
807 if (str_isprint (r)) {
808 memmove (w, r, n - r);
809 w+= n - r;
811 r = n;
813 *w = 0;
814 return s;
818 #ifndef USE_VFS
819 char *
820 get_current_wd (char *buffer, int size)
822 char *p;
823 int len;
825 p = g_get_current_dir ();
826 len = strlen(p) + 1;
828 if (len > size) {
829 g_free (p);
830 return NULL;
833 memcpy (buffer, p, len);
834 g_free (p);
836 return buffer;
838 #endif /* !USE_VFS */
840 enum compression_type
841 get_compression_type (int fd)
843 unsigned char magic[16];
845 /* Read the magic signature */
846 if (mc_read (fd, (char *) magic, 4) != 4)
847 return COMPRESSION_NONE;
849 /* GZIP_MAGIC and OLD_GZIP_MAGIC */
850 if (magic[0] == 037 && (magic[1] == 0213 || magic[1] == 0236)) {
851 return COMPRESSION_GZIP;
854 /* PKZIP_MAGIC */
855 if (magic[0] == 0120 && magic[1] == 0113 && magic[2] == 003
856 && magic[3] == 004) {
857 /* Read compression type */
858 mc_lseek (fd, 8, SEEK_SET);
859 if (mc_read (fd, (char *) magic, 2) != 2)
860 return COMPRESSION_NONE;
862 /* Gzip can handle only deflated (8) or stored (0) files */
863 if ((magic[0] != 8 && magic[0] != 0) || magic[1] != 0)
864 return COMPRESSION_NONE;
866 /* Compatible with gzip */
867 return COMPRESSION_GZIP;
870 /* PACK_MAGIC and LZH_MAGIC and compress magic */
871 if (magic[0] == 037
872 && (magic[1] == 036 || magic[1] == 0240 || magic[1] == 0235)) {
873 /* Compatible with gzip */
874 return COMPRESSION_GZIP;
877 /* BZIP and BZIP2 files */
878 if ((magic[0] == 'B') && (magic[1] == 'Z') &&
879 (magic[3] >= '1') && (magic[3] <= '9')) {
880 switch (magic[2]) {
881 case '0':
882 return COMPRESSION_BZIP;
883 case 'h':
884 return COMPRESSION_BZIP2;
888 /* Support for LZMA (only utils format with magic in header).
889 * This is the default format of LZMA utils 4.32.1 and later. */
891 if (mc_read(fd, (char *) magic+4, 1) == 1)
893 /* LZMA utils format */
895 ( magic[0] == 0xFF
896 && magic[1] == 'L'
897 && magic[2] == 'Z'
898 && magic[3] == 'M'
899 && magic[4] == 'A'
900 && magic[5] == 0x00
902 return COMPRESSION_LZMA;
905 /* XZ compression magic */
906 if (magic[0] == 0xFD
907 && magic[1] == 0x37 && magic[2] == 0x7A && magic[3] == 0x58) {
908 if (mc_read (fd, (char *) magic + 4, 2) == 2) {
909 if (magic[4] == 0x5A && magic[5] == 0x00) {
910 return COMPRESSION_XZ;
915 return COMPRESSION_NONE;
918 const char *
919 decompress_extension (int type)
921 switch (type){
922 case COMPRESSION_GZIP: return "#ugz";
923 case COMPRESSION_BZIP: return "#ubz";
924 case COMPRESSION_BZIP2: return "#ubz2";
925 case COMPRESSION_LZMA: return "#ulzma";
926 case COMPRESSION_XZ: return "#uxz";
928 /* Should never reach this place */
929 fprintf (stderr, "Fatal: decompress_extension called with an unknown argument\n");
930 return 0;
933 /* Hooks */
934 void
935 add_hook (Hook **hook_list, void (*hook_fn)(void *), void *data)
937 Hook *new_hook = g_new (Hook, 1);
939 new_hook->hook_fn = hook_fn;
940 new_hook->next = *hook_list;
941 new_hook->hook_data = data;
943 *hook_list = new_hook;
946 void
947 execute_hooks (Hook *hook_list)
949 Hook *new_hook = 0;
950 Hook *p;
952 /* We copy the hook list first so tahat we let the hook
953 * function call delete_hook
956 while (hook_list){
957 add_hook (&new_hook, hook_list->hook_fn, hook_list->hook_data);
958 hook_list = hook_list->next;
960 p = new_hook;
962 while (new_hook){
963 (*new_hook->hook_fn)(new_hook->hook_data);
964 new_hook = new_hook->next;
967 for (hook_list = p; hook_list;){
968 p = hook_list;
969 hook_list = hook_list->next;
970 g_free (p);
974 void
975 delete_hook (Hook **hook_list, void (*hook_fn)(void *))
977 Hook *current, *new_list, *next;
979 new_list = 0;
981 for (current = *hook_list; current; current = next){
982 next = current->next;
983 if (current->hook_fn == hook_fn)
984 g_free (current);
985 else
986 add_hook (&new_list, current->hook_fn, current->hook_data);
988 *hook_list = new_list;
992 hook_present (Hook *hook_list, void (*hook_fn)(void *))
994 Hook *p;
996 for (p = hook_list; p; p = p->next)
997 if (p->hook_fn == hook_fn)
998 return 1;
999 return 0;
1002 void
1003 wipe_password (char *passwd)
1005 char *p = passwd;
1007 if (!p)
1008 return;
1009 for (;*p ; p++)
1010 *p = 0;
1011 g_free (passwd);
1014 /* Convert "\E" -> esc character and ^x to control-x key and ^^ to ^ key */
1015 /* Returns a newly allocated string */
1016 char *
1017 convert_controls (const char *p)
1019 char *valcopy = g_strdup (p);
1020 char *q;
1022 /* Parse the escape special character */
1023 for (q = valcopy; *p;){
1024 if (*p == '\\'){
1025 p++;
1026 if ((*p == 'e') || (*p == 'E')){
1027 p++;
1028 *q++ = ESC_CHAR;
1030 } else {
1031 if (*p == '^'){
1032 p++;
1033 if (*p == '^')
1034 *q++ = *p++;
1035 else {
1036 char c = (*p | 0x20);
1037 if (c >= 'a' && c <= 'z') {
1038 *q++ = c - 'a' + 1;
1039 p++;
1040 } else if (*p)
1041 p++;
1043 } else
1044 *q++ = *p++;
1047 *q = 0;
1048 return valcopy;
1051 static char *
1052 resolve_symlinks (const char *path)
1054 char *buf, *buf2, *q, *r, c;
1055 int len;
1056 struct stat mybuf;
1057 const char *p;
1059 if (*path != PATH_SEP)
1060 return NULL;
1061 r = buf = g_malloc (MC_MAXPATHLEN);
1062 buf2 = g_malloc (MC_MAXPATHLEN);
1063 *r++ = PATH_SEP;
1064 *r = 0;
1065 p = path;
1066 for (;;) {
1067 q = strchr (p + 1, PATH_SEP);
1068 if (!q) {
1069 q = strchr (p + 1, 0);
1070 if (q == p + 1)
1071 break;
1073 c = *q;
1074 *q = 0;
1075 if (mc_lstat (path, &mybuf) < 0) {
1076 g_free (buf);
1077 g_free (buf2);
1078 *q = c;
1079 return NULL;
1081 if (!S_ISLNK (mybuf.st_mode))
1082 strcpy (r, p + 1);
1083 else {
1084 len = mc_readlink (path, buf2, MC_MAXPATHLEN - 1);
1085 if (len < 0) {
1086 g_free (buf);
1087 g_free (buf2);
1088 *q = c;
1089 return NULL;
1091 buf2 [len] = 0;
1092 if (*buf2 == PATH_SEP)
1093 strcpy (buf, buf2);
1094 else
1095 strcpy (r, buf2);
1097 canonicalize_pathname (buf);
1098 r = strchr (buf, 0);
1099 if (!*r || *(r - 1) != PATH_SEP) {
1100 *r++ = PATH_SEP;
1101 *r = 0;
1103 *q = c;
1104 p = q;
1105 if (!c)
1106 break;
1108 if (!*buf)
1109 strcpy (buf, PATH_SEP_STR);
1110 else if (*(r - 1) == PATH_SEP && r != buf + 1)
1111 *(r - 1) = 0;
1112 g_free (buf2);
1113 return buf;
1116 /* Finds out a relative path from first to second, i.e. goes as many ..
1117 * as needed up in first and then goes down using second */
1118 char *
1119 diff_two_paths (const char *first, const char *second)
1121 char *p, *q, *r, *s, *buf = NULL;
1122 int i, j, prevlen = -1, currlen;
1123 char *my_first = NULL, *my_second = NULL;
1125 my_first = resolve_symlinks (first);
1126 if (my_first == NULL)
1127 return NULL;
1128 my_second = resolve_symlinks (second);
1129 if (my_second == NULL) {
1130 g_free (my_first);
1131 return NULL;
1133 for (j = 0; j < 2; j++) {
1134 p = my_first;
1135 q = my_second;
1136 for (;;) {
1137 r = strchr (p, PATH_SEP);
1138 s = strchr (q, PATH_SEP);
1139 if (!r || !s)
1140 break;
1141 *r = 0; *s = 0;
1142 if (strcmp (p, q)) {
1143 *r = PATH_SEP; *s = PATH_SEP;
1144 break;
1145 } else {
1146 *r = PATH_SEP; *s = PATH_SEP;
1148 p = r + 1;
1149 q = s + 1;
1151 p--;
1152 for (i = 0; (p = strchr (p + 1, PATH_SEP)) != NULL; i++);
1153 currlen = (i + 1) * 3 + strlen (q) + 1;
1154 if (j) {
1155 if (currlen < prevlen)
1156 g_free (buf);
1157 else {
1158 g_free (my_first);
1159 g_free (my_second);
1160 return buf;
1163 p = buf = g_malloc (currlen);
1164 prevlen = currlen;
1165 for (; i >= 0; i--, p += 3)
1166 strcpy (p, "../");
1167 strcpy (p, q);
1169 g_free (my_first);
1170 g_free (my_second);
1171 return buf;
1174 /* If filename is NULL, then we just append PATH_SEP to the dir */
1175 char *
1176 concat_dir_and_file (const char *dir, const char *file)
1178 int i = strlen (dir);
1180 if (dir [i-1] == PATH_SEP)
1181 return g_strconcat (dir, file, (char *) NULL);
1182 else
1183 return g_strconcat (dir, PATH_SEP_STR, file, (char *) NULL);
1186 /* Append text to GList, remove all entries with the same text */
1187 GList *
1188 list_append_unique (GList *list, char *text)
1190 GList *link, *newlink, *tmp;
1193 * Go to the last position and traverse the list backwards
1194 * starting from the second last entry to make sure that we
1195 * are not removing the current link.
1197 list = g_list_append (list, text);
1198 list = g_list_last (list);
1199 link = g_list_previous (list);
1201 while (link) {
1202 newlink = g_list_previous (link);
1203 if (!strcmp ((char *) link->data, text)) {
1204 g_free (link->data);
1205 tmp = g_list_remove_link (list, link);
1206 g_list_free_1 (link);
1208 link = newlink;
1211 return list;
1214 /* Following code heavily borrows from libiberty, mkstemps.c */
1216 /* Number of attempts to create a temporary file */
1217 #ifndef TMP_MAX
1218 #define TMP_MAX 16384
1219 #endif /* !TMP_MAX */
1222 * Arguments:
1223 * pname (output) - pointer to the name of the temp file (needs g_free).
1224 * NULL if the function fails.
1225 * prefix - part of the filename before the random part.
1226 * Prepend $TMPDIR or /tmp if there are no path separators.
1227 * suffix - if not NULL, part of the filename after the random part.
1229 * Result:
1230 * handle of the open file or -1 if couldn't open any.
1233 mc_mkstemps (char **pname, const char *prefix, const char *suffix)
1235 static const char letters[]
1236 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
1237 static unsigned long value;
1238 struct timeval tv;
1239 char *tmpbase;
1240 char *tmpname;
1241 char *XXXXXX;
1242 int count;
1244 if (strchr (prefix, PATH_SEP) == NULL) {
1245 /* Add prefix first to find the position of XXXXXX */
1246 tmpbase = concat_dir_and_file (mc_tmpdir (), prefix);
1247 } else {
1248 tmpbase = g_strdup (prefix);
1251 tmpname = g_strconcat (tmpbase, "XXXXXX", suffix, (char *) NULL);
1252 *pname = tmpname;
1253 XXXXXX = &tmpname[strlen (tmpbase)];
1254 g_free (tmpbase);
1256 /* Get some more or less random data. */
1257 gettimeofday (&tv, NULL);
1258 value += (tv.tv_usec << 16) ^ tv.tv_sec ^ getpid ();
1260 for (count = 0; count < TMP_MAX; ++count) {
1261 unsigned long v = value;
1262 int fd;
1264 /* Fill in the random bits. */
1265 XXXXXX[0] = letters[v % 62];
1266 v /= 62;
1267 XXXXXX[1] = letters[v % 62];
1268 v /= 62;
1269 XXXXXX[2] = letters[v % 62];
1270 v /= 62;
1271 XXXXXX[3] = letters[v % 62];
1272 v /= 62;
1273 XXXXXX[4] = letters[v % 62];
1274 v /= 62;
1275 XXXXXX[5] = letters[v % 62];
1277 fd = open (tmpname, O_RDWR | O_CREAT | O_TRUNC | O_EXCL,
1278 S_IRUSR | S_IWUSR);
1279 if (fd >= 0) {
1280 /* Successfully created. */
1281 return fd;
1284 /* This is a random value. It is only necessary that the next
1285 TMP_MAX values generated by adding 7777 to VALUE are different
1286 with (module 2^32). */
1287 value += 7777;
1290 /* Unsuccessful. Free the filename. */
1291 g_free (tmpname);
1292 *pname = NULL;
1294 return -1;
1298 * Read and restore position for the given filename.
1299 * If there is no stored data, return line 1 and col 0.
1301 void
1302 load_file_position (const char *filename, long *line, long *column)
1304 char *fn;
1305 FILE *f;
1306 char buf[MC_MAXPATHLEN + 20];
1307 int len;
1309 /* defaults */
1310 *line = 1;
1311 *column = 0;
1313 /* open file with positions */
1314 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1315 f = fopen (fn, "r");
1316 g_free (fn);
1317 if (!f)
1318 return;
1320 len = strlen (filename);
1322 while (fgets (buf, sizeof (buf), f)) {
1323 const char *p;
1325 /* check if the filename matches the beginning of string */
1326 if (strncmp (buf, filename, len) != 0)
1327 continue;
1329 /* followed by single space */
1330 if (buf[len] != ' ')
1331 continue;
1333 /* and string without spaces */
1334 p = &buf[len + 1];
1335 if (strchr (p, ' '))
1336 continue;
1338 *line = strtol(p, const_cast(char **, &p), 10);
1339 if (*p == ';') {
1340 *column = strtol(p+1, const_cast(char **, &p), 10);
1341 if (*p != '\n')
1342 *column = 0;
1343 } else
1344 *line = 1;
1346 fclose (f);
1349 /* Save position for the given file */
1350 void
1351 save_file_position (const char *filename, long line, long column)
1353 char *tmp, *fn;
1354 FILE *f, *t;
1355 char buf[MC_MAXPATHLEN + 20];
1356 int i = 1;
1357 int len;
1359 len = strlen (filename);
1361 tmp = concat_dir_and_file (home_dir, MC_FILEPOS_TMP);
1362 fn = concat_dir_and_file (home_dir, MC_FILEPOS);
1364 /* open temporary file */
1365 t = fopen (tmp, "w");
1366 if (!t) {
1367 g_free (tmp);
1368 g_free (fn);
1369 return;
1372 /* put the new record */
1373 if (line != 1 || column != 0) {
1374 fprintf (t, "%s %ld;%ld\n", filename, line, column);
1377 /* copy records from the old file */
1378 f = fopen (fn, "r");
1379 if (f) {
1380 while (fgets (buf, sizeof (buf), f)) {
1381 /* Skip entries for the current filename */
1382 if (strncmp (buf, filename, len) == 0 && buf[len] == ' '
1383 && !strchr (&buf[len + 1], ' '))
1384 continue;
1386 fprintf (t, "%s", buf);
1387 if (++i > MC_FILEPOS_ENTRIES)
1388 break;
1390 fclose (f);
1393 fclose (t);
1394 rename (tmp, fn);
1395 g_free (tmp);
1396 g_free (fn);
1399 extern const char *
1400 cstrcasestr (const char *haystack, const char *needle)
1402 char *nee = str_create_search_needle (needle, 0);
1403 const char *result = str_search_first (haystack, nee, 0);
1404 str_release_search_needle (nee, 0);
1405 return result;
1408 const char *
1409 cstrstr (const char *haystack, const char *needle)
1411 return strstr(haystack, needle);
1414 extern char *
1415 str_unconst (const char *s)
1417 return (char *) s;
1420 #define ASCII_A (0x40 + 1)
1421 #define ASCII_Z (0x40 + 26)
1422 #define ASCII_a (0x60 + 1)
1423 #define ASCII_z (0x60 + 26)
1425 extern int
1426 ascii_alpha_to_cntrl (int ch)
1428 if ((ch >= ASCII_A && ch <= ASCII_Z)
1429 || (ch >= ASCII_a && ch <= ASCII_z)) {
1430 ch &= 0x1f;
1432 return ch;
1435 const char *
1436 Q_ (const char *s)
1438 const char *result, *sep;
1440 result = _(s);
1441 sep = strchr(result, '|');
1442 return (sep != NULL) ? sep + 1 : result;