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