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