r2180: Code tidying (Bernard Jungen).
[rox-filer.git] / ROX-Filer / src / support.c
blob67929d7eea1c35d854ceada77007d0cf44bbc24c
1 /*
2 * $Id$
4 * ROX-Filer, filer for the ROX desktop project
5 * Copyright (C) 2002, 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 "my_vfs.h"
49 #include "fscache.h"
50 #include "main.h"
51 #include "xml.h"
53 static GHashTable *uid_hash = NULL; /* UID -> User name */
54 static GHashTable *gid_hash = NULL; /* GID -> Group name */
56 /* Static prototypes */
57 static void MD5Transform(guint32 buf[4], guint32 const in[16]);
59 /****************************************************************
60 * EXTERNAL INTERFACE *
61 ****************************************************************/
63 /* g_object_unref() the result! */
64 XMLwrapper *xml_cache_load(const gchar *pathname)
66 static GFSCache *xml_cache = NULL;
68 if (!xml_cache)
69 xml_cache = g_fscache_new((GFSLoadFunc) xml_new, NULL, NULL);
70 return g_fscache_lookup(xml_cache, pathname);
73 /* Save doc as XML as filename, 0 on success or 1 on failure */
74 int save_xml_file(xmlDocPtr doc, const gchar *filename)
76 #if LIBXML_VERSION > 20400
77 if (xmlSaveFormatFileEnc(filename, doc, NULL, 1) < 0)
78 return 1;
79 #else
80 FILE *out;
82 out = fopen(filename, "w");
83 if (!out)
84 return 1;
86 xmlDocDump(out, doc); /* Some versions return void */
88 if (fclose(out))
89 return 1;
90 #endif
92 return 0;
95 /* Create a new SOAP message and return the document and the (empty)
96 * body node.
98 xmlDocPtr soap_new(xmlNodePtr *ret_body)
100 xmlDocPtr doc;
101 xmlNodePtr root;
102 xmlNs *env_ns;
104 doc = xmlNewDoc("1.0");
105 root = xmlNewDocNode(doc, NULL, "Envelope", NULL);
106 xmlDocSetRootElement(doc, root);
108 env_ns = xmlNewNs(root, SOAP_ENV_NS, "env");
109 xmlSetNs(root, env_ns);
111 *ret_body = xmlNewTextChild(root, env_ns, "Body", NULL);
112 xmlNewNs(*ret_body, ROX_NS, "rox");
114 return doc;
117 /* Like g_strdup, but does realpath() too (if possible) */
118 char *pathdup(const char *path)
120 char real[MAXPATHLEN];
122 g_return_val_if_fail(path != NULL, NULL);
124 if (realpath(path, real))
125 return g_strdup(real);
127 return g_strdup(path);
130 /* Join the path to the leaf (adding a / between them) and
131 * return a pointer to a static buffer with the result. Buffer is valid
132 * until the next call to make_path.
133 * The return value may be used as 'dir' for the next call.
135 const guchar *make_path(const char *dir, const char *leaf)
137 static GString *buffer = NULL;
139 if (!buffer)
140 buffer = g_string_new(NULL);
142 g_return_val_if_fail(dir != NULL, buffer->str);
143 g_return_val_if_fail(leaf != NULL, buffer->str);
145 if (buffer->str != dir)
146 g_string_assign(buffer, dir);
148 if (dir[0] != '/' || dir[1] != '\0')
149 g_string_append_c(buffer, '/'); /* For anything except "/" */
151 g_string_append(buffer, leaf);
153 return buffer->str;
156 /* Return our complete host name for DND */
157 const char *our_host_name_for_dnd(void)
159 if (o_dnd_no_hostnames.int_value)
160 return "";
161 return our_host_name();
164 /* Return our complete host name, unconditionally */
165 const char *our_host_name(void)
167 static char *name = NULL;
169 if (!name)
171 char buffer[4096];
173 if (gethostname(buffer, 4096) == 0)
175 /* gethostname doesn't always return the full name... */
176 struct hostent *ent;
178 buffer[4095] = '\0';
179 ent = gethostbyname(buffer);
180 name = g_strdup(ent ? ent->h_name : buffer);
182 else
184 g_warning("gethostname() failed - using localhost\n");
185 name = g_strdup("localhost");
189 return name;
192 void debug_free_string(void *data)
194 g_print("Freeing string '%s'\n", (char *) data);
195 g_free(data);
198 const char *user_name(uid_t uid)
200 const char *retval;
202 if (!uid_hash)
203 uid_hash = g_hash_table_new(NULL, NULL);
205 retval = g_hash_table_lookup(uid_hash, GINT_TO_POINTER(uid));
207 if (!retval)
209 struct passwd *passwd;
211 passwd = getpwuid(uid);
212 retval = passwd ? g_strdup(passwd->pw_name)
213 : g_strdup_printf("[%d]", (int) uid);
214 g_hash_table_insert(uid_hash, GINT_TO_POINTER(uid),
215 (gchar *) retval);
218 return retval;
221 const char *group_name(gid_t gid)
223 const char *retval;
225 if (!gid_hash)
226 gid_hash = g_hash_table_new(NULL, NULL);
228 retval = g_hash_table_lookup(gid_hash, GINT_TO_POINTER(gid));
230 if (!retval)
232 struct group *group;
234 group = getgrgid(gid);
235 retval = group ? g_strdup(group->gr_name)
236 : g_strdup_printf("[%d]", (int) gid);
237 g_hash_table_insert(gid_hash, GINT_TO_POINTER(gid),
238 (gchar *) retval);
241 return retval;
244 /* Return a string in the form '23Mb' in a static buffer valid until
245 * the next call.
247 const char *format_size(off_t size)
249 static char *buffer = NULL;
250 const char *units;
252 if (size >= PRETTY_SIZE_LIMIT)
254 size += 1023;
255 size >>= 10;
256 if (size >= PRETTY_SIZE_LIMIT)
258 size += 1023;
259 size >>= 10;
260 if (size >= PRETTY_SIZE_LIMIT)
262 size += 1023;
263 size >>= 10;
264 units = "G";
266 else
267 units = "M";
269 else
270 units = "K";
272 else if (size == 1)
273 units = _("byte");
274 else
275 units = _("bytes");
277 g_free(buffer);
278 buffer = g_strdup_printf("%" SIZE_FMT " %s", size, units);
280 return buffer;
283 /* Return a string in the form '23M' in a static buffer valid until
284 * the next call. Aligned to the right (5 chars).
286 const char *format_size_aligned(off_t size)
288 static char *buffer = NULL;
289 char units;
291 if (size >= PRETTY_SIZE_LIMIT)
293 size += 1023;
294 size >>= 10;
295 if (size >= PRETTY_SIZE_LIMIT)
297 size += 1023;
298 size >>= 10;
299 if (size >= PRETTY_SIZE_LIMIT)
301 size += 1023;
302 size >>= 10;
303 units = 'G';
305 else
306 units = 'M';
308 else
309 units = 'K';
311 else
312 units = ' ';
314 g_free(buffer);
315 buffer = g_strdup_printf("%4" SIZE_FMT "%c", size, units);
317 return buffer;
321 * Similar to format_size(), but this one uses a double argument since
322 * unsigned long isn't wide enough on all platforms and we must be able to
323 * sum sizes above 4 GB.
325 const gchar *format_double_size(double size)
327 static gchar *buf = NULL;
328 const char *units;
330 if (size >= PRETTY_SIZE_LIMIT)
332 size += 1023;
333 size /= 1024;
334 if (size >= PRETTY_SIZE_LIMIT)
336 size += 1023;
337 size /= 1024;
338 if (size >= PRETTY_SIZE_LIMIT)
340 size += 1023;
341 size /= 1024;
342 units = "G";
344 else
345 units = "M";
347 else
348 units = "K";
351 else if (size != 1)
352 units = _("bytes");
353 else
354 units = _("byte");
356 g_free(buf);
357 buf = g_strdup_printf("%.0f %s", floor(size), units);
359 return buf;
362 /* Fork and exec argv. Wait and return the child's exit status.
363 * -1 if spawn fails.
364 * Returns the error string from the command if any, or NULL on success.
365 * If the process returns a non-zero exit status without producing a message,
366 * a suitable message is created.
367 * g_free() the result.
369 char *fork_exec_wait(const char **argv)
371 int status;
372 gchar *errors = NULL;
373 GError *error = NULL;
375 if (!g_spawn_sync(NULL, (char **) argv, NULL,
376 G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL,
377 NULL, NULL,
378 NULL, &errors, &status, &error))
380 char *msg;
382 msg = g_strdup(error->message);
383 g_error_free(error);
384 return msg;
387 if (errors && !*errors)
388 null_g_free(&errors);
390 if (!WIFEXITED(status))
392 if (!errors)
393 errors = g_strdup("(Subprocess crashed?)");
395 else if (WEXITSTATUS(status))
397 if (!errors)
398 errors = g_strdup(_("ERROR"));
401 if (errors)
402 g_strstrip(errors);
404 return errors;
407 /* If a file has this UID and GID, which permissions apply to us?
408 * 0 = User, 1 = Group, 2 = World
410 gint applicable(uid_t uid, gid_t gid)
412 int i;
414 if (uid == euid)
415 return 0;
417 if (gid == egid)
418 return 1;
420 for (i = 0; i < ngroups; i++)
422 if (supplemental_groups[i] == gid)
423 return 1;
426 return 2;
429 /* Converts a file's mode to a string. Result is a pointer
430 * to a static buffer, valid until the next call.
432 const char *pretty_permissions(mode_t m)
434 static char buffer[] = "rwx,rwx,rwx/UG"
435 #ifdef S_ISVTX
437 #endif
440 buffer[0] = m & S_IRUSR ? 'r' : '-';
441 buffer[1] = m & S_IWUSR ? 'w' : '-';
442 buffer[2] = m & S_IXUSR ? 'x' : '-';
444 buffer[4] = m & S_IRGRP ? 'r' : '-';
445 buffer[5] = m & S_IWGRP ? 'w' : '-';
446 buffer[6] = m & S_IXGRP ? 'x' : '-';
448 buffer[8] = m & S_IROTH ? 'r' : '-';
449 buffer[9] = m & S_IWOTH ? 'w' : '-';
450 buffer[10] = m & S_IXOTH ? 'x' : '-';
452 buffer[12] = m & S_ISUID ? 'U' : '-';
453 buffer[13] = m & S_ISGID ? 'G' : '-';
454 #ifdef S_ISVTX
455 buffer[14] = m & S_ISVTX ? 'T' : '-';
456 #endif
458 return buffer;
461 /* Gets the canonical name for address and compares to our_host_name() */
462 static gboolean is_local_address(char *address)
464 struct hostent *ent;
466 ent = gethostbyname(address);
468 return strcmp(our_host_name(), ent ? ent->h_name : address) == 0;
471 /* Convert a URI to a local pathname (or NULL if it isn't local).
472 * The returned pointer points inside the input string.
473 * Possible formats:
474 * /path
475 * ///path
476 * //host/path
477 * file://host/path
479 const char *get_local_path(const char *uri)
481 if (*uri == '/')
483 char *path, *uri_host;
485 if (uri[1] != '/')
486 return uri; /* Just a local path - no host part */
488 path = strchr(uri + 2, '/');
489 if (!path)
490 return NULL; /* //something */
492 if (path - uri == 2)
493 return path; /* ///path */
495 uri_host = g_strndup(uri + 2, path - uri - 2);
496 if (is_local_address(uri_host))
498 g_free(uri_host);
499 return path; /* //myhost/path */
501 g_free(uri_host);
503 return NULL; /* From a different host */
505 else
507 if (strncasecmp(uri, "file:", 5))
508 return NULL; /* Don't know this format */
510 uri += 5;
512 if (*uri == '/')
513 return get_local_path(uri);
515 return NULL;
519 /* Set the close-on-exec flag for this FD.
520 * TRUE means that an exec()'d process will not get the FD.
522 void close_on_exec(int fd, gboolean close)
524 if (fcntl(fd, F_SETFD, close))
525 g_warning("fcntl() failed: %s\n", g_strerror(errno));
528 void set_blocking(int fd, gboolean blocking)
530 if (fcntl(fd, F_SETFL, blocking ? 0 : O_NONBLOCK))
531 g_warning("fcntl() failed: %s\n", g_strerror(errno));
534 /* Format this time nicely.
535 * g_free() the result.
537 char *pretty_time(const time_t *time)
539 char time_buf[32];
541 if (strftime(time_buf, sizeof(time_buf),
542 TIME_FORMAT, localtime(time)) == 0)
543 time_buf[0]= 0;
545 return to_utf8(time_buf);
548 #ifndef O_NOFOLLOW
549 # define O_NOFOLLOW 0x0
550 #endif
552 /* 'from' and 'to' are complete pathnames of files (not dirs or symlinks).
553 * This spawns 'cp' to do the copy if lstat() succeeds, otherwise we
554 * do the copy manually using vfs.
556 * Returns an error string, or NULL on success. g_free() the result.
558 * XXX: This was only used for libvfs...
560 guchar *copy_file(const guchar *from, const guchar *to)
562 const char *argv[] = {"cp", "-pRf", NULL, NULL, NULL};
564 argv[2] = from;
565 argv[3] = to;
567 return fork_exec_wait(argv);
570 /* 'word' has all special characters escaped so that it may be inserted
571 * into a shell command.
572 * Eg: 'My Dir?' becomes 'My\ Dir\?'. g_free() the result.
574 guchar *shell_escape(const guchar *word)
576 GString *tmp;
577 guchar *retval;
579 tmp = g_string_new(NULL);
581 while (*word)
583 if (strchr(" ?*['\"$~\\|();!`&", *word))
584 g_string_append_c(tmp, '\\');
585 g_string_append_c(tmp, *word);
586 word++;
589 retval = tmp->str;
590 g_string_free(tmp, FALSE);
591 return retval;
594 /* TRUE iff `sub' is (or would be) an object inside the directory `parent',
595 * (or the two are the same item/directory).
596 * FALSE if parent doesn't exist.
598 gboolean is_sub_dir(const char *sub_obj, const char *parent)
600 struct stat parent_info;
601 char *sub;
603 if (mc_lstat(parent, &parent_info))
604 return FALSE; /* Parent doesn't exist */
606 /* For checking Copy/Move operations do a realpath first on sub
607 * (the destination), since copying into a symlink is the same as
608 * copying into the thing it points to. Don't realpath 'parent' though;
609 * copying a symlink just makes a new symlink.
611 * When checking if an icon depends on a file (parent), use realpath on
612 * sub (the icon) too.
614 sub = pathdup(sub_obj);
616 while (1)
618 char *slash;
619 struct stat info;
621 if (mc_lstat(sub, &info) == 0)
623 if (info.st_dev == parent_info.st_dev &&
624 info.st_ino == parent_info.st_ino)
626 g_free(sub);
627 return TRUE;
631 slash = strrchr(sub, '/');
632 if (!slash)
633 break;
634 if (slash == sub)
636 if (sub[1])
637 sub[1] = '\0';
638 else
639 break;
641 else
642 *slash = '\0';
645 g_free(sub);
647 return FALSE;
650 /* True if the string 'list' contains 'item'.
651 * Eg ("close", "close, help") -> TRUE
653 gboolean in_list(const guchar *item, const guchar *list)
655 int len;
657 len = strlen(item);
659 while (*list)
661 if (strncmp(item, list, len) == 0 && !isalpha(list[len]))
662 return TRUE;
663 list = strchr(list, ',');
664 if (!list)
665 return FALSE;
666 while (isspace(*++list))
670 return FALSE;
673 /* Split a path into its components. Eg:
675 * /bob/fred -> ["bob", "fred"]
676 * ///a//b// -> ["a", "b"]
677 * / -> []
679 * The array and the strings in it must be freed after use.
681 GPtrArray *split_path(const guchar *path)
683 GPtrArray *array;
684 guchar *slash;
686 g_return_val_if_fail(path != NULL, NULL);
688 array = g_ptr_array_new();
690 while (1)
692 while (path[0] == '/')
693 path++;
694 if (path[0] == '\0')
695 break;
697 slash = strchr(path, '/');
698 if (slash)
700 g_ptr_array_add(array, g_strndup(path, slash - path));
701 path = slash + 1;
702 continue;
704 g_ptr_array_add(array, g_strdup(path));
705 break;
708 return array;
711 /* Return the shortest path from 'from' to 'to'.
712 * Eg: get_relative_path("/a/b/c", "a/d/e") -> "../d/e"
714 guchar *get_relative_path(const guchar *from, const guchar *to)
716 GString *path;
717 guchar *retval;
718 GPtrArray *src, *dst;
719 int i, j;
721 src = split_path(from);
722 dst = split_path(to);
724 /* The last component of src doesn't matter... */
725 if (src->len)
727 g_free(src->pdata[src->len - 1]);
728 g_ptr_array_remove_index(src, src->len - 1);
731 /* Strip off common path elements... */
732 i = 0;
733 while (i < src->len && i < dst->len)
735 guchar *a = (guchar *) src->pdata[i];
736 guchar *b = (guchar *) dst->pdata[i];
738 if (strcmp(a, b) != 0)
739 break;
740 i++;
743 /* Go up one dir for each element remaining in src */
744 path = g_string_new(NULL);
745 for (j = i; j < src->len; j++)
746 g_string_append(path, "../");
748 /* Go down one dir for each element remaining in dst */
749 for (j = i; j < dst->len; j++)
751 g_string_append(path, (guchar *) dst->pdata[j]);
752 g_string_append_c(path, '/');
755 if (path->str[path->len - 1] == '/')
756 g_string_truncate(path, path->len - 1);
757 if (path->len == 0)
758 g_string_assign(path, ".");
760 /* Free the arrays */
761 for (i = 0; i < src->len; i++)
762 g_free(src->pdata[i]);
763 g_ptr_array_free(src, TRUE);
764 for (i = 0; i < dst->len; i++)
765 g_free(dst->pdata[i]);
766 g_ptr_array_free(dst, TRUE);
768 retval = path->str;
769 g_string_free(path, FALSE);
771 return retval;
775 * Interperet text as a boolean value. Return defvalue if we don't
776 * recognise it
778 int text_to_boolean(const char *text, int defvalue)
780 if (g_strcasecmp(text, "true")==0)
781 return TRUE;
782 else if (g_strcasecmp(text, "false")==0)
783 return FALSE;
784 else if (g_strcasecmp(text, "yes")==0)
785 return TRUE;
786 else if (g_strcasecmp(text, "no")==0)
787 return FALSE;
788 else if (isdigit(text[0]))
789 return !!atoi(text);
791 return defvalue;
794 /* Return the pathname that this symlink points to.
795 * NULL on error (not a symlink, path too long) and errno set.
796 * g_free() the result.
798 char *readlink_dup(const char *source)
800 char path[MAXPATHLEN + 1];
801 int got;
803 got = readlink(source, path, MAXPATHLEN);
804 if (got < 0 || got > MAXPATHLEN)
805 return NULL;
807 return g_strndup(path, got);
811 * This code implements the MD5 message-digest algorithm.
812 * The algorithm is due to Ron Rivest. The original code was
813 * written by Colin Plumb in 1993, and put in the public domain.
815 * Modified to use glib datatypes. Put under GPL to simplify
816 * licensing for ROX-Filer. Taken from Debian's dpkg package.
819 #define md5byte unsigned char
821 typedef struct _MD5Context MD5Context;
823 struct _MD5Context {
824 guint32 buf[4];
825 guint32 bytes[2];
826 guint32 in[16];
829 #if G_BYTE_ORDER == G_BIG_ENDIAN
830 void byteSwap(guint32 *buf, unsigned words)
832 md5byte *p = (md5byte *)buf;
834 do {
835 *buf++ = (guint32)((unsigned)p[3] << 8 | p[2]) << 16 |
836 ((unsigned)p[1] << 8 | p[0]);
837 p += 4;
838 } while (--words);
840 #else
841 #define byteSwap(buf,words)
842 #endif
845 * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
846 * initialization constants.
848 static void MD5Init(MD5Context *ctx)
850 ctx->buf[0] = 0x67452301;
851 ctx->buf[1] = 0xefcdab89;
852 ctx->buf[2] = 0x98badcfe;
853 ctx->buf[3] = 0x10325476;
855 ctx->bytes[0] = 0;
856 ctx->bytes[1] = 0;
860 * Update context to reflect the concatenation of another buffer full
861 * of bytes.
863 static void MD5Update(MD5Context *ctx, md5byte const *buf, unsigned len)
865 guint32 t;
867 /* Update byte count */
869 t = ctx->bytes[0];
870 if ((ctx->bytes[0] = t + len) < t)
871 ctx->bytes[1]++; /* Carry from low to high */
873 t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
874 if (t > len) {
875 memcpy((md5byte *)ctx->in + 64 - t, buf, len);
876 return;
878 /* First chunk is an odd size */
879 memcpy((md5byte *)ctx->in + 64 - t, buf, t);
880 byteSwap(ctx->in, 16);
881 MD5Transform(ctx->buf, ctx->in);
882 buf += t;
883 len -= t;
885 /* Process data in 64-byte chunks */
886 while (len >= 64) {
887 memcpy(ctx->in, buf, 64);
888 byteSwap(ctx->in, 16);
889 MD5Transform(ctx->buf, ctx->in);
890 buf += 64;
891 len -= 64;
894 /* Handle any remaining bytes of data. */
895 memcpy(ctx->in, buf, len);
899 * Final wrapup - pad to 64-byte boundary with the bit pattern
900 * 1 0* (64-bit count of bits processed, MSB-first)
901 * Returns the newly allocated string of the hash.
903 static char *MD5Final(MD5Context *ctx)
905 char *retval;
906 int i;
907 int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
908 md5byte *p = (md5byte *)ctx->in + count;
909 guint8 *bytes;
911 /* Set the first char of padding to 0x80. There is always room. */
912 *p++ = 0x80;
914 /* Bytes of padding needed to make 56 bytes (-8..55) */
915 count = 56 - 1 - count;
917 if (count < 0) { /* Padding forces an extra block */
918 memset(p, 0, count + 8);
919 byteSwap(ctx->in, 16);
920 MD5Transform(ctx->buf, ctx->in);
921 p = (md5byte *)ctx->in;
922 count = 56;
924 memset(p, 0, count);
925 byteSwap(ctx->in, 14);
927 /* Append length in bits and transform */
928 ctx->in[14] = ctx->bytes[0] << 3;
929 ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
930 MD5Transform(ctx->buf, ctx->in);
932 byteSwap(ctx->buf, 4);
934 retval = g_malloc(33);
935 bytes = (guint8 *) ctx->buf;
936 for (i = 0; i < 16; i++)
937 sprintf(retval + (i * 2), "%02x", bytes[i]);
938 retval[32] = '\0';
940 return retval;
943 # ifndef ASM_MD5
945 /* The four core functions - F1 is optimized somewhat */
947 /* #define F1(x, y, z) (x & y | ~x & z) */
948 #define F1(x, y, z) (z ^ (x & (y ^ z)))
949 #define F2(x, y, z) F1(z, x, y)
950 #define F3(x, y, z) (x ^ y ^ z)
951 #define F4(x, y, z) (y ^ (x | ~z))
953 /* This is the central step in the MD5 algorithm. */
954 #define MD5STEP(f,w,x,y,z,in,s) \
955 (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
958 * The core of the MD5 algorithm, this alters an existing MD5 hash to
959 * reflect the addition of 16 longwords of new data. MD5Update blocks
960 * the data and converts bytes into longwords for this routine.
962 static void MD5Transform(guint32 buf[4], guint32 const in[16])
964 register guint32 a, b, c, d;
966 a = buf[0];
967 b = buf[1];
968 c = buf[2];
969 d = buf[3];
971 MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
972 MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
973 MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
974 MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
975 MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
976 MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
977 MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
978 MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
979 MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
980 MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
981 MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
982 MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
983 MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
984 MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
985 MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
986 MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
988 MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
989 MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
990 MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
991 MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
992 MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
993 MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
994 MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
995 MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
996 MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
997 MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
998 MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
999 MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
1000 MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
1001 MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
1002 MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
1003 MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
1005 MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
1006 MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
1007 MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
1008 MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
1009 MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
1010 MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
1011 MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
1012 MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
1013 MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
1014 MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
1015 MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
1016 MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
1017 MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
1018 MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
1019 MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
1020 MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
1022 MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
1023 MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
1024 MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
1025 MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
1026 MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
1027 MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
1028 MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
1029 MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
1030 MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
1031 MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
1032 MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
1033 MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
1034 MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
1035 MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
1036 MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
1037 MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
1039 buf[0] += a;
1040 buf[1] += b;
1041 buf[2] += c;
1042 buf[3] += d;
1045 # endif /* ASM_MD5 */
1047 char *md5_hash(const char *message)
1049 MD5Context ctx;
1051 MD5Init(&ctx);
1052 MD5Update(&ctx, message, strlen(message));
1053 return MD5Final(&ctx);
1056 /* Convert string 'src' from the current locale to UTF-8 */
1057 gchar *to_utf8(const gchar *src)
1059 gchar *retval;
1061 if (!src)
1062 return NULL;
1064 retval = g_locale_to_utf8(src, -1, NULL, NULL, NULL);
1066 return retval ? retval : g_strdup(src);
1069 /* Ensure string at 'sp' is UTF-8. g_free() and replace by
1070 * UTF-8 version if not.
1072 void ensure_utf8(gchar **sp)
1074 gchar *s = *sp;
1076 if (!g_utf8_validate(s, -1, NULL))
1078 *sp = to_utf8(s);
1079 g_free(s);
1083 /* Removes trailing / chars and converts a leading '~/' (if any) to
1084 * the user's home dir. g_free() the result.
1086 gchar *expand_path(const gchar *path)
1088 guchar *retval;
1089 int path_len;
1091 g_return_val_if_fail(path != NULL, NULL);
1093 path_len = strlen(path);
1094 while (path_len > 1 && path[path_len - 1] == '/')
1095 path_len--;
1097 retval = g_strndup(path, path_len);
1099 if (path[0] == '~' && (path[1] == '\0' || path[1] == '/'))
1101 guchar *tmp = retval;
1103 retval = g_strconcat(home_dir, retval + 1, NULL);
1104 g_free(tmp);
1107 return retval;
1110 /* g_free() every element in the list, then free the list itself and
1111 * NULL the pointer to the list.
1113 void destroy_glist(GList **list)
1115 GList *l = *list;
1116 g_list_foreach(l, (GFunc) g_free, NULL);
1117 g_list_free(l);
1118 *list = NULL;
1121 void null_g_free(gpointer p)
1123 g_free(*(gpointer *)p);
1124 *(gpointer *)p = NULL;
1127 struct _CollateKey {
1128 guchar *text; /* NULL => end of list */
1129 long number;
1132 /* Break 'name' (a UTF-8 string) down into a list of (text, number) pairs.
1133 * The text parts processed for collating. This allows any two names to be
1134 * quickly compared later for intelligent sorting (comparing names is
1135 * speed-critical).
1137 CollateKey *collate_key_new(const guchar *name)
1139 const guchar *i;
1140 guchar *to_free = NULL;
1141 GArray *array;
1142 CollateKey new;
1143 CollateKey *retval;
1145 g_return_val_if_fail(name != NULL, NULL);
1147 array = g_array_new(FALSE, FALSE, sizeof(CollateKey));
1149 /* Ensure valid UTF-8 */
1150 if (!g_utf8_validate(name, -1, NULL))
1152 to_free = to_utf8(name);
1153 name = to_free;
1156 for (i = name; *i; i = g_utf8_next_char(i))
1158 /* We're in a (possibly blank) text section starting at 'name'.
1159 * Find the end of it (the next digit, or end of string).
1161 if (g_unichar_isdigit(g_utf8_get_char(i)))
1163 guchar *endp;
1165 /* i -> first digit character */
1166 new.text = g_utf8_collate_key(name, i - name);
1167 new.number = strtol(i, (char **) &endp, 10);
1169 g_array_append_val(array, new);
1171 g_return_val_if_fail(endp > i, NULL);
1173 name = endp;
1174 i = name - 1;
1178 new.text = g_utf8_collate_key(name, i - name);
1179 new.number = -1;
1180 g_array_append_val(array, new);
1182 new.text = NULL;
1183 g_array_append_val(array, new);
1185 retval = (CollateKey *) array->data;
1186 g_array_free(array, FALSE);
1188 if (to_free)
1189 g_free(to_free); /* Only taken for invalid UTF-8 */
1191 return retval;
1194 void collate_key_free(CollateKey *key)
1196 CollateKey *part;
1198 for (part = key; part->text; part++)
1199 g_free(part->text);
1200 g_free(key);
1203 int collate_key_cmp(const CollateKey *n1, const CollateKey *n2)
1205 int r;
1207 while (1)
1209 if (!n1->text)
1210 return n2->text ? -1 : 0;
1211 if (!n2->text)
1212 return 1;
1213 r = strcmp(n1->text, n2->text);
1214 if (r)
1215 return r;
1217 if (n1->number < n2->number)
1218 return -1;
1219 if (n1->number > n2->number)
1220 return 1;
1222 n1++;
1223 n2++;
1227 /* Returns TRUE if the object exists, FALSE if it doesn't.
1228 * For symlinks, the file pointed to must exist.
1230 gboolean file_exists(const char *path)
1232 struct stat info;
1234 return !mc_stat(path, &info);