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