6cb5dca20e3c7712ec31f0a5d19e35aa8048cd84
[claws.git] / src / common / utils.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2003 Hiroyuki Yamamoto
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 gchar *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 gchar *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         gchar *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         gchar *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 gchar *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 gchar *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 gchar *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 gchar *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 gchar *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 gchar *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 gchar *first_pos;
1079         const gchar *last_pos;
1080         const gchar *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 - 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(*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 gchar *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 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1447                      gchar **subject, gchar **body)
1448 {
1449         gchar *tmp_mailto;
1450         gchar *p;
1451
1452         Xstrdup_a(tmp_mailto, mailto, return -1);
1453
1454         if (!strncmp(tmp_mailto, "mailto:", 7))
1455                 tmp_mailto += 7;
1456
1457         p = strchr(tmp_mailto, '?');
1458         if (p) {
1459                 *p = '\0';
1460                 p++;
1461         }
1462
1463         if (to && !*to)
1464                 *to = g_strdup(tmp_mailto);
1465
1466         while (p) {
1467                 gchar *field, *value;
1468
1469                 field = p;
1470
1471                 p = strchr(p, '=');
1472                 if (!p) break;
1473                 *p = '\0';
1474                 p++;
1475
1476                 value = p;
1477
1478                 p = strchr(p, '&');
1479                 if (p) {
1480                         *p = '\0';
1481                         p++;
1482                 }
1483
1484                 if (*value == '\0') continue;
1485
1486                 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1487                         *cc = g_strdup(value);
1488                 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1489                         *bcc = g_strdup(value);
1490                 } else if (subject && !*subject &&
1491                            !g_strcasecmp(field, "subject")) {
1492                         *subject = g_malloc(strlen(value) + 1);
1493                         decode_uri(*subject, value);
1494                 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1495                         *body = g_malloc(strlen(value) + 1);
1496                         decode_uri(*body, value);
1497                 }
1498         }
1499
1500         return 0;
1501 }
1502
1503 /*
1504  * We need this wrapper around g_get_home_dir(), so that
1505  * we can fix some Windoze things here.  Should be done in glibc of course
1506  * but as long as we are not able to do our own extensions to glibc, we do
1507  * it here.
1508  */
1509 gchar *get_home_dir(void)
1510 {
1511 #if HAVE_DOSISH_SYSTEM
1512     static gchar *home_dir;
1513
1514     if (!home_dir) {
1515         home_dir = read_w32_registry_string(NULL,
1516                                             "Software\\Sylpheed", "HomeDir" );
1517         if (!home_dir || !*home_dir) {
1518             if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1519                 const char *s = g_get_home_dir();
1520                 if (s && *s)
1521                     home_dir = g_strdup (s);
1522             }
1523             if (!home_dir || !*home_dir) 
1524                 home_dir = g_strdup ("c:\\sylpheed");
1525         }
1526         debug_print("initialized home_dir to `%s'\n", home_dir);
1527     }
1528     return home_dir;
1529 #else /* standard glib */
1530     return g_get_home_dir();
1531 #endif
1532 }
1533
1534 gchar *get_rc_dir(void)
1535 {
1536         static gchar *rc_dir = NULL;
1537
1538         if (!rc_dir)
1539                 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1540                                      RC_DIR, NULL);
1541
1542         return rc_dir;
1543 }
1544
1545 gchar *get_news_cache_dir(void)
1546 {
1547         static gchar *news_cache_dir = NULL;
1548
1549         if (!news_cache_dir)
1550                 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1551                                              NEWS_CACHE_DIR, NULL);
1552
1553         return news_cache_dir;
1554 }
1555
1556 gchar *get_imap_cache_dir(void)
1557 {
1558         static gchar *imap_cache_dir = NULL;
1559
1560         if (!imap_cache_dir)
1561                 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1562                                              IMAP_CACHE_DIR, NULL);
1563
1564         return imap_cache_dir;
1565 }
1566
1567 gchar *get_mbox_cache_dir(void)
1568 {
1569         static gchar *mbox_cache_dir = NULL;
1570
1571         if (!mbox_cache_dir)
1572                 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1573                                              MBOX_CACHE_DIR, NULL);
1574
1575         return mbox_cache_dir;
1576 }
1577
1578 gchar *get_mime_tmp_dir(void)
1579 {
1580         static gchar *mime_tmp_dir = NULL;
1581
1582         if (!mime_tmp_dir)
1583                 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1584                                            MIME_TMP_DIR, NULL);
1585
1586         return mime_tmp_dir;
1587 }
1588
1589 gchar *get_template_dir(void)
1590 {
1591         static gchar *template_dir = NULL;
1592
1593         if (!template_dir)
1594                 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1595                                            TEMPLATE_DIR, NULL);
1596
1597         return template_dir;
1598 }
1599
1600 gchar *get_header_cache_dir(void)
1601 {
1602         static gchar *header_dir = NULL;
1603
1604         if (!header_dir)
1605                 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1606                                          HEADER_CACHE_DIR, NULL);
1607
1608         return header_dir;
1609 }
1610
1611 gchar *get_tmp_dir(void)
1612 {
1613         static gchar *tmp_dir = NULL;
1614
1615         if (!tmp_dir)
1616                 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1617                                       TMP_DIR, NULL);
1618
1619         return tmp_dir;
1620 }
1621
1622 gchar *get_tmp_file(void)
1623 {
1624         gchar *tmp_file;
1625         static guint32 id = 0;
1626
1627         tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1628                                    get_tmp_dir(), G_DIR_SEPARATOR, id++);
1629
1630         return tmp_file;
1631 }
1632
1633 gchar *get_domain_name(void)
1634 {
1635         static gchar *domain_name = NULL;
1636
1637         if (!domain_name) {
1638                 gchar buf[128] = "";
1639                 struct hostent *hp;
1640
1641                 if (gethostname(buf, sizeof(buf)) < 0) {
1642                         perror("gethostname");
1643                         domain_name = "unknown";
1644                 } else {
1645                         buf[sizeof(buf) - 1] = '\0';
1646                         if ((hp = my_gethostbyname(buf)) == NULL) {
1647                                 perror("gethostbyname");
1648                                 domain_name = g_strdup(buf);
1649                         } else {
1650                                 domain_name = g_strdup(hp->h_name);
1651                         }
1652                 }
1653
1654                 debug_print("domain name = %s\n", domain_name);
1655         }
1656
1657         return domain_name;
1658 }
1659
1660 off_t get_file_size(const gchar *file)
1661 {
1662         struct stat s;
1663
1664         if (stat(file, &s) < 0) {
1665                 FILE_OP_ERROR(file, "stat");
1666                 return -1;
1667         }
1668
1669         return s.st_size;
1670 }
1671
1672 off_t get_file_size_as_crlf(const gchar *file)
1673 {
1674         FILE *fp;
1675         off_t size = 0;
1676         gchar buf[BUFFSIZE];
1677
1678         if ((fp = fopen(file, "rb")) == NULL) {
1679                 FILE_OP_ERROR(file, "fopen");
1680                 return -1;
1681         }
1682
1683         while (fgets(buf, sizeof(buf), fp) != NULL) {
1684                 strretchomp(buf);
1685                 size += strlen(buf) + 2;
1686         }
1687
1688         if (ferror(fp)) {
1689                 FILE_OP_ERROR(file, "fgets");
1690                 size = -1;
1691         }
1692
1693         fclose(fp);
1694
1695         return size;
1696 }
1697
1698 off_t get_left_file_size(FILE *fp)
1699 {
1700         glong pos;
1701         glong end;
1702         off_t size;
1703
1704         if ((pos = ftell(fp)) < 0) {
1705                 perror("ftell");
1706                 return -1;
1707         }
1708         if (fseek(fp, 0L, SEEK_END) < 0) {
1709                 perror("fseek");
1710                 return -1;
1711         }
1712         if ((end = ftell(fp)) < 0) {
1713                 perror("fseek");
1714                 return -1;
1715         }
1716         size = end - pos;
1717         if (fseek(fp, pos, SEEK_SET) < 0) {
1718                 perror("fseek");
1719                 return -1;
1720         }
1721
1722         return size;
1723 }
1724
1725 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1726 {
1727         struct stat s;
1728
1729         if (file == NULL)
1730                 return FALSE;
1731
1732         if (stat(file, &s) < 0) {
1733                 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1734                 return FALSE;
1735         }
1736
1737         if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1738                 return TRUE;
1739
1740         return FALSE;
1741 }
1742
1743 gboolean is_dir_exist(const gchar *dir)
1744 {
1745         struct stat s;
1746
1747         if (dir == NULL)
1748                 return FALSE;
1749
1750         if (stat(dir, &s) < 0) {
1751                 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1752                 return FALSE;
1753         }
1754
1755         if (S_ISDIR(s.st_mode))
1756                 return TRUE;
1757
1758         return FALSE;
1759 }
1760
1761 gboolean is_file_entry_exist(const gchar *file)
1762 {
1763         struct stat s;
1764
1765         if (file == NULL)
1766                 return FALSE;
1767
1768         if (stat(file, &s) < 0) {
1769                 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1770                 return FALSE;
1771         }
1772
1773         return TRUE;
1774 }
1775
1776 gboolean dirent_is_regular_file(struct dirent *d)
1777 {
1778         struct stat s;
1779
1780 #ifdef HAVE_DIRENT_D_TYPE
1781         if (d->d_type == DT_REG)
1782                 return TRUE;
1783         else if (d->d_type != DT_UNKNOWN)
1784                 return FALSE;
1785 #endif
1786
1787         return (stat(d->d_name, &s) == 0 && S_ISREG(s.st_mode));
1788 }
1789
1790 gboolean dirent_is_directory(struct dirent *d)
1791 {
1792         struct stat s;
1793
1794 #ifdef HAVE_DIRENT_D_TYPE
1795         if (d->d_type == DT_DIR)
1796                 return TRUE;
1797         else if (d->d_type != DT_UNKNOWN)
1798                 return FALSE;
1799 #endif
1800
1801         return (stat(d->d_name, &s) == 0 && S_ISDIR(s.st_mode));
1802 }
1803
1804 gint change_dir(const gchar *dir)
1805 {
1806         gchar *prevdir = NULL;
1807
1808         if (debug_mode)
1809                 prevdir = g_get_current_dir();
1810
1811         if (chdir(dir) < 0) {
1812                 FILE_OP_ERROR(dir, "chdir");
1813                 if (debug_mode) g_free(prevdir);
1814                 return -1;
1815         } else if (debug_mode) {
1816                 gchar *cwd;
1817
1818                 cwd = g_get_current_dir();
1819                 if (strcmp(prevdir, cwd) != 0)
1820                         g_print("current dir: %s\n", cwd);
1821                 g_free(cwd);
1822                 g_free(prevdir);
1823         }
1824
1825         return 0;
1826 }
1827
1828 gint make_dir(const gchar *dir)
1829 {
1830         if (mkdir(dir, S_IRWXU) < 0) {
1831                 FILE_OP_ERROR(dir, "mkdir");
1832                 return -1;
1833         }
1834         if (chmod(dir, S_IRWXU) < 0)
1835                 FILE_OP_ERROR(dir, "chmod");
1836
1837         return 0;
1838 }
1839
1840 gint make_dir_hier(const gchar *dir)
1841 {
1842         gchar *parent_dir;
1843         const gchar *p;
1844
1845         for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1846                 parent_dir = g_strndup(dir, p - dir);
1847                 if (*parent_dir != '\0') {
1848                         if (!is_dir_exist(parent_dir)) {
1849                                 if (make_dir(parent_dir) < 0) {
1850                                         g_free(parent_dir);
1851                                         return -1;
1852                                 }
1853                         }
1854                 }
1855                 g_free(parent_dir);
1856         }
1857
1858         if (!is_dir_exist(dir)) {
1859                 if (make_dir(dir) < 0)
1860                         return -1;
1861         }
1862
1863         return 0;
1864 }
1865
1866 gint remove_all_files(const gchar *dir)
1867 {
1868         DIR *dp;
1869         struct dirent *d;
1870         gchar *prev_dir;
1871
1872         prev_dir = g_get_current_dir();
1873
1874         if (chdir(dir) < 0) {
1875                 FILE_OP_ERROR(dir, "chdir");
1876                 g_free(prev_dir);
1877                 return -1;
1878         }
1879
1880         if ((dp = opendir(".")) == NULL) {
1881                 FILE_OP_ERROR(dir, "opendir");
1882                 g_free(prev_dir);
1883                 return -1;
1884         }
1885
1886         while ((d = readdir(dp)) != NULL) {
1887                 if (!strcmp(d->d_name, ".") ||
1888                     !strcmp(d->d_name, ".."))
1889                         continue;
1890
1891                 if (unlink(d->d_name) < 0)
1892                         FILE_OP_ERROR(d->d_name, "unlink");
1893         }
1894
1895         closedir(dp);
1896
1897         if (chdir(prev_dir) < 0) {
1898                 FILE_OP_ERROR(prev_dir, "chdir");
1899                 g_free(prev_dir);
1900                 return -1;
1901         }
1902
1903         g_free(prev_dir);
1904
1905         return 0;
1906 }
1907
1908 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1909 {
1910         DIR *dp;
1911         struct dirent *d;
1912         gchar *prev_dir;
1913         gint fileno;
1914
1915         prev_dir = g_get_current_dir();
1916
1917         if (chdir(dir) < 0) {
1918                 FILE_OP_ERROR(dir, "chdir");
1919                 g_free(prev_dir);
1920                 return -1;
1921         }
1922
1923         if ((dp = opendir(".")) == NULL) {
1924                 FILE_OP_ERROR(dir, "opendir");
1925                 g_free(prev_dir);
1926                 return -1;
1927         }
1928
1929         while ((d = readdir(dp)) != NULL) {
1930                 fileno = to_number(d->d_name);
1931                 if (fileno >= 0 && first <= fileno && fileno <= last) {
1932                         if (is_dir_exist(d->d_name))
1933                                 continue;
1934                         if (unlink(d->d_name) < 0)
1935                                 FILE_OP_ERROR(d->d_name, "unlink");
1936                 }
1937         }
1938
1939         closedir(dp);
1940
1941         if (chdir(prev_dir) < 0) {
1942                 FILE_OP_ERROR(prev_dir, "chdir");
1943                 g_free(prev_dir);
1944                 return -1;
1945         }
1946
1947         g_free(prev_dir);
1948
1949         return 0;
1950 }
1951
1952 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1953 {
1954         DIR *dp;
1955         struct dirent *d;
1956         gchar *prev_dir;
1957         gint fileno;
1958
1959         prev_dir = g_get_current_dir();
1960
1961         if (chdir(dir) < 0) {
1962                 FILE_OP_ERROR(dir, "chdir");
1963                 g_free(prev_dir);
1964                 return -1;
1965         }
1966
1967         if ((dp = opendir(".")) == NULL) {
1968                 FILE_OP_ERROR(dir, "opendir");
1969                 g_free(prev_dir);
1970                 return -1;
1971         }
1972
1973         while ((d = readdir(dp)) != NULL) {
1974                 fileno = to_number(d->d_name);
1975                 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1976                         debug_print("removing unwanted file %d from %s\n", fileno, dir);
1977                         if (is_dir_exist(d->d_name))
1978                                 continue;
1979                         if (unlink(d->d_name) < 0)
1980                                 FILE_OP_ERROR(d->d_name, "unlink");
1981                 }
1982         }
1983
1984         closedir(dp);
1985
1986         if (chdir(prev_dir) < 0) {
1987                 FILE_OP_ERROR(prev_dir, "chdir");
1988                 g_free(prev_dir);
1989                 return -1;
1990         }
1991
1992         g_free(prev_dir);
1993
1994         return 0;
1995 }
1996
1997 gint remove_all_numbered_files(const gchar *dir)
1998 {
1999         return remove_numbered_files(dir, 0, UINT_MAX);
2000 }
2001
2002 gint remove_expired_files(const gchar *dir, guint hours)
2003 {
2004         DIR *dp;
2005         struct dirent *d;
2006         struct stat s;
2007         gchar *prev_dir;
2008         gint fileno;
2009         time_t mtime, now, expire_time;
2010
2011         prev_dir = g_get_current_dir();
2012
2013         if (chdir(dir) < 0) {
2014                 FILE_OP_ERROR(dir, "chdir");
2015                 g_free(prev_dir);
2016                 return -1;
2017         }
2018
2019         if ((dp = opendir(".")) == NULL) {
2020                 FILE_OP_ERROR(dir, "opendir");
2021                 g_free(prev_dir);
2022                 return -1;
2023         }
2024
2025         now = time(NULL);
2026         expire_time = hours * 60 * 60;
2027
2028         while ((d = readdir(dp)) != NULL) {
2029                 fileno = to_number(d->d_name);
2030                 if (fileno >= 0) {
2031                         if (stat(d->d_name, &s) < 0) {
2032                                 FILE_OP_ERROR(d->d_name, "stat");
2033                                 continue;
2034                         }
2035                         if (S_ISDIR(s.st_mode))
2036                                 continue;
2037                         mtime = MAX(s.st_mtime, s.st_atime);
2038                         if (now - mtime > expire_time) {
2039                                 if (unlink(d->d_name) < 0)
2040                                         FILE_OP_ERROR(d->d_name, "unlink");
2041                         }
2042                 }
2043         }
2044
2045         closedir(dp);
2046
2047         if (chdir(prev_dir) < 0) {
2048                 FILE_OP_ERROR(prev_dir, "chdir");
2049                 g_free(prev_dir);
2050                 return -1;
2051         }
2052
2053         g_free(prev_dir);
2054
2055         return 0;
2056 }
2057
2058 gint remove_dir_recursive(const gchar *dir)
2059 {
2060         struct stat s;
2061         DIR *dp;
2062         struct dirent *d;
2063         gchar *prev_dir;
2064
2065         /* g_print("dir = %s\n", dir); */
2066
2067         if (stat(dir, &s) < 0) {
2068                 FILE_OP_ERROR(dir, "stat");
2069                 if (ENOENT == errno) return 0;
2070                 return -1;
2071         }
2072
2073         if (!S_ISDIR(s.st_mode)) {
2074                 if (unlink(dir) < 0) {
2075                         FILE_OP_ERROR(dir, "unlink");
2076                         return -1;
2077                 }
2078
2079                 return 0;
2080         }
2081
2082         prev_dir = g_get_current_dir();
2083         /* g_print("prev_dir = %s\n", prev_dir); */
2084
2085         if (!path_cmp(prev_dir, dir)) {
2086                 g_free(prev_dir);
2087                 if (chdir("..") < 0) {
2088                         FILE_OP_ERROR(dir, "chdir");
2089                         return -1;
2090                 }
2091                 prev_dir = g_get_current_dir();
2092         }
2093
2094         if (chdir(dir) < 0) {
2095                 FILE_OP_ERROR(dir, "chdir");
2096                 g_free(prev_dir);
2097                 return -1;
2098         }
2099
2100         if ((dp = opendir(".")) == NULL) {
2101                 FILE_OP_ERROR(dir, "opendir");
2102                 chdir(prev_dir);
2103                 g_free(prev_dir);
2104                 return -1;
2105         }
2106
2107         /* remove all files in the directory */
2108         while ((d = readdir(dp)) != NULL) {
2109                 if (!strcmp(d->d_name, ".") ||
2110                     !strcmp(d->d_name, ".."))
2111                         continue;
2112
2113                 /* g_print("removing %s\n", d->d_name); */
2114
2115                 if (dirent_is_directory(d)) {
2116                         if (remove_dir_recursive(d->d_name) < 0) {
2117                                 g_warning("can't remove directory\n");
2118                                 return -1;
2119                         }
2120                 } else {
2121                         if (unlink(d->d_name) < 0)
2122                                 FILE_OP_ERROR(d->d_name, "unlink");
2123                 }
2124         }
2125
2126         closedir(dp);
2127
2128         if (chdir(prev_dir) < 0) {
2129                 FILE_OP_ERROR(prev_dir, "chdir");
2130                 g_free(prev_dir);
2131                 return -1;
2132         }
2133
2134         g_free(prev_dir);
2135
2136         if (rmdir(dir) < 0) {
2137                 FILE_OP_ERROR(dir, "rmdir");
2138                 return -1;
2139         }
2140
2141         return 0;
2142 }
2143
2144 #if 0
2145 /* this seems to be slower than the stdio version... */
2146 gint copy_file(const gchar *src, const gchar *dest)
2147 {
2148         gint src_fd, dest_fd;
2149         gint n_read;
2150         gint n_write;
2151         gchar buf[BUFSIZ];
2152         gchar *dest_bak = NULL;
2153
2154         if ((src_fd = open(src, O_RDONLY)) < 0) {
2155                 FILE_OP_ERROR(src, "open");
2156                 return -1;
2157         }
2158
2159         if (is_file_exist(dest)) {
2160                 dest_bak = g_strconcat(dest, ".bak", NULL);
2161                 if (rename(dest, dest_bak) < 0) {
2162                         FILE_OP_ERROR(dest, "rename");
2163                         close(src_fd);
2164                         g_free(dest_bak);
2165                         return -1;
2166                 }
2167         }
2168
2169         if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2170                 FILE_OP_ERROR(dest, "open");
2171                 close(src_fd);
2172                 if (dest_bak) {
2173                         if (rename(dest_bak, dest) < 0)
2174                                 FILE_OP_ERROR(dest_bak, "rename");
2175                         g_free(dest_bak);
2176                 }
2177                 return -1;
2178         }
2179
2180         while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2181                 gint len = n_read;
2182                 gchar *bufp = buf;
2183
2184                 while (len > 0) {
2185                         n_write = write(dest_fd, bufp, len);
2186                         if (n_write <= 0) {
2187                                 g_warning("writing to %s failed.\n", dest);
2188                                 close(dest_fd);
2189                                 close(src_fd);
2190                                 unlink(dest);
2191                                 if (dest_bak) {
2192                                         if (rename(dest_bak, dest) < 0)
2193                                                 FILE_OP_ERROR(dest_bak, "rename");
2194                                         g_free(dest_bak);
2195                                 }
2196                                 return -1;
2197                         }
2198                         len -= n_write;
2199                         bufp += n_write;
2200                 }
2201         }
2202
2203         close(src_fd);
2204         close(dest_fd);
2205
2206         if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2207                 g_warning("File copy from %s to %s failed.\n", src, dest);
2208                 unlink(dest);
2209                 if (dest_bak) {
2210                         if (rename(dest_bak, dest) < 0)
2211                                 FILE_OP_ERROR(dest_bak, "rename");
2212                         g_free(dest_bak);
2213                 }
2214                 return -1;
2215         }
2216         g_free(dest_bak);
2217
2218         return 0;
2219 }
2220 #endif
2221
2222
2223 /*
2224  * Append src file body to the tail of dest file.
2225  * Now keep_backup has no effects.
2226  */
2227 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2228 {
2229         FILE *src_fp, *dest_fp;
2230         gint n_read;
2231         gchar buf[BUFSIZ];
2232
2233         gboolean err = FALSE;
2234
2235         if ((src_fp = fopen(src, "rb")) == NULL) {
2236                 FILE_OP_ERROR(src, "fopen");
2237                 return -1;
2238         }
2239         
2240         if ((dest_fp = fopen(dest, "ab")) == NULL) {
2241                 FILE_OP_ERROR(dest, "fopen");
2242                 fclose(src_fp);
2243                 return -1;
2244         }
2245
2246         if (change_file_mode_rw(dest_fp, dest) < 0) {
2247                 FILE_OP_ERROR(dest, "chmod");
2248                 g_warning("can't change file mode\n");
2249         }
2250
2251         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2252                 if (n_read < sizeof(buf) && ferror(src_fp))
2253                         break;
2254                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2255                         g_warning("writing to %s failed.\n", dest);
2256                         fclose(dest_fp);
2257                         fclose(src_fp);
2258                         unlink(dest);
2259                         return -1;
2260                 }
2261         }
2262
2263         if (ferror(src_fp)) {
2264                 FILE_OP_ERROR(src, "fread");
2265                 err = TRUE;
2266         }
2267         fclose(src_fp);
2268         if (fclose(dest_fp) == EOF) {
2269                 FILE_OP_ERROR(dest, "fclose");
2270                 err = TRUE;
2271         }
2272
2273         if (err) {
2274                 unlink(dest);
2275                 return -1;
2276         }
2277
2278         return 0;
2279 }
2280
2281 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2282 {
2283         FILE *src_fp, *dest_fp;
2284         gint n_read;
2285         gchar buf[BUFSIZ];
2286         gchar *dest_bak = NULL;
2287         gboolean err = FALSE;
2288
2289         if ((src_fp = fopen(src, "rb")) == NULL) {
2290                 FILE_OP_ERROR(src, "fopen");
2291                 return -1;
2292         }
2293         if (is_file_exist(dest)) {
2294                 dest_bak = g_strconcat(dest, ".bak", NULL);
2295                 if (rename(dest, dest_bak) < 0) {
2296                         FILE_OP_ERROR(dest, "rename");
2297                         fclose(src_fp);
2298                         g_free(dest_bak);
2299                         return -1;
2300                 }
2301         }
2302
2303         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2304                 FILE_OP_ERROR(dest, "fopen");
2305                 fclose(src_fp);
2306                 if (dest_bak) {
2307                         if (rename(dest_bak, dest) < 0)
2308                                 FILE_OP_ERROR(dest_bak, "rename");
2309                         g_free(dest_bak);
2310                 }
2311                 return -1;
2312         }
2313
2314         if (change_file_mode_rw(dest_fp, dest) < 0) {
2315                 FILE_OP_ERROR(dest, "chmod");
2316                 g_warning("can't change file mode\n");
2317         }
2318
2319         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2320                 if (n_read < sizeof(buf) && ferror(src_fp))
2321                         break;
2322                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2323                         g_warning("writing to %s failed.\n", dest);
2324                         fclose(dest_fp);
2325                         fclose(src_fp);
2326                         unlink(dest);
2327                         if (dest_bak) {
2328                                 if (rename(dest_bak, dest) < 0)
2329                                         FILE_OP_ERROR(dest_bak, "rename");
2330                                 g_free(dest_bak);
2331                         }
2332                         return -1;
2333                 }
2334         }
2335
2336         if (ferror(src_fp)) {
2337                 FILE_OP_ERROR(src, "fread");
2338                 err = TRUE;
2339         }
2340         fclose(src_fp);
2341         if (fclose(dest_fp) == EOF) {
2342                 FILE_OP_ERROR(dest, "fclose");
2343                 err = TRUE;
2344         }
2345
2346         if (err) {
2347                 unlink(dest);
2348                 if (dest_bak) {
2349                         if (rename(dest_bak, dest) < 0)
2350                                 FILE_OP_ERROR(dest_bak, "rename");
2351                         g_free(dest_bak);
2352                 }
2353                 return -1;
2354         }
2355
2356         if (keep_backup == FALSE && dest_bak)
2357                 unlink(dest_bak);
2358
2359         g_free(dest_bak);
2360
2361         return 0;
2362 }
2363
2364 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2365 {
2366         if (overwrite == FALSE && is_file_exist(dest)) {
2367                 g_warning("move_file(): file %s already exists.", dest);
2368                 return -1;
2369         }
2370
2371         if (rename(src, dest) == 0) return 0;
2372
2373         if (EXDEV != errno) {
2374                 FILE_OP_ERROR(src, "rename");
2375                 return -1;
2376         }
2377
2378         if (copy_file(src, dest, FALSE) < 0) return -1;
2379
2380         unlink(src);
2381
2382         return 0;
2383 }
2384
2385 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2386 {
2387         FILE *dest_fp;
2388         gint n_read;
2389         gint bytes_left, to_read;
2390         gchar buf[BUFSIZ];
2391         gboolean err = FALSE;
2392
2393         if (fseek(fp, offset, SEEK_SET) < 0) {
2394                 perror("fseek");
2395                 return -1;
2396         }
2397
2398         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2399                 FILE_OP_ERROR(dest, "fopen");
2400                 return -1;
2401         }
2402
2403         if (change_file_mode_rw(dest_fp, dest) < 0) {
2404                 FILE_OP_ERROR(dest, "chmod");
2405                 g_warning("can't change file mode\n");
2406         }
2407
2408         bytes_left = length;
2409         to_read = MIN(bytes_left, sizeof(buf));
2410
2411         while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2412                 if (n_read < to_read && ferror(fp))
2413                         break;
2414                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2415                         g_warning("writing to %s failed.\n", dest);
2416                         fclose(dest_fp);
2417                         unlink(dest);
2418                         return -1;
2419                 }
2420                 bytes_left -= n_read;
2421                 if (bytes_left == 0)
2422                         break;
2423                 to_read = MIN(bytes_left, sizeof(buf));
2424         }
2425
2426         if (ferror(fp)) {
2427                 perror("fread");
2428                 err = TRUE;
2429         }
2430         if (fclose(dest_fp) == EOF) {
2431                 FILE_OP_ERROR(dest, "fclose");
2432                 err = TRUE;
2433         }
2434
2435         if (err) {
2436                 unlink(dest);
2437                 return -1;
2438         }
2439
2440         return 0;
2441 }
2442
2443 /* convert line endings into CRLF. If the last line doesn't end with
2444  * linebreak, add it.
2445  */
2446 gchar *canonicalize_str(const gchar *str)
2447 {
2448         const gchar *p;
2449         guint new_len = 0;
2450         gchar *out, *outp;
2451
2452         for (p = str; *p != '\0'; ++p) {
2453                 if (*p != '\r') {
2454                         ++new_len;
2455                         if (*p == '\n')
2456                                 ++new_len;
2457                 }
2458         }
2459         if (p == str || *(p - 1) != '\n')
2460                 new_len += 2;
2461
2462         out = outp = g_malloc(new_len + 1);
2463         for (p = str; *p != '\0'; ++p) {
2464                 if (*p != '\r') {
2465                         if (*p == '\n')
2466                                 *outp++ = '\r';
2467                         *outp++ = *p;
2468                 }
2469         }
2470         if (p == str || *(p - 1) != '\n') {
2471                 *outp++ = '\r';
2472                 *outp++ = '\n';
2473         }
2474         *outp = '\0';
2475
2476         return out;
2477 }
2478
2479 gint canonicalize_file(const gchar *src, const gchar *dest)
2480 {
2481         FILE *src_fp, *dest_fp;
2482         gchar buf[BUFFSIZE];
2483         gint len;
2484         gboolean err = FALSE;
2485         gboolean last_linebreak = FALSE;
2486
2487         if ((src_fp = fopen(src, "rb")) == NULL) {
2488                 FILE_OP_ERROR(src, "fopen");
2489                 return -1;
2490         }
2491
2492         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2493                 FILE_OP_ERROR(dest, "fopen");
2494                 fclose(src_fp);
2495                 return -1;
2496         }
2497
2498         if (change_file_mode_rw(dest_fp, dest) < 0) {
2499                 FILE_OP_ERROR(dest, "chmod");
2500                 g_warning("can't change file mode\n");
2501         }
2502
2503         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2504                 gint r = 0;
2505
2506                 len = strlen(buf);
2507                 if (len == 0) break;
2508                 last_linebreak = FALSE;
2509
2510                 if (buf[len - 1] != '\n') {
2511                         last_linebreak = TRUE;
2512                         r = fputs(buf, dest_fp);
2513                 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2514                         r = fputs(buf, dest_fp);
2515                 } else {
2516                         if (len > 1) {
2517                                 r = fwrite(buf, len - 1, 1, dest_fp);
2518                                 if (r != 1)
2519                                         r = EOF;
2520                         }
2521                         if (r != EOF)
2522                                 r = fputs("\r\n", dest_fp);
2523                 }
2524
2525                 if (r == EOF) {
2526                         g_warning("writing to %s failed.\n", dest);
2527                         fclose(dest_fp);
2528                         fclose(src_fp);
2529                         unlink(dest);
2530                         return -1;
2531                 }
2532         }
2533
2534         if (last_linebreak == TRUE) {
2535                 if (fputs("\r\n", dest_fp) == EOF)
2536                         err = TRUE;
2537         }
2538
2539         if (ferror(src_fp)) {
2540                 FILE_OP_ERROR(src, "fgets");
2541                 err = TRUE;
2542         }
2543         fclose(src_fp);
2544         if (fclose(dest_fp) == EOF) {
2545                 FILE_OP_ERROR(dest, "fclose");
2546                 err = TRUE;
2547         }
2548
2549         if (err) {
2550                 unlink(dest);
2551                 return -1;
2552         }
2553
2554         return 0;
2555 }
2556
2557 gint canonicalize_file_replace(const gchar *file)
2558 {
2559         gchar *tmp_file;
2560
2561         tmp_file = get_tmp_file();
2562
2563         if (canonicalize_file(file, tmp_file) < 0) {
2564                 g_free(tmp_file);
2565                 return -1;
2566         }
2567
2568         if (move_file(tmp_file, file, TRUE) < 0) {
2569                 g_warning("can't replace %s .\n", file);
2570                 unlink(tmp_file);
2571                 g_free(tmp_file);
2572                 return -1;
2573         }
2574
2575         g_free(tmp_file);
2576         return 0;
2577 }
2578
2579 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2580 {
2581         FILE *src_fp, *dest_fp;
2582         gchar buf[BUFFSIZE];
2583         gboolean err = FALSE;
2584
2585         if ((src_fp = fopen(src, "rb")) == NULL) {
2586                 FILE_OP_ERROR(src, "fopen");
2587                 return -1;
2588         }
2589
2590         if ((dest_fp = fopen(dest, "wb")) == NULL) {
2591                 FILE_OP_ERROR(dest, "fopen");
2592                 fclose(src_fp);
2593                 return -1;
2594         }
2595
2596         if (change_file_mode_rw(dest_fp, dest) < 0) {
2597                 FILE_OP_ERROR(dest, "chmod");
2598                 g_warning("can't change file mode\n");
2599         }
2600
2601         while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2602                 strcrchomp(buf);
2603                 if (fputs(buf, dest_fp) == EOF) {
2604                         g_warning("writing to %s failed.\n", dest);
2605                         fclose(dest_fp);
2606                         fclose(src_fp);
2607                         unlink(dest);
2608                         return -1;
2609                 }
2610         }
2611
2612         if (ferror(src_fp)) {
2613                 FILE_OP_ERROR(src, "fgets");
2614                 err = TRUE;
2615         }
2616         fclose(src_fp);
2617         if (fclose(dest_fp) == EOF) {
2618                 FILE_OP_ERROR(dest, "fclose");
2619                 err = TRUE;
2620         }
2621
2622         if (err) {
2623                 unlink(dest);
2624                 return -1;
2625         }
2626
2627         return 0;
2628 }
2629
2630 gint uncanonicalize_file_replace(const gchar *file)
2631 {
2632         gchar *tmp_file;
2633
2634         tmp_file = get_tmp_file();
2635
2636         if (uncanonicalize_file(file, tmp_file) < 0) {
2637                 g_free(tmp_file);
2638                 return -1;
2639         }
2640
2641         if (move_file(tmp_file, file, TRUE) < 0) {
2642                 g_warning("can't replace %s .\n", file);
2643                 unlink(tmp_file);
2644                 g_free(tmp_file);
2645                 return -1;
2646         }
2647
2648         g_free(tmp_file);
2649         return 0;
2650 }
2651
2652 gchar *normalize_newlines(const gchar *str)
2653 {
2654         const gchar *p = str;
2655         gchar *out, *outp;
2656
2657         out = outp = g_malloc(strlen(str) + 1);
2658         for (p = str; *p != '\0'; ++p) {
2659                 if (*p == '\r') {
2660                         if (*(p + 1) != '\n')
2661                                 *outp++ = '\n';
2662                 } else
2663                         *outp++ = *p;
2664         }
2665
2666         *outp = '\0';
2667
2668         return out;
2669 }
2670
2671 gchar *get_outgoing_rfc2822_str(FILE *fp)
2672 {
2673         gchar buf[BUFFSIZE];
2674         GString *str;
2675         gchar *ret;
2676
2677         str = g_string_new(NULL);
2678
2679         /* output header part */
2680         while (fgets(buf, sizeof(buf), fp) != NULL) {
2681                 strretchomp(buf);
2682                 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2683                         gint next;
2684
2685                         for (;;) {
2686                                 next = fgetc(fp);
2687                                 if (next == EOF)
2688                                         break;
2689                                 else if (next != ' ' && next != '\t') {
2690                                         ungetc(next, fp);
2691                                         break;
2692                                 }
2693                                 if (fgets(buf, sizeof(buf), fp) == NULL)
2694                                         break;
2695                         }
2696                 } else {
2697                         g_string_append(str, buf);
2698                         g_string_append(str, "\r\n");
2699                         if (buf[0] == '\0')
2700                                 break;
2701                 }
2702         }
2703
2704         /* output body part */
2705         while (fgets(buf, sizeof(buf), fp) != NULL) {
2706                 strretchomp(buf);
2707                 if (buf[0] == '.')
2708                         g_string_append_c(str, '.');
2709                 g_string_append(str, buf);
2710                 g_string_append(str, "\r\n");
2711         }
2712
2713         ret = str->str;
2714         g_string_free(str, FALSE);
2715
2716         return ret;
2717 }
2718
2719 /*
2720  * Create a new boundary in a way that it is very unlikely that this
2721  * will occur in the following text.  It would be easy to ensure
2722  * uniqueness if everything is either quoted-printable or base64
2723  * encoded (note that conversion is allowed), but because MIME bodies
2724  * may be nested, it may happen that the same boundary has already
2725  * been used. We avoid scanning the message for conflicts and hope the
2726  * best.
2727  *
2728  *   boundary := 0*69<bchars> bcharsnospace
2729  *   bchars := bcharsnospace / " "
2730  *   bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2731  *                    "+" / "_" / "," / "-" / "." /
2732  *                    "/" / ":" / "=" / "?"
2733  *
2734  * some special characters removed because of buggy MTAs
2735  */
2736
2737 gchar *generate_mime_boundary(const gchar *prefix)
2738 {
2739         static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2740                              "abcdefghijklmnopqrstuvwxyz"
2741                              "1234567890+_./=";
2742         gchar buf_uniq[17];
2743         gchar buf_date[64];
2744         gint i;
2745         gint pid;
2746
2747         pid = getpid();
2748
2749         /* We make the boundary depend on the pid, so that all running
2750          * processes generate different values even when they have been
2751          * started within the same second and srandom(time(NULL)) has been
2752          * used.  I can't see whether this is really an advantage but it
2753          * doesn't do any harm.
2754          */
2755         for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2756                 buf_uniq[i] = tbl[(random() ^ pid) % (sizeof(tbl) - 1)];
2757         buf_uniq[i] = '\0';
2758
2759         get_rfc822_date(buf_date, sizeof(buf_date));
2760         subst_char(buf_date, ' ', '_');
2761         subst_char(buf_date, ',', '_');
2762         subst_char(buf_date, ':', '_');
2763
2764         return g_strdup_printf("%s=_%s_%s", prefix ? prefix : "Multipart",
2765                                buf_date, buf_uniq);
2766 }
2767
2768 gint change_file_mode_rw(FILE *fp, const gchar *file)
2769 {
2770 #if HAVE_FCHMOD
2771         return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2772 #else
2773         return chmod(file, S_IRUSR|S_IWUSR);
2774 #endif
2775 }
2776
2777 FILE *my_tmpfile(void)
2778 {
2779 #if HAVE_MKSTEMP
2780         const gchar suffix[] = ".XXXXXX";
2781         const gchar *tmpdir;
2782         guint tmplen;
2783         const gchar *progname;
2784         guint proglen;
2785         gchar *fname;
2786         gint fd;
2787         FILE *fp;
2788
2789         tmpdir = get_tmp_dir();
2790         tmplen = strlen(tmpdir);
2791         progname = g_get_prgname();
2792         proglen = strlen(progname);
2793         Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2794                 return tmpfile());
2795
2796         memcpy(fname, tmpdir, tmplen);
2797         fname[tmplen] = G_DIR_SEPARATOR;
2798         memcpy(fname + tmplen + 1, progname, proglen);
2799         memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2800
2801         fd = mkstemp(fname);
2802         if (fd < 0)
2803                 return tmpfile();
2804
2805         unlink(fname);
2806
2807         fp = fdopen(fd, "w+b");
2808         if (!fp)
2809                 close(fd);
2810         else
2811                 return fp;
2812 #endif /* HAVE_MKSTEMP */
2813
2814         return tmpfile();
2815 }
2816
2817 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2818 {
2819         int fd;
2820         
2821         *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2822         fd = mkstemp(*filename);
2823
2824         return fdopen(fd, "w+");
2825 }
2826
2827 FILE *str_open_as_stream(const gchar *str)
2828 {
2829         FILE *fp;
2830         size_t len;
2831
2832         g_return_val_if_fail(str != NULL, NULL);
2833
2834         fp = my_tmpfile();
2835         if (!fp) {
2836                 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2837                 return NULL;
2838         }
2839
2840         len = strlen(str);
2841         if (len == 0) return fp;
2842
2843         if (fwrite(str, len, 1, fp) != 1) {
2844                 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2845                 fclose(fp);
2846                 return NULL;
2847         }
2848
2849         rewind(fp);
2850         return fp;
2851 }
2852
2853 gint str_write_to_file(const gchar *str, const gchar *file)
2854 {
2855         FILE *fp;
2856         size_t len;
2857
2858         g_return_val_if_fail(str != NULL, -1);
2859         g_return_val_if_fail(file != NULL, -1);
2860
2861         if ((fp = fopen(file, "wb")) == NULL) {
2862                 FILE_OP_ERROR(file, "fopen");
2863                 return -1;
2864         }
2865
2866         len = strlen(str);
2867         if (len == 0) {
2868                 fclose(fp);
2869                 return 0;
2870         }
2871
2872         if (fwrite(str, len, 1, fp) != 1) {
2873                 FILE_OP_ERROR(file, "fwrite");
2874                 fclose(fp);
2875                 unlink(file);
2876                 return -1;
2877         }
2878
2879         if (fclose(fp) == EOF) {
2880                 FILE_OP_ERROR(file, "fclose");
2881                 unlink(file);
2882                 return -1;
2883         }
2884
2885         return 0;
2886 }
2887
2888 gchar *file_read_to_str(const gchar *file)
2889 {
2890         FILE *fp;
2891         gchar *str;
2892
2893         g_return_val_if_fail(file != NULL, NULL);
2894
2895         if ((fp = fopen(file, "rb")) == NULL) {
2896                 FILE_OP_ERROR(file, "fopen");
2897                 return NULL;
2898         }
2899
2900         str = file_read_stream_to_str(fp);
2901
2902         fclose(fp);
2903
2904         return str;
2905 }
2906
2907 gchar *file_read_stream_to_str(FILE *fp)
2908 {
2909         GByteArray *array;
2910         gchar buf[BUFSIZ];
2911         gint n_read;
2912         gchar *str;
2913
2914         g_return_val_if_fail(fp != NULL, NULL);
2915
2916         array = g_byte_array_new();
2917
2918         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2919                 if (n_read < sizeof(buf) && ferror(fp))
2920                         break;
2921                 g_byte_array_append(array, buf, n_read);
2922         }
2923
2924         if (ferror(fp)) {
2925                 FILE_OP_ERROR("file stream", "fread");
2926                 g_byte_array_free(array, TRUE);
2927                 return NULL;
2928         }
2929
2930         buf[0] = '\0';
2931         g_byte_array_append(array, buf, 1);
2932         str = (gchar *)array->data;
2933         g_byte_array_free(array, FALSE);
2934
2935         return str;
2936 }
2937
2938 gint execute_async(gchar *const argv[])
2939 {
2940         pid_t pid;
2941
2942         if ((pid = fork()) < 0) {
2943                 perror("fork");
2944                 return -1;
2945         }
2946
2947         if (pid == 0) {                 /* child process */
2948                 pid_t gch_pid;
2949
2950                 if ((gch_pid = fork()) < 0) {
2951                         perror("fork");
2952                         _exit(1);
2953                 }
2954
2955                 if (gch_pid == 0) {     /* grandchild process */
2956                         execvp(argv[0], argv);
2957
2958                         perror("execvp");
2959                         _exit(1);
2960                 }
2961
2962                 _exit(0);
2963         }
2964
2965         waitpid(pid, NULL, 0);
2966
2967         return 0;
2968 }
2969
2970 gint execute_sync(gchar *const argv[])
2971 {
2972         pid_t pid;
2973
2974         if ((pid = fork()) < 0) {
2975                 perror("fork");
2976                 return -1;
2977         }
2978
2979         if (pid == 0) {         /* child process */
2980                 execvp(argv[0], argv);
2981
2982                 perror("execvp");
2983                 _exit(1);
2984         }
2985
2986         waitpid(pid, NULL, 0);
2987
2988         return 0;
2989 }
2990
2991 gint execute_command_line(const gchar *cmdline, gboolean async)
2992 {
2993         gchar **argv;
2994         gint ret;
2995
2996         argv = strsplit_with_quote(cmdline, " ", 0);
2997
2998         if (async)
2999                 ret = execute_async(argv);
3000         else
3001                 ret = execute_sync(argv);
3002         g_strfreev(argv);
3003
3004         return ret;
3005 }
3006
3007 gchar *get_command_output(const gchar *cmdline)
3008 {
3009         gchar buf[BUFFSIZE];
3010         FILE *fp;
3011         GString *str;
3012         gchar *ret;
3013
3014         g_return_val_if_fail(cmdline != NULL, NULL);
3015
3016         if ((fp = popen(cmdline, "r")) == NULL) {
3017                 FILE_OP_ERROR(cmdline, "popen");
3018                 return NULL;
3019         }
3020
3021         str = g_string_new("");
3022
3023         while (fgets(buf, sizeof(buf), fp) != NULL)
3024                 g_string_append(str, buf);
3025
3026         pclose(fp);
3027
3028         ret = str->str;
3029         g_string_free(str, FALSE);
3030
3031         return ret;
3032 }
3033
3034 static gint is_unchanged_uri_char(char c)
3035 {
3036         switch (c) {
3037                 case '(':
3038                 case ')':
3039                 case ',':
3040                         return 0;
3041                 default:
3042                         return 1;
3043         }
3044 }
3045
3046 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3047 {
3048         int i;
3049         int k;
3050
3051         k = 0;
3052         for(i = 0; i < strlen(uri) ; i++) {
3053                 if (is_unchanged_uri_char(uri[i])) {
3054                         if (k + 2 >= bufsize)
3055                                 break;
3056                         encoded_uri[k++] = uri[i];
3057                 }
3058                 else {
3059                         char * hexa = "0123456789ABCDEF";
3060                         
3061                         if (k + 4 >= bufsize)
3062                                 break;
3063                         encoded_uri[k++] = '%';
3064                         encoded_uri[k++] = hexa[uri[i] / 16];
3065                         encoded_uri[k++] = hexa[uri[i] % 16];
3066                 }
3067         }
3068         encoded_uri[k] = 0;
3069 }
3070
3071 /* Converts two-digit hexadecimal to decimal.  Used for unescaping escaped 
3072  * characters
3073  */
3074 static gint axtoi(const gchar *hexstr)
3075 {
3076         gint hi, lo, result;
3077        
3078         hi = hexstr[0];
3079         if ('0' <= hi && hi <= '9') {
3080                 hi -= '0';
3081         } else
3082                 if ('a' <= hi && hi <= 'f') {
3083                         hi -= ('a' - 10);
3084                 } else
3085                         if ('A' <= hi && hi <= 'F') {
3086                                 hi -= ('A' - 10);
3087                         }
3088
3089         lo = hexstr[1];
3090         if ('0' <= lo && lo <= '9') {
3091                 lo -= '0';
3092         } else
3093                 if ('a' <= lo && lo <= 'f') {
3094                         lo -= ('a'-10);
3095                 } else
3096                         if ('A' <= lo && lo <= 'F') {
3097                                 lo -= ('A' - 10);
3098                         }
3099         result = lo + (16 * hi);
3100         return result;
3101 }
3102
3103
3104 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
3105  * plusses, and escape characters are used)
3106  */
3107
3108 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
3109 {
3110         const gchar *encoded;
3111         gchar *decoded;
3112
3113         encoded = encoded_uri;
3114         decoded = decoded_uri;
3115
3116         while (*encoded) {
3117                 if (*encoded == '%') {
3118                         encoded++;
3119                         if (isxdigit(encoded[0])
3120                             && isxdigit(encoded[1])) {
3121                                 *decoded = (gchar) axtoi(encoded);
3122                                 decoded++;
3123                                 encoded += 2;
3124                         }
3125                 }
3126                 else if (*encoded == '+') {
3127                         *decoded = ' ';
3128                         decoded++;
3129                         encoded++;
3130                 }
3131                 else {
3132                         *decoded = *encoded;
3133                         decoded++;
3134                         encoded++;
3135                 }
3136         }
3137
3138         *decoded = '\0';
3139 }
3140
3141
3142 gint open_uri(const gchar *uri, const gchar *cmdline)
3143 {
3144         gchar buf[BUFFSIZE];
3145         gchar *p;
3146         gchar encoded_uri[BUFFSIZE];
3147         
3148         g_return_val_if_fail(uri != NULL, -1);
3149
3150         /* an option to choose whether to use encode_uri or not ? */
3151         encode_uri(encoded_uri, BUFFSIZE, uri);
3152         
3153         if (cmdline &&
3154             (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3155             !strchr(p + 2, '%'))
3156                 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3157         else {
3158                 if (cmdline)
3159                         g_warning("Open URI command line is invalid: `%s'",
3160                                   cmdline);
3161                 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3162         }
3163         
3164         execute_command_line(buf, TRUE);
3165
3166         return 0;
3167 }
3168
3169 time_t remote_tzoffset_sec(const gchar *zone)
3170 {
3171         static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3172         gchar zone3[4];
3173         gchar *p;
3174         gchar c;
3175         gint iustz;
3176         gint offset;
3177         time_t remoteoffset;
3178
3179         strncpy(zone3, zone, 3);
3180         zone3[3] = '\0';
3181         remoteoffset = 0;
3182
3183         if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3184             (c == '+' || c == '-')) {
3185                 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3186                 if (c == '-')
3187                         remoteoffset = -remoteoffset;
3188         } else if (!strncmp(zone, "UT" , 2) ||
3189                    !strncmp(zone, "GMT", 2)) {
3190                 remoteoffset = 0;
3191         } else if (strlen(zone3) == 3) {
3192                 for (p = ustzstr; *p != '\0'; p += 3) {
3193                         if (!strncasecmp(p, zone3, 3)) {
3194                                 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3195                                 remoteoffset = iustz * 3600;
3196                                 break;
3197                         }
3198                 }
3199                 if (*p == '\0')
3200                         return -1;
3201         } else if (strlen(zone3) == 1) {
3202                 switch (zone[0]) {
3203                 case 'Z': remoteoffset =   0; break;
3204                 case 'A': remoteoffset =  -1; break;
3205                 case 'B': remoteoffset =  -2; break;
3206                 case 'C': remoteoffset =  -3; break;
3207                 case 'D': remoteoffset =  -4; break;
3208                 case 'E': remoteoffset =  -5; break;
3209                 case 'F': remoteoffset =  -6; break;
3210                 case 'G': remoteoffset =  -7; break;
3211                 case 'H': remoteoffset =  -8; break;
3212                 case 'I': remoteoffset =  -9; break;
3213                 case 'K': remoteoffset = -10; break; /* J is not used */
3214                 case 'L': remoteoffset = -11; break;
3215                 case 'M': remoteoffset = -12; break;
3216                 case 'N': remoteoffset =   1; break;
3217                 case 'O': remoteoffset =   2; break;
3218                 case 'P': remoteoffset =   3; break;
3219                 case 'Q': remoteoffset =   4; break;
3220                 case 'R': remoteoffset =   5; break;
3221                 case 'S': remoteoffset =   6; break;
3222                 case 'T': remoteoffset =   7; break;
3223                 case 'U': remoteoffset =   8; break;
3224                 case 'V': remoteoffset =   9; break;
3225                 case 'W': remoteoffset =  10; break;
3226                 case 'X': remoteoffset =  11; break;
3227                 case 'Y': remoteoffset =  12; break;
3228                 default:  remoteoffset =   0; break;
3229                 }
3230                 remoteoffset = remoteoffset * 3600;
3231         } else
3232                 return -1;
3233
3234         return remoteoffset;
3235 }
3236
3237 time_t tzoffset_sec(time_t *now)
3238 {
3239         struct tm gmt, *lt;
3240         gint off;
3241
3242         gmt = *gmtime(now);
3243         lt = localtime(now);
3244
3245         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3246
3247         if (lt->tm_year < gmt.tm_year)
3248                 off -= 24 * 60;
3249         else if (lt->tm_year > gmt.tm_year)
3250                 off += 24 * 60;
3251         else if (lt->tm_yday < gmt.tm_yday)
3252                 off -= 24 * 60;
3253         else if (lt->tm_yday > gmt.tm_yday)
3254                 off += 24 * 60;
3255
3256         if (off >= 24 * 60)             /* should be impossible */
3257                 off = 23 * 60 + 59;     /* if not, insert silly value */
3258         if (off <= -24 * 60)
3259                 off = -(23 * 60 + 59);
3260
3261         return off * 60;
3262 }
3263
3264 /* calculate timezone offset */
3265 gchar *tzoffset(time_t *now)
3266 {
3267         static gchar offset_string[6];
3268         struct tm gmt, *lt;
3269         gint off;
3270         gchar sign = '+';
3271
3272         gmt = *gmtime(now);
3273         lt = localtime(now);
3274
3275         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3276
3277         if (lt->tm_year < gmt.tm_year)
3278                 off -= 24 * 60;
3279         else if (lt->tm_year > gmt.tm_year)
3280                 off += 24 * 60;
3281         else if (lt->tm_yday < gmt.tm_yday)
3282                 off -= 24 * 60;
3283         else if (lt->tm_yday > gmt.tm_yday)
3284                 off += 24 * 60;
3285
3286         if (off < 0) {
3287                 sign = '-';
3288                 off = -off;
3289         }
3290
3291         if (off >= 24 * 60)             /* should be impossible */
3292                 off = 23 * 60 + 59;     /* if not, insert silly value */
3293
3294         sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3295
3296         return offset_string;
3297 }
3298
3299 void get_rfc822_date(gchar *buf, gint len)
3300 {
3301         struct tm *lt;
3302         time_t t;
3303         gchar day[4], mon[4];
3304         gint dd, hh, mm, ss, yyyy;
3305
3306         t = time(NULL);
3307         lt = localtime(&t);
3308
3309         sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3310                day, mon, &dd, &hh, &mm, &ss, &yyyy);
3311         g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3312                    day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3313 }
3314
3315 void debug_set_mode(gboolean mode)
3316 {
3317         debug_mode = mode;
3318 }
3319
3320 gboolean debug_get_mode(void)
3321 {
3322         return debug_mode;
3323 }
3324
3325 void debug_print_real(const gchar *format, ...)
3326 {
3327         va_list args;
3328         gchar buf[BUFFSIZE];
3329
3330         if (!debug_mode) return;
3331
3332         va_start(args, format);
3333         g_vsnprintf(buf, sizeof(buf), format, args);
3334         va_end(args);
3335
3336         fputs(buf, stdout);
3337 }
3338
3339 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3340 {
3341         if (subject == NULL)
3342                 subject = "";
3343         else
3344                 subject += subject_get_prefix_length(subject);
3345
3346         return g_hash_table_lookup(subject_table, subject);
3347 }
3348
3349 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3350                           void * data)
3351 {
3352         if (subject == NULL || *subject == 0)
3353                 return;
3354         subject += subject_get_prefix_length(subject);
3355         g_hash_table_insert(subject_table, subject, data);
3356 }
3357
3358 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3359 {
3360         if (subject == NULL)
3361                 return;
3362
3363         subject += subject_get_prefix_length(subject);  
3364         g_hash_table_remove(subject_table, subject);
3365 }
3366
3367 /*!
3368  *\brief        Check if a string is prefixed with known (combinations) 
3369  *              of prefixes. The function assumes that each prefix 
3370  *              is terminated by zero or exactly _one_ space.
3371  *
3372  *\param        str String to check for a prefixes
3373  *
3374  *\return       int Number of chars in the prefix that should be skipped 
3375  *              for a "clean" subject line. If no prefix was found, 0
3376  *              is returned.
3377  */             
3378 int subject_get_prefix_length(const gchar *subject)
3379 {
3380         /*!< Array with allowable reply prefixes regexps. */
3381         static const gchar * const prefixes[] = {
3382                 "Re\\:",                        /* "Re:" */
3383                 "Re\\[[1-9][0-9]*\\]\\:",       /* "Re[XXX]:" (non-conforming news mail clients) */
3384                 "Antw\\:",                      /* "Antw:" (Dutch / German Outlook) */
3385                 "Aw\\:",                        /* "Aw:"   (German) */
3386                 "Antwort\\:",                   /* "Antwort:" (German Lotus Notes) */
3387                 "Res\\:",                       /* "Res:" (Brazilian Outlook) */
3388                 "Fw\\:",                        /* "Fw:" Forward */
3389                 "Enc\\:"                        /* "Enc:" Forward (Brazilian Outlook) */
3390                 /* add more */
3391         };
3392         const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3393         int n;
3394         regmatch_t pos;
3395         static regex_t regex;
3396         static gboolean init_;
3397
3398         if (!subject) return 0;
3399         if (!*subject) return 0;
3400
3401         if (!init_) {
3402                 GString *s = g_string_new("");
3403                 
3404                 for (n = 0; n < PREFIXES; n++)
3405                         /* Terminate each prefix regexpression by a
3406                          * "\ ?" (zero or ONE space), and OR them */
3407                         g_string_sprintfa(s, "(%s\\ ?)%s",
3408                                           prefixes[n],
3409                                           n < PREFIXES - 1 ? 
3410                                           "|" : "");
3411                 
3412                 g_string_prepend(s, "(");
3413                 g_string_append(s, ")+");       /* match at least once */
3414                 g_string_prepend(s, "^\\ *");   /* from beginning of line */
3415                 
3416
3417                 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+" 
3418                  * TODO: Should this be       "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3419                 if (regcomp(&regex, s->str, REG_EXTENDED | REG_ICASE)) { 
3420                         debug_print("Error compiling regexp %s\n", s->str);
3421                         g_string_free(s, TRUE);
3422                         return 0;
3423                 } else {
3424                         init_ = TRUE;
3425                         g_string_free(s, TRUE);
3426                 }
3427         }
3428         
3429         if (!regexec(&regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3430                 return pos.rm_eo;
3431         else
3432                 return 0;
3433 }
3434
3435 /* allow Mutt-like patterns in quick search */
3436 gchar *expand_search_string(const gchar *search_string)
3437 {
3438         int i = 0;
3439         gchar term_char, save_char;
3440         gchar *cmd_start, *cmd_end;
3441         GString *matcherstr;
3442         gchar *returnstr = NULL;
3443         gchar *copy_str;
3444         gboolean casesens, dontmatch;
3445         /* list of allowed pattern abbreviations */
3446         struct {
3447                 gchar           *abbreviated;   /* abbreviation */
3448                 gchar           *command;       /* actual matcher command */ 
3449                 gint            numparams;      /* number of params for cmd */
3450                 gboolean        qualifier;      /* do we append regexpcase */
3451                 gboolean        quotes;         /* do we need quotes */
3452         }
3453         cmds[] = {
3454                 { "a",  "all",                          0,      FALSE,  FALSE },
3455                 { "ag", "age_greater",                  1,      FALSE,  FALSE },
3456                 { "al", "age_lower",                    1,      FALSE,  FALSE },
3457                 { "b",  "body_part",                    1,      TRUE,   TRUE  },
3458                 { "B",  "message",                      1,      TRUE,   TRUE  },
3459                 { "c",  "cc",                           1,      TRUE,   TRUE  },
3460                 { "C",  "to_or_cc",                     1,      TRUE,   TRUE  },
3461                 { "D",  "deleted",                      0,      FALSE,  FALSE },
3462                 { "e",  "header \"Sender\"",            1,      TRUE,   TRUE  },
3463                 { "E",  "execute",                      1,      FALSE,  TRUE  },
3464                 { "f",  "from",                         1,      TRUE,   TRUE  },
3465                 { "F",  "forwarded",                    0,      FALSE,  FALSE },
3466                 { "h",  "headers_part",                 1,      TRUE,   TRUE  },
3467                 { "i",  "header \"Message-Id\"",        1,      TRUE,   TRUE  },
3468                 { "I",  "inreplyto",                    1,      TRUE,   TRUE  },
3469                 { "L",  "locked",                       0,      FALSE,  FALSE },
3470                 { "n",  "newsgroups",                   1,      TRUE,   TRUE  },
3471                 { "N",  "new",                          0,      FALSE,  FALSE },
3472                 { "O",  "~new",                         0,      FALSE,  FALSE },
3473                 { "r",  "replied",                      0,      FALSE,  FALSE },
3474                 { "R",  "~unread",                      0,      FALSE,  FALSE },
3475                 { "s",  "subject",                      1,      TRUE,   TRUE  },
3476                 { "se", "score_equal",                  1,      FALSE,  FALSE },
3477                 { "sg", "score_greater",                1,      FALSE,  FALSE },
3478                 { "sl", "score_lower",                  1,      FALSE,  FALSE },
3479                 { "Se", "size_equal",                   1,      FALSE,  FALSE },
3480                 { "Sg", "size_greater",                 1,      FALSE,  FALSE },
3481                 { "Ss", "size_smaller",                 1,      FALSE,  FALSE },
3482                 { "t",  "to",                           1,      TRUE,   TRUE  },
3483                 { "T",  "marked",                       0,      FALSE,  FALSE },
3484                 { "U",  "unread",                       0,      FALSE,  FALSE },
3485                 { "x",  "header \"References\"",        1,      TRUE,   TRUE  },
3486                 { "y",  "header \"X-Label\"",           1,      TRUE,   TRUE  },
3487                 { "&",  "&",                            0,      FALSE,  FALSE },
3488                 { "|",  "|",                            0,      FALSE,  FALSE },
3489                 { NULL, NULL,                           0,      FALSE,  FALSE }
3490         };
3491
3492         if (search_string == NULL)
3493                 return NULL;
3494
3495         copy_str = g_strdup(search_string);
3496
3497         /* if it's a full command don't process it so users
3498            can still do something like from regexpcase "foo" */
3499         for (i = 0; cmds[i].command; i++) {
3500                 const gchar *tmp_search_string = search_string;
3501                 cmd_start = cmds[i].command;
3502                 /* allow logical NOT */
3503                 if (*tmp_search_string == '~')
3504                         tmp_search_string++;
3505                 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3506                         break;
3507         }
3508         if (cmds[i].command)
3509                 return copy_str;
3510
3511         matcherstr = g_string_sized_new(16);
3512         cmd_start = cmd_end = copy_str;
3513         while (cmd_end && *cmd_end) {
3514                 /* skip all white spaces */
3515                 while (*cmd_end && isspace(*cmd_end))
3516                         cmd_end++;
3517
3518                 /* extract a command */
3519                 while (*cmd_end && !isspace(*cmd_end))
3520                         cmd_end++;
3521
3522                 /* save character */
3523                 save_char = *cmd_end;
3524                 *cmd_end = '\0';
3525
3526                 dontmatch = FALSE;
3527                 casesens = FALSE;
3528
3529                 /* ~ and ! mean logical NOT */
3530                 if (*cmd_start == '~' || *cmd_start == '!')
3531                 {
3532                         dontmatch = TRUE;
3533                         cmd_start++;
3534                 }
3535                 /* % means case sensitive match */
3536                 if (*cmd_start == '%')
3537                 {
3538                         casesens = TRUE;
3539                         cmd_start++;
3540                 }
3541
3542                 /* find matching abbreviation */
3543                 for (i = 0; cmds[i].command; i++) {
3544                         if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3545                                 /* restore character */
3546                                 *cmd_end = save_char;
3547
3548                                 /* copy command */
3549                                 if (matcherstr->len > 0) {
3550                                         g_string_append(matcherstr, " ");
3551                                 }
3552                                 if (dontmatch)
3553                                         g_string_append(matcherstr, "~");
3554                                 g_string_append(matcherstr, cmds[i].command);
3555                                 g_string_append(matcherstr, " ");
3556
3557                                 /* stop if no params required */
3558                                 if (cmds[i].numparams == 0)
3559                                         break;
3560
3561                                 /* extract a parameter, allow quotes */
3562                                 cmd_end++;
3563                                 cmd_start = cmd_end;
3564                                 if (*cmd_start == '"') {
3565                                         term_char = '"';
3566                                         cmd_end++;
3567                                 }
3568                                 else
3569                                         term_char = ' ';
3570
3571                                 /* extract actual parameter */
3572                                 while ((*cmd_end) && (*cmd_end != term_char))
3573                                         cmd_end++;
3574
3575                                 if (*cmd_end && (*cmd_end != term_char))
3576                                         break;
3577
3578                                 if (*cmd_end == '"')
3579                                         cmd_end++;
3580
3581                                 save_char = *cmd_end;
3582                                 *cmd_end = '\0';
3583
3584                                 if (cmds[i].qualifier) {
3585                                         if (casesens)
3586                                                 g_string_append(matcherstr, "regexp ");
3587                                         else
3588                                                 g_string_append(matcherstr, "regexpcase ");
3589                                 }
3590
3591                                 /* do we need to add quotes ? */
3592                                 if (cmds[i].quotes && term_char != '"')
3593                                         g_string_append(matcherstr, "\"");
3594
3595                                 /* copy actual parameter */
3596                                 g_string_append(matcherstr, cmd_start);
3597
3598                                 /* do we need to add quotes ? */
3599                                 if (cmds[i].quotes && term_char != '"')
3600                                         g_string_append(matcherstr, "\"");
3601
3602                                 /* restore original character */
3603                                 *cmd_end = save_char;
3604
3605                                 break;
3606                         }
3607                 }
3608
3609                 if (*cmd_end) {
3610                         cmd_end++;
3611                         cmd_start = cmd_end;
3612                 }
3613         }
3614
3615         g_free(copy_str);
3616         returnstr = matcherstr->str;
3617         g_string_free(matcherstr, FALSE);
3618         return returnstr;
3619 }
3620
3621 guint g_stricase_hash(gconstpointer gptr)
3622 {
3623         guint hash_result = 0;
3624         const char *str;
3625
3626         for (str = gptr; str && *str; str++) {
3627                 if (isupper(*str)) hash_result += (*str + ' ');
3628                 else hash_result += *str;
3629         }
3630
3631         return hash_result;
3632 }
3633
3634 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3635 {
3636         const char *str1 = gptr1;
3637         const char *str2 = gptr2;
3638
3639         return !strcasecmp(str1, str2);
3640 }
3641
3642 gint g_int_compare(gconstpointer a, gconstpointer b)
3643 {
3644         return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3645 }
3646
3647 gchar *generate_msgid(const gchar *address, gchar *buf, gint len)
3648 {
3649         /* steal from compose.c::compose_generate_msgid() */
3650         struct tm *lt;
3651         time_t t;
3652         gchar *addr;
3653
3654         t = time(NULL);
3655         lt = localtime(&t);
3656
3657         if (address && *address) {
3658                 if (strchr(address, '@'))
3659                         addr = g_strdup(address);
3660                 else
3661                         addr = g_strconcat(address, "@", get_domain_name(), NULL);
3662         } else
3663                 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3664                                    NULL);
3665
3666         g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3667                    lt->tm_year + 1900, lt->tm_mon + 1,
3668                    lt->tm_mday, lt->tm_hour,
3669                    lt->tm_min, lt->tm_sec,
3670                    (guint)random(), addr);
3671
3672         g_free(addr);
3673         return buf;
3674 }
3675
3676
3677 /*
3678    quote_cmd_argument()
3679    
3680    return a quoted string safely usable in argument of a command.
3681    
3682    code is extracted and adapted from etPan! project -- DINH V. HoĆ .
3683 */
3684
3685 gint quote_cmd_argument(gchar * result, guint size,
3686                         const gchar * path)
3687 {
3688         const gchar * p;
3689         gchar * result_p;
3690         guint remaining;
3691
3692         result_p = result;
3693         remaining = size;
3694
3695         for(p = path ; * p != '\0' ; p ++) {
3696
3697                 if (isalnum(* p) || (* p == '/')) {
3698                         if (remaining > 0) {
3699                                 * result_p = * p;
3700                                 result_p ++; 
3701                                 remaining --;
3702                         }
3703                         else {
3704                                 result[size - 1] = '\0';
3705                                 return -1;
3706                         }
3707                 }
3708                 else { 
3709                         if (remaining >= 2) {
3710                                 * result_p = '\\';
3711                                 result_p ++; 
3712                                 * result_p = * p;
3713                                 result_p ++; 
3714                                 remaining -= 2;
3715                         }
3716                         else {
3717                                 result[size - 1] = '\0';
3718                                 return -1;
3719                         }
3720                 }
3721         }
3722         if (remaining > 0) {
3723                 * result_p = '\0';
3724         }
3725         else {
3726                 result[size - 1] = '\0';
3727                 return -1;
3728         }
3729   
3730         return 0;
3731 }
3732