Code cleanup around glib version check (2.28 minimum).
[claws.git] / src / common / utils.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2016 Hiroyuki Yamamoto & The Claws Mail Team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  *
18  * The code of the g_utf8_substring function below is owned by
19  * Matthias Clasen <matthiasc@src.gnome.org>/<mclasen@redhat.com>
20  * and is got from GLIB 2.30: https://git.gnome.org/browse/glib/commit/
21  *  ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
22  *
23  * GLib 2.30 is licensed under GPL v2 or later and:
24  * Copyright (C) 1999 Tom Tromey
25  * Copyright (C) 2000 Red Hat, Inc.
26  *
27  * https://git.gnome.org/browse/glib/tree/glib/gutf8.c
28  *  ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
29  */
30
31 #ifdef HAVE_CONFIG_H
32 #  include "config.h"
33 #include "claws-features.h"
34 #endif
35
36 #include "defs.h"
37
38 #include <glib.h>
39 #include <gio/gio.h>
40
41 #include <glib/gi18n.h>
42
43 #ifdef USE_PTHREAD
44 #include <pthread.h>
45 #endif
46
47 #include <stdio.h>
48 #include <string.h>
49 #include <ctype.h>
50 #include <errno.h>
51 #include <sys/param.h>
52 #ifndef G_OS_WIN32
53 #include <sys/socket.h>
54 #endif
55
56 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
57 #  include <wchar.h>
58 #  include <wctype.h>
59 #endif
60 #include <stdlib.h>
61 #include <sys/stat.h>
62 #include <unistd.h>
63 #include <stdarg.h>
64 #include <sys/types.h>
65 #if HAVE_SYS_WAIT_H
66 #  include <sys/wait.h>
67 #endif
68 #include <dirent.h>
69 #include <time.h>
70 #include <regex.h>
71
72 #ifdef G_OS_UNIX
73 #include <sys/utsname.h>
74 #endif
75
76 #include <fcntl.h>
77
78 #ifdef G_OS_WIN32
79 #  include <direct.h>
80 #  include <io.h>
81 #  include <w32lib.h>
82 #endif
83
84 #include "utils.h"
85 #include "socket.h"
86 #include "../codeconv.h"
87 #include "tlds.h"
88
89 #define BUFFSIZE        8192
90
91 static gboolean debug_mode = FALSE;
92
93 /* Return true if we are running as root.  This function should beused
94    instead of getuid () == 0.  */
95 gboolean superuser_p (void)
96 {
97 #ifdef G_OS_WIN32
98   return w32_is_administrator ();
99 #else
100   return !getuid();
101 #endif  
102 }
103
104 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
105 {
106 #if GLIB_CHECK_VERSION(2, 34, 0)
107         return g_slist_copy_deep(list, func, NULL);
108 #else
109         GSList *res = g_slist_copy(list);
110         GSList *walk = res;
111         while (walk) {
112                 walk->data = func(walk->data, NULL);
113                 walk = walk->next;
114         }
115         return res;
116 #endif
117 }
118
119 void list_free_strings_full(GList *list)
120 {
121         g_list_free_full(list, (GDestroyNotify)g_free);
122 }
123
124 void slist_free_strings_full(GSList *list)
125 {
126         g_slist_free_full(list, (GDestroyNotify)g_free);
127 }
128
129 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
130 {
131         g_free(key);
132 }
133
134 void hash_free_strings(GHashTable *table)
135 {
136         g_hash_table_foreach(table, hash_free_strings_func, NULL);
137 }
138
139 gint str_case_equal(gconstpointer v, gconstpointer v2)
140 {
141         return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
142 }
143
144 guint str_case_hash(gconstpointer key)
145 {
146         const gchar *p = key;
147         guint h = *p;
148
149         if (h) {
150                 h = g_ascii_tolower(h);
151                 for (p += 1; *p != '\0'; p++)
152                         h = (h << 5) - h + g_ascii_tolower(*p);
153         }
154
155         return h;
156 }
157
158 void ptr_array_free_strings(GPtrArray *array)
159 {
160         gint i;
161         gchar *str;
162
163         cm_return_if_fail(array != NULL);
164
165         for (i = 0; i < array->len; i++) {
166                 str = g_ptr_array_index(array, i);
167                 g_free(str);
168         }
169 }
170
171 gint to_number(const gchar *nstr)
172 {
173         register const gchar *p;
174
175         if (*nstr == '\0') return -1;
176
177         for (p = nstr; *p != '\0'; p++)
178                 if (!g_ascii_isdigit(*p)) return -1;
179
180         return atoi(nstr);
181 }
182
183 /* convert integer into string,
184    nstr must be not lower than 11 characters length */
185 gchar *itos_buf(gchar *nstr, gint n)
186 {
187         g_snprintf(nstr, 11, "%d", n);
188         return nstr;
189 }
190
191 /* convert integer into string */
192 gchar *itos(gint n)
193 {
194         static gchar nstr[11];
195
196         return itos_buf(nstr, n);
197 }
198
199 #define divide(num,divisor,i,d)         \
200 {                                       \
201         i = num >> divisor;             \
202         d = num & ((1<<divisor)-1);     \
203         d = (d*100) >> divisor;         \
204 }
205
206
207 /*!
208  * \brief Convert a given size in bytes in a human-readable string
209  *
210  * \param size  The size expressed in bytes to convert in string
211  * \return      The string that respresents the size in an human-readable way
212  */
213 gchar *to_human_readable(goffset size)
214 {
215         static gchar str[14];
216         static gchar *b_format = NULL, *kb_format = NULL, 
217                      *mb_format = NULL, *gb_format = NULL;
218         register int t = 0, r = 0;
219         if (b_format == NULL) {
220                 b_format  = _("%dB");
221                 kb_format = _("%d.%02dKB");
222                 mb_format = _("%d.%02dMB");
223                 gb_format = _("%.2fGB");
224         }
225         
226         if (size < (goffset)1024) {
227                 g_snprintf(str, sizeof(str), b_format, (gint)size);
228                 return str;
229         } else if (size >> 10 < (goffset)1024) {
230                 divide(size, 10, t, r);
231                 g_snprintf(str, sizeof(str), kb_format, t, r);
232                 return str;
233         } else if (size >> 20 < (goffset)1024) {
234                 divide(size, 20, t, r);
235                 g_snprintf(str, sizeof(str), mb_format, t, r);
236                 return str;
237         } else {
238                 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
239                 return str;
240         }
241 }
242
243 /* strcmp with NULL-checking */
244 gint strcmp2(const gchar *s1, const gchar *s2)
245 {
246         if (s1 == NULL || s2 == NULL)
247                 return -1;
248         else
249                 return strcmp(s1, s2);
250 }
251 /* strstr with NULL-checking */
252 gchar *strstr2(const gchar *s1, const gchar *s2)
253 {
254         if (s1 == NULL || s2 == NULL)
255                 return NULL;
256         else
257                 return strstr(s1, s2);
258 }
259 /* compare paths */
260 gint path_cmp(const gchar *s1, const gchar *s2)
261 {
262         gint len1, len2;
263         int rc;
264 #ifdef G_OS_WIN32
265         gchar *s1buf, *s2buf;
266 #endif
267
268         if (s1 == NULL || s2 == NULL) return -1;
269         if (*s1 == '\0' || *s2 == '\0') return -1;
270
271 #ifdef G_OS_WIN32
272         s1buf = g_strdup (s1);
273         s2buf = g_strdup (s2);
274         subst_char (s1buf, '/', G_DIR_SEPARATOR);
275         subst_char (s2buf, '/', G_DIR_SEPARATOR);
276         s1 = s1buf;
277         s2 = s2buf;
278 #endif /* !G_OS_WIN32 */
279
280         len1 = strlen(s1);
281         len2 = strlen(s2);
282
283         if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
284         if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
285
286         rc = strncmp(s1, s2, MAX(len1, len2));
287 #ifdef G_OS_WIN32
288         g_free (s1buf);
289         g_free (s2buf);
290 #endif /* !G_OS_WIN32 */
291         return rc;
292 }
293
294 /* remove trailing return code */
295 gchar *strretchomp(gchar *str)
296 {
297         register gchar *s;
298
299         if (!*str) return str;
300
301         for (s = str + strlen(str) - 1;
302              s >= str && (*s == '\n' || *s == '\r');
303              s--)
304                 *s = '\0';
305
306         return str;
307 }
308
309 /* remove trailing character */
310 gchar *strtailchomp(gchar *str, gchar tail_char)
311 {
312         register gchar *s;
313
314         if (!*str) return str;
315         if (tail_char == '\0') return str;
316
317         for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
318                 *s = '\0';
319
320         return str;
321 }
322
323 /* remove CR (carriage return) */
324 gchar *strcrchomp(gchar *str)
325 {
326         register gchar *s;
327
328         if (!*str) return str;
329
330         s = str + strlen(str) - 1;
331         if (*s == '\n' && s > str && *(s - 1) == '\r') {
332                 *(s - 1) = '\n';
333                 *s = '\0';
334         }
335
336         return str;
337 }
338
339 gint file_strip_crs(const gchar *file)
340 {
341         FILE *fp = NULL, *outfp = NULL;
342         gchar buf[4096];
343         gchar *out = get_tmp_file();
344         if (file == NULL)
345                 goto freeout;
346
347         fp = g_fopen(file, "rb");
348         if (!fp)
349                 goto freeout;
350
351         outfp = g_fopen(out, "wb");
352         if (!outfp) {
353                 fclose(fp);
354                 goto freeout;
355         }
356
357         while (fgets(buf, sizeof (buf), fp) != NULL) {
358                 strcrchomp(buf);
359                 if (fputs(buf, outfp) == EOF) {
360                         fclose(fp);
361                         fclose(outfp);
362                         goto unlinkout;
363                 }
364         }
365
366         fclose(fp);
367         if (fclose(outfp) == EOF) {
368                 goto unlinkout;
369         }
370         
371         if (move_file(out, file, TRUE) < 0)
372                 goto unlinkout;
373         
374         g_free(out);
375         return 0;
376 unlinkout:
377         claws_unlink(out);
378 freeout:
379         g_free(out);
380         return -1;
381 }
382
383 /* Similar to `strstr' but this function ignores the case of both strings.  */
384 gchar *strcasestr(const gchar *haystack, const gchar *needle)
385 {
386         size_t haystack_len = strlen(haystack);
387
388         return strncasestr(haystack, haystack_len, needle);
389 }
390
391 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
392 {
393         register size_t needle_len;
394
395         needle_len   = strlen(needle);
396
397         if (haystack_len < needle_len || needle_len == 0)
398                 return NULL;
399
400         while (haystack_len >= needle_len) {
401                 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
402                         return (gchar *)haystack;
403                 else {
404                         haystack++;
405                         haystack_len--;
406                 }
407         }
408
409         return NULL;
410 }
411
412 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
413                    gconstpointer needle, size_t needlelen)
414 {
415         const gchar *haystack_ = (const gchar *)haystack;
416         const gchar *needle_ = (const gchar *)needle;
417         const gchar *haystack_cur = (const gchar *)haystack;
418         size_t haystack_left = haystacklen;
419
420         if (needlelen == 1)
421                 return memchr(haystack_, *needle_, haystacklen);
422
423         while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
424                != NULL) {
425                 if (haystacklen - (haystack_cur - haystack_) < needlelen)
426                         break;
427                 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
428                         return (gpointer)haystack_cur;
429                 else{
430                         haystack_cur++;
431                         haystack_left = haystacklen - (haystack_cur - haystack_);
432                 }
433         }
434
435         return NULL;
436 }
437
438 /* Copy no more than N characters of SRC to DEST, with NULL terminating.  */
439 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
440 {
441         register const gchar *s = src;
442         register gchar *d = dest;
443
444         while (--n && *s)
445                 *d++ = *s++;
446         *d = '\0';
447
448         return dest;
449 }
450
451
452 /* Examine if next block is non-ASCII string */
453 gboolean is_next_nonascii(const gchar *s)
454 {
455         const gchar *p;
456
457         /* skip head space */
458         for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
459                 ;
460         for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
461                 if (*(guchar *)p > 127 || *(guchar *)p < 32)
462                         return TRUE;
463         }
464
465         return FALSE;
466 }
467
468 gint get_next_word_len(const gchar *s)
469 {
470         gint len = 0;
471
472         for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
473                 ;
474
475         return len;
476 }
477
478 static void trim_subject_for_compare(gchar *str)
479 {
480         gchar *srcp;
481
482         eliminate_parenthesis(str, '[', ']');
483         eliminate_parenthesis(str, '(', ')');
484         g_strstrip(str);
485
486         srcp = str + subject_get_prefix_length(str);
487         if (srcp != str)
488                 memmove(str, srcp, strlen(srcp) + 1);
489 }
490
491 static void trim_subject_for_sort(gchar *str)
492 {
493         gchar *srcp;
494
495         g_strstrip(str);
496
497         srcp = str + subject_get_prefix_length(str);
498         if (srcp != str)
499                 memmove(str, srcp, strlen(srcp) + 1);
500 }
501
502 /* compare subjects */
503 gint subject_compare(const gchar *s1, const gchar *s2)
504 {
505         gchar *str1, *str2;
506
507         if (!s1 || !s2) return -1;
508         if (!*s1 || !*s2) return -1;
509
510         Xstrdup_a(str1, s1, return -1);
511         Xstrdup_a(str2, s2, return -1);
512
513         trim_subject_for_compare(str1);
514         trim_subject_for_compare(str2);
515
516         if (!*str1 || !*str2) return -1;
517
518         return strcmp(str1, str2);
519 }
520
521 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
522 {
523         gchar *str1, *str2;
524
525         if (!s1 || !s2) return -1;
526
527         Xstrdup_a(str1, s1, return -1);
528         Xstrdup_a(str2, s2, return -1);
529
530         trim_subject_for_sort(str1);
531         trim_subject_for_sort(str2);
532
533         return g_utf8_collate(str1, str2);
534 }
535
536 void trim_subject(gchar *str)
537 {
538         register gchar *srcp;
539         gchar op, cl;
540         gint in_brace;
541
542         g_strstrip(str);
543
544         srcp = str + subject_get_prefix_length(str);
545
546         if (*srcp == '[') {
547                 op = '[';
548                 cl = ']';
549         } else if (*srcp == '(') {
550                 op = '(';
551                 cl = ')';
552         } else
553                 op = 0;
554
555         if (op) {
556                 ++srcp;
557                 in_brace = 1;
558                 while (*srcp) {
559                         if (*srcp == op)
560                                 in_brace++;
561                         else if (*srcp == cl)
562                                 in_brace--;
563                         srcp++;
564                         if (in_brace == 0)
565                                 break;
566                 }
567         }
568         while (g_ascii_isspace(*srcp)) srcp++;
569         memmove(str, srcp, strlen(srcp) + 1);
570 }
571
572 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
573 {
574         register gchar *srcp, *destp;
575         gint in_brace;
576
577         destp = str;
578
579         while ((destp = strchr(destp, op))) {
580                 in_brace = 1;
581                 srcp = destp + 1;
582                 while (*srcp) {
583                         if (*srcp == op)
584                                 in_brace++;
585                         else if (*srcp == cl)
586                                 in_brace--;
587                         srcp++;
588                         if (in_brace == 0)
589                                 break;
590                 }
591                 while (g_ascii_isspace(*srcp)) srcp++;
592                 memmove(destp, srcp, strlen(srcp) + 1);
593         }
594 }
595
596 void extract_parenthesis(gchar *str, gchar op, gchar cl)
597 {
598         register gchar *srcp, *destp;
599         gint in_brace;
600
601         destp = str;
602
603         while ((srcp = strchr(destp, op))) {
604                 if (destp > str)
605                         *destp++ = ' ';
606                 memmove(destp, srcp + 1, strlen(srcp));
607                 in_brace = 1;
608                 while(*destp) {
609                         if (*destp == op)
610                                 in_brace++;
611                         else if (*destp == cl)
612                                 in_brace--;
613
614                         if (in_brace == 0)
615                                 break;
616
617                         destp++;
618                 }
619         }
620         *destp = '\0';
621 }
622
623 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
624                                          gchar op, gchar cl)
625 {
626         register gchar *srcp, *destp;
627         gint in_brace;
628         gboolean in_quote = FALSE;
629
630         destp = str;
631
632         while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
633                 if (destp > str)
634                         *destp++ = ' ';
635                 memmove(destp, srcp + 1, strlen(srcp));
636                 in_brace = 1;
637                 while(*destp) {
638                         if (*destp == op && !in_quote)
639                                 in_brace++;
640                         else if (*destp == cl && !in_quote)
641                                 in_brace--;
642                         else if (*destp == quote_chr)
643                                 in_quote ^= TRUE;
644
645                         if (in_brace == 0)
646                                 break;
647
648                         destp++;
649                 }
650         }
651         *destp = '\0';
652 }
653
654 void extract_quote(gchar *str, gchar quote_chr)
655 {
656         register gchar *p;
657
658         if ((str = strchr(str, quote_chr))) {
659                 p = str;
660                 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
661                         memmove(p - 1, p, strlen(p) + 1);
662                         p--;
663                 }
664                 if(p) {
665                         *p = '\0';
666                         memmove(str, str + 1, p - str);
667                 }
668         }
669 }
670
671 /* Returns a newly allocated string with all quote_chr not at the beginning
672    or the end of str escaped with '\' or the given str if not required. */
673 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
674 {
675         register gchar *p, *q;
676         gchar *qstr;
677         int k = 0, l = 0;
678
679         if (str == NULL || *str == '\0')
680                 return str;
681
682         /* search for unescaped quote_chr */
683         p = str;
684         if (*p == quote_chr)
685                 ++p, ++l;
686         while (*p) {
687                 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
688                         ++k;
689                 ++p, ++l;
690         }
691         if (!k) /* nothing to escape */
692                 return str;
693
694         /* unescaped quote_chr found */
695         qstr = g_malloc(l + k + 1);
696         p = str;
697         q = qstr;
698         if (*p == quote_chr) {
699                 *q = quote_chr;
700                 ++p, ++q;
701         }
702         while (*p) {
703                 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
704                         *q++ = '\\';
705                 *q++ = *p++;
706         }
707         *q = '\0';
708
709         return qstr;
710 }
711
712 void eliminate_address_comment(gchar *str)
713 {
714         register gchar *srcp, *destp;
715         gint in_brace;
716
717         destp = str;
718
719         while ((destp = strchr(destp, '"'))) {
720                 if ((srcp = strchr(destp + 1, '"'))) {
721                         srcp++;
722                         if (*srcp == '@') {
723                                 destp = srcp + 1;
724                         } else {
725                                 while (g_ascii_isspace(*srcp)) srcp++;
726                                 memmove(destp, srcp, strlen(srcp) + 1);
727                         }
728                 } else {
729                         *destp = '\0';
730                         break;
731                 }
732         }
733
734         destp = str;
735
736         while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
737                 in_brace = 1;
738                 srcp = destp + 1;
739                 while (*srcp) {
740                         if (*srcp == '(')
741                                 in_brace++;
742                         else if (*srcp == ')')
743                                 in_brace--;
744                         srcp++;
745                         if (in_brace == 0)
746                                 break;
747                 }
748                 while (g_ascii_isspace(*srcp)) srcp++;
749                 memmove(destp, srcp, strlen(srcp) + 1);
750         }
751 }
752
753 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
754 {
755         gboolean in_quote = FALSE;
756
757         while (*str) {
758                 if (*str == c && !in_quote)
759                         return (gchar *)str;
760                 if (*str == quote_chr)
761                         in_quote ^= TRUE;
762                 str++;
763         }
764
765         return NULL;
766 }
767
768 void extract_address(gchar *str)
769 {
770         cm_return_if_fail(str != NULL);
771         eliminate_address_comment(str);
772         if (strchr_with_skip_quote(str, '"', '<'))
773                 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
774         g_strstrip(str);
775 }
776
777 void extract_list_id_str(gchar *str)
778 {
779         if (strchr_with_skip_quote(str, '"', '<'))
780                 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
781         g_strstrip(str);
782 }
783
784 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
785 {
786         gchar *work;
787         gchar *workp;
788
789         if (!str) return addr_list;
790
791         Xstrdup_a(work, str, return addr_list);
792
793         if (removecomments)
794                 eliminate_address_comment(work);
795         workp = work;
796
797         while (workp && *workp) {
798                 gchar *p, *next;
799
800                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
801                         *p = '\0';
802                         next = p + 1;
803                 } else
804                         next = NULL;
805
806                 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
807                         extract_parenthesis_with_skip_quote
808                                 (workp, '"', '<', '>');
809
810                 g_strstrip(workp);
811                 if (*workp)
812                         addr_list = g_slist_append(addr_list, g_strdup(workp));
813
814                 workp = next;
815         }
816
817         return addr_list;
818 }
819
820 GSList *address_list_append(GSList *addr_list, const gchar *str)
821 {
822         return address_list_append_real(addr_list, str, TRUE);
823 }
824
825 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
826 {
827         return address_list_append_real(addr_list, str, FALSE);
828 }
829
830 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
831 {
832         const gchar *strp;
833
834         if (!str) return msgid_list;
835         strp = str;
836
837         while (strp && *strp) {
838                 const gchar *start, *end;
839                 gchar *msgid;
840
841                 if ((start = strchr(strp, '<')) != NULL) {
842                         end = strchr(start + 1, '>');
843                         if (!end) break;
844                 } else
845                         break;
846
847                 msgid = g_strndup(start + 1, end - start - 1);
848                 g_strstrip(msgid);
849                 if (*msgid)
850                         msgid_list = g_slist_prepend(msgid_list, msgid);
851                 else
852                         g_free(msgid);
853
854                 strp = end + 1;
855         }
856
857         return msgid_list;
858 }
859
860 GSList *references_list_append(GSList *msgid_list, const gchar *str)
861 {
862         GSList *list;
863
864         list = references_list_prepend(NULL, str);
865         list = g_slist_reverse(list);
866         msgid_list = g_slist_concat(msgid_list, list);
867
868         return msgid_list;
869 }
870
871 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
872 {
873         gchar *work;
874         gchar *workp;
875
876         if (!str) return group_list;
877
878         Xstrdup_a(work, str, return group_list);
879
880         workp = work;
881
882         while (workp && *workp) {
883                 gchar *p, *next;
884
885                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
886                         *p = '\0';
887                         next = p + 1;
888                 } else
889                         next = NULL;
890
891                 g_strstrip(workp);
892                 if (*workp)
893                         group_list = g_slist_append(group_list,
894                                                     g_strdup(workp));
895
896                 workp = next;
897         }
898
899         return group_list;
900 }
901
902 GList *add_history(GList *list, const gchar *str)
903 {
904         GList *old;
905         gchar *oldstr;
906
907         cm_return_val_if_fail(str != NULL, list);
908
909         old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
910         if (old) {
911                 oldstr = old->data;
912                 list = g_list_remove(list, old->data);
913                 g_free(oldstr);
914         } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
915                 GList *last;
916
917                 last = g_list_last(list);
918                 if (last) {
919                         oldstr = last->data;
920                         list = g_list_remove(list, last->data);
921                         g_free(oldstr);
922                 }
923         }
924
925         list = g_list_prepend(list, g_strdup(str));
926
927         return list;
928 }
929
930 void remove_return(gchar *str)
931 {
932         register gchar *p = str;
933
934         while (*p) {
935                 if (*p == '\n' || *p == '\r')
936                         memmove(p, p + 1, strlen(p));
937                 else
938                         p++;
939         }
940 }
941
942 void remove_space(gchar *str)
943 {
944         register gchar *p = str;
945         register gint spc;
946
947         while (*p) {
948                 spc = 0;
949                 while (g_ascii_isspace(*(p + spc)))
950                         spc++;
951                 if (spc)
952                         memmove(p, p + spc, strlen(p + spc) + 1);
953                 else
954                         p++;
955         }
956 }
957
958 void unfold_line(gchar *str)
959 {
960         register gchar *ch;
961         register gunichar c;
962         register gint len;
963
964         ch = str; /* iterator for source string */
965
966         while (*ch != 0) {
967                 c = g_utf8_get_char_validated(ch, -1);
968
969                 if (c == (gunichar)-1 || c == (gunichar)-2) {
970                         /* non-unicode byte, move past it */
971                         ch++;
972                         continue;
973                 }
974
975                 len = g_unichar_to_utf8(c, NULL);
976
977                 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
978                                 g_unichar_isspace(c)) {
979                         /* replace anything bad or whitespacey with a single space */
980                         *ch = ' ';
981                         ch++;
982                         if (len > 1) {
983                                 /* move rest of the string forwards, since we just replaced
984                                  * a multi-byte sequence with one byte */
985                                 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
986                         }
987                 } else {
988                         /* A valid unicode character, copy it. */
989                         ch += len;
990                 }
991         }
992 }
993
994 void subst_char(gchar *str, gchar orig, gchar subst)
995 {
996         register gchar *p = str;
997
998         while (*p) {
999                 if (*p == orig)
1000                         *p = subst;
1001                 p++;
1002         }
1003 }
1004
1005 void subst_chars(gchar *str, gchar *orig, gchar subst)
1006 {
1007         register gchar *p = str;
1008
1009         while (*p) {
1010                 if (strchr(orig, *p) != NULL)
1011                         *p = subst;
1012                 p++;
1013         }
1014 }
1015
1016 void subst_for_filename(gchar *str)
1017 {
1018         if (!str)
1019                 return;
1020 #ifdef G_OS_WIN32
1021         subst_chars(str, "\t\r\n\\/*?:", '_');
1022 #else
1023         subst_chars(str, "\t\r\n\\/*", '_');
1024 #endif
1025 }
1026
1027 void subst_for_shellsafe_filename(gchar *str)
1028 {
1029         if (!str)
1030                 return;
1031         subst_for_filename(str);
1032         subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1033 }
1034
1035 gboolean is_ascii_str(const gchar *str)
1036 {
1037         const guchar *p = (const guchar *)str;
1038
1039         while (*p != '\0') {
1040                 if (*p != '\t' && *p != ' ' &&
1041                     *p != '\r' && *p != '\n' &&
1042                     (*p < 32 || *p >= 127))
1043                         return FALSE;
1044                 p++;
1045         }
1046
1047         return TRUE;
1048 }
1049
1050 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1051 {
1052         gchar * position = NULL;
1053         gchar * tmp_pos = NULL;
1054         int i;
1055
1056         if (str == NULL || quote_chars == NULL)
1057                 return NULL;
1058
1059         for (i = 0; i < strlen(quote_chars); i++) {
1060                 tmp_pos = strrchr (str, quote_chars[i]);
1061                 if(position == NULL
1062                                 || (tmp_pos != NULL && position <= tmp_pos) )
1063                         position = tmp_pos;
1064         }
1065         return position;
1066 }
1067
1068 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1069 {
1070         const gchar *first_pos;
1071         const gchar *last_pos;
1072         const gchar *p = str;
1073         gint quote_level = -1;
1074
1075         /* speed up line processing by only searching to the last '>' */
1076         if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1077                 /* skip a line if it contains a '<' before the initial '>' */
1078                 if (memchr(str, '<', first_pos - str) != NULL)
1079                         return -1;
1080                 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1081         } else
1082                 return -1;
1083
1084         while (p <= last_pos) {
1085                 while (p < last_pos) {
1086                         if (g_ascii_isspace(*p))
1087                                 p++;
1088                         else
1089                                 break;
1090                 }
1091
1092                 if (strchr(quote_chars, *p))
1093                         quote_level++;
1094                 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1095                         /* any characters are allowed except '-','<' and space */
1096                         while (*p != '-' && *p != '<'
1097                                && !strchr(quote_chars, *p)
1098                                && !g_ascii_isspace(*p)
1099                                && p < last_pos)
1100                                 p++;
1101                         if (strchr(quote_chars, *p))
1102                                 quote_level++;
1103                         else
1104                                 break;
1105                 }
1106
1107                 p++;
1108         }
1109
1110         return quote_level;
1111 }
1112
1113 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1114 {
1115         const gchar *p = str, *q;
1116         gint cur_line = 0, len;
1117
1118         while ((q = strchr(p, '\n')) != NULL) {
1119                 len = q - p + 1;
1120                 if (len > max_chars) {
1121                         if (line)
1122                                 *line = cur_line;
1123                         return -1;
1124                 }
1125                 p = q + 1;
1126                 ++cur_line;
1127         }
1128
1129         len = strlen(p);
1130         if (len > max_chars) {
1131                 if (line)
1132                         *line = cur_line;
1133                 return -1;
1134         }
1135
1136         return 0;
1137 }
1138
1139 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1140 {
1141         gchar * position = NULL;
1142         gchar * tmp_pos = NULL;
1143         int i;
1144
1145         if (str == NULL || quote_chars == NULL)
1146                 return NULL;
1147
1148         for (i = 0; i < strlen(quote_chars); i++) {
1149                 tmp_pos = strchr (str, quote_chars[i]);
1150                 if(position == NULL
1151                                 || (tmp_pos != NULL && position >= tmp_pos) )
1152                         position = tmp_pos;
1153         }
1154         return position;
1155 }
1156
1157 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1158 {
1159         register guint haystack_len, needle_len;
1160         gboolean in_squote = FALSE, in_dquote = FALSE;
1161
1162         haystack_len = strlen(haystack);
1163         needle_len   = strlen(needle);
1164
1165         if (haystack_len < needle_len || needle_len == 0)
1166                 return NULL;
1167
1168         while (haystack_len >= needle_len) {
1169                 if (!in_squote && !in_dquote &&
1170                     !strncmp(haystack, needle, needle_len))
1171                         return (gchar *)haystack;
1172
1173                 /* 'foo"bar"' -> foo"bar"
1174                    "foo'bar'" -> foo'bar' */
1175                 if (*haystack == '\'') {
1176                         if (in_squote)
1177                                 in_squote = FALSE;
1178                         else if (!in_dquote)
1179                                 in_squote = TRUE;
1180                 } else if (*haystack == '\"') {
1181                         if (in_dquote)
1182                                 in_dquote = FALSE;
1183                         else if (!in_squote)
1184                                 in_dquote = TRUE;
1185                 } else if (*haystack == '\\') {
1186                         haystack++;
1187                         haystack_len--;
1188                 }
1189
1190                 haystack++;
1191                 haystack_len--;
1192         }
1193
1194         return NULL;
1195 }
1196
1197 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1198                             gint max_tokens)
1199 {
1200         GSList *string_list = NULL, *slist;
1201         gchar **str_array, *s, *new_str;
1202         guint i, n = 1, len;
1203
1204         cm_return_val_if_fail(str != NULL, NULL);
1205         cm_return_val_if_fail(delim != NULL, NULL);
1206
1207         if (max_tokens < 1)
1208                 max_tokens = G_MAXINT;
1209
1210         s = strstr_with_skip_quote(str, delim);
1211         if (s) {
1212                 guint delimiter_len = strlen(delim);
1213
1214                 do {
1215                         len = s - str;
1216                         new_str = g_strndup(str, len);
1217
1218                         if (new_str[0] == '\'' || new_str[0] == '\"') {
1219                                 if (new_str[len - 1] == new_str[0]) {
1220                                         new_str[len - 1] = '\0';
1221                                         memmove(new_str, new_str + 1, len - 1);
1222                                 }
1223                         }
1224                         string_list = g_slist_prepend(string_list, new_str);
1225                         n++;
1226                         str = s + delimiter_len;
1227                         s = strstr_with_skip_quote(str, delim);
1228                 } while (--max_tokens && s);
1229         }
1230
1231         if (*str) {
1232                 new_str = g_strdup(str);
1233                 if (new_str[0] == '\'' || new_str[0] == '\"') {
1234                         len = strlen(str);
1235                         if (new_str[len - 1] == new_str[0]) {
1236                                 new_str[len - 1] = '\0';
1237                                 memmove(new_str, new_str + 1, len - 1);
1238                         }
1239                 }
1240                 string_list = g_slist_prepend(string_list, new_str);
1241                 n++;
1242         }
1243
1244         str_array = g_new(gchar*, n);
1245
1246         i = n - 1;
1247
1248         str_array[i--] = NULL;
1249         for (slist = string_list; slist; slist = slist->next)
1250                 str_array[i--] = slist->data;
1251
1252         g_slist_free(string_list);
1253
1254         return str_array;
1255 }
1256
1257 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1258 {
1259         gchar *abbrev_group;
1260         gchar *ap;
1261         const gchar *p = group;
1262         const gchar *last;
1263
1264         cm_return_val_if_fail(group != NULL, NULL);
1265
1266         last = group + strlen(group);
1267         abbrev_group = ap = g_malloc(strlen(group) + 1);
1268
1269         while (*p) {
1270                 while (*p == '.')
1271                         *ap++ = *p++;
1272                 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1273                         *ap++ = *p++;
1274                         while (*p != '.') p++;
1275                 } else {
1276                         strcpy(ap, p);
1277                         return abbrev_group;
1278                 }
1279         }
1280
1281         *ap = '\0';
1282         return abbrev_group;
1283 }
1284
1285 gchar *trim_string(const gchar *str, gint len)
1286 {
1287         const gchar *p = str;
1288         gint mb_len;
1289         gchar *new_str;
1290         gint new_len = 0;
1291
1292         if (!str) return NULL;
1293         if (strlen(str) <= len)
1294                 return g_strdup(str);
1295         if (g_utf8_validate(str, -1, NULL) == FALSE)
1296                 return g_strdup(str);
1297
1298         while (*p != '\0') {
1299                 mb_len = g_utf8_skip[*(guchar *)p];
1300                 if (mb_len == 0)
1301                         break;
1302                 else if (new_len + mb_len > len)
1303                         break;
1304
1305                 new_len += mb_len;
1306                 p += mb_len;
1307         }
1308
1309         Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1310         return g_strconcat(new_str, "...", NULL);
1311 }
1312
1313 GList *uri_list_extract_filenames(const gchar *uri_list)
1314 {
1315         GList *result = NULL;
1316         const gchar *p, *q;
1317         gchar *escaped_utf8uri;
1318
1319         p = uri_list;
1320
1321         while (p) {
1322                 if (*p != '#') {
1323                         while (g_ascii_isspace(*p)) p++;
1324                         if (!strncmp(p, "file:", 5)) {
1325                                 q = p;
1326                                 q += 5;
1327                                 while (*q && *q != '\n' && *q != '\r') q++;
1328
1329                                 if (q > p) {
1330                                         gchar *file, *locale_file = NULL;
1331                                         q--;
1332                                         while (q > p && g_ascii_isspace(*q))
1333                                                 q--;
1334                                         Xalloca(escaped_utf8uri, q - p + 2,
1335                                                 return result);
1336                                         Xalloca(file, q - p + 2,
1337                                                 return result);
1338                                         *file = '\0';
1339                                         strncpy(escaped_utf8uri, p, q - p + 1);
1340                                         escaped_utf8uri[q - p + 1] = '\0';
1341                                         decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1342                     /*
1343                      * g_filename_from_uri() rejects escaped/locale encoded uri
1344                      * string which come from Nautilus.
1345                      */
1346 #ifndef G_OS_WIN32
1347                                         if (g_utf8_validate(file, -1, NULL))
1348                                                 locale_file
1349                                                         = conv_codeset_strdup(
1350                                                                 file + 5,
1351                                                                 CS_UTF_8,
1352                                                                 conv_get_locale_charset_str());
1353                                         if (!locale_file)
1354                                                 locale_file = g_strdup(file + 5);
1355 #else
1356                                         locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1357 #endif
1358                                         result = g_list_append(result, locale_file);
1359                                 }
1360                         }
1361                 }
1362                 p = strchr(p, '\n');
1363                 if (p) p++;
1364         }
1365
1366         return result;
1367 }
1368
1369 /* Converts two-digit hexadecimal to decimal.  Used for unescaping escaped
1370  * characters
1371  */
1372 static gint axtoi(const gchar *hexstr)
1373 {
1374         gint hi, lo, result;
1375
1376         hi = hexstr[0];
1377         if ('0' <= hi && hi <= '9') {
1378                 hi -= '0';
1379         } else
1380                 if ('a' <= hi && hi <= 'f') {
1381                         hi -= ('a' - 10);
1382                 } else
1383                         if ('A' <= hi && hi <= 'F') {
1384                                 hi -= ('A' - 10);
1385                         }
1386
1387         lo = hexstr[1];
1388         if ('0' <= lo && lo <= '9') {
1389                 lo -= '0';
1390         } else
1391                 if ('a' <= lo && lo <= 'f') {
1392                         lo -= ('a'-10);
1393                 } else
1394                         if ('A' <= lo && lo <= 'F') {
1395                                 lo -= ('A' - 10);
1396                         }
1397         result = lo + (16 * hi);
1398         return result;
1399 }
1400
1401 gboolean is_uri_string(const gchar *str)
1402 {
1403         while (str && *str && g_ascii_isspace(*str))
1404                 str++;
1405         return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1406                 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1407                 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1408                 g_ascii_strncasecmp(str, "www.", 4) == 0);
1409 }
1410
1411 gchar *get_uri_path(const gchar *uri)
1412 {
1413         while (uri && *uri && g_ascii_isspace(*uri))
1414                 uri++;
1415         if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1416                 return (gchar *)(uri + 7);
1417         else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1418                 return (gchar *)(uri + 8);
1419         else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1420                 return (gchar *)(uri + 6);
1421         else
1422                 return (gchar *)uri;
1423 }
1424
1425 gint get_uri_len(const gchar *str)
1426 {
1427         const gchar *p;
1428
1429         if (is_uri_string(str)) {
1430                 for (p = str; *p != '\0'; p++) {
1431                         if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1432                                 break;
1433                 }
1434                 return p - str;
1435         }
1436
1437         return 0;
1438 }
1439
1440 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1441  * plusses, and escape characters are used)
1442  */
1443 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1444 {
1445         gchar *dec = decoded_uri;
1446         const gchar *enc = encoded_uri;
1447
1448         while (*enc) {
1449                 if (*enc == '%') {
1450                         enc++;
1451                         if (isxdigit((guchar)enc[0]) &&
1452                             isxdigit((guchar)enc[1])) {
1453                                 *dec = axtoi(enc);
1454                                 dec++;
1455                                 enc += 2;
1456                         }
1457                 } else {
1458                         if (with_plus && *enc == '+')
1459                                 *dec = ' ';
1460                         else
1461                                 *dec = *enc;
1462                         dec++;
1463                         enc++;
1464                 }
1465         }
1466
1467         *dec = '\0';
1468 }
1469
1470 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1471 {
1472         decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1473 }
1474
1475 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1476 {
1477     gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1478     decode_uri_with_plus(buffer, encoded_uri, FALSE);
1479     return buffer;
1480 }
1481
1482 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1483                      gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1484 {
1485         gchar *tmp_mailto;
1486         gchar *p;
1487         const gchar *forbidden_uris[] = { ".gnupg/",
1488                                           "/etc/passwd",
1489                                           "/etc/shadow",
1490                                           ".ssh/",
1491                                           "../",
1492                                           NULL };
1493         gint num_attach = 0;
1494         gchar **my_att = NULL;
1495
1496         Xstrdup_a(tmp_mailto, mailto, return -1);
1497
1498         if (!strncmp(tmp_mailto, "mailto:", 7))
1499                 tmp_mailto += 7;
1500
1501         p = strchr(tmp_mailto, '?');
1502         if (p) {
1503                 *p = '\0';
1504                 p++;
1505         }
1506
1507         if (to && !*to)
1508                 *to = decode_uri_gdup(tmp_mailto);
1509
1510         my_att = g_malloc(sizeof(char *));
1511         my_att[0] = NULL;
1512
1513         while (p) {
1514                 gchar *field, *value;
1515
1516                 field = p;
1517
1518                 p = strchr(p, '=');
1519                 if (!p) break;
1520                 *p = '\0';
1521                 p++;
1522
1523                 value = p;
1524
1525                 p = strchr(p, '&');
1526                 if (p) {
1527                         *p = '\0';
1528                         p++;
1529                 }
1530
1531                 if (*value == '\0') continue;
1532
1533                 if (from && !g_ascii_strcasecmp(field, "from")) {
1534                         if (!*from) {
1535                                 *from = decode_uri_gdup(value);
1536                         } else {
1537                                 gchar *tmp = decode_uri_gdup(value);
1538                                 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1539                                 g_free(*from);
1540                                 *from = new_from;
1541                         }
1542                 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1543                         if (!*cc) {
1544                                 *cc = decode_uri_gdup(value);
1545                         } else {
1546                                 gchar *tmp = decode_uri_gdup(value);
1547                                 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1548                                 g_free(*cc);
1549                                 *cc = new_cc;
1550                         }
1551                 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1552                         if (!*bcc) {
1553                                 *bcc = decode_uri_gdup(value);
1554                         } else {
1555                                 gchar *tmp = decode_uri_gdup(value);
1556                                 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1557                                 g_free(*bcc);
1558                                 *bcc = new_bcc;
1559                         }
1560                 } else if (subject && !*subject &&
1561                            !g_ascii_strcasecmp(field, "subject")) {
1562                         *subject = decode_uri_gdup(value);
1563                 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1564                         *body = decode_uri_gdup(value);
1565                 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1566                         gchar *tmp = decode_uri_gdup(value);
1567                         if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1568                                 g_warning("couldn't set insert file '%s' in body", value);
1569                         }
1570                         g_free(tmp);
1571                 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1572                         int i = 0;
1573                         gchar *tmp = decode_uri_gdup(value);
1574                         for (; forbidden_uris[i]; i++) {
1575                                 if (strstr(tmp, forbidden_uris[i])) {
1576                                         g_print("Refusing to attach '%s', potential private data leak\n",
1577                                                         tmp);
1578                                         g_free(tmp);
1579                                         break;
1580                                 }
1581                         }
1582                         if (tmp) {
1583                                 /* attach is correct */
1584                                 num_attach++;
1585                                 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1586                                 my_att[num_attach-1] = tmp;
1587                                 my_att[num_attach] = NULL;
1588                         }
1589                 } else if (inreplyto && !*inreplyto &&
1590                            !g_ascii_strcasecmp(field, "in-reply-to")) {
1591                         *inreplyto = decode_uri_gdup(value);
1592                 }
1593         }
1594
1595         if (attach)
1596                 *attach = my_att;
1597         return 0;
1598 }
1599
1600
1601 #ifdef G_OS_WIN32
1602 #include <windows.h>
1603 #ifndef CSIDL_APPDATA
1604 #define CSIDL_APPDATA 0x001a
1605 #endif
1606 #ifndef CSIDL_LOCAL_APPDATA
1607 #define CSIDL_LOCAL_APPDATA 0x001c
1608 #endif
1609 #ifndef CSIDL_FLAG_CREATE
1610 #define CSIDL_FLAG_CREATE 0x8000
1611 #endif
1612 #define DIM(v)               (sizeof(v)/sizeof((v)[0]))
1613
1614 #define RTLD_LAZY 0
1615 const char *
1616 w32_strerror (int w32_errno)
1617 {
1618   static char strerr[256];
1619   int ec = (int)GetLastError ();
1620
1621   if (w32_errno == 0)
1622     w32_errno = ec;
1623   FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1624                  MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1625                  strerr, DIM (strerr)-1, NULL);
1626   return strerr;
1627 }
1628
1629 static __inline__ void *
1630 dlopen (const char * name, int flag)
1631 {
1632   void * hd = LoadLibrary (name);
1633   return hd;
1634 }
1635
1636 static __inline__ void *
1637 dlsym (void * hd, const char * sym)
1638 {
1639   if (hd && sym)
1640     {
1641       void * fnc = GetProcAddress (hd, sym);
1642       if (!fnc)
1643         return NULL;
1644       return fnc;
1645     }
1646   return NULL;
1647 }
1648
1649
1650 static __inline__ const char *
1651 dlerror (void)
1652 {
1653   return w32_strerror (0);
1654 }
1655
1656
1657 static __inline__ int
1658 dlclose (void * hd)
1659 {
1660   if (hd)
1661     {
1662       FreeLibrary (hd);
1663       return 0;
1664     }
1665   return -1;
1666 }
1667
1668 static HRESULT
1669 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1670 {
1671   static int initialized;
1672   static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1673
1674   if (!initialized)
1675     {
1676       static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1677       void *handle;
1678       int i;
1679
1680       initialized = 1;
1681
1682       for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1683         {
1684           handle = dlopen (dllnames[i], RTLD_LAZY);
1685           if (handle)
1686             {
1687               func = dlsym (handle, "SHGetFolderPathW");
1688               if (!func)
1689                 {
1690                   dlclose (handle);
1691                   handle = NULL;
1692                 }
1693             }
1694         }
1695     }
1696
1697   if (func)
1698     return func (a,b,c,d,e);
1699   else
1700     return -1;
1701 }
1702
1703 /* Returns a static string with the directroy from which the module
1704    has been loaded.  Returns an empty string on error. */
1705 static char *w32_get_module_dir(void)
1706 {
1707         static char *moddir;
1708
1709         if (!moddir) {
1710                 char name[MAX_PATH+10];
1711                 char *p;
1712
1713                 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1714                         *name = 0;
1715                 else {
1716                         p = strrchr (name, '\\');
1717                         if (p)
1718                                 *p = 0;
1719                         else
1720                                 *name = 0;
1721                 }
1722                 moddir = g_strdup (name);
1723         }
1724         return moddir;
1725 }
1726 #endif /* G_OS_WIN32 */
1727
1728 /* Return a static string with the locale dir. */
1729 const gchar *get_locale_dir(void)
1730 {
1731         static gchar *loc_dir;
1732
1733 #ifdef G_OS_WIN32
1734         if (!loc_dir)
1735                 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1736                                       "\\share\\locale", NULL);
1737 #endif
1738         if (!loc_dir)
1739                 loc_dir = LOCALEDIR;
1740         
1741         return loc_dir;
1742 }
1743
1744
1745 const gchar *get_home_dir(void)
1746 {
1747 #ifdef G_OS_WIN32
1748         static char home_dir_utf16[MAX_PATH] = "";
1749         static gchar *home_dir_utf8 = NULL;
1750         if (home_dir_utf16[0] == '\0') {
1751                 if (w32_shgetfolderpath
1752                             (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1753                              NULL, 0, home_dir_utf16) < 0)
1754                                 strcpy (home_dir_utf16, "C:\\Claws Mail");
1755                 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1756         }
1757         return home_dir_utf8;
1758 #else
1759         static const gchar *homeenv = NULL;
1760
1761         if (homeenv)
1762                 return homeenv;
1763
1764         if (!homeenv && g_getenv("HOME") != NULL)
1765                 homeenv = g_strdup(g_getenv("HOME"));
1766         if (!homeenv)
1767                 homeenv = g_get_home_dir();
1768
1769         return homeenv;
1770 #endif
1771 }
1772
1773 static gchar *claws_rc_dir = NULL;
1774 static gboolean rc_dir_alt = FALSE;
1775 const gchar *get_rc_dir(void)
1776 {
1777
1778         if (!claws_rc_dir) {
1779                 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1780                                      RC_DIR, NULL);
1781                 debug_print("using default rc_dir %s\n", claws_rc_dir);
1782         }
1783         return claws_rc_dir;
1784 }
1785
1786 void set_rc_dir(const gchar *dir)
1787 {
1788         gchar *canonical_dir;
1789         if (claws_rc_dir != NULL) {
1790                 g_print("Error: rc_dir already set\n");
1791         } else {
1792                 int err = cm_canonicalize_filename(dir, &canonical_dir);
1793                 int len;
1794
1795                 if (err) {
1796                         g_print("Error looking for %s: %d(%s)\n",
1797                                 dir, -err, g_strerror(-err));
1798                         exit(0);
1799                 }
1800                 rc_dir_alt = TRUE;
1801
1802                 claws_rc_dir = canonical_dir;
1803                 
1804                 len = strlen(claws_rc_dir);
1805                 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1806                         claws_rc_dir[len - 1] = '\0';
1807                 
1808                 debug_print("set rc_dir to %s\n", claws_rc_dir);
1809                 if (!is_dir_exist(claws_rc_dir)) {
1810                         if (make_dir_hier(claws_rc_dir) != 0) {
1811                                 g_print("Error: can't create %s\n",
1812                                 claws_rc_dir);
1813                                 exit(0);
1814                         }
1815                 }
1816         }
1817 }
1818
1819 gboolean rc_dir_is_alt(void) {
1820         return rc_dir_alt;
1821 }
1822
1823 const gchar *get_mail_base_dir(void)
1824 {
1825         return get_home_dir();
1826 }
1827
1828 const gchar *get_news_cache_dir(void)
1829 {
1830         static gchar *news_cache_dir = NULL;
1831         if (!news_cache_dir)
1832                 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1833                                              NEWS_CACHE_DIR, NULL);
1834
1835         return news_cache_dir;
1836 }
1837
1838 const gchar *get_imap_cache_dir(void)
1839 {
1840         static gchar *imap_cache_dir = NULL;
1841
1842         if (!imap_cache_dir)
1843                 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1844                                              IMAP_CACHE_DIR, NULL);
1845
1846         return imap_cache_dir;
1847 }
1848
1849 const gchar *get_mime_tmp_dir(void)
1850 {
1851         static gchar *mime_tmp_dir = NULL;
1852
1853         if (!mime_tmp_dir)
1854                 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1855                                            MIME_TMP_DIR, NULL);
1856
1857         return mime_tmp_dir;
1858 }
1859
1860 const gchar *get_template_dir(void)
1861 {
1862         static gchar *template_dir = NULL;
1863
1864         if (!template_dir)
1865                 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1866                                            TEMPLATE_DIR, NULL);
1867
1868         return template_dir;
1869 }
1870
1871 #ifdef G_OS_WIN32
1872 const gchar *w32_get_cert_file(void)
1873 {
1874         const gchar *cert_file = NULL;
1875         if (!cert_file)
1876                 cert_file = g_strconcat(w32_get_module_dir(),
1877                                  "\\share\\claws-mail\\",
1878                                 "ca-certificates.crt",
1879                                 NULL);  
1880         return cert_file;
1881 }
1882 #endif
1883
1884 /* Return the filepath of the claws-mail.desktop file */
1885 const gchar *get_desktop_file(void)
1886 {
1887 #ifdef DESKTOPFILEPATH
1888   return DESKTOPFILEPATH;
1889 #else
1890   return NULL;
1891 #endif
1892 }
1893
1894 /* Return the default directory for Plugins. */
1895 const gchar *get_plugin_dir(void)
1896 {
1897 #ifdef G_OS_WIN32
1898         static gchar *plugin_dir = NULL;
1899
1900         if (!plugin_dir)
1901                 plugin_dir = g_strconcat(w32_get_module_dir(),
1902                                          "\\lib\\claws-mail\\plugins\\",
1903                                          NULL);
1904         return plugin_dir;
1905 #else
1906         if (is_dir_exist(PLUGINDIR))
1907                 return PLUGINDIR;
1908         else {
1909                 static gchar *plugin_dir = NULL;
1910                 if (!plugin_dir)
1911                         plugin_dir = g_strconcat(get_rc_dir(), 
1912                                 G_DIR_SEPARATOR_S, "plugins", 
1913                                 G_DIR_SEPARATOR_S, NULL);
1914                 return plugin_dir;                      
1915         }
1916 #endif
1917 }
1918
1919
1920 #ifdef G_OS_WIN32
1921 /* Return the default directory for Themes. */
1922 const gchar *w32_get_themes_dir(void)
1923 {
1924         static gchar *themes_dir = NULL;
1925
1926         if (!themes_dir)
1927                 themes_dir = g_strconcat(w32_get_module_dir(),
1928                                          "\\share\\claws-mail\\themes",
1929                                          NULL);
1930         return themes_dir;
1931 }
1932 #endif
1933
1934 const gchar *get_tmp_dir(void)
1935 {
1936         static gchar *tmp_dir = NULL;
1937
1938         if (!tmp_dir)
1939                 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1940                                       TMP_DIR, NULL);
1941
1942         return tmp_dir;
1943 }
1944
1945 gchar *get_tmp_file(void)
1946 {
1947         gchar *tmp_file;
1948         static guint32 id = 0;
1949
1950         tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1951                                    get_tmp_dir(), G_DIR_SEPARATOR, id++);
1952
1953         return tmp_file;
1954 }
1955
1956 const gchar *get_domain_name(void)
1957 {
1958 #ifdef G_OS_UNIX
1959         static gchar *domain_name = NULL;
1960         struct addrinfo hints, *res;
1961         char hostname[256];
1962         int s;
1963
1964         if (!domain_name) {
1965                 if (gethostname(hostname, sizeof(hostname)) != 0) {
1966                         perror("gethostname");
1967                         domain_name = "localhost";
1968                 } else {
1969                         memset(&hints, 0, sizeof(struct addrinfo));
1970                         hints.ai_family = AF_UNSPEC;
1971                         hints.ai_socktype = 0;
1972                         hints.ai_flags = AI_CANONNAME;
1973                         hints.ai_protocol = 0;
1974
1975                         s = getaddrinfo(hostname, NULL, &hints, &res);
1976                         if (s != 0) {
1977                                 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1978                                 domain_name = g_strdup(hostname);
1979                         } else {
1980                                 domain_name = g_strdup(res->ai_canonname);
1981                                 freeaddrinfo(res);
1982                         }
1983                 }
1984                 debug_print("domain name = %s\n", domain_name);
1985         }
1986
1987         return domain_name;
1988 #else
1989         return "localhost";
1990 #endif
1991 }
1992
1993 off_t get_file_size(const gchar *file)
1994 {
1995 #ifdef G_OS_WIN32
1996         GFile *f;
1997         GFileInfo *fi;
1998         GError *error = NULL;
1999         goffset size;
2000
2001         f = g_file_new_for_path(file);
2002         fi = g_file_query_info(f, "standard::size",
2003                         G_FILE_QUERY_INFO_NONE, NULL, &error);
2004         if (error != NULL) {
2005                 debug_print("get_file_size error: %s\n", error->message);
2006                 g_error_free(error);
2007                 g_object_unref(f);
2008                 return -1;
2009         }
2010         size = g_file_info_get_size(fi);
2011         g_object_unref(fi);
2012         g_object_unref(f);
2013         return size;
2014
2015 #else
2016         GStatBuf s;
2017
2018         if (g_stat(file, &s) < 0) {
2019                 FILE_OP_ERROR(file, "stat");
2020                 return -1;
2021         }
2022
2023         return s.st_size;
2024 #endif
2025 }
2026
2027 time_t get_file_mtime(const gchar *file)
2028 {
2029         GStatBuf s;
2030
2031         if (g_stat(file, &s) < 0) {
2032                 FILE_OP_ERROR(file, "stat");
2033                 return -1;
2034         }
2035
2036         return s.st_mtime;
2037 }
2038
2039 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2040 {
2041         GStatBuf s;
2042
2043         if (file == NULL)
2044                 return FALSE;
2045
2046         if (g_stat(file, &s) < 0) {
2047                 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2048                 return FALSE;
2049         }
2050
2051         if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2052                 return TRUE;
2053
2054         return FALSE;
2055 }
2056
2057
2058 /* Test on whether FILE is a relative file name. This is
2059  * straightforward for Unix but more complex for Windows. */
2060 gboolean is_relative_filename(const gchar *file)
2061 {
2062         if (!file)
2063                 return TRUE;
2064 #ifdef G_OS_WIN32
2065         if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2066                 return FALSE; /* Prefixed with a hostname - this can't
2067                                * be a relative name. */
2068
2069         if ( ((*file >= 'a' && *file <= 'z')
2070               || (*file >= 'A' && *file <= 'Z'))
2071              && file[1] == ':')
2072                 file += 2;  /* Skip drive letter. */
2073
2074         return !(*file == '\\' || *file == '/');
2075 #else
2076         return !(*file == G_DIR_SEPARATOR);
2077 #endif
2078 }
2079
2080
2081 gboolean is_dir_exist(const gchar *dir)
2082 {
2083         if (dir == NULL)
2084                 return FALSE;
2085
2086         return g_file_test(dir, G_FILE_TEST_IS_DIR);
2087 }
2088
2089 gboolean is_file_entry_exist(const gchar *file)
2090 {
2091         if (file == NULL)
2092                 return FALSE;
2093
2094         return g_file_test(file, G_FILE_TEST_EXISTS);
2095 }
2096
2097 gboolean dirent_is_regular_file(struct dirent *d)
2098 {
2099 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2100         if (d->d_type == DT_REG)
2101                 return TRUE;
2102         else if (d->d_type != DT_UNKNOWN)
2103                 return FALSE;
2104 #endif
2105
2106         return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2107 }
2108
2109 gint change_dir(const gchar *dir)
2110 {
2111         gchar *prevdir = NULL;
2112
2113         if (debug_mode)
2114                 prevdir = g_get_current_dir();
2115
2116         if (g_chdir(dir) < 0) {
2117                 FILE_OP_ERROR(dir, "chdir");
2118                 if (debug_mode) g_free(prevdir);
2119                 return -1;
2120         } else if (debug_mode) {
2121                 gchar *cwd;
2122
2123                 cwd = g_get_current_dir();
2124                 if (strcmp(prevdir, cwd) != 0)
2125                         g_print("current dir: %s\n", cwd);
2126                 g_free(cwd);
2127                 g_free(prevdir);
2128         }
2129
2130         return 0;
2131 }
2132
2133 gint make_dir(const gchar *dir)
2134 {
2135         if (g_mkdir(dir, S_IRWXU) < 0) {
2136                 FILE_OP_ERROR(dir, "mkdir");
2137                 return -1;
2138         }
2139         if (g_chmod(dir, S_IRWXU) < 0)
2140                 FILE_OP_ERROR(dir, "chmod");
2141
2142         return 0;
2143 }
2144
2145 gint make_dir_hier(const gchar *dir)
2146 {
2147         gchar *parent_dir;
2148         const gchar *p;
2149
2150         for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2151                 parent_dir = g_strndup(dir, p - dir);
2152                 if (*parent_dir != '\0') {
2153                         if (!is_dir_exist(parent_dir)) {
2154                                 if (make_dir(parent_dir) < 0) {
2155                                         g_free(parent_dir);
2156                                         return -1;
2157                                 }
2158                         }
2159                 }
2160                 g_free(parent_dir);
2161         }
2162
2163         if (!is_dir_exist(dir)) {
2164                 if (make_dir(dir) < 0)
2165                         return -1;
2166         }
2167
2168         return 0;
2169 }
2170
2171 gint remove_all_files(const gchar *dir)
2172 {
2173         GDir *dp;
2174         const gchar *file_name;
2175         gchar *tmp;
2176
2177         if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2178                 g_warning("failed to open directory: %s", dir);
2179                 return -1;
2180         }
2181
2182         while ((file_name = g_dir_read_name(dp)) != NULL) {
2183                 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2184                 if (claws_unlink(tmp) < 0)
2185                         FILE_OP_ERROR(tmp, "unlink");
2186                 g_free(tmp);
2187         }
2188
2189         g_dir_close(dp);
2190
2191         return 0;
2192 }
2193
2194 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2195 {
2196         GDir *dp;
2197         const gchar *dir_name;
2198         gchar *prev_dir;
2199         gint file_no;
2200
2201         if (first == last) {
2202                 /* Skip all the dir reading part. */
2203                 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2204                 if (is_dir_exist(filename)) {
2205                         /* a numbered directory with this name exists,
2206                          * remove the dot-file instead */
2207                         g_free(filename);
2208                         filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2209                 }
2210                 if (claws_unlink(filename) < 0) {
2211                         FILE_OP_ERROR(filename, "unlink");
2212                         g_free(filename);
2213                         return -1;
2214                 }
2215                 g_free(filename);
2216                 return 0;
2217         }
2218
2219         prev_dir = g_get_current_dir();
2220
2221         if (g_chdir(dir) < 0) {
2222                 FILE_OP_ERROR(dir, "chdir");
2223                 g_free(prev_dir);
2224                 return -1;
2225         }
2226
2227         if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2228                 g_warning("failed to open directory: %s", dir);
2229                 g_free(prev_dir);
2230                 return -1;
2231         }
2232
2233         while ((dir_name = g_dir_read_name(dp)) != NULL) {
2234                 file_no = to_number(dir_name);
2235                 if (file_no > 0 && first <= file_no && file_no <= last) {
2236                         if (is_dir_exist(dir_name)) {
2237                                 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2238                                 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2239                                         FILE_OP_ERROR(dot_file, "unlink");
2240                                 }
2241                                 g_free(dot_file);
2242                                 continue;
2243                         }
2244                         if (claws_unlink(dir_name) < 0)
2245                                 FILE_OP_ERROR(dir_name, "unlink");
2246                 }
2247         }
2248
2249         g_dir_close(dp);
2250
2251         if (g_chdir(prev_dir) < 0) {
2252                 FILE_OP_ERROR(prev_dir, "chdir");
2253                 g_free(prev_dir);
2254                 return -1;
2255         }
2256
2257         g_free(prev_dir);
2258
2259         return 0;
2260 }
2261
2262 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2263 {
2264         GDir *dp;
2265         const gchar *dir_name;
2266         gchar *prev_dir;
2267         gint file_no;
2268         GHashTable *wanted_files;
2269         GSList *cur;
2270         GError *error = NULL;
2271
2272         if (numberlist == NULL)
2273             return 0;
2274
2275         prev_dir = g_get_current_dir();
2276
2277         if (g_chdir(dir) < 0) {
2278                 FILE_OP_ERROR(dir, "chdir");
2279                 g_free(prev_dir);
2280                 return -1;
2281         }
2282
2283         if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2284                 g_message("Couldn't open current directory: %s (%d).\n",
2285                                 error->message, error->code);
2286                 g_error_free(error);
2287                 g_free(prev_dir);
2288                 return -1;
2289         }
2290
2291         wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2292         for (cur = numberlist; cur != NULL; cur = cur->next) {
2293                 /* numberlist->data is expected to be GINT_TO_POINTER */
2294                 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2295         }
2296
2297         while ((dir_name = g_dir_read_name(dp)) != NULL) {
2298                 file_no = to_number(dir_name);
2299                 if (is_dir_exist(dir_name))
2300                         continue;
2301                 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2302                         debug_print("removing unwanted file %d from %s\n", file_no, dir);
2303                         if (is_dir_exist(dir_name)) {
2304                                 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2305                                 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2306                                         FILE_OP_ERROR(dot_file, "unlink");
2307                                 }
2308                                 g_free(dot_file);
2309                                 continue;
2310                         }
2311                         if (claws_unlink(dir_name) < 0)
2312                                 FILE_OP_ERROR(dir_name, "unlink");
2313                 }
2314         }
2315
2316         g_dir_close(dp);
2317         g_hash_table_destroy(wanted_files);
2318
2319         if (g_chdir(prev_dir) < 0) {
2320                 FILE_OP_ERROR(prev_dir, "chdir");
2321                 g_free(prev_dir);
2322                 return -1;
2323         }
2324
2325         g_free(prev_dir);
2326
2327         return 0;
2328 }
2329
2330 gint remove_all_numbered_files(const gchar *dir)
2331 {
2332         return remove_numbered_files(dir, 0, UINT_MAX);
2333 }
2334
2335 gint remove_dir_recursive(const gchar *dir)
2336 {
2337         GStatBuf s;
2338         GDir *dp;
2339         const gchar *dir_name;
2340         gchar *prev_dir;
2341
2342         if (g_stat(dir, &s) < 0) {
2343                 FILE_OP_ERROR(dir, "stat");
2344                 if (ENOENT == errno) return 0;
2345                 return -(errno);
2346         }
2347
2348         if (!S_ISDIR(s.st_mode)) {
2349                 if (claws_unlink(dir) < 0) {
2350                         FILE_OP_ERROR(dir, "unlink");
2351                         return -(errno);
2352                 }
2353
2354                 return 0;
2355         }
2356
2357         prev_dir = g_get_current_dir();
2358         /* g_print("prev_dir = %s\n", prev_dir); */
2359
2360         if (!path_cmp(prev_dir, dir)) {
2361                 g_free(prev_dir);
2362                 if (g_chdir("..") < 0) {
2363                         FILE_OP_ERROR(dir, "chdir");
2364                         return -(errno);
2365                 }
2366                 prev_dir = g_get_current_dir();
2367         }
2368
2369         if (g_chdir(dir) < 0) {
2370                 FILE_OP_ERROR(dir, "chdir");
2371                 g_free(prev_dir);
2372                 return -(errno);
2373         }
2374
2375         if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2376                 g_warning("failed to open directory: %s", dir);
2377                 g_chdir(prev_dir);
2378                 g_free(prev_dir);
2379                 return -(errno);
2380         }
2381
2382         /* remove all files in the directory */
2383         while ((dir_name = g_dir_read_name(dp)) != NULL) {
2384                 /* g_print("removing %s\n", dir_name); */
2385
2386                 if (is_dir_exist(dir_name)) {
2387                         gint ret;
2388
2389                         if ((ret = remove_dir_recursive(dir_name)) < 0) {
2390                                 g_warning("can't remove directory: %s", dir_name);
2391                                 return ret;
2392                         }
2393                 } else {
2394                         if (claws_unlink(dir_name) < 0)
2395                                 FILE_OP_ERROR(dir_name, "unlink");
2396                 }
2397         }
2398
2399         g_dir_close(dp);
2400
2401         if (g_chdir(prev_dir) < 0) {
2402                 FILE_OP_ERROR(prev_dir, "chdir");
2403                 g_free(prev_dir);
2404                 return -(errno);
2405         }
2406
2407         g_free(prev_dir);
2408
2409         if (g_rmdir(dir) < 0) {
2410                 FILE_OP_ERROR(dir, "rmdir");
2411                 return -(errno);
2412         }
2413
2414         return 0;
2415 }
2416
2417 gint rename_force(const gchar *oldpath, const gchar *newpath)
2418 {
2419 #ifndef G_OS_UNIX
2420         if (!is_file_entry_exist(oldpath)) {
2421                 errno = ENOENT;
2422                 return -1;
2423         }
2424         if (is_file_exist(newpath)) {
2425                 if (claws_unlink(newpath) < 0)
2426                         FILE_OP_ERROR(newpath, "unlink");
2427         }
2428 #endif
2429         return g_rename(oldpath, newpath);
2430 }
2431
2432 /*
2433  * Append src file body to the tail of dest file.
2434  * Now keep_backup has no effects.
2435  */
2436 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2437 {
2438         FILE *src_fp, *dest_fp;
2439         gint n_read;
2440         gchar buf[BUFSIZ];
2441
2442         gboolean err = FALSE;
2443
2444         if ((src_fp = g_fopen(src, "rb")) == NULL) {
2445                 FILE_OP_ERROR(src, "g_fopen");
2446                 return -1;
2447         }
2448
2449         if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2450                 FILE_OP_ERROR(dest, "g_fopen");
2451                 fclose(src_fp);
2452                 return -1;
2453         }
2454
2455         if (change_file_mode_rw(dest_fp, dest) < 0) {
2456                 FILE_OP_ERROR(dest, "chmod");
2457                 g_warning("can't change file mode: %s", dest);
2458         }
2459
2460         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2461                 if (n_read < sizeof(buf) && ferror(src_fp))
2462                         break;
2463                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2464                         g_warning("writing to %s failed.", dest);
2465                         fclose(dest_fp);
2466                         fclose(src_fp);
2467                         claws_unlink(dest);
2468                         return -1;
2469                 }
2470         }
2471
2472         if (ferror(src_fp)) {
2473                 FILE_OP_ERROR(src, "fread");
2474                 err = TRUE;
2475         }
2476         fclose(src_fp);
2477         if (fclose(dest_fp) == EOF) {
2478                 FILE_OP_ERROR(dest, "fclose");
2479                 err = TRUE;
2480         }
2481
2482         if (err) {
2483                 claws_unlink(dest);
2484                 return -1;
2485         }
2486
2487         return 0;
2488 }
2489
2490 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2491 {
2492         FILE *src_fp, *dest_fp;
2493         gint n_read;
2494         gchar buf[BUFSIZ];
2495         gchar *dest_bak = NULL;
2496         gboolean err = FALSE;
2497
2498         if ((src_fp = g_fopen(src, "rb")) == NULL) {
2499                 FILE_OP_ERROR(src, "g_fopen");
2500                 return -1;
2501         }
2502         if (is_file_exist(dest)) {
2503                 dest_bak = g_strconcat(dest, ".bak", NULL);
2504                 if (rename_force(dest, dest_bak) < 0) {
2505                         FILE_OP_ERROR(dest, "rename");
2506                         fclose(src_fp);
2507                         g_free(dest_bak);
2508                         return -1;
2509                 }
2510         }
2511
2512         if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2513                 FILE_OP_ERROR(dest, "g_fopen");
2514                 fclose(src_fp);
2515                 if (dest_bak) {
2516                         if (rename_force(dest_bak, dest) < 0)
2517                                 FILE_OP_ERROR(dest_bak, "rename");
2518                         g_free(dest_bak);
2519                 }
2520                 return -1;
2521         }
2522
2523         if (change_file_mode_rw(dest_fp, dest) < 0) {
2524                 FILE_OP_ERROR(dest, "chmod");
2525                 g_warning("can't change file mode: %s", dest);
2526         }
2527
2528         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2529                 if (n_read < sizeof(buf) && ferror(src_fp))
2530                         break;
2531                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2532                         g_warning("writing to %s failed.", dest);
2533                         fclose(dest_fp);
2534                         fclose(src_fp);
2535                         claws_unlink(dest);
2536                         if (dest_bak) {
2537                                 if (rename_force(dest_bak, dest) < 0)
2538                                         FILE_OP_ERROR(dest_bak, "rename");
2539                                 g_free(dest_bak);
2540                         }
2541                         return -1;
2542                 }
2543         }
2544
2545         if (ferror(src_fp)) {
2546                 FILE_OP_ERROR(src, "fread");
2547                 err = TRUE;
2548         }
2549         fclose(src_fp);
2550         if (fclose(dest_fp) == EOF) {
2551                 FILE_OP_ERROR(dest, "fclose");
2552                 err = TRUE;
2553         }
2554
2555         if (err) {
2556                 claws_unlink(dest);
2557                 if (dest_bak) {
2558                         if (rename_force(dest_bak, dest) < 0)
2559                                 FILE_OP_ERROR(dest_bak, "rename");
2560                         g_free(dest_bak);
2561                 }
2562                 return -1;
2563         }
2564
2565         if (keep_backup == FALSE && dest_bak)
2566                 claws_unlink(dest_bak);
2567
2568         g_free(dest_bak);
2569
2570         return 0;
2571 }
2572
2573 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2574 {
2575         if (overwrite == FALSE && is_file_exist(dest)) {
2576                 g_warning("move_file(): file %s already exists.", dest);
2577                 return -1;
2578         }
2579
2580         if (rename_force(src, dest) == 0) return 0;
2581
2582         if (EXDEV != errno) {
2583                 FILE_OP_ERROR(src, "rename");
2584                 return -1;
2585         }
2586
2587         if (copy_file(src, dest, FALSE) < 0) return -1;
2588
2589         claws_unlink(src);
2590
2591         return 0;
2592 }
2593
2594 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2595 {
2596         gint n_read;
2597         gint bytes_left, to_read;
2598         gchar buf[BUFSIZ];
2599
2600         if (fseek(fp, offset, SEEK_SET) < 0) {
2601                 perror("fseek");
2602                 return -1;
2603         }
2604
2605         bytes_left = length;
2606         to_read = MIN(bytes_left, sizeof(buf));
2607
2608         while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2609                 if (n_read < to_read && ferror(fp))
2610                         break;
2611                 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2612                         return -1;
2613                 }
2614                 bytes_left -= n_read;
2615                 if (bytes_left == 0)
2616                         break;
2617                 to_read = MIN(bytes_left, sizeof(buf));
2618         }
2619
2620         if (ferror(fp)) {
2621                 perror("fread");
2622                 return -1;
2623         }
2624
2625         return 0;
2626 }
2627
2628 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2629 {
2630         FILE *dest_fp;
2631         gboolean err = FALSE;
2632
2633         if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2634                 FILE_OP_ERROR(dest, "g_fopen");
2635                 return -1;
2636         }
2637
2638         if (change_file_mode_rw(dest_fp, dest) < 0) {
2639                 FILE_OP_ERROR(dest, "chmod");
2640                 g_warning("can't change file mode: %s", dest);
2641         }
2642
2643         if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2644                 err = TRUE;
2645
2646         if (!err && fclose(dest_fp) == EOF) {
2647                 FILE_OP_ERROR(dest, "fclose");
2648                 err = TRUE;
2649         }
2650
2651         if (err) {
2652                 g_warning("writing to %s failed.", dest);
2653                 claws_unlink(dest);
2654                 return -1;
2655         }
2656
2657         return 0;
2658 }
2659
2660 /* convert line endings into CRLF. If the last line doesn't end with
2661  * linebreak, add it.
2662  */
2663 gchar *canonicalize_str(const gchar *str)
2664 {
2665         const gchar *p;
2666         guint new_len = 0;
2667         gchar *out, *outp;
2668
2669         for (p = str; *p != '\0'; ++p) {
2670                 if (*p != '\r') {
2671                         ++new_len;
2672                         if (*p == '\n')
2673                                 ++new_len;
2674                 }
2675         }
2676         if (p == str || *(p - 1) != '\n')
2677                 new_len += 2;
2678
2679         out = outp = g_malloc(new_len + 1);
2680         for (p = str; *p != '\0'; ++p) {
2681                 if (*p != '\r') {
2682                         if (*p == '\n')
2683                                 *outp++ = '\r';
2684                         *outp++ = *p;
2685                 }
2686         }
2687         if (p == str || *(p - 1) != '\n') {
2688                 *outp++ = '\r';
2689                 *outp++ = '\n';
2690         }
2691         *outp = '\0';
2692
2693         return out;
2694 }
2695
2696 gint canonicalize_file(const gchar *src, const gchar *dest)
2697 {
2698         FILE *src_fp, *dest_fp;
2699         gchar buf[BUFFSIZE];
2700         gint len;
2701         gboolean err = FALSE;
2702         gboolean last_linebreak = FALSE;
2703
2704         if (src == NULL || dest == NULL)
2705                 return -1;
2706
2707         if ((src_fp = g_fopen(src, "rb")) == NULL) {
2708                 FILE_OP_ERROR(src, "g_fopen");
2709                 return -1;
2710         }
2711
2712         if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2713                 FILE_OP_ERROR(dest, "g_fopen");
2714                 fclose(src_fp);
2715                 return -1;
2716         }
2717
2718         if (change_file_mode_rw(dest_fp, dest) < 0) {
2719                 FILE_OP_ERROR(dest, "chmod");
2720                 g_warning("can't change file mode: %s", dest);
2721         }
2722
2723         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2724                 gint r = 0;
2725
2726                 len = strlen(buf);
2727                 if (len == 0) break;
2728                 last_linebreak = FALSE;
2729
2730                 if (buf[len - 1] != '\n') {
2731                         last_linebreak = TRUE;
2732                         r = fputs(buf, dest_fp);
2733                 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2734                         r = fputs(buf, dest_fp);
2735                 } else {
2736                         if (len > 1) {
2737                                 r = fwrite(buf, 1, len - 1, dest_fp);
2738                                 if (r != (len -1))
2739                                         r = EOF;
2740                         }
2741                         if (r != EOF)
2742                                 r = fputs("\r\n", dest_fp);
2743                 }
2744
2745                 if (r == EOF) {
2746                         g_warning("writing to %s failed.", dest);
2747                         fclose(dest_fp);
2748                         fclose(src_fp);
2749                         claws_unlink(dest);
2750                         return -1;
2751                 }
2752         }
2753
2754         if (last_linebreak == TRUE) {
2755                 if (fputs("\r\n", dest_fp) == EOF)
2756                         err = TRUE;
2757         }
2758
2759         if (ferror(src_fp)) {
2760                 FILE_OP_ERROR(src, "fgets");
2761                 err = TRUE;
2762         }
2763         fclose(src_fp);
2764         if (fclose(dest_fp) == EOF) {
2765                 FILE_OP_ERROR(dest, "fclose");
2766                 err = TRUE;
2767         }
2768
2769         if (err) {
2770                 claws_unlink(dest);
2771                 return -1;
2772         }
2773
2774         return 0;
2775 }
2776
2777 gint canonicalize_file_replace(const gchar *file)
2778 {
2779         gchar *tmp_file;
2780
2781         tmp_file = get_tmp_file();
2782
2783         if (canonicalize_file(file, tmp_file) < 0) {
2784                 g_free(tmp_file);
2785                 return -1;
2786         }
2787
2788         if (move_file(tmp_file, file, TRUE) < 0) {
2789                 g_warning("can't replace file: %s", file);
2790                 claws_unlink(tmp_file);
2791                 g_free(tmp_file);
2792                 return -1;
2793         }
2794
2795         g_free(tmp_file);
2796         return 0;
2797 }
2798
2799 gchar *normalize_newlines(const gchar *str)
2800 {
2801         const gchar *p;
2802         gchar *out, *outp;
2803
2804         out = outp = g_malloc(strlen(str) + 1);
2805         for (p = str; *p != '\0'; ++p) {
2806                 if (*p == '\r') {
2807                         if (*(p + 1) != '\n')
2808                                 *outp++ = '\n';
2809                 } else
2810                         *outp++ = *p;
2811         }
2812
2813         *outp = '\0';
2814
2815         return out;
2816 }
2817
2818 gchar *get_outgoing_rfc2822_str(FILE *fp)
2819 {
2820         gchar buf[BUFFSIZE];
2821         GString *str;
2822         gchar *ret;
2823
2824         str = g_string_new(NULL);
2825
2826         /* output header part */
2827         while (fgets(buf, sizeof(buf), fp) != NULL) {
2828                 strretchomp(buf);
2829                 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2830                         gint next;
2831
2832                         for (;;) {
2833                                 next = fgetc(fp);
2834                                 if (next == EOF)
2835                                         break;
2836                                 else if (next != ' ' && next != '\t') {
2837                                         ungetc(next, fp);
2838                                         break;
2839                                 }
2840                                 if (fgets(buf, sizeof(buf), fp) == NULL)
2841                                         break;
2842                         }
2843                 } else {
2844                         g_string_append(str, buf);
2845                         g_string_append(str, "\r\n");
2846                         if (buf[0] == '\0')
2847                                 break;
2848                 }
2849         }
2850
2851         /* output body part */
2852         while (fgets(buf, sizeof(buf), fp) != NULL) {
2853                 strretchomp(buf);
2854                 if (buf[0] == '.')
2855                         g_string_append_c(str, '.');
2856                 g_string_append(str, buf);
2857                 g_string_append(str, "\r\n");
2858         }
2859
2860         ret = str->str;
2861         g_string_free(str, FALSE);
2862
2863         return ret;
2864 }
2865
2866 /*
2867  * Create a new boundary in a way that it is very unlikely that this
2868  * will occur in the following text.  It would be easy to ensure
2869  * uniqueness if everything is either quoted-printable or base64
2870  * encoded (note that conversion is allowed), but because MIME bodies
2871  * may be nested, it may happen that the same boundary has already
2872  * been used.
2873  *
2874  *   boundary := 0*69<bchars> bcharsnospace
2875  *   bchars := bcharsnospace / " "
2876  *   bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2877  *                  "+" / "_" / "," / "-" / "." /
2878  *                  "/" / ":" / "=" / "?"
2879  *
2880  * some special characters removed because of buggy MTAs
2881  */
2882
2883 gchar *generate_mime_boundary(const gchar *prefix)
2884 {
2885         static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2886                              "abcdefghijklmnopqrstuvwxyz"
2887                              "1234567890+_./=";
2888         gchar buf_uniq[24];
2889         gint i;
2890
2891         for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2892                 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2893         buf_uniq[i] = '\0';
2894
2895         return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2896                                buf_uniq);
2897 }
2898
2899 gint change_file_mode_rw(FILE *fp, const gchar *file)
2900 {
2901 #if HAVE_FCHMOD
2902         return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2903 #else
2904         return g_chmod(file, S_IRUSR|S_IWUSR);
2905 #endif
2906 }
2907
2908 FILE *my_tmpfile(void)
2909 {
2910         const gchar suffix[] = ".XXXXXX";
2911         const gchar *tmpdir;
2912         guint tmplen;
2913         const gchar *progname;
2914         guint proglen;
2915         gchar *fname;
2916         gint fd;
2917         FILE *fp;
2918 #ifndef G_OS_WIN32
2919         gchar buf[2]="\0";
2920 #endif
2921
2922         tmpdir = get_tmp_dir();
2923         tmplen = strlen(tmpdir);
2924         progname = g_get_prgname();
2925         if (progname == NULL)
2926                 progname = "claws-mail";
2927         proglen = strlen(progname);
2928         Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2929                 return tmpfile());
2930
2931         memcpy(fname, tmpdir, tmplen);
2932         fname[tmplen] = G_DIR_SEPARATOR;
2933         memcpy(fname + tmplen + 1, progname, proglen);
2934         memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2935
2936         fd = g_mkstemp(fname);
2937         if (fd < 0)
2938                 return tmpfile();
2939
2940 #ifndef G_OS_WIN32
2941         claws_unlink(fname);
2942         
2943         /* verify that we can write in the file after unlinking */
2944         if (write(fd, buf, 1) < 0) {
2945                 close(fd);
2946                 return tmpfile();
2947         }
2948         
2949 #endif
2950
2951         fp = fdopen(fd, "w+b");
2952         if (!fp)
2953                 close(fd);
2954         else {
2955                 rewind(fp);
2956                 return fp;
2957         }
2958
2959         return tmpfile();
2960 }
2961
2962 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2963 {
2964         int fd;
2965         *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
2966         fd = g_mkstemp(*filename);
2967         if (fd < 0)
2968                 return NULL;
2969         return fdopen(fd, "w+");
2970 }
2971
2972 FILE *str_open_as_stream(const gchar *str)
2973 {
2974         FILE *fp;
2975         size_t len;
2976
2977         cm_return_val_if_fail(str != NULL, NULL);
2978
2979         fp = my_tmpfile();
2980         if (!fp) {
2981                 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2982                 return NULL;
2983         }
2984
2985         len = strlen(str);
2986         if (len == 0) return fp;
2987
2988         if (fwrite(str, 1, len, fp) != len) {
2989                 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2990                 fclose(fp);
2991                 return NULL;
2992         }
2993
2994         rewind(fp);
2995         return fp;
2996 }
2997
2998 gint str_write_to_file(const gchar *str, const gchar *file)
2999 {
3000         FILE *fp;
3001         size_t len;
3002
3003         cm_return_val_if_fail(str != NULL, -1);
3004         cm_return_val_if_fail(file != NULL, -1);
3005
3006         if ((fp = g_fopen(file, "wb")) == NULL) {
3007                 FILE_OP_ERROR(file, "g_fopen");
3008                 return -1;
3009         }
3010
3011         len = strlen(str);
3012         if (len == 0) {
3013                 fclose(fp);
3014                 return 0;
3015         }
3016
3017         if (fwrite(str, 1, len, fp) != len) {
3018                 FILE_OP_ERROR(file, "fwrite");
3019                 fclose(fp);
3020                 claws_unlink(file);
3021                 return -1;
3022         }
3023
3024         if (fclose(fp) == EOF) {
3025                 FILE_OP_ERROR(file, "fclose");
3026                 claws_unlink(file);
3027                 return -1;
3028         }
3029
3030         return 0;
3031 }
3032
3033 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3034 {
3035         GByteArray *array;
3036         guchar buf[BUFSIZ];
3037         gint n_read;
3038         gchar *str;
3039
3040         cm_return_val_if_fail(fp != NULL, NULL);
3041
3042         array = g_byte_array_new();
3043
3044         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3045                 if (n_read < sizeof(buf) && ferror(fp))
3046                         break;
3047                 g_byte_array_append(array, buf, n_read);
3048         }
3049
3050         if (ferror(fp)) {
3051                 FILE_OP_ERROR("file stream", "fread");
3052                 g_byte_array_free(array, TRUE);
3053                 return NULL;
3054         }
3055
3056         buf[0] = '\0';
3057         g_byte_array_append(array, buf, 1);
3058         str = (gchar *)array->data;
3059         g_byte_array_free(array, FALSE);
3060
3061         if (recode && !g_utf8_validate(str, -1, NULL)) {
3062                 const gchar *src_codeset, *dest_codeset;
3063                 gchar *tmp = NULL;
3064                 src_codeset = conv_get_locale_charset_str();
3065                 dest_codeset = CS_UTF_8;
3066                 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3067                 g_free(str);
3068                 str = tmp;
3069         }
3070
3071         return str;
3072 }
3073
3074 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3075 {
3076         FILE *fp;
3077         gchar *str;
3078         GStatBuf s;
3079 #ifndef G_OS_WIN32
3080         gint fd, err;
3081         struct timeval timeout = {1, 0};
3082         fd_set fds;
3083         int fflags = 0;
3084 #endif
3085
3086         cm_return_val_if_fail(file != NULL, NULL);
3087
3088         if (g_stat(file, &s) != 0) {
3089                 FILE_OP_ERROR(file, "stat");
3090                 return NULL;
3091         }
3092         if (S_ISDIR(s.st_mode)) {
3093                 g_warning("%s: is a directory", file);
3094                 return NULL;
3095         }
3096
3097 #ifdef G_OS_WIN32
3098         fp = g_fopen (file, "rb");
3099         if (fp == NULL) {
3100                 FILE_OP_ERROR(file, "open");
3101                 return NULL;
3102         }
3103 #else     
3104         /* test whether the file is readable without blocking */
3105         fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3106         if (fd == -1) {
3107                 FILE_OP_ERROR(file, "open");
3108                 return NULL;
3109         }
3110
3111         FD_ZERO(&fds);
3112         FD_SET(fd, &fds);
3113
3114         /* allow for one second */
3115         err = select(fd+1, &fds, NULL, NULL, &timeout);
3116         if (err <= 0 || !FD_ISSET(fd, &fds)) {
3117                 if (err < 0) {
3118                         FILE_OP_ERROR(file, "select");
3119                 } else {
3120                         g_warning("%s: doesn't seem readable", file);
3121                 }
3122                 close(fd);
3123                 return NULL;
3124         }
3125         
3126         /* Now clear O_NONBLOCK */
3127         if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3128                 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3129                 close(fd);
3130                 return NULL;
3131         }
3132         if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3133                 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3134                 close(fd);
3135                 return NULL;
3136         }
3137         
3138         /* get the FILE pointer */
3139         fp = fdopen(fd, "rb");
3140
3141         if (fp == NULL) {
3142                 FILE_OP_ERROR(file, "fdopen");
3143                 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3144                 return NULL;
3145         }
3146 #endif
3147
3148         str = file_read_stream_to_str_full(fp, recode);
3149
3150         fclose(fp);
3151
3152         return str;
3153 }
3154
3155 gchar *file_read_to_str(const gchar *file)
3156 {
3157         return file_read_to_str_full(file, TRUE);
3158 }
3159 gchar *file_read_stream_to_str(FILE *fp)
3160 {
3161         return file_read_stream_to_str_full(fp, TRUE);
3162 }
3163
3164 gchar *file_read_to_str_no_recode(const gchar *file)
3165 {
3166         return file_read_to_str_full(file, FALSE);
3167 }
3168 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3169 {
3170         return file_read_stream_to_str_full(fp, FALSE);
3171 }
3172
3173 char *fgets_crlf(char *buf, int size, FILE *stream)
3174 {
3175         gboolean is_cr = FALSE;
3176         gboolean last_was_cr = FALSE;
3177         int c = 0;
3178         char *cs;
3179
3180         cs = buf;
3181         while (--size > 0 && (c = getc(stream)) != EOF)
3182         {
3183                 *cs++ = c;
3184                 is_cr = (c == '\r');
3185                 if (c == '\n') {
3186                         break;
3187                 }
3188                 if (last_was_cr) {
3189                         *(--cs) = '\n';
3190                         cs++;
3191                         ungetc(c, stream);
3192                         break;
3193                 }
3194                 last_was_cr = is_cr;
3195         }
3196         if (c == EOF && cs == buf)
3197                 return NULL;
3198
3199         *cs = '\0';
3200
3201         return buf;     
3202 }
3203
3204 static gint execute_async(gchar *const argv[], const gchar *working_directory)
3205 {
3206         cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3207
3208         if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3209                           NULL, NULL, NULL, FALSE) == FALSE) {
3210                 g_warning("couldn't execute command: %s", argv[0]);
3211                 return -1;
3212         }
3213
3214         return 0;
3215 }
3216
3217 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
3218 {
3219         gint status;
3220
3221         cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3222
3223 #ifdef G_OS_UNIX
3224         if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3225                          NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3226                 g_warning("couldn't execute command: %s", argv[0]);
3227                 return -1;
3228         }
3229
3230         if (WIFEXITED(status))
3231                 return WEXITSTATUS(status);
3232         else
3233                 return -1;
3234 #else
3235         if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
3236                                 G_SPAWN_SEARCH_PATH|
3237                                 G_SPAWN_CHILD_INHERITS_STDIN|
3238                                 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3239                          NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3240                 g_warning("couldn't execute command: %s", argv[0]);
3241                 return -1;
3242         }
3243
3244         return status;
3245 #endif
3246 }
3247
3248 gint execute_command_line(const gchar *cmdline, gboolean async,
3249                 const gchar *working_directory)
3250 {
3251         gchar **argv;
3252         gint ret;
3253
3254         debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3255
3256         argv = strsplit_with_quote(cmdline, " ", 0);
3257
3258         if (async)
3259                 ret = execute_async(argv, working_directory);
3260         else
3261                 ret = execute_sync(argv, working_directory);
3262
3263         g_strfreev(argv);
3264
3265         return ret;
3266 }
3267
3268 gchar *get_command_output(const gchar *cmdline)
3269 {
3270         gchar *child_stdout;
3271         gint status;
3272
3273         cm_return_val_if_fail(cmdline != NULL, NULL);
3274
3275         debug_print("get_command_output(): executing: %s\n", cmdline);
3276
3277         if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3278                                       NULL) == FALSE) {
3279                 g_warning("couldn't execute command: %s", cmdline);
3280                 return NULL;
3281         }
3282
3283         return child_stdout;
3284 }
3285
3286 static gint is_unchanged_uri_char(char c)
3287 {
3288         switch (c) {
3289                 case '(':
3290                 case ')':
3291                         return 0;
3292                 default:
3293                         return 1;
3294         }
3295 }
3296
3297 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3298 {
3299         int i;
3300         int k;
3301
3302         k = 0;
3303         for(i = 0; i < strlen(uri) ; i++) {
3304                 if (is_unchanged_uri_char(uri[i])) {
3305                         if (k + 2 >= bufsize)
3306                                 break;
3307                         encoded_uri[k++] = uri[i];
3308                 }
3309                 else {
3310                         char * hexa = "0123456789ABCDEF";
3311
3312                         if (k + 4 >= bufsize)
3313                                 break;
3314                         encoded_uri[k++] = '%';
3315                         encoded_uri[k++] = hexa[uri[i] / 16];
3316                         encoded_uri[k++] = hexa[uri[i] % 16];
3317                 }
3318         }
3319         encoded_uri[k] = 0;
3320 }
3321
3322 gint open_uri(const gchar *uri, const gchar *cmdline)
3323 {
3324
3325 #ifndef G_OS_WIN32
3326         gchar buf[BUFFSIZE];
3327         gchar *p;
3328         gchar encoded_uri[BUFFSIZE];
3329         cm_return_val_if_fail(uri != NULL, -1);
3330
3331         /* an option to choose whether to use encode_uri or not ? */
3332         encode_uri(encoded_uri, BUFFSIZE, uri);
3333
3334         if (cmdline &&
3335             (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3336             !strchr(p + 2, '%'))
3337                 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3338         else {
3339                 if (cmdline)
3340                         g_warning("Open URI command-line is invalid "
3341                                   "(there must be only one '%%s'): %s",
3342                                   cmdline);
3343                 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3344         }
3345
3346         execute_command_line(buf, TRUE, NULL);
3347 #else
3348         ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3349 #endif
3350         return 0;
3351 }
3352
3353 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3354 {
3355         gchar buf[BUFFSIZE];
3356         gchar *p;
3357
3358         cm_return_val_if_fail(filepath != NULL, -1);
3359
3360         if (cmdline &&
3361             (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3362             !strchr(p + 2, '%'))
3363                 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3364         else {
3365                 if (cmdline)
3366                         g_warning("Open Text Editor command-line is invalid "
3367                                   "(there must be only one '%%s'): %s",
3368                                   cmdline);
3369                 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3370         }
3371
3372         execute_command_line(buf, TRUE, NULL);
3373
3374         return 0;
3375 }
3376
3377 time_t remote_tzoffset_sec(const gchar *zone)
3378 {
3379         static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3380         gchar zone3[4];
3381         gchar *p;
3382         gchar c;
3383         gint iustz;
3384         gint offset;
3385         time_t remoteoffset;
3386
3387         strncpy(zone3, zone, 3);
3388         zone3[3] = '\0';
3389         remoteoffset = 0;
3390
3391         if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3392             (c == '+' || c == '-')) {
3393                 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3394                 if (c == '-')
3395                         remoteoffset = -remoteoffset;
3396         } else if (!strncmp(zone, "UT" , 2) ||
3397                    !strncmp(zone, "GMT", 3)) {
3398                 remoteoffset = 0;
3399         } else if (strlen(zone3) == 3) {
3400                 for (p = ustzstr; *p != '\0'; p += 3) {
3401                         if (!g_ascii_strncasecmp(p, zone3, 3)) {
3402                                 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3403                                 remoteoffset = iustz * 3600;
3404                                 break;
3405                         }
3406                 }
3407                 if (*p == '\0')
3408                         return -1;
3409         } else if (strlen(zone3) == 1) {
3410                 switch (zone[0]) {
3411                 case 'Z': remoteoffset =   0; break;
3412                 case 'A': remoteoffset =  -1; break;
3413                 case 'B': remoteoffset =  -2; break;
3414                 case 'C': remoteoffset =  -3; break;
3415                 case 'D': remoteoffset =  -4; break;
3416                 case 'E': remoteoffset =  -5; break;
3417                 case 'F': remoteoffset =  -6; break;
3418                 case 'G': remoteoffset =  -7; break;
3419                 case 'H': remoteoffset =  -8; break;
3420                 case 'I': remoteoffset =  -9; break;
3421                 case 'K': remoteoffset = -10; break; /* J is not used */
3422                 case 'L': remoteoffset = -11; break;
3423                 case 'M': remoteoffset = -12; break;
3424                 case 'N': remoteoffset =   1; break;
3425                 case 'O': remoteoffset =   2; break;
3426                 case 'P': remoteoffset =   3; break;
3427                 case 'Q': remoteoffset =   4; break;
3428                 case 'R': remoteoffset =   5; break;
3429                 case 'S': remoteoffset =   6; break;
3430                 case 'T': remoteoffset =   7; break;
3431                 case 'U': remoteoffset =   8; break;
3432                 case 'V': remoteoffset =   9; break;
3433                 case 'W': remoteoffset =  10; break;
3434                 case 'X': remoteoffset =  11; break;
3435                 case 'Y': remoteoffset =  12; break;
3436                 default:  remoteoffset =   0; break;
3437                 }
3438                 remoteoffset = remoteoffset * 3600;
3439         } else
3440                 return -1;
3441
3442         return remoteoffset;
3443 }
3444
3445 time_t tzoffset_sec(time_t *now)
3446 {
3447         struct tm gmt, *lt;
3448         gint off;
3449         struct tm buf1, buf2;
3450 #ifdef G_OS_WIN32
3451         if (now && *now < 0)
3452                 return 0;
3453 #endif  
3454         gmt = *gmtime_r(now, &buf1);
3455         lt = localtime_r(now, &buf2);
3456
3457         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3458
3459         if (lt->tm_year < gmt.tm_year)
3460                 off -= 24 * 60;
3461         else if (lt->tm_year > gmt.tm_year)
3462                 off += 24 * 60;
3463         else if (lt->tm_yday < gmt.tm_yday)
3464                 off -= 24 * 60;
3465         else if (lt->tm_yday > gmt.tm_yday)
3466                 off += 24 * 60;
3467
3468         if (off >= 24 * 60)             /* should be impossible */
3469                 off = 23 * 60 + 59;     /* if not, insert silly value */
3470         if (off <= -24 * 60)
3471                 off = -(23 * 60 + 59);
3472
3473         return off * 60;
3474 }
3475
3476 /* calculate timezone offset */
3477 gchar *tzoffset(time_t *now)
3478 {
3479         static gchar offset_string[6];
3480         struct tm gmt, *lt;
3481         gint off;
3482         gchar sign = '+';
3483         struct tm buf1, buf2;
3484 #ifdef G_OS_WIN32
3485         if (now && *now < 0)
3486                 return 0;
3487 #endif
3488         gmt = *gmtime_r(now, &buf1);
3489         lt = localtime_r(now, &buf2);
3490
3491         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3492
3493         if (lt->tm_year < gmt.tm_year)
3494                 off -= 24 * 60;
3495         else if (lt->tm_year > gmt.tm_year)
3496                 off += 24 * 60;
3497         else if (lt->tm_yday < gmt.tm_yday)
3498                 off -= 24 * 60;
3499         else if (lt->tm_yday > gmt.tm_yday)
3500                 off += 24 * 60;
3501
3502         if (off < 0) {
3503                 sign = '-';
3504                 off = -off;
3505         }
3506
3507         if (off >= 24 * 60)             /* should be impossible */
3508                 off = 23 * 60 + 59;     /* if not, insert silly value */
3509
3510         sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3511
3512         return offset_string;
3513 }
3514
3515 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
3516 {
3517         struct tm *lt;
3518         time_t t;
3519         gchar day[4], mon[4];
3520         gint dd, hh, mm, ss, yyyy;
3521         struct tm buf1;
3522         gchar buf2[RFC822_DATE_BUFFSIZE];
3523
3524         t = time(NULL);
3525         if (hidetz)
3526                 lt = gmtime_r(&t, &buf1);
3527         else
3528                 lt = localtime_r(&t, &buf1);
3529
3530         if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
3531                day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
3532                 g_warning("failed reading date/time");
3533
3534         g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3535                    day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
3536 }
3537
3538 void get_rfc822_date(gchar *buf, gint len)
3539 {
3540         _get_rfc822_date(buf, len, FALSE);
3541 }
3542
3543 void get_rfc822_date_hide_tz(gchar *buf, gint len)
3544 {
3545         _get_rfc822_date(buf, len, TRUE);
3546 }
3547
3548 void debug_set_mode(gboolean mode)
3549 {
3550         debug_mode = mode;
3551 }
3552
3553 gboolean debug_get_mode(void)
3554 {
3555         return debug_mode;
3556 }
3557
3558 void debug_print_real(const gchar *format, ...)
3559 {
3560         va_list args;
3561         gchar buf[BUFFSIZE];
3562
3563         if (!debug_mode) return;
3564
3565         va_start(args, format);
3566         g_vsnprintf(buf, sizeof(buf), format, args);
3567         va_end(args);
3568
3569         g_print("%s", buf);
3570 }
3571
3572
3573 const char * debug_srcname(const char *file)
3574 {
3575         const char *s = strrchr (file, '/');
3576         return s? s+1:file;
3577 }
3578
3579
3580 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3581 {
3582         if (subject == NULL)
3583                 subject = "";
3584         else
3585                 subject += subject_get_prefix_length(subject);
3586
3587         return g_hash_table_lookup(subject_table, subject);
3588 }
3589
3590 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3591                           void * data)
3592 {
3593         if (subject == NULL || *subject == 0)
3594                 return;
3595         subject += subject_get_prefix_length(subject);
3596         g_hash_table_insert(subject_table, subject, data);
3597 }
3598
3599 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3600 {
3601         if (subject == NULL)
3602                 return;
3603
3604         subject += subject_get_prefix_length(subject);
3605         g_hash_table_remove(subject_table, subject);
3606 }
3607
3608 static regex_t u_regex;
3609 static gboolean u_init_;
3610
3611 void utils_free_regex(void)
3612 {
3613         if (u_init_) {
3614                 regfree(&u_regex);
3615                 u_init_ = FALSE;
3616         }
3617 }
3618
3619 /*!
3620  *\brief        Check if a string is prefixed with known (combinations)
3621  *              of prefixes. The function assumes that each prefix
3622  *              is terminated by zero or exactly _one_ space.
3623  *
3624  *\param        str String to check for a prefixes
3625  *
3626  *\return       int Number of chars in the prefix that should be skipped
3627  *              for a "clean" subject line. If no prefix was found, 0
3628  *              is returned.
3629  */
3630 int subject_get_prefix_length(const gchar *subject)
3631 {
3632         /*!< Array with allowable reply prefixes regexps. */
3633         static const gchar * const prefixes[] = {
3634                 "Re\\:",                        /* "Re:" */
3635                 "Re\\[[1-9][0-9]*\\]\\:",       /* "Re[XXX]:" (non-conforming news mail clients) */
3636                 "Antw\\:",                      /* "Antw:" (Dutch / German Outlook) */
3637                 "Aw\\:",                        /* "Aw:"   (German) */
3638                 "Antwort\\:",                   /* "Antwort:" (German Lotus Notes) */
3639                 "Res\\:",                       /* "Res:" (Spanish/Brazilian Outlook) */
3640                 "Fw\\:",                        /* "Fw:" Forward */
3641                 "Fwd\\:",                       /* "Fwd:" Forward */
3642                 "Enc\\:",                       /* "Enc:" Forward (Brazilian Outlook) */
3643                 "Odp\\:",                       /* "Odp:" Re (Polish Outlook) */
3644                 "Rif\\:",                       /* "Rif:" (Italian Outlook) */
3645                 "Sv\\:",                        /* "Sv" (Norwegian) */
3646                 "Vs\\:",                        /* "Vs" (Norwegian) */
3647                 "Ad\\:",                        /* "Ad" (Norwegian) */
3648                 "\347\255\224\345\244\215\\:",  /* "Re" (Chinese, UTF-8) */
3649                 "R\303\251f\\. \\:",            /* "R�f. :" (French Lotus Notes) */
3650                 "Re \\:",                       /* "Re :" (French Yahoo Mail) */
3651                 /* add more */
3652         };
3653         const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3654         int n;
3655         regmatch_t pos;
3656
3657         if (!subject) return 0;
3658         if (!*subject) return 0;
3659
3660         if (!u_init_) {
3661                 GString *s = g_string_new("");
3662
3663                 for (n = 0; n < PREFIXES; n++)
3664                         /* Terminate each prefix regexpression by a
3665                          * "\ ?" (zero or ONE space), and OR them */
3666                         g_string_append_printf(s, "(%s\\ ?)%s",
3667                                           prefixes[n],
3668                                           n < PREFIXES - 1 ?
3669                                           "|" : "");
3670
3671                 g_string_prepend(s, "(");
3672                 g_string_append(s, ")+");       /* match at least once */
3673                 g_string_prepend(s, "^\\ *");   /* from beginning of line */
3674
3675
3676                 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3677                  * TODO: Should this be       "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3678                 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3679                         debug_print("Error compiling regexp %s\n", s->str);
3680                         g_string_free(s, TRUE);
3681                         return 0;
3682                 } else {
3683                         u_init_ = TRUE;
3684                         g_string_free(s, TRUE);
3685                 }
3686         }
3687
3688         if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3689                 return pos.rm_eo;
3690         else
3691                 return 0;
3692 }
3693
3694 static guint g_stricase_hash(gconstpointer gptr)
3695 {
3696         guint hash_result = 0;
3697         const char *str;
3698
3699         for (str = gptr; str && *str; str++) {
3700                 hash_result += toupper(*str);
3701         }
3702
3703         return hash_result;
3704 }
3705
3706 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3707 {
3708         const char *str1 = gptr1;
3709         const char *str2 = gptr2;
3710
3711         return !strcasecmp(str1, str2);
3712 }
3713
3714 gint g_int_compare(gconstpointer a, gconstpointer b)
3715 {
3716         return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3717 }
3718
3719 /*
3720    quote_cmd_argument()
3721
3722    return a quoted string safely usable in argument of a command.
3723
3724    code is extracted and adapted from etPan! project -- DINH V. Ho�.
3725 */
3726
3727 gint quote_cmd_argument(gchar * result, guint size,
3728                         const gchar * path)
3729 {
3730         const gchar * p;
3731         gchar * result_p;
3732         guint remaining;
3733
3734         result_p = result;
3735         remaining = size;
3736
3737         for(p = path ; * p != '\0' ; p ++) {
3738
3739                 if (isalnum((guchar)*p) || (* p == '/')) {
3740                         if (remaining > 0) {
3741                                 * result_p = * p;
3742                                 result_p ++;
3743                                 remaining --;
3744                         }
3745                         else {
3746                                 result[size - 1] = '\0';
3747                                 return -1;
3748                         }
3749                 }
3750                 else {
3751                         if (remaining >= 2) {
3752                                 * result_p = '\\';
3753                                 result_p ++;
3754                                 * result_p = * p;
3755                                 result_p ++;
3756                                 remaining -= 2;
3757                         }
3758                         else {
3759                                 result[size - 1] = '\0';
3760                                 return -1;
3761                         }
3762                 }
3763         }
3764         if (remaining > 0) {
3765                 * result_p = '\0';
3766         }
3767         else {
3768                 result[size - 1] = '\0';
3769                 return -1;
3770         }
3771
3772         return 0;
3773 }
3774
3775 typedef struct
3776 {
3777         GNode           *parent;
3778         GNodeMapFunc     func;
3779         gpointer         data;
3780 } GNodeMapData;
3781
3782 static void g_node_map_recursive(GNode *node, gpointer data)
3783 {
3784         GNodeMapData *mapdata = (GNodeMapData *) data;
3785         GNode *newnode;
3786         GNodeMapData newmapdata;
3787         gpointer newdata;
3788
3789         newdata = mapdata->func(node->data, mapdata->data);
3790         if (newdata != NULL) {
3791                 newnode = g_node_new(newdata);
3792                 g_node_append(mapdata->parent, newnode);
3793
3794                 newmapdata.parent = newnode;
3795                 newmapdata.func = mapdata->func;
3796                 newmapdata.data = mapdata->data;
3797
3798                 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3799         }
3800 }
3801
3802 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3803 {
3804         GNode *root;
3805         GNodeMapData mapdata;
3806
3807         cm_return_val_if_fail(node != NULL, NULL);
3808         cm_return_val_if_fail(func != NULL, NULL);
3809
3810         root = g_node_new(func(node->data, data));
3811
3812         mapdata.parent = root;
3813         mapdata.func = func;
3814         mapdata.data = data;
3815
3816         g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3817
3818         return root;
3819 }
3820
3821 #define HEX_TO_INT(val, hex)                    \
3822 {                                               \
3823         gchar c = hex;                          \
3824                                                 \
3825         if ('0' <= c && c <= '9') {             \
3826                 val = c - '0';                  \
3827         } else if ('a' <= c && c <= 'f') {      \
3828                 val = c - 'a' + 10;             \
3829         } else if ('A' <= c && c <= 'F') {      \
3830                 val = c - 'A' + 10;             \
3831         } else {                                \
3832                 val = -1;                       \
3833         }                                       \
3834 }
3835
3836 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3837 {
3838         gint hi, lo;
3839
3840         HEX_TO_INT(hi, c1);
3841         HEX_TO_INT(lo, c2);
3842
3843         if (hi == -1 || lo == -1)
3844                 return FALSE;
3845
3846         *out = (hi << 4) + lo;
3847         return TRUE;
3848 }
3849
3850 #define INT_TO_HEX(hex, val)            \
3851 {                                       \
3852         if ((val) < 10)                 \
3853                 hex = '0' + (val);      \
3854         else                            \
3855                 hex = 'A' + (val) - 10; \
3856 }
3857
3858 void get_hex_str(gchar *out, guchar ch)
3859 {
3860         gchar hex;
3861
3862         INT_TO_HEX(hex, ch >> 4);
3863         *out++ = hex;
3864         INT_TO_HEX(hex, ch & 0x0f);
3865         *out   = hex;
3866 }
3867
3868 #undef REF_DEBUG
3869 #ifndef REF_DEBUG
3870 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3871 #else
3872 #define G_PRINT_REF g_print
3873 #endif
3874
3875 /*!
3876  *\brief        Register ref counted pointer. It is based on GBoxed, so should
3877  *              work with anything that uses the GType system. The semantics
3878  *              are similar to a C++ auto pointer, with the exception that
3879  *              C doesn't have automatic closure (calling destructors) when
3880  *              exiting a block scope.
3881  *              Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3882  *              function directly.
3883  *
3884  *\return       GType A GType type.
3885  */
3886 GType g_auto_pointer_register(void)
3887 {
3888         static GType auto_pointer_type;
3889         if (!auto_pointer_type)
3890                 auto_pointer_type =
3891                         g_boxed_type_register_static
3892                                 ("G_TYPE_AUTO_POINTER",
3893                                  (GBoxedCopyFunc) g_auto_pointer_copy,
3894                                  (GBoxedFreeFunc) g_auto_pointer_free);
3895         return auto_pointer_type;
3896 }
3897
3898 /*!
3899  *\brief        Structure with g_new() allocated pointer guarded by the
3900  *              auto pointer
3901  */
3902 typedef struct AutoPointerRef {
3903         void          (*free) (gpointer);
3904         gpointer        pointer;
3905         glong           cnt;
3906 } AutoPointerRef;
3907
3908 /*!
3909  *\brief        The auto pointer opaque structure that references the
3910  *              pointer guard block.
3911  */
3912 typedef struct AutoPointer {
3913         AutoPointerRef *ref;
3914         gpointer        ptr; /*!< access to protected pointer */
3915 } AutoPointer;
3916
3917 /*!
3918  *\brief        Creates an auto pointer for a g_new()ed pointer. Example:
3919  *
3920  *\code
3921  *
3922  *              ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3923  *              ... when assigning, copying and freeing storage elements
3924  *
3925  *              gtk_list_store_new(N_S_COLUMNS,
3926  *                                 G_TYPE_AUTO_POINTER,
3927  *                                 -1);
3928  *
3929  *
3930  *              Template *precious_data = g_new0(Template, 1);
3931  *              g_pointer protect = g_auto_pointer_new(precious_data);
3932  *
3933  *              gtk_list_store_set(container, &iter,
3934  *                                 S_DATA, protect,
3935  *                                 -1);
3936  *
3937  *              ... the gtk_list_store has copied the pointer and
3938  *              ... incremented its reference count, we should free
3939  *              ... the auto pointer (in C++ a destructor would do
3940  *              ... this for us when leaving block scope)
3941  *
3942  *              g_auto_pointer_free(protect);
3943  *
3944  *              ... gtk_list_store_set() now manages the data. When
3945  *              ... *explicitly* requesting a pointer from the list
3946  *              ... store, don't forget you get a copy that should be
3947  *              ... freed with g_auto_pointer_free() eventually.
3948  *
3949  *\endcode
3950  *
3951  *\param        pointer Pointer to be guarded.
3952  *
3953  *\return       GAuto * Pointer that should be used in containers with
3954  *              GType support.
3955  */
3956 GAuto *g_auto_pointer_new(gpointer p)
3957 {
3958         AutoPointerRef *ref;
3959         AutoPointer    *ptr;
3960
3961         if (p == NULL)
3962                 return NULL;
3963
3964         ref = g_new0(AutoPointerRef, 1);
3965         ptr = g_new0(AutoPointer, 1);
3966
3967         ref->pointer = p;
3968         ref->free = g_free;
3969         ref->cnt = 1;
3970
3971         ptr->ref = ref;
3972         ptr->ptr = p;
3973
3974 #ifdef REF_DEBUG
3975         G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3976 #endif
3977         return ptr;
3978 }
3979
3980 /*!
3981  *\brief        Allocate an autopointer using the passed \a free function to
3982  *              free the guarded pointer
3983  */
3984 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3985 {
3986         AutoPointer *aptr;
3987
3988         if (p == NULL)
3989                 return NULL;
3990
3991         aptr = g_auto_pointer_new(p);
3992         aptr->ref->free = free_;
3993         return aptr;
3994 }
3995
3996 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3997 {
3998         if (auto_ptr == NULL)
3999                 return NULL;
4000         return ((AutoPointer *) auto_ptr)->ptr;
4001 }
4002
4003 /*!
4004  *\brief        Copies an auto pointer by. It's mostly not necessary
4005  *              to call this function directly, unless you copy/assign
4006  *              the guarded pointer.
4007  *
4008  *\param        auto_ptr Auto pointer returned by previous call to
4009  *              g_auto_pointer_new_XXX()
4010  *
4011  *\return       gpointer An auto pointer
4012  */
4013 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
4014 {
4015         AutoPointer     *ptr;
4016         AutoPointerRef  *ref;
4017         AutoPointer     *newp;
4018
4019         if (auto_ptr == NULL)
4020                 return NULL;
4021
4022         ptr = auto_ptr;
4023         ref = ptr->ref;
4024         newp = g_new0(AutoPointer, 1);
4025
4026         newp->ref = ref;
4027         newp->ptr = ref->pointer;
4028         ++(ref->cnt);
4029
4030 #ifdef REF_DEBUG
4031         G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4032 #endif
4033         return newp;
4034 }
4035
4036 /*!
4037  *\brief        Free an auto pointer
4038  */
4039 void g_auto_pointer_free(GAuto *auto_ptr)
4040 {
4041         AutoPointer     *ptr;
4042         AutoPointerRef  *ref;
4043
4044         if (auto_ptr == NULL)
4045                 return;
4046
4047         ptr = auto_ptr;
4048         ref = ptr->ref;
4049
4050         if (--(ref->cnt) == 0) {
4051 #ifdef REF_DEBUG
4052                 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4053 #endif
4054                 ref->free(ref->pointer);
4055                 g_free(ref);
4056         }
4057 #ifdef REF_DEBUG
4058         else
4059                 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4060 #endif
4061         g_free(ptr);
4062 }
4063
4064 void replace_returns(gchar *str)
4065 {
4066         if (!str)
4067                 return;
4068
4069         while (strstr(str, "\n")) {
4070                 *strstr(str, "\n") = ' ';
4071         }
4072         while (strstr(str, "\r")) {
4073                 *strstr(str, "\r") = ' ';
4074         }
4075 }
4076
4077 /* get_uri_part() - retrieves a URI starting from scanpos.
4078                     Returns TRUE if successful */
4079 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
4080                              const gchar **bp, const gchar **ep, gboolean hdr)
4081 {
4082         const gchar *ep_;
4083         gint parenthese_cnt = 0;
4084
4085         cm_return_val_if_fail(start != NULL, FALSE);
4086         cm_return_val_if_fail(scanpos != NULL, FALSE);
4087         cm_return_val_if_fail(bp != NULL, FALSE);
4088         cm_return_val_if_fail(ep != NULL, FALSE);
4089
4090         *bp = scanpos;
4091
4092         /* find end point of URI */
4093         for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
4094                 if (!g_ascii_isgraph(*(const guchar *)ep_) ||
4095                     !IS_ASCII(*(const guchar *)ep_) ||
4096                     strchr("[]{}<>\"", *ep_)) {
4097                         break;
4098                 } else if (strchr("(", *ep_)) {
4099                         parenthese_cnt++;
4100                 } else if (strchr(")", *ep_)) {
4101                         if (parenthese_cnt > 0)
4102                                 parenthese_cnt--;
4103                         else
4104                                 break;
4105                 }
4106         }
4107
4108         /* no punctuation at end of string */
4109
4110         /* FIXME: this stripping of trailing punctuations may bite with other URIs.
4111          * should pass some URI type to this function and decide on that whether
4112          * to perform punctuation stripping */
4113
4114 #define IS_REAL_PUNCT(ch)       (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
4115
4116         for (; ep_ - 1 > scanpos + 1 &&
4117                IS_REAL_PUNCT(*(ep_ - 1));
4118              ep_--)
4119                 ;
4120
4121 #undef IS_REAL_PUNCT
4122
4123         *ep = ep_;
4124
4125         return TRUE;
4126 }
4127
4128 gchar *make_uri_string(const gchar *bp, const gchar *ep)
4129 {
4130         while (bp && *bp && g_ascii_isspace(*bp))
4131                 bp++;
4132         return g_strndup(bp, ep - bp);
4133 }
4134
4135 /* valid mail address characters */
4136 #define IS_RFC822_CHAR(ch) \
4137         (IS_ASCII(ch) && \
4138          (ch) > 32   && \
4139          (ch) != 127 && \
4140          !g_ascii_isspace(ch) && \
4141          !strchr("(),;<>\"", (ch)))
4142
4143 /* alphabet and number within 7bit ASCII */
4144 #define IS_ASCII_ALNUM(ch)      (IS_ASCII(ch) && g_ascii_isalnum(ch))
4145 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
4146
4147 static GHashTable *create_domain_tab(void)
4148 {
4149         gint n;
4150         GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
4151
4152         cm_return_val_if_fail(htab, NULL);
4153         for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
4154                 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
4155         return htab;
4156 }
4157
4158 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
4159 {
4160         const gint MAX_LVL_DOM_NAME_LEN = 6;
4161         gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
4162         const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
4163         register gchar *p;
4164
4165         if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
4166                 return FALSE;
4167
4168         for (p = buf; p < m &&  first < last; *p++ = *first++)
4169                 ;
4170         *p = 0;
4171
4172         return g_hash_table_lookup(tab, buf) != NULL;
4173 }
4174
4175 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
4176 gboolean get_email_part(const gchar *start, const gchar *scanpos,
4177                                const gchar **bp, const gchar **ep, gboolean hdr)
4178 {
4179         /* more complex than the uri part because we need to scan back and forward starting from
4180          * the scan position. */
4181         gboolean result = FALSE;
4182         const gchar *bp_ = NULL;
4183         const gchar *ep_ = NULL;
4184         static GHashTable *dom_tab;
4185         const gchar *last_dot = NULL;
4186         const gchar *prelast_dot = NULL;
4187         const gchar *last_tld_char = NULL;
4188
4189         /* the informative part of the email address (describing the name
4190          * of the email address owner) may contain quoted parts. the
4191          * closure stack stores the last encountered quotes. */
4192         gchar closure_stack[128];
4193         gchar *ptr = closure_stack;
4194
4195         cm_return_val_if_fail(start != NULL, FALSE);
4196         cm_return_val_if_fail(scanpos != NULL, FALSE);
4197         cm_return_val_if_fail(bp != NULL, FALSE);
4198         cm_return_val_if_fail(ep != NULL, FALSE);
4199
4200         if (hdr) {
4201                 const gchar *start_quote = NULL;
4202                 const gchar *end_quote = NULL;
4203 search_again:
4204                 /* go to the real start */
4205                 if (start[0] == ',')
4206                         start++;
4207                 if (start[0] == ';')
4208                         start++;
4209                 while (start[0] == '\n' || start[0] == '\r')
4210                         start++;
4211                 while (start[0] == ' ' || start[0] == '\t')
4212                         start++;
4213
4214                 *bp = start;
4215                 
4216                 /* check if there are quotes (to skip , in them) */
4217                 if (*start == '"') {
4218                         start_quote = start;
4219                         start++;
4220                         end_quote = strstr(start, "\"");
4221                 } else {
4222                         start_quote = NULL;
4223                         end_quote = NULL;
4224                 }
4225                 
4226                 /* skip anything between quotes */
4227                 if (start_quote && end_quote) {
4228                         start = end_quote;
4229                         
4230                 } 
4231
4232                 /* find end (either , or ; or end of line) */
4233                 if (strstr(start, ",") && strstr(start, ";"))
4234                         *ep = strstr(start,",") < strstr(start, ";")
4235                                 ? strstr(start, ",") : strstr(start, ";");
4236                 else if (strstr(start, ","))
4237                         *ep = strstr(start, ",");
4238                 else if (strstr(start, ";"))
4239                         *ep = strstr(start, ";");
4240                 else
4241                         *ep = start+strlen(start);
4242
4243                 /* go back to real start */
4244                 if (start_quote && end_quote) {
4245                         start = start_quote;
4246                 }
4247
4248                 /* check there's still an @ in that, or search
4249                  * further if possible */
4250                 if (strstr(start, "@") && strstr(start, "@") < *ep)
4251                         return TRUE;
4252                 else if (*ep < start+strlen(start)) {
4253                         start = *ep;
4254                         goto search_again;
4255                 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
4256                         *bp = start_quote;
4257                         return TRUE;
4258                 } else
4259                         return FALSE;
4260         }
4261
4262         if (!dom_tab)
4263                 dom_tab = create_domain_tab();
4264         cm_return_val_if_fail(dom_tab, FALSE);
4265
4266         /* scan start of address */
4267         for (bp_ = scanpos - 1;
4268              bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
4269                 ;
4270
4271         /* TODO: should start with an alnum? */
4272         bp_++;
4273         for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
4274                 ;
4275
4276         if (bp_ != scanpos) {
4277                 /* scan end of address */
4278                 for (ep_ = scanpos + 1;
4279                      *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
4280                         if (*ep_ == '.') {
4281                                 prelast_dot = last_dot;
4282                                 last_dot = ep_;
4283                                 if (*(last_dot + 1) == '.') {
4284                                         if (prelast_dot == NULL)
4285                                                 return FALSE;
4286                                         last_dot = prelast_dot;
4287                                         break;
4288                                 }
4289                         }
4290
4291                 /* TODO: really should terminate with an alnum? */
4292                 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
4293                      --ep_)
4294                         ;
4295                 ep_++;
4296
4297                 if (last_dot == NULL)
4298                         return FALSE;
4299                 if (last_dot >= ep_)
4300                         last_dot = prelast_dot;
4301                 if (last_dot == NULL || (scanpos + 1 >= last_dot))
4302                         return FALSE;
4303                 last_dot++;
4304
4305                 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
4306                         if (*last_tld_char == '?')
4307                                 break;
4308
4309                 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
4310                         result = TRUE;
4311
4312                 *ep = ep_;
4313                 *bp = bp_;
4314         }
4315
4316         if (!result) return FALSE;
4317
4318         if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
4319         && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
4320         && IS_RFC822_CHAR(*(ep_ + 3))) {
4321                 /* this informative part with an @ in it is
4322                  * followed by the email address */
4323                 ep_ += 3;
4324
4325                 /* go to matching '>' (or next non-rfc822 char, like \n) */
4326                 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
4327                         ;
4328
4329                 /* include the bracket */
4330                 if (*ep_ == '>') ep_++;
4331
4332                 /* include the leading quote */
4333                 bp_--;
4334
4335                 *ep = ep_;
4336                 *bp = bp_;
4337                 return TRUE;
4338         }
4339
4340         /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
4341         if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
4342                 return FALSE;
4343
4344         /* see if this is <bracketed>; in this case we also scan for the informative part. */
4345         if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
4346                 return TRUE;
4347
4348 #define FULL_STACK()    ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
4349 #define IN_STACK()      (ptr > closure_stack)
4350 /* has underrun check */
4351 #define POP_STACK()     if(IN_STACK()) --ptr
4352 /* has overrun check */
4353 #define PUSH_STACK(c)   if(!FULL_STACK()) *ptr++ = (c); else return TRUE
4354 /* has underrun check */
4355 #define PEEK_STACK()    (IN_STACK() ? *(ptr - 1) : 0)
4356
4357         ep_++;
4358
4359         /* scan for the informative part. */
4360         for (bp_ -= 2; bp_ >= start; bp_--) {
4361                 /* if closure on the stack keep scanning */
4362                 if (PEEK_STACK() == *bp_) {
4363                         POP_STACK();
4364                         continue;
4365                 }
4366                 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
4367                         PUSH_STACK(*bp_);
4368                         continue;
4369                 }
4370
4371                 /* if nothing in the closure stack, do the special conditions
4372                  * the following if..else expression simply checks whether
4373                  * a token is acceptable. if not acceptable, the clause
4374                  * should terminate the loop with a 'break' */
4375                 if (!PEEK_STACK()) {
4376                         if (*bp_ == '-'
4377                         && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
4378                         && (((bp_ + 1) < ep_)    && isalnum(*(bp_ + 1)))) {
4379                                 /* hyphens are allowed, but only in
4380                                    between alnums */
4381                         } else if (strchr(" \"'", *bp_)) {
4382                                 /* but anything not being a punctiation
4383                                    is ok */
4384                         } else {
4385                                 break; /* anything else is rejected */
4386                         }
4387                 }
4388         }
4389
4390         bp_++;
4391
4392         /* scan forward (should start with an alnum) */
4393         for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
4394                 ;
4395 #undef PEEK_STACK
4396 #undef PUSH_STACK
4397 #undef POP_STACK
4398 #undef IN_STACK
4399 #undef FULL_STACK
4400
4401
4402         *bp = bp_;
4403         *ep = ep_;
4404
4405         return result;
4406 }
4407
4408 #undef IS_QUOTE
4409 #undef IS_ASCII_ALNUM
4410 #undef IS_RFC822_CHAR
4411
4412 gchar *make_email_string(const gchar *bp, const gchar *ep)
4413 {
4414         /* returns a mailto: URI; mailto: is also used to detect the
4415          * uri type later on in the button_pressed signal handler */
4416         gchar *tmp;
4417         gchar *result;
4418         gchar *colon, *at;
4419
4420         tmp = g_strndup(bp, ep - bp);
4421
4422         /* If there is a colon in the username part of the address,
4423          * we're dealing with an URI for some other protocol - do
4424          * not prefix with mailto: in such case. */
4425         colon = strchr(tmp, ':');
4426         at = strchr(tmp, '@');
4427         if (colon != NULL && at != NULL && colon < at) {
4428                 result = tmp;
4429         } else {
4430                 result = g_strconcat("mailto:", tmp, NULL);
4431                 g_free(tmp);
4432         }
4433
4434         return result;
4435 }
4436
4437 gchar *make_http_string(const gchar *bp, const gchar *ep)
4438 {
4439         /* returns an http: URI; */
4440         gchar *tmp;
4441         gchar *result;
4442
4443         while (bp && *bp && g_ascii_isspace(*bp))
4444                 bp++;
4445         tmp = g_strndup(bp, ep - bp);
4446         result = g_strconcat("http://", tmp, NULL);
4447         g_free(tmp);
4448
4449         return result;
4450 }
4451
4452 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
4453 {
4454         FILE *fp = g_fopen(path, "rb");
4455         gchar buf[BUFFSIZE];
4456         gchar *result = NULL;
4457         if (!fp)
4458                 return NULL;
4459         while (fgets(buf, sizeof (buf), fp) != NULL) {
4460                 gchar **parts = g_strsplit(buf, ";", 3);
4461                 gchar *trimmed = parts[0];
4462                 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4463                         trimmed++;
4464                 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4465                         trimmed[strlen(trimmed)-1] = '\0';
4466
4467                 if (!strcmp(trimmed, type)) {
4468                         gboolean needsterminal = FALSE;
4469                         if (parts[2] && strstr(parts[2], "needsterminal")) {
4470                                 needsterminal = TRUE;
4471                         }
4472                         if (parts[2] && strstr(parts[2], "test=")) {
4473                                 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
4474                                 gchar *testcmd = orig_testcmd;
4475                                 if (strstr(testcmd,";"))
4476                                         *(strstr(testcmd,";")) = '\0';
4477                                 while (testcmd[0] == ' ' || testcmd[0] == '\t')
4478                                         testcmd++;
4479                                 while (testcmd[strlen(testcmd)-1] == '\n')
4480                                         testcmd[strlen(testcmd)-1] = '\0';
4481                                 while (testcmd[strlen(testcmd)-1] == '\r')
4482                                         testcmd[strlen(testcmd)-1] = '\0';
4483                                 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
4484                                         testcmd[strlen(testcmd)-1] = '\0';
4485                                         
4486                                 if (strstr(testcmd, "%s")) {
4487                                         gchar *tmp = g_strdup_printf(testcmd, file_to_open);
4488                                         gint res = system(tmp);
4489                                         g_free(tmp);
4490                                         g_free(orig_testcmd);
4491                                         
4492                                         if (res != 0) {
4493                                                 g_strfreev(parts);
4494                                                 continue;
4495                                         }
4496                                 } else {
4497                                         gint res = system(testcmd);
4498                                         g_free(orig_testcmd);
4499                                         
4500                                         if (res != 0) {
4501                                                 g_strfreev(parts);
4502                                                 continue;
4503                                         }
4504                                 }
4505                         }
4506                         
4507                         trimmed = parts[1];
4508                         while (trimmed[0] == ' ' || trimmed[0] == '\t')
4509                                 trimmed++;
4510                         while (trimmed[strlen(trimmed)-1] == '\n')
4511                                 trimmed[strlen(trimmed)-1] = '\0';
4512                         while (trimmed[strlen(trimmed)-1] == '\r')
4513                                 trimmed[strlen(trimmed)-1] = '\0';
4514                         while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4515                                 trimmed[strlen(trimmed)-1] = '\0';
4516                         result = g_strdup(trimmed);
4517                         g_strfreev(parts);
4518                         fclose(fp);
4519                         if (needsterminal) {
4520                                 gchar *tmp = g_strdup_printf("xterm -e %s", result);
4521                                 g_free(result);
4522                                 result = tmp;
4523                         }
4524                         return result;
4525                 }
4526                 g_strfreev(parts);
4527         }
4528         fclose(fp);
4529         return NULL;
4530 }
4531 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
4532 {
4533         gchar *result = NULL;
4534         gchar *path = NULL;
4535         if (type == NULL)
4536                 return NULL;
4537         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4538         result = mailcap_get_command_in_file(path, type, file_to_open);
4539         g_free(path);
4540         if (result)
4541                 return result;
4542         result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
4543         return result;
4544 }
4545
4546 void mailcap_update_default(const gchar *type, const gchar *command)
4547 {
4548         gchar *path = NULL, *outpath = NULL;
4549         path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4550         outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
4551         FILE *fp = g_fopen(path, "rb");
4552         FILE *outfp = NULL;
4553         gchar buf[BUFFSIZE];
4554         gboolean err = FALSE;
4555
4556         if (!fp) {
4557                 fp = g_fopen(path, "a");
4558                 if (!fp) {
4559                         g_warning("failed to create file %s", path);
4560                         g_free(path);
4561                         g_free(outpath);
4562                         return;
4563                 }
4564                 fp = g_freopen(path, "rb", fp);
4565                 if (!fp) {
4566                         g_warning("failed to reopen file %s", path);
4567                         g_free(path);
4568                         g_free(outpath);
4569                         return;
4570                 }
4571         }
4572
4573         outfp = g_fopen(outpath, "wb");
4574         if (!outfp) {
4575                 g_warning("failed to create file %s", outpath);
4576                 g_free(path);
4577                 g_free(outpath);
4578                 fclose(fp);
4579                 return;
4580         }
4581         while (fp && fgets(buf, sizeof (buf), fp) != NULL) {
4582                 gchar **parts = g_strsplit(buf, ";", 3);
4583                 gchar *trimmed = parts[0];
4584                 while (trimmed[0] == ' ')
4585                         trimmed++;
4586                 while (trimmed[strlen(trimmed)-1] == ' ')
4587                         trimmed[strlen(trimmed)-1] = '\0';
4588
4589                 if (!strcmp(trimmed, type)) {
4590                         g_strfreev(parts);
4591                         continue;
4592                 }
4593                 else {
4594                         if(fputs(buf, outfp) == EOF) {
4595                                 err = TRUE;
4596                                 break;
4597                         }
4598                 }
4599                 g_strfreev(parts);
4600         }
4601         if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4602                 err = TRUE;
4603
4604         if (fp)
4605                 fclose(fp);
4606
4607         if (fclose(outfp) == EOF)
4608                 err = TRUE;
4609                 
4610         if (!err)
4611                 g_rename(outpath, path);
4612
4613         g_free(path);
4614         g_free(outpath);
4615 }
4616
4617 gint copy_dir(const gchar *src, const gchar *dst)
4618 {
4619         GDir *dir;
4620         const gchar *name;
4621
4622         if ((dir = g_dir_open(src, 0, NULL)) == NULL) {
4623                 g_warning("failed to open directory: %s", src);
4624                 return -1;
4625         }
4626
4627         if (make_dir(dst) < 0)
4628                 return -1;
4629
4630         while ((name = g_dir_read_name(dir)) != NULL) {
4631                 gchar *old_file, *new_file;
4632                 old_file = g_strconcat(src, G_DIR_SEPARATOR_S, name, NULL);
4633                 new_file = g_strconcat(dst, G_DIR_SEPARATOR_S, name, NULL);
4634                 debug_print("copying: %s -> %s\n", old_file, new_file);
4635                 if (g_file_test(old_file, G_FILE_TEST_IS_REGULAR)) {
4636                         gint r = copy_file(old_file, new_file, TRUE);
4637                         if (r < 0) {
4638                                 g_dir_close(dir);
4639                                 return r;
4640                         }
4641                 }
4642 #ifndef G_OS_WIN32
4643                 /* Windows has no symlinks.  Or well, Vista seems to
4644                    have something like this but the semantics might be
4645                    different.  Thus we don't use it under Windows. */
4646                  else if (g_file_test(old_file, G_FILE_TEST_IS_SYMLINK)) {
4647                         GError *error = NULL;
4648                         gint r = 0;
4649                         gchar *target = g_file_read_link(old_file, &error);
4650                         if (target)
4651                                 r = symlink(target, new_file);
4652                         g_free(target);
4653                         if (r < 0) {
4654                                 g_dir_close(dir);
4655                                 return r;
4656                         }
4657                  }
4658 #endif /*G_OS_WIN32*/
4659                 else if (g_file_test(old_file, G_FILE_TEST_IS_DIR)) {
4660                         gint r = copy_dir(old_file, new_file);
4661                         if (r < 0) {
4662                                 g_dir_close(dir);
4663                                 return r;
4664                         }
4665                 }
4666         }
4667         g_dir_close(dir);
4668         return 0;
4669 }
4670
4671 /* crude test to see if a file is an email. */
4672 gboolean file_is_email (const gchar *filename)
4673 {
4674         FILE *fp = NULL;
4675         gchar buffer[2048];
4676         gint i = 0;
4677         gint score = 0;
4678         if (filename == NULL)
4679                 return FALSE;
4680         if ((fp = g_fopen(filename, "rb")) == NULL)
4681                 return FALSE;
4682         while (i < 60 && score < 3
4683                && fgets(buffer, sizeof (buffer), fp) != NULL) {
4684                 if (!strncmp(buffer, "From:", strlen("From:")))
4685                         score++;
4686                 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4687                         score++;
4688                 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4689                         score++;
4690                 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4691                         score++;
4692                 i++;
4693         }
4694         fclose(fp);
4695         return (score >= 3);
4696 }
4697
4698 gboolean sc_g_list_bigger(GList *list, gint max)
4699 {
4700         GList *cur = list;
4701         int i = 0;
4702         while (cur && i <= max+1) {
4703                 i++;
4704                 cur = cur->next;
4705         }
4706         return (i > max);
4707 }
4708
4709 gboolean sc_g_slist_bigger(GSList *list, gint max)
4710 {
4711         GSList *cur = list;
4712         int i = 0;
4713         while (cur && i <= max+1) {
4714                 i++;
4715                 cur = cur->next;
4716         }
4717         return (i > max);
4718 }
4719
4720 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4721 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL, 
4722                              NULL, NULL, NULL, NULL, NULL, NULL};
4723 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4724 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL, 
4725                              NULL, NULL, NULL, NULL, NULL, NULL};
4726
4727 gint daynames_len[] =     {0,0,0,0,0,0,0};
4728 gint monthnames_len[] =   {0,0,0,0,0,0,
4729                                  0,0,0,0,0,0};
4730 gint s_daynames_len[] =   {0,0,0,0,0,0,0};
4731 gint s_monthnames_len[] = {0,0,0,0,0,0,
4732                                  0,0,0,0,0,0};
4733 const gchar *s_am_up = NULL;
4734 const gchar *s_pm_up = NULL;
4735 const gchar *s_am_low = NULL;
4736 const gchar *s_pm_low = NULL;
4737
4738 gint s_am_up_len = 0;
4739 gint s_pm_up_len = 0;
4740 gint s_am_low_len = 0;
4741 gint s_pm_low_len = 0;
4742
4743 static gboolean time_names_init_done = FALSE;
4744
4745 static void init_time_names(void)
4746 {
4747         int i = 0;
4748
4749         daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4750         daynames[1] = C_("Complete day name for use by strftime", "Monday");
4751         daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4752         daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4753         daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4754         daynames[5] = C_("Complete day name for use by strftime", "Friday");
4755         daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4756
4757         monthnames[0] = C_("Complete month name for use by strftime", "January");
4758         monthnames[1] = C_("Complete month name for use by strftime", "February");
4759         monthnames[2] = C_("Complete month name for use by strftime", "March");
4760         monthnames[3] = C_("Complete month name for use by strftime", "April");
4761         monthnames[4] = C_("Complete month name for use by strftime", "May");
4762         monthnames[5] = C_("Complete month name for use by strftime", "June");
4763         monthnames[6] = C_("Complete month name for use by strftime", "July");
4764         monthnames[7] = C_("Complete month name for use by strftime", "August");
4765         monthnames[8] = C_("Complete month name for use by strftime", "September");
4766         monthnames[9] = C_("Complete month name for use by strftime", "October");
4767         monthnames[10] = C_("Complete month name for use by strftime", "November");
4768         monthnames[11] = C_("Complete month name for use by strftime", "December");
4769
4770         s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4771         s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4772         s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4773         s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4774         s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4775         s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4776         s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4777         
4778         s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4779         s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4780         s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4781         s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4782         s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4783         s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4784         s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4785         s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4786         s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4787         s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4788         s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4789         s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4790
4791         for (i = 0; i < 7; i++) {
4792                 daynames_len[i] = strlen(daynames[i]);
4793                 s_daynames_len[i] = strlen(s_daynames[i]);
4794         }
4795         for (i = 0; i < 12; i++) {
4796                 monthnames_len[i] = strlen(monthnames[i]);
4797                 s_monthnames_len[i] = strlen(s_monthnames[i]);
4798         }
4799
4800         s_am_up = C_("For use by strftime (morning)", "AM");
4801         s_pm_up = C_("For use by strftime (afternoon)", "PM");
4802         s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4803         s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4804         
4805         s_am_up_len = strlen(s_am_up);
4806         s_pm_up_len = strlen(s_pm_up);
4807         s_am_low_len = strlen(s_am_low);
4808         s_pm_low_len = strlen(s_pm_low);
4809
4810         time_names_init_done = TRUE;
4811 }
4812
4813 #define CHECK_SIZE() {                  \
4814         total_done += len;              \
4815         if (total_done >= buflen) {     \
4816                 buf[buflen-1] = '\0';   \
4817                 return 0;               \
4818         }                               \
4819 }
4820
4821 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4822 {
4823         gchar *curpos = buf;
4824         gint total_done = 0;
4825         gchar subbuf[64], subfmt[64];
4826         static time_t last_tzset = (time_t)0;
4827         
4828         if (!time_names_init_done)
4829                 init_time_names();
4830         
4831         if (format == NULL || lt == NULL)
4832                 return 0;
4833                 
4834         if (last_tzset != time(NULL)) {
4835                 tzset();
4836                 last_tzset = time(NULL);
4837         }
4838         while(*format) {
4839                 if (*format == '%') {
4840                         gint len = 0, tmp = 0;
4841                         format++;
4842                         switch(*format) {
4843                         case '%':
4844                                 len = 1; CHECK_SIZE();
4845                                 *curpos = '%';
4846                                 break;
4847                         case 'a':
4848                                 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4849                                 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4850                                 break;
4851                         case 'A':
4852                                 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4853                                 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4854                                 break;
4855                         case 'b':
4856                         case 'h':
4857                                 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4858                                 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4859                                 break;
4860                         case 'B':
4861                                 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4862                                 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4863                                 break;
4864                         case 'c':
4865                                 strftime(subbuf, 64, "%c", lt);
4866                                 len = strlen(subbuf); CHECK_SIZE();
4867                                 strncpy2(curpos, subbuf, buflen - total_done);
4868                                 break;
4869                         case 'C':
4870                                 total_done += 2; CHECK_SIZE();
4871                                 tmp = (lt->tm_year + 1900)/100;
4872                                 *curpos++ = '0'+(tmp / 10);
4873                                 *curpos++ = '0'+(tmp % 10);
4874                                 break;
4875                         case 'd':
4876                                 total_done += 2; CHECK_SIZE();
4877                                 *curpos++ = '0'+(lt->tm_mday / 10);
4878                                 *curpos++ = '0'+(lt->tm_mday % 10);
4879                                 break;
4880                         case 'D':
4881                                 total_done += 8; CHECK_SIZE();
4882                                 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4883                                 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4884                                 *curpos++ = '/';
4885                                 *curpos++ = '0'+(lt->tm_mday / 10);
4886                                 *curpos++ = '0'+(lt->tm_mday % 10);
4887                                 *curpos++ = '/';
4888                                 tmp = lt->tm_year%100;
4889                                 *curpos++ = '0'+(tmp / 10);
4890                                 *curpos++ = '0'+(tmp % 10);
4891                                 break;
4892                         case 'e':
4893                                 len = 2; CHECK_SIZE();
4894                                 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4895                                 break;
4896                         case 'F':
4897                                 len = 10; CHECK_SIZE();
4898                                 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d", 
4899                                         lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4900                                 break;
4901                         case 'H':
4902                                 total_done += 2; CHECK_SIZE();
4903                                 *curpos++ = '0'+(lt->tm_hour / 10);
4904                                 *curpos++ = '0'+(lt->tm_hour % 10);
4905                                 break;
4906                         case 'I':
4907                                 total_done += 2; CHECK_SIZE();
4908                                 tmp = lt->tm_hour;
4909                                 if (tmp > 12)
4910                                         tmp -= 12;
4911                                 else if (tmp == 0)
4912                                         tmp = 12;
4913                                 *curpos++ = '0'+(tmp / 10);
4914                                 *curpos++ = '0'+(tmp % 10);
4915                                 break;
4916                         case 'j':
4917                                 len = 3; CHECK_SIZE();
4918                                 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4919                                 break;
4920                         case 'k':
4921                                 len = 2; CHECK_SIZE();
4922                                 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4923                                 break;
4924                         case 'l':
4925                                 len = 2; CHECK_SIZE();
4926                                 tmp = lt->tm_hour;
4927                                 if (tmp > 12)
4928                                         tmp -= 12;
4929                                 else if (tmp == 0)
4930                                         tmp = 12;
4931                                 snprintf(curpos, buflen - total_done, "%2d", tmp);
4932                                 break;
4933                         case 'm':
4934                                 total_done += 2; CHECK_SIZE();
4935                                 tmp = lt->tm_mon + 1;
4936                                 *curpos++ = '0'+(tmp / 10);
4937                                 *curpos++ = '0'+(tmp % 10);
4938                                 break;
4939                         case 'M':
4940                                 total_done += 2; CHECK_SIZE();
4941                                 *curpos++ = '0'+(lt->tm_min / 10);
4942                                 *curpos++ = '0'+(lt->tm_min % 10);
4943                                 break;
4944                         case 'n':
4945                                 len = 1; CHECK_SIZE();
4946                                 *curpos = '\n';
4947                                 break;
4948                         case 'p':
4949                                 if (lt->tm_hour >= 12) {
4950                                         len = s_pm_up_len; CHECK_SIZE();
4951                                         snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4952                                 } else {
4953                                         len = s_am_up_len; CHECK_SIZE();
4954                                         snprintf(curpos, buflen-total_done, "%s", s_am_up);
4955                                 }
4956                                 break;
4957                         case 'P':
4958                                 if (lt->tm_hour >= 12) {
4959                                         len = s_pm_low_len; CHECK_SIZE();
4960                                         snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4961                                 } else {
4962                                         len = s_am_low_len; CHECK_SIZE();
4963                                         snprintf(curpos, buflen-total_done, "%s", s_am_low);
4964                                 }
4965                                 break;
4966                         case 'r':
4967                                 strftime(subbuf, 64, "%r", lt);
4968                                 len = strlen(subbuf); CHECK_SIZE();
4969                                 strncpy2(curpos, subbuf, buflen - total_done);
4970                                 break;
4971                         case 'R':
4972                                 total_done += 5; CHECK_SIZE();
4973                                 *curpos++ = '0'+(lt->tm_hour / 10);
4974                                 *curpos++ = '0'+(lt->tm_hour % 10);
4975                                 *curpos++ = ':';
4976                                 *curpos++ = '0'+(lt->tm_min / 10);
4977                                 *curpos++ = '0'+(lt->tm_min % 10);
4978                                 break;
4979                         case 's':
4980                                 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
4981                                 len = strlen(subbuf); CHECK_SIZE();
4982                                 strncpy2(curpos, subbuf, buflen - total_done);
4983                                 break;
4984                         case 'S':
4985                                 total_done += 2; CHECK_SIZE();
4986                                 *curpos++ = '0'+(lt->tm_sec / 10);
4987                                 *curpos++ = '0'+(lt->tm_sec % 10);
4988                                 break;
4989                         case 't':
4990                                 len = 1; CHECK_SIZE();
4991                                 *curpos = '\t';
4992                                 break;
4993                         case 'T':
4994                                 total_done += 8; CHECK_SIZE();
4995                                 *curpos++ = '0'+(lt->tm_hour / 10);
4996                                 *curpos++ = '0'+(lt->tm_hour % 10);
4997                                 *curpos++ = ':';
4998                                 *curpos++ = '0'+(lt->tm_min / 10);
4999                                 *curpos++ = '0'+(lt->tm_min % 10);
5000                                 *curpos++ = ':';
5001                                 *curpos++ = '0'+(lt->tm_sec / 10);
5002                                 *curpos++ = '0'+(lt->tm_sec % 10);
5003                                 break;
5004                         case 'u':
5005                                 len = 1; CHECK_SIZE();
5006                                 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
5007                                 break;
5008                         case 'w':
5009                                 len = 1; CHECK_SIZE();
5010                                 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
5011                                 break;
5012                         case 'x':
5013                                 strftime(subbuf, 64, "%x", lt);
5014                                 len = strlen(subbuf); CHECK_SIZE();
5015                                 strncpy2(curpos, subbuf, buflen - total_done);
5016                                 break;
5017                         case 'X':
5018                                 strftime(subbuf, 64, "%X", lt);
5019                                 len = strlen(subbuf); CHECK_SIZE();
5020                                 strncpy2(curpos, subbuf, buflen - total_done);
5021                                 break;
5022                         case 'y':
5023                                 total_done += 2; CHECK_SIZE();
5024                                 tmp = lt->tm_year%100;
5025                                 *curpos++ = '0'+(tmp / 10);
5026                                 *curpos++ = '0'+(tmp % 10);
5027                                 break;
5028                         case 'Y':
5029                                 len = 4; CHECK_SIZE();
5030                                 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
5031                                 break;
5032                         case 'G':
5033                         case 'g':
5034                         case 'U':
5035                         case 'V':
5036                         case 'W':
5037                         case 'z':
5038                         case 'Z':
5039                         case '+':
5040                                 /* let these complicated ones be done with the libc */
5041                                 snprintf(subfmt, 64, "%%%c", *format);
5042                                 strftime(subbuf, 64, subfmt, lt);
5043                                 len = strlen(subbuf); CHECK_SIZE();
5044                                 strncpy2(curpos, subbuf, buflen - total_done);
5045                                 break;
5046                         case 'E':
5047                         case 'O':
5048                                 /* let these complicated modifiers be done with the libc */
5049                                 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
5050                                 strftime(subbuf, 64, subfmt, lt);
5051                                 len = strlen(subbuf); CHECK_SIZE();
5052                                 strncpy2(curpos, subbuf, buflen - total_done);
5053                                 format++;
5054                                 break;
5055                         default:
5056                                 g_warning("format error (%c)", *format);
5057                                 *curpos = '\0';
5058                                 return total_done;
5059                         }
5060                         curpos += len;
5061                         format++;
5062                 } else {
5063                         int len = 1; CHECK_SIZE();
5064                         *curpos++ = *format++; 
5065                 }
5066         }
5067         *curpos = '\0';
5068         return total_done;
5069 }
5070
5071 gboolean prefs_common_get_use_shred(void);
5072
5073
5074 #ifdef G_OS_WIN32
5075 #define WEXITSTATUS(x) (x)
5076 #endif
5077
5078 int claws_unlink(const gchar *filename) 
5079 {
5080         GStatBuf s;
5081         static int found_shred = -1;
5082         static const gchar *args[4];
5083
5084         if (filename == NULL)
5085                 return 0;
5086
5087         if (prefs_common_get_use_shred()) {
5088                 if (found_shred == -1) {
5089                         /* init */
5090                         args[0] = g_find_program_in_path("shred");
5091                         debug_print("found shred: %s\n", args[0]);
5092                         found_shred = (args[0] != NULL) ? 1:0;
5093                         args[1] = "-f";
5094                         args[3] = NULL;
5095                 }
5096                 if (found_shred == 1) {
5097                         if (g_stat(filename, &s) == 0 && S_ISREG(s.st_mode)) {
5098                                 if (s.st_nlink == 1) {
5099                                         gint status=0;
5100                                         args[2] = filename;
5101                                         g_spawn_sync(NULL, (gchar **)args, NULL, 0,
5102                                          NULL, NULL, NULL, NULL, &status, NULL);
5103                                         debug_print("%s %s exited with status %d\n",
5104                                                 args[0], filename, WEXITSTATUS(status));
5105                                         if (truncate(filename, 0) < 0)
5106                                                 g_warning("couln't truncate: %s", filename);
5107                                 }
5108                         }
5109                 }
5110         }
5111         return g_unlink(filename);
5112 }
5113
5114 GMutex *cm_mutex_new(void) {
5115 #if GLIB_CHECK_VERSION(2,32,0)
5116         GMutex *m = g_new0(GMutex, 1);
5117         g_mutex_init(m);
5118         return m;
5119 #else
5120         return g_mutex_new();
5121 #endif
5122 }
5123
5124 void cm_mutex_free(GMutex *mutex) {
5125 #if GLIB_CHECK_VERSION(2,32,0)
5126         g_mutex_clear(mutex);
5127         g_free(mutex);
5128 #else
5129         g_mutex_free(mutex);
5130 #endif
5131 }
5132
5133 static gchar *canonical_list_to_file(GSList *list)
5134 {
5135         GString *result = g_string_new(NULL);
5136         GSList *pathlist = g_slist_reverse(g_slist_copy(list));
5137         GSList *cur;
5138         gchar *str;
5139
5140 #ifndef G_OS_WIN32
5141         result = g_string_append(result, G_DIR_SEPARATOR_S);
5142 #else
5143         if (pathlist->data) {
5144                 const gchar *root = (gchar *)pathlist->data;
5145                 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
5146                     root[1] == ':') {
5147                         /* drive - don't prepend dir separator */
5148                 } else {
5149                         result = g_string_append(result, G_DIR_SEPARATOR_S);
5150                 }
5151         }
5152 #endif
5153
5154         for (cur = pathlist; cur; cur = cur->next) {
5155                 result = g_string_append(result, (gchar *)cur->data);
5156                 if (cur->next)
5157                         result = g_string_append(result, G_DIR_SEPARATOR_S);
5158         }
5159         g_slist_free(pathlist);
5160
5161         str = result->str;
5162         g_string_free(result, FALSE);
5163
5164         return str;
5165 }
5166
5167 static GSList *cm_split_path(const gchar *filename, int depth)
5168 {
5169         gchar **path_parts;
5170         GSList *canonical_parts = NULL;
5171         GStatBuf st;
5172         int i;
5173 #ifndef G_OS_WIN32
5174         gboolean follow_symlinks = TRUE;
5175 #endif
5176
5177         if (depth > 32) {
5178 #ifndef G_OS_WIN32
5179                 errno = ELOOP;
5180 #else
5181                 errno = EINVAL; /* can't happen, no symlink handling */
5182 #endif
5183                 return NULL;
5184         }
5185
5186         if (!g_path_is_absolute(filename)) {
5187                 errno =EINVAL;
5188                 return NULL;
5189         }
5190
5191         path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
5192
5193         for (i = 0; path_parts[i] != NULL; i++) {
5194                 if (!strcmp(path_parts[i], ""))
5195                         continue;
5196                 if (!strcmp(path_parts[i], "."))
5197                         continue;
5198                 else if (!strcmp(path_parts[i], "..")) {
5199                         if (i == 0) {
5200                                 errno =ENOTDIR;
5201                                 return NULL;
5202                         }
5203                         else /* Remove the last inserted element */
5204                                 canonical_parts = 
5205                                         g_slist_delete_link(canonical_parts,
5206                                                             canonical_parts);
5207                 } else {
5208                         gchar *tmp_path;
5209
5210                         canonical_parts = g_slist_prepend(canonical_parts,
5211                                                 g_strdup(path_parts[i]));
5212
5213                         tmp_path = canonical_list_to_file(canonical_parts);
5214
5215                         if(g_stat(tmp_path, &st) < 0) {
5216                                 if (errno == ENOENT) {
5217                                         errno = 0;
5218 #ifndef G_OS_WIN32
5219                                         follow_symlinks = FALSE;
5220 #endif
5221                                 }
5222                                 if (errno != 0) {
5223                                         g_free(tmp_path);
5224                                         slist_free_strings_full(canonical_parts);
5225                                         g_strfreev(path_parts);
5226
5227                                         return NULL;
5228                                 }
5229                         }
5230 #ifndef G_OS_WIN32
5231                         if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
5232                                 GError *error = NULL;
5233                                 gchar *target = g_file_read_link(tmp_path, &error);
5234
5235                                 if (!g_path_is_absolute(target)) {
5236                                         /* remove the last inserted element */
5237                                         canonical_parts = 
5238                                                 g_slist_delete_link(canonical_parts,
5239                                                             canonical_parts);
5240                                         /* add the target */
5241                                         canonical_parts = g_slist_prepend(canonical_parts,
5242                                                 g_strdup(target));
5243                                         g_free(target);
5244
5245                                         /* and get the new target */
5246                                         target = canonical_list_to_file(canonical_parts);
5247                                 }
5248
5249                                 /* restart from absolute target */
5250                                 slist_free_strings_full(canonical_parts);
5251                                 canonical_parts = NULL;
5252                                 if (!error)
5253                                         canonical_parts = cm_split_path(target, depth + 1);
5254                                 else
5255                                         g_error_free(error);
5256                                 if (canonical_parts == NULL) {
5257                                         g_free(tmp_path);
5258                                         g_strfreev(path_parts);
5259                                         return NULL;
5260                                 }
5261                                 g_free(target);
5262                         }
5263 #endif
5264                         g_free(tmp_path);
5265                 }
5266         }
5267         g_strfreev(path_parts);
5268         return canonical_parts;
5269 }
5270
5271 /*
5272  * Canonicalize a filename, resolving symlinks along the way.
5273  * Returns a negative errno in case of error.
5274  */
5275 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
5276         GSList *canonical_parts;
5277         gboolean is_absolute;
5278
5279         if (filename == NULL)
5280                 return -EINVAL;
5281         if (canonical_name == NULL)
5282                 return -EINVAL;
5283         *canonical_name = NULL;
5284
5285         is_absolute = g_path_is_absolute(filename);
5286         if (!is_absolute) {
5287                 /* Always work on absolute filenames. */
5288                 gchar *cur = g_get_current_dir();
5289                 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
5290                                                        filename, NULL);
5291                 
5292                 canonical_parts = cm_split_path(absolute_filename, 0);
5293                 g_free(absolute_filename);
5294                 g_free(cur);
5295         } else
5296                 canonical_parts = cm_split_path(filename, 0);
5297
5298         if (canonical_parts == NULL)
5299                 return -errno;
5300
5301         *canonical_name = canonical_list_to_file(canonical_parts);
5302         slist_free_strings_full(canonical_parts);
5303         return 0;
5304 }
5305
5306 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
5307 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
5308 {
5309         gchar *tmp = g_base64_decode(text, out_len);
5310         gchar *out = g_strndup(tmp, *out_len);
5311
5312         g_free(tmp);
5313
5314         if (strlen(out) != *out_len) {
5315                 g_warning ("strlen(out) %zd != *out_len %" G_GSIZE_FORMAT, strlen(out), *out_len);
5316         }
5317
5318         return out;
5319 }
5320
5321 #if !GLIB_CHECK_VERSION(2, 30, 0)
5322 /**
5323  * g_utf8_substring:
5324  * @str: a UTF-8 encoded string
5325  * @start_pos: a character offset within @str
5326  * @end_pos: another character offset within @str
5327  *
5328  * Copies a substring out of a UTF-8 encoded string.
5329  * The substring will contain @end_pos - @start_pos
5330  * characters.
5331  *
5332  * Returns: a newly allocated copy of the requested
5333  *     substring. Free with g_free() when no longer needed.
5334  *
5335  * Since: GLIB 2.30
5336  */
5337 gchar *
5338 g_utf8_substring (const gchar *str,
5339                                   glong            start_pos,
5340                                   glong            end_pos)
5341 {
5342   gchar *start, *end, *out;
5343
5344   start = g_utf8_offset_to_pointer (str, start_pos);
5345   end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
5346
5347   out = g_malloc (end - start + 1);
5348   memcpy (out, start, end - start);
5349   out[end - start] = 0;
5350
5351   return out;
5352 }
5353 #endif
5354
5355 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
5356  * It is up to the caller to make sure there is at least count bytes
5357  * available at buf. */
5358 gboolean
5359 get_random_bytes(void *buf, size_t count)
5360 {
5361         /* Open our prng source. */
5362 #if defined G_OS_WIN32
5363         HCRYPTPROV rnd;
5364
5365         if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
5366                         !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
5367                 debug_print("Could not acquire a CSP handle.\n");
5368                 return FALSE;
5369         }
5370 #else
5371         int rnd;
5372         ssize_t ret;
5373
5374         rnd = open("/dev/urandom", O_RDONLY);
5375         if (rnd == -1) {
5376                 FILE_OP_ERROR("/dev/urandom", "open");
5377                 debug_print("Could not open /dev/urandom.\n");
5378                 return FALSE;
5379         }
5380 #endif
5381
5382         /* Read data from the source into buf. */
5383 #if defined G_OS_WIN32
5384         if (!CryptGenRandom(rnd, count, buf)) {
5385                 debug_print("Could not read %zd random bytes.\n", count);
5386                 CryptReleaseContext(rnd, 0);
5387                 return FALSE;
5388         }
5389 #else
5390         ret = read(rnd, buf, count);
5391         if (ret != count) {
5392                 FILE_OP_ERROR("/dev/urandom", "read");
5393                 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
5394                 close(rnd);
5395                 return FALSE;
5396         }
5397 #endif
5398
5399         /* Close the prng source. */
5400 #if defined G_OS_WIN32
5401         CryptReleaseContext(rnd, 0);
5402 #else
5403         close(rnd);
5404 #endif
5405
5406         return TRUE;
5407 }