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