r3274: Don't hang when entering a bad network dir in the minibuffer.
[rox-filer.git] / ROX-Filer / src / support.c
blob1a3fcbd32d6f6ff8e3caf214b9f67f4a8be2a08d
1 /*
2 * $Id$
4 * ROX-Filer, filer for the ROX desktop project
5 * Copyright (C) 2003, the ROX-Filer team.
7 * This program is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the Free
9 * Software Foundation; either version 2 of the License, or (at your option)
10 * any later version.
12 * This program is distributed in the hope that it will be useful, but WITHOUT
13 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 * more details.
17 * You should have received a copy of the GNU General Public License along with
18 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
19 * Place, Suite 330, Boston, MA 02111-1307 USA
22 /* support.c - (non-GUI) useful routines */
24 #include "config.h"
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <netdb.h>
29 #include <errno.h>
30 #include <ctype.h>
31 #include <sys/param.h>
32 #include <pwd.h>
33 #include <grp.h>
34 #include <fcntl.h>
35 #include <sys/wait.h>
36 #include <string.h>
37 #include <time.h>
38 #include <unistd.h>
39 #include <libxml/parser.h>
40 #include <math.h>
42 #include "global.h"
44 #include "choices.h"
45 #include "main.h"
46 #include "options.h"
47 #include "support.h"
48 #include "fscache.h"
49 #include "main.h"
50 #include "xml.h"
52 static GHashTable *uid_hash = NULL; /* UID -> User name */
53 static GHashTable *gid_hash = NULL; /* GID -> Group name */
55 /* Static prototypes */
56 static void MD5Transform(guint32 buf[4], guint32 const in[16]);
58 /****************************************************************
59 * EXTERNAL INTERFACE *
60 ****************************************************************/
62 /* g_object_unref() the result! */
63 XMLwrapper *xml_cache_load(const gchar *pathname)
65 static GFSCache *xml_cache = NULL;
67 if (!xml_cache)
68 xml_cache = g_fscache_new((GFSLoadFunc) xml_new, NULL, NULL);
69 return g_fscache_lookup(xml_cache, pathname);
72 /* Save doc as XML as filename, 0 on success or 1 on failure */
73 int save_xml_file(xmlDocPtr doc, const gchar *filename)
75 #if LIBXML_VERSION > 20400
76 if (xmlSaveFormatFileEnc(filename, doc, NULL, 1) < 0)
77 return 1;
78 #else
79 FILE *out;
81 out = fopen(filename, "w");
82 if (!out)
83 return 1;
85 xmlDocDump(out, doc); /* Some versions return void */
87 if (fclose(out))
88 return 1;
89 #endif
91 return 0;
94 /* Create a new SOAP message and return the document and the (empty)
95 * body node.
97 xmlDocPtr soap_new(xmlNodePtr *ret_body)
99 xmlDocPtr doc;
100 xmlNodePtr root;
101 xmlNs *env_ns;
103 doc = xmlNewDoc("1.0");
104 root = xmlNewDocNode(doc, NULL, "Envelope", NULL);
105 xmlDocSetRootElement(doc, root);
107 env_ns = xmlNewNs(root, SOAP_ENV_NS, "env");
108 xmlSetNs(root, env_ns);
110 *ret_body = xmlNewTextChild(root, env_ns, "Body", NULL);
111 xmlNewNs(*ret_body, ROX_NS, "rox");
113 return doc;
116 /* Like g_strdup, but does realpath() too (if possible) */
117 char *pathdup(const char *path)
119 char real[MAXPATHLEN];
121 g_return_val_if_fail(path != NULL, NULL);
123 if (realpath(path, real))
124 return g_strdup(real);
126 return g_strdup(path);
129 /* Join the path to the leaf (adding a / between them) and
130 * return a pointer to a static buffer with the result. Buffer is valid
131 * until the next call to make_path.
132 * The return value may be used as 'dir' for the next call.
134 const guchar *make_path(const char *dir, const char *leaf)
136 static GString *buffer = NULL;
138 if (!buffer)
139 buffer = g_string_new(NULL);
141 g_return_val_if_fail(dir != NULL, buffer->str);
142 g_return_val_if_fail(leaf != NULL, buffer->str);
144 if (buffer->str != dir)
145 g_string_assign(buffer, dir);
147 if (dir[0] != '/' || dir[1] != '\0')
148 g_string_append_c(buffer, '/'); /* For anything except "/" */
150 g_string_append(buffer, leaf);
152 return buffer->str;
155 /* Return our complete host name for DND */
156 const char *our_host_name_for_dnd(void)
158 if (o_dnd_no_hostnames.int_value)
159 return "";
160 return our_host_name();
163 /* Return our complete host name, unconditionally */
164 const char *our_host_name(void)
166 static char *name = NULL;
168 if (!name)
170 char buffer[4096];
172 if (gethostname(buffer, 4096) == 0)
174 /* gethostname doesn't always return the full name... */
175 struct hostent *ent;
177 buffer[4095] = '\0';
178 ent = gethostbyname(buffer);
179 name = g_strdup(ent ? ent->h_name : buffer);
181 else
183 g_warning("gethostname() failed - using localhost\n");
184 name = g_strdup("localhost");
188 return name;
191 void debug_free_string(void *data)
193 g_print("Freeing string '%s'\n", (char *) data);
194 g_free(data);
197 const char *user_name(uid_t uid)
199 const char *retval;
201 if (!uid_hash)
202 uid_hash = g_hash_table_new(NULL, NULL);
204 retval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(uid));
206 if (!retval)
208 struct passwd *passwd;
210 passwd = getpwuid(uid);
211 retval = passwd ? g_strdup(passwd->pw_name)
212 : g_strdup_printf("[%d]", (int) uid);
213 g_hash_table_insert(uid_hash, GINT_TO_POINTER(uid),
214 (gchar *) retval);
217 return retval;
220 const char *group_name(gid_t gid)
222 const char *retval;
224 if (!gid_hash)
225 gid_hash = g_hash_table_new(NULL, NULL);
227 retval = g_hash_table_lookup(gid_hash, GINT_TO_POINTER(gid));
229 if (!retval)
231 struct group *group;
233 group = getgrgid(gid);
234 retval = group ? g_strdup(group->gr_name)
235 : g_strdup_printf("[%d]", (int) gid);
236 g_hash_table_insert(gid_hash, GINT_TO_POINTER(gid),
237 (gchar *) retval);
240 return retval;
243 /* Return a string in the form '23 M' in a static buffer valid until
244 * the next call.
246 const char *format_size(off_t size)
248 static char *buffer = NULL;
249 const char *units;
251 if (size >= PRETTY_SIZE_LIMIT)
253 size += 1023;
254 size >>= 10;
255 if (size >= PRETTY_SIZE_LIMIT)
257 size += 1023;
258 size >>= 10;
259 if (size >= PRETTY_SIZE_LIMIT)
261 size += 1023;
262 size >>= 10;
263 units = "G";
265 else
266 units = "M";
268 else
269 units = "K";
271 else
272 units = _("B");
274 g_free(buffer);
275 buffer = g_strdup_printf("%" SIZE_FMT " %s", size, units);
277 return buffer;
280 /* Return a string in the form '23M' in a static buffer valid until
281 * the next call. Aligned to the right (5 chars).
283 const char *format_size_aligned(off_t size)
285 static char *buffer = NULL;
286 char units;
288 if (size >= PRETTY_SIZE_LIMIT)
290 size += 1023;
291 size >>= 10;
292 if (size >= PRETTY_SIZE_LIMIT)
294 size += 1023;
295 size >>= 10;
296 if (size >= PRETTY_SIZE_LIMIT)
298 size += 1023;
299 size >>= 10;
300 units = 'G';
302 else
303 units = 'M';
305 else
306 units = 'K';
308 else
309 units = ' ';
311 g_free(buffer);
312 buffer = g_strdup_printf("%4" SIZE_FMT "%c", size, units);
314 return buffer;
318 * Similar to format_size(), but this one uses a double argument since
319 * unsigned long isn't wide enough on all platforms and we must be able to
320 * sum sizes above 4 GB.
322 const gchar *format_double_size(double size)
324 static gchar *buf = NULL;
325 const char *units;
327 if (size >= PRETTY_SIZE_LIMIT)
329 size += 1023;
330 size /= 1024;
331 if (size >= PRETTY_SIZE_LIMIT)
333 size += 1023;
334 size /= 1024;
335 if (size >= PRETTY_SIZE_LIMIT)
337 size += 1023;
338 size /= 1024;
339 units = "G";
341 else
342 units = "M";
344 else
345 units = "K";
348 else if (size != 1)
349 units = _("bytes");
350 else
351 units = _("byte");
353 g_free(buf);
354 buf = g_strdup_printf("%.0f %s", floor(size), units);
356 return buf;
359 /* Fork and exec argv. Wait and return the child's exit status.
360 * -1 if spawn fails.
361 * Returns the error string from the command if any, or NULL on success.
362 * If the process returns a non-zero exit status without producing a message,
363 * a suitable message is created.
364 * g_free() the result.
366 char *fork_exec_wait(const char **argv)
368 int status;
369 gchar *errors = NULL;
370 GError *error = NULL;
372 if (!g_spawn_sync(NULL, (char **) argv, NULL,
373 G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL,
374 NULL, NULL,
375 NULL, &errors, &status, &error))
377 char *msg;
379 msg = g_strdup(error->message);
380 g_error_free(error);
381 return msg;
384 if (errors && !*errors)
385 null_g_free(&errors);
387 if (!WIFEXITED(status))
389 if (!errors)
390 errors = g_strdup("(Subprocess crashed?)");
392 else if (WEXITSTATUS(status))
394 if (!errors)
395 errors = g_strdup(_("ERROR"));
398 if (errors)
399 g_strstrip(errors);
401 return errors;
404 /* If a file has this UID and GID, which permissions apply to us?
405 * 0 = User, 1 = Group, 2 = World
407 gint applicable(uid_t uid, gid_t gid)
409 int i;
411 if (uid == euid)
412 return 0;
414 if (gid == egid)
415 return 1;
417 for (i = 0; i < ngroups; i++)
419 if (supplemental_groups[i] == gid)
420 return 1;
423 return 2;
426 /* Converts a file's mode to a string. Result is a pointer
427 * to a static buffer, valid until the next call.
429 const char *pretty_permissions(mode_t m)
431 static char buffer[] = "rwx,rwx,rwx/UG"
432 #ifdef S_ISVTX
434 #endif
437 buffer[0] = m & S_IRUSR ? 'r' : '-';
438 buffer[1] = m & S_IWUSR ? 'w' : '-';
439 buffer[2] = m & S_IXUSR ? 'x' : '-';
441 buffer[4] = m & S_IRGRP ? 'r' : '-';
442 buffer[5] = m & S_IWGRP ? 'w' : '-';
443 buffer[6] = m & S_IXGRP ? 'x' : '-';
445 buffer[8] = m & S_IROTH ? 'r' : '-';
446 buffer[9] = m & S_IWOTH ? 'w' : '-';
447 buffer[10] = m & S_IXOTH ? 'x' : '-';
449 buffer[12] = m & S_ISUID ? 'U' : '-';
450 buffer[13] = m & S_ISGID ? 'G' : '-';
451 #ifdef S_ISVTX
452 buffer[14] = m & S_ISVTX ? 'T' : '-';
453 #endif
455 return buffer;
458 /* Gets the canonical name for address and compares to our_host_name() */
459 static gboolean is_local_address(char *address)
461 struct hostent *ent;
463 ent = gethostbyname(address);
465 return strcmp(our_host_name(), ent ? ent->h_name : address) == 0;
468 /* Convert a URI to a local pathname (or NULL if it isn't local).
469 * The returned pointer needs to be passed to g_free() when done (if not NULL).
470 * THIS IS A CHANGE. The return path has been processed by unescape_uri().
471 * Possible formats:
472 * /path
473 * ///path
474 * //host/path
475 * file://host/path
477 char *get_local_path(const char *uri)
479 if (*uri == '/')
481 char *path, *uri_host;
483 if (uri[1] != '/')
484 return unescape_uri(uri); /* Just a local path - no host part */
486 path = strchr(uri + 2, '/');
487 if (!path)
488 return NULL; /* //something */
490 if (path - uri == 2)
491 return unescape_uri(path); /* ///path */
493 uri_host = g_strndup(uri + 2, path - uri - 2);
494 if (is_local_address(uri_host))
496 g_free(uri_host);
497 return unescape_uri(path); /* //myhost/path */
499 g_free(uri_host);
501 return NULL; /* From a different host */
503 else
505 if (strncasecmp(uri, "file:", 5))
506 return NULL; /* Don't know this format */
508 uri += 5;
510 if (*uri == '/')
511 return get_local_path(uri);
513 return NULL;
517 /* Set the close-on-exec flag for this FD.
518 * TRUE means that an exec()'d process will not get the FD.
520 void close_on_exec(int fd, gboolean close)
522 if (fcntl(fd, F_SETFD, close))
523 g_warning("fcntl() failed: %s\n", g_strerror(errno));
526 void set_blocking(int fd, gboolean blocking)
528 if (fcntl(fd, F_SETFL, blocking ? 0 : O_NONBLOCK))
529 g_warning("fcntl() failed: %s\n", g_strerror(errno));
532 /* Format this time nicely.
533 * g_free() the result.
535 char *pretty_time(const time_t *time)
537 char time_buf[32];
539 if (strftime(time_buf, sizeof(time_buf),
540 TIME_FORMAT, localtime(time)) == 0)
541 time_buf[0]= 0;
543 return to_utf8(time_buf);
546 #ifndef O_NOFOLLOW
547 # define O_NOFOLLOW 0x0
548 #endif
550 /* 'from' and 'to' are complete pathnames of files (not dirs or symlinks).
551 * This spawns 'cp' to do the copy if lstat() succeeds, otherwise we
552 * do the copy manually using vfs.
554 * Returns an error string, or NULL on success. g_free() the result.
556 * XXX: This was only used for libvfs...
558 guchar *copy_file(const guchar *from, const guchar *to)
560 const char *argv[] = {"cp", "-pRf", NULL, NULL, NULL};
562 argv[2] = from;
563 argv[3] = to;
565 return fork_exec_wait(argv);
568 /* 'word' has all special characters escaped so that it may be inserted
569 * into a shell command.
570 * Eg: 'My Dir?' becomes 'My\ Dir\?'. g_free() the result.
572 guchar *shell_escape(const guchar *word)
574 GString *tmp;
575 guchar *retval;
577 tmp = g_string_new(NULL);
579 while (*word)
581 if (strchr(" ?*['\"$~\\|();!`&", *word))
582 g_string_append_c(tmp, '\\');
583 g_string_append_c(tmp, *word);
584 word++;
587 retval = tmp->str;
588 g_string_free(tmp, FALSE);
589 return retval;
592 /* TRUE iff `sub' is (or would be) an object inside the directory `parent',
593 * (or the two are the same item/directory).
594 * FALSE if parent doesn't exist.
596 gboolean is_sub_dir(const char *sub_obj, const char *parent)
598 struct stat parent_info;
599 char *sub;
601 if (mc_lstat(parent, &parent_info))
602 return FALSE; /* Parent doesn't exist */
604 /* For checking Copy/Move operations do a realpath first on sub
605 * (the destination), since copying into a symlink is the same as
606 * copying into the thing it points to. Don't realpath 'parent' though;
607 * copying a symlink just makes a new symlink.
609 * When checking if an icon depends on a file (parent), use realpath on
610 * sub (the icon) too.
612 sub = pathdup(sub_obj);
614 while (1)
616 char *slash;
617 struct stat info;
619 if (mc_lstat(sub, &info) == 0)
621 if (info.st_dev == parent_info.st_dev &&
622 info.st_ino == parent_info.st_ino)
624 g_free(sub);
625 return TRUE;
629 slash = strrchr(sub, '/');
630 if (!slash)
631 break;
632 if (slash == sub)
634 if (sub[1])
635 sub[1] = '\0';
636 else
637 break;
639 else
640 *slash = '\0';
643 g_free(sub);
645 return FALSE;
648 /* True if the string 'list' contains 'item'.
649 * Eg ("close", "close, help") -> TRUE
651 gboolean in_list(const guchar *item, const guchar *list)
653 int len;
655 len = strlen(item);
657 while (*list)
659 if (strncmp(item, list, len) == 0 &&
660 !g_ascii_isalpha(list[len]))
661 return TRUE;
662 list = strchr(list, ',');
663 if (!list)
664 return FALSE;
665 while (g_ascii_isspace(*++list))
669 return FALSE;
672 /* Split a path into its components. Eg:
674 * /bob/fred -> ["bob", "fred"]
675 * ///a//b// -> ["a", "b"]
676 * / -> []
678 * The array and the strings in it must be freed after use.
680 GPtrArray *split_path(const guchar *path)
682 GPtrArray *array;
683 guchar *slash;
685 g_return_val_if_fail(path != NULL, NULL);
687 array = g_ptr_array_new();
689 while (1)
691 while (path[0] == '/')
692 path++;
693 if (path[0] == '\0')
694 break;
696 slash = strchr(path, '/');
697 if (slash)
699 g_ptr_array_add(array, g_strndup(path, slash - path));
700 path = slash + 1;
701 continue;
703 g_ptr_array_add(array, g_strdup(path));
704 break;
707 return array;
710 /* Return the shortest path from 'from' to 'to'.
711 * Eg: get_relative_path("/a/b/c", "a/d/e") -> "../d/e"
713 guchar *get_relative_path(const guchar *from, const guchar *to)
715 GString *path;
716 guchar *retval;
717 GPtrArray *src, *dst;
718 int i, j;
720 src = split_path(from);
721 dst = split_path(to);
723 /* The last component of src doesn't matter... */
724 if (src->len)
726 g_free(src->pdata[src->len - 1]);
727 g_ptr_array_remove_index(src, src->len - 1);
730 /* Strip off common path elements... */
731 i = 0;
732 while (i < src->len && i < dst->len)
734 guchar *a = (guchar *) src->pdata[i];
735 guchar *b = (guchar *) dst->pdata[i];
737 if (strcmp(a, b) != 0)
738 break;
739 i++;
742 /* Go up one dir for each element remaining in src */
743 path = g_string_new(NULL);
744 for (j = i; j < src->len; j++)
745 g_string_append(path, "../");
747 /* Go down one dir for each element remaining in dst */
748 for (j = i; j < dst->len; j++)
750 g_string_append(path, (guchar *) dst->pdata[j]);
751 g_string_append_c(path, '/');
754 if (path->str[path->len - 1] == '/')
755 g_string_truncate(path, path->len - 1);
756 if (path->len == 0)
757 g_string_assign(path, ".");
759 /* Free the arrays */
760 for (i = 0; i < src->len; i++)
761 g_free(src->pdata[i]);
762 g_ptr_array_free(src, TRUE);
763 for (i = 0; i < dst->len; i++)
764 g_free(dst->pdata[i]);
765 g_ptr_array_free(dst, TRUE);
767 retval = path->str;
768 g_string_free(path, FALSE);
770 return retval;
774 * Interperet text as a boolean value. Return defvalue if we don't
775 * recognise it
777 int text_to_boolean(const char *text, int defvalue)
779 if (g_strcasecmp(text, "true")==0)
780 return TRUE;
781 else if (g_strcasecmp(text, "false")==0)
782 return FALSE;
783 else if (g_strcasecmp(text, "yes")==0)
784 return TRUE;
785 else if (g_strcasecmp(text, "no")==0)
786 return FALSE;
787 else if (g_ascii_isdigit(text[0]))
788 return !!atoi(text);
790 return defvalue;
793 /* Return the pathname that this symlink points to.
794 * NULL on error (not a symlink, path too long) and errno set.
795 * g_free() the result.
797 char *readlink_dup(const char *source)
799 char path[MAXPATHLEN + 1];
800 int got;
802 got = readlink(source, path, MAXPATHLEN);
803 if (got < 0 || got > MAXPATHLEN)
804 return NULL;
806 return g_strndup(path, got);
810 * This code implements the MD5 message-digest algorithm.
811 * The algorithm is due to Ron Rivest. The original code was
812 * written by Colin Plumb in 1993, and put in the public domain.
814 * Modified to use glib datatypes. Put under GPL to simplify
815 * licensing for ROX-Filer. Taken from Debian's dpkg package.
818 #define md5byte unsigned char
820 typedef struct _MD5Context MD5Context;
822 struct _MD5Context {
823 guint32 buf[4];
824 guint32 bytes[2];
825 guint32 in[16];
828 #if G_BYTE_ORDER == G_BIG_ENDIAN
829 void byteSwap(guint32 *buf, unsigned words)
831 md5byte *p = (md5byte *)buf;
833 do {
834 *buf++ = (guint32)((unsigned)p[3] << 8 | p[2]) << 16 |
835 ((unsigned)p[1] << 8 | p[0]);
836 p += 4;
837 } while (--words);
839 #else
840 #define byteSwap(buf,words)
841 #endif
844 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
845 * initialization constants.
847 static void MD5Init(MD5Context *ctx)
849 ctx->buf[0] = 0x67452301;
850 ctx->buf[1] = 0xefcdab89;
851 ctx->buf[2] = 0x98badcfe;
852 ctx->buf[3] = 0x10325476;
854 ctx->bytes[0] = 0;
855 ctx->bytes[1] = 0;
859 * Update context to reflect the concatenation of another buffer full
860 * of bytes.
862 static void MD5Update(MD5Context *ctx, md5byte const *buf, unsigned len)
864 guint32 t;
866 /* Update byte count */
868 t = ctx->bytes[0];
869 if ((ctx->bytes[0] = t + len) < t)
870 ctx->bytes[1]++; /* Carry from low to high */
872 t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
873 if (t > len) {
874 memcpy((md5byte *)ctx->in + 64 - t, buf, len);
875 return;
877 /* First chunk is an odd size */
878 memcpy((md5byte *)ctx->in + 64 - t, buf, t);
879 byteSwap(ctx->in, 16);
880 MD5Transform(ctx->buf, ctx->in);
881 buf += t;
882 len -= t;
884 /* Process data in 64-byte chunks */
885 while (len >= 64) {
886 memcpy(ctx->in, buf, 64);
887 byteSwap(ctx->in, 16);
888 MD5Transform(ctx->buf, ctx->in);
889 buf += 64;
890 len -= 64;
893 /* Handle any remaining bytes of data. */
894 memcpy(ctx->in, buf, len);
898 * Final wrapup - pad to 64-byte boundary with the bit pattern
899 * 1 0* (64-bit count of bits processed, MSB-first)
900 * Returns the newly allocated string of the hash.
902 static char *MD5Final(MD5Context *ctx)
904 char *retval;
905 int i;
906 int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
907 md5byte *p = (md5byte *)ctx->in + count;
908 guint8 *bytes;
910 /* Set the first char of padding to 0x80. There is always room. */
911 *p++ = 0x80;
913 /* Bytes of padding needed to make 56 bytes (-8..55) */
914 count = 56 - 1 - count;
916 if (count < 0) { /* Padding forces an extra block */
917 memset(p, 0, count + 8);
918 byteSwap(ctx->in, 16);
919 MD5Transform(ctx->buf, ctx->in);
920 p = (md5byte *)ctx->in;
921 count = 56;
923 memset(p, 0, count);
924 byteSwap(ctx->in, 14);
926 /* Append length in bits and transform */
927 ctx->in[14] = ctx->bytes[0] << 3;
928 ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
929 MD5Transform(ctx->buf, ctx->in);
931 byteSwap(ctx->buf, 4);
933 retval = g_malloc(33);
934 bytes = (guint8 *) ctx->buf;
935 for (i = 0; i < 16; i++)
936 sprintf(retval + (i * 2), "%02x", bytes[i]);
937 retval[32] = '\0';
939 return retval;
942 # ifndef ASM_MD5
944 /* The four core functions - F1 is optimized somewhat */
946 /* #define F1(x, y, z) (x & y | ~x & z) */
947 #define F1(x, y, z) (z ^ (x & (y ^ z)))
948 #define F2(x, y, z) F1(z, x, y)
949 #define F3(x, y, z) (x ^ y ^ z)
950 #define F4(x, y, z) (y ^ (x | ~z))
952 /* This is the central step in the MD5 algorithm. */
953 #define MD5STEP(f,w,x,y,z,in,s) \
954 (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
957 * The core of the MD5 algorithm, this alters an existing MD5 hash to
958 * reflect the addition of 16 longwords of new data. MD5Update blocks
959 * the data and converts bytes into longwords for this routine.
961 static void MD5Transform(guint32 buf[4], guint32 const in[16])
963 register guint32 a, b, c, d;
965 a = buf[0];
966 b = buf[1];
967 c = buf[2];
968 d = buf[3];
970 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
971 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
972 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
973 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
974 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
975 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
976 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
977 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
978 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
979 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
980 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
981 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
982 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
983 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
984 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
985 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
987 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
988 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
989 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
990 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
991 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
992 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
993 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
994 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
995 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
996 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
997 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
998 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
999 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1000 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1001 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1002 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1004 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1005 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1006 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1007 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1008 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1009 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1010 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1011 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1012 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1013 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1014 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1015 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1016 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1017 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1018 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1019 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1021 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1022 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1023 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1024 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1025 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1026 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1027 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1028 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1029 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1030 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1031 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1032 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1033 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1034 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1035 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1036 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1038 buf[0] += a;
1039 buf[1] += b;
1040 buf[2] += c;
1041 buf[3] += d;
1044 # endif /* ASM_MD5 */
1046 char *md5_hash(const char *message)
1048 MD5Context ctx;
1050 MD5Init(&ctx);
1051 MD5Update(&ctx, message, strlen(message));
1052 return MD5Final(&ctx);
1055 /* Convert string 'src' from the current locale to UTF-8 */
1056 gchar *to_utf8(const gchar *src)
1058 gchar *retval;
1060 if (!src)
1061 return NULL;
1063 retval = g_locale_to_utf8(src, -1, NULL, NULL, NULL);
1064 if (!retval)
1065 retval = g_convert_with_fallback(src, -1, "utf-8", "iso-8859-1",
1066 "?", NULL, NULL, NULL);
1068 return retval ? retval : g_strdup(src);
1071 /* Ensure string at 'sp' is UTF-8. g_free() and replace by
1072 * UTF-8 version if not.
1074 void ensure_utf8(gchar **sp)
1076 gchar *s = *sp;
1078 if (!g_utf8_validate(s, -1, NULL))
1080 *sp = to_utf8(s);
1081 g_free(s);
1085 /* Removes trailing / chars and converts a leading '~/' (if any) to
1086 * the user's home dir. g_free() the result.
1088 gchar *expand_path(const gchar *path)
1090 guchar *retval;
1091 int path_len;
1093 g_return_val_if_fail(path != NULL, NULL);
1095 path_len = strlen(path);
1096 while (path_len > 1 && path[path_len - 1] == '/')
1097 path_len--;
1099 retval = g_strndup(path, path_len);
1101 if (path[0] == '~' && (path[1] == '\0' || path[1] == '/'))
1103 guchar *tmp = retval;
1105 retval = g_strconcat(home_dir, retval + 1, NULL);
1106 g_free(tmp);
1109 return retval;
1112 /* g_free() every element in the list, then free the list itself and
1113 * NULL the pointer to the list.
1115 void destroy_glist(GList **list)
1117 GList *l = *list;
1118 g_list_foreach(l, (GFunc) g_free, NULL);
1119 g_list_free(l);
1120 *list = NULL;
1123 void null_g_free(gpointer p)
1125 g_free(*(gpointer *)p);
1126 *(gpointer *)p = NULL;
1129 typedef struct _CollatePart CollatePart;
1131 struct _CollateKey {
1132 CollatePart *parts;
1133 gboolean caps;
1136 struct _CollatePart {
1137 guchar *text; /* NULL => end of list */
1138 long number;
1141 /* Break 'name' (a UTF-8 string) down into a list of (text, number) pairs.
1142 * The text parts processed for collating. This allows any two names to be
1143 * quickly compared later for intelligent sorting (comparing names is
1144 * speed-critical).
1146 CollateKey *collate_key_new(const guchar *name)
1148 const guchar *i;
1149 guchar *to_free = NULL;
1150 GArray *array;
1151 CollatePart new;
1152 CollateKey *retval;
1153 char *tmp;
1155 g_return_val_if_fail(name != NULL, NULL);
1157 array = g_array_new(FALSE, FALSE, sizeof(CollatePart));
1159 /* Ensure valid UTF-8 */
1160 if (!g_utf8_validate(name, -1, NULL))
1162 to_free = to_utf8(name);
1163 name = to_free;
1166 retval = g_new(CollateKey, 1);
1167 retval->caps = g_unichar_isupper(g_utf8_get_char(name));
1169 for (i = name; *i; i = g_utf8_next_char(i))
1171 /* We're in a (possibly blank) text section starting at 'name'.
1172 * Find the end of it (the next digit, or end of string).
1174 if (g_unichar_isdigit(g_utf8_get_char(i)))
1176 char *endp;
1178 /* i -> first digit character */
1179 tmp = g_utf8_strdown(name, i - name);
1180 new.text = g_utf8_collate_key(tmp, -1);
1181 g_free(tmp);
1182 new.number = strtol(i, &endp, 10);
1184 g_array_append_val(array, new);
1186 g_return_val_if_fail(endp > (char *) i, NULL);
1188 name = endp;
1189 i = name - 1;
1193 tmp = g_utf8_strdown(name, i - name);
1194 new.text = g_utf8_collate_key(tmp, -1);
1195 g_free(tmp);
1196 new.number = -1;
1197 g_array_append_val(array, new);
1199 new.text = NULL;
1200 g_array_append_val(array, new);
1202 retval->parts = (CollatePart *) array->data;
1203 g_array_free(array, FALSE);
1205 if (to_free)
1206 g_free(to_free); /* Only taken for invalid UTF-8 */
1208 return retval;
1211 void collate_key_free(CollateKey *key)
1213 CollatePart *part;
1215 for (part = key->parts; part->text; part++)
1216 g_free(part->text);
1217 g_free(key->parts);
1218 g_free(key);
1221 int collate_key_cmp(const CollateKey *key1, const CollateKey *key2,
1222 gboolean caps_first)
1224 CollatePart *n1 = key1->parts;
1225 CollatePart *n2 = key2->parts;
1226 int r;
1228 if (caps_first)
1230 if (key1->caps && !key2->caps)
1231 return -1;
1232 else if (key2->caps && !key1->caps)
1233 return 1;
1236 while (1)
1238 if (!n1->text)
1239 return n2->text ? -1 : 0;
1240 if (!n2->text)
1241 return 1;
1242 r = strcmp(n1->text, n2->text);
1243 if (r)
1244 return r;
1246 if (n1->number < n2->number)
1247 return -1;
1248 if (n1->number > n2->number)
1249 return 1;
1251 n1++;
1252 n2++;
1256 /* Returns TRUE if the object exists, FALSE if it doesn't.
1257 * For symlinks, the file pointed to must exist.
1259 gboolean file_exists(const char *path)
1261 struct stat info;
1263 return !mc_stat(path, &info);
1266 /* Escape path for future use in URI */
1267 gchar *escape_uri_path(const char *path)
1269 const char *safe = "-_./"; /* Plus isalnum() */
1270 const guchar *s;
1271 gchar *ans;
1272 GString *str;
1274 str = g_string_sized_new(strlen(path));
1276 for (s = path; *s; s++)
1278 if (!g_ascii_isalnum(*s) && !strchr(safe, *s))
1279 g_string_append_printf(str, "%%%02x", *s);
1280 else
1281 str = g_string_append_c(str, *s);
1284 ans = str->str;
1285 g_string_free(str, FALSE);
1287 return ans;
1290 gchar *encode_path_as_uri(const guchar *path)
1292 gchar *tpath = escape_uri_path(path);
1293 gchar *uri;
1295 uri = g_strconcat("file://", our_host_name_for_dnd(), tpath, NULL);
1296 g_free(tpath);
1298 return uri;
1301 gchar *unescape_uri(const char *uri)
1303 const gchar *s;
1304 gchar *d;
1305 gchar *tmp;
1307 tmp = g_malloc(strlen(uri) + 1);
1308 for (s = uri, d = tmp; *s; s++, d++)
1310 /*printf("%s\n", s);*/
1311 if (*s == '%' && g_ascii_isxdigit(s[1]) &&
1312 g_ascii_isxdigit(s[2]))
1314 int c;
1315 char buf[3];
1316 buf[0] = s[1];
1317 buf[1] = s[2];
1318 buf[2] = 0;
1319 c = (int) strtol(buf, NULL, 16);
1320 *d = c;
1321 s += 2;
1323 else
1324 *d = *s;
1326 *d = '\0';
1328 return tmp;
1331 /* Used as the sort function for sorting GPtrArrays */
1332 gint strcmp2(gconstpointer a, gconstpointer b)
1334 const char *aa = *(char **) a;
1335 const char *bb = *(char **) b;
1337 return g_strcasecmp(aa, bb);
1340 /* Returns an array listing all the names in the directory 'path'.
1341 * The array is sorted.
1342 * '.' and '..' are skipped.
1343 * On error, the error is reported with g_warning and NULL is returned.
1345 GPtrArray *list_dir(const guchar *path)
1347 GDir *dir;
1348 GError *error = NULL;
1349 const char *leaf;
1350 GPtrArray *names;
1352 dir = g_dir_open(path, 0, &error);
1353 if (error)
1355 g_warning("Can't list directory:\n%s", error->message);
1356 g_error_free(error);
1357 return NULL;
1360 names = g_ptr_array_new();
1362 while ((leaf = g_dir_read_name(dir))) {
1363 if (leaf[0] != '.')
1364 g_ptr_array_add(names, g_strdup(leaf));
1367 g_dir_close(dir);
1369 g_ptr_array_sort(names, strcmp2);
1371 return names;
1374 int stat_with_timeout(const char *path, struct stat *info)
1376 int status;
1377 pid_t child;
1378 gboolean retval;
1380 child = fork();
1381 if (child < 0)
1383 g_warning("stat_with_timeout: fork(): %s", g_strerror(errno));
1384 return -1;
1387 if (child == 0)
1389 /* Child */
1390 alarm(3);
1391 _exit(mc_stat(path, info) ? 1 : 0);
1394 waitpid(child, &status, 0);
1396 if (status == 0)
1397 retval = mc_stat(path, info);
1398 else
1399 retval = -1;
1401 return retval;