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