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