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