2004-08-27 [colin] 0.9.12cvs83.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
46 #include "intl.h"
47 #include "utils.h"
48 #include "socket.h"
49 #include "../codeconv.h"
50
51 #define BUFFSIZE        8192
52
53 static gboolean debug_mode = FALSE;
54
55 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
56
57 void list_free_strings(GList *list)
58 {
59         list = g_list_first(list);
60
61         while (list != NULL) {
62                 g_free(list->data);
63                 list = list->next;
64         }
65 }
66
67 void slist_free_strings(GSList *list)
68 {
69         while (list != NULL) {
70                 g_free(list->data);
71                 list = list->next;
72         }
73 }
74
75 GSList *slist_concat_unique (GSList *first, GSList *second)
76 {
77         GSList *tmp, *ret;
78         if (first == NULL) {
79                 if (second == NULL)
80                         return NULL;
81                 else 
82                         return second;
83         } else if (second == NULL)
84                 return first;
85         ret = first;
86         for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
87                 if (g_slist_find(ret, tmp->data) == NULL)
88                         ret = g_slist_prepend(ret, tmp->data);
89         }
90         return ret;
91 }
92  
93 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
94 {
95         g_free(key);
96 }
97
98 void hash_free_strings(GHashTable *table)
99 {
100         g_hash_table_foreach(table, hash_free_strings_func, NULL);
101 }
102
103 static void hash_free_value_mem_func(gpointer key, gpointer value,
104                                      gpointer data)
105 {
106         g_free(value);
107 }
108
109 void hash_free_value_mem(GHashTable *table)
110 {
111         g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
112 }
113
114 gint str_case_equal(gconstpointer v, gconstpointer v2)
115 {
116         return strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
117 }
118
119 guint str_case_hash(gconstpointer key)
120 {
121         const gchar *p = key;
122         guint h = *p;
123
124         if (h) {
125                 h = tolower(h);
126                 for (p += 1; *p != '\0'; p++)
127                         h = (h << 5) - h + tolower(*p);
128         }
129
130         return h;
131 }
132
133 void ptr_array_free_strings(GPtrArray *array)
134 {
135         gint i;
136         gchar *str;
137
138         g_return_if_fail(array != NULL);
139
140         for (i = 0; i < array->len; i++) {
141                 str = g_ptr_array_index(array, i);
142                 g_free(str);
143         }
144 }
145
146 gint to_number(const gchar *nstr)
147 {
148         register const guchar *p;
149
150         if (*nstr == '\0') return -1;
151
152         for (p = nstr; *p != '\0'; p++)
153                 if (!isdigit(*p)) return -1;
154
155         return atoi(nstr);
156 }
157
158 /* convert integer into string,
159    nstr must be not lower than 11 characters length */
160 gchar *itos_buf(gchar *nstr, gint n)
161 {
162         g_snprintf(nstr, 11, "%d", n);
163         return nstr;
164 }
165
166 /* convert integer into string */
167 gchar *itos(gint n)
168 {
169         static gchar nstr[11];
170
171         return itos_buf(nstr, n);
172 }
173
174 gchar *to_human_readable(off_t size)
175 {
176         static gchar str[10];
177
178         if (size < 1024)
179                 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
180         else if (size >> 10 < 1024)
181                 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
182         else if (size >> 20 < 1024)
183                 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
184         else
185                 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
186
187         return str;
188 }
189
190 /* strcmp with NULL-checking */
191 gint strcmp2(const gchar *s1, const gchar *s2)
192 {
193         if (s1 == NULL || s2 == NULL)
194                 return -1;
195         else
196                 return strcmp(s1, s2);
197 }
198 /* strstr with NULL-checking */
199 gchar *strstr2(const gchar *s1, const gchar *s2)
200 {
201         if (s1 == NULL || s2 == NULL)
202                 return NULL;
203         else
204                 return strstr(s1, s2);
205 }
206 /* compare paths */
207 gint path_cmp(const gchar *s1, const gchar *s2)
208 {
209         gint len1, len2;
210
211         if (s1 == NULL || s2 == NULL) return -1;
212         if (*s1 == '\0' || *s2 == '\0') return -1;
213
214         len1 = strlen(s1);
215         len2 = strlen(s2);
216
217         if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
218         if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
219
220         return strncmp(s1, s2, MAX(len1, len2));
221 }
222
223 /* remove trailing return code */
224 gchar *strretchomp(gchar *str)
225 {
226         register gchar *s;
227
228         if (!*str) return str;
229
230         for (s = str + strlen(str) - 1;
231              s >= str && (*s == '\n' || *s == '\r');
232              s--)
233                 *s = '\0';
234
235         return str;
236 }
237
238 /* remove trailing character */
239 gchar *strtailchomp(gchar *str, gchar tail_char)
240 {
241         register gchar *s;
242
243         if (!*str) return str;
244         if (tail_char == '\0') return str;
245
246         for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
247                 *s = '\0';
248
249         return str;
250 }
251
252 /* remove CR (carriage return) */
253 gchar *strcrchomp(gchar *str)
254 {
255         register gchar *s;
256
257         if (!*str) return str;
258
259         s = str + strlen(str) - 1;
260         if (*s == '\n' && s > str && *(s - 1) == '\r') {
261                 *(s - 1) = '\n';
262                 *s = '\0';
263         }
264
265         return str;
266 }
267
268 /* Similar to `strstr' but this function ignores the case of both strings.  */
269 gchar *strcasestr(const gchar *haystack, const gchar *needle)
270 {
271         register size_t haystack_len, needle_len;
272
273         haystack_len = strlen(haystack);
274         needle_len   = strlen(needle);
275
276         if (haystack_len < needle_len || needle_len == 0)
277                 return NULL;
278
279         while (haystack_len >= needle_len) {
280                 if (!strncasecmp(haystack, needle, needle_len))
281                         return (gchar *)haystack;
282                 else {
283                         haystack++;
284                         haystack_len--;
285                 }
286         }
287
288         return NULL;
289 }
290
291 /* Copy no more than N characters of SRC to DEST, with NULL terminating.  */
292 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
293 {
294         register gchar c;
295         gchar *s = dest;
296
297         do {
298                 if (--n == 0) {
299                         *dest = '\0';
300                         return s;
301                 }
302                 c = *src++;
303                 *dest++ = c;
304         } while (c != '\0');
305
306         /* don't do zero fill */
307         return s;
308 }
309
310 #if !HAVE_ISWALNUM
311 int iswalnum(wint_t wc)
312 {
313         return isalnum((int)wc);
314 }
315 #endif
316
317 #if !HAVE_ISWSPACE
318 int iswspace(wint_t wc)
319 {
320         return isspace((int)wc);
321 }
322 #endif
323
324 #if !HAVE_TOWLOWER
325 wint_t towlower(wint_t wc)
326 {
327         if (wc >= L'A' && wc <= L'Z')
328                 return wc + L'a' - L'A';
329
330         return wc;
331 }
332 #endif
333
334 #if !HAVE_WCSLEN
335 size_t wcslen(const wchar_t *s)
336 {
337         size_t len = 0;
338
339         while (*s != L'\0')
340                 ++len, ++s;
341
342         return len;
343 }
344 #endif
345
346 #if !HAVE_WCSCPY
347 /* Copy SRC to DEST.  */
348 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
349 {
350         wint_t c;
351         wchar_t *s = dest;
352
353         do {
354                 c = *src++;
355                 *dest++ = c;
356         } while (c != L'\0');
357
358         return s;
359 }
360 #endif
361
362 #if !HAVE_WCSNCPY
363 /* Copy no more than N wide-characters of SRC to DEST.  */
364 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
365 {
366         wint_t c;
367         wchar_t *s = dest;
368
369         do {
370                 c = *src++;
371                 *dest++ = c;
372                 if (--n == 0)
373                         return s;
374         } while (c != L'\0');
375
376         /* zero fill */
377         do
378                 *dest++ = L'\0';
379         while (--n > 0);
380
381         return s;
382 }
383 #endif
384
385 /* Duplicate S, returning an identical malloc'd string. */
386 wchar_t *wcsdup(const wchar_t *s)
387 {
388         wchar_t *new_str;
389
390         if (s) {
391                 new_str = g_new(wchar_t, wcslen(s) + 1);
392                 wcscpy(new_str, s);
393         } else
394                 new_str = NULL;
395
396         return new_str;
397 }
398
399 /* Duplicate no more than N wide-characters of S,
400    returning an identical malloc'd string. */
401 wchar_t *wcsndup(const wchar_t *s, size_t n)
402 {
403         wchar_t *new_str;
404
405         if (s) {
406                 new_str = g_new(wchar_t, n + 1);
407                 wcsncpy(new_str, s, n);
408                 new_str[n] = (wchar_t)0;
409         } else
410                 new_str = NULL;
411
412         return new_str;
413 }
414
415 wchar_t *strdup_mbstowcs(const gchar *s)
416 {
417         wchar_t *new_str;
418
419         if (s) {
420                 new_str = g_new(wchar_t, strlen(s) + 1);
421                 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
422                         g_free(new_str);
423                         new_str = NULL;
424                 } else
425                         new_str = g_realloc(new_str,
426                                             sizeof(wchar_t) * (wcslen(new_str) + 1));
427         } else
428                 new_str = NULL;
429
430         return new_str;
431 }
432
433 gchar *strdup_wcstombs(const wchar_t *s)
434 {
435         gchar *new_str;
436         size_t len;
437
438         if (s) {
439                 len = wcslen(s) * MB_CUR_MAX + 1;
440                 new_str = g_new(gchar, len);
441                 if (wcstombs(new_str, s, len) < 0) {
442                         g_free(new_str);
443                         new_str = NULL;
444                 } else
445                         new_str = g_realloc(new_str, strlen(new_str) + 1);
446         } else
447                 new_str = NULL;
448
449         return new_str;
450 }
451
452 /* Compare S1 and S2, ignoring case.  */
453 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
454 {
455         wint_t c1;
456         wint_t c2;
457
458         while (n--) {
459                 c1 = towlower(*s1++);
460                 c2 = towlower(*s2++);
461                 if (c1 != c2)
462                         return c1 - c2;
463                 else if (c1 == 0 && c2 == 0)
464                         break;
465         }
466
467         return 0;
468 }
469
470 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case.  */
471 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
472 {
473         register size_t haystack_len, needle_len;
474
475         haystack_len = wcslen(haystack);
476         needle_len   = wcslen(needle);
477
478         if (haystack_len < needle_len || needle_len == 0)
479                 return NULL;
480
481         while (haystack_len >= needle_len) {
482                 if (!wcsncasecmp(haystack, needle, needle_len))
483                         return (wchar_t *)haystack;
484                 else {
485                         haystack++;
486                         haystack_len--;
487                 }
488         }
489
490         return NULL;
491 }
492
493 gint get_mbs_len(const gchar *s)
494 {
495         const gchar *p = s;
496         gint mb_len;
497         gint len = 0;
498
499         if (!p)
500                 return -1;
501
502         while (*p != '\0') {
503                 mb_len = mblen(p, MB_LEN_MAX);
504                 if (mb_len == 0)
505                         break;
506                 else if (mb_len < 0)
507                         return -1;
508                 else
509                         len++;
510
511                 p += mb_len;
512         }
513
514         return len;
515 }
516
517 /* Examine if next block is non-ASCII string */
518 gboolean is_next_nonascii(const guchar *s)
519 {
520         const guchar *p;
521
522         /* skip head space */
523         for (p = s; *p != '\0' && isspace(*p); p++)
524                 ;
525         for (; *p != '\0' && !isspace(*p); p++) {
526                 if (*p > 127 || *p < 32)
527                         return TRUE;
528         }
529
530         return FALSE;
531 }
532
533 gint get_next_word_len(const guchar *s)
534 {
535         gint len = 0;
536
537         for (; *s != '\0' && !isspace(*s); s++, len++)
538                 ;
539
540         return len;
541 }
542
543 /* compare subjects */
544 gint subject_compare(const gchar *s1, const gchar *s2)
545 {
546         gchar *str1, *str2;
547
548         if (!s1 || !s2) return -1;
549         if (!*s1 || !*s2) return -1;
550
551         Xstrdup_a(str1, s1, return -1);
552         Xstrdup_a(str2, s2, return -1);
553
554         trim_subject_for_compare(str1);
555         trim_subject_for_compare(str2);
556
557         if (!*str1 || !*str2) return -1;
558
559         return strcmp(str1, str2);
560 }
561
562 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
563 {
564         gchar *str1, *str2;
565
566         if (!s1 || !s2) return -1;
567
568         Xstrdup_a(str1, s1, return -1);
569         Xstrdup_a(str2, s2, return -1);
570
571         trim_subject_for_sort(str1);
572         trim_subject_for_sort(str2);
573
574         return strcasecmp(str1, str2);
575 }
576
577 void trim_subject_for_compare(gchar *str)
578 {
579         guchar *srcp;
580
581         eliminate_parenthesis(str, '[', ']');
582         eliminate_parenthesis(str, '(', ')');
583         g_strstrip(str);
584
585         srcp = str + subject_get_prefix_length(str);
586         if (srcp != str)
587                 memmove(str, srcp, strlen(srcp) + 1);
588 }
589
590 void trim_subject_for_sort(gchar *str)
591 {
592         guchar *srcp;
593
594         g_strstrip(str);
595
596         srcp = str + subject_get_prefix_length(str);
597         if (srcp != str)        
598                 memmove(str, srcp, strlen(srcp) + 1);
599 }
600
601 void trim_subject(gchar *str)
602 {
603         register guchar *srcp, *destp;
604         gchar op, cl;
605         gint in_brace;
606
607         destp = str + subject_get_prefix_length(str);
608
609         if (*destp == '[') {
610                 op = '[';
611                 cl = ']';
612         } else if (*destp == '(') {
613                 op = '(';
614                 cl = ')';
615         } else
616                 return;
617
618         srcp = destp + 1;
619         in_brace = 1;
620         while (*srcp) {
621                 if (*srcp == op)
622                         in_brace++;
623                 else if (*srcp == cl)
624                         in_brace--;
625                 srcp++;
626                 if (in_brace == 0)
627                         break;
628         }
629         while (isspace(*srcp)) srcp++;
630         memmove(destp, srcp, strlen(srcp) + 1);
631 }
632
633 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
634 {
635         register guchar *srcp, *destp;
636         gint in_brace;
637
638         srcp = destp = str;
639
640         while ((destp = strchr(destp, op))) {
641                 in_brace = 1;
642                 srcp = destp + 1;
643                 while (*srcp) {
644                         if (*srcp == op)
645                                 in_brace++;
646                         else if (*srcp == cl)
647                                 in_brace--;
648                         srcp++;
649                         if (in_brace == 0)
650                                 break;
651                 }
652                 while (isspace(*srcp)) srcp++;
653                 memmove(destp, srcp, strlen(srcp) + 1);
654         }
655 }
656
657 void extract_parenthesis(gchar *str, gchar op, gchar cl)
658 {
659         register gchar *srcp, *destp;
660         gint in_brace;
661
662         srcp = destp = str;
663
664         while ((srcp = strchr(destp, op))) {
665                 if (destp > str)
666                         *destp++ = ' ';
667                 memmove(destp, srcp + 1, strlen(srcp));
668                 in_brace = 1;
669                 while(*destp) {
670                         if (*destp == op)
671                                 in_brace++;
672                         else if (*destp == cl)
673                                 in_brace--;
674
675                         if (in_brace == 0)
676                                 break;
677
678                         destp++;
679                 }
680         }
681         *destp = '\0';
682 }
683
684 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
685                                          gchar op, gchar cl)
686 {
687         register gchar *srcp, *destp;
688         gint in_brace;
689         gboolean in_quote = FALSE;
690
691         srcp = destp = str;
692
693         while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
694                 if (destp > str)
695                         *destp++ = ' ';
696                 memmove(destp, srcp + 1, strlen(srcp));
697                 in_brace = 1;
698                 while(*destp) {
699                         if (*destp == op && !in_quote)
700                                 in_brace++;
701                         else if (*destp == cl && !in_quote)
702                                 in_brace--;
703                         else if (*destp == quote_chr)
704                                 in_quote ^= TRUE;
705
706                         if (in_brace == 0)
707                                 break;
708
709                         destp++;
710                 }
711         }
712         *destp = '\0';
713 }
714
715 void eliminate_quote(gchar *str, gchar quote_chr)
716 {
717         register guchar *srcp, *destp;
718
719         srcp = destp = str;
720
721         while ((destp = strchr(destp, quote_chr))) {
722                 if ((srcp = strchr(destp + 1, quote_chr))) {
723                         srcp++;
724                         while (isspace(*srcp)) srcp++;
725                         memmove(destp, srcp, strlen(srcp) + 1);
726                 } else {
727                         *destp = '\0';
728                         break;
729                 }
730         }
731 }
732
733 void extract_quote(gchar *str, gchar quote_chr)
734 {
735         register gchar *p;
736
737         if ((str = strchr(str, quote_chr))) {
738                 p = str;
739                 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
740                         memmove(p - 1, p, strlen(p) + 1);
741                         p--;
742                 }
743                 if(p) {
744                         *p = '\0';
745                         memmove(str, str + 1, p - str);
746                 }
747         }
748 }
749
750 void eliminate_address_comment(gchar *str)
751 {
752         register guchar *srcp, *destp;
753         gint in_brace;
754
755         srcp = destp = str;
756
757         while ((destp = strchr(destp, '"'))) {
758                 if ((srcp = strchr(destp + 1, '"'))) {
759                         srcp++;
760                         if (*srcp == '@') {
761                                 destp = srcp + 1;
762                         } else {
763                                 while (isspace(*srcp)) srcp++;
764                                 memmove(destp, srcp, strlen(srcp) + 1);
765                         }
766                 } else {
767                         *destp = '\0';
768                         break;
769                 }
770         }
771
772         srcp = destp = str;
773
774         while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
775                 in_brace = 1;
776                 srcp = destp + 1;
777                 while (*srcp) {
778                         if (*srcp == '(')
779                                 in_brace++;
780                         else if (*srcp == ')')
781                                 in_brace--;
782                         srcp++;
783                         if (in_brace == 0)
784                                 break;
785                 }
786                 while (isspace(*srcp)) srcp++;
787                 memmove(destp, srcp, strlen(srcp) + 1);
788         }
789 }
790
791 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
792 {
793         gboolean in_quote = FALSE;
794
795         while (*str) {
796                 if (*str == c && !in_quote)
797                         return (gchar *)str;
798                 if (*str == quote_chr)
799                         in_quote ^= TRUE;
800                 str++;
801         }
802
803         return NULL;
804 }
805
806 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
807 {
808         gboolean in_quote = FALSE;
809         const gchar *p;
810
811         p = str + strlen(str) - 1;
812         while (p >= str) {
813                 if (*p == c && !in_quote)
814                         return (gchar *)p;
815                 if (*p == quote_chr)
816                         in_quote ^= TRUE;
817                 p--;
818         }
819
820         return NULL;
821 }
822
823 void extract_address(gchar *str)
824 {
825         eliminate_address_comment(str);
826         if (strchr_with_skip_quote(str, '"', '<'))
827                 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
828         g_strstrip(str);
829 }
830
831 void extract_list_id_str(gchar *str)
832 {
833         if (strchr_with_skip_quote(str, '"', '<'))
834                 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
835         g_strstrip(str);
836 }
837
838 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
839 {
840         gchar *work;
841         gchar *workp;
842
843         if (!str) return addr_list;
844
845         Xstrdup_a(work, str, return addr_list);
846
847         if (removecomments)
848                 eliminate_address_comment(work);
849         workp = work;
850
851         while (workp && *workp) {
852                 gchar *p, *next;
853
854                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
855                         *p = '\0';
856                         next = p + 1;
857                 } else
858                         next = NULL;
859
860                 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
861                         extract_parenthesis_with_skip_quote
862                                 (workp, '"', '<', '>');
863
864                 g_strstrip(workp);
865                 if (*workp)
866                         addr_list = g_slist_append(addr_list, g_strdup(workp));
867
868                 workp = next;
869         }
870
871         return addr_list;
872 }
873
874 GSList *address_list_append(GSList *addr_list, const gchar *str)
875 {
876         return address_list_append_real(addr_list, str, TRUE);
877 }
878
879 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
880 {
881         return address_list_append_real(addr_list, str, FALSE);
882 }
883
884 GSList *references_list_append(GSList *msgid_list, const gchar *str)
885 {
886         const gchar *strp;
887
888         if (!str) return msgid_list;
889         strp = str;
890
891         while (strp && *strp) {
892                 const gchar *start, *end;
893                 gchar *msgid;
894
895                 if ((start = strchr(strp, '<')) != NULL) {
896                         end = strchr(start + 1, '>');
897                         if (!end) break;
898                 } else
899                         break;
900
901                 msgid = g_strndup(start + 1, end - start - 1);
902                 g_strstrip(msgid);
903                 if (*msgid)
904                         msgid_list = g_slist_append(msgid_list, msgid);
905                 else
906                         g_free(msgid);
907
908                 strp = end + 1;
909         }
910
911         return msgid_list;
912 }
913
914 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
915 {
916         gchar *work;
917         gchar *workp;
918
919         if (!str) return group_list;
920
921         Xstrdup_a(work, str, return group_list);
922
923         workp = work;
924
925         while (workp && *workp) {
926                 gchar *p, *next;
927
928                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
929                         *p = '\0';
930                         next = p + 1;
931                 } else
932                         next = NULL;
933
934                 g_strstrip(workp);
935                 if (*workp)
936                         group_list = g_slist_append(group_list,
937                                                     g_strdup(workp));
938
939                 workp = next;
940         }
941
942         return group_list;
943 }
944
945 GList *add_history(GList *list, const gchar *str)
946 {
947         GList *old;
948
949         g_return_val_if_fail(str != NULL, list);
950
951         old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
952         if (old) {
953                 g_free(old->data);
954                 list = g_list_remove(list, old->data);
955         } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
956                 GList *last;
957
958                 last = g_list_last(list);
959                 if (last) {
960                         g_free(last->data);
961                         g_list_remove(list, last->data);
962                 }
963         }
964
965         list = g_list_prepend(list, g_strdup(str));
966
967         return list;
968 }
969
970 void remove_return(gchar *str)
971 {
972         register gchar *p = str;
973
974         while (*p) {
975                 if (*p == '\n' || *p == '\r')
976                         memmove(p, p + 1, strlen(p));
977                 else
978                         p++;
979         }
980 }
981
982 void remove_space(gchar *str)
983 {
984         register guchar *p = str;
985         register gint spc;
986
987         while (*p) {
988                 spc = 0;
989                 while (isspace(*(p + spc)))
990                         spc++;
991                 if (spc)
992                         memmove(p, p + spc, strlen(p + spc) + 1);
993                 else
994                         p++;
995         }
996 }
997
998 void unfold_line(gchar *str)
999 {
1000         register guchar *p = str;
1001         register gint spc;
1002
1003         while (*p) {
1004                 if (*p == '\n' || *p == '\r') {
1005                         *p++ = ' ';
1006                         spc = 0;
1007                         while (isspace(*(p + spc)))
1008                                 spc++;
1009                         if (spc)
1010                                 memmove(p, p + spc, strlen(p + spc) + 1);
1011                 } else
1012                         p++;
1013         }
1014 }
1015
1016 void subst_char(gchar *str, gchar orig, gchar subst)
1017 {
1018         register gchar *p = str;
1019
1020         while (*p) {
1021                 if (*p == orig)
1022                         *p = subst;
1023                 p++;
1024         }
1025 }
1026
1027 void subst_chars(gchar *str, gchar *orig, gchar subst)
1028 {
1029         register gchar *p = str;
1030
1031         while (*p) {
1032                 if (strchr(orig, *p) != NULL)
1033                         *p = subst;
1034                 p++;
1035         }
1036 }
1037
1038 void subst_for_filename(gchar *str)
1039 {
1040         subst_chars(str, " \t\r\n\"/\\", '_');
1041 }
1042
1043 void subst_for_shellsafe_filename(gchar *str)
1044 {
1045         subst_for_filename(str);
1046         subst_chars(str, "|&;()<>'!{}[]",'_');
1047 }
1048
1049 gboolean is_header_line(const gchar *str)
1050 {
1051         if (str[0] == ':') return FALSE;
1052
1053         while (*str != '\0' && *str != ' ') {
1054                 if (*str == ':')
1055                         return TRUE;
1056                 str++;
1057         }
1058
1059         return FALSE;
1060 }
1061
1062 gboolean is_ascii_str(const guchar *str)
1063 {
1064         g_return_val_if_fail(str, FALSE);
1065
1066         while (*str != '\0') {
1067                 if (*str != '\t' && *str != ' ' &&
1068                     *str != '\r' && *str != '\n' &&
1069                     (*str < 32 || *str >= 127))
1070                         return FALSE;
1071                 str++;
1072         }
1073
1074         return TRUE;
1075 }
1076
1077 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1078 {
1079         const guchar *first_pos;
1080         const guchar *last_pos;
1081         const guchar *p = str;
1082         gint quote_level = -1;
1083
1084         /* speed up line processing by only searching to the last '>' */
1085         if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1086                 /* skip a line if it contains a '<' before the initial '>' */
1087                 if (memchr(str, '<', first_pos - (const guchar *)str) != NULL)
1088                         return -1;
1089                 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1090         } else
1091                 return -1;
1092
1093         while (p <= last_pos) {
1094                 while (p < last_pos) {
1095                         if (isspace(*p))
1096                                 p++;
1097                         else
1098                                 break;
1099                 }
1100
1101                 if (strchr(quote_chars, *p))
1102                         quote_level++;
1103                 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1104                         /* any characters are allowed except '-' and space */
1105                         while (*p != '-' 
1106                                && !strchr(quote_chars, *p) 
1107                                && !isspace(*p) 
1108                                && p < last_pos)
1109                                 p++;
1110                         if (strchr(quote_chars, *p))
1111                                 quote_level++;
1112                         else
1113                                 break;
1114                 }
1115
1116                 p++;
1117         }
1118
1119         return quote_level;
1120 }
1121
1122 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars) 
1123 {
1124         gchar * position = NULL;
1125         gchar * tmp_pos = NULL;
1126         int i;
1127
1128         if (quote_chars == NULL)
1129                 return FALSE;
1130         
1131         for (i = 0; i < strlen(quote_chars); i++) {
1132                 tmp_pos = strchr (str,  quote_chars[i]);
1133                 if(position == NULL 
1134                    || (tmp_pos != NULL && position >= tmp_pos) )
1135                         position = tmp_pos;
1136         }
1137         return position; 
1138 }
1139
1140 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars) 
1141 {
1142         gchar * position = NULL;
1143         gchar * tmp_pos = NULL;
1144         int i;
1145
1146         if (quote_chars == NULL)
1147                 return FALSE;
1148         
1149         for (i = 0; i < strlen(quote_chars); i++) {
1150                 tmp_pos = strrchr (str, quote_chars[i]);
1151                 if(position == NULL 
1152                    || (tmp_pos != NULL && position <= tmp_pos) )
1153                         position = tmp_pos;
1154         }
1155         return position; 
1156 }
1157
1158 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1159 {
1160         register guint haystack_len, needle_len;
1161         gboolean in_squote = FALSE, in_dquote = FALSE;
1162
1163         haystack_len = strlen(haystack);
1164         needle_len   = strlen(needle);
1165
1166         if (haystack_len < needle_len || needle_len == 0)
1167                 return NULL;
1168
1169         while (haystack_len >= needle_len) {
1170                 if (!in_squote && !in_dquote &&
1171                     !strncmp(haystack, needle, needle_len))
1172                         return (gchar *)haystack;
1173
1174                 /* 'foo"bar"' -> foo"bar"
1175                    "foo'bar'" -> foo'bar' */
1176                 if (*haystack == '\'') {
1177                         if (in_squote)
1178                                 in_squote = FALSE;
1179                         else if (!in_dquote)
1180                                 in_squote = TRUE;
1181                 } else if (*haystack == '\"') {
1182                         if (in_dquote)
1183                                 in_dquote = FALSE;
1184                         else if (!in_squote)
1185                                 in_dquote = TRUE;
1186                 }
1187
1188                 haystack++;
1189                 haystack_len--;
1190         }
1191
1192         return NULL;
1193 }
1194
1195 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1196 {
1197         const gchar *p;
1198         gchar quote_chr = '"';
1199         gint in_brace;
1200         gboolean in_quote = FALSE;
1201
1202         p = str;
1203
1204         if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1205                 p++;
1206                 in_brace = 1;
1207                 while (*p) {
1208                         if (*p == op && !in_quote)
1209                                 in_brace++;
1210                         else if (*p == cl && !in_quote)
1211                                 in_brace--;
1212                         else if (*p == quote_chr)
1213                                 in_quote ^= TRUE;
1214
1215                         if (in_brace == 0)
1216                                 return (gchar *)p;
1217
1218                         p++;
1219                 }
1220         }
1221
1222         return NULL;
1223 }
1224
1225 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1226                              gint max_tokens)
1227 {
1228         GSList *string_list = NULL, *slist;
1229         gchar **str_array;
1230         const gchar *s_op, *s_cl;
1231         guint i, n = 1;
1232
1233         g_return_val_if_fail(str != NULL, NULL);
1234
1235         if (max_tokens < 1)
1236                 max_tokens = G_MAXINT;
1237
1238         s_op = strchr_with_skip_quote(str, '"', op);
1239         if (!s_op) return NULL;
1240         str = s_op;
1241         s_cl = strchr_parenthesis_close(str, op, cl);
1242         if (s_cl) {
1243                 do {
1244                         guint len;
1245                         gchar *new_string;
1246
1247                         str++;
1248                         len = s_cl - str;
1249                         new_string = g_new(gchar, len + 1);
1250                         strncpy(new_string, str, len);
1251                         new_string[len] = 0;
1252                         string_list = g_slist_prepend(string_list, new_string);
1253                         n++;
1254                         str = s_cl + 1;
1255
1256                         while (*str && isspace(*(guchar *)str)) str++;
1257                         if (*str != op) {
1258                                 string_list = g_slist_prepend(string_list,
1259                                                               g_strdup(""));
1260                                 n++;
1261                                 s_op = strchr_with_skip_quote(str, '"', op);
1262                                 if (!--max_tokens || !s_op) break;
1263                                 str = s_op;
1264                         } else
1265                                 s_op = str;
1266                         s_cl = strchr_parenthesis_close(str, op, cl);
1267                 } while (--max_tokens && s_cl);
1268         }
1269
1270         str_array = g_new(gchar*, n);
1271
1272         i = n - 1;
1273
1274         str_array[i--] = NULL;
1275         for (slist = string_list; slist; slist = slist->next)
1276                 str_array[i--] = slist->data;
1277
1278         g_slist_free(string_list);
1279
1280         return str_array;
1281 }
1282
1283 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1284                             gint max_tokens)
1285 {
1286         GSList *string_list = NULL, *slist;
1287         gchar **str_array, *s, *new_str;
1288         guint i, n = 1, len;
1289
1290         g_return_val_if_fail(str != NULL, NULL);
1291         g_return_val_if_fail(delim != NULL, NULL);
1292
1293         if (max_tokens < 1)
1294                 max_tokens = G_MAXINT;
1295
1296         s = strstr_with_skip_quote(str, delim);
1297         if (s) {
1298                 guint delimiter_len = strlen(delim);
1299
1300                 do {
1301                         len = s - str;
1302                         new_str = g_strndup(str, len);
1303
1304                         if (new_str[0] == '\'' || new_str[0] == '\"') {
1305                                 if (new_str[len - 1] == new_str[0]) {
1306                                         new_str[len - 1] = '\0';
1307                                         memmove(new_str, new_str + 1, len - 1);
1308                                 }
1309                         }
1310                         string_list = g_slist_prepend(string_list, new_str);
1311                         n++;
1312                         str = s + delimiter_len;
1313                         s = strstr_with_skip_quote(str, delim);
1314                 } while (--max_tokens && s);
1315         }
1316
1317         if (*str) {
1318                 new_str = g_strdup(str);
1319                 if (new_str[0] == '\'' || new_str[0] == '\"') {
1320                         len = strlen(str);
1321                         if (new_str[len - 1] == new_str[0]) {
1322                                 new_str[len - 1] = '\0';
1323                                 memmove(new_str, new_str + 1, len - 1);
1324                         }
1325                 }
1326                 string_list = g_slist_prepend(string_list, new_str);
1327                 n++;
1328         }
1329
1330         str_array = g_new(gchar*, n);
1331
1332         i = n - 1;
1333
1334         str_array[i--] = NULL;
1335         for (slist = string_list; slist; slist = slist->next)
1336                 str_array[i--] = slist->data;
1337
1338         g_slist_free(string_list);
1339
1340         return str_array;
1341 }
1342
1343 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1344 {
1345         gchar *abbrev_group;
1346         gchar *ap;
1347         const gchar *p = group;
1348         const gchar *last;
1349
1350         g_return_val_if_fail(group != NULL, NULL);
1351
1352         last = group + strlen(group);
1353         abbrev_group = ap = g_malloc(strlen(group) + 1);
1354
1355         while (*p) {
1356                 while (*p == '.')
1357                         *ap++ = *p++;
1358                 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1359                         *ap++ = *p++;
1360                         while (*p != '.') p++;
1361                 } else {
1362                         strcpy(ap, p);
1363                         return abbrev_group;
1364                 }
1365         }
1366
1367         *ap = '\0';
1368         return abbrev_group;
1369 }
1370
1371 gchar *trim_string(const gchar *str, gint len)
1372 {
1373         const gchar *p = str;
1374         gint mb_len;
1375         gchar *new_str;
1376         gint new_len = 0;
1377
1378         if (!str) return NULL;
1379         if (strlen(str) <= len)
1380                 return g_strdup(str);
1381
1382         while (*p != '\0') {
1383                 mb_len = mblen(p, MB_LEN_MAX);
1384                 if (mb_len == 0)
1385                         break;
1386                 else if (mb_len < 0)
1387                         return g_strdup(str);
1388                 else if (new_len + mb_len > len)
1389                         break;
1390                 else
1391                         new_len += mb_len;
1392                 p += mb_len;
1393         }
1394
1395         Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1396         return g_strconcat(new_str, "...", NULL);
1397 }
1398
1399 GList *uri_list_extract_filenames(const gchar *uri_list)
1400 {
1401         GList *result = NULL;
1402         const gchar *p, *q;
1403         gchar *escaped_utf8uri;
1404         gchar *file;
1405
1406         p = uri_list;
1407
1408         while (p) {
1409                 if (*p != '#') {
1410                         while (isspace(*p)) p++;
1411                         if (!strncmp(p, "file:", 5)) {
1412                                 q = p;
1413                                 q += 5;
1414                                 while (*q && *q != '\n' && *q != '\r') q++;
1415
1416                                 if (q > p) {
1417                                         gchar *file, *locale_file = NULL;
1418                                         q--;
1419                                         while (q > p && isspace(*q)) q--;
1420                                         Xalloca(escaped_utf8uri, q - p + 2,
1421                                                 return result);
1422                                         Xalloca(file, q - p + 2,
1423                                                 return result);
1424                                         *file = '\0';
1425                                         strncpy(escaped_utf8uri, p, q - p + 1);
1426                                         escaped_utf8uri[q - p + 1] = '\0';
1427                                         decode_uri(file, escaped_utf8uri);
1428 #warning FIXME_GTK2 /* should we use g_filename_from_utf8()? */
1429                     /*
1430                      * g_filename_from_uri() rejects escaped/locale encoded uri
1431                      * string which come from Nautilus.
1432                      */
1433                                         if (g_utf8_validate(file, -1, NULL))
1434                                                 locale_file
1435                                                         = conv_codeset_strdup(
1436                                                                 file + 5,
1437                                                                 CS_UTF_8,
1438                                                                 conv_get_current_charset_str());
1439                                         if (!locale_file)
1440                                                 locale_file = g_strdup(file + 5);
1441                                         result = g_list_append(result, locale_file);
1442                                 }
1443                         }
1444                 }
1445                 p = strchr(p, '\n');
1446                 if (p) p++;
1447         }
1448
1449         return result;
1450 }
1451
1452 #define HEX_TO_INT(val, hex) \
1453 { \
1454         gchar c = hex; \
1455  \
1456         if ('0' <= c && c <= '9') { \
1457                 val = c - '0'; \
1458         } else if ('a' <= c && c <= 'f') { \
1459                 val = c - 'a' + 10; \
1460         } else if ('A' <= c && c <= 'F') { \
1461                 val = c - 'A' + 10; \
1462         } else { \
1463                 val = 0; \
1464         } \
1465 }
1466
1467 /* Converts two-digit hexadecimal to decimal.  Used for unescaping escaped 
1468  * characters
1469  */
1470 static gint axtoi(const gchar *hexstr)
1471 {
1472         gint hi, lo, result;
1473        
1474         hi = hexstr[0];
1475         if ('0' <= hi && hi <= '9') {
1476                 hi -= '0';
1477         } else
1478                 if ('a' <= hi && hi <= 'f') {
1479                         hi -= ('a' - 10);
1480                 } else
1481                         if ('A' <= hi && hi <= 'F') {
1482                                 hi -= ('A' - 10);
1483                         }
1484
1485         lo = hexstr[1];
1486         if ('0' <= lo && lo <= '9') {
1487                 lo -= '0';
1488         } else
1489                 if ('a' <= lo && lo <= 'f') {
1490                         lo -= ('a'-10);
1491                 } else
1492                         if ('A' <= lo && lo <= 'F') {
1493                                 lo -= ('A' - 10);
1494                         }
1495         result = lo + (16 * hi);
1496         return result;
1497 }
1498
1499 gboolean is_uri_string(const gchar *str)
1500 {
1501         return (g_strncasecmp(str, "http://", 7) == 0 ||
1502                 g_strncasecmp(str, "https://", 8) == 0 ||
1503                 g_strncasecmp(str, "ftp://", 6) == 0 ||
1504                 g_strncasecmp(str, "www.", 4) == 0);
1505 }
1506
1507 gchar *get_uri_path(const gchar *uri)
1508 {
1509         if (g_strncasecmp(uri, "http://", 7) == 0)
1510                 return (gchar *)(uri + 7);
1511         else if (g_strncasecmp(uri, "https://", 8) == 0)
1512                 return (gchar *)(uri + 8);
1513         else if (g_strncasecmp(uri, "ftp://", 6) == 0)
1514                 return (gchar *)(uri + 6);
1515         else
1516                 return (gchar *)uri;
1517 }
1518
1519 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1520  * plusses, and escape characters are used)
1521  */
1522 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1523 {
1524         gchar *dec = decoded_uri;
1525         const gchar *enc = encoded_uri;
1526
1527         while (*enc) {
1528                 if (*enc == '%') {
1529                         enc++;
1530                         if (isxdigit((guchar)enc[0]) &&
1531                             isxdigit((guchar)enc[1])) {
1532                                 *dec = axtoi(enc);
1533                                 dec++;
1534                                 enc += 2;
1535                         }
1536                 } else {
1537                         if (*enc == '+')
1538                                 *dec = ' ';
1539                         else
1540                                 *dec = *enc;
1541                         dec++;
1542                         enc++;
1543                 }
1544         }
1545
1546         *dec = '\0';
1547 }
1548
1549 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1550                      gchar **subject, gchar **body)
1551 {
1552         gchar *tmp_mailto;
1553         gchar *p;
1554
1555         Xstrdup_a(tmp_mailto, mailto, return -1);
1556
1557         if (!strncmp(tmp_mailto, "mailto:", 7))
1558                 tmp_mailto += 7;
1559
1560         p = strchr(tmp_mailto, '?');
1561         if (p) {
1562                 *p = '\0';
1563                 p++;
1564         }
1565
1566         if (to && !*to)
1567                 *to = g_strdup(tmp_mailto);
1568
1569         while (p) {
1570                 gchar *field, *value;
1571
1572                 field = p;
1573
1574                 p = strchr(p, '=');
1575                 if (!p) break;
1576                 *p = '\0';
1577                 p++;
1578
1579                 value = p;
1580
1581                 p = strchr(p, '&');
1582                 if (p) {
1583                         *p = '\0';
1584                         p++;
1585                 }
1586
1587                 if (*value == '\0') continue;
1588
1589                 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1590                         *cc = g_strdup(value);
1591                 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1592                         *bcc = g_strdup(value);
1593                 } else if (subject && !*subject &&
1594                            !g_strcasecmp(field, "subject")) {
1595                         *subject = g_malloc(strlen(value) + 1);
1596                         decode_uri(*subject, value);
1597                 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1598                         *body = g_malloc(strlen(value) + 1);
1599                         decode_uri(*body, value);
1600                 }
1601         }
1602
1603         return 0;
1604 }
1605
1606 /*
1607  * We need this wrapper around g_get_home_dir(), so that
1608  * we can fix some Windoze things here.  Should be done in glibc of course
1609  * but as long as we are not able to do our own extensions to glibc, we do
1610  * it here.
1611  */
1612 const gchar *get_home_dir(void)
1613 {
1614 #if HAVE_DOSISH_SYSTEM
1615     static gchar *home_dir;
1616
1617     if (!home_dir) {
1618         home_dir = read_w32_registry_string(NULL,
1619                                             "Software\\Sylpheed", "HomeDir" );
1620         if (!home_dir || !*home_dir) {
1621             if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1622                 const char *s = g_get_home_dir();
1623                 if (s && *s)
1624                     home_dir = g_strdup (s);
1625             }
1626             if (!home_dir || !*home_dir) 
1627                 home_dir = g_strdup ("c:\\sylpheed");
1628         }
1629         debug_print("initialized home_dir to `%s'\n", home_dir);
1630     }
1631     return home_dir;
1632 #else /* standard glib */
1633     return g_get_home_dir();
1634 #endif
1635 }
1636
1637 const gchar *get_rc_dir(void)
1638 {
1639         static gchar *rc_dir = NULL;
1640
1641         if (!rc_dir)
1642                 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1643                                      RC_DIR, NULL);
1644
1645         return rc_dir;
1646 }
1647
1648 const gchar *get_news_cache_dir(void)
1649 {
1650         static gchar *news_cache_dir = NULL;
1651
1652         if (!news_cache_dir)
1653                 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1654                                              NEWS_CACHE_DIR, NULL);
1655
1656         return news_cache_dir;
1657 }
1658
1659 const gchar *get_imap_cache_dir(void)
1660 {
1661         static gchar *imap_cache_dir = NULL;
1662
1663         if (!imap_cache_dir)
1664                 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1665                                              IMAP_CACHE_DIR, NULL);
1666
1667         return imap_cache_dir;
1668 }
1669
1670 const gchar *get_mbox_cache_dir(void)
1671 {
1672         static gchar *mbox_cache_dir = NULL;
1673
1674         if (!mbox_cache_dir)
1675                 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1676                                              MBOX_CACHE_DIR, NULL);
1677
1678         return mbox_cache_dir;
1679 }
1680
1681 const gchar *get_mime_tmp_dir(void)
1682 {
1683         static gchar *mime_tmp_dir = NULL;
1684
1685         if (!mime_tmp_dir)
1686                 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1687                                            MIME_TMP_DIR, NULL);
1688
1689         return mime_tmp_dir;
1690 }
1691
1692 const gchar *get_template_dir(void)
1693 {
1694         static gchar *template_dir = NULL;
1695
1696         if (!template_dir)
1697                 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1698                                            TEMPLATE_DIR, NULL);
1699
1700         return template_dir;
1701 }
1702
1703 const gchar *get_header_cache_dir(void)
1704 {
1705         static gchar *header_dir = NULL;
1706
1707         if (!header_dir)
1708                 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1709                                          HEADER_CACHE_DIR, NULL);
1710
1711         return header_dir;
1712 }
1713
1714 const gchar *get_tmp_dir(void)
1715 {
1716         static gchar *tmp_dir = NULL;
1717
1718         if (!tmp_dir)
1719                 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1720                                       TMP_DIR, NULL);
1721
1722         return tmp_dir;
1723 }
1724
1725 gchar *get_tmp_file(void)
1726 {
1727         gchar *tmp_file;
1728         static guint32 id = 0;
1729
1730         tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1731                                    get_tmp_dir(), G_DIR_SEPARATOR, id++);
1732
1733         return tmp_file;
1734 }
1735
1736 const gchar *get_domain_name(void)
1737 {
1738         static gchar *domain_name = NULL;
1739
1740         if (!domain_name) {
1741                 gchar buf[128] = "";
1742                 struct hostent *hp;
1743
1744                 if (gethostname(buf, sizeof(buf)) < 0) {
1745                         perror("gethostname");
1746                         domain_name = "unknown";
1747                 } else {
1748                         buf[sizeof(buf) - 1] = '\0';
1749                         if ((hp = my_gethostbyname(buf)) == NULL) {
1750                                 perror("gethostbyname");
1751                                 domain_name = g_strdup(buf);
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(FILE *fp, off_t offset, size_t length, const gchar *dest)
2489 {
2490         FILE *dest_fp;
2491         gint n_read;
2492         gint bytes_left, to_read;
2493         gchar buf[BUFSIZ];
2494         gboolean err = FALSE;
2495
2496         if (fseek(fp, offset, SEEK_SET) < 0) {
2497                 perror("fseek");
2498                 return -1;
2499         }
2500
2501         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2502                 FILE_OP_ERROR(dest, "fopen");
2503                 return -1;
2504         }
2505
2506         if (change_file_mode_rw(dest_fp, dest) < 0) {
2507                 FILE_OP_ERROR(dest, "chmod");
2508                 g_warning("can't change file mode\n");
2509         }
2510
2511         bytes_left = length;
2512         to_read = MIN(bytes_left, sizeof(buf));
2513
2514         while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2515                 if (n_read < to_read && ferror(fp))
2516                         break;
2517                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2518                         g_warning("writing to %s failed.\n", dest);
2519                         fclose(dest_fp);
2520                         unlink(dest);
2521                         return -1;
2522                 }
2523                 bytes_left -= n_read;
2524                 if (bytes_left == 0)
2525                         break;
2526                 to_read = MIN(bytes_left, sizeof(buf));
2527         }
2528
2529         if (ferror(fp)) {
2530                 perror("fread");
2531                 err = TRUE;
2532         }
2533         if (fclose(dest_fp) == EOF) {
2534                 FILE_OP_ERROR(dest, "fclose");
2535                 err = TRUE;
2536         }
2537
2538         if (err) {
2539                 unlink(dest);
2540                 return -1;
2541         }
2542
2543         return 0;
2544 }
2545
2546 /* convert line endings into CRLF. If the last line doesn't end with
2547  * linebreak, add it.
2548  */
2549 gchar *canonicalize_str(const gchar *str)
2550 {
2551         const gchar *p;
2552         guint new_len = 0;
2553         gchar *out, *outp;
2554
2555         for (p = str; *p != '\0'; ++p) {
2556                 if (*p != '\r') {
2557                         ++new_len;
2558                         if (*p == '\n')
2559                                 ++new_len;
2560                 }
2561         }
2562         if (p == str || *(p - 1) != '\n')
2563                 new_len += 2;
2564
2565         out = outp = g_malloc(new_len + 1);
2566         for (p = str; *p != '\0'; ++p) {
2567                 if (*p != '\r') {
2568                         if (*p == '\n')
2569                                 *outp++ = '\r';
2570                         *outp++ = *p;
2571                 }
2572         }
2573         if (p == str || *(p - 1) != '\n') {
2574                 *outp++ = '\r';
2575                 *outp++ = '\n';
2576         }
2577         *outp = '\0';
2578
2579         return out;
2580 }
2581
2582 gint canonicalize_file(const gchar *src, const gchar *dest)
2583 {
2584         FILE *src_fp, *dest_fp;
2585         gchar buf[BUFFSIZE];
2586         gint len;
2587         gboolean err = FALSE;
2588         gboolean last_linebreak = FALSE;
2589
2590         if ((src_fp = fopen(src, "rb")) == NULL) {
2591                 FILE_OP_ERROR(src, "fopen");
2592                 return -1;
2593         }
2594
2595         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2596                 FILE_OP_ERROR(dest, "fopen");
2597                 fclose(src_fp);
2598                 return -1;
2599         }
2600
2601         if (change_file_mode_rw(dest_fp, dest) < 0) {
2602                 FILE_OP_ERROR(dest, "chmod");
2603                 g_warning("can't change file mode\n");
2604         }
2605
2606         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2607                 gint r = 0;
2608
2609                 len = strlen(buf);
2610                 if (len == 0) break;
2611                 last_linebreak = FALSE;
2612
2613                 if (buf[len - 1] != '\n') {
2614                         last_linebreak = TRUE;
2615                         r = fputs(buf, dest_fp);
2616                 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2617                         r = fputs(buf, dest_fp);
2618                 } else {
2619                         if (len > 1) {
2620                                 r = fwrite(buf, len - 1, 1, dest_fp);
2621                                 if (r != 1)
2622                                         r = EOF;
2623                         }
2624                         if (r != EOF)
2625                                 r = fputs("\r\n", dest_fp);
2626                 }
2627
2628                 if (r == EOF) {
2629                         g_warning("writing to %s failed.\n", dest);
2630                         fclose(dest_fp);
2631                         fclose(src_fp);
2632                         unlink(dest);
2633                         return -1;
2634                 }
2635         }
2636
2637         if (last_linebreak == TRUE) {
2638                 if (fputs("\r\n", dest_fp) == EOF)
2639                         err = TRUE;
2640         }
2641
2642         if (ferror(src_fp)) {
2643                 FILE_OP_ERROR(src, "fgets");
2644                 err = TRUE;
2645         }
2646         fclose(src_fp);
2647         if (fclose(dest_fp) == EOF) {
2648                 FILE_OP_ERROR(dest, "fclose");
2649                 err = TRUE;
2650         }
2651
2652         if (err) {
2653                 unlink(dest);
2654                 return -1;
2655         }
2656
2657         return 0;
2658 }
2659
2660 gint canonicalize_file_replace(const gchar *file)
2661 {
2662         gchar *tmp_file;
2663
2664         tmp_file = get_tmp_file();
2665
2666         if (canonicalize_file(file, tmp_file) < 0) {
2667                 g_free(tmp_file);
2668                 return -1;
2669         }
2670
2671         if (move_file(tmp_file, file, TRUE) < 0) {
2672                 g_warning("can't replace %s .\n", file);
2673                 unlink(tmp_file);
2674                 g_free(tmp_file);
2675                 return -1;
2676         }
2677
2678         g_free(tmp_file);
2679         return 0;
2680 }
2681
2682 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2683 {
2684         FILE *src_fp, *dest_fp;
2685         gchar buf[BUFFSIZE];
2686         gboolean err = FALSE;
2687
2688         if ((src_fp = fopen(src, "rb")) == NULL) {
2689                 FILE_OP_ERROR(src, "fopen");
2690                 return -1;
2691         }
2692
2693         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2694                 FILE_OP_ERROR(dest, "fopen");
2695                 fclose(src_fp);
2696                 return -1;
2697         }
2698
2699         if (change_file_mode_rw(dest_fp, dest) < 0) {
2700                 FILE_OP_ERROR(dest, "chmod");
2701                 g_warning("can't change file mode\n");
2702         }
2703
2704         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2705                 strcrchomp(buf);
2706                 if (fputs(buf, dest_fp) == EOF) {
2707                         g_warning("writing to %s failed.\n", dest);
2708                         fclose(dest_fp);
2709                         fclose(src_fp);
2710                         unlink(dest);
2711                         return -1;
2712                 }
2713         }
2714
2715         if (ferror(src_fp)) {
2716                 FILE_OP_ERROR(src, "fgets");
2717                 err = TRUE;
2718         }
2719         fclose(src_fp);
2720         if (fclose(dest_fp) == EOF) {
2721                 FILE_OP_ERROR(dest, "fclose");
2722                 err = TRUE;
2723         }
2724
2725         if (err) {
2726                 unlink(dest);
2727                 return -1;
2728         }
2729
2730         return 0;
2731 }
2732
2733 gint uncanonicalize_file_replace(const gchar *file)
2734 {
2735         gchar *tmp_file;
2736
2737         tmp_file = get_tmp_file();
2738
2739         if (uncanonicalize_file(file, tmp_file) < 0) {
2740                 g_free(tmp_file);
2741                 return -1;
2742         }
2743
2744         if (move_file(tmp_file, file, TRUE) < 0) {
2745                 g_warning("can't replace %s .\n", file);
2746                 unlink(tmp_file);
2747                 g_free(tmp_file);
2748                 return -1;
2749         }
2750
2751         g_free(tmp_file);
2752         return 0;
2753 }
2754
2755 gchar *normalize_newlines(const gchar *str)
2756 {
2757         const gchar *p = str;
2758         gchar *out, *outp;
2759
2760         out = outp = g_malloc(strlen(str) + 1);
2761         for (p = str; *p != '\0'; ++p) {
2762                 if (*p == '\r') {
2763                         if (*(p + 1) != '\n')
2764                                 *outp++ = '\n';
2765                 } else
2766                         *outp++ = *p;
2767         }
2768
2769         *outp = '\0';
2770
2771         return out;
2772 }
2773
2774 gchar *get_outgoing_rfc2822_str(FILE *fp)
2775 {
2776         gchar buf[BUFFSIZE];
2777         GString *str;
2778         gchar *ret;
2779
2780         str = g_string_new(NULL);
2781
2782         /* output header part */
2783         while (fgets(buf, sizeof(buf), fp) != NULL) {
2784                 strretchomp(buf);
2785                 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2786                         gint next;
2787
2788                         for (;;) {
2789                                 next = fgetc(fp);
2790                                 if (next == EOF)
2791                                         break;
2792                                 else if (next != ' ' && next != '\t') {
2793                                         ungetc(next, fp);
2794                                         break;
2795                                 }
2796                                 if (fgets(buf, sizeof(buf), fp) == NULL)
2797                                         break;
2798                         }
2799                 } else {
2800                         g_string_append(str, buf);
2801                         g_string_append(str, "\r\n");
2802                         if (buf[0] == '\0')
2803                                 break;
2804                 }
2805         }
2806
2807         /* output body part */
2808         while (fgets(buf, sizeof(buf), fp) != NULL) {
2809                 strretchomp(buf);
2810                 if (buf[0] == '.')
2811                         g_string_append_c(str, '.');
2812                 g_string_append(str, buf);
2813                 g_string_append(str, "\r\n");
2814         }
2815
2816         ret = str->str;
2817         g_string_free(str, FALSE);
2818
2819         return ret;
2820 }
2821
2822 /*
2823  * Create a new boundary in a way that it is very unlikely that this
2824  * will occur in the following text.  It would be easy to ensure
2825  * uniqueness if everything is either quoted-printable or base64
2826  * encoded (note that conversion is allowed), but because MIME bodies
2827  * may be nested, it may happen that the same boundary has already
2828  * been used. We avoid scanning the message for conflicts and hope the
2829  * best.
2830  *
2831  *   boundary := 0*69<bchars> bcharsnospace
2832  *   bchars := bcharsnospace / " "
2833  *   bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2834  *                    "+" / "_" / "," / "-" / "." /
2835  *                    "/" / ":" / "=" / "?"
2836  *
2837  * some special characters removed because of buggy MTAs
2838  */
2839
2840 gchar *generate_mime_boundary(const gchar *prefix)
2841 {
2842         static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2843                              "abcdefghijklmnopqrstuvwxyz"
2844                              "1234567890+_./=";
2845         gchar buf_uniq[17];
2846         gchar buf_date[64];
2847         gint i;
2848         gint pid;
2849
2850         pid = getpid();
2851
2852         /* We make the boundary depend on the pid, so that all running
2853          * processes generate different values even when they have been
2854          * started within the same second and srandom(time(NULL)) has been
2855          * used.  I can't see whether this is really an advantage but it
2856          * doesn't do any harm.
2857          */
2858         for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2859                 buf_uniq[i] = tbl[(random() ^ pid) % (sizeof(tbl) - 1)];
2860         buf_uniq[i] = '\0';
2861
2862         get_rfc822_date(buf_date, sizeof(buf_date));
2863         subst_char(buf_date, ' ', '_');
2864         subst_char(buf_date, ',', '_');
2865         subst_char(buf_date, ':', '_');
2866
2867         return g_strdup_printf("%s=_%s_%s", prefix ? prefix : "Multipart",
2868                                buf_date, buf_uniq);
2869 }
2870
2871 gint change_file_mode_rw(FILE *fp, const gchar *file)
2872 {
2873 #if HAVE_FCHMOD
2874         return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2875 #else
2876         return chmod(file, S_IRUSR|S_IWUSR);
2877 #endif
2878 }
2879
2880 FILE *my_tmpfile(void)
2881 {
2882 #if HAVE_MKSTEMP
2883         const gchar suffix[] = ".XXXXXX";
2884         const gchar *tmpdir;
2885         guint tmplen;
2886         const gchar *progname;
2887         guint proglen;
2888         gchar *fname;
2889         gint fd;
2890         FILE *fp;
2891
2892         tmpdir = get_tmp_dir();
2893         tmplen = strlen(tmpdir);
2894         progname = g_get_prgname();
2895         proglen = strlen(progname);
2896         Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2897                 return tmpfile());
2898
2899         memcpy(fname, tmpdir, tmplen);
2900         fname[tmplen] = G_DIR_SEPARATOR;
2901         memcpy(fname + tmplen + 1, progname, proglen);
2902         memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2903
2904         fd = mkstemp(fname);
2905         if (fd < 0)
2906                 return tmpfile();
2907
2908         unlink(fname);
2909
2910         fp = fdopen(fd, "w+b");
2911         if (!fp)
2912                 close(fd);
2913         else
2914                 return fp;
2915 #endif /* HAVE_MKSTEMP */
2916
2917         return tmpfile();
2918 }
2919
2920 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2921 {
2922         int fd;
2923         
2924         *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2925         fd = mkstemp(*filename);
2926
2927         return fdopen(fd, "w+");
2928 }
2929
2930 FILE *str_open_as_stream(const gchar *str)
2931 {
2932         FILE *fp;
2933         size_t len;
2934
2935         g_return_val_if_fail(str != NULL, NULL);
2936
2937         fp = my_tmpfile();
2938         if (!fp) {
2939                 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2940                 return NULL;
2941         }
2942
2943         len = strlen(str);
2944         if (len == 0) return fp;
2945
2946         if (fwrite(str, len, 1, fp) != 1) {
2947                 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2948                 fclose(fp);
2949                 return NULL;
2950         }
2951
2952         rewind(fp);
2953         return fp;
2954 }
2955
2956 gint str_write_to_file(const gchar *str, const gchar *file)
2957 {
2958         FILE *fp;
2959         size_t len;
2960
2961         g_return_val_if_fail(str != NULL, -1);
2962         g_return_val_if_fail(file != NULL, -1);
2963
2964         if ((fp = fopen(file, "wb")) == NULL) {
2965                 FILE_OP_ERROR(file, "fopen");
2966                 return -1;
2967         }
2968
2969         len = strlen(str);
2970         if (len == 0) {
2971                 fclose(fp);
2972                 return 0;
2973         }
2974
2975         if (fwrite(str, len, 1, fp) != 1) {
2976                 FILE_OP_ERROR(file, "fwrite");
2977                 fclose(fp);
2978                 unlink(file);
2979                 return -1;
2980         }
2981
2982         if (fclose(fp) == EOF) {
2983                 FILE_OP_ERROR(file, "fclose");
2984                 unlink(file);
2985                 return -1;
2986         }
2987
2988         return 0;
2989 }
2990
2991 gchar *file_read_to_str(const gchar *file)
2992 {
2993         FILE *fp;
2994         gchar *str;
2995
2996         g_return_val_if_fail(file != NULL, NULL);
2997
2998         if ((fp = fopen(file, "rb")) == NULL) {
2999                 FILE_OP_ERROR(file, "fopen");
3000                 return NULL;
3001         }
3002
3003         str = file_read_stream_to_str(fp);
3004
3005         fclose(fp);
3006
3007         return str;
3008 }
3009
3010 gchar *file_read_stream_to_str(FILE *fp)
3011 {
3012         GByteArray *array;
3013         gchar buf[BUFSIZ];
3014         gint n_read;
3015         gchar *str;
3016
3017         g_return_val_if_fail(fp != NULL, NULL);
3018
3019         array = g_byte_array_new();
3020
3021         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3022                 if (n_read < sizeof(buf) && ferror(fp))
3023                         break;
3024                 g_byte_array_append(array, buf, n_read);
3025         }
3026
3027         if (ferror(fp)) {
3028                 FILE_OP_ERROR("file stream", "fread");
3029                 g_byte_array_free(array, TRUE);
3030                 return NULL;
3031         }
3032
3033         buf[0] = '\0';
3034         g_byte_array_append(array, buf, 1);
3035         str = (gchar *)array->data;
3036         g_byte_array_free(array, FALSE);
3037
3038         if (!g_utf8_validate(str, -1, NULL)) {
3039                 const gchar *src_codeset, *dest_codeset;
3040                 gchar *tmp = NULL;
3041                 src_codeset = conv_get_current_charset_str();
3042                 dest_codeset = CS_UTF_8;
3043                 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3044                 g_free(str);
3045                 str = tmp;
3046         }
3047
3048         return str;
3049 }
3050
3051 gint execute_async(gchar *const argv[])
3052 {
3053         pid_t pid;
3054         gint status;
3055
3056         if ((pid = fork()) < 0) {
3057                 perror("fork");
3058                 return -1;
3059         }
3060
3061         if (pid == 0) {                 /* child process */
3062                 pid_t gch_pid;
3063
3064                 if ((gch_pid = fork()) < 0) {
3065                         perror("fork");
3066                         _exit(1);
3067                 }
3068
3069                 if (gch_pid == 0) {     /* grandchild process */
3070                         execvp(argv[0], argv);
3071
3072                         perror("execvp");
3073                         _exit(1);
3074                 }
3075
3076                 _exit(0);
3077         }
3078
3079         waitpid(pid, &status, 0);
3080
3081         if (WIFEXITED(status))
3082                 return WEXITSTATUS(status);
3083         else
3084                 return -1;
3085 }
3086
3087 gint execute_sync(gchar *const argv[])
3088 {
3089         pid_t pid;
3090         gint status;
3091
3092         if ((pid = fork()) < 0) {
3093                 perror("fork");
3094                 return -1;
3095         }
3096
3097         if (pid == 0) {         /* child process */
3098                 execvp(argv[0], argv);
3099
3100                 perror("execvp");
3101                 _exit(1);
3102         }
3103
3104         waitpid(pid, &status, 0);
3105
3106         if (WIFEXITED(status))
3107                 return WEXITSTATUS(status);
3108         else
3109                 return -1;
3110 }
3111
3112 gint execute_command_line(const gchar *cmdline, gboolean async)
3113 {
3114         gchar **argv;
3115         gint ret;
3116
3117         debug_print("executing: %s\n", cmdline);
3118
3119         argv = strsplit_with_quote(cmdline, " ", 0);
3120
3121         if (async)
3122                 ret = execute_async(argv);
3123         else
3124                 ret = execute_sync(argv);
3125
3126         g_strfreev(argv);
3127
3128         return ret;
3129 }
3130
3131 gchar *get_command_output(const gchar *cmdline)
3132 {
3133         gchar buf[BUFFSIZE];
3134         FILE *fp;
3135         GString *str;
3136         gchar *ret;
3137
3138         g_return_val_if_fail(cmdline != NULL, NULL);
3139
3140         if ((fp = popen(cmdline, "r")) == NULL) {
3141                 FILE_OP_ERROR(cmdline, "popen");
3142                 return NULL;
3143         }
3144
3145         str = g_string_new("");
3146
3147         while (fgets(buf, sizeof(buf), fp) != NULL)
3148                 g_string_append(str, buf);
3149
3150         pclose(fp);
3151
3152         ret = str->str;
3153         g_string_free(str, FALSE);
3154
3155         if (!g_utf8_validate(ret, -1, NULL)) {
3156                 const gchar *src_codeset, *dest_codeset;
3157                 gchar *tmp = NULL;
3158                 src_codeset = conv_get_current_charset_str();
3159                 dest_codeset = CS_UTF_8;
3160                 tmp = conv_codeset_strdup(ret, src_codeset, dest_codeset);
3161                 g_free(ret);
3162                 ret = tmp;
3163         }
3164         
3165         return ret;
3166 }
3167
3168 static gint is_unchanged_uri_char(char c)
3169 {
3170         switch (c) {
3171                 case '(':
3172                 case ')':
3173                 case ',':
3174                         return 0;
3175                 default:
3176                         return 1;
3177         }
3178 }
3179
3180 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3181 {
3182         int i;
3183         int k;
3184
3185         k = 0;
3186         for(i = 0; i < strlen(uri) ; i++) {
3187                 if (is_unchanged_uri_char(uri[i])) {
3188                         if (k + 2 >= bufsize)
3189                                 break;
3190                         encoded_uri[k++] = uri[i];
3191                 }
3192                 else {
3193                         char * hexa = "0123456789ABCDEF";
3194                         
3195                         if (k + 4 >= bufsize)
3196                                 break;
3197                         encoded_uri[k++] = '%';
3198                         encoded_uri[k++] = hexa[uri[i] / 16];
3199                         encoded_uri[k++] = hexa[uri[i] % 16];
3200                 }
3201         }
3202         encoded_uri[k] = 0;
3203 }
3204
3205 gint open_uri(const gchar *uri, const gchar *cmdline)
3206 {
3207         gchar buf[BUFFSIZE];
3208         gchar *p;
3209         gchar encoded_uri[BUFFSIZE];
3210         
3211         g_return_val_if_fail(uri != NULL, -1);
3212
3213         /* an option to choose whether to use encode_uri or not ? */
3214         encode_uri(encoded_uri, BUFFSIZE, uri);
3215         
3216         if (cmdline &&
3217             (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3218             !strchr(p + 2, '%'))
3219                 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3220         else {
3221                 if (cmdline)
3222                         g_warning("Open URI command line is invalid "
3223                                   "(there must be only one '%%s'): %s",
3224                                   cmdline);
3225                 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3226         }
3227
3228         execute_command_line(buf, TRUE);
3229
3230         return 0;
3231 }
3232
3233 time_t remote_tzoffset_sec(const gchar *zone)
3234 {
3235         static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3236         gchar zone3[4];
3237         gchar *p;
3238         gchar c;
3239         gint iustz;
3240         gint offset;
3241         time_t remoteoffset;
3242
3243         strncpy(zone3, zone, 3);
3244         zone3[3] = '\0';
3245         remoteoffset = 0;
3246
3247         if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3248             (c == '+' || c == '-')) {
3249                 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3250                 if (c == '-')
3251                         remoteoffset = -remoteoffset;
3252         } else if (!strncmp(zone, "UT" , 2) ||
3253                    !strncmp(zone, "GMT", 2)) {
3254                 remoteoffset = 0;
3255         } else if (strlen(zone3) == 3) {
3256                 for (p = ustzstr; *p != '\0'; p += 3) {
3257                         if (!strncasecmp(p, zone3, 3)) {
3258                                 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3259                                 remoteoffset = iustz * 3600;
3260                                 break;
3261                         }
3262                 }
3263                 if (*p == '\0')
3264                         return -1;
3265         } else if (strlen(zone3) == 1) {
3266                 switch (zone[0]) {
3267                 case 'Z': remoteoffset =   0; break;
3268                 case 'A': remoteoffset =  -1; break;
3269                 case 'B': remoteoffset =  -2; break;
3270                 case 'C': remoteoffset =  -3; break;
3271                 case 'D': remoteoffset =  -4; break;
3272                 case 'E': remoteoffset =  -5; break;
3273                 case 'F': remoteoffset =  -6; break;
3274                 case 'G': remoteoffset =  -7; break;
3275                 case 'H': remoteoffset =  -8; break;
3276                 case 'I': remoteoffset =  -9; break;
3277                 case 'K': remoteoffset = -10; break; /* J is not used */
3278                 case 'L': remoteoffset = -11; break;
3279                 case 'M': remoteoffset = -12; break;
3280                 case 'N': remoteoffset =   1; break;
3281                 case 'O': remoteoffset =   2; break;
3282                 case 'P': remoteoffset =   3; break;
3283                 case 'Q': remoteoffset =   4; break;
3284                 case 'R': remoteoffset =   5; break;
3285                 case 'S': remoteoffset =   6; break;
3286                 case 'T': remoteoffset =   7; break;
3287                 case 'U': remoteoffset =   8; break;
3288                 case 'V': remoteoffset =   9; break;
3289                 case 'W': remoteoffset =  10; break;
3290                 case 'X': remoteoffset =  11; break;
3291                 case 'Y': remoteoffset =  12; break;
3292                 default:  remoteoffset =   0; break;
3293                 }
3294                 remoteoffset = remoteoffset * 3600;
3295         } else
3296                 return -1;
3297
3298         return remoteoffset;
3299 }
3300
3301 time_t tzoffset_sec(time_t *now)
3302 {
3303         struct tm gmt, *lt;
3304         gint off;
3305
3306         gmt = *gmtime(now);
3307         lt = localtime(now);
3308
3309         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3310
3311         if (lt->tm_year < gmt.tm_year)
3312                 off -= 24 * 60;
3313         else if (lt->tm_year > gmt.tm_year)
3314                 off += 24 * 60;
3315         else if (lt->tm_yday < gmt.tm_yday)
3316                 off -= 24 * 60;
3317         else if (lt->tm_yday > gmt.tm_yday)
3318                 off += 24 * 60;
3319
3320         if (off >= 24 * 60)             /* should be impossible */
3321                 off = 23 * 60 + 59;     /* if not, insert silly value */
3322         if (off <= -24 * 60)
3323                 off = -(23 * 60 + 59);
3324
3325         return off * 60;
3326 }
3327
3328 /* calculate timezone offset */
3329 gchar *tzoffset(time_t *now)
3330 {
3331         static gchar offset_string[6];
3332         struct tm gmt, *lt;
3333         gint off;
3334         gchar sign = '+';
3335
3336         gmt = *gmtime(now);
3337         lt = localtime(now);
3338
3339         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3340
3341         if (lt->tm_year < gmt.tm_year)
3342                 off -= 24 * 60;
3343         else if (lt->tm_year > gmt.tm_year)
3344                 off += 24 * 60;
3345         else if (lt->tm_yday < gmt.tm_yday)
3346                 off -= 24 * 60;
3347         else if (lt->tm_yday > gmt.tm_yday)
3348                 off += 24 * 60;
3349
3350         if (off < 0) {
3351                 sign = '-';
3352                 off = -off;
3353         }
3354
3355         if (off >= 24 * 60)             /* should be impossible */
3356                 off = 23 * 60 + 59;     /* if not, insert silly value */
3357
3358         sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3359
3360         return offset_string;
3361 }
3362
3363 void get_rfc822_date(gchar *buf, gint len)
3364 {
3365         struct tm *lt;
3366         time_t t;
3367         gchar day[4], mon[4];
3368         gint dd, hh, mm, ss, yyyy;
3369
3370         t = time(NULL);
3371         lt = localtime(&t);
3372
3373         sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3374                day, mon, &dd, &hh, &mm, &ss, &yyyy);
3375         g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3376                    day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3377 }
3378
3379 void debug_set_mode(gboolean mode)
3380 {
3381         debug_mode = mode;
3382 }
3383
3384 gboolean debug_get_mode(void)
3385 {
3386         return debug_mode;
3387 }
3388
3389 void debug_print_real(const gchar *format, ...)
3390 {
3391         va_list args;
3392         gchar buf[BUFFSIZE];
3393
3394         if (!debug_mode) return;
3395
3396         va_start(args, format);
3397         g_vsnprintf(buf, sizeof(buf), format, args);
3398         va_end(args);
3399
3400         fputs(buf, stdout);
3401 }
3402
3403 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3404 {
3405         if (subject == NULL)
3406                 subject = "";
3407         else
3408                 subject += subject_get_prefix_length(subject);
3409
3410         return g_hash_table_lookup(subject_table, subject);
3411 }
3412
3413 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3414                           void * data)
3415 {
3416         if (subject == NULL || *subject == 0)
3417                 return;
3418         subject += subject_get_prefix_length(subject);
3419         g_hash_table_insert(subject_table, subject, data);
3420 }
3421
3422 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3423 {
3424         if (subject == NULL)
3425                 return;
3426
3427         subject += subject_get_prefix_length(subject);  
3428         g_hash_table_remove(subject_table, subject);
3429 }
3430
3431 /*!
3432  *\brief        Check if a string is prefixed with known (combinations) 
3433  *              of prefixes. The function assumes that each prefix 
3434  *              is terminated by zero or exactly _one_ space.
3435  *
3436  *\param        str String to check for a prefixes
3437  *
3438  *\return       int Number of chars in the prefix that should be skipped 
3439  *              for a "clean" subject line. If no prefix was found, 0
3440  *              is returned.
3441  */             
3442 int subject_get_prefix_length(const gchar *subject)
3443 {
3444         /*!< Array with allowable reply prefixes regexps. */
3445         static const gchar * const prefixes[] = {
3446                 "Re\\:",                        /* "Re:" */
3447                 "Re\\[[1-9][0-9]*\\]\\:",       /* "Re[XXX]:" (non-conforming news mail clients) */
3448                 "Antw\\:",                      /* "Antw:" (Dutch / German Outlook) */
3449                 "Aw\\:",                        /* "Aw:"   (German) */
3450                 "Antwort\\:",                   /* "Antwort:" (German Lotus Notes) */
3451                 "Res\\:",                       /* "Res:" (Brazilian Outlook) */
3452                 "Fw\\:",                        /* "Fw:" Forward */
3453                 "Enc\\:",                       /* "Enc:" Forward (Brazilian Outlook) */
3454                 "Odp\\:",                       /* "Odp:" Re (Polish Outlook) */
3455                 "Rif\\:"                        /* "Rif:" (Italian Outlook) */
3456                 /* add more */
3457         };
3458         const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3459         int n;
3460         regmatch_t pos;
3461         static regex_t regex;
3462         static gboolean init_;
3463
3464         if (!subject) return 0;
3465         if (!*subject) return 0;
3466
3467         if (!init_) {
3468                 GString *s = g_string_new("");
3469                 
3470                 for (n = 0; n < PREFIXES; n++)
3471                         /* Terminate each prefix regexpression by a
3472                          * "\ ?" (zero or ONE space), and OR them */
3473                         g_string_sprintfa(s, "(%s\\ ?)%s",
3474                                           prefixes[n],
3475                                           n < PREFIXES - 1 ? 
3476                                           "|" : "");
3477                 
3478                 g_string_prepend(s, "(");
3479                 g_string_append(s, ")+");       /* match at least once */
3480                 g_string_prepend(s, "^\\ *");   /* from beginning of line */
3481                 
3482
3483                 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+" 
3484                  * TODO: Should this be       "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3485                 if (regcomp(&regex, s->str, REG_EXTENDED | REG_ICASE)) { 
3486                         debug_print("Error compiling regexp %s\n", s->str);
3487                         g_string_free(s, TRUE);
3488                         return 0;
3489                 } else {
3490                         init_ = TRUE;
3491                         g_string_free(s, TRUE);
3492                 }
3493         }
3494         
3495         if (!regexec(&regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3496                 return pos.rm_eo;
3497         else
3498                 return 0;
3499 }
3500
3501 guint g_stricase_hash(gconstpointer gptr)
3502 {
3503         guint hash_result = 0;
3504         const char *str;
3505
3506         for (str = gptr; str && *str; str++) {
3507                 if (isupper((guchar)*str)) hash_result += (*str + ' ');
3508                 else hash_result += *str;
3509         }
3510
3511         return hash_result;
3512 }
3513
3514 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3515 {
3516         const char *str1 = gptr1;
3517         const char *str2 = gptr2;
3518
3519         return !strcasecmp(str1, str2);
3520 }
3521
3522 gint g_int_compare(gconstpointer a, gconstpointer b)
3523 {
3524         return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3525 }
3526
3527 gchar *generate_msgid(const gchar *address, gchar *buf, gint len)
3528 {
3529         /* steal from compose.c::compose_generate_msgid() */
3530         struct tm *lt;
3531         time_t t;
3532         gchar *addr;
3533
3534         t = time(NULL);
3535         lt = localtime(&t);
3536
3537         if (address && *address) {
3538                 if (strchr(address, '@'))
3539                         addr = g_strdup(address);
3540                 else
3541                         addr = g_strconcat(address, "@", get_domain_name(), NULL);
3542         } else
3543                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3544                                    NULL);
3545
3546         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3547                    lt->tm_year + 1900, lt->tm_mon + 1,
3548                    lt->tm_mday, lt->tm_hour,
3549                    lt->tm_min, lt->tm_sec,
3550                    (guint)random(), addr);
3551
3552         g_free(addr);
3553         return buf;
3554 }
3555
3556
3557 /*
3558    quote_cmd_argument()
3559    
3560    return a quoted string safely usable in argument of a command.
3561    
3562    code is extracted and adapted from etPan! project -- DINH V. HoĆ .
3563 */
3564
3565 gint quote_cmd_argument(gchar * result, guint size,
3566                         const gchar * path)
3567 {
3568         const gchar * p;
3569         gchar * result_p;
3570         guint remaining;
3571
3572         result_p = result;
3573         remaining = size;
3574
3575         for(p = path ; * p != '\0' ; p ++) {
3576
3577                 if (isalnum((guchar)*p) || (* p == '/')) {
3578                         if (remaining > 0) {
3579                                 * result_p = * p;
3580                                 result_p ++; 
3581                                 remaining --;
3582                         }
3583                         else {
3584                                 result[size - 1] = '\0';
3585                                 return -1;
3586                         }
3587                 }
3588                 else { 
3589                         if (remaining >= 2) {
3590                                 * result_p = '\\';
3591                                 result_p ++; 
3592                                 * result_p = * p;
3593                                 result_p ++; 
3594                                 remaining -= 2;
3595                         }
3596                         else {
3597                                 result[size - 1] = '\0';
3598                                 return -1;
3599                         }
3600                 }
3601         }
3602         if (remaining > 0) {
3603                 * result_p = '\0';
3604         }
3605         else {
3606                 result[size - 1] = '\0';
3607                 return -1;
3608         }
3609   
3610         return 0;
3611 }
3612
3613 typedef struct 
3614 {
3615         GNode           *parent;
3616         GNodeMapFunc     func;
3617         gpointer         data;
3618 } GNodeMapData;
3619
3620 static void g_node_map_recursive(GNode *node, gpointer data)
3621 {
3622         GNodeMapData *mapdata = (GNodeMapData *) data;
3623         GNode *newnode;
3624         GNodeMapData newmapdata;
3625         gpointer newdata;
3626
3627         newdata = mapdata->func(node->data, mapdata->data);
3628         if (newdata != NULL) {
3629                 newnode = g_node_new(newdata);
3630                 g_node_append(mapdata->parent, newnode);
3631
3632                 newmapdata.parent = newnode;
3633                 newmapdata.func = mapdata->func;
3634                 newmapdata.data = mapdata->data;
3635
3636                 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3637         }
3638 }
3639
3640 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3641 {
3642         GNode *root;
3643         GNodeMapData mapdata;
3644
3645         g_return_val_if_fail(node != NULL, NULL);
3646         g_return_val_if_fail(func != NULL, NULL);
3647
3648         root = g_node_new(func(node->data, data));
3649
3650         mapdata.parent = root;
3651         mapdata.func = func;
3652         mapdata.data = data;
3653
3654         g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3655
3656         return root;
3657 }