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