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