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