scoring - bugfix for summaryview
[claws.git] / src / utils.c
1 /*
2  * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2001 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
45 #include "intl.h"
46 #include "utils.h"
47 #include "statusbar.h"
48 #include "logwindow.h"
49
50 #define BUFFSIZE        8192
51
52 extern gboolean debug_mode;
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 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
75 {
76         g_free(key);
77 }
78
79 void hash_free_strings(GHashTable *table)
80 {
81         g_hash_table_foreach(table, hash_free_strings_func, NULL);
82 }
83
84 void ptr_array_free_strings(GPtrArray *array)
85 {
86         gint i;
87         gchar *str;
88
89         g_return_if_fail(array != NULL);
90
91         for (i = 0; i < array->len; i++) {
92                 str = g_ptr_array_index(array, i);
93                 g_free(str);
94         }
95 }
96
97 gint to_number(const gchar *nstr)
98 {
99         register const gchar *p;
100
101         if (*nstr == '\0') return -1;
102
103         for (p = nstr; *p != '\0'; p++)
104                 if (!isdigit(*p)) return -1;
105
106         return atoi(nstr);
107 }
108
109 /* convert integer into string
110    nstr must be a 11 characters table
111 */
112 gchar *itos_buf(gchar nstr[], gint n)
113 {
114         g_snprintf(nstr, 11, "%d", n);
115         return nstr;
116 }
117
118 /* convert integer into string
119    use an internal static buffer */
120 gchar *itos(gint n)
121 {
122         static gchar nstr[11];
123
124         return itos_buf(nstr, n);
125 }
126
127 gchar *to_human_readable(off_t size)
128 {
129         static gchar str[9];
130         gint count;
131         guint32 div = 1;
132
133         for (count = 0; count < 3; count++) {
134                 if (size / div < 1024)
135                         break;
136                 else
137                         div *= 1024;
138         }
139
140         switch (count) {
141         case 0: g_snprintf(str, sizeof(str), "%dB",    (gint)size);   break;
142         case 1: g_snprintf(str, sizeof(str), "%.1fKB", (gfloat)size / div);
143                 break;
144         case 2: g_snprintf(str, sizeof(str), "%.1fMB", (gfloat)size / div);
145                 break;
146         default:
147                 g_snprintf(str, sizeof(str), "%.1fGB", (gfloat)size / div);
148                 break;
149         }
150
151         return str;
152 }
153
154 /* strcmp with NULL-checking */
155 gint strcmp2(const gchar *s1, const gchar *s2)
156 {
157         if (s1 == NULL || s2 == NULL)
158                 return -1;
159         else
160                 return strcmp(s1, s2);
161 }
162
163 /* compare paths */
164 gint path_cmp(const gchar *s1, const gchar *s2)
165 {
166         gint len1, len2;
167
168         if (s1 == NULL || s2 == NULL) return -1;
169         if (*s1 == '\0' || *s2 == '\0') return -1;
170
171         len1 = strlen(s1);
172         len2 = strlen(s2);
173
174         if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
175         if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
176
177         return strncmp(s1, s2, MAX(len1, len2));
178 }
179
180 /* remove trailing return code */
181 gchar *strretchomp(gchar *str)
182 {
183         register gchar *s;
184
185         if (!*str) return str;
186
187         for (s = str + strlen(str) - 1;
188              s >= str && (*s == '\n' || *s == '\r');
189              s--)
190                 *s = '\0';
191
192         return str;
193 }
194
195 /* Similar to `strstr' but this function ignores the case of both strings.  */
196 gchar *strcasestr(const gchar *haystack, const gchar *needle)
197 {
198         register size_t haystack_len, needle_len;
199
200         haystack_len = strlen(haystack);
201         needle_len   = strlen(needle);
202
203         if (haystack_len < needle_len || needle_len == 0)
204                 return NULL;
205
206         while (haystack_len >= needle_len) {
207                 if (!strncasecmp(haystack, needle, needle_len))
208                         return (gchar *)haystack;
209                 else {
210                         haystack++;
211                         haystack_len--;
212                 }
213         }
214
215         return NULL;
216 }
217
218 /* Copy no more than N characters of SRC to DEST, with NULL terminating.  */
219 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
220 {
221         register gchar c;
222         gchar *s = dest;
223
224         do {
225                 if (--n == 0) {
226                         *dest = '\0';
227                         return s;
228                 }
229                 c = *src++;
230                 *dest++ = c;
231         } while (c != '\0');
232
233         /* don't do zero fill */
234         return s;
235 }
236
237 #if !HAVE_ISWALNUM
238 int iswalnum(wint_t wc)
239 {
240         return isalnum((int)wc);
241 }
242 #endif
243
244 #if !HAVE_ISWSPACE
245 int iswspace(wint_t wc)
246 {
247         return isspace((int)wc);
248 }
249 #endif
250
251 #if !HAVE_TOWLOWER
252 wint_t towlower(wint_t wc)
253 {
254         if (wc >= L'A' && wc <= L'Z')
255                 return wc + L'a' - L'A';
256
257         return wc;
258 }
259 #endif
260
261 #if !HAVE_WCSLEN
262 size_t wcslen(const wchar_t *s)
263 {
264         size_t len = 0;
265
266         while (*s != L'\0')
267                 ++len, ++s;
268
269         return len;
270 }
271 #endif
272
273 #if !HAVE_WCSCPY
274 /* Copy SRC to DEST.  */
275 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
276 {
277         wint_t c;
278         wchar_t *s = dest;
279
280         do {
281                 c = *src++;
282                 *dest++ = c;
283         } while (c != L'\0');
284
285         return s;
286 }
287 #endif
288
289 #if !HAVE_WCSNCPY
290 /* Copy no more than N wide-characters of SRC to DEST.  */
291 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
292 {
293         wint_t c;
294         wchar_t *s = dest;
295
296         do {
297                 c = *src++;
298                 *dest++ = c;
299                 if (--n == 0)
300                         return s;
301         } while (c != L'\0');
302
303         /* zero fill */
304         do
305                 *dest++ = L'\0';
306         while (--n > 0);
307
308         return s;
309 }
310 #endif
311
312 /* Duplicate S, returning an identical malloc'd string. */
313 wchar_t *wcsdup(const wchar_t *s)
314 {
315         wchar_t *new_str;
316
317         if (s) {
318                 new_str = g_new(wchar_t, wcslen(s) + 1);
319                 wcscpy(new_str, s);
320         } else
321                 new_str = NULL;
322
323         return new_str;
324 }
325
326 /* Duplicate no more than N wide-characters of S,
327    returning an identical malloc'd string. */
328 wchar_t *wcsndup(const wchar_t *s, size_t n)
329 {
330         wchar_t *new_str;
331
332         if (s) {
333                 new_str = g_new(wchar_t, n + 1);
334                 wcsncpy(new_str, s, n);
335                 new_str[n] = (wchar_t)0;
336         } else
337                 new_str = NULL;
338
339         return new_str;
340 }
341
342 wchar_t *strdup_mbstowcs(const gchar *s)
343 {
344         wchar_t *new_str;
345
346         if (s) {
347                 new_str = g_new(wchar_t, strlen(s) + 1);
348                 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
349                         g_free(new_str);
350                         new_str = NULL;
351                 } else
352                         new_str = g_realloc(new_str,
353                                             sizeof(wchar_t) * (wcslen(new_str) + 1));
354         } else
355                 new_str = NULL;
356
357         return new_str;
358 }
359
360 gchar *strdup_wcstombs(const wchar_t *s)
361 {
362         gchar *new_str;
363         size_t len;
364
365         if (s) {
366                 len = wcslen(s) * MB_CUR_MAX + 1;
367                 new_str = g_new(gchar, len);
368                 if (wcstombs(new_str, s, len) < 0) {
369                         g_free(new_str);
370                         new_str = NULL;
371                 } else
372                         new_str = g_realloc(new_str, strlen(new_str) + 1);
373         } else
374                 new_str = NULL;
375
376         return new_str;
377 }
378
379 /* Compare S1 and S2, ignoring case.  */
380 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
381 {
382         wint_t c1;
383         wint_t c2;
384
385         while (n--) {
386                 c1 = towlower(*s1++);
387                 c2 = towlower(*s2++);
388                 if (c1 != c2)
389                         return c1 - c2;
390                 else if (c1 == 0 && c2 == 0)
391                         break;
392         }
393
394         return 0;
395 }
396
397 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case.  */
398 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
399 {
400         register size_t haystack_len, needle_len;
401
402         haystack_len = wcslen(haystack);
403         needle_len   = wcslen(needle);
404
405         if (haystack_len < needle_len || needle_len == 0)
406                 return NULL;
407
408         while (haystack_len >= needle_len) {
409                 if (!wcsncasecmp(haystack, needle, needle_len))
410                         return (wchar_t *)haystack;
411                 else {
412                         haystack++;
413                         haystack_len--;
414                 }
415         }
416
417         return NULL;
418 }
419
420 /* Examine if next block is non-ASCII string */
421 gboolean is_next_nonascii(const wchar_t *s)
422 {
423         const wchar_t *wp;
424
425         /* skip head space */
426         for (wp = s; *wp != (wchar_t)0 && iswspace(*wp); wp++)
427                 ;
428         for (; *wp != (wchar_t)0 && !iswspace(*wp); wp++) {
429                 if (*wp > 127)
430                         return TRUE;
431         }
432
433         return FALSE;
434 }
435
436 /* Examine if next block is multi-byte string */
437 gboolean is_next_mbs(const wchar_t *s)
438 {
439         gint mbl;
440         const wchar_t *wp;
441         gchar tmp[MB_CUR_MAX];
442
443         /* skip head space */
444         for (wp = s; *wp != (wchar_t)0 && iswspace(*wp); wp++)
445                 ;
446         for (; *wp != (wchar_t)0 && !iswspace(*wp); wp++) {
447                 mbl = wctomb(tmp, *wp);
448                 if (mbl > 1)
449                         return TRUE;
450         }
451
452         return FALSE;
453 }
454
455 wchar_t *find_wspace(const wchar_t *s)
456 {
457         const wchar_t *wp;
458
459         for (wp = s; *wp != (wchar_t)0 && iswspace(*wp); wp++)
460                 ;
461         for (; *wp != (wchar_t)0; wp++) {
462                 if (iswspace(*wp))
463                         return (wchar_t *)wp;
464         }
465
466         return NULL;
467 }
468
469 /* compare subjects */
470 gint subject_compare(const gchar *s1, const gchar *s2)
471 {
472         gint retval;
473         gchar *str1, *str2;
474
475         if (!s1 || !s2) return -1;
476         if (!*s1 || !*s2) return -1;
477
478         Xalloca(str1, strlen(s1) + 1, return -1);
479         Xalloca(str2, strlen(s2) + 1, return -1);
480         strcpy(str1, s1);
481         strcpy(str2, s2);
482
483         trim_subject(str1);
484         trim_subject(str2);
485
486         if (!*str1 || !*str2) return -1;
487
488         retval = strcmp(str1, str2);
489         //if (retval == 0)
490         //      g_print("\ns1 = %s\ns2 = %s\n"
491         //              "str1 = %s\nstr2 = %s\nmatched.\n",
492         //              s1, s2, str1, str2);
493
494         return retval;
495 }
496
497 void trim_subject(gchar *str)
498 {
499         gchar *srcp;
500
501         eliminate_parenthesis(str, '[', ']');
502         eliminate_parenthesis(str, '(', ')');
503         g_strstrip(str);
504
505         while (!strncasecmp(str, "Re:", 3)) {
506                 srcp = str + 3;
507                 while (isspace(*srcp)) srcp++;
508                 memmove(str, srcp, strlen(srcp) + 1);
509         }
510 }
511
512 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
513 {
514         register gchar *srcp, *destp;
515         gint in_brace;
516
517         srcp = destp = str;
518
519         while ((destp = strchr(destp, op))) {
520                 in_brace = 1;
521                 srcp = destp + 1;
522                 while (*srcp) {
523                         if (*srcp == op)
524                                 in_brace++;
525                         else if (*srcp == cl)
526                                 in_brace--;
527                         srcp++;
528                         if (in_brace == 0)
529                                 break;
530                 }
531                 while (isspace(*srcp)) srcp++;
532                 memmove(destp, srcp, strlen(srcp) + 1);
533         }
534 }
535
536 void extract_parenthesis(gchar *str, gchar op, gchar cl)
537 {
538         register gchar *srcp, *destp;
539         gint in_brace;
540
541         srcp = destp = str;
542
543         while ((srcp = strchr(destp, op))) {
544                 if (destp > str)
545                         *destp++ = ' ';
546                 memmove(destp, srcp + 1, strlen(srcp));
547                 in_brace = 1;
548                 while(*destp) {
549                         if (*destp == op)
550                                 in_brace++;
551                         else if (*destp == cl)
552                                 in_brace--;
553
554                         if (in_brace == 0)
555                                 break;
556
557                         destp++;
558                 }
559         }
560         *destp = '\0';
561 }
562
563 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
564                                          gchar op, gchar cl)
565 {
566         register gchar *srcp, *destp;
567         gint in_brace;
568         gboolean in_quote = FALSE;
569
570         srcp = destp = str;
571
572         while ((srcp = strchr_with_skip_quote(destp, '"', op))) {
573                 if (destp > str)
574                         *destp++ = ' ';
575                 memmove(destp, srcp + 1, strlen(srcp));
576                 in_brace = 1;
577                 while(*destp) {
578                         if (*destp == op && !in_quote)
579                                 in_brace++;
580                         else if (*destp == cl && !in_quote)
581                                 in_brace--;
582                         else if (*destp == quote_chr)
583                                 in_quote ^= TRUE;
584
585                         if (in_brace == 0)
586                                 break;
587
588                         destp++;
589                 }
590         }
591         *destp = '\0';
592 }
593
594 void eliminate_quote(gchar *str, gchar quote_chr)
595 {
596         register gchar *srcp, *destp;
597
598         srcp = destp = str;
599
600         while ((destp = strchr(destp, quote_chr))) {
601                 if ((srcp = strchr(destp + 1, quote_chr))) {
602                         srcp++;
603                         while (isspace(*srcp)) srcp++;
604                         memmove(destp, srcp, strlen(srcp) + 1);
605                 } else {
606                         *destp = '\0';
607                         break;
608                 }
609         }
610 }
611
612 void extract_quote(gchar *str, gchar quote_chr)
613 {
614         register gchar *p;
615
616         if ((str = strchr(str, quote_chr))) {
617                 if ((p = strchr(str + 1, quote_chr))) {
618                         *p = '\0';
619                         memmove(str, str + 1, p - str);
620                 }
621         }
622 }
623
624 void eliminate_address_comment(gchar *str)
625 {
626         register gchar *srcp, *destp;
627         gint in_brace;
628
629         srcp = destp = str;
630
631         while ((destp = strchr(destp, '"'))) {
632                 if ((srcp = strchr(destp + 1, '"'))) {
633                         srcp++;
634                         if (*srcp == '@') {
635                                 destp = srcp + 1;
636                         } else {
637                                 while (isspace(*srcp)) srcp++;
638                                 memmove(destp, srcp, strlen(srcp) + 1);
639                         }
640                 } else {
641                         *destp = '\0';
642                         break;
643                 }
644         }
645
646         srcp = destp = str;
647
648         while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
649                 in_brace = 1;
650                 srcp = destp + 1;
651                 while (*srcp) {
652                         if (*srcp == '(')
653                                 in_brace++;
654                         else if (*srcp == ')')
655                                 in_brace--;
656                         srcp++;
657                         if (in_brace == 0)
658                                 break;
659                 }
660                 while (isspace(*srcp)) srcp++;
661                 memmove(destp, srcp, strlen(srcp) + 1);
662         }
663 }
664
665 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
666 {
667         gboolean in_quote = FALSE;
668
669         while (*str) {
670                 if (*str == c && !in_quote)
671                         return (gchar *)str;
672                 if (*str == quote_chr)
673                         in_quote ^= TRUE;
674                 str++;
675         }
676
677         return NULL;
678 }
679
680 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
681 {
682         gboolean in_quote = FALSE;
683         const gchar *p;
684
685         p = str + strlen(str) - 1;
686         while (p >= str) {
687                 if (*p == c && !in_quote)
688                         return (gchar *)p;
689                 if (*p == quote_chr)
690                         in_quote ^= TRUE;
691                 p--;
692         }
693
694         return NULL;
695 }
696
697 void extract_address(gchar *str)
698 {
699         eliminate_address_comment(str);
700         if (strchr_with_skip_quote(str, '"', '<'))
701                 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
702         g_strstrip(str);
703 }
704
705 GSList *address_list_append(GSList *addr_list, const gchar *str)
706 {
707         gchar *work;
708         gchar *workp;
709
710         if (!str) return addr_list;
711
712         Xstrdup_a(work, str, return addr_list);
713
714         eliminate_address_comment(work);
715         workp = work;
716
717         while (workp && *workp) {
718                 gchar *p, *next;
719
720                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
721                         *p = '\0';
722                         next = p + 1;
723                 } else
724                         next = NULL;
725
726                 if (strchr_with_skip_quote(workp, '"', '<'))
727                         extract_parenthesis_with_skip_quote
728                                 (workp, '"', '<', '>');
729
730                 g_strstrip(workp);
731                 if (*workp)
732                         addr_list = g_slist_append(addr_list, g_strdup(workp));
733
734                 workp = next;
735         }
736
737         return addr_list;
738 }
739
740 GSList *references_list_append(GSList *msgid_list, const gchar *str)
741 {
742         const gchar *strp;
743
744         if (!str) return msgid_list;
745         strp = str;
746
747         while (strp && *strp) {
748                 const gchar *start, *end;
749                 gchar *msgid;
750
751                 if ((start = strchr(strp, '<')) != NULL) {
752                         end = strchr(start + 1, '>');
753                         if (!end) break;
754                 } else
755                         break;
756
757                 msgid = g_strndup(start + 1, end - start - 1);
758                 g_strstrip(msgid);
759                 if (*msgid)
760                         msgid_list = g_slist_append(msgid_list, msgid);
761                 else
762                         g_free(msgid);
763
764                 strp = end + 1;
765         }
766
767         return msgid_list;
768 }
769
770 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
771 {
772         gchar *work;
773         gchar *workp;
774
775         if (!str) return group_list;
776
777         Xstrdup_a(work, str, return group_list);
778
779         workp = work;
780
781         while (workp && *workp) {
782                 gchar *p, *next;
783
784                 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
785                         *p = '\0';
786                         next = p + 1;
787                 } else
788                         next = NULL;
789
790                 g_strstrip(workp);
791                 if (*workp)
792                         group_list = g_slist_append(group_list,
793                                                     g_strdup(workp));
794
795                 workp = next;
796         }
797
798         return group_list;
799 }
800
801 void remove_return(gchar *str)
802 {
803         register gchar *p = str;
804
805         while (*p) {
806                 if (*p == '\n' || *p == '\r')
807                         memmove(p, p + 1, strlen(p));
808                 else
809                         p++;
810         }
811 }
812
813 void remove_space(gchar *str)
814 {
815         register gchar *p = str;
816         register gint spc;
817
818         while (*p) {
819                 spc = 0;
820                 while (isspace(*(p + spc)))
821                         spc++;
822                 if (spc)
823                         memmove(p, p + spc, strlen(p + spc) + 1);
824                 else
825                         p++;
826         }
827 }
828
829 void subst_char(gchar *str, gchar orig, gchar subst)
830 {
831         register gchar *p = str;
832
833         while (*p) {
834                 if (*p == orig)
835                         *p = subst;
836                 p++;
837         }
838 }
839
840 gboolean is_header_line(const gchar *str)
841 {
842         if (str[0] == ':') return FALSE;
843
844         while (*str != '\0' && *str != ' ') {
845                 if (*str == ':')
846                         return TRUE;
847                 str++;
848         }
849
850         return FALSE;
851 }
852
853 gboolean is_ascii_str(const guchar *str)
854 {
855         while (*str != '\0') {
856                 if (*str != '\t' && *str != ' ' &&
857                     *str != '\r' && *str != '\n' &&
858                     (*str < 32 || *str >= 127))
859                         return FALSE;
860                 str++;
861         }
862
863         return TRUE;
864 }
865
866 gint get_quote_level(const gchar *str)
867 {
868         size_t firstquotepos;
869         size_t lastquotepos = -1;
870         const gchar *p = str;
871         const gchar *pos;
872         gint quotelevel = -1;
873         gint i = 0;
874
875         /* speed up line processing by only searching to the last '>' */
876         if ((pos = strchr(str, '>')) != NULL) {
877                 firstquotepos = pos - str;
878                 lastquotepos = strrchr(str, '>') - str + 1;
879
880                 /* skip a line if it contains a '<' before the initial '>' */
881                 if (memchr(str, '<', pos - str) != NULL)
882                         return -1;
883         } else
884                 return -1;
885
886         while (i < lastquotepos) {
887                 while (i < lastquotepos) {
888                         if (isspace(*p) || (*p == '\t')) {
889                                 p++;
890                                 i++;
891                         } else
892                                 break;
893                 }
894                 if (i >= lastquotepos)
895                         break;
896
897                 if (*p == '>')
898                         quotelevel++;
899                 else if ((*p != '-') && !isspace(*p) && (i < lastquotepos)) {
900                         /* any characters are allowed except '-' and space */
901                         while ((*p != '-') && (*p != '>') && !isspace(*p) &&
902                                (i < lastquotepos)) {
903                                 p++;
904                                 i++;
905                         }
906                         if (*p == '>')
907                                 quotelevel++;
908                         else if ((i >= lastquotepos) || isspace(*p))
909                                 break;
910                 }
911
912                 p++;
913                 i++;
914         }
915
916         return quotelevel;
917 }
918
919 GList *uri_list_extract_filenames(const gchar *uri_list)
920 {
921         GList *result = NULL;
922         const gchar *p, *q;
923         gchar *file;
924
925         p = uri_list;
926
927         while (p) {
928                 if (*p != '#') {
929                         while (isspace(*p)) p++;
930                         if (!strncmp(p, "file:", 5)) {
931                                 p += 5;
932                                 q = p;
933                                 while (*q && *q != '\n' && *q != '\r') q++;
934
935                                 if (q > p) {
936                                         q--;
937                                         while (q > p && isspace(*q)) q--;
938                                         file = g_malloc(q - p + 2);
939                                         strncpy(file, p, q - p + 1);
940                                         file[q - p + 1] = '\0';
941                                         result = g_list_append(result,file);
942                                 }
943                         }
944                 }
945                 p = strchr(p, '\n');
946                 if (p) p++;
947         }
948
949         return result;
950 }
951
952 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
953 {
954         register guint haystack_len, needle_len;
955         gboolean in_squote = FALSE, in_dquote = FALSE;
956
957         haystack_len = strlen(haystack);
958         needle_len   = strlen(needle);
959
960         if (haystack_len < needle_len || needle_len == 0)
961                 return NULL;
962
963         while (haystack_len >= needle_len) {
964                 if (!in_squote && !in_dquote &&
965                     !strncmp(haystack, needle, needle_len))
966                         return (gchar *)haystack;
967
968                 /* 'foo"bar"' -> foo"bar"
969                    "foo'bar'" -> foo'bar' */
970                 if (*haystack == '\'') {
971                         if (in_squote)
972                                 in_squote = FALSE;
973                         else if (!in_dquote)
974                                 in_squote = TRUE;
975                 } else if (*haystack == '\"') {
976                         if (in_dquote)
977                                 in_dquote = FALSE;
978                         else if (!in_squote)
979                                 in_dquote = TRUE;
980                 }
981
982                 haystack++;
983                 haystack_len--;
984         }
985
986         return NULL;
987 }
988
989 /* this fuction was taken from gstrfuncs.c in glib. */
990 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
991                             gint max_tokens)
992 {
993         GSList *string_list = NULL, *slist;
994         gchar **str_array, *s;
995         guint i, n = 1;
996
997         g_return_val_if_fail(str != NULL, NULL);
998         g_return_val_if_fail(delim != NULL, NULL);
999
1000         if (max_tokens < 1)
1001                 max_tokens = G_MAXINT;
1002
1003         s = strstr_with_skip_quote(str, delim);
1004         if (s) {
1005                 guint delimiter_len = strlen(delim);
1006
1007                 do {
1008                         guint len;
1009                         gchar *new_str;
1010
1011                         len = s - str;
1012                         new_str = g_new(gchar, len + 1);
1013                         strncpy(new_str, str, len);
1014                         new_str[len] = 0;
1015                         string_list = g_slist_prepend(string_list, new_str);
1016                         n++;
1017                         str = s + delimiter_len;
1018                         s = strstr_with_skip_quote(str, delim);
1019                 } while (--max_tokens && s);
1020         }
1021
1022         if (*str) {
1023                 n++;
1024                 string_list = g_slist_prepend(string_list, g_strdup(str));
1025         }
1026
1027         str_array = g_new(gchar*, n);
1028
1029         i = n - 1;
1030
1031         str_array[i--] = NULL;
1032         for (slist = string_list; slist; slist = slist->next)
1033                 str_array[i--] = slist->data;
1034
1035         g_slist_free(string_list);
1036
1037         return str_array;
1038 }
1039
1040 /*
1041  * We need this wrapper around g_get_home_dir(), so that
1042  * we can fix some Windoze things here.  Should be done in glibc of course
1043  * but as long as we are not able to do our own extensions to glibc, we do 
1044  * it here.
1045  */
1046 gchar *get_home_dir(void)
1047 {
1048 #if HAVE_DOSISH_SYSTEM
1049     static gchar *home_dir;
1050
1051     if (!home_dir) {
1052         home_dir = read_w32_registry_string(NULL,
1053                                             "Software\\Sylpheed", "HomeDir" );
1054         if (!home_dir || !*home_dir) {
1055             if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1056                 const char *s = g_get_home_dir();
1057                 if (s && *s)
1058                     home_dir = g_strdup (s);
1059             }
1060             if (!home_dir || !*home_dir) 
1061                 home_dir = g_strdup ("c:\\sylpheed");
1062         }
1063         debug_print("initialized home_dir to `%s'\n", home_dir);
1064     }
1065     return home_dir;
1066 #else /* standard glib */
1067     return g_get_home_dir();
1068 #endif
1069 }
1070
1071 gchar *get_rc_dir(void)
1072 {
1073         static gchar *rc_dir = NULL;
1074
1075         if (!rc_dir)
1076                 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1077                                      RC_DIR, NULL);
1078
1079         return rc_dir;
1080 }
1081
1082 gchar *get_news_cache_dir(void)
1083 {
1084         static gchar *news_cache_dir = NULL;
1085
1086         if (!news_cache_dir)
1087                 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1088                                              NEWS_CACHE_DIR, NULL);
1089
1090         return news_cache_dir;
1091 }
1092
1093 gchar *get_imap_cache_dir(void)
1094 {
1095         static gchar *imap_cache_dir = NULL;
1096
1097         if (!imap_cache_dir)
1098                 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1099                                              IMAP_CACHE_DIR, NULL);
1100
1101         return imap_cache_dir;
1102 }
1103
1104 gchar *get_mime_tmp_dir(void)
1105 {
1106         static gchar *mime_tmp_dir = NULL;
1107
1108         if (!mime_tmp_dir)
1109                 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1110                                            MIME_TMP_DIR, NULL);
1111
1112         return mime_tmp_dir;
1113 }
1114
1115 gchar *get_tmp_file(void)
1116 {
1117         static gchar *tmp_file = NULL;
1118
1119         if (!tmp_file)
1120                 tmp_file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1121                                        "tmpfile", NULL);
1122
1123         return tmp_file;
1124 }
1125
1126 gchar *get_domain_name(void)
1127 {
1128         static gchar *domain_name = NULL;
1129
1130         if (!domain_name) {
1131                 gchar buf[BUFFSIZE] = "";
1132
1133                 if (gethostname(buf, sizeof(buf)) < 0) {
1134                         perror("gethostname");
1135                         strcpy(buf, "unknown");
1136                 }
1137
1138                 domain_name = g_strdup(buf);
1139         }
1140
1141         return domain_name;
1142 }
1143
1144 off_t get_file_size(const gchar *file)
1145 {
1146         struct stat s;
1147
1148         if (stat(file, &s) < 0) {
1149                 FILE_OP_ERROR(file, "stat");
1150                 return -1;
1151         }
1152
1153         return s.st_size;
1154 }
1155
1156 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1157 {
1158         struct stat s;
1159
1160         if (stat(file, &s) < 0) {
1161                 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1162                 return FALSE;
1163         }
1164
1165         if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1166                 return TRUE;
1167
1168         return FALSE;
1169 }
1170
1171 gboolean is_dir_exist(const gchar *dir)
1172 {
1173         struct stat s;
1174
1175         if (stat(dir, &s) < 0) {
1176                 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1177                 return FALSE;
1178         }
1179
1180         if (S_ISDIR(s.st_mode))
1181                 return TRUE;
1182
1183         return FALSE;
1184 }
1185
1186 gint change_dir(const gchar *dir)
1187 {
1188         gchar *prevdir = NULL;
1189
1190         if (debug_mode)
1191                 prevdir = g_get_current_dir();
1192
1193         if (chdir(dir) < 0) {
1194                 FILE_OP_ERROR(dir, "chdir");
1195                 if (debug_mode) g_free(prevdir);
1196                 return -1;
1197         } else if (debug_mode) {
1198                 gchar *cwd;
1199
1200                 cwd = g_get_current_dir();
1201                 if (strcmp(prevdir, cwd) != 0)
1202                         g_print("current dir: %s\n", cwd);
1203                 g_free(cwd);
1204                 g_free(prevdir);
1205         }
1206
1207         return 0;
1208 }
1209
1210 gint make_dir_hier(const gchar *dir)
1211 {
1212         gchar *parent_dir;
1213         const gchar *p;
1214
1215         for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1216                 parent_dir = g_strndup(dir, p - dir);
1217                 if (*parent_dir != '\0') {
1218                         if (!is_dir_exist(parent_dir)) {
1219                                 if (mkdir(parent_dir, S_IRWXU) < 0) {
1220                                         FILE_OP_ERROR(parent_dir, "mkdir");
1221                                         g_free(parent_dir);
1222                                         return -1;
1223                                 }
1224                                 if (chmod(parent_dir, S_IRWXU) < 0)
1225                                         FILE_OP_ERROR(parent_dir, "chmod");
1226                         }
1227                 }
1228                 g_free(parent_dir);
1229         }
1230         if (!is_dir_exist(dir)) {
1231                 if (mkdir(dir, S_IRWXU) < 0) {
1232                         FILE_OP_ERROR(dir, "mkdir");
1233                         return -1;
1234                 }
1235                 if (chmod(dir, S_IRWXU) < 0)
1236                         FILE_OP_ERROR(dir, "chmod");
1237         }
1238
1239         return 0;
1240 }
1241
1242 gint remove_all_files(const gchar *dir)
1243 {
1244         DIR *dp;
1245         struct dirent *d;
1246         gchar *prev_dir;
1247
1248         prev_dir = g_get_current_dir();
1249
1250         if (chdir(dir) < 0) {
1251                 FILE_OP_ERROR(dir, "chdir");
1252                 return -1;
1253         }
1254
1255         if ((dp = opendir(".")) == NULL) {
1256                 FILE_OP_ERROR(dir, "opendir");
1257                 return -1;
1258         }
1259
1260         while ((d = readdir(dp)) != NULL) {
1261                 if (!strcmp(d->d_name, ".") ||
1262                     !strcmp(d->d_name, ".."))
1263                         continue;
1264
1265                 if (unlink(d->d_name) < 0)
1266                         FILE_OP_ERROR(d->d_name, "unlink");
1267         }
1268
1269         closedir(dp);
1270
1271         if (chdir(prev_dir) < 0) {
1272                 FILE_OP_ERROR(prev_dir, "chdir");
1273                 g_free(prev_dir);
1274                 return -1;
1275         }
1276
1277         g_free(prev_dir);
1278
1279         return 0;
1280 }
1281
1282 gint remove_dir_recursive(const gchar *dir)
1283 {
1284         struct stat s;
1285         DIR *dp;
1286         struct dirent *d;
1287         gchar *prev_dir;
1288
1289         //g_print("dir = %s\n", dir);
1290
1291         if (stat(dir, &s) < 0) {
1292                 FILE_OP_ERROR(dir, "stat");
1293                 if (ENOENT == errno) return 0;
1294                 return -1;
1295         }
1296
1297         if (!S_ISDIR(s.st_mode)) {
1298                 if (unlink(dir) < 0) {
1299                         FILE_OP_ERROR(dir, "unlink");
1300                         return -1;
1301                 }
1302
1303                 return 0;
1304         }
1305
1306         prev_dir = g_get_current_dir();
1307         //g_print("prev_dir = %s\n", prev_dir);
1308
1309         if (!path_cmp(prev_dir, dir)) {
1310                 g_free(prev_dir);
1311                 if (chdir("..") < 0) {
1312                         FILE_OP_ERROR(dir, "chdir");
1313                         return -1;
1314                 }
1315                 prev_dir = g_get_current_dir();
1316         }
1317
1318         if (chdir(dir) < 0) {
1319                 FILE_OP_ERROR(dir, "chdir");
1320                 g_free(prev_dir);
1321                 return -1;
1322         }
1323
1324         if ((dp = opendir(".")) == NULL) {
1325                 FILE_OP_ERROR(dir, "opendir");
1326                 chdir(prev_dir);
1327                 g_free(prev_dir);
1328                 return -1;
1329         }
1330
1331         /* remove all files in the directory */
1332         while ((d = readdir(dp)) != NULL) {
1333                 if (!strcmp(d->d_name, ".") ||
1334                     !strcmp(d->d_name, ".."))
1335                         continue;
1336
1337                 if (stat(d->d_name, &s) < 0) {
1338                         FILE_OP_ERROR(d->d_name, "stat");
1339                         continue;
1340                 }
1341
1342                 //g_print("removing %s\n", d->d_name);
1343
1344                 if (S_ISDIR(s.st_mode)) {
1345                         if (remove_dir_recursive(d->d_name) < 0) {
1346                                 g_warning("can't remove directory\n");
1347                                 return -1;
1348                         }
1349                 } else {
1350                         if (unlink(d->d_name) < 0)
1351                                 FILE_OP_ERROR(d->d_name, "unlink");
1352                 }
1353         }
1354
1355         closedir(dp);
1356
1357         if (chdir(prev_dir) < 0) {
1358                 FILE_OP_ERROR(prev_dir, "chdir");
1359                 g_free(prev_dir);
1360                 return -1;
1361         }
1362
1363         g_free(prev_dir);
1364
1365         if (rmdir(dir) < 0) {
1366                 FILE_OP_ERROR(dir, "rmdir");
1367                 return -1;
1368         }
1369
1370         return 0;
1371 }
1372
1373 #if 0
1374 /* this seems to be slower than the stdio version... */
1375 gint copy_file(const gchar *src, const gchar *dest)
1376 {
1377         gint src_fd, dest_fd;
1378         gint n_read;
1379         gint n_write;
1380         gchar buf[BUFSIZ];
1381         gchar *dest_bak = NULL;
1382
1383         if ((src_fd = open(src, O_RDONLY)) < 0) {
1384                 FILE_OP_ERROR(src, "open");
1385                 return -1;
1386         }
1387
1388         if (is_file_exist(dest)) {
1389                 dest_bak = g_strconcat(dest, ".bak", NULL);
1390                 if (rename(dest, dest_bak) < 0) {
1391                         FILE_OP_ERROR(dest, "rename");
1392                         close(src_fd);
1393                         g_free(dest_bak);
1394                         return -1;
1395                 }
1396         }
1397
1398         if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
1399                 FILE_OP_ERROR(dest, "open");
1400                 close(src_fd);
1401                 if (dest_bak) {
1402                         if (rename(dest_bak, dest) < 0)
1403                                 FILE_OP_ERROR(dest_bak, "rename");
1404                         g_free(dest_bak);
1405                 }
1406                 return -1;
1407         }
1408
1409         while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
1410                 gint len = n_read;
1411                 gchar *bufp = buf;
1412
1413                 while (len > 0) {
1414                         n_write = write(dest_fd, bufp, len);
1415                         if (n_write <= 0) {
1416                                 g_warning(_("writing to %s failed.\n"), dest);
1417                                 close(dest_fd);
1418                                 close(src_fd);
1419                                 unlink(dest);
1420                                 if (dest_bak) {
1421                                         if (rename(dest_bak, dest) < 0)
1422                                                 FILE_OP_ERROR(dest_bak, "rename");
1423                                         g_free(dest_bak);
1424                                 }
1425                                 return -1;
1426                         }
1427                         len -= n_write;
1428                         bufp += n_write;
1429                 }
1430         }
1431
1432         close(src_fd);
1433         close(dest_fd);
1434
1435         if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
1436                 g_warning(_("File copy from %s to %s failed.\n"), src, dest);
1437                 unlink(dest);
1438                 if (dest_bak) {
1439                         if (rename(dest_bak, dest) < 0)
1440                                 FILE_OP_ERROR(dest_bak, "rename");
1441                         g_free(dest_bak);
1442                 }
1443                 return -1;
1444         }
1445         g_free(dest_bak);
1446
1447         return 0;
1448 }
1449 #endif
1450
1451 gint copy_file(const gchar *src, const gchar *dest)
1452 {
1453         FILE *src_fp, *dest_fp;
1454         gint n_read;
1455         gchar buf[BUFSIZ];
1456         gchar *dest_bak = NULL;
1457         gboolean err = FALSE;
1458
1459         if ((src_fp = fopen(src, "r")) == NULL) {
1460                 FILE_OP_ERROR(src, "fopen");
1461                 return -1;
1462         }
1463         if (is_file_exist(dest)) {
1464                 dest_bak = g_strconcat(dest, ".bak", NULL);
1465                 if (rename(dest, dest_bak) < 0) {
1466                         FILE_OP_ERROR(dest, "rename");
1467                         fclose(src_fp);
1468                         g_free(dest_bak);
1469                         return -1;
1470                 }
1471         }
1472
1473         if ((dest_fp = fopen(dest, "w")) == NULL) {
1474                 FILE_OP_ERROR(dest, "fopen");
1475                 fclose(src_fp);
1476                 if (dest_bak) {
1477                         if (rename(dest_bak, dest) < 0)
1478                                 FILE_OP_ERROR(dest_bak, "rename");
1479                         g_free(dest_bak);
1480                 }
1481                 return -1;
1482         }
1483
1484         if (change_file_mode_rw(dest_fp, dest) < 0) {
1485                 FILE_OP_ERROR(dest, "chmod");
1486                 g_warning(_("can't change file mode\n"));
1487         }
1488
1489         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
1490                 if (n_read < sizeof(buf) && ferror(src_fp))
1491                         break;
1492                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
1493                         g_warning(_("writing to %s failed.\n"), dest);
1494                         fclose(dest_fp);
1495                         fclose(src_fp);
1496                         unlink(dest);
1497                         if (dest_bak) {
1498                                 if (rename(dest_bak, dest) < 0)
1499                                         FILE_OP_ERROR(dest_bak, "rename");
1500                                 g_free(dest_bak);
1501                         }
1502                         return -1;
1503                 }
1504         }
1505
1506         if (ferror(src_fp)) {
1507                 FILE_OP_ERROR(src, "fread");
1508                 err = TRUE;
1509         }
1510         fclose(src_fp);
1511         if (fclose(dest_fp) == EOF) {
1512                 FILE_OP_ERROR(dest, "fclose");
1513                 err = TRUE;
1514         }
1515
1516         if (err) {
1517                 unlink(dest);
1518                 if (dest_bak) {
1519                         if (rename(dest_bak, dest) < 0)
1520                                 FILE_OP_ERROR(dest_bak, "rename");
1521                         g_free(dest_bak);
1522                 }
1523                 return -1;
1524         }
1525
1526         g_free(dest_bak);
1527
1528         return 0;
1529 }
1530
1531 gint change_file_mode_rw(FILE *fp, const gchar *file)
1532 {
1533 #if HAVE_FCHMOD
1534         return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
1535 #else
1536         return chmod(file, S_IRUSR|S_IWUSR);
1537 #endif
1538 }
1539
1540 FILE *my_tmpfile(void)
1541 {
1542 #if HAVE_MKSTEMP
1543         const gchar suffix[] = ".XXXXXX";
1544         const gchar *tmpdir;
1545         guint tmplen;
1546         const gchar *progname;
1547         guint proglen;
1548         gchar *fname;
1549         gint fd;
1550         FILE *fp;
1551
1552         tmpdir = g_get_tmp_dir();
1553         tmplen = strlen(tmpdir);
1554         progname = g_get_prgname();
1555         proglen = strlen(progname);
1556         Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
1557                 return tmpfile());
1558
1559         memcpy(fname, tmpdir, tmplen);
1560         fname[tmplen] = G_DIR_SEPARATOR;
1561         memcpy(fname + tmplen + 1, progname, proglen);
1562         memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
1563
1564         fd = mkstemp(fname);
1565         if (fd < 0)
1566                 return tmpfile();
1567
1568         unlink(fname);
1569
1570         fp = fdopen(fd, "w+b");
1571         if (!fp)
1572                 close(fd);
1573         else
1574                 return fp;
1575 #endif /* HAVE_MKSTEMP */
1576
1577         return tmpfile();
1578 }
1579
1580 gint execute_async(gchar *const argv[])
1581 {
1582         pid_t pid;
1583
1584         if ((pid = fork()) < 0) {
1585                 perror("fork");
1586                 return -1;
1587         }
1588
1589         if (pid == 0) {                 /* child process */
1590                 pid_t gch_pid;
1591
1592                 if ((gch_pid = fork()) < 0) {
1593                         perror("fork");
1594                         _exit(1);
1595                 }
1596
1597                 if (gch_pid == 0) {     /* grandchild process */
1598                         execvp(argv[0], argv);
1599
1600                         perror("execvp");
1601                         _exit(1);
1602                 }
1603
1604                 _exit(0);
1605         }
1606
1607         waitpid(pid, NULL, 0);
1608
1609         return 0;
1610 }
1611
1612 gint execute_command_line(const gchar *cmdline)
1613 {
1614         gchar **argv;
1615         gint i;
1616         gint ret;
1617
1618         argv = strsplit_with_quote(cmdline, " ", 0);
1619
1620         for (i = 0; argv[i] != NULL; i++) {
1621                 gchar *str = argv[i];
1622
1623                 if (str[0] == '\'' || str[0] == '\"') {
1624                         gint len;
1625
1626                         len = strlen(str);
1627                         if (str[len - 1] == str[0]) {
1628                                 str[len - 1] = '\0';
1629                                 memmove(str, str + 1, len - 1);
1630                         }
1631                 }
1632         }
1633
1634         ret = execute_async(argv);
1635         g_strfreev(argv);
1636
1637         return ret;
1638 }
1639
1640 gint open_uri(const gchar *uri, const gchar *cmdline)
1641 {
1642         static gchar *default_cmdline = "netscape -remote openURL(%s,raise)";
1643         gchar buf[BUFFSIZE];
1644         gchar *p;
1645
1646         g_return_val_if_fail(uri != NULL, -1);
1647
1648         if (cmdline &&
1649             (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
1650             !strchr(p + 2, '%'))
1651                 g_snprintf(buf, sizeof(buf), cmdline, uri);
1652         else {
1653                 if (cmdline)
1654                         g_warning(_("Open URI command line is invalid: `%s'"),
1655                                   cmdline);
1656                 g_snprintf(buf, sizeof(buf), default_cmdline, uri);
1657         }
1658
1659         execute_command_line(buf);
1660
1661         return 0;
1662 }
1663
1664 time_t remote_tzoffset_sec(const gchar *zone)
1665 {
1666         static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
1667         gchar zone3[4];
1668         gchar *p;
1669         gchar c;
1670         gint iustz;
1671         gint h, m;
1672         time_t remoteoffset;
1673
1674         strncpy(zone3, zone, 3);
1675         zone3[3] = '\0';
1676         remoteoffset = 0;
1677
1678         if (sscanf(zone, "%c%2d%2d", &c, &h, &m) == 3 &&
1679             (c == '+' || c == '-')) {
1680                 remoteoffset = ((h * 60) + m) * 60;
1681                 if (c == '-')
1682                         remoteoffset = -remoteoffset;
1683         } else if (!strncmp(zone, "UT" , 2) ||
1684                    !strncmp(zone, "GMT", 2)) {
1685                 remoteoffset = 0;
1686         } else if (strlen(zone3) == 3 &&
1687                    (p = strstr(ustzstr, zone3)) != NULL &&
1688                    (p - ustzstr) % 3 == 0) {
1689                 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
1690                 remoteoffset = iustz * 3600;
1691         } else if (strlen(zone3) == 1) {
1692                 switch (zone[0]) {
1693                 case 'Z': remoteoffset =   0; break;
1694                 case 'A': remoteoffset =  -1; break;
1695                 case 'B': remoteoffset =  -2; break;
1696                 case 'C': remoteoffset =  -3; break;
1697                 case 'D': remoteoffset =  -4; break;
1698                 case 'E': remoteoffset =  -5; break;
1699                 case 'F': remoteoffset =  -6; break;
1700                 case 'G': remoteoffset =  -7; break;
1701                 case 'H': remoteoffset =  -8; break;
1702                 case 'I': remoteoffset =  -9; break;
1703                 case 'K': remoteoffset = -10; break; /* J is not used */
1704                 case 'L': remoteoffset = -11; break;
1705                 case 'M': remoteoffset = -12; break;
1706                 case 'N': remoteoffset =   1; break;
1707                 case 'O': remoteoffset =   2; break;
1708                 case 'P': remoteoffset =   3; break;
1709                 case 'Q': remoteoffset =   4; break;
1710                 case 'R': remoteoffset =   5; break;
1711                 case 'S': remoteoffset =   6; break;
1712                 case 'T': remoteoffset =   7; break;
1713                 case 'U': remoteoffset =   8; break;
1714                 case 'V': remoteoffset =   9; break;
1715                 case 'W': remoteoffset =  10; break;
1716                 case 'X': remoteoffset =  11; break;
1717                 case 'Y': remoteoffset =  12; break;
1718                 default:  remoteoffset =   0; break;
1719                 }
1720                 remoteoffset = remoteoffset * 3600;
1721         }
1722
1723         return remoteoffset;
1724 }
1725
1726 time_t tzoffset_sec(time_t *now)
1727 {
1728         struct tm gmt, *lt;
1729         gint off;
1730
1731         gmt = *gmtime(now);
1732         lt = localtime(now);
1733
1734         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
1735
1736         if (lt->tm_year < gmt.tm_year)
1737                 off -= 24 * 60;
1738         else if (lt->tm_year > gmt.tm_year)
1739                 off += 24 * 60;
1740         else if (lt->tm_yday < gmt.tm_yday)
1741                 off -= 24 * 60;
1742         else if (lt->tm_yday > gmt.tm_yday)
1743                 off += 24 * 60;
1744
1745         if (off >= 24 * 60)             /* should be impossible */
1746                 off = 23 * 60 + 59;     /* if not, insert silly value */
1747         if (off <= -24 * 60)
1748                 off = -(23 * 60 + 59);
1749         if (off > 12 * 60)
1750                 off -= 24 * 60;
1751         if (off < -12 * 60)
1752                 off += 24 * 60;
1753
1754         return off * 60;
1755 }
1756
1757 /* calculate timezone offset */
1758 gchar *tzoffset(time_t *now)
1759 {
1760         static gchar offset_string[6];
1761         struct tm gmt, *lt;
1762         gint off;
1763         gchar sign = '+';
1764
1765         gmt = *gmtime(now);
1766         lt = localtime(now);
1767
1768         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
1769
1770         if (lt->tm_year < gmt.tm_year)
1771                 off -= 24 * 60;
1772         else if (lt->tm_year > gmt.tm_year)
1773                 off += 24 * 60;
1774         else if (lt->tm_yday < gmt.tm_yday)
1775                 off -= 24 * 60;
1776         else if (lt->tm_yday > gmt.tm_yday)
1777                 off += 24 * 60;
1778
1779         if (off < 0) {
1780                 sign = '-';
1781                 off = -off;
1782         }
1783
1784         if (off >= 24 * 60)             /* should be impossible */
1785                 off = 23 * 60 + 59;     /* if not, insert silly value */
1786
1787         sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
1788
1789         return offset_string;
1790 }
1791
1792 void get_rfc822_date(gchar *buf, gint len)
1793 {
1794         struct tm *lt;
1795         time_t t;
1796         gchar day[4], mon[4];
1797         gint dd, hh, mm, ss, yyyy;
1798
1799         t = time(NULL);
1800         lt = localtime(&t);
1801
1802         sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
1803                day, mon, &dd, &hh, &mm, &ss, &yyyy);
1804         g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
1805                    day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
1806 }
1807
1808 void debug_print(const gchar *format, ...)
1809 {
1810         va_list args;
1811         gchar buf[BUFFSIZE];
1812
1813         if (!debug_mode) return;
1814
1815         va_start(args, format);
1816         g_vsnprintf(buf, sizeof(buf), format, args);
1817         va_end(args);
1818
1819         fputs(buf, stdout);
1820 }
1821
1822 void log_print(const gchar *format, ...)
1823 {
1824         va_list args;
1825         gchar buf[BUFFSIZE];
1826
1827         va_start(args, format);
1828         g_vsnprintf(buf, sizeof(buf), format, args);
1829         va_end(args);
1830
1831         if (debug_mode) fputs(buf, stdout);
1832         log_window_append(buf, LOG_NORMAL);
1833         statusbar_puts_all(buf);
1834 }
1835
1836 void log_message(const gchar *format, ...)
1837 {
1838         va_list args;
1839         gchar buf[BUFFSIZE];
1840
1841         va_start(args, format);
1842         g_vsnprintf(buf, sizeof(buf), format, args);
1843         va_end(args);
1844
1845         if (debug_mode) g_message("%s", buf);
1846         log_window_append(buf, LOG_MSG);
1847 }
1848
1849 void log_warning(const gchar *format, ...)
1850 {
1851         va_list args;
1852         gchar buf[BUFFSIZE];
1853
1854         va_start(args, format);
1855         g_vsnprintf(buf, sizeof(buf), format, args);
1856         va_end(args);
1857
1858         g_warning("%s", buf);
1859         log_window_append(buf, LOG_WARN);
1860 }
1861
1862 void log_error(const gchar *format, ...)
1863 {
1864         va_list args;
1865         gchar buf[BUFFSIZE];
1866
1867         va_start(args, format);
1868         g_vsnprintf(buf, sizeof(buf), format, args);
1869         va_end(args);
1870
1871         g_warning("%s", buf);
1872         log_window_append(buf, LOG_ERROR);
1873 }