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