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