added a directory doc-src that contains informations about implementation
[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 unfold_line(gchar *str)
830 {
831         register gchar *p = str;
832         register gint spc;
833
834         while (*p) {
835                 if (*p == '\n' || *p == '\r') {
836                         *p++ = ' ';
837                         spc = 0;
838                         while (isspace(*(p + spc)))
839                                 spc++;
840                         if (spc)
841                                 memmove(p, p + spc, strlen(p + spc) + 1);
842                 } else
843                         p++;
844         }
845 }
846
847 void subst_char(gchar *str, gchar orig, gchar subst)
848 {
849         register gchar *p = str;
850
851         while (*p) {
852                 if (*p == orig)
853                         *p = subst;
854                 p++;
855         }
856 }
857
858 gboolean is_header_line(const gchar *str)
859 {
860         if (str[0] == ':') return FALSE;
861
862         while (*str != '\0' && *str != ' ') {
863                 if (*str == ':')
864                         return TRUE;
865                 str++;
866         }
867
868         return FALSE;
869 }
870
871 gboolean is_ascii_str(const guchar *str)
872 {
873         while (*str != '\0') {
874                 if (*str != '\t' && *str != ' ' &&
875                     *str != '\r' && *str != '\n' &&
876                     (*str < 32 || *str >= 127))
877                         return FALSE;
878                 str++;
879         }
880
881         return TRUE;
882 }
883
884 gint get_quote_level(const gchar *str)
885 {
886         size_t firstquotepos;
887         size_t lastquotepos = -1;
888         const gchar *p = str;
889         const gchar *pos;
890         gint quotelevel = -1;
891         gint i = 0;
892
893         /* speed up line processing by only searching to the last '>' */
894         if ((pos = strchr(str, '>')) != NULL) {
895                 firstquotepos = pos - str;
896                 lastquotepos = strrchr(str, '>') - str + 1;
897
898                 /* skip a line if it contains a '<' before the initial '>' */
899                 if (memchr(str, '<', pos - str) != NULL)
900                         return -1;
901         } else
902                 return -1;
903
904         while (i < lastquotepos) {
905                 while (i < lastquotepos) {
906                         if (isspace(*p) || (*p == '\t')) {
907                                 p++;
908                                 i++;
909                         } else
910                                 break;
911                 }
912                 if (i >= lastquotepos)
913                         break;
914
915                 if (*p == '>')
916                         quotelevel++;
917                 else if ((*p != '-') && !isspace(*p) && (i < lastquotepos)) {
918                         /* any characters are allowed except '-' and space */
919                         while ((*p != '-') && (*p != '>') && !isspace(*p) &&
920                                (i < lastquotepos)) {
921                                 p++;
922                                 i++;
923                         }
924                         if (*p == '>')
925                                 quotelevel++;
926                         else if ((i >= lastquotepos) || isspace(*p))
927                                 break;
928                 }
929
930                 p++;
931                 i++;
932         }
933
934         return quotelevel;
935 }
936
937 GList *uri_list_extract_filenames(const gchar *uri_list)
938 {
939         GList *result = NULL;
940         const gchar *p, *q;
941         gchar *file;
942
943         p = uri_list;
944
945         while (p) {
946                 if (*p != '#') {
947                         while (isspace(*p)) p++;
948                         if (!strncmp(p, "file:", 5)) {
949                                 p += 5;
950                                 q = p;
951                                 while (*q && *q != '\n' && *q != '\r') q++;
952
953                                 if (q > p) {
954                                         q--;
955                                         while (q > p && isspace(*q)) q--;
956                                         file = g_malloc(q - p + 2);
957                                         strncpy(file, p, q - p + 1);
958                                         file[q - p + 1] = '\0';
959                                         result = g_list_append(result,file);
960                                 }
961                         }
962                 }
963                 p = strchr(p, '\n');
964                 if (p) p++;
965         }
966
967         return result;
968 }
969
970 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
971 {
972         register guint haystack_len, needle_len;
973         gboolean in_squote = FALSE, in_dquote = FALSE;
974
975         haystack_len = strlen(haystack);
976         needle_len   = strlen(needle);
977
978         if (haystack_len < needle_len || needle_len == 0)
979                 return NULL;
980
981         while (haystack_len >= needle_len) {
982                 if (!in_squote && !in_dquote &&
983                     !strncmp(haystack, needle, needle_len))
984                         return (gchar *)haystack;
985
986                 /* 'foo"bar"' -> foo"bar"
987                    "foo'bar'" -> foo'bar' */
988                 if (*haystack == '\'') {
989                         if (in_squote)
990                                 in_squote = FALSE;
991                         else if (!in_dquote)
992                                 in_squote = TRUE;
993                 } else if (*haystack == '\"') {
994                         if (in_dquote)
995                                 in_dquote = FALSE;
996                         else if (!in_squote)
997                                 in_dquote = TRUE;
998                 }
999
1000                 haystack++;
1001                 haystack_len--;
1002         }
1003
1004         return NULL;
1005 }
1006
1007 /* this fuction was taken from gstrfuncs.c in glib. */
1008 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1009                             gint max_tokens)
1010 {
1011         GSList *string_list = NULL, *slist;
1012         gchar **str_array, *s;
1013         guint i, n = 1;
1014
1015         g_return_val_if_fail(str != NULL, NULL);
1016         g_return_val_if_fail(delim != NULL, NULL);
1017
1018         if (max_tokens < 1)
1019                 max_tokens = G_MAXINT;
1020
1021         s = strstr_with_skip_quote(str, delim);
1022         if (s) {
1023                 guint delimiter_len = strlen(delim);
1024
1025                 do {
1026                         guint len;
1027                         gchar *new_str;
1028
1029                         len = s - str;
1030                         new_str = g_new(gchar, len + 1);
1031                         strncpy(new_str, str, len);
1032                         new_str[len] = 0;
1033                         string_list = g_slist_prepend(string_list, new_str);
1034                         n++;
1035                         str = s + delimiter_len;
1036                         s = strstr_with_skip_quote(str, delim);
1037                 } while (--max_tokens && s);
1038         }
1039
1040         if (*str) {
1041                 n++;
1042                 string_list = g_slist_prepend(string_list, g_strdup(str));
1043         }
1044
1045         str_array = g_new(gchar*, n);
1046
1047         i = n - 1;
1048
1049         str_array[i--] = NULL;
1050         for (slist = string_list; slist; slist = slist->next)
1051                 str_array[i--] = slist->data;
1052
1053         g_slist_free(string_list);
1054
1055         return str_array;
1056 }
1057
1058 /*
1059  * We need this wrapper around g_get_home_dir(), so that
1060  * we can fix some Windoze things here.  Should be done in glibc of course
1061  * but as long as we are not able to do our own extensions to glibc, we do 
1062  * it here.
1063  */
1064 gchar *get_home_dir(void)
1065 {
1066 #if HAVE_DOSISH_SYSTEM
1067     static gchar *home_dir;
1068
1069     if (!home_dir) {
1070         home_dir = read_w32_registry_string(NULL,
1071                                             "Software\\Sylpheed", "HomeDir" );
1072         if (!home_dir || !*home_dir) {
1073             if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1074                 const char *s = g_get_home_dir();
1075                 if (s && *s)
1076                     home_dir = g_strdup (s);
1077             }
1078             if (!home_dir || !*home_dir) 
1079                 home_dir = g_strdup ("c:\\sylpheed");
1080         }
1081         debug_print("initialized home_dir to `%s'\n", home_dir);
1082     }
1083     return home_dir;
1084 #else /* standard glib */
1085     return g_get_home_dir();
1086 #endif
1087 }
1088
1089 gchar *get_rc_dir(void)
1090 {
1091         static gchar *rc_dir = NULL;
1092
1093         if (!rc_dir)
1094                 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1095                                      RC_DIR, NULL);
1096
1097         return rc_dir;
1098 }
1099
1100 gchar *get_news_cache_dir(void)
1101 {
1102         static gchar *news_cache_dir = NULL;
1103
1104         if (!news_cache_dir)
1105                 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1106                                              NEWS_CACHE_DIR, NULL);
1107
1108         return news_cache_dir;
1109 }
1110
1111 gchar *get_imap_cache_dir(void)
1112 {
1113         static gchar *imap_cache_dir = NULL;
1114
1115         if (!imap_cache_dir)
1116                 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1117                                              IMAP_CACHE_DIR, NULL);
1118
1119         return imap_cache_dir;
1120 }
1121
1122 gchar *get_mime_tmp_dir(void)
1123 {
1124         static gchar *mime_tmp_dir = NULL;
1125
1126         if (!mime_tmp_dir)
1127                 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1128                                            MIME_TMP_DIR, NULL);
1129
1130         return mime_tmp_dir;
1131 }
1132
1133 gchar *get_tmp_file(void)
1134 {
1135         static gchar *tmp_file = NULL;
1136
1137         if (!tmp_file)
1138                 tmp_file = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1139                                        "tmpfile", NULL);
1140
1141         return tmp_file;
1142 }
1143
1144 gchar *get_domain_name(void)
1145 {
1146         static gchar *domain_name = NULL;
1147
1148         if (!domain_name) {
1149                 gchar buf[BUFFSIZE] = "";
1150
1151                 if (gethostname(buf, sizeof(buf)) < 0) {
1152                         perror("gethostname");
1153                         strcpy(buf, "unknown");
1154                 }
1155
1156                 domain_name = g_strdup(buf);
1157         }
1158
1159         return domain_name;
1160 }
1161
1162 off_t get_file_size(const gchar *file)
1163 {
1164         struct stat s;
1165
1166         if (stat(file, &s) < 0) {
1167                 FILE_OP_ERROR(file, "stat");
1168                 return -1;
1169         }
1170
1171         return s.st_size;
1172 }
1173
1174 off_t get_left_file_size(FILE *fp)
1175 {
1176         glong pos;
1177         glong end;
1178         off_t size;
1179
1180         if ((pos = ftell(fp)) < 0) {
1181                 perror("ftell");
1182                 return -1;
1183         }
1184         if (fseek(fp, 0L, SEEK_END) < 0) {
1185                 perror("fseek");
1186                 return -1;
1187         }
1188         if ((end = ftell(fp)) < 0) {
1189                 perror("fseek");
1190                 return -1;
1191         }
1192         size = end - pos;
1193         if (fseek(fp, pos, SEEK_SET) < 0) {
1194                 perror("fseek");
1195                 return -1;
1196         }
1197
1198         return size;
1199 }
1200
1201 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1202 {
1203         struct stat s;
1204
1205         if (stat(file, &s) < 0) {
1206                 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1207                 return FALSE;
1208         }
1209
1210         if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1211                 return TRUE;
1212
1213         return FALSE;
1214 }
1215
1216 gboolean is_dir_exist(const gchar *dir)
1217 {
1218         struct stat s;
1219
1220         if (stat(dir, &s) < 0) {
1221                 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1222                 return FALSE;
1223         }
1224
1225         if (S_ISDIR(s.st_mode))
1226                 return TRUE;
1227
1228         return FALSE;
1229 }
1230
1231 gint change_dir(const gchar *dir)
1232 {
1233         gchar *prevdir = NULL;
1234
1235         if (debug_mode)
1236                 prevdir = g_get_current_dir();
1237
1238         if (chdir(dir) < 0) {
1239                 FILE_OP_ERROR(dir, "chdir");
1240                 if (debug_mode) g_free(prevdir);
1241                 return -1;
1242         } else if (debug_mode) {
1243                 gchar *cwd;
1244
1245                 cwd = g_get_current_dir();
1246                 if (strcmp(prevdir, cwd) != 0)
1247                         g_print("current dir: %s\n", cwd);
1248                 g_free(cwd);
1249                 g_free(prevdir);
1250         }
1251
1252         return 0;
1253 }
1254
1255 gint make_dir_hier(const gchar *dir)
1256 {
1257         gchar *parent_dir;
1258         const gchar *p;
1259
1260         for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1261                 parent_dir = g_strndup(dir, p - dir);
1262                 if (*parent_dir != '\0') {
1263                         if (!is_dir_exist(parent_dir)) {
1264                                 if (mkdir(parent_dir, S_IRWXU) < 0) {
1265                                         FILE_OP_ERROR(parent_dir, "mkdir");
1266                                         g_free(parent_dir);
1267                                         return -1;
1268                                 }
1269                                 if (chmod(parent_dir, S_IRWXU) < 0)
1270                                         FILE_OP_ERROR(parent_dir, "chmod");
1271                         }
1272                 }
1273                 g_free(parent_dir);
1274         }
1275         if (!is_dir_exist(dir)) {
1276                 if (mkdir(dir, S_IRWXU) < 0) {
1277                         FILE_OP_ERROR(dir, "mkdir");
1278                         return -1;
1279                 }
1280                 if (chmod(dir, S_IRWXU) < 0)
1281                         FILE_OP_ERROR(dir, "chmod");
1282         }
1283
1284         return 0;
1285 }
1286
1287 gint remove_all_files(const gchar *dir)
1288 {
1289         DIR *dp;
1290         struct dirent *d;
1291         gchar *prev_dir;
1292
1293         prev_dir = g_get_current_dir();
1294
1295         if (chdir(dir) < 0) {
1296                 FILE_OP_ERROR(dir, "chdir");
1297                 return -1;
1298         }
1299
1300         if ((dp = opendir(".")) == NULL) {
1301                 FILE_OP_ERROR(dir, "opendir");
1302                 return -1;
1303         }
1304
1305         while ((d = readdir(dp)) != NULL) {
1306                 if (!strcmp(d->d_name, ".") ||
1307                     !strcmp(d->d_name, ".."))
1308                         continue;
1309
1310                 if (unlink(d->d_name) < 0)
1311                         FILE_OP_ERROR(d->d_name, "unlink");
1312         }
1313
1314         closedir(dp);
1315
1316         if (chdir(prev_dir) < 0) {
1317                 FILE_OP_ERROR(prev_dir, "chdir");
1318                 g_free(prev_dir);
1319                 return -1;
1320         }
1321
1322         g_free(prev_dir);
1323
1324         return 0;
1325 }
1326
1327 gint remove_dir_recursive(const gchar *dir)
1328 {
1329         struct stat s;
1330         DIR *dp;
1331         struct dirent *d;
1332         gchar *prev_dir;
1333
1334         //g_print("dir = %s\n", dir);
1335
1336         if (stat(dir, &s) < 0) {
1337                 FILE_OP_ERROR(dir, "stat");
1338                 if (ENOENT == errno) return 0;
1339                 return -1;
1340         }
1341
1342         if (!S_ISDIR(s.st_mode)) {
1343                 if (unlink(dir) < 0) {
1344                         FILE_OP_ERROR(dir, "unlink");
1345                         return -1;
1346                 }
1347
1348                 return 0;
1349         }
1350
1351         prev_dir = g_get_current_dir();
1352         //g_print("prev_dir = %s\n", prev_dir);
1353
1354         if (!path_cmp(prev_dir, dir)) {
1355                 g_free(prev_dir);
1356                 if (chdir("..") < 0) {
1357                         FILE_OP_ERROR(dir, "chdir");
1358                         return -1;
1359                 }
1360                 prev_dir = g_get_current_dir();
1361         }
1362
1363         if (chdir(dir) < 0) {
1364                 FILE_OP_ERROR(dir, "chdir");
1365                 g_free(prev_dir);
1366                 return -1;
1367         }
1368
1369         if ((dp = opendir(".")) == NULL) {
1370                 FILE_OP_ERROR(dir, "opendir");
1371                 chdir(prev_dir);
1372                 g_free(prev_dir);
1373                 return -1;
1374         }
1375
1376         /* remove all files in the directory */
1377         while ((d = readdir(dp)) != NULL) {
1378                 if (!strcmp(d->d_name, ".") ||
1379                     !strcmp(d->d_name, ".."))
1380                         continue;
1381
1382                 if (stat(d->d_name, &s) < 0) {
1383                         FILE_OP_ERROR(d->d_name, "stat");
1384                         continue;
1385                 }
1386
1387                 //g_print("removing %s\n", d->d_name);
1388
1389                 if (S_ISDIR(s.st_mode)) {
1390                         if (remove_dir_recursive(d->d_name) < 0) {
1391                                 g_warning("can't remove directory\n");
1392                                 return -1;
1393                         }
1394                 } else {
1395                         if (unlink(d->d_name) < 0)
1396                                 FILE_OP_ERROR(d->d_name, "unlink");
1397                 }
1398         }
1399
1400         closedir(dp);
1401
1402         if (chdir(prev_dir) < 0) {
1403                 FILE_OP_ERROR(prev_dir, "chdir");
1404                 g_free(prev_dir);
1405                 return -1;
1406         }
1407
1408         g_free(prev_dir);
1409
1410         if (rmdir(dir) < 0) {
1411                 FILE_OP_ERROR(dir, "rmdir");
1412                 return -1;
1413         }
1414
1415         return 0;
1416 }
1417
1418 #if 0
1419 /* this seems to be slower than the stdio version... */
1420 gint copy_file(const gchar *src, const gchar *dest)
1421 {
1422         gint src_fd, dest_fd;
1423         gint n_read;
1424         gint n_write;
1425         gchar buf[BUFSIZ];
1426         gchar *dest_bak = NULL;
1427
1428         if ((src_fd = open(src, O_RDONLY)) < 0) {
1429                 FILE_OP_ERROR(src, "open");
1430                 return -1;
1431         }
1432
1433         if (is_file_exist(dest)) {
1434                 dest_bak = g_strconcat(dest, ".bak", NULL);
1435                 if (rename(dest, dest_bak) < 0) {
1436                         FILE_OP_ERROR(dest, "rename");
1437                         close(src_fd);
1438                         g_free(dest_bak);
1439                         return -1;
1440                 }
1441         }
1442
1443         if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
1444                 FILE_OP_ERROR(dest, "open");
1445                 close(src_fd);
1446                 if (dest_bak) {
1447                         if (rename(dest_bak, dest) < 0)
1448                                 FILE_OP_ERROR(dest_bak, "rename");
1449                         g_free(dest_bak);
1450                 }
1451                 return -1;
1452         }
1453
1454         while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
1455                 gint len = n_read;
1456                 gchar *bufp = buf;
1457
1458                 while (len > 0) {
1459                         n_write = write(dest_fd, bufp, len);
1460                         if (n_write <= 0) {
1461                                 g_warning(_("writing to %s failed.\n"), dest);
1462                                 close(dest_fd);
1463                                 close(src_fd);
1464                                 unlink(dest);
1465                                 if (dest_bak) {
1466                                         if (rename(dest_bak, dest) < 0)
1467                                                 FILE_OP_ERROR(dest_bak, "rename");
1468                                         g_free(dest_bak);
1469                                 }
1470                                 return -1;
1471                         }
1472                         len -= n_write;
1473                         bufp += n_write;
1474                 }
1475         }
1476
1477         close(src_fd);
1478         close(dest_fd);
1479
1480         if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
1481                 g_warning(_("File copy from %s to %s failed.\n"), src, dest);
1482                 unlink(dest);
1483                 if (dest_bak) {
1484                         if (rename(dest_bak, dest) < 0)
1485                                 FILE_OP_ERROR(dest_bak, "rename");
1486                         g_free(dest_bak);
1487                 }
1488                 return -1;
1489         }
1490         g_free(dest_bak);
1491
1492         return 0;
1493 }
1494 #endif
1495
1496 gint copy_file(const gchar *src, const gchar *dest)
1497 {
1498         FILE *src_fp, *dest_fp;
1499         gint n_read;
1500         gchar buf[BUFSIZ];
1501         gchar *dest_bak = NULL;
1502         gboolean err = FALSE;
1503
1504         if ((src_fp = fopen(src, "r")) == NULL) {
1505                 FILE_OP_ERROR(src, "fopen");
1506                 return -1;
1507         }
1508         if (is_file_exist(dest)) {
1509                 dest_bak = g_strconcat(dest, ".bak", NULL);
1510                 if (rename(dest, dest_bak) < 0) {
1511                         FILE_OP_ERROR(dest, "rename");
1512                         fclose(src_fp);
1513                         g_free(dest_bak);
1514                         return -1;
1515                 }
1516         }
1517
1518         if ((dest_fp = fopen(dest, "w")) == NULL) {
1519                 FILE_OP_ERROR(dest, "fopen");
1520                 fclose(src_fp);
1521                 if (dest_bak) {
1522                         if (rename(dest_bak, dest) < 0)
1523                                 FILE_OP_ERROR(dest_bak, "rename");
1524                         g_free(dest_bak);
1525                 }
1526                 return -1;
1527         }
1528
1529         if (change_file_mode_rw(dest_fp, dest) < 0) {
1530                 FILE_OP_ERROR(dest, "chmod");
1531                 g_warning(_("can't change file mode\n"));
1532         }
1533
1534         while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
1535                 if (n_read < sizeof(buf) && ferror(src_fp))
1536                         break;
1537                 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
1538                         g_warning(_("writing to %s failed.\n"), dest);
1539                         fclose(dest_fp);
1540                         fclose(src_fp);
1541                         unlink(dest);
1542                         if (dest_bak) {
1543                                 if (rename(dest_bak, dest) < 0)
1544                                         FILE_OP_ERROR(dest_bak, "rename");
1545                                 g_free(dest_bak);
1546                         }
1547                         return -1;
1548                 }
1549         }
1550
1551         if (ferror(src_fp)) {
1552                 FILE_OP_ERROR(src, "fread");
1553                 err = TRUE;
1554         }
1555         fclose(src_fp);
1556         if (fclose(dest_fp) == EOF) {
1557                 FILE_OP_ERROR(dest, "fclose");
1558                 err = TRUE;
1559         }
1560
1561         if (err) {
1562                 unlink(dest);
1563                 if (dest_bak) {
1564                         if (rename(dest_bak, dest) < 0)
1565                                 FILE_OP_ERROR(dest_bak, "rename");
1566                         g_free(dest_bak);
1567                 }
1568                 return -1;
1569         }
1570
1571         g_free(dest_bak);
1572
1573         return 0;
1574 }
1575
1576 gint change_file_mode_rw(FILE *fp, const gchar *file)
1577 {
1578 #if HAVE_FCHMOD
1579         return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
1580 #else
1581         return chmod(file, S_IRUSR|S_IWUSR);
1582 #endif
1583 }
1584
1585 FILE *my_tmpfile(void)
1586 {
1587 #if HAVE_MKSTEMP
1588         const gchar suffix[] = ".XXXXXX";
1589         const gchar *tmpdir;
1590         guint tmplen;
1591         const gchar *progname;
1592         guint proglen;
1593         gchar *fname;
1594         gint fd;
1595         FILE *fp;
1596
1597         tmpdir = g_get_tmp_dir();
1598         tmplen = strlen(tmpdir);
1599         progname = g_get_prgname();
1600         proglen = strlen(progname);
1601         Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
1602                 return tmpfile());
1603
1604         memcpy(fname, tmpdir, tmplen);
1605         fname[tmplen] = G_DIR_SEPARATOR;
1606         memcpy(fname + tmplen + 1, progname, proglen);
1607         memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
1608
1609         fd = mkstemp(fname);
1610         if (fd < 0)
1611                 return tmpfile();
1612
1613         unlink(fname);
1614
1615         fp = fdopen(fd, "w+b");
1616         if (!fp)
1617                 close(fd);
1618         else
1619                 return fp;
1620 #endif /* HAVE_MKSTEMP */
1621
1622         return tmpfile();
1623 }
1624
1625 gint execute_async(gchar *const argv[])
1626 {
1627         pid_t pid;
1628
1629         if ((pid = fork()) < 0) {
1630                 perror("fork");
1631                 return -1;
1632         }
1633
1634         if (pid == 0) {                 /* child process */
1635                 pid_t gch_pid;
1636
1637                 if ((gch_pid = fork()) < 0) {
1638                         perror("fork");
1639                         _exit(1);
1640                 }
1641
1642                 if (gch_pid == 0) {     /* grandchild process */
1643                         execvp(argv[0], argv);
1644
1645                         perror("execvp");
1646                         _exit(1);
1647                 }
1648
1649                 _exit(0);
1650         }
1651
1652         waitpid(pid, NULL, 0);
1653
1654         return 0;
1655 }
1656
1657 gint execute_command_line(const gchar *cmdline)
1658 {
1659         gchar **argv;
1660         gint i;
1661         gint ret;
1662
1663         argv = strsplit_with_quote(cmdline, " ", 0);
1664
1665         for (i = 0; argv[i] != NULL; i++) {
1666                 gchar *str = argv[i];
1667
1668                 if (str[0] == '\'' || str[0] == '\"') {
1669                         gint len;
1670
1671                         len = strlen(str);
1672                         if (str[len - 1] == str[0]) {
1673                                 str[len - 1] = '\0';
1674                                 memmove(str, str + 1, len - 1);
1675                         }
1676                 }
1677         }
1678
1679         ret = execute_async(argv);
1680         g_strfreev(argv);
1681
1682         return ret;
1683 }
1684
1685 gint open_uri(const gchar *uri, const gchar *cmdline)
1686 {
1687         static gchar *default_cmdline = "netscape -remote openURL(%s,raise)";
1688         gchar buf[BUFFSIZE];
1689         gchar *p;
1690
1691         g_return_val_if_fail(uri != NULL, -1);
1692
1693         if (cmdline &&
1694             (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
1695             !strchr(p + 2, '%'))
1696                 g_snprintf(buf, sizeof(buf), cmdline, uri);
1697         else {
1698                 if (cmdline)
1699                         g_warning(_("Open URI command line is invalid: `%s'"),
1700                                   cmdline);
1701                 g_snprintf(buf, sizeof(buf), default_cmdline, uri);
1702         }
1703
1704         execute_command_line(buf);
1705
1706         return 0;
1707 }
1708
1709 time_t remote_tzoffset_sec(const gchar *zone)
1710 {
1711         static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
1712         gchar zone3[4];
1713         gchar *p;
1714         gchar c;
1715         gint iustz;
1716         gint h, m;
1717         time_t remoteoffset;
1718
1719         strncpy(zone3, zone, 3);
1720         zone3[3] = '\0';
1721         remoteoffset = 0;
1722
1723         if (sscanf(zone, "%c%2d%2d", &c, &h, &m) == 3 &&
1724             (c == '+' || c == '-')) {
1725                 remoteoffset = ((h * 60) + m) * 60;
1726                 if (c == '-')
1727                         remoteoffset = -remoteoffset;
1728         } else if (!strncmp(zone, "UT" , 2) ||
1729                    !strncmp(zone, "GMT", 2)) {
1730                 remoteoffset = 0;
1731         } else if (strlen(zone3) == 3 &&
1732                    (p = strstr(ustzstr, zone3)) != NULL &&
1733                    (p - ustzstr) % 3 == 0) {
1734                 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
1735                 remoteoffset = iustz * 3600;
1736         } else if (strlen(zone3) == 1) {
1737                 switch (zone[0]) {
1738                 case 'Z': remoteoffset =   0; break;
1739                 case 'A': remoteoffset =  -1; break;
1740                 case 'B': remoteoffset =  -2; break;
1741                 case 'C': remoteoffset =  -3; break;
1742                 case 'D': remoteoffset =  -4; break;
1743                 case 'E': remoteoffset =  -5; break;
1744                 case 'F': remoteoffset =  -6; break;
1745                 case 'G': remoteoffset =  -7; break;
1746                 case 'H': remoteoffset =  -8; break;
1747                 case 'I': remoteoffset =  -9; break;
1748                 case 'K': remoteoffset = -10; break; /* J is not used */
1749                 case 'L': remoteoffset = -11; break;
1750                 case 'M': remoteoffset = -12; break;
1751                 case 'N': remoteoffset =   1; break;
1752                 case 'O': remoteoffset =   2; break;
1753                 case 'P': remoteoffset =   3; break;
1754                 case 'Q': remoteoffset =   4; break;
1755                 case 'R': remoteoffset =   5; break;
1756                 case 'S': remoteoffset =   6; break;
1757                 case 'T': remoteoffset =   7; break;
1758                 case 'U': remoteoffset =   8; break;
1759                 case 'V': remoteoffset =   9; break;
1760                 case 'W': remoteoffset =  10; break;
1761                 case 'X': remoteoffset =  11; break;
1762                 case 'Y': remoteoffset =  12; break;
1763                 default:  remoteoffset =   0; break;
1764                 }
1765                 remoteoffset = remoteoffset * 3600;
1766         }
1767
1768         return remoteoffset;
1769 }
1770
1771 time_t tzoffset_sec(time_t *now)
1772 {
1773         struct tm gmt, *lt;
1774         gint off;
1775
1776         gmt = *gmtime(now);
1777         lt = localtime(now);
1778
1779         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
1780
1781         if (lt->tm_year < gmt.tm_year)
1782                 off -= 24 * 60;
1783         else if (lt->tm_year > gmt.tm_year)
1784                 off += 24 * 60;
1785         else if (lt->tm_yday < gmt.tm_yday)
1786                 off -= 24 * 60;
1787         else if (lt->tm_yday > gmt.tm_yday)
1788                 off += 24 * 60;
1789
1790         if (off >= 24 * 60)             /* should be impossible */
1791                 off = 23 * 60 + 59;     /* if not, insert silly value */
1792         if (off <= -24 * 60)
1793                 off = -(23 * 60 + 59);
1794         if (off > 12 * 60)
1795                 off -= 24 * 60;
1796         if (off < -12 * 60)
1797                 off += 24 * 60;
1798
1799         return off * 60;
1800 }
1801
1802 /* calculate timezone offset */
1803 gchar *tzoffset(time_t *now)
1804 {
1805         static gchar offset_string[6];
1806         struct tm gmt, *lt;
1807         gint off;
1808         gchar sign = '+';
1809
1810         gmt = *gmtime(now);
1811         lt = localtime(now);
1812
1813         off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
1814
1815         if (lt->tm_year < gmt.tm_year)
1816                 off -= 24 * 60;
1817         else if (lt->tm_year > gmt.tm_year)
1818                 off += 24 * 60;
1819         else if (lt->tm_yday < gmt.tm_yday)
1820                 off -= 24 * 60;
1821         else if (lt->tm_yday > gmt.tm_yday)
1822                 off += 24 * 60;
1823
1824         if (off < 0) {
1825                 sign = '-';
1826                 off = -off;
1827         }
1828
1829         if (off >= 24 * 60)             /* should be impossible */
1830                 off = 23 * 60 + 59;     /* if not, insert silly value */
1831
1832         sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
1833
1834         return offset_string;
1835 }
1836
1837 void get_rfc822_date(gchar *buf, gint len)
1838 {
1839         struct tm *lt;
1840         time_t t;
1841         gchar day[4], mon[4];
1842         gint dd, hh, mm, ss, yyyy;
1843
1844         t = time(NULL);
1845         lt = localtime(&t);
1846
1847         sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
1848                day, mon, &dd, &hh, &mm, &ss, &yyyy);
1849         g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
1850                    day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
1851 }
1852
1853 void debug_print(const gchar *format, ...)
1854 {
1855         va_list args;
1856         gchar buf[BUFFSIZE];
1857
1858         if (!debug_mode) return;
1859
1860         va_start(args, format);
1861         g_vsnprintf(buf, sizeof(buf), format, args);
1862         va_end(args);
1863
1864         fputs(buf, stdout);
1865 }
1866
1867 void log_print(const gchar *format, ...)
1868 {
1869         va_list args;
1870         gchar buf[BUFFSIZE];
1871
1872         va_start(args, format);
1873         g_vsnprintf(buf, sizeof(buf), format, args);
1874         va_end(args);
1875
1876         if (debug_mode) fputs(buf, stdout);
1877         log_window_append(buf, LOG_NORMAL);
1878         statusbar_puts_all(buf);
1879 }
1880
1881 void log_message(const gchar *format, ...)
1882 {
1883         va_list args;
1884         gchar buf[BUFFSIZE];
1885
1886         va_start(args, format);
1887         g_vsnprintf(buf, sizeof(buf), format, args);
1888         va_end(args);
1889
1890         if (debug_mode) g_message("%s", buf);
1891         log_window_append(buf, LOG_MSG);
1892 }
1893
1894 void log_warning(const gchar *format, ...)
1895 {
1896         va_list args;
1897         gchar buf[BUFFSIZE];
1898
1899         va_start(args, format);
1900         g_vsnprintf(buf, sizeof(buf), format, args);
1901         va_end(args);
1902
1903         g_warning("%s", buf);
1904         log_window_append(buf, LOG_WARN);
1905 }
1906
1907 void log_error(const gchar *format, ...)
1908 {
1909         va_list args;
1910         gchar buf[BUFFSIZE];
1911
1912         va_start(args, format);
1913         g_vsnprintf(buf, sizeof(buf), format, args);
1914         va_end(args);
1915
1916         g_warning("%s", buf);
1917         log_window_append(buf, LOG_ERROR);
1918 }