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