2005-06-01 [colin] 1.9.11cvs31
[claws.git] / src / common / utils.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2005 Hiroyuki Yamamoto & The Sylpheed-Claws 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 2 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, write to the Free Software
17  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #  include "config.h"
22 #endif
23
24 #include "defs.h"
25
26 #include <glib.h>
27 #include <glib/gi18n.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <errno.h>
32
33 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
34 #  include <wchar.h>
35 #  include <wctype.h>
36 #endif
37 #include <stdlib.h>
38 #include <sys/stat.h>
39 #include <unistd.h>
40 #include <stdarg.h>
41 #include <sys/types.h>
42 #include <sys/wait.h>
43 #include <dirent.h>
44 #include <time.h>
45 #include <regex.h>
46 #include <sys/utsname.h>
47
48 #include "utils.h"
49 #include "socket.h"
50 #include "../codeconv.h"
51
52 #define BUFFSIZE        8192
53
54 static gboolean debug_mode = FALSE;
55
56 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
57
58 void list_free_strings(GList *list)
59 {
60         list = g_list_first(list);
61
62         while (list != NULL) {
63                 g_free(list->data);
64                 list = list->next;
65         }
66 }
67
68 void slist_free_strings(GSList *list)
69 {
70         while (list != NULL) {
71                 g_free(list->data);
72                 list = list->next;
73         }
74 }
75
76 GSList *slist_concat_unique (GSList *first, GSList *second)
77 {
78         GSList *tmp, *ret;
79         if (first == NULL) {
80                 if (second == NULL)
81                         return NULL;
82                 else 
83                         return second;
84         } else if (second == NULL)
85                 return first;
86         ret = first;
87         for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
88                 if (g_slist_find(ret, tmp->data) == NULL)
89                         ret = g_slist_prepend(ret, tmp->data);
90         }
91         return ret;
92 }
93  
94 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
95 {
96         g_free(key);
97 }
98
99 void hash_free_strings(GHashTable *table)
100 {
101         g_hash_table_foreach(table, hash_free_strings_func, NULL);
102 }
103
104 static void hash_free_value_mem_func(gpointer key, gpointer value,
105                                      gpointer data)
106 {
107         g_free(value);
108 }
109
110 void hash_free_value_mem(GHashTable *table)
111 {
112         g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
113 }
114
115 gint str_case_equal(gconstpointer v, gconstpointer v2)
116 {
117         return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
118 }
119
120 guint str_case_hash(gconstpointer key)
121 {
122         const gchar *p = key;
123         guint h = *p;
124
125         if (h) {
126                 h = tolower(h);
127                 for (p += 1; *p != '\0'; p++)
128                         h = (h << 5) - h + tolower(*p);
129         }
130
131         return h;
132 }
133
134 void ptr_array_free_strings(GPtrArray *array)
135 {
136         gint i;
137         gchar *str;
138
139         g_return_if_fail(array != NULL);
140
141         for (i = 0; i < array->len; i++) {
142                 str = g_ptr_array_index(array, i);
143                 g_free(str);
144         }
145 }
146
147 gboolean str_find(const gchar *haystack, const gchar *needle)
148 {
149         return strstr(haystack, needle) != NULL ? TRUE : FALSE;
150 }
151
152 gboolean str_case_find(const gchar *haystack, const gchar *needle)
153 {
154         return strcasestr(haystack, needle) != NULL ? TRUE : FALSE;
155 }
156
157 gboolean str_find_equal(const gchar *haystack, const gchar *needle)
158 {
159         return strcmp(haystack, needle) == 0;
160 }
161
162 gboolean str_case_find_equal(const gchar *haystack, const gchar *needle)
163 {
164         return strcasecmp(haystack, needle) == 0;
165 }
166
167 gint to_number(const gchar *nstr)
168 {
169         register const guchar *p;
170
171         if (*nstr == '\0') return -1;
172
173         for (p = nstr; *p != '\0'; p++)
174                 if (!isdigit(*p)) return -1;
175
176         return atoi(nstr);
177 }
178
179 /* convert integer into string,
180    nstr must be not lower than 11 characters length */
181 gchar *itos_buf(gchar *nstr, gint n)
182 {
183         g_snprintf(nstr, 11, "%d", n);
184         return nstr;
185 }
186
187 /* convert integer into string */
188 gchar *itos(gint n)
189 {
190         static gchar nstr[11];
191
192         return itos_buf(nstr, n);
193 }
194
195 gchar *to_human_readable(off_t size)
196 {
197         static gchar str[10];
198
199         if (size < 1024)
200                 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
201         else if (size >> 10 < 1024)
202                 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
203         else if (size >> 20 < 1024)
204                 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
205         else
206                 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
207
208         return str;
209 }
210
211 /* strcmp with NULL-checking */
212 gint strcmp2(const gchar *s1, const gchar *s2)
213 {
214         if (s1 == NULL || s2 == NULL)
215                 return -1;
216         else
217                 return strcmp(s1, s2);
218 }
219 /* strstr with NULL-checking */
220 gchar *strstr2(const gchar *s1, const gchar *s2)
221 {
222         if (s1 == NULL || s2 == NULL)
223                 return NULL;
224         else
225                 return strstr(s1, s2);
226 }
227 /* compare paths */
228 gint path_cmp(const gchar *s1, const gchar *s2)
229 {
230         gint len1, len2;
231
232         if (s1 == NULL || s2 == NULL) return -1;
233         if (*s1 == '\0' || *s2 == '\0') return -1;
234
235         len1 = strlen(s1);
236         len2 = strlen(s2);
237
238         if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
239         if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
240
241         return strncmp(s1, s2, MAX(len1, len2));
242 }
243
244 /* remove trailing return code */
245 gchar *strretchomp(gchar *str)
246 {
247         register gchar *s;
248
249         if (!*str) return str;
250
251         for (s = str + strlen(str) - 1;
252              s >= str && (*s == '\n' || *s == '\r');
253              s--)
254                 *s = '\0';
255
256         return str;
257 }
258
259 /* remove trailing character */
260 gchar *strtailchomp(gchar *str, gchar tail_char)
261 {
262         register gchar *s;
263
264         if (!*str) return str;
265         if (tail_char == '\0') return str;
266
267         for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
268                 *s = '\0';
269
270         return str;
271 }
272
273 /* remove CR (carriage return) */
274 gchar *strcrchomp(gchar *str)
275 {
276         register gchar *s;
277
278         if (!*str) return str;
279
280         s = str + strlen(str) - 1;
281         if (*s == '\n' && s > str && *(s - 1) == '\r') {
282                 *(s - 1) = '\n';
283                 *s = '\0';
284         }
285
286         return str;
287 }
288
289 /* Similar to `strstr' but this function ignores the case of both strings.  */
290 gchar *strcasestr(const gchar *haystack, const gchar *needle)
291 {
292         register size_t haystack_len, needle_len;
293
294         haystack_len = strlen(haystack);
295         needle_len   = strlen(needle);
296
297         if (haystack_len < needle_len || needle_len == 0)
298                 return NULL;
299
300         while (haystack_len >= needle_len) {
301                 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
302                         return (gchar *)haystack;
303                 else {
304                         haystack++;
305                         haystack_len--;
306                 }
307         }
308
309         return NULL;
310 }
311
312 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
313                    gconstpointer needle, size_t needlelen)
314 {
315         const gchar *haystack_ = (const gchar *)haystack;
316         const gchar *needle_ = (const gchar *)needle;
317         const gchar *haystack_cur = (const gchar *)haystack;
318
319         if (needlelen == 1)
320                 return memchr(haystack_, *needle_, haystacklen);
321
322         while ((haystack_cur = memchr(haystack_cur, *needle_, haystacklen))
323                != NULL) {
324                 if (haystacklen - (haystack_cur - haystack_) < needlelen)
325                         break;
326                 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
327                         return (gpointer)haystack_cur;
328                 else
329                         haystack_cur++;
330         }
331
332         return NULL;
333 }
334
335 /* Copy no more than N characters of SRC to DEST, with NULL terminating.  */
336 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
337 {
338         register const gchar *s = src;
339         register gchar *d = dest;
340
341         while (--n && *s)
342                 *d++ = *s++;
343         *d = '\0';
344
345         return dest;
346 }
347
348 #if !HAVE_ISWALNUM
349 int iswalnum(wint_t wc)
350 {
351         return isalnum((int)wc);
352 }
353 #endif
354
355 #if !HAVE_ISWSPACE
356 int iswspace(wint_t wc)
357 {
358         return isspace((int)wc);
359 }
360 #endif
361
362 #if !HAVE_TOWLOWER
363 wint_t towlower(wint_t wc)
364 {
365         if (wc >= L'A' && wc <= L'Z')
366                 return wc + L'a' - L'A';
367
368         return wc;
369 }
370 #endif
371
372 #if !HAVE_WCSLEN
373 size_t wcslen(const wchar_t *s)
374 {
375         size_t len = 0;
376
377         while (*s != L'\0')
378                 ++len, ++s;
379
380         return len;
381 }
382 #endif
383
384 #if !HAVE_WCSCPY
385 /* Copy SRC to DEST.  */
386 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
387 {
388         wint_t c;
389         wchar_t *s = dest;
390
391         do {
392                 c = *src++;
393                 *dest++ = c;
394         } while (c != L'\0');
395
396         return s;
397 }
398 #endif
399
400 #if !HAVE_WCSNCPY
401 /* Copy no more than N wide-characters of SRC to DEST.  */
402 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
403 {
404         wint_t c;
405         wchar_t *s = dest;
406
407         do {
408                 c = *src++;
409                 *dest++ = c;
410                 if (--n == 0)
411                         return s;
412         } while (c != L'\0');
413
414         /* zero fill */
415         do
416                 *dest++ = L'\0';
417         while (--n > 0);
418
419         return s;
420 }
421 #endif
422
423 /* Duplicate S, returning an identical malloc'd string. */
424 wchar_t *wcsdup(const wchar_t *s)
425 {
426         wchar_t *new_str;
427
428         if (s) {
429                 new_str = g_new(wchar_t, wcslen(s) + 1);
430                 wcscpy(new_str, s);
431         } else
432                 new_str = NULL;
433
434         return new_str;
435 }
436
437 /* Duplicate no more than N wide-characters of S,
438    returning an identical malloc'd string. */
439 wchar_t *wcsndup(const wchar_t *s, size_t n)
440 {
441         wchar_t *new_str;
442
443         if (s) {
444                 new_str = g_new(wchar_t, n + 1);
445                 wcsncpy(new_str, s, n);
446                 new_str[n] = (wchar_t)0;
447         } else
448                 new_str = NULL;
449
450         return new_str;
451 }
452
453 wchar_t *strdup_mbstowcs(const gchar *s)
454 {
455         wchar_t *new_str;
456
457         if (s) {
458                 new_str = g_new(wchar_t, strlen(s) + 1);
459                 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
460                         g_free(new_str);
461                         new_str = NULL;
462                 } else
463                         new_str = g_realloc(new_str,
464                                             sizeof(wchar_t) * (wcslen(new_str) + 1));
465         } else
466                 new_str = NULL;
467
468         return new_str;
469 }
470
471 gchar *strdup_wcstombs(const wchar_t *s)
472 {
473         gchar *new_str;
474         size_t len;
475
476         if (s) {
477                 len = wcslen(s) * MB_CUR_MAX + 1;
478                 new_str = g_new(gchar, len);
479                 if (wcstombs(new_str, s, len) < 0) {
480                         g_free(new_str);
481                         new_str = NULL;
482                 } else
483                         new_str = g_realloc(new_str, strlen(new_str) + 1);
484         } else
485                 new_str = NULL;
486
487         return new_str;
488 }
489
490 /* Compare S1 and S2, ignoring case.  */
491 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
492 {
493         wint_t c1;
494         wint_t c2;
495
496         while (n--) {
497                 c1 = towlower(*s1++);
498                 c2 = towlower(*s2++);
499                 if (c1 != c2)
500                         return c1 - c2;
501                 else if (c1 == 0 && c2 == 0)
502                         break;
503         }
504
505         return 0;
506 }
507
508 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case.  */
509 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
510 {
511         register size_t haystack_len, needle_len;
512
513         haystack_len = wcslen(haystack);
514         needle_len   = wcslen(needle);
515
516         if (haystack_len < needle_len || needle_len == 0)
517                 return NULL;
518
519         while (haystack_len >= needle_len) {
520                 if (!wcsncasecmp(haystack, needle, needle_len))
521                         return (wchar_t *)haystack;
522                 else {
523                         haystack++;
524                         haystack_len--;
525                 }
526         }
527
528         return NULL;
529 }
530
531 gint get_mbs_len(const gchar *s)
532 {
533         const gchar *p = s;
534         gint mb_len;
535         gint len = 0;
536
537         if (!p)
538                 return -1;
539
540         while (*p != '\0') {
541                 mb_len = g_utf8_skip[*(guchar *)p];
542                 if (mb_len == 0)
543                         break;
544                 else
545                         len++;
546
547                 p += mb_len;
548         }
549
550         return len;
551 }
552
553 /* Examine if next block is non-ASCII string */
554 gboolean is_next_nonascii(const guchar *s)
555 {
556         const guchar *p;
557
558         /* skip head space */
559         for (p = s; *p != '\0' && isspace(*p); p++)
560                 ;
561         for (; *p != '\0' && !isspace(*p); p++) {
562                 if (*p > 127 || *p < 32)
563                         return TRUE;
564         }
565
566         return FALSE;
567 }
568
569 gint get_next_word_len(const guchar *s)
570 {
571         gint len = 0;
572
573         for (; *s != '\0' && !isspace(*s); s++, len++)
574                 ;
575
576         return len;
577 }
578
579 /* compare subjects */
580 gint subject_compare(const gchar *s1, const gchar *s2)
581 {
582         gchar *str1, *str2;
583
584         if (!s1 || !s2) return -1;
585         if (!*s1 || !*s2) return -1;
586
587         Xstrdup_a(str1, s1, return -1);
588         Xstrdup_a(str2, s2, return -1);
589
590         trim_subject_for_compare(str1);
591         trim_subject_for_compare(str2);
592
593         if (!*str1 || !*str2) return -1;
594
595         return strcmp(str1, str2);
596 }
597
598 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
599 {
600         gchar *str1, *str2;
601
602         if (!s1 || !s2) return -1;
603
604         Xstrdup_a(str1, s1, return -1);
605         Xstrdup_a(str2, s2, return -1);
606
607         trim_subject_for_sort(str1);
608         trim_subject_for_sort(str2);
609
610         return g_utf8_collate(str1, str2);
611 }
612
613 void trim_subject_for_compare(gchar *str)
614 {
615         gchar *srcp;
616
617         eliminate_parenthesis(str, '[', ']');
618         eliminate_parenthesis(str, '(', ')');
619         g_strstrip(str);
620
621         srcp = str + subject_get_prefix_length(str);
622         if (srcp != str)
623                 memmove(str, srcp, strlen(srcp) + 1);
624 }
625
626 void trim_subject_for_sort(gchar *str)
627 {
628         gchar *srcp;
629
630         g_strstrip(str);
631
632         srcp = str + subject_get_prefix_length(str);
633         if (srcp != str)        
634                 memmove(str, srcp, strlen(srcp) + 1);
635 }
636
637 void trim_subject(gchar *str)
638 {
639         register guchar *srcp;
640         gchar op, cl;
641         gint in_brace;
642         
643         g_strstrip(str);
644
645         srcp = str + subject_get_prefix_length(str);
646
647         if (*srcp == '[') {
648                 op = '[';
649                 cl = ']';
650         } else if (*srcp == '(') {
651                 op = '(';
652                 cl = ')';
653         } else
654                 op = 0;
655
656         if (op) {
657                 ++srcp;
658                 in_brace = 1;
659                 while (*srcp) {
660                         if (*srcp == op)
661                                 in_brace++;
662                         else if (*srcp == cl)
663                                 in_brace--;
664                         srcp++;
665                         if (in_brace == 0)
666                                 break;
667                 }
668         }
669         while (isspace(*srcp)) srcp++;
670         memmove(str, srcp, strlen(srcp) + 1);
671 }
672
673 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
674 {
675         register guchar *srcp, *destp;
676         gint in_brace;
677
678         srcp = destp = str;
679
680         while ((destp = strchr(destp, op))) {
681                 in_brace = 1;
682                 srcp = destp + 1;
683                 while (*srcp) {
684                         if (*srcp == op)
685                                 in_brace++;
686                         else if (*srcp == cl)
687                                 in_brace--;
688                         srcp++;
689                         if (in_brace == 0)
690                                 break;
691                 }
692                 while (isspace(*srcp)) srcp++;
693                 memmove(destp, srcp, strlen(srcp) + 1);
694         }
695 }
696
697 void extract_parenthesis(gchar *str, gchar op, gchar cl)
698 {
699         register gchar *srcp, *destp;
700         gint in_brace;
701
702         srcp = destp = str;
703
704         while ((srcp = strchr(destp, op))) {
705                 if (destp > str)
706                         *destp++ = ' ';
707                 memmove(destp, srcp + 1, strlen(srcp));
708                 in_brace = 1;
709                 while(*destp) {
710                         if (*destp == op)
711                                 in_brace++;
712                         else if (*destp == cl)
713                                 in_brace--;
714
715                         if (in_brace == 0)
716                                 break;
717
718                         destp++;
719                 }
720         }
721         *destp = '\0';
722 }
723
724 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
725                                          gchar op, gchar cl)
726 {
727         register gchar *srcp, *destp;
728         gint in_brace;
729         gboolean in_quote = FALSE;
730
731         srcp = destp = str;
732
733         while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
734                 if (destp > str)
735                         *destp++ = ' ';
736                 memmove(destp, srcp + 1, strlen(srcp));
737                 in_brace = 1;
738                 while(*destp) {
739                         if (*destp == op && !in_quote)
740                                 in_brace++;
741                         else if (*destp == cl && !in_quote)
742                                 in_brace--;
743                         else if (*destp == quote_chr)
744                                 in_quote ^= TRUE;
745
746                         if (in_brace == 0)
747                                 break;
748
749                         destp++;
750                 }
751         }
752         *destp = '\0';
753 }
754
755 void eliminate_quote(gchar *str, gchar quote_chr)
756 {
757         register guchar *srcp, *destp;
758
759         srcp = destp = str;
760
761         while ((destp = strchr(destp, quote_chr))) {
762                 if ((srcp = strchr(destp + 1, quote_chr))) {
763                         srcp++;
764                         while (isspace(*srcp)) srcp++;
765                         memmove(destp, srcp, strlen(srcp) + 1);
766                 } else {
767                         *destp = '\0';
768                         break;
769                 }
770         }
771 }
772
773 void extract_quote(gchar *str, gchar quote_chr)
774 {
775         register gchar *p;
776
777         if ((str = strchr(str, quote_chr))) {
778                 p = str;
779                 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
780                         memmove(p - 1, p, strlen(p) + 1);
781                         p--;
782                 }
783                 if(p) {
784                         *p = '\0';
785                         memmove(str, str + 1, p - str);
786                 }
787         }
788 }
789
790 void eliminate_address_comment(gchar *str)
791 {
792         register guchar *srcp, *destp;
793         gint in_brace;
794
795         srcp = destp = str;
796
797         while ((destp = strchr(destp, '"'))) {
798                 if ((srcp = strchr(destp + 1, '"'))) {
799                         srcp++;
800                         if (*srcp == '@') {
801                                 destp = srcp + 1;
802                         } else {
803                                 while (isspace(*srcp)) srcp++;
804                                 memmove(destp, srcp, strlen(srcp) + 1);
805                         }
806                 } else {
807                         *destp = '\0';
808                         break;
809                 }
810         }
811
812         srcp = destp = str;
813
814         while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
815                 in_brace = 1;
816                 srcp = destp + 1;
817                 while (*srcp) {
818                         if (*srcp == '(')
819                                 in_brace++;
820                         else if (*srcp == ')')
821                                 in_brace--;
822                         srcp++;
823                         if (in_brace == 0)
824                                 break;
825                 }
826                 while (isspace(*srcp)) srcp++;
827                 memmove(destp, srcp, strlen(srcp) + 1);
828         }
829 }
830
831 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
832 {
833         gboolean in_quote = FALSE;
834
835         while (*str) {
836                 if (*str == c && !in_quote)
837                         return (gchar *)str;
838                 if (*str == quote_chr)
839                         in_quote ^= TRUE;
840                 str++;
841         }
842
843         return NULL;
844 }
845
846 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
847 {
848         gboolean in_quote = FALSE;
849         const gchar *p;
850
851         p = str + strlen(str) - 1;
852         while (p >= str) {
853                 if (*p == c && !in_quote)
854                         return (gchar *)p;
855                 if (*p == quote_chr)
856                         in_quote ^= TRUE;
857                 p--;
858         }
859
860         return NULL;
861 }
862
863 void extract_address(gchar *str)
864 {
865         eliminate_address_comment(str);
866         if (strchr_with_skip_quote(str, '"', '<'))
867                 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
868         g_strstrip(str);
869 }
870
871 void extract_list_id_str(gchar *str)
872 {
873         if (strchr_with_skip_quote(str, '"', '<'))
874                 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
875         g_strstrip(str);
876 }
877
878 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
879 {
880         gchar *work;
881         gchar *workp;
882
883         if (!str) return addr_list;
884
885         Xstrdup_a(work, str, return addr_list);
886
887         if (removecomments)
888                 eliminate_address_comment(work);
889         workp = work;
890
891         while (workp && *workp) {
892                 gchar *p, *next;
893
894                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
895                         *p = '\0';
896                         next = p + 1;
897                 } else
898                         next = NULL;
899
900                 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
901                         extract_parenthesis_with_skip_quote
902                                 (workp, '"', '<', '>');
903
904                 g_strstrip(workp);
905                 if (*workp)
906                         addr_list = g_slist_append(addr_list, g_strdup(workp));
907
908                 workp = next;
909         }
910
911         return addr_list;
912 }
913
914 GSList *address_list_append(GSList *addr_list, const gchar *str)
915 {
916         return address_list_append_real(addr_list, str, TRUE);
917 }
918
919 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
920 {
921         return address_list_append_real(addr_list, str, FALSE);
922 }
923
924 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
925 {
926         const gchar *strp;
927
928         if (!str) return msgid_list;
929         strp = str;
930
931         while (strp && *strp) {
932                 const gchar *start, *end;
933                 gchar *msgid;
934
935                 if ((start = strchr(strp, '<')) != NULL) {
936                         end = strchr(start + 1, '>');
937                         if (!end) break;
938                 } else
939                         break;
940
941                 msgid = g_strndup(start + 1, end - start - 1);
942                 g_strstrip(msgid);
943                 if (*msgid)
944                         msgid_list = g_slist_prepend(msgid_list, msgid);
945                 else
946                         g_free(msgid);
947
948                 strp = end + 1;
949         }
950
951         return msgid_list;
952 }
953
954 GSList *references_list_append(GSList *msgid_list, const gchar *str)
955 {
956         GSList *list;
957
958         list = references_list_prepend(NULL, str);
959         list = g_slist_reverse(list);
960         msgid_list = g_slist_concat(msgid_list, list);
961
962         return msgid_list;
963 }
964
965 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
966 {
967         gchar *work;
968         gchar *workp;
969
970         if (!str) return group_list;
971
972         Xstrdup_a(work, str, return group_list);
973
974         workp = work;
975
976         while (workp && *workp) {
977                 gchar *p, *next;
978
979                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
980                         *p = '\0';
981                         next = p + 1;
982                 } else
983                         next = NULL;
984
985                 g_strstrip(workp);
986                 if (*workp)
987                         group_list = g_slist_append(group_list,
988                                                     g_strdup(workp));
989
990                 workp = next;
991         }
992
993         return group_list;
994 }
995
996 GList *add_history(GList *list, const gchar *str)
997 {
998         GList *old;
999
1000         g_return_val_if_fail(str != NULL, list);
1001
1002         old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
1003         if (old) {
1004                 g_free(old->data);
1005                 list = g_list_remove(list, old->data);
1006         } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
1007                 GList *last;
1008
1009                 last = g_list_last(list);
1010                 if (last) {
1011                         g_free(last->data);
1012                         g_list_remove(list, last->data);
1013                 }
1014         }
1015
1016         list = g_list_prepend(list, g_strdup(str));
1017
1018         return list;
1019 }
1020
1021 void remove_return(gchar *str)
1022 {
1023         register gchar *p = str;
1024
1025         while (*p) {
1026                 if (*p == '\n' || *p == '\r')
1027                         memmove(p, p + 1, strlen(p));
1028                 else
1029                         p++;
1030         }
1031 }
1032
1033 void remove_space(gchar *str)
1034 {
1035         register guchar *p = str;
1036         register gint spc;
1037
1038         while (*p) {
1039                 spc = 0;
1040                 while (isspace(*(p + spc)))
1041                         spc++;
1042                 if (spc)
1043                         memmove(p, p + spc, strlen(p + spc) + 1);
1044                 else
1045                         p++;
1046         }
1047 }
1048
1049 void unfold_line(gchar *str)
1050 {
1051         register guchar *p = str;
1052         register gint spc;
1053
1054         while (*p) {
1055                 if (*p == '\n' || *p == '\r') {
1056                         *p++ = ' ';
1057                         spc = 0;
1058                         while (isspace(*(p + spc)))
1059                                 spc++;
1060                         if (spc)
1061                                 memmove(p, p + spc, strlen(p + spc) + 1);
1062                 } else
1063                         p++;
1064         }
1065 }
1066
1067 void subst_char(gchar *str, gchar orig, gchar subst)
1068 {
1069         register gchar *p = str;
1070
1071         while (*p) {
1072                 if (*p == orig)
1073                         *p = subst;
1074                 p++;
1075         }
1076 }
1077
1078 void subst_chars(gchar *str, gchar *orig, gchar subst)
1079 {
1080         register gchar *p = str;
1081
1082         while (*p) {
1083                 if (strchr(orig, *p) != NULL)
1084                         *p = subst;
1085                 p++;
1086         }
1087 }
1088
1089 void subst_for_filename(gchar *str)
1090 {
1091         if (!str)
1092                 return;
1093         subst_chars(str, "\t\r\n\\/*", '_');
1094 }
1095
1096 void subst_for_shellsafe_filename(gchar *str)
1097 {
1098         if (!str)
1099                 return;
1100         subst_for_filename(str);
1101         subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1102 }
1103
1104 gboolean is_header_line(const gchar *str)
1105 {
1106         if (str[0] == ':') return FALSE;
1107
1108         while (*str != '\0' && *str != ' ') {
1109                 if (*str == ':')
1110                         return TRUE;
1111                 str++;
1112         }
1113
1114         return FALSE;
1115 }
1116
1117 gboolean is_ascii_str(const guchar *str)
1118 {
1119         g_return_val_if_fail(str, FALSE);
1120
1121         while (*str != '\0') {
1122                 if (*str != '\t' && *str != ' ' &&
1123                     *str != '\r' && *str != '\n' &&
1124                     (*str < 32 || *str >= 127))
1125                         return FALSE;
1126                 str++;
1127         }
1128
1129         return TRUE;
1130 }
1131
1132 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1133 {
1134         const guchar *first_pos;
1135         const guchar *last_pos;
1136         const guchar *p = str;
1137         gint quote_level = -1;
1138
1139         /* speed up line processing by only searching to the last '>' */
1140         if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1141                 /* skip a line if it contains a '<' before the initial '>' */
1142                 if (memchr(str, '<', first_pos - (const guchar *)str) != NULL)
1143                         return -1;
1144                 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1145         } else
1146                 return -1;
1147
1148         while (p <= last_pos) {
1149                 while (p < last_pos) {
1150                         if (isspace(*p))
1151                                 p++;
1152                         else
1153                                 break;
1154                 }
1155
1156                 if (strchr(quote_chars, *p))
1157                         quote_level++;
1158                 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1159                         /* any characters are allowed except '-' and space */
1160                         while (*p != '-' 
1161                                && !strchr(quote_chars, *p) 
1162                                && !isspace(*p) 
1163                                && p < last_pos)
1164                                 p++;
1165                         if (strchr(quote_chars, *p))
1166                                 quote_level++;
1167                         else
1168                                 break;
1169                 }
1170
1171                 p++;
1172         }
1173
1174         return quote_level;
1175 }
1176
1177 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars) 
1178 {
1179         gchar * position = NULL;
1180         gchar * tmp_pos = NULL;
1181         int i;
1182
1183         if (quote_chars == NULL)
1184                 return FALSE;
1185         
1186         for (i = 0; i < strlen(quote_chars); i++) {
1187                 tmp_pos = strchr (str,  quote_chars[i]);
1188                 if(position == NULL 
1189                    || (tmp_pos != NULL && position >= tmp_pos) )
1190                         position = tmp_pos;
1191         }
1192         return position; 
1193 }
1194
1195 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars) 
1196 {
1197         gchar * position = NULL;
1198         gchar * tmp_pos = NULL;
1199         int i;
1200
1201         if (quote_chars == NULL)
1202                 return FALSE;
1203         
1204         for (i = 0; i < strlen(quote_chars); i++) {
1205                 tmp_pos = strrchr (str, quote_chars[i]);
1206                 if(position == NULL 
1207                    || (tmp_pos != NULL && position <= tmp_pos) )
1208                         position = tmp_pos;
1209         }
1210         return position; 
1211 }
1212
1213 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1214 {
1215         register guint haystack_len, needle_len;
1216         gboolean in_squote = FALSE, in_dquote = FALSE;
1217
1218         haystack_len = strlen(haystack);
1219         needle_len   = strlen(needle);
1220
1221         if (haystack_len < needle_len || needle_len == 0)
1222                 return NULL;
1223
1224         while (haystack_len >= needle_len) {
1225                 if (!in_squote && !in_dquote &&
1226                     !strncmp(haystack, needle, needle_len))
1227                         return (gchar *)haystack;
1228
1229                 /* 'foo"bar"' -> foo"bar"
1230                    "foo'bar'" -> foo'bar' */
1231                 if (*haystack == '\'') {
1232                         if (in_squote)
1233                                 in_squote = FALSE;
1234                         else if (!in_dquote)
1235                                 in_squote = TRUE;
1236                 } else if (*haystack == '\"') {
1237                         if (in_dquote)
1238                                 in_dquote = FALSE;
1239                         else if (!in_squote)
1240                                 in_dquote = TRUE;
1241                 }
1242
1243                 haystack++;
1244                 haystack_len--;
1245         }
1246
1247         return NULL;
1248 }
1249
1250 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1251 {
1252         const gchar *p;
1253         gchar quote_chr = '"';
1254         gint in_brace;
1255         gboolean in_quote = FALSE;
1256
1257         p = str;
1258
1259         if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1260                 p++;
1261                 in_brace = 1;
1262                 while (*p) {
1263                         if (*p == op && !in_quote)
1264                                 in_brace++;
1265                         else if (*p == cl && !in_quote)
1266                                 in_brace--;
1267                         else if (*p == quote_chr)
1268                                 in_quote ^= TRUE;
1269
1270                         if (in_brace == 0)
1271                                 return (gchar *)p;
1272
1273                         p++;
1274                 }
1275         }
1276
1277         return NULL;
1278 }
1279
1280 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1281                              gint max_tokens)
1282 {
1283         GSList *string_list = NULL, *slist;
1284         gchar **str_array;
1285         const gchar *s_op, *s_cl;
1286         guint i, n = 1;
1287
1288         g_return_val_if_fail(str != NULL, NULL);
1289
1290         if (max_tokens < 1)
1291                 max_tokens = G_MAXINT;
1292
1293         s_op = strchr_with_skip_quote(str, '"', op);
1294         if (!s_op) return NULL;
1295         str = s_op;
1296         s_cl = strchr_parenthesis_close(str, op, cl);
1297         if (s_cl) {
1298                 do {
1299                         guint len;
1300                         gchar *new_string;
1301
1302                         str++;
1303                         len = s_cl - str;
1304                         new_string = g_new(gchar, len + 1);
1305                         strncpy(new_string, str, len);
1306                         new_string[len] = 0;
1307                         string_list = g_slist_prepend(string_list, new_string);
1308                         n++;
1309                         str = s_cl + 1;
1310
1311                         while (*str && isspace(*(guchar *)str)) str++;
1312                         if (*str != op) {
1313                                 string_list = g_slist_prepend(string_list,
1314                                                               g_strdup(""));
1315                                 n++;
1316                                 s_op = strchr_with_skip_quote(str, '"', op);
1317                                 if (!--max_tokens || !s_op) break;
1318                                 str = s_op;
1319                         } else
1320                                 s_op = str;
1321                         s_cl = strchr_parenthesis_close(str, op, cl);
1322                 } while (--max_tokens && s_cl);
1323         }
1324
1325         str_array = g_new(gchar*, n);
1326
1327         i = n - 1;
1328
1329         str_array[i--] = NULL;
1330         for (slist = string_list; slist; slist = slist->next)
1331                 str_array[i--] = slist->data;
1332
1333         g_slist_free(string_list);
1334
1335         return str_array;
1336 }
1337
1338 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1339                             gint max_tokens)
1340 {
1341         GSList *string_list = NULL, *slist;
1342         gchar **str_array, *s, *new_str;
1343         guint i, n = 1, len;
1344
1345         g_return_val_if_fail(str != NULL, NULL);
1346         g_return_val_if_fail(delim != NULL, NULL);
1347
1348         if (max_tokens < 1)
1349                 max_tokens = G_MAXINT;
1350
1351         s = strstr_with_skip_quote(str, delim);
1352         if (s) {
1353                 guint delimiter_len = strlen(delim);
1354
1355                 do {
1356                         len = s - str;
1357                         new_str = g_strndup(str, len);
1358
1359                         if (new_str[0] == '\'' || new_str[0] == '\"') {
1360                                 if (new_str[len - 1] == new_str[0]) {
1361                                         new_str[len - 1] = '\0';
1362                                         memmove(new_str, new_str + 1, len - 1);
1363                                 }
1364                         }
1365                         string_list = g_slist_prepend(string_list, new_str);
1366                         n++;
1367                         str = s + delimiter_len;
1368                         s = strstr_with_skip_quote(str, delim);
1369                 } while (--max_tokens && s);
1370         }
1371
1372         if (*str) {
1373                 new_str = g_strdup(str);
1374                 if (new_str[0] == '\'' || new_str[0] == '\"') {
1375                         len = strlen(str);
1376                         if (new_str[len - 1] == new_str[0]) {
1377                                 new_str[len - 1] = '\0';
1378                                 memmove(new_str, new_str + 1, len - 1);
1379                         }
1380                 }
1381                 string_list = g_slist_prepend(string_list, new_str);
1382                 n++;
1383         }
1384
1385         str_array = g_new(gchar*, n);
1386
1387         i = n - 1;
1388
1389         str_array[i--] = NULL;
1390         for (slist = string_list; slist; slist = slist->next)
1391                 str_array[i--] = slist->data;
1392
1393         g_slist_free(string_list);
1394
1395         return str_array;
1396 }
1397
1398 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1399 {
1400         gchar *abbrev_group;
1401         gchar *ap;
1402         const gchar *p = group;
1403         const gchar *last;
1404
1405         g_return_val_if_fail(group != NULL, NULL);
1406
1407         last = group + strlen(group);
1408         abbrev_group = ap = g_malloc(strlen(group) + 1);
1409
1410         while (*p) {
1411                 while (*p == '.')
1412                         *ap++ = *p++;
1413                 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1414                         *ap++ = *p++;
1415                         while (*p != '.') p++;
1416                 } else {
1417                         strcpy(ap, p);
1418                         return abbrev_group;
1419                 }
1420         }
1421
1422         *ap = '\0';
1423         return abbrev_group;
1424 }
1425
1426 gchar *trim_string(const gchar *str, gint len)
1427 {
1428         const gchar *p = str;
1429         gint mb_len;
1430         gchar *new_str;
1431         gint new_len = 0;
1432
1433         if (!str) return NULL;
1434         if (strlen(str) <= len)
1435                 return g_strdup(str);
1436         if (g_utf8_validate(str, -1, NULL) == FALSE)
1437                 return g_strdup(str);
1438
1439         while (*p != '\0') {
1440                 mb_len = g_utf8_skip[*(guchar *)p];
1441                 if (mb_len == 0)
1442                         break;
1443                 else if (new_len + mb_len > len)
1444                         break;
1445
1446                 new_len += mb_len;
1447                 p += mb_len;
1448         }
1449
1450         Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1451         return g_strconcat(new_str, "...", NULL);
1452 }
1453
1454 GList *uri_list_extract_filenames(const gchar *uri_list)
1455 {
1456         GList *result = NULL;
1457         const gchar *p, *q;
1458         gchar *escaped_utf8uri;
1459
1460         p = uri_list;
1461
1462         while (p) {
1463                 if (*p != '#') {
1464                         while (isspace(*p)) p++;
1465                         if (!strncmp(p, "file:", 5)) {
1466                                 q = p;
1467                                 q += 5;
1468                                 while (*q && *q != '\n' && *q != '\r') q++;
1469
1470                                 if (q > p) {
1471                                         gchar *file, *locale_file = NULL;
1472                                         q--;
1473                                         while (q > p && isspace(*q)) q--;
1474                                         Xalloca(escaped_utf8uri, q - p + 2,
1475                                                 return result);
1476                                         Xalloca(file, q - p + 2,
1477                                                 return result);
1478                                         *file = '\0';
1479                                         strncpy(escaped_utf8uri, p, q - p + 1);
1480                                         escaped_utf8uri[q - p + 1] = '\0';
1481                                         decode_uri(file, escaped_utf8uri);
1482                     /*
1483                      * g_filename_from_uri() rejects escaped/locale encoded uri
1484                      * string which come from Nautilus.
1485                      */
1486                                         if (g_utf8_validate(file, -1, NULL))
1487                                                 locale_file
1488                                                         = conv_codeset_strdup(
1489                                                                 file + 5,
1490                                                                 CS_UTF_8,
1491                                                                 conv_get_locale_charset_str());
1492                                         if (!locale_file)
1493                                                 locale_file = g_strdup(file + 5);
1494                                         result = g_list_append(result, locale_file);
1495                                 }
1496                         }
1497                 }
1498                 p = strchr(p, '\n');
1499                 if (p) p++;
1500         }
1501
1502         return result;
1503 }
1504
1505 /* Converts two-digit hexadecimal to decimal.  Used for unescaping escaped 
1506  * characters
1507  */
1508 static gint axtoi(const gchar *hexstr)
1509 {
1510         gint hi, lo, result;
1511        
1512         hi = hexstr[0];
1513         if ('0' <= hi && hi <= '9') {
1514                 hi -= '0';
1515         } else
1516                 if ('a' <= hi && hi <= 'f') {
1517                         hi -= ('a' - 10);
1518                 } else
1519                         if ('A' <= hi && hi <= 'F') {
1520                                 hi -= ('A' - 10);
1521                         }
1522
1523         lo = hexstr[1];
1524         if ('0' <= lo && lo <= '9') {
1525                 lo -= '0';
1526         } else
1527                 if ('a' <= lo && lo <= 'f') {
1528                         lo -= ('a'-10);
1529                 } else
1530                         if ('A' <= lo && lo <= 'F') {
1531                                 lo -= ('A' - 10);
1532                         }
1533         result = lo + (16 * hi);
1534         return result;
1535 }
1536
1537 gboolean is_uri_string(const gchar *str)
1538 {
1539         return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1540                 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1541                 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1542                 g_ascii_strncasecmp(str, "www.", 4) == 0);
1543 }
1544
1545 gchar *get_uri_path(const gchar *uri)
1546 {
1547         if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1548                 return (gchar *)(uri + 7);
1549         else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1550                 return (gchar *)(uri + 8);
1551         else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1552                 return (gchar *)(uri + 6);
1553         else
1554                 return (gchar *)uri;
1555 }
1556
1557 gint get_uri_len(const gchar *str)
1558 {
1559         const gchar *p;
1560
1561         if (is_uri_string(str)) {
1562                 for (p = str; *p != '\0'; p++) {
1563                         if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1564                                 break;
1565                 }
1566                 return p - str;
1567         }
1568
1569         return 0;
1570 }
1571
1572 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1573  * plusses, and escape characters are used)
1574  */
1575 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1576 {
1577         gchar *dec = decoded_uri;
1578         const gchar *enc = encoded_uri;
1579
1580         while (*enc) {
1581                 if (*enc == '%') {
1582                         enc++;
1583                         if (isxdigit((guchar)enc[0]) &&
1584                             isxdigit((guchar)enc[1])) {
1585                                 *dec = axtoi(enc);
1586                                 dec++;
1587                                 enc += 2;
1588                         }
1589                 } else {
1590                         if (*enc == '+')
1591                                 *dec = ' ';
1592                         else
1593                                 *dec = *enc;
1594                         dec++;
1595                         enc++;
1596                 }
1597         }
1598
1599         *dec = '\0';
1600 }
1601
1602 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1603                      gchar **subject, gchar **body)
1604 {
1605         gchar *tmp_mailto;
1606         gchar *p;
1607
1608         Xstrdup_a(tmp_mailto, mailto, return -1);
1609
1610         if (!strncmp(tmp_mailto, "mailto:", 7))
1611                 tmp_mailto += 7;
1612
1613         p = strchr(tmp_mailto, '?');
1614         if (p) {
1615                 *p = '\0';
1616                 p++;
1617         }
1618
1619         if (to && !*to)
1620                 *to = g_strdup(tmp_mailto);
1621
1622         while (p) {
1623                 gchar *field, *value;
1624
1625                 field = p;
1626
1627                 p = strchr(p, '=');
1628                 if (!p) break;
1629                 *p = '\0';
1630                 p++;
1631
1632                 value = p;
1633
1634                 p = strchr(p, '&');
1635                 if (p) {
1636                         *p = '\0';
1637                         p++;
1638                 }
1639
1640                 if (*value == '\0') continue;
1641
1642                 if (cc && !*cc && !g_ascii_strcasecmp(field, "cc")) {
1643                         *cc = g_strdup(value);
1644                 } else if (bcc && !*bcc && !g_ascii_strcasecmp(field, "bcc")) {
1645                         *bcc = g_strdup(value);
1646                 } else if (subject && !*subject &&
1647                            !g_ascii_strcasecmp(field, "subject")) {
1648                         *subject = g_malloc(strlen(value) + 1);
1649                         decode_uri(*subject, value);
1650                 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1651                         *body = g_malloc(strlen(value) + 1);
1652                         decode_uri(*body, value);
1653                 }
1654         }
1655
1656         return 0;
1657 }
1658
1659 /*
1660  * We need this wrapper around g_get_home_dir(), so that
1661  * we can fix some Windoze things here.  Should be done in glibc of course
1662  * but as long as we are not able to do our own extensions to glibc, we do
1663  * it here.
1664  */
1665 const gchar *get_home_dir(void)
1666 {
1667 #if HAVE_DOSISH_SYSTEM
1668     static gchar *home_dir;
1669
1670     if (!home_dir) {
1671         home_dir = read_w32_registry_string(NULL,
1672                                             "Software\\Sylpheed", "HomeDir" );
1673         if (!home_dir || !*home_dir) {
1674             if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1675                 const char *s = g_get_home_dir();
1676                 if (s && *s)
1677                     home_dir = g_strdup (s);
1678             }
1679             if (!home_dir || !*home_dir) 
1680                 home_dir = g_strdup ("c:\\sylpheed");
1681         }
1682         debug_print("initialized home_dir to `%s'\n", home_dir);
1683     }
1684     return home_dir;
1685 #else /* standard glib */
1686     return g_get_home_dir();
1687 #endif
1688 }
1689
1690 const gchar *get_rc_dir(void)
1691 {
1692         static gchar *rc_dir = NULL;
1693
1694         if (!rc_dir)
1695                 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1696                                      RC_DIR, NULL);
1697
1698         return rc_dir;
1699 }
1700
1701 const gchar *get_news_cache_dir(void)
1702 {
1703         static gchar *news_cache_dir = NULL;
1704
1705         if (!news_cache_dir)
1706                 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1707                                              NEWS_CACHE_DIR, NULL);
1708
1709         return news_cache_dir;
1710 }
1711
1712 const gchar *get_imap_cache_dir(void)
1713 {
1714         static gchar *imap_cache_dir = NULL;
1715
1716         if (!imap_cache_dir)
1717                 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1718                                              IMAP_CACHE_DIR, NULL);
1719
1720         return imap_cache_dir;
1721 }
1722
1723 const gchar *get_mbox_cache_dir(void)
1724 {
1725         static gchar *mbox_cache_dir = NULL;
1726
1727         if (!mbox_cache_dir)
1728                 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1729                                              MBOX_CACHE_DIR, NULL);
1730
1731         return mbox_cache_dir;
1732 }
1733
1734 const gchar *get_mime_tmp_dir(void)
1735 {
1736         static gchar *mime_tmp_dir = NULL;
1737
1738         if (!mime_tmp_dir)
1739                 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1740                                            MIME_TMP_DIR, NULL);
1741
1742         return mime_tmp_dir;
1743 }
1744
1745 const gchar *get_template_dir(void)
1746 {
1747         static gchar *template_dir = NULL;
1748
1749         if (!template_dir)
1750                 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1751                                            TEMPLATE_DIR, NULL);
1752
1753         return template_dir;
1754 }
1755
1756 const gchar *get_header_cache_dir(void)
1757 {
1758         static gchar *header_dir = NULL;
1759
1760         if (!header_dir)
1761                 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1762                                          HEADER_CACHE_DIR, NULL);
1763
1764         return header_dir;
1765 }
1766
1767 const gchar *get_tmp_dir(void)
1768 {
1769         static gchar *tmp_dir = NULL;
1770
1771         if (!tmp_dir)
1772                 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1773                                       TMP_DIR, NULL);
1774
1775         return tmp_dir;
1776 }
1777
1778 gchar *get_tmp_file(void)
1779 {
1780         gchar *tmp_file;
1781         static guint32 id = 0;
1782
1783         tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1784                                    get_tmp_dir(), G_DIR_SEPARATOR, id++);
1785
1786         return tmp_file;
1787 }
1788
1789 const gchar *get_domain_name(void)
1790 {
1791         static gchar *domain_name = NULL;
1792
1793         if (!domain_name) {
1794                 struct hostent *hp;
1795                 struct utsname uts;
1796
1797                 if (uname(&uts) < 0) {
1798                         perror("gethostname");
1799                         domain_name = "unknown";
1800                 } else {
1801                         if ((hp = my_gethostbyname(uts.nodename)) == NULL) {
1802                                 perror("gethostbyname");
1803                                 domain_name = g_strdup(uts.nodename);
1804                         } else {
1805                                 domain_name = g_strdup(hp->h_name);
1806                         }
1807                 }
1808
1809                 debug_print("domain name = %s\n", domain_name);
1810         }
1811
1812         return domain_name;
1813 }
1814
1815 off_t get_file_size(const gchar *file)
1816 {
1817         struct stat s;
1818
1819         if (stat(file, &s) < 0) {
1820                 FILE_OP_ERROR(file, "stat");
1821                 return -1;
1822         }
1823
1824         return s.st_size;
1825 }
1826
1827 off_t get_file_size_as_crlf(const gchar *file)
1828 {
1829         FILE *fp;
1830         off_t size = 0;
1831         gchar buf[BUFFSIZE];
1832
1833         if ((fp = fopen(file, "rb")) == NULL) {
1834                 FILE_OP_ERROR(file, "fopen");
1835                 return -1;
1836         }
1837
1838         while (fgets(buf, sizeof(buf), fp) != NULL) {
1839                 strretchomp(buf);
1840                 size += strlen(buf) + 2;
1841         }
1842
1843         if (ferror(fp)) {
1844                 FILE_OP_ERROR(file, "fgets");
1845                 size = -1;
1846         }
1847
1848         fclose(fp);
1849
1850         return size;
1851 }
1852
1853 off_t get_left_file_size(FILE *fp)
1854 {
1855         glong pos;
1856         glong end;
1857         off_t size;
1858
1859         if ((pos = ftell(fp)) < 0) {
1860                 perror("ftell");
1861                 return -1;
1862         }
1863         if (fseek(fp, 0L, SEEK_END) < 0) {
1864                 perror("fseek");
1865                 return -1;
1866         }
1867         if ((end = ftell(fp)) < 0) {
1868                 perror("fseek");
1869                 return -1;
1870         }
1871         size = end - pos;
1872         if (fseek(fp, pos, SEEK_SET) < 0) {
1873                 perror("fseek");
1874                 return -1;
1875         }
1876
1877         return size;
1878 }
1879
1880 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1881 {
1882         struct stat s;
1883
1884         if (file == NULL)
1885                 return FALSE;
1886
1887         if (stat(file, &s) < 0) {
1888                 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1889                 return FALSE;
1890         }
1891
1892         if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1893                 return TRUE;
1894
1895         return FALSE;
1896 }
1897
1898 gboolean is_dir_exist(const gchar *dir)
1899 {
1900         struct stat s;
1901
1902         if (dir == NULL)
1903                 return FALSE;
1904
1905         if (stat(dir, &s) < 0) {
1906                 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1907                 return FALSE;
1908         }
1909
1910         if (S_ISDIR(s.st_mode))
1911                 return TRUE;
1912
1913         return FALSE;
1914 }
1915
1916 gboolean is_file_entry_exist(const gchar *file)
1917 {
1918         struct stat s;
1919
1920         if (file == NULL)
1921                 return FALSE;
1922
1923         if (stat(file, &s) < 0) {
1924                 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1925                 return FALSE;
1926         }
1927
1928         return TRUE;
1929 }
1930
1931 gboolean dirent_is_regular_file(struct dirent *d)
1932 {
1933         struct stat s;
1934
1935 #ifdef HAVE_DIRENT_D_TYPE
1936         if (d->d_type == DT_REG)
1937                 return TRUE;
1938         else if (d->d_type != DT_UNKNOWN)
1939                 return FALSE;
1940 #endif
1941
1942         return (stat(d->d_name, &s) == 0 && S_ISREG(s.st_mode));
1943 }
1944
1945 gboolean dirent_is_directory(struct dirent *d)
1946 {
1947         struct stat s;
1948
1949 #ifdef HAVE_DIRENT_D_TYPE
1950         if (d->d_type == DT_DIR)
1951                 return TRUE;
1952         else if (d->d_type != DT_UNKNOWN)
1953                 return FALSE;
1954 #endif
1955
1956         return (stat(d->d_name, &s) == 0 && S_ISDIR(s.st_mode));
1957 }
1958
1959 gint change_dir(const gchar *dir)
1960 {
1961         gchar *prevdir = NULL;
1962
1963         if (debug_mode)
1964                 prevdir = g_get_current_dir();
1965
1966         if (chdir(dir) < 0) {
1967                 FILE_OP_ERROR(dir, "chdir");
1968                 if (debug_mode) g_free(prevdir);
1969                 return -1;
1970         } else if (debug_mode) {
1971                 gchar *cwd;
1972
1973                 cwd = g_get_current_dir();
1974                 if (strcmp(prevdir, cwd) != 0)
1975                         g_print("current dir: %s\n", cwd);
1976                 g_free(cwd);
1977                 g_free(prevdir);
1978         }
1979
1980         return 0;
1981 }
1982
1983 gint make_dir(const gchar *dir)
1984 {
1985         if (mkdir(dir, S_IRWXU) < 0) {
1986                 FILE_OP_ERROR(dir, "mkdir");
1987                 return -1;
1988         }
1989         if (chmod(dir, S_IRWXU) < 0)
1990                 FILE_OP_ERROR(dir, "chmod");
1991
1992         return 0;
1993 }
1994
1995 gint make_dir_hier(const gchar *dir)
1996 {
1997         gchar *parent_dir;
1998         const gchar *p;
1999
2000         for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2001                 parent_dir = g_strndup(dir, p - dir);
2002                 if (*parent_dir != '\0') {
2003                         if (!is_dir_exist(parent_dir)) {
2004                                 if (make_dir(parent_dir) < 0) {
2005                                         g_free(parent_dir);
2006                                         return -1;
2007                                 }
2008                         }
2009                 }
2010                 g_free(parent_dir);
2011         }
2012
2013         if (!is_dir_exist(dir)) {
2014                 if (make_dir(dir) < 0)
2015                         return -1;
2016         }
2017
2018         return 0;
2019 }
2020
2021 gint remove_all_files(const gchar *dir)
2022 {
2023         DIR *dp;
2024         struct dirent *d;
2025         gchar *prev_dir;
2026
2027         prev_dir = g_get_current_dir();
2028
2029         if (chdir(dir) < 0) {
2030                 FILE_OP_ERROR(dir, "chdir");
2031                 g_free(prev_dir);
2032                 return -1;
2033         }
2034
2035         if ((dp = opendir(".")) == NULL) {
2036                 FILE_OP_ERROR(dir, "opendir");
2037                 g_free(prev_dir);
2038                 return -1;
2039         }
2040
2041         while ((d = readdir(dp)) != NULL) {
2042                 if (!strcmp(d->d_name, ".") ||
2043                     !strcmp(d->d_name, ".."))
2044                         continue;
2045
2046                 if (unlink(d->d_name) < 0)
2047                         FILE_OP_ERROR(d->d_name, "unlink");
2048         }
2049
2050         closedir(dp);
2051
2052         if (chdir(prev_dir) < 0) {
2053                 FILE_OP_ERROR(prev_dir, "chdir");
2054                 g_free(prev_dir);
2055                 return -1;
2056         }
2057
2058         g_free(prev_dir);
2059
2060         return 0;
2061 }
2062
2063 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2064 {
2065         DIR *dp;
2066         struct dirent *d;
2067         gchar *prev_dir;
2068         gint file_no;
2069
2070         prev_dir = g_get_current_dir();
2071
2072         if (chdir(dir) < 0) {
2073                 FILE_OP_ERROR(dir, "chdir");
2074                 g_free(prev_dir);
2075                 return -1;
2076         }
2077
2078         if ((dp = opendir(".")) == NULL) {
2079                 FILE_OP_ERROR(dir, "opendir");
2080                 g_free(prev_dir);
2081                 return -1;
2082         }
2083
2084         while ((d = readdir(dp)) != NULL) {
2085                 file_no = to_number(d->d_name);
2086                 if (file_no > 0 && first <= file_no && file_no <= last) {
2087                         if (is_dir_exist(d->d_name))
2088                                 continue;
2089                         if (unlink(d->d_name) < 0)
2090                                 FILE_OP_ERROR(d->d_name, "unlink");
2091                 }
2092         }
2093
2094         closedir(dp);
2095
2096         if (chdir(prev_dir) < 0) {
2097                 FILE_OP_ERROR(prev_dir, "chdir");
2098                 g_free(prev_dir);
2099                 return -1;
2100         }
2101
2102         g_free(prev_dir);
2103
2104         return 0;
2105 }
2106
2107 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2108 {
2109         DIR *dp;
2110         struct dirent *d;
2111         gchar *prev_dir;
2112         gint file_no;
2113
2114         prev_dir = g_get_current_dir();
2115
2116         if (chdir(dir) < 0) {
2117                 FILE_OP_ERROR(dir, "chdir");
2118                 g_free(prev_dir);
2119                 return -1;
2120         }
2121
2122         if ((dp = opendir(".")) == NULL) {
2123                 FILE_OP_ERROR(dir, "opendir");
2124                 g_free(prev_dir);
2125                 return -1;
2126         }
2127
2128         while ((d = readdir(dp)) != NULL) {
2129                 file_no = to_number(d->d_name);
2130                 if (file_no > 0 && (g_slist_find(numberlist, GINT_TO_POINTER(file_no)) == NULL)) {
2131                         debug_print("removing unwanted file %d from %s\n", file_no, dir);
2132                         if (is_dir_exist(d->d_name))
2133                                 continue;
2134                         if (unlink(d->d_name) < 0)
2135                                 FILE_OP_ERROR(d->d_name, "unlink");
2136                 }
2137         }
2138
2139         closedir(dp);
2140
2141         if (chdir(prev_dir) < 0) {
2142                 FILE_OP_ERROR(prev_dir, "chdir");
2143                 g_free(prev_dir);
2144                 return -1;
2145         }
2146
2147         g_free(prev_dir);
2148
2149         return 0;
2150 }
2151
2152 gint remove_all_numbered_files(const gchar *dir)
2153 {
2154         return remove_numbered_files(dir, 0, UINT_MAX);
2155 }
2156
2157 gint remove_expired_files(const gchar *dir, guint hours)
2158 {
2159         DIR *dp;
2160         struct dirent *d;
2161         struct stat s;
2162         gchar *prev_dir;
2163         gint file_no;
2164         time_t mtime, now, expire_time;
2165
2166         prev_dir = g_get_current_dir();
2167
2168         if (chdir(dir) < 0) {
2169                 FILE_OP_ERROR(dir, "chdir");
2170                 g_free(prev_dir);
2171                 return -1;
2172         }
2173
2174         if ((dp = opendir(".")) == NULL) {
2175                 FILE_OP_ERROR(dir, "opendir");
2176                 g_free(prev_dir);
2177                 return -1;
2178         }
2179
2180         now = time(NULL);
2181         expire_time = hours * 60 * 60;
2182
2183         while ((d = readdir(dp)) != NULL) {
2184                 file_no = to_number(d->d_name);
2185                 if (file_no > 0) {
2186                         if (stat(d->d_name, &s) < 0) {
2187                                 FILE_OP_ERROR(d->d_name, "stat");
2188                                 continue;
2189                         }
2190                         if (S_ISDIR(s.st_mode))
2191                                 continue;
2192                         mtime = MAX(s.st_mtime, s.st_atime);
2193                         if (now - mtime > expire_time) {
2194                                 if (unlink(d->d_name) < 0)
2195                                         FILE_OP_ERROR(d->d_name, "unlink");
2196                         }
2197                 }
2198         }
2199
2200         closedir(dp);
2201
2202         if (chdir(prev_dir) < 0) {
2203                 FILE_OP_ERROR(prev_dir, "chdir");
2204                 g_free(prev_dir);
2205                 return -1;
2206         }
2207
2208         g_free(prev_dir);
2209
2210         return 0;
2211 }
2212
2213 gint remove_dir_recursive(const gchar *dir)
2214 {
2215         struct stat s;
2216         DIR *dp;
2217         struct dirent *d;
2218         gchar *prev_dir;
2219
2220         /* g_print("dir = %s\n", dir); */
2221
2222         if (stat(dir, &s) < 0) {
2223                 FILE_OP_ERROR(dir, "stat");
2224                 if (ENOENT == errno) return 0;
2225                 return -1;
2226         }
2227
2228         if (!S_ISDIR(s.st_mode)) {
2229                 if (unlink(dir) < 0) {
2230                         FILE_OP_ERROR(dir, "unlink");
2231                         return -1;
2232                 }
2233
2234                 return 0;
2235         }
2236
2237         prev_dir = g_get_current_dir();
2238         /* g_print("prev_dir = %s\n", prev_dir); */
2239
2240         if (!path_cmp(prev_dir, dir)) {
2241                 g_free(prev_dir);
2242                 if (chdir("..") < 0) {
2243                         FILE_OP_ERROR(dir, "chdir");
2244                         return -1;
2245                 }
2246                 prev_dir = g_get_current_dir();
2247         }
2248
2249         if (chdir(dir) < 0) {
2250                 FILE_OP_ERROR(dir, "chdir");
2251                 g_free(prev_dir);
2252                 return -1;
2253         }
2254
2255         if ((dp = opendir(".")) == NULL) {
2256                 FILE_OP_ERROR(dir, "opendir");
2257                 chdir(prev_dir);
2258                 g_free(prev_dir);
2259                 return -1;
2260         }
2261
2262         /* remove all files in the directory */
2263         while ((d = readdir(dp)) != NULL) {
2264                 if (!strcmp(d->d_name, ".") ||
2265                     !strcmp(d->d_name, ".."))
2266                         continue;
2267
2268                 /* g_print("removing %s\n", d->d_name); */
2269
2270                 if (dirent_is_directory(d)) {
2271                         if (remove_dir_recursive(d->d_name) < 0) {
2272                                 g_warning("can't remove directory\n");
2273                                 return -1;
2274                         }
2275                 } else {
2276                         if (unlink(d->d_name) < 0)
2277                                 FILE_OP_ERROR(d->d_name, "unlink");
2278                 }
2279         }
2280
2281         closedir(dp);
2282
2283         if (chdir(prev_dir) < 0) {
2284                 FILE_OP_ERROR(prev_dir, "chdir");
2285                 g_free(prev_dir);
2286                 return -1;
2287         }
2288
2289         g_free(prev_dir);
2290
2291         if (rmdir(dir) < 0) {
2292                 FILE_OP_ERROR(dir, "rmdir");
2293                 return -1;
2294         }
2295
2296         return 0;
2297 }
2298
2299 #if 0
2300 /* this seems to be slower than the stdio version... */
2301 gint copy_file(const gchar *src, const gchar *dest)
2302 {
2303         gint src_fd, dest_fd;
2304         gint n_read;
2305         gint n_write;
2306         gchar buf[BUFSIZ];
2307         gchar *dest_bak = NULL;
2308
2309         if ((src_fd = open(src, O_RDONLY)) < 0) {
2310                 FILE_OP_ERROR(src, "open");
2311                 return -1;
2312         }
2313
2314         if (is_file_exist(dest)) {
2315                 dest_bak = g_strconcat(dest, ".bak", NULL);
2316                 if (rename(dest, dest_bak) < 0) {
2317                         FILE_OP_ERROR(dest, "rename");
2318                         close(src_fd);
2319                         g_free(dest_bak);
2320                         return -1;
2321                 }
2322         }
2323
2324         if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2325                 FILE_OP_ERROR(dest, "open");
2326                 close(src_fd);
2327                 if (dest_bak) {
2328                         if (rename(dest_bak, dest) < 0)
2329                                 FILE_OP_ERROR(dest_bak, "rename");
2330                         g_free(dest_bak);
2331                 }
2332                 return -1;
2333         }
2334
2335         while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2336                 gint len = n_read;
2337                 gchar *bufp = buf;
2338
2339                 while (len > 0) {
2340                         n_write = write(dest_fd, bufp, len);
2341                         if (n_write <= 0) {
2342                                 g_warning("writing to %s failed.\n", dest);
2343                                 close(dest_fd);
2344                                 close(src_fd);
2345                                 unlink(dest);
2346                                 if (dest_bak) {
2347                                         if (rename(dest_bak, dest) < 0)
2348                                                 FILE_OP_ERROR(dest_bak, "rename");
2349                                         g_free(dest_bak);
2350                                 }
2351                                 return -1;
2352                         }
2353                         len -= n_write;
2354                         bufp += n_write;
2355                 }
2356         }
2357
2358         close(src_fd);
2359         close(dest_fd);
2360
2361         if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2362                 g_warning("File copy from %s to %s failed.\n", src, dest);
2363                 unlink(dest);
2364                 if (dest_bak) {
2365                         if (rename(dest_bak, dest) < 0)
2366                                 FILE_OP_ERROR(dest_bak, "rename");
2367                         g_free(dest_bak);
2368                 }
2369                 return -1;
2370         }
2371         g_free(dest_bak);
2372
2373         return 0;
2374 }
2375 #endif
2376
2377
2378 /*
2379  * Append src file body to the tail of dest file.
2380  * Now keep_backup has no effects.
2381  */
2382 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2383 {
2384         FILE *src_fp, *dest_fp;
2385         gint n_read;
2386         gchar buf[BUFSIZ];
2387
2388         gboolean err = FALSE;
2389
2390         if ((src_fp = fopen(src, "rb")) == NULL) {
2391                 FILE_OP_ERROR(src, "fopen");
2392                 return -1;
2393         }
2394         
2395         if ((dest_fp = fopen(dest, "ab")) == NULL) {
2396                 FILE_OP_ERROR(dest, "fopen");
2397                 fclose(src_fp);
2398                 return -1;
2399         }
2400
2401         if (change_file_mode_rw(dest_fp, dest) < 0) {
2402                 FILE_OP_ERROR(dest, "chmod");
2403                 g_warning("can't change file mode\n");
2404         }
2405
2406         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2407                 if (n_read < sizeof(buf) && ferror(src_fp))
2408                         break;
2409                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2410                         g_warning("writing to %s failed.\n", dest);
2411                         fclose(dest_fp);
2412                         fclose(src_fp);
2413                         unlink(dest);
2414                         return -1;
2415                 }
2416         }
2417
2418         if (ferror(src_fp)) {
2419                 FILE_OP_ERROR(src, "fread");
2420                 err = TRUE;
2421         }
2422         fclose(src_fp);
2423         if (fclose(dest_fp) == EOF) {
2424                 FILE_OP_ERROR(dest, "fclose");
2425                 err = TRUE;
2426         }
2427
2428         if (err) {
2429                 unlink(dest);
2430                 return -1;
2431         }
2432
2433         return 0;
2434 }
2435
2436 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2437 {
2438         FILE *src_fp, *dest_fp;
2439         gint n_read;
2440         gchar buf[BUFSIZ];
2441         gchar *dest_bak = NULL;
2442         gboolean err = FALSE;
2443
2444         if ((src_fp = fopen(src, "rb")) == NULL) {
2445                 FILE_OP_ERROR(src, "fopen");
2446                 return -1;
2447         }
2448         if (is_file_exist(dest)) {
2449                 dest_bak = g_strconcat(dest, ".bak", NULL);
2450                 if (rename(dest, dest_bak) < 0) {
2451                         FILE_OP_ERROR(dest, "rename");
2452                         fclose(src_fp);
2453                         g_free(dest_bak);
2454                         return -1;
2455                 }
2456         }
2457
2458         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2459                 FILE_OP_ERROR(dest, "fopen");
2460                 fclose(src_fp);
2461                 if (dest_bak) {
2462                         if (rename(dest_bak, dest) < 0)
2463                                 FILE_OP_ERROR(dest_bak, "rename");
2464                         g_free(dest_bak);
2465                 }
2466                 return -1;
2467         }
2468
2469         if (change_file_mode_rw(dest_fp, dest) < 0) {
2470                 FILE_OP_ERROR(dest, "chmod");
2471                 g_warning("can't change file mode\n");
2472         }
2473
2474         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2475                 if (n_read < sizeof(buf) && ferror(src_fp))
2476                         break;
2477                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2478                         g_warning("writing to %s failed.\n", dest);
2479                         fclose(dest_fp);
2480                         fclose(src_fp);
2481                         unlink(dest);
2482                         if (dest_bak) {
2483                                 if (rename(dest_bak, dest) < 0)
2484                                         FILE_OP_ERROR(dest_bak, "rename");
2485                                 g_free(dest_bak);
2486                         }
2487                         return -1;
2488                 }
2489         }
2490
2491         if (ferror(src_fp)) {
2492                 FILE_OP_ERROR(src, "fread");
2493                 err = TRUE;
2494         }
2495         fclose(src_fp);
2496         if (fclose(dest_fp) == EOF) {
2497                 FILE_OP_ERROR(dest, "fclose");
2498                 err = TRUE;
2499         }
2500
2501         if (err) {
2502                 unlink(dest);
2503                 if (dest_bak) {
2504                         if (rename(dest_bak, dest) < 0)
2505                                 FILE_OP_ERROR(dest_bak, "rename");
2506                         g_free(dest_bak);
2507                 }
2508                 return -1;
2509         }
2510
2511         if (keep_backup == FALSE && dest_bak)
2512                 unlink(dest_bak);
2513
2514         g_free(dest_bak);
2515
2516         return 0;
2517 }
2518
2519 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2520 {
2521         if (overwrite == FALSE && is_file_exist(dest)) {
2522                 g_warning("move_file(): file %s already exists.", dest);
2523                 return -1;
2524         }
2525
2526         if (rename(src, dest) == 0) return 0;
2527
2528         if (EXDEV != errno) {
2529                 FILE_OP_ERROR(src, "rename");
2530                 return -1;
2531         }
2532
2533         if (copy_file(src, dest, FALSE) < 0) return -1;
2534
2535         unlink(src);
2536
2537         return 0;
2538 }
2539
2540 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2541 {
2542         gint n_read;
2543         gint bytes_left, to_read;
2544         gchar buf[BUFSIZ];
2545
2546         if (fseek(fp, offset, SEEK_SET) < 0) {
2547                 perror("fseek");
2548                 return -1;
2549         }
2550
2551         bytes_left = length;
2552         to_read = MIN(bytes_left, sizeof(buf));
2553
2554         while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2555                 if (n_read < to_read && ferror(fp))
2556                         break;
2557                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2558                         return -1;
2559                 }
2560                 bytes_left -= n_read;
2561                 if (bytes_left == 0)
2562                         break;
2563                 to_read = MIN(bytes_left, sizeof(buf));
2564         }
2565
2566         if (ferror(fp)) {
2567                 perror("fread");
2568                 return -1;
2569         }
2570
2571         return 0;
2572 }
2573
2574 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2575 {
2576         FILE *dest_fp;
2577         gboolean err = FALSE;
2578
2579         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2580                 FILE_OP_ERROR(dest, "fopen");
2581                 return -1;
2582         }
2583
2584         if (change_file_mode_rw(dest_fp, dest) < 0) {
2585                 FILE_OP_ERROR(dest, "chmod");
2586                 g_warning("can't change file mode\n");
2587         }
2588
2589         if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2590                 err = TRUE;
2591
2592         if (!err && fclose(dest_fp) == EOF) {
2593                 FILE_OP_ERROR(dest, "fclose");
2594                 err = TRUE;
2595         }
2596
2597         if (err) {
2598                 g_warning("writing to %s failed.\n", dest);
2599                 unlink(dest);
2600                 return -1;
2601         }
2602
2603         return 0;
2604 }
2605
2606 /* convert line endings into CRLF. If the last line doesn't end with
2607  * linebreak, add it.
2608  */
2609 gchar *canonicalize_str(const gchar *str)
2610 {
2611         const gchar *p;
2612         guint new_len = 0;
2613         gchar *out, *outp;
2614
2615         for (p = str; *p != '\0'; ++p) {
2616                 if (*p != '\r') {
2617                         ++new_len;
2618                         if (*p == '\n')
2619                                 ++new_len;
2620                 }
2621         }
2622         if (p == str || *(p - 1) != '\n')
2623                 new_len += 2;
2624
2625         out = outp = g_malloc(new_len + 1);
2626         for (p = str; *p != '\0'; ++p) {
2627                 if (*p != '\r') {
2628                         if (*p == '\n')
2629                                 *outp++ = '\r';
2630                         *outp++ = *p;
2631                 }
2632         }
2633         if (p == str || *(p - 1) != '\n') {
2634                 *outp++ = '\r';
2635                 *outp++ = '\n';
2636         }
2637         *outp = '\0';
2638
2639         return out;
2640 }
2641
2642 gint canonicalize_file(const gchar *src, const gchar *dest)
2643 {
2644         FILE *src_fp, *dest_fp;
2645         gchar buf[BUFFSIZE];
2646         gint len;
2647         gboolean err = FALSE;
2648         gboolean last_linebreak = FALSE;
2649
2650         if ((src_fp = fopen(src, "rb")) == NULL) {
2651                 FILE_OP_ERROR(src, "fopen");
2652                 return -1;
2653         }
2654
2655         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2656                 FILE_OP_ERROR(dest, "fopen");
2657                 fclose(src_fp);
2658                 return -1;
2659         }
2660
2661         if (change_file_mode_rw(dest_fp, dest) < 0) {
2662                 FILE_OP_ERROR(dest, "chmod");
2663                 g_warning("can't change file mode\n");
2664         }
2665
2666         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2667                 gint r = 0;
2668
2669                 len = strlen(buf);
2670                 if (len == 0) break;
2671                 last_linebreak = FALSE;
2672
2673                 if (buf[len - 1] != '\n') {
2674                         last_linebreak = TRUE;
2675                         r = fputs(buf, dest_fp);
2676                 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2677                         r = fputs(buf, dest_fp);
2678                 } else {
2679                         if (len > 1) {
2680                                 r = fwrite(buf, len - 1, 1, dest_fp);
2681                                 if (r != 1)
2682                                         r = EOF;
2683                         }
2684                         if (r != EOF)
2685                                 r = fputs("\r\n", dest_fp);
2686                 }
2687
2688                 if (r == EOF) {
2689                         g_warning("writing to %s failed.\n", dest);
2690                         fclose(dest_fp);
2691                         fclose(src_fp);
2692                         unlink(dest);
2693                         return -1;
2694                 }
2695         }
2696
2697         if (last_linebreak == TRUE) {
2698                 if (fputs("\r\n", dest_fp) == EOF)
2699                         err = TRUE;
2700         }
2701
2702         if (ferror(src_fp)) {
2703                 FILE_OP_ERROR(src, "fgets");
2704                 err = TRUE;
2705         }
2706         fclose(src_fp);
2707         if (fclose(dest_fp) == EOF) {
2708                 FILE_OP_ERROR(dest, "fclose");
2709                 err = TRUE;
2710         }
2711
2712         if (err) {
2713                 unlink(dest);
2714                 return -1;
2715         }
2716
2717         return 0;
2718 }
2719
2720 gint canonicalize_file_replace(const gchar *file)
2721 {
2722         gchar *tmp_file;
2723
2724         tmp_file = get_tmp_file();
2725
2726         if (canonicalize_file(file, tmp_file) < 0) {
2727                 g_free(tmp_file);
2728                 return -1;
2729         }
2730
2731         if (move_file(tmp_file, file, TRUE) < 0) {
2732                 g_warning("can't replace %s .\n", file);
2733                 unlink(tmp_file);
2734                 g_free(tmp_file);
2735                 return -1;
2736         }
2737
2738         g_free(tmp_file);
2739         return 0;
2740 }
2741
2742 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2743 {
2744         FILE *src_fp, *dest_fp;
2745         gchar buf[BUFFSIZE];
2746         gboolean err = FALSE;
2747
2748         if ((src_fp = fopen(src, "rb")) == NULL) {
2749                 FILE_OP_ERROR(src, "fopen");
2750                 return -1;
2751         }
2752
2753         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2754                 FILE_OP_ERROR(dest, "fopen");
2755                 fclose(src_fp);
2756                 return -1;
2757         }
2758
2759         if (change_file_mode_rw(dest_fp, dest) < 0) {
2760                 FILE_OP_ERROR(dest, "chmod");
2761                 g_warning("can't change file mode\n");
2762         }
2763
2764         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2765                 strcrchomp(buf);
2766                 if (fputs(buf, dest_fp) == EOF) {
2767                         g_warning("writing to %s failed.\n", dest);
2768                         fclose(dest_fp);
2769                         fclose(src_fp);
2770                         unlink(dest);
2771                         return -1;
2772                 }
2773         }
2774
2775         if (ferror(src_fp)) {
2776                 FILE_OP_ERROR(src, "fgets");
2777                 err = TRUE;
2778         }
2779         fclose(src_fp);
2780         if (fclose(dest_fp) == EOF) {
2781                 FILE_OP_ERROR(dest, "fclose");
2782                 err = TRUE;
2783         }
2784
2785         if (err) {
2786                 unlink(dest);
2787                 return -1;
2788         }
2789
2790         return 0;
2791 }
2792
2793 gint uncanonicalize_file_replace(const gchar *file)
2794 {
2795         gchar *tmp_file;
2796
2797         tmp_file = get_tmp_file();
2798
2799         if (uncanonicalize_file(file, tmp_file) < 0) {
2800                 g_free(tmp_file);
2801                 return -1;
2802         }
2803
2804         if (move_file(tmp_file, file, TRUE) < 0) {
2805                 g_warning("can't replace %s .\n", file);
2806                 unlink(tmp_file);
2807                 g_free(tmp_file);
2808                 return -1;
2809         }
2810
2811         g_free(tmp_file);
2812         return 0;
2813 }
2814
2815 gchar *normalize_newlines(const gchar *str)
2816 {
2817         const gchar *p = str;
2818         gchar *out, *outp;
2819
2820         out = outp = g_malloc(strlen(str) + 1);
2821         for (p = str; *p != '\0'; ++p) {
2822                 if (*p == '\r') {
2823                         if (*(p + 1) != '\n')
2824                                 *outp++ = '\n';
2825                 } else
2826                         *outp++ = *p;
2827         }
2828
2829         *outp = '\0';
2830
2831         return out;
2832 }
2833
2834 gchar *get_outgoing_rfc2822_str(FILE *fp)
2835 {
2836         gchar buf[BUFFSIZE];
2837         GString *str;
2838         gchar *ret;
2839
2840         str = g_string_new(NULL);
2841
2842         /* output header part */
2843         while (fgets(buf, sizeof(buf), fp) != NULL) {
2844                 strretchomp(buf);
2845                 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2846                         gint next;
2847
2848                         for (;;) {
2849                                 next = fgetc(fp);
2850                                 if (next == EOF)
2851                                         break;
2852                                 else if (next != ' ' && next != '\t') {
2853                                         ungetc(next, fp);
2854                                         break;
2855                                 }
2856                                 if (fgets(buf, sizeof(buf), fp) == NULL)
2857                                         break;
2858                         }
2859                 } else {
2860                         g_string_append(str, buf);
2861                         g_string_append(str, "\r\n");
2862                         if (buf[0] == '\0')
2863                                 break;
2864                 }
2865         }
2866
2867         /* output body part */
2868         while (fgets(buf, sizeof(buf), fp) != NULL) {
2869                 strretchomp(buf);
2870                 if (buf[0] == '.')
2871                         g_string_append_c(str, '.');
2872                 g_string_append(str, buf);
2873                 g_string_append(str, "\r\n");
2874         }
2875
2876         ret = str->str;
2877         g_string_free(str, FALSE);
2878
2879         return ret;
2880 }
2881
2882 /*
2883  * Create a new boundary in a way that it is very unlikely that this
2884  * will occur in the following text.  It would be easy to ensure
2885  * uniqueness if everything is either quoted-printable or base64
2886  * encoded (note that conversion is allowed), but because MIME bodies
2887  * may be nested, it may happen that the same boundary has already
2888  * been used. We avoid scanning the message for conflicts and hope the
2889  * best.
2890  *
2891  *   boundary := 0*69<bchars> bcharsnospace
2892  *   bchars := bcharsnospace / " "
2893  *   bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2894  *                    "+" / "_" / "," / "-" / "." /
2895  *                    "/" / ":" / "=" / "?"
2896  *
2897  * some special characters removed because of buggy MTAs
2898  */
2899
2900 gchar *generate_mime_boundary(const gchar *prefix)
2901 {
2902         static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2903                              "abcdefghijklmnopqrstuvwxyz"
2904                              "1234567890+_./=";
2905         gchar buf_uniq[17];
2906         gchar buf_date[64];
2907         gint i;
2908         gint pid;
2909
2910         pid = getpid();
2911
2912         /* We make the boundary depend on the pid, so that all running
2913          * processes generate different values even when they have been
2914          * started within the same second and srandom(time(NULL)) has been
2915          * used.  I can't see whether this is really an advantage but it
2916          * doesn't do any harm.
2917          */
2918         for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2919                 buf_uniq[i] = tbl[(rand() ^ pid) % (sizeof(tbl) - 1)];
2920         buf_uniq[i] = '\0';
2921
2922         get_rfc822_date(buf_date, sizeof(buf_date));
2923         subst_char(buf_date, ' ', '_');
2924         subst_char(buf_date, ',', '_');
2925         subst_char(buf_date, ':', '_');
2926
2927         return g_strdup_printf("%s_%s_%s", prefix ? prefix : "Multipart",
2928                                buf_date, buf_uniq);
2929 }
2930
2931 gint change_file_mode_rw(FILE *fp, const gchar *file)
2932 {
2933 #if HAVE_FCHMOD
2934         return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2935 #else
2936         return chmod(file, S_IRUSR|S_IWUSR);
2937 #endif
2938 }
2939
2940 FILE *my_tmpfile(void)
2941 {
2942 #if HAVE_MKSTEMP
2943         const gchar suffix[] = ".XXXXXX";
2944         const gchar *tmpdir;
2945         guint tmplen;
2946         const gchar *progname;
2947         guint proglen;
2948         gchar *fname;
2949         gint fd;
2950         FILE *fp;
2951
2952         tmpdir = get_tmp_dir();
2953         tmplen = strlen(tmpdir);
2954         progname = g_get_prgname();
2955         if (progname == NULL)
2956                 progname = "sylpheed-claws";
2957         proglen = strlen(progname);
2958         Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2959                 return tmpfile());
2960
2961         memcpy(fname, tmpdir, tmplen);
2962         fname[tmplen] = G_DIR_SEPARATOR;
2963         memcpy(fname + tmplen + 1, progname, proglen);
2964         memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2965
2966         fd = mkstemp(fname);
2967         if (fd < 0)
2968                 return tmpfile();
2969
2970         unlink(fname);
2971
2972         fp = fdopen(fd, "w+b");
2973         if (!fp)
2974                 close(fd);
2975         else
2976                 return fp;
2977 #endif /* HAVE_MKSTEMP */
2978
2979         return tmpfile();
2980 }
2981
2982 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2983 {
2984         int fd;
2985         
2986         *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2987         fd = mkstemp(*filename);
2988
2989         return fdopen(fd, "w+");
2990 }
2991
2992 FILE *str_open_as_stream(const gchar *str)
2993 {
2994         FILE *fp;
2995         size_t len;
2996
2997         g_return_val_if_fail(str != NULL, NULL);
2998
2999         fp = my_tmpfile();
3000         if (!fp) {
3001                 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3002                 return NULL;
3003         }
3004
3005         len = strlen(str);
3006         if (len == 0) return fp;
3007
3008         if (fwrite(str, len, 1, fp) != 1) {
3009                 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3010                 fclose(fp);
3011                 return NULL;
3012         }
3013
3014         rewind(fp);
3015         return fp;
3016 }
3017
3018 gint str_write_to_file(const gchar *str, const gchar *file)
3019 {
3020         FILE *fp;
3021         size_t len;
3022
3023         g_return_val_if_fail(str != NULL, -1);
3024         g_return_val_if_fail(file != NULL, -1);
3025
3026         if ((fp = fopen(file, "wb")) == NULL) {
3027                 FILE_OP_ERROR(file, "fopen");
3028                 return -1;
3029         }
3030
3031         len = strlen(str);
3032         if (len == 0) {
3033                 fclose(fp);
3034                 return 0;
3035         }
3036
3037         if (fwrite(str, len, 1, fp) != 1) {
3038                 FILE_OP_ERROR(file, "fwrite");
3039                 fclose(fp);
3040                 unlink(file);
3041                 return -1;
3042         }
3043
3044         if (fclose(fp) == EOF) {
3045                 FILE_OP_ERROR(file, "fclose");
3046                 unlink(file);
3047                 return -1;
3048         }
3049
3050         return 0;
3051 }
3052
3053 gchar *file_read_to_str(const gchar *file)
3054 {
3055         FILE *fp;
3056         gchar *str;
3057
3058         g_return_val_if_fail(file != NULL, NULL);
3059
3060         if ((fp = fopen(file, "rb")) == NULL) {
3061                 FILE_OP_ERROR(file, "fopen");
3062                 return NULL;
3063         }
3064
3065         str = file_read_stream_to_str(fp);
3066
3067         fclose(fp);
3068
3069         return str;
3070 }
3071
3072 gchar *file_read_stream_to_str(FILE *fp)
3073 {
3074         GByteArray *array;
3075         gchar buf[BUFSIZ];
3076         gint n_read;
3077         gchar *str;
3078
3079         g_return_val_if_fail(fp != NULL, NULL);
3080
3081         array = g_byte_array_new();
3082
3083         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3084                 if (n_read < sizeof(buf) && ferror(fp))
3085                         break;
3086                 g_byte_array_append(array, buf, n_read);
3087         }
3088
3089         if (ferror(fp)) {
3090                 FILE_OP_ERROR("file stream", "fread");
3091                 g_byte_array_free(array, TRUE);
3092                 return NULL;
3093         }
3094
3095         buf[0] = '\0';
3096         g_byte_array_append(array, buf, 1);
3097         str = (gchar *)array->data;
3098         g_byte_array_free(array, FALSE);
3099
3100         if (!g_utf8_validate(str, -1, NULL)) {
3101                 const gchar *src_codeset, *dest_codeset;
3102                 gchar *tmp = NULL;
3103                 src_codeset = conv_get_locale_charset_str();
3104                 dest_codeset = CS_UTF_8;
3105                 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3106                 g_free(str);
3107                 str = tmp;
3108         }
3109
3110         return str;
3111 }
3112
3113 gint execute_async(gchar *const argv[])
3114 {
3115         pid_t pid;
3116         gint status;
3117
3118         if ((pid = fork()) < 0) {
3119                 perror("fork");
3120                 return -1;
3121         }
3122
3123         if (pid == 0) {                 /* child process */
3124                 pid_t gch_pid;
3125
3126                 if ((gch_pid = fork()) < 0) {
3127                         perror("fork");
3128                         _exit(1);
3129                 }
3130
3131                 if (gch_pid == 0) {     /* grandchild process */
3132                         execvp(argv[0], argv);
3133
3134                         perror("execvp");
3135                         _exit(1);
3136                 }
3137
3138                 _exit(0);
3139         }
3140
3141         waitpid(pid, &status, 0);
3142
3143         if (WIFEXITED(status))
3144                 return WEXITSTATUS(status);
3145         else
3146                 return -1;
3147 }
3148
3149 gint execute_sync(gchar *const argv[])
3150 {
3151         pid_t pid;
3152         gint status;
3153
3154         if ((pid = fork()) < 0) {
3155                 perror("fork");
3156                 return -1;
3157         }
3158
3159         if (pid == 0) {         /* child process */
3160                 execvp(argv[0], argv);
3161
3162                 perror("execvp");
3163                 _exit(1);
3164         }
3165
3166         waitpid(pid, &status, 0);
3167
3168         if (WIFEXITED(status))
3169                 return WEXITSTATUS(status);
3170         else
3171                 return -1;
3172 }
3173
3174 gint execute_command_line(const gchar *cmdline, gboolean async)
3175 {
3176         gchar **argv;
3177         gint ret;
3178
3179         debug_print("executing: %s\n", cmdline);
3180
3181         argv = strsplit_with_quote(cmdline, " ", 0);
3182
3183         if (async)
3184                 ret = execute_async(argv);
3185         else
3186                 ret = execute_sync(argv);
3187
3188         g_strfreev(argv);
3189
3190         return ret;
3191 }
3192
3193 gchar *get_command_output(const gchar *cmdline)
3194 {
3195         gchar *child_stdout;
3196         gint status;
3197
3198         g_return_val_if_fail(cmdline != NULL, NULL);
3199
3200         if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3201                                       NULL) == FALSE) {
3202                 g_warning("Can't execute command: %s\n", cmdline);
3203                 return NULL;
3204         }
3205
3206         return child_stdout;
3207 }
3208
3209 static gint is_unchanged_uri_char(char c)
3210 {
3211         switch (c) {
3212                 case '(':
3213                 case ')':
3214                 case ',':
3215                         return 0;
3216                 default:
3217                         return 1;
3218         }
3219 }
3220
3221 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3222 {
3223         int i;
3224         int k;
3225
3226         k = 0;
3227         for(i = 0; i < strlen(uri) ; i++) {
3228                 if (is_unchanged_uri_char(uri[i])) {
3229                         if (k + 2 >= bufsize)
3230                                 break;
3231                         encoded_uri[k++] = uri[i];
3232                 }
3233                 else {
3234                         char * hexa = "0123456789ABCDEF";
3235                         
3236                         if (k + 4 >= bufsize)
3237                                 break;
3238                         encoded_uri[k++] = '%';
3239                         encoded_uri[k++] = hexa[uri[i] / 16];
3240                         encoded_uri[k++] = hexa[uri[i] % 16];
3241                 }
3242         }
3243         encoded_uri[k] = 0;
3244 }
3245
3246 gint open_uri(const gchar *uri, const gchar *cmdline)
3247 {
3248         gchar buf[BUFFSIZE];
3249         gchar *p;
3250         gchar encoded_uri[BUFFSIZE];
3251         
3252         g_return_val_if_fail(uri != NULL, -1);
3253
3254         /* an option to choose whether to use encode_uri or not ? */
3255         encode_uri(encoded_uri, BUFFSIZE, uri);
3256         
3257         if (cmdline &&
3258             (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3259             !strchr(p + 2, '%'))
3260                 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3261         else {
3262                 if (cmdline)
3263                         g_warning("Open URI command line is invalid "
3264                                   "(there must be only one '%%s'): %s",
3265                                   cmdline);
3266                 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3267         }
3268
3269         execute_command_line(buf, TRUE);
3270
3271         return 0;
3272 }
3273
3274 time_t remote_tzoffset_sec(const gchar *zone)
3275 {
3276         static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3277         gchar zone3[4];
3278         gchar *p;
3279         gchar c;
3280         gint iustz;
3281         gint offset;
3282         time_t remoteoffset;
3283
3284         strncpy(zone3, zone, 3);
3285         zone3[3] = '\0';
3286         remoteoffset = 0;
3287
3288         if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3289             (c == '+' || c == '-')) {
3290                 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3291                 if (c == '-')
3292                         remoteoffset = -remoteoffset;
3293         } else if (!strncmp(zone, "UT" , 2) ||
3294                    !strncmp(zone, "GMT", 2)) {
3295                 remoteoffset = 0;
3296         } else if (strlen(zone3) == 3) {
3297                 for (p = ustzstr; *p != '\0'; p += 3) {
3298                         if (!g_ascii_strncasecmp(p, zone3, 3)) {
3299                                 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3300                                 remoteoffset = iustz * 3600;
3301                                 break;
3302                         }
3303                 }
3304                 if (*p == '\0')
3305                         return -1;
3306         } else if (strlen(zone3) == 1) {
3307                 switch (zone[0]) {
3308                 case 'Z': remoteoffset =   0; break;
3309                 case 'A': remoteoffset =  -1; break;
3310                 case 'B': remoteoffset =  -2; break;
3311                 case 'C': remoteoffset =  -3; break;
3312                 case 'D': remoteoffset =  -4; break;
3313                 case 'E': remoteoffset =  -5; break;
3314                 case 'F': remoteoffset =  -6; break;
3315                 case 'G': remoteoffset =  -7; break;
3316                 case 'H': remoteoffset =  -8; break;
3317                 case 'I': remoteoffset =  -9; break;
3318                 case 'K': remoteoffset = -10; break; /* J is not used */
3319                 case 'L': remoteoffset = -11; break;
3320                 case 'M': remoteoffset = -12; break;
3321                 case 'N': remoteoffset =   1; break;
3322                 case 'O': remoteoffset =   2; break;
3323                 case 'P': remoteoffset =   3; break;
3324                 case 'Q': remoteoffset =   4; break;
3325                 case 'R': remoteoffset =   5; break;
3326                 case 'S': remoteoffset =   6; break;
3327                 case 'T': remoteoffset =   7; break;
3328                 case 'U': remoteoffset =   8; break;
3329                 case 'V': remoteoffset =   9; break;
3330                 case 'W': remoteoffset =  10; break;
3331                 case 'X': remoteoffset =  11; break;
3332                 case 'Y': remoteoffset =  12; break;
3333                 default:  remoteoffset =   0; break;
3334                 }
3335                 remoteoffset = remoteoffset * 3600;
3336         } else
3337                 return -1;
3338
3339         return remoteoffset;
3340 }
3341
3342 time_t tzoffset_sec(time_t *now)
3343 {
3344         struct tm gmt, *lt;
3345         gint off;
3346
3347         gmt = *gmtime(now);
3348         lt = localtime(now);
3349
3350         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3351
3352         if (lt->tm_year < gmt.tm_year)
3353                 off -= 24 * 60;
3354         else if (lt->tm_year > gmt.tm_year)
3355                 off += 24 * 60;
3356         else if (lt->tm_yday < gmt.tm_yday)
3357                 off -= 24 * 60;
3358         else if (lt->tm_yday > gmt.tm_yday)
3359                 off += 24 * 60;
3360
3361         if (off >= 24 * 60)             /* should be impossible */
3362                 off = 23 * 60 + 59;     /* if not, insert silly value */
3363         if (off <= -24 * 60)
3364                 off = -(23 * 60 + 59);
3365
3366         return off * 60;
3367 }
3368
3369 /* calculate timezone offset */
3370 gchar *tzoffset(time_t *now)
3371 {
3372         static gchar offset_string[6];
3373         struct tm gmt, *lt;
3374         gint off;
3375         gchar sign = '+';
3376
3377         gmt = *gmtime(now);
3378         lt = localtime(now);
3379
3380         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3381
3382         if (lt->tm_year < gmt.tm_year)
3383                 off -= 24 * 60;
3384         else if (lt->tm_year > gmt.tm_year)
3385                 off += 24 * 60;
3386         else if (lt->tm_yday < gmt.tm_yday)
3387                 off -= 24 * 60;
3388         else if (lt->tm_yday > gmt.tm_yday)
3389                 off += 24 * 60;
3390
3391         if (off < 0) {
3392                 sign = '-';
3393                 off = -off;
3394         }
3395
3396         if (off >= 24 * 60)             /* should be impossible */
3397                 off = 23 * 60 + 59;     /* if not, insert silly value */
3398
3399         sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3400
3401         return offset_string;
3402 }
3403
3404 void get_rfc822_date(gchar *buf, gint len)
3405 {
3406         struct tm *lt;
3407         time_t t;
3408         gchar day[4], mon[4];
3409         gint dd, hh, mm, ss, yyyy;
3410
3411         t = time(NULL);
3412         lt = localtime(&t);
3413
3414         sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3415                day, mon, &dd, &hh, &mm, &ss, &yyyy);
3416         g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3417                    day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3418 }
3419
3420 void debug_set_mode(gboolean mode)
3421 {
3422         debug_mode = mode;
3423 }
3424
3425 gboolean debug_get_mode(void)
3426 {
3427         return debug_mode;
3428 }
3429
3430 void debug_print_real(const gchar *format, ...)
3431 {
3432         va_list args;
3433         gchar buf[BUFFSIZE];
3434
3435         if (!debug_mode) return;
3436
3437         va_start(args, format);
3438         g_vsnprintf(buf, sizeof(buf), format, args);
3439         va_end(args);
3440
3441         g_print("%s", buf);
3442 }
3443
3444 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3445 {
3446         if (subject == NULL)
3447                 subject = "";
3448         else
3449                 subject += subject_get_prefix_length(subject);
3450
3451         return g_hash_table_lookup(subject_table, subject);
3452 }
3453
3454 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3455                           void * data)
3456 {
3457         if (subject == NULL || *subject == 0)
3458                 return;
3459         subject += subject_get_prefix_length(subject);
3460         g_hash_table_insert(subject_table, subject, data);
3461 }
3462
3463 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3464 {
3465         if (subject == NULL)
3466                 return;
3467
3468         subject += subject_get_prefix_length(subject);  
3469         g_hash_table_remove(subject_table, subject);
3470 }
3471
3472 /*!
3473  *\brief        Check if a string is prefixed with known (combinations) 
3474  *              of prefixes. The function assumes that each prefix 
3475  *              is terminated by zero or exactly _one_ space.
3476  *
3477  *\param        str String to check for a prefixes
3478  *
3479  *\return       int Number of chars in the prefix that should be skipped 
3480  *              for a "clean" subject line. If no prefix was found, 0
3481  *              is returned.
3482  */             
3483 int subject_get_prefix_length(const gchar *subject)
3484 {
3485         /*!< Array with allowable reply prefixes regexps. */
3486         static const gchar * const prefixes[] = {
3487                 "Re\\:",                        /* "Re:" */
3488                 "Re\\[[1-9][0-9]*\\]\\:",       /* "Re[XXX]:" (non-conforming news mail clients) */
3489                 "Antw\\:",                      /* "Antw:" (Dutch / German Outlook) */
3490                 "Aw\\:",                        /* "Aw:"   (German) */
3491                 "Antwort\\:",                   /* "Antwort:" (German Lotus Notes) */
3492                 "Res\\:",                       /* "Res:" (Brazilian Outlook) */
3493                 "Fw\\:",                        /* "Fw:" Forward */
3494                 "Enc\\:",                       /* "Enc:" Forward (Brazilian Outlook) */
3495                 "Odp\\:",                       /* "Odp:" Re (Polish Outlook) */
3496                 "Rif\\:"                        /* "Rif:" (Italian Outlook) */
3497                 /* add more */
3498         };
3499         const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3500         int n;
3501         regmatch_t pos;
3502         static regex_t regex;
3503         static gboolean init_;
3504
3505         if (!subject) return 0;
3506         if (!*subject) return 0;
3507
3508         if (!init_) {
3509                 GString *s = g_string_new("");
3510                 
3511                 for (n = 0; n < PREFIXES; n++)
3512                         /* Terminate each prefix regexpression by a
3513                          * "\ ?" (zero or ONE space), and OR them */
3514                         g_string_append_printf(s, "(%s\\ ?)%s",
3515                                           prefixes[n],
3516                                           n < PREFIXES - 1 ? 
3517                                           "|" : "");
3518                 
3519                 g_string_prepend(s, "(");
3520                 g_string_append(s, ")+");       /* match at least once */
3521                 g_string_prepend(s, "^\\ *");   /* from beginning of line */
3522                 
3523
3524                 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+" 
3525                  * TODO: Should this be       "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3526                 if (regcomp(&regex, s->str, REG_EXTENDED | REG_ICASE)) { 
3527                         debug_print("Error compiling regexp %s\n", s->str);
3528                         g_string_free(s, TRUE);
3529                         return 0;
3530                 } else {
3531                         init_ = TRUE;
3532                         g_string_free(s, TRUE);
3533                 }
3534         }
3535         
3536         if (!regexec(&regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3537                 return pos.rm_eo;
3538         else
3539                 return 0;
3540 }
3541
3542 guint g_stricase_hash(gconstpointer gptr)
3543 {
3544         guint hash_result = 0;
3545         const char *str;
3546
3547         for (str = gptr; str && *str; str++) {
3548                 if (isupper((guchar)*str)) hash_result += (*str + ' ');
3549                 else hash_result += *str;
3550         }
3551
3552         return hash_result;
3553 }
3554
3555 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3556 {
3557         const char *str1 = gptr1;
3558         const char *str2 = gptr2;
3559
3560         return !g_utf8_collate(str1, str2);
3561 }
3562
3563 gint g_int_compare(gconstpointer a, gconstpointer b)
3564 {
3565         return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3566 }
3567
3568 gchar *generate_msgid(gchar *buf, gint len)
3569 {
3570         struct tm *lt;
3571         time_t t;
3572         gchar *addr;
3573
3574         t = time(NULL);
3575         lt = localtime(&t);
3576
3577         addr = g_strconcat("@", get_domain_name(), NULL);
3578
3579         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x%s",
3580                    lt->tm_year + 1900, lt->tm_mon + 1,
3581                    lt->tm_mday, lt->tm_hour,
3582                    lt->tm_min, lt->tm_sec,
3583                    (guint) rand(), addr);
3584
3585         g_free(addr);
3586         return buf;
3587 }
3588
3589 /*
3590    quote_cmd_argument()
3591    
3592    return a quoted string safely usable in argument of a command.
3593    
3594    code is extracted and adapted from etPan! project -- DINH V. Hoà.
3595 */
3596
3597 gint quote_cmd_argument(gchar * result, guint size,
3598                         const gchar * path)
3599 {
3600         const gchar * p;
3601         gchar * result_p;
3602         guint remaining;
3603
3604         result_p = result;
3605         remaining = size;
3606
3607         for(p = path ; * p != '\0' ; p ++) {
3608
3609                 if (isalnum((guchar)*p) || (* p == '/')) {
3610                         if (remaining > 0) {
3611                                 * result_p = * p;
3612                                 result_p ++; 
3613                                 remaining --;
3614                         }
3615                         else {
3616                                 result[size - 1] = '\0';
3617                                 return -1;
3618                         }
3619                 }
3620                 else { 
3621                         if (remaining >= 2) {
3622                                 * result_p = '\\';
3623                                 result_p ++; 
3624                                 * result_p = * p;
3625                                 result_p ++; 
3626                                 remaining -= 2;
3627                         }
3628                         else {
3629                                 result[size - 1] = '\0';
3630                                 return -1;
3631                         }
3632                 }
3633         }
3634         if (remaining > 0) {
3635                 * result_p = '\0';
3636         }
3637         else {
3638                 result[size - 1] = '\0';
3639                 return -1;
3640         }
3641   
3642         return 0;
3643 }
3644
3645 typedef struct 
3646 {
3647         GNode           *parent;
3648         GNodeMapFunc     func;
3649         gpointer         data;
3650 } GNodeMapData;
3651
3652 static void g_node_map_recursive(GNode *node, gpointer data)
3653 {
3654         GNodeMapData *mapdata = (GNodeMapData *) data;
3655         GNode *newnode;
3656         GNodeMapData newmapdata;
3657         gpointer newdata;
3658
3659         newdata = mapdata->func(node->data, mapdata->data);
3660         if (newdata != NULL) {
3661                 newnode = g_node_new(newdata);
3662                 g_node_append(mapdata->parent, newnode);
3663
3664                 newmapdata.parent = newnode;
3665                 newmapdata.func = mapdata->func;
3666                 newmapdata.data = mapdata->data;
3667
3668                 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3669         }
3670 }
3671
3672 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3673 {
3674         GNode *root;
3675         GNodeMapData mapdata;
3676
3677         g_return_val_if_fail(node != NULL, NULL);
3678         g_return_val_if_fail(func != NULL, NULL);
3679
3680         root = g_node_new(func(node->data, data));
3681
3682         mapdata.parent = root;
3683         mapdata.func = func;
3684         mapdata.data = data;
3685
3686         g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3687
3688         return root;
3689 }
3690
3691 #define HEX_TO_INT(val, hex)                    \
3692 {                                               \
3693         gchar c = hex;                          \
3694                                                 \
3695         if ('0' <= c && c <= '9') {             \
3696                 val = c - '0';                  \
3697         } else if ('a' <= c && c <= 'f') {      \
3698                 val = c - 'a' + 10;             \
3699         } else if ('A' <= c && c <= 'F') {      \
3700                 val = c - 'A' + 10;             \
3701         } else {                                \
3702                 val = -1;                       \
3703         }                                       \
3704 }
3705
3706 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3707 {
3708         gint hi, lo;
3709
3710         HEX_TO_INT(hi, c1);
3711         HEX_TO_INT(lo, c2);
3712
3713         if (hi == -1 || lo == -1)
3714                 return FALSE;
3715
3716         *out = (hi << 4) + lo;
3717         return TRUE;
3718 }
3719
3720 #define INT_TO_HEX(hex, val)            \
3721 {                                       \
3722         if ((val) < 10)                 \
3723                 hex = '0' + (val);      \
3724         else                            \
3725                 hex = 'A' + (val) - 10; \
3726 }
3727
3728 void get_hex_str(gchar *out, guchar ch)
3729 {
3730         gchar hex;
3731
3732         INT_TO_HEX(hex, ch >> 4);
3733         *out++ = hex;
3734         INT_TO_HEX(hex, ch & 0x0f);
3735         *out++ = hex;
3736 }
3737
3738 #undef REF_DEBUG
3739 #ifndef REF_DEBUG
3740 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3741 #else
3742 #define G_PRINT_REF g_print
3743 #endif
3744
3745 /*!
3746  *\brief        Register ref counted pointer. It is based on GBoxed, so should
3747  *              work with anything that uses the GType system. The semantics
3748  *              are similar to a C++ auto pointer, with the exception that
3749  *              C doesn't have automatic closure (calling destructors) when 
3750  *              exiting a block scope.
3751  *              Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3752  *              function directly.
3753  *
3754  *\return       GType A GType type.
3755  */
3756 GType g_auto_pointer_register(void)
3757 {
3758         static GType auto_pointer_type;
3759         if (!auto_pointer_type)
3760                 auto_pointer_type =
3761                         g_boxed_type_register_static
3762                                 ("G_TYPE_AUTO_POINTER",
3763                                  (GBoxedCopyFunc) g_auto_pointer_copy,
3764                                  (GBoxedFreeFunc) g_auto_pointer_free);
3765         return auto_pointer_type;                                                    
3766 }
3767
3768 /*!
3769  *\brief        Structure with g_new() allocated pointer guarded by the
3770  *              auto pointer
3771  */
3772 typedef struct AutoPointerRef {
3773         void          (*free) (gpointer);
3774         gpointer        pointer;
3775         glong           cnt;
3776 } AutoPointerRef;
3777
3778 /*!
3779  *\brief        The auto pointer opaque structure that references the
3780  *              pointer guard block.
3781  */
3782 typedef struct AutoPointer {
3783         AutoPointerRef *ref;
3784         gpointer        ptr; /*!< access to protected pointer */
3785 } AutoPointer;
3786
3787 /*!
3788  *\brief        Creates an auto pointer for a g_new()ed pointer. Example:
3789  *
3790  *\code 
3791  *
3792  *              ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3793  *              ... when assigning, copying and freeing storage elements
3794  *
3795  *              gtk_list_store_new(N_S_COLUMNS, 
3796  *                                 G_TYPE_AUTO_POINTER,
3797  *                                 -1);
3798  *
3799  *
3800  *              Template *precious_data = g_new0(Template, 1);
3801  *              g_pointer protect = g_auto_pointer_new(precious_data);
3802  *
3803  *              gtk_list_store_set(container, &iter,
3804  *                                 S_DATA, protect,
3805  *                                 -1);
3806  *
3807  *              ... the gtk_list_store has copied the pointer and 
3808  *              ... incremented its reference count, we should free
3809  *              ... the auto pointer (in C++ a destructor would do
3810  *              ... this for us when leaving block scope)
3811  * 
3812  *              g_auto_pointer_free(protect);
3813  *
3814  *              ... gtk_list_store_set() now manages the data. When
3815  *              ... *explicitly* requesting a pointer from the list 
3816  *              ... store, don't forget you get a copy that should be 
3817  *              ... freed with g_auto_pointer_free() eventually.
3818  *
3819  *\endcode
3820  *
3821  *\param        pointer Pointer to be guarded.
3822  *
3823  *\return       GAuto * Pointer that should be used in containers with
3824  *              GType support.
3825  */
3826 GAuto *g_auto_pointer_new(gpointer p)
3827 {
3828         AutoPointerRef *ref;
3829         AutoPointer    *ptr;
3830         
3831         if (p == NULL) 
3832                 return NULL;
3833
3834         ref = g_new0(AutoPointerRef, 1);
3835         ptr = g_new0(AutoPointer, 1);
3836
3837         ref->pointer = p;
3838         ref->free = g_free;
3839         ref->cnt = 1;
3840
3841         ptr->ref = ref;
3842         ptr->ptr = p;
3843
3844 #ifdef REF_DEBUG
3845         G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3846 #endif
3847         return ptr;
3848 }
3849
3850 /*!
3851  *\brief        Allocate an autopointer using the passed \a free function to
3852  *              free the guarded pointer
3853  */
3854 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3855 {
3856         AutoPointer *aptr;
3857         
3858         if (p == NULL)
3859                 return NULL;
3860
3861         aptr = g_auto_pointer_new(p);
3862         aptr->ref->free = free_;
3863         return aptr; 
3864 }
3865
3866 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3867 {
3868         if (auto_ptr == NULL) 
3869                 return NULL;
3870         return ((AutoPointer *) auto_ptr)->ptr; 
3871 }
3872
3873 /*!
3874  *\brief        Copies an auto pointer by. It's mostly not necessary
3875  *              to call this function directly, unless you copy/assign
3876  *              the guarded pointer.
3877  *
3878  *\param        auto_ptr Auto pointer returned by previous call to 
3879  *              g_auto_pointer_new_XXX()
3880  *
3881  *\return       gpointer An auto pointer
3882  */
3883 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3884 {
3885         AutoPointer     *ptr;
3886         AutoPointerRef  *ref;
3887         AutoPointer     *newp;
3888
3889         if (auto_ptr == NULL) 
3890                 return NULL;
3891
3892         ptr = auto_ptr;
3893         ref = ptr->ref;
3894         newp = g_new0(AutoPointer, 1);
3895
3896         newp->ref = ref;
3897         newp->ptr = ref->pointer;
3898         ++(ref->cnt);
3899         
3900 #ifdef REF_DEBUG
3901         G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3902 #endif
3903         return newp;
3904 }
3905
3906 /*!
3907  *\brief        Free an auto pointer
3908  */
3909 void g_auto_pointer_free(GAuto *auto_ptr)
3910 {
3911         AutoPointer     *ptr;
3912         AutoPointerRef  *ref;
3913         
3914         if (auto_ptr == NULL)
3915                 return;
3916
3917         ptr = auto_ptr;
3918         ref = ptr->ref;
3919
3920         if (--(ref->cnt) == 0) {
3921 #ifdef REF_DEBUG
3922                 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3923 #endif
3924                 ref->free(ref->pointer);
3925                 g_free(ref);
3926         } 
3927 #ifdef REF_DEBUG
3928         else
3929                 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3930 #endif
3931         g_free(ptr);            
3932 }
3933