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