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