2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2003 Hiroyuki Yamamoto
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.
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.
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.
32 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
40 #include <sys/types.h>
51 static gboolean debug_mode = FALSE;
53 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
55 void list_free_strings(GList *list)
57 list = g_list_first(list);
59 while (list != NULL) {
65 void slist_free_strings(GSList *list)
67 while (list != NULL) {
73 GSList *slist_concat_unique (GSList *first, GSList *second)
81 } else if (second == NULL)
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);
91 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
96 void hash_free_strings(GHashTable *table)
98 g_hash_table_foreach(table, hash_free_strings_func, NULL);
101 static void hash_free_value_mem_func(gpointer key, gpointer value,
107 void hash_free_value_mem(GHashTable *table)
109 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
112 gint str_case_equal(gconstpointer v, gconstpointer v2)
114 return strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
117 guint str_case_hash(gconstpointer key)
119 const gchar *p = key;
124 for (p += 1; *p != '\0'; p++)
125 h = (h << 5) - h + tolower(*p);
131 void ptr_array_free_strings(GPtrArray *array)
136 g_return_if_fail(array != NULL);
138 for (i = 0; i < array->len; i++) {
139 str = g_ptr_array_index(array, i);
144 gint to_number(const gchar *nstr)
146 register const gchar *p;
148 if (*nstr == '\0') return -1;
150 for (p = nstr; *p != '\0'; p++)
151 if (!isdigit(*p)) return -1;
156 /* convert integer into string,
157 nstr must be not lower than 11 characters length */
158 gchar *itos_buf(gchar *nstr, gint n)
160 g_snprintf(nstr, 11, "%d", n);
164 /* convert integer into string */
167 static gchar nstr[11];
169 return itos_buf(nstr, n);
172 gchar *to_human_readable(off_t size)
174 static gchar str[10];
177 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
178 else if (size >> 10 < 1024)
179 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
180 else if (size >> 20 < 1024)
181 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
183 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
188 /* strcmp with NULL-checking */
189 gint strcmp2(const gchar *s1, const gchar *s2)
191 if (s1 == NULL || s2 == NULL)
194 return strcmp(s1, s2);
196 /* strstr with NULL-checking */
197 gchar *strstr2(const gchar *s1, const gchar *s2)
199 if (s1 == NULL || s2 == NULL)
202 return strstr(s1, s2);
205 gint path_cmp(const gchar *s1, const gchar *s2)
209 if (s1 == NULL || s2 == NULL) return -1;
210 if (*s1 == '\0' || *s2 == '\0') return -1;
215 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
216 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
218 return strncmp(s1, s2, MAX(len1, len2));
221 /* remove trailing return code */
222 gchar *strretchomp(gchar *str)
226 if (!*str) return str;
228 for (s = str + strlen(str) - 1;
229 s >= str && (*s == '\n' || *s == '\r');
236 /* remove trailing character */
237 gchar *strtailchomp(gchar *str, gchar tail_char)
241 if (!*str) return str;
242 if (tail_char == '\0') return str;
244 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
250 /* remove CR (carriage return) */
251 gchar *strcrchomp(gchar *str)
255 if (!*str) return str;
257 s = str + strlen(str) - 1;
258 if (*s == '\n' && s > str && *(s - 1) == '\r') {
266 /* Similar to `strstr' but this function ignores the case of both strings. */
267 gchar *strcasestr(const gchar *haystack, const gchar *needle)
269 register size_t haystack_len, needle_len;
271 haystack_len = strlen(haystack);
272 needle_len = strlen(needle);
274 if (haystack_len < needle_len || needle_len == 0)
277 while (haystack_len >= needle_len) {
278 if (!strncasecmp(haystack, needle, needle_len))
279 return (gchar *)haystack;
289 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
290 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
304 /* don't do zero fill */
309 int iswalnum(wint_t wc)
311 return isalnum((int)wc);
316 int iswspace(wint_t wc)
318 return isspace((int)wc);
323 wint_t towlower(wint_t wc)
325 if (wc >= L'A' && wc <= L'Z')
326 return wc + L'a' - L'A';
333 size_t wcslen(const wchar_t *s)
345 /* Copy SRC to DEST. */
346 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
354 } while (c != L'\0');
361 /* Copy no more than N wide-characters of SRC to DEST. */
362 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
372 } while (c != L'\0');
383 /* Duplicate S, returning an identical malloc'd string. */
384 wchar_t *wcsdup(const wchar_t *s)
389 new_str = g_new(wchar_t, wcslen(s) + 1);
397 /* Duplicate no more than N wide-characters of S,
398 returning an identical malloc'd string. */
399 wchar_t *wcsndup(const wchar_t *s, size_t n)
404 new_str = g_new(wchar_t, n + 1);
405 wcsncpy(new_str, s, n);
406 new_str[n] = (wchar_t)0;
413 wchar_t *strdup_mbstowcs(const gchar *s)
418 new_str = g_new(wchar_t, strlen(s) + 1);
419 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
423 new_str = g_realloc(new_str,
424 sizeof(wchar_t) * (wcslen(new_str) + 1));
431 gchar *strdup_wcstombs(const wchar_t *s)
437 len = wcslen(s) * MB_CUR_MAX + 1;
438 new_str = g_new(gchar, len);
439 if (wcstombs(new_str, s, len) < 0) {
443 new_str = g_realloc(new_str, strlen(new_str) + 1);
450 /* Compare S1 and S2, ignoring case. */
451 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
457 c1 = towlower(*s1++);
458 c2 = towlower(*s2++);
461 else if (c1 == 0 && c2 == 0)
468 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
469 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
471 register size_t haystack_len, needle_len;
473 haystack_len = wcslen(haystack);
474 needle_len = wcslen(needle);
476 if (haystack_len < needle_len || needle_len == 0)
479 while (haystack_len >= needle_len) {
480 if (!wcsncasecmp(haystack, needle, needle_len))
481 return (wchar_t *)haystack;
491 gint get_wcs_len(const gchar *s)
501 mb_len = mblen(p, MB_LEN_MAX);
515 /* Examine if next block is non-ASCII string */
516 gboolean is_next_nonascii(const guchar *s)
520 /* skip head space */
521 for (p = s; *p != '\0' && isspace(*p); p++)
523 for (; *p != '\0' && !isspace(*p); p++) {
524 if (*p > 127 || *p < 32)
531 gint get_next_word_len(const gchar *s)
535 for (; *s != '\0' && !isspace(*s); s++, len++)
541 /* compare subjects */
542 gint subject_compare(const gchar *s1, const gchar *s2)
546 if (!s1 || !s2) return -1;
547 if (!*s1 || !*s2) return -1;
549 Xstrdup_a(str1, s1, return -1);
550 Xstrdup_a(str2, s2, return -1);
552 trim_subject_for_compare(str1);
553 trim_subject_for_compare(str2);
555 if (!*str1 || !*str2) return -1;
557 return strcmp(str1, str2);
560 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
564 if (!s1 || !s2) return -1;
566 Xstrdup_a(str1, s1, return -1);
567 Xstrdup_a(str2, s2, return -1);
569 trim_subject_for_sort(str1);
570 trim_subject_for_sort(str2);
572 return strcasecmp(str1, str2);
575 void trim_subject_for_compare(gchar *str)
579 eliminate_parenthesis(str, '[', ']');
580 eliminate_parenthesis(str, '(', ')');
583 while (!strncasecmp(str, "Re:", 3)) {
585 while (isspace(*srcp)) srcp++;
586 memmove(str, srcp, strlen(srcp) + 1);
590 void trim_subject_for_sort(gchar *str)
596 while (!strncasecmp(str, "Re:", 3)) {
598 while (isspace(*srcp)) srcp++;
599 memmove(str, srcp, strlen(srcp) + 1);
603 void trim_subject(gchar *str)
605 register gchar *srcp, *destp;
610 while (!strncasecmp(destp, "Re:", 3)) {
612 while (isspace(*destp)) destp++;
618 } else if (*destp == '(') {
629 else if (*srcp == cl)
635 while (isspace(*srcp)) srcp++;
636 memmove(destp, srcp, strlen(srcp) + 1);
639 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
641 register gchar *srcp, *destp;
646 while ((destp = strchr(destp, op))) {
652 else if (*srcp == cl)
658 while (isspace(*srcp)) srcp++;
659 memmove(destp, srcp, strlen(srcp) + 1);
663 void extract_parenthesis(gchar *str, gchar op, gchar cl)
665 register gchar *srcp, *destp;
670 while ((srcp = strchr(destp, op))) {
673 memmove(destp, srcp + 1, strlen(srcp));
678 else if (*destp == cl)
690 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
693 register gchar *srcp, *destp;
695 gboolean in_quote = FALSE;
699 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
702 memmove(destp, srcp + 1, strlen(srcp));
705 if (*destp == op && !in_quote)
707 else if (*destp == cl && !in_quote)
709 else if (*destp == quote_chr)
721 void eliminate_quote(gchar *str, gchar quote_chr)
723 register gchar *srcp, *destp;
727 while ((destp = strchr(destp, quote_chr))) {
728 if ((srcp = strchr(destp + 1, quote_chr))) {
730 while (isspace(*srcp)) srcp++;
731 memmove(destp, srcp, strlen(srcp) + 1);
739 void extract_quote(gchar *str, gchar quote_chr)
743 if ((str = strchr(str, quote_chr))) {
745 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
746 memmove(p - 1, p, strlen(p) + 1);
751 memmove(str, str + 1, p - str);
756 void eliminate_address_comment(gchar *str)
758 register gchar *srcp, *destp;
763 while ((destp = strchr(destp, '"'))) {
764 if ((srcp = strchr(destp + 1, '"'))) {
769 while (isspace(*srcp)) srcp++;
770 memmove(destp, srcp, strlen(srcp) + 1);
780 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
786 else if (*srcp == ')')
792 while (isspace(*srcp)) srcp++;
793 memmove(destp, srcp, strlen(srcp) + 1);
797 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
799 gboolean in_quote = FALSE;
802 if (*str == c && !in_quote)
804 if (*str == quote_chr)
812 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
814 gboolean in_quote = FALSE;
817 p = str + strlen(str) - 1;
819 if (*p == c && !in_quote)
829 void extract_address(gchar *str)
831 eliminate_address_comment(str);
832 if (strchr_with_skip_quote(str, '"', '<'))
833 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
837 void extract_list_id_str(gchar *str)
839 if (strchr_with_skip_quote(str, '"', '<'))
840 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
844 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
849 if (!str) return addr_list;
851 Xstrdup_a(work, str, return addr_list);
854 eliminate_address_comment(work);
857 while (workp && *workp) {
860 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
866 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
867 extract_parenthesis_with_skip_quote
868 (workp, '"', '<', '>');
872 addr_list = g_slist_append(addr_list, g_strdup(workp));
880 GSList *address_list_append(GSList *addr_list, const gchar *str)
882 return address_list_append_real(addr_list, str, TRUE);
885 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
887 return address_list_append_real(addr_list, str, FALSE);
890 GSList *references_list_append(GSList *msgid_list, const gchar *str)
894 if (!str) return msgid_list;
897 while (strp && *strp) {
898 const gchar *start, *end;
901 if ((start = strchr(strp, '<')) != NULL) {
902 end = strchr(start + 1, '>');
907 msgid = g_strndup(start + 1, end - start - 1);
910 msgid_list = g_slist_append(msgid_list, msgid);
920 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
925 if (!str) return group_list;
927 Xstrdup_a(work, str, return group_list);
931 while (workp && *workp) {
934 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
942 group_list = g_slist_append(group_list,
951 GList *add_history(GList *list, const gchar *str)
955 g_return_val_if_fail(str != NULL, list);
957 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
960 list = g_list_remove(list, old->data);
961 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
964 last = g_list_last(list);
967 g_list_remove(list, last->data);
971 list = g_list_prepend(list, g_strdup(str));
976 void remove_return(gchar *str)
978 register gchar *p = str;
981 if (*p == '\n' || *p == '\r')
982 memmove(p, p + 1, strlen(p));
988 void remove_space(gchar *str)
990 register gchar *p = str;
995 while (isspace(*(p + spc)))
998 memmove(p, p + spc, strlen(p + spc) + 1);
1004 void unfold_line(gchar *str)
1006 register gchar *p = str;
1010 if (*p == '\n' || *p == '\r') {
1013 while (isspace(*(p + spc)))
1016 memmove(p, p + spc, strlen(p + spc) + 1);
1022 void subst_char(gchar *str, gchar orig, gchar subst)
1024 register gchar *p = str;
1033 void subst_chars(gchar *str, gchar *orig, gchar subst)
1035 register gchar *p = str;
1038 if (strchr(orig, *p) != NULL)
1044 void subst_for_filename(gchar *str)
1046 subst_chars(str, " \t\r\n\"/\\", '_');
1049 gboolean is_header_line(const gchar *str)
1051 if (str[0] == ':') return FALSE;
1053 while (*str != '\0' && *str != ' ') {
1062 gboolean is_ascii_str(const guchar *str)
1064 while (*str != '\0') {
1065 if (*str != '\t' && *str != ' ' &&
1066 *str != '\r' && *str != '\n' &&
1067 (*str < 32 || *str >= 127))
1075 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1077 const gchar *first_pos;
1078 const gchar *last_pos;
1079 const gchar *p = str;
1080 gint quote_level = -1;
1082 /* speed up line processing by only searching to the last '>' */
1083 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1084 /* skip a line if it contains a '<' before the initial '>' */
1085 if (memchr(str, '<', first_pos - str) != NULL)
1087 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1091 while (p <= last_pos) {
1092 while (p < last_pos) {
1099 if (strchr(quote_chars, *p))
1101 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1102 /* any characters are allowed except '-' and space */
1104 && !strchr(quote_chars, *p)
1108 if (strchr(quote_chars, *p))
1120 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1122 gchar * position = NULL;
1123 gchar * tmp_pos = NULL;
1126 if (quote_chars == NULL)
1129 for (i = 0; i < strlen(quote_chars); i++) {
1130 tmp_pos = strchr (str, quote_chars[i]);
1132 || (tmp_pos != NULL && position >= tmp_pos) )
1138 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1140 gchar * position = NULL;
1141 gchar * tmp_pos = NULL;
1144 if (quote_chars == NULL)
1147 for (i = 0; i < strlen(quote_chars); i++) {
1148 tmp_pos = strrchr (str, quote_chars[i]);
1150 || (tmp_pos != NULL && position <= tmp_pos) )
1156 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1158 register guint haystack_len, needle_len;
1159 gboolean in_squote = FALSE, in_dquote = FALSE;
1161 haystack_len = strlen(haystack);
1162 needle_len = strlen(needle);
1164 if (haystack_len < needle_len || needle_len == 0)
1167 while (haystack_len >= needle_len) {
1168 if (!in_squote && !in_dquote &&
1169 !strncmp(haystack, needle, needle_len))
1170 return (gchar *)haystack;
1172 /* 'foo"bar"' -> foo"bar"
1173 "foo'bar'" -> foo'bar' */
1174 if (*haystack == '\'') {
1177 else if (!in_dquote)
1179 } else if (*haystack == '\"') {
1182 else if (!in_squote)
1193 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1196 gchar quote_chr = '"';
1198 gboolean in_quote = FALSE;
1202 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1206 if (*p == op && !in_quote)
1208 else if (*p == cl && !in_quote)
1210 else if (*p == quote_chr)
1223 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1226 GSList *string_list = NULL, *slist;
1228 const gchar *s_op, *s_cl;
1231 g_return_val_if_fail(str != NULL, NULL);
1234 max_tokens = G_MAXINT;
1236 s_op = strchr_with_skip_quote(str, '"', op);
1237 if (!s_op) return NULL;
1239 s_cl = strchr_parenthesis_close(str, op, cl);
1247 new_string = g_new(gchar, len + 1);
1248 strncpy(new_string, str, len);
1249 new_string[len] = 0;
1250 string_list = g_slist_prepend(string_list, new_string);
1254 while (*str && isspace(*str)) str++;
1256 string_list = g_slist_prepend(string_list,
1259 s_op = strchr_with_skip_quote(str, '"', op);
1260 if (!--max_tokens || !s_op) break;
1264 s_cl = strchr_parenthesis_close(str, op, cl);
1265 } while (--max_tokens && s_cl);
1268 str_array = g_new(gchar*, n);
1272 str_array[i--] = NULL;
1273 for (slist = string_list; slist; slist = slist->next)
1274 str_array[i--] = slist->data;
1276 g_slist_free(string_list);
1281 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1284 GSList *string_list = NULL, *slist;
1285 gchar **str_array, *s, *new_str;
1286 guint i, n = 1, len;
1288 g_return_val_if_fail(str != NULL, NULL);
1289 g_return_val_if_fail(delim != NULL, NULL);
1292 max_tokens = G_MAXINT;
1294 s = strstr_with_skip_quote(str, delim);
1296 guint delimiter_len = strlen(delim);
1300 new_str = g_strndup(str, len);
1302 if (new_str[0] == '\'' || new_str[0] == '\"') {
1303 if (new_str[len - 1] == new_str[0]) {
1304 new_str[len - 1] = '\0';
1305 memmove(new_str, new_str + 1, len - 1);
1308 string_list = g_slist_prepend(string_list, new_str);
1310 str = s + delimiter_len;
1311 s = strstr_with_skip_quote(str, delim);
1312 } while (--max_tokens && s);
1316 new_str = g_strdup(str);
1317 if (new_str[0] == '\'' || new_str[0] == '\"') {
1319 if (new_str[len - 1] == new_str[0]) {
1320 new_str[len - 1] = '\0';
1321 memmove(new_str, new_str + 1, len - 1);
1324 string_list = g_slist_prepend(string_list, new_str);
1328 str_array = g_new(gchar*, n);
1332 str_array[i--] = NULL;
1333 for (slist = string_list; slist; slist = slist->next)
1334 str_array[i--] = slist->data;
1336 g_slist_free(string_list);
1341 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1343 gchar *abbrev_group;
1345 const gchar *p = group;
1348 g_return_val_if_fail(group != NULL, NULL);
1350 last = group + strlen(group);
1351 abbrev_group = ap = g_malloc(strlen(group) + 1);
1356 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1358 while (*p != '.') p++;
1361 return abbrev_group;
1366 return abbrev_group;
1369 gchar *trim_string(const gchar *str, gint len)
1371 const gchar *p = str;
1376 if (!str) return NULL;
1377 if (strlen(str) <= len)
1378 return g_strdup(str);
1380 while (*p != '\0') {
1381 mb_len = mblen(p, MB_LEN_MAX);
1384 else if (mb_len < 0)
1385 return g_strdup(str);
1386 else if (new_len + mb_len > len)
1393 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1394 return g_strconcat(new_str, "...", NULL);
1397 GList *uri_list_extract_filenames(const gchar *uri_list)
1399 GList *result = NULL;
1407 while (isspace(*p)) p++;
1408 if (!strncmp(p, "file:", 5)) {
1411 while (*q && *q != '\n' && *q != '\r') q++;
1415 while (q > p && isspace(*q)) q--;
1416 file = g_malloc(q - p + 2);
1417 strncpy(file, p, q - p + 1);
1418 file[q - p + 1] = '\0';
1419 result = g_list_append(result,file);
1423 p = strchr(p, '\n');
1430 #define HEX_TO_INT(val, hex) \
1434 if ('0' <= c && c <= '9') { \
1436 } else if ('a' <= c && c <= 'f') { \
1437 val = c - 'a' + 10; \
1438 } else if ('A' <= c && c <= 'F') { \
1439 val = c - 'A' + 10; \
1445 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1446 gchar **subject, gchar **body)
1451 Xstrdup_a(tmp_mailto, mailto, return -1);
1453 if (!strncmp(tmp_mailto, "mailto:", 7))
1456 p = strchr(tmp_mailto, '?');
1463 *to = g_strdup(tmp_mailto);
1466 gchar *field, *value;
1483 if (*value == '\0') continue;
1485 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1486 *cc = g_strdup(value);
1487 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1488 *bcc = g_strdup(value);
1489 } else if (subject && !*subject &&
1490 !g_strcasecmp(field, "subject")) {
1491 *subject = g_malloc(strlen(value) + 1);
1492 decode_uri(*subject, value);
1493 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1494 *body = g_malloc(strlen(value) + 1);
1495 decode_uri(*body, value);
1503 * We need this wrapper around g_get_home_dir(), so that
1504 * we can fix some Windoze things here. Should be done in glibc of course
1505 * but as long as we are not able to do our own extensions to glibc, we do
1508 gchar *get_home_dir(void)
1510 #if HAVE_DOSISH_SYSTEM
1511 static gchar *home_dir;
1514 home_dir = read_w32_registry_string(NULL,
1515 "Software\\Sylpheed", "HomeDir" );
1516 if (!home_dir || !*home_dir) {
1517 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1518 const char *s = g_get_home_dir();
1520 home_dir = g_strdup (s);
1522 if (!home_dir || !*home_dir)
1523 home_dir = g_strdup ("c:\\sylpheed");
1525 debug_print("initialized home_dir to `%s'\n", home_dir);
1528 #else /* standard glib */
1529 return g_get_home_dir();
1533 gchar *get_rc_dir(void)
1535 static gchar *rc_dir = NULL;
1538 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1544 gchar *get_news_cache_dir(void)
1546 static gchar *news_cache_dir = NULL;
1548 if (!news_cache_dir)
1549 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1550 NEWS_CACHE_DIR, NULL);
1552 return news_cache_dir;
1555 gchar *get_imap_cache_dir(void)
1557 static gchar *imap_cache_dir = NULL;
1559 if (!imap_cache_dir)
1560 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1561 IMAP_CACHE_DIR, NULL);
1563 return imap_cache_dir;
1566 gchar *get_mbox_cache_dir(void)
1568 static gchar *mbox_cache_dir = NULL;
1570 if (!mbox_cache_dir)
1571 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1572 MBOX_CACHE_DIR, NULL);
1574 return mbox_cache_dir;
1577 gchar *get_mime_tmp_dir(void)
1579 static gchar *mime_tmp_dir = NULL;
1582 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1583 MIME_TMP_DIR, NULL);
1585 return mime_tmp_dir;
1588 gchar *get_template_dir(void)
1590 static gchar *template_dir = NULL;
1593 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1594 TEMPLATE_DIR, NULL);
1596 return template_dir;
1599 gchar *get_header_cache_dir(void)
1601 static gchar *header_dir = NULL;
1604 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1605 HEADER_CACHE_DIR, NULL);
1610 gchar *get_tmp_dir(void)
1612 static gchar *tmp_dir = NULL;
1615 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1621 gchar *get_tmp_file(void)
1624 static guint32 id = 0;
1626 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1627 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1632 gchar *get_domain_name(void)
1634 static gchar *domain_name = NULL;
1637 gchar buf[128] = "";
1640 if (gethostname(buf, sizeof(buf)) < 0) {
1641 perror("gethostname");
1642 domain_name = "unknown";
1644 buf[sizeof(buf) - 1] = '\0';
1645 if ((hp = my_gethostbyname(buf)) == NULL) {
1646 perror("gethostbyname");
1647 domain_name = g_strdup(buf);
1649 domain_name = g_strdup(hp->h_name);
1653 debug_print("domain name = %s\n", domain_name);
1659 off_t get_file_size(const gchar *file)
1663 if (stat(file, &s) < 0) {
1664 FILE_OP_ERROR(file, "stat");
1671 off_t get_file_size_as_crlf(const gchar *file)
1675 gchar buf[BUFFSIZE];
1677 if ((fp = fopen(file, "rb")) == NULL) {
1678 FILE_OP_ERROR(file, "fopen");
1682 while (fgets(buf, sizeof(buf), fp) != NULL) {
1684 size += strlen(buf) + 2;
1688 FILE_OP_ERROR(file, "fgets");
1697 off_t get_left_file_size(FILE *fp)
1703 if ((pos = ftell(fp)) < 0) {
1707 if (fseek(fp, 0L, SEEK_END) < 0) {
1711 if ((end = ftell(fp)) < 0) {
1716 if (fseek(fp, pos, SEEK_SET) < 0) {
1724 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1731 if (stat(file, &s) < 0) {
1732 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1736 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1742 gboolean is_dir_exist(const gchar *dir)
1749 if (stat(dir, &s) < 0) {
1750 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1754 if (S_ISDIR(s.st_mode))
1760 gboolean is_file_entry_exist(const gchar *file)
1767 if (stat(file, &s) < 0) {
1768 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1775 gint change_dir(const gchar *dir)
1777 gchar *prevdir = NULL;
1780 prevdir = g_get_current_dir();
1782 if (chdir(dir) < 0) {
1783 FILE_OP_ERROR(dir, "chdir");
1784 if (debug_mode) g_free(prevdir);
1786 } else if (debug_mode) {
1789 cwd = g_get_current_dir();
1790 if (strcmp(prevdir, cwd) != 0)
1791 g_print("current dir: %s\n", cwd);
1799 gint make_dir(const gchar *dir)
1801 if (mkdir(dir, S_IRWXU) < 0) {
1802 FILE_OP_ERROR(dir, "mkdir");
1805 if (chmod(dir, S_IRWXU) < 0)
1806 FILE_OP_ERROR(dir, "chmod");
1811 gint make_dir_hier(const gchar *dir)
1816 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1817 parent_dir = g_strndup(dir, p - dir);
1818 if (*parent_dir != '\0') {
1819 if (!is_dir_exist(parent_dir)) {
1820 if (make_dir(parent_dir) < 0) {
1829 if (!is_dir_exist(dir)) {
1830 if (make_dir(dir) < 0)
1837 gint remove_all_files(const gchar *dir)
1843 prev_dir = g_get_current_dir();
1845 if (chdir(dir) < 0) {
1846 FILE_OP_ERROR(dir, "chdir");
1851 if ((dp = opendir(".")) == NULL) {
1852 FILE_OP_ERROR(dir, "opendir");
1857 while ((d = readdir(dp)) != NULL) {
1858 if (!strcmp(d->d_name, ".") ||
1859 !strcmp(d->d_name, ".."))
1862 if (unlink(d->d_name) < 0)
1863 FILE_OP_ERROR(d->d_name, "unlink");
1868 if (chdir(prev_dir) < 0) {
1869 FILE_OP_ERROR(prev_dir, "chdir");
1879 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1886 prev_dir = g_get_current_dir();
1888 if (chdir(dir) < 0) {
1889 FILE_OP_ERROR(dir, "chdir");
1894 if ((dp = opendir(".")) == NULL) {
1895 FILE_OP_ERROR(dir, "opendir");
1900 while ((d = readdir(dp)) != NULL) {
1901 fileno = to_number(d->d_name);
1902 if (fileno >= 0 && first <= fileno && fileno <= last) {
1903 if (is_dir_exist(d->d_name))
1905 if (unlink(d->d_name) < 0)
1906 FILE_OP_ERROR(d->d_name, "unlink");
1912 if (chdir(prev_dir) < 0) {
1913 FILE_OP_ERROR(prev_dir, "chdir");
1923 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1930 prev_dir = g_get_current_dir();
1932 if (chdir(dir) < 0) {
1933 FILE_OP_ERROR(dir, "chdir");
1938 if ((dp = opendir(".")) == NULL) {
1939 FILE_OP_ERROR(dir, "opendir");
1944 while ((d = readdir(dp)) != NULL) {
1945 fileno = to_number(d->d_name);
1946 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1947 debug_print("removing unwanted file %d from %s\n", fileno, dir);
1948 if (is_dir_exist(d->d_name))
1950 if (unlink(d->d_name) < 0)
1951 FILE_OP_ERROR(d->d_name, "unlink");
1957 if (chdir(prev_dir) < 0) {
1958 FILE_OP_ERROR(prev_dir, "chdir");
1968 gint remove_all_numbered_files(const gchar *dir)
1970 return remove_numbered_files(dir, 0, UINT_MAX);
1973 gint remove_expired_files(const gchar *dir, guint hours)
1980 time_t mtime, now, expire_time;
1982 prev_dir = g_get_current_dir();
1984 if (chdir(dir) < 0) {
1985 FILE_OP_ERROR(dir, "chdir");
1990 if ((dp = opendir(".")) == NULL) {
1991 FILE_OP_ERROR(dir, "opendir");
1997 expire_time = hours * 60 * 60;
1999 while ((d = readdir(dp)) != NULL) {
2000 fileno = to_number(d->d_name);
2002 if (stat(d->d_name, &s) < 0) {
2003 FILE_OP_ERROR(d->d_name, "stat");
2006 if (S_ISDIR(s.st_mode))
2008 mtime = MAX(s.st_mtime, s.st_atime);
2009 if (now - mtime > expire_time) {
2010 if (unlink(d->d_name) < 0)
2011 FILE_OP_ERROR(d->d_name, "unlink");
2018 if (chdir(prev_dir) < 0) {
2019 FILE_OP_ERROR(prev_dir, "chdir");
2029 gint remove_dir_recursive(const gchar *dir)
2036 /* g_print("dir = %s\n", dir); */
2038 if (stat(dir, &s) < 0) {
2039 FILE_OP_ERROR(dir, "stat");
2040 if (ENOENT == errno) return 0;
2044 if (!S_ISDIR(s.st_mode)) {
2045 if (unlink(dir) < 0) {
2046 FILE_OP_ERROR(dir, "unlink");
2053 prev_dir = g_get_current_dir();
2054 /* g_print("prev_dir = %s\n", prev_dir); */
2056 if (!path_cmp(prev_dir, dir)) {
2058 if (chdir("..") < 0) {
2059 FILE_OP_ERROR(dir, "chdir");
2062 prev_dir = g_get_current_dir();
2065 if (chdir(dir) < 0) {
2066 FILE_OP_ERROR(dir, "chdir");
2071 if ((dp = opendir(".")) == NULL) {
2072 FILE_OP_ERROR(dir, "opendir");
2078 /* remove all files in the directory */
2079 while ((d = readdir(dp)) != NULL) {
2080 if (!strcmp(d->d_name, ".") ||
2081 !strcmp(d->d_name, ".."))
2084 if (stat(d->d_name, &s) < 0) {
2085 FILE_OP_ERROR(d->d_name, "stat");
2089 /* g_print("removing %s\n", d->d_name); */
2091 if (S_ISDIR(s.st_mode)) {
2092 if (remove_dir_recursive(d->d_name) < 0) {
2093 g_warning("can't remove directory\n");
2097 if (unlink(d->d_name) < 0)
2098 FILE_OP_ERROR(d->d_name, "unlink");
2104 if (chdir(prev_dir) < 0) {
2105 FILE_OP_ERROR(prev_dir, "chdir");
2112 if (rmdir(dir) < 0) {
2113 FILE_OP_ERROR(dir, "rmdir");
2121 /* this seems to be slower than the stdio version... */
2122 gint copy_file(const gchar *src, const gchar *dest)
2124 gint src_fd, dest_fd;
2128 gchar *dest_bak = NULL;
2130 if ((src_fd = open(src, O_RDONLY)) < 0) {
2131 FILE_OP_ERROR(src, "open");
2135 if (is_file_exist(dest)) {
2136 dest_bak = g_strconcat(dest, ".bak", NULL);
2137 if (rename(dest, dest_bak) < 0) {
2138 FILE_OP_ERROR(dest, "rename");
2145 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2146 FILE_OP_ERROR(dest, "open");
2149 if (rename(dest_bak, dest) < 0)
2150 FILE_OP_ERROR(dest_bak, "rename");
2156 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2161 n_write = write(dest_fd, bufp, len);
2163 g_warning("writing to %s failed.\n", dest);
2168 if (rename(dest_bak, dest) < 0)
2169 FILE_OP_ERROR(dest_bak, "rename");
2182 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2183 g_warning("File copy from %s to %s failed.\n", src, dest);
2186 if (rename(dest_bak, dest) < 0)
2187 FILE_OP_ERROR(dest_bak, "rename");
2200 * Append src file body to the tail of dest file.
2201 * Now keep_backup has no effects.
2203 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2205 FILE *src_fp, *dest_fp;
2209 gboolean err = FALSE;
2211 if ((src_fp = fopen(src, "rb")) == NULL) {
2212 FILE_OP_ERROR(src, "fopen");
2216 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2217 FILE_OP_ERROR(dest, "fopen");
2222 if (change_file_mode_rw(dest_fp, dest) < 0) {
2223 FILE_OP_ERROR(dest, "chmod");
2224 g_warning("can't change file mode\n");
2227 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2228 if (n_read < sizeof(buf) && ferror(src_fp))
2230 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2231 g_warning("writing to %s failed.\n", dest);
2239 if (ferror(src_fp)) {
2240 FILE_OP_ERROR(src, "fread");
2244 if (fclose(dest_fp) == EOF) {
2245 FILE_OP_ERROR(dest, "fclose");
2257 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2259 FILE *src_fp, *dest_fp;
2262 gchar *dest_bak = NULL;
2263 gboolean err = FALSE;
2265 if ((src_fp = fopen(src, "rb")) == NULL) {
2266 FILE_OP_ERROR(src, "fopen");
2269 if (is_file_exist(dest)) {
2270 dest_bak = g_strconcat(dest, ".bak", NULL);
2271 if (rename(dest, dest_bak) < 0) {
2272 FILE_OP_ERROR(dest, "rename");
2279 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2280 FILE_OP_ERROR(dest, "fopen");
2283 if (rename(dest_bak, dest) < 0)
2284 FILE_OP_ERROR(dest_bak, "rename");
2290 if (change_file_mode_rw(dest_fp, dest) < 0) {
2291 FILE_OP_ERROR(dest, "chmod");
2292 g_warning("can't change file mode\n");
2295 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2296 if (n_read < sizeof(buf) && ferror(src_fp))
2298 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2299 g_warning("writing to %s failed.\n", dest);
2304 if (rename(dest_bak, dest) < 0)
2305 FILE_OP_ERROR(dest_bak, "rename");
2312 if (ferror(src_fp)) {
2313 FILE_OP_ERROR(src, "fread");
2317 if (fclose(dest_fp) == EOF) {
2318 FILE_OP_ERROR(dest, "fclose");
2325 if (rename(dest_bak, dest) < 0)
2326 FILE_OP_ERROR(dest_bak, "rename");
2332 if (keep_backup == FALSE && dest_bak)
2340 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2342 if (overwrite == FALSE && is_file_exist(dest)) {
2343 g_warning("move_file(): file %s already exists.", dest);
2347 if (rename(src, dest) == 0) return 0;
2349 if (EXDEV != errno) {
2350 FILE_OP_ERROR(src, "rename");
2354 if (copy_file(src, dest, FALSE) < 0) return -1;
2361 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2365 gint bytes_left, to_read;
2367 gboolean err = FALSE;
2369 if (fseek(fp, offset, SEEK_SET) < 0) {
2374 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2375 FILE_OP_ERROR(dest, "fopen");
2379 if (change_file_mode_rw(dest_fp, dest) < 0) {
2380 FILE_OP_ERROR(dest, "chmod");
2381 g_warning("can't change file mode\n");
2384 bytes_left = length;
2385 to_read = MIN(bytes_left, sizeof(buf));
2387 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2388 if (n_read < to_read && ferror(fp))
2390 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2391 g_warning("writing to %s failed.\n", dest);
2396 bytes_left -= n_read;
2397 if (bytes_left == 0)
2399 to_read = MIN(bytes_left, sizeof(buf));
2406 if (fclose(dest_fp) == EOF) {
2407 FILE_OP_ERROR(dest, "fclose");
2419 /* convert line endings into CRLF. If the last line doesn't end with
2420 * linebreak, add it.
2422 gchar *canonicalize_str(const gchar *str)
2428 for (p = str; *p != '\0'; ++p) {
2435 if (p == str || *(p - 1) != '\n')
2438 out = outp = g_malloc(new_len + 1);
2439 for (p = str; *p != '\0'; ++p) {
2446 if (p == str || *(p - 1) != '\n') {
2455 gint canonicalize_file(const gchar *src, const gchar *dest)
2457 FILE *src_fp, *dest_fp;
2458 gchar buf[BUFFSIZE];
2460 gboolean err = FALSE;
2461 gboolean last_linebreak = FALSE;
2463 if ((src_fp = fopen(src, "rb")) == NULL) {
2464 FILE_OP_ERROR(src, "fopen");
2468 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2469 FILE_OP_ERROR(dest, "fopen");
2474 if (change_file_mode_rw(dest_fp, dest) < 0) {
2475 FILE_OP_ERROR(dest, "chmod");
2476 g_warning("can't change file mode\n");
2479 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2483 if (len == 0) break;
2484 last_linebreak = FALSE;
2486 if (buf[len - 1] != '\n') {
2487 last_linebreak = TRUE;
2488 r = fputs(buf, dest_fp);
2489 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2490 r = fputs(buf, dest_fp);
2493 r = fwrite(buf, len - 1, 1, dest_fp);
2498 r = fputs("\r\n", dest_fp);
2502 g_warning("writing to %s failed.\n", dest);
2510 if (last_linebreak == TRUE) {
2511 if (fputs("\r\n", dest_fp) == EOF)
2515 if (ferror(src_fp)) {
2516 FILE_OP_ERROR(src, "fgets");
2520 if (fclose(dest_fp) == EOF) {
2521 FILE_OP_ERROR(dest, "fclose");
2533 gint canonicalize_file_replace(const gchar *file)
2537 tmp_file = get_tmp_file();
2539 if (canonicalize_file(file, tmp_file) < 0) {
2544 if (move_file(tmp_file, file, TRUE) < 0) {
2545 g_warning("can't replace %s .\n", file);
2555 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2557 FILE *src_fp, *dest_fp;
2558 gchar buf[BUFFSIZE];
2559 gboolean err = FALSE;
2561 if ((src_fp = fopen(src, "rb")) == NULL) {
2562 FILE_OP_ERROR(src, "fopen");
2566 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2567 FILE_OP_ERROR(dest, "fopen");
2572 if (change_file_mode_rw(dest_fp, dest) < 0) {
2573 FILE_OP_ERROR(dest, "chmod");
2574 g_warning("can't change file mode\n");
2577 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2579 if (fputs(buf, dest_fp) == EOF) {
2580 g_warning("writing to %s failed.\n", dest);
2588 if (ferror(src_fp)) {
2589 FILE_OP_ERROR(src, "fgets");
2593 if (fclose(dest_fp) == EOF) {
2594 FILE_OP_ERROR(dest, "fclose");
2606 gint uncanonicalize_file_replace(const gchar *file)
2610 tmp_file = get_tmp_file();
2612 if (uncanonicalize_file(file, tmp_file) < 0) {
2617 if (move_file(tmp_file, file, TRUE) < 0) {
2618 g_warning("can't replace %s .\n", file);
2628 gchar *normalize_newlines(const gchar *str)
2630 const gchar *p = str;
2633 out = outp = g_malloc(strlen(str) + 1);
2634 for (p = str; *p != '\0'; ++p) {
2636 if (*(p + 1) != '\n')
2647 gchar *get_outgoing_rfc2822_str(FILE *fp)
2649 gchar buf[BUFFSIZE];
2653 str = g_string_new(NULL);
2655 /* output header part */
2656 while (fgets(buf, sizeof(buf), fp) != NULL) {
2658 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2665 else if (next != ' ' && next != '\t') {
2669 if (fgets(buf, sizeof(buf), fp) == NULL)
2673 g_string_append(str, buf);
2674 g_string_append(str, "\r\n");
2680 /* output body part */
2681 while (fgets(buf, sizeof(buf), fp) != NULL) {
2684 g_string_append_c(str, '.');
2685 g_string_append(str, buf);
2686 g_string_append(str, "\r\n");
2690 g_string_free(str, FALSE);
2695 gint change_file_mode_rw(FILE *fp, const gchar *file)
2698 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2700 return chmod(file, S_IRUSR|S_IWUSR);
2704 FILE *my_tmpfile(void)
2707 const gchar suffix[] = ".XXXXXX";
2708 const gchar *tmpdir;
2710 const gchar *progname;
2716 tmpdir = get_tmp_dir();
2717 tmplen = strlen(tmpdir);
2718 progname = g_get_prgname();
2719 proglen = strlen(progname);
2720 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2723 memcpy(fname, tmpdir, tmplen);
2724 fname[tmplen] = G_DIR_SEPARATOR;
2725 memcpy(fname + tmplen + 1, progname, proglen);
2726 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2728 fd = mkstemp(fname);
2734 fp = fdopen(fd, "w+b");
2739 #endif /* HAVE_MKSTEMP */
2744 FILE *str_open_as_stream(const gchar *str)
2749 g_return_val_if_fail(str != NULL, NULL);
2753 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2758 if (len == 0) return fp;
2760 if (fwrite(str, len, 1, fp) != 1) {
2761 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2770 gint str_write_to_file(const gchar *str, const gchar *file)
2775 g_return_val_if_fail(str != NULL, -1);
2776 g_return_val_if_fail(file != NULL, -1);
2778 if ((fp = fopen(file, "wb")) == NULL) {
2779 FILE_OP_ERROR(file, "fopen");
2789 if (fwrite(str, len, 1, fp) != 1) {
2790 FILE_OP_ERROR(file, "fwrite");
2796 if (fclose(fp) == EOF) {
2797 FILE_OP_ERROR(file, "fclose");
2805 gchar *file_read_to_str(const gchar *file)
2810 g_return_val_if_fail(file != NULL, NULL);
2812 if ((fp = fopen(file, "rb")) == NULL) {
2813 FILE_OP_ERROR(file, "fopen");
2817 str = file_read_stream_to_str(fp);
2824 gchar *file_read_stream_to_str(FILE *fp)
2831 g_return_val_if_fail(fp != NULL, NULL);
2833 array = g_byte_array_new();
2835 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2836 if (n_read < sizeof(buf) && ferror(fp))
2838 g_byte_array_append(array, buf, n_read);
2842 FILE_OP_ERROR("file stream", "fread");
2843 g_byte_array_free(array, TRUE);
2848 g_byte_array_append(array, buf, 1);
2849 str = (gchar *)array->data;
2850 g_byte_array_free(array, FALSE);
2855 gint execute_async(gchar *const argv[])
2859 if ((pid = fork()) < 0) {
2864 if (pid == 0) { /* child process */
2867 if ((gch_pid = fork()) < 0) {
2872 if (gch_pid == 0) { /* grandchild process */
2873 execvp(argv[0], argv);
2882 waitpid(pid, NULL, 0);
2887 gint execute_sync(gchar *const argv[])
2891 if ((pid = fork()) < 0) {
2896 if (pid == 0) { /* child process */
2897 execvp(argv[0], argv);
2903 waitpid(pid, NULL, 0);
2908 gint execute_command_line(const gchar *cmdline, gboolean async)
2913 argv = strsplit_with_quote(cmdline, " ", 0);
2916 ret = execute_async(argv);
2918 ret = execute_sync(argv);
2924 gchar *get_command_output(const gchar *cmdline)
2926 gchar buf[BUFFSIZE];
2931 g_return_val_if_fail(cmdline != NULL, NULL);
2933 if ((fp = popen(cmdline, "r")) == NULL) {
2934 FILE_OP_ERROR(cmdline, "popen");
2938 str = g_string_new("");
2940 while (fgets(buf, sizeof(buf), fp) != NULL)
2941 g_string_append(str, buf);
2946 g_string_free(str, FALSE);
2951 static gint is_unchanged_uri_char(char c)
2963 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2969 for(i = 0; i < strlen(uri) ; i++) {
2970 if (is_unchanged_uri_char(uri[i])) {
2971 if (k + 2 >= bufsize)
2973 encoded_uri[k++] = uri[i];
2976 char * hexa = "0123456789ABCDEF";
2978 if (k + 4 >= bufsize)
2980 encoded_uri[k++] = '%';
2981 encoded_uri[k++] = hexa[uri[i] / 16];
2982 encoded_uri[k++] = hexa[uri[i] % 16];
2988 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
2991 static gint axtoi(const gchar *hexstr)
2993 gint hi, lo, result;
2996 if ('0' <= hi && hi <= '9') {
2999 if ('a' <= hi && hi <= 'f') {
3002 if ('A' <= hi && hi <= 'F') {
3007 if ('0' <= lo && lo <= '9') {
3010 if ('a' <= lo && lo <= 'f') {
3013 if ('A' <= lo && lo <= 'F') {
3016 result = lo + (16 * hi);
3021 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
3022 * plusses, and escape characters are used)
3025 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
3027 const gchar *encoded;
3030 encoded = encoded_uri;
3031 decoded = decoded_uri;
3034 if (*encoded == '%') {
3036 if (isxdigit(encoded[0])
3037 && isxdigit(encoded[1])) {
3038 *decoded = (gchar) axtoi(encoded);
3043 else if (*encoded == '+') {
3049 *decoded = *encoded;
3059 gint open_uri(const gchar *uri, const gchar *cmdline)
3061 gchar buf[BUFFSIZE];
3063 gchar encoded_uri[BUFFSIZE];
3065 g_return_val_if_fail(uri != NULL, -1);
3067 /* an option to choose whether to use encode_uri or not ? */
3068 encode_uri(encoded_uri, BUFFSIZE, uri);
3071 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3072 !strchr(p + 2, '%'))
3073 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3076 g_warning("Open URI command line is invalid: `%s'",
3078 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3081 execute_command_line(buf, TRUE);
3086 time_t remote_tzoffset_sec(const gchar *zone)
3088 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3094 time_t remoteoffset;
3096 strncpy(zone3, zone, 3);
3100 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3101 (c == '+' || c == '-')) {
3102 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3104 remoteoffset = -remoteoffset;
3105 } else if (!strncmp(zone, "UT" , 2) ||
3106 !strncmp(zone, "GMT", 2)) {
3108 } else if (strlen(zone3) == 3 &&
3109 (p = strstr(ustzstr, zone3)) != NULL &&
3110 (p - ustzstr) % 3 == 0) {
3111 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3112 remoteoffset = iustz * 3600;
3113 } else if (strlen(zone3) == 1) {
3115 case 'Z': remoteoffset = 0; break;
3116 case 'A': remoteoffset = -1; break;
3117 case 'B': remoteoffset = -2; break;
3118 case 'C': remoteoffset = -3; break;
3119 case 'D': remoteoffset = -4; break;
3120 case 'E': remoteoffset = -5; break;
3121 case 'F': remoteoffset = -6; break;
3122 case 'G': remoteoffset = -7; break;
3123 case 'H': remoteoffset = -8; break;
3124 case 'I': remoteoffset = -9; break;
3125 case 'K': remoteoffset = -10; break; /* J is not used */
3126 case 'L': remoteoffset = -11; break;
3127 case 'M': remoteoffset = -12; break;
3128 case 'N': remoteoffset = 1; break;
3129 case 'O': remoteoffset = 2; break;
3130 case 'P': remoteoffset = 3; break;
3131 case 'Q': remoteoffset = 4; break;
3132 case 'R': remoteoffset = 5; break;
3133 case 'S': remoteoffset = 6; break;
3134 case 'T': remoteoffset = 7; break;
3135 case 'U': remoteoffset = 8; break;
3136 case 'V': remoteoffset = 9; break;
3137 case 'W': remoteoffset = 10; break;
3138 case 'X': remoteoffset = 11; break;
3139 case 'Y': remoteoffset = 12; break;
3140 default: remoteoffset = 0; break;
3142 remoteoffset = remoteoffset * 3600;
3145 return remoteoffset;
3148 time_t tzoffset_sec(time_t *now)
3154 lt = localtime(now);
3156 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3158 if (lt->tm_year < gmt.tm_year)
3160 else if (lt->tm_year > gmt.tm_year)
3162 else if (lt->tm_yday < gmt.tm_yday)
3164 else if (lt->tm_yday > gmt.tm_yday)
3167 if (off >= 24 * 60) /* should be impossible */
3168 off = 23 * 60 + 59; /* if not, insert silly value */
3169 if (off <= -24 * 60)
3170 off = -(23 * 60 + 59);
3175 /* calculate timezone offset */
3176 gchar *tzoffset(time_t *now)
3178 static gchar offset_string[6];
3184 lt = localtime(now);
3186 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3188 if (lt->tm_year < gmt.tm_year)
3190 else if (lt->tm_year > gmt.tm_year)
3192 else if (lt->tm_yday < gmt.tm_yday)
3194 else if (lt->tm_yday > gmt.tm_yday)
3202 if (off >= 24 * 60) /* should be impossible */
3203 off = 23 * 60 + 59; /* if not, insert silly value */
3205 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3207 return offset_string;
3210 void get_rfc822_date(gchar *buf, gint len)
3214 gchar day[4], mon[4];
3215 gint dd, hh, mm, ss, yyyy;
3220 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3221 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3222 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3223 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3226 void debug_set_mode(gboolean mode)
3231 gboolean debug_get_mode()
3236 void debug_print_real(const gchar *format, ...)
3239 gchar buf[BUFFSIZE];
3241 if (!debug_mode) return;
3243 va_start(args, format);
3244 g_vsnprintf(buf, sizeof(buf), format, args);
3250 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3252 if (subject == NULL)
3255 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3256 return g_hash_table_lookup(subject_table, subject + 4);
3258 return g_hash_table_lookup(subject_table, subject);
3261 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3264 if (subject == NULL)
3268 if (g_strcasecmp(subject, "Re:") == 0)
3270 if (g_strcasecmp(subject, "Re: ") == 0)
3273 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3274 g_hash_table_insert(subject_table, subject + 4, data);
3276 g_hash_table_insert(subject_table, subject, data);
3279 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3281 if (subject == NULL)
3284 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3285 g_hash_table_remove(subject_table, subject + 4);
3287 g_hash_table_remove(subject_table, subject);
3290 gboolean subject_is_reply(const gchar *subject)
3292 /* XXX: just simply here so someone can handle really
3293 * advanced Re: detection like "Re[4]", "ANTW:" or
3294 * Re: Re: Re: Re: Re: Re: Re: Re:" stuff. */
3295 if (subject == NULL) return FALSE;
3296 else return 0 == g_strncasecmp(subject, "Re: ", 4);
3299 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
3303 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
3304 fd = mkstemp(*filename);
3306 return fdopen(fd, "w+");
3309 /* allow Mutt-like patterns in quick search */
3310 gchar *expand_search_string(const gchar *search_string)
3313 gchar term_char, save_char;
3314 gchar *cmd_start, *cmd_end;
3315 GString *matcherstr;
3316 gchar *returnstr = NULL;
3318 gboolean casesens, dontmatch;
3319 /* list of allowed pattern abbreviations */
3321 gchar *abbreviated; /* abbreviation */
3322 gchar *command; /* actual matcher command */
3323 gint numparams; /* number of params for cmd */
3324 gboolean qualifier; /* do we append regexpcase */
3325 gboolean quotes; /* do we need quotes */
3328 { "a", "all", 0, FALSE, FALSE },
3329 { "ag", "age_greater", 1, FALSE, FALSE },
3330 { "al", "age_lower", 1, FALSE, FALSE },
3331 { "b", "body_part", 1, TRUE, TRUE },
3332 { "B", "message", 1, TRUE, TRUE },
3333 { "c", "cc", 1, TRUE, TRUE },
3334 { "C", "to_or_cc", 1, TRUE, TRUE },
3335 { "D", "deleted", 0, FALSE, FALSE },
3336 { "e", "header \"Sender\"", 1, TRUE, TRUE },
3337 { "E", "execute", 1, FALSE, TRUE },
3338 { "f", "from", 1, TRUE, TRUE },
3339 { "F", "forwarded", 0, FALSE, FALSE },
3340 { "h", "headers_part", 1, TRUE, TRUE },
3341 { "i", "header \"Message-Id\"", 1, TRUE, TRUE },
3342 { "I", "inreplyto", 1, TRUE, TRUE },
3343 { "L", "locked", 0, FALSE, FALSE },
3344 { "n", "newsgroups", 1, TRUE, TRUE },
3345 { "N", "new", 0, FALSE, FALSE },
3346 { "O", "~new", 0, FALSE, FALSE },
3347 { "r", "replied", 0, FALSE, FALSE },
3348 { "R", "~unread", 0, FALSE, FALSE },
3349 { "s", "subject", 1, TRUE, TRUE },
3350 { "se", "score_equal", 1, FALSE, FALSE },
3351 { "sg", "score_greater", 1, FALSE, FALSE },
3352 { "sl", "score_lower", 1, FALSE, FALSE },
3353 { "Se", "size_equal", 1, FALSE, FALSE },
3354 { "Sg", "size_greater", 1, FALSE, FALSE },
3355 { "Ss", "size_smaller", 1, FALSE, FALSE },
3356 { "t", "to", 1, TRUE, TRUE },
3357 { "T", "marked", 0, FALSE, FALSE },
3358 { "U", "unread", 0, FALSE, FALSE },
3359 { "x", "header \"References\"", 1, TRUE, TRUE },
3360 { "y", "header \"X-Label\"", 1, TRUE, TRUE },
3361 { "&", "&", 0, FALSE, FALSE },
3362 { "|", "|", 0, FALSE, FALSE },
3363 { NULL, NULL, 0, FALSE, FALSE }
3366 if (search_string == NULL)
3369 copy_str = g_strdup(search_string);
3371 /* if it's a full command don't process it so users
3372 can still do something like from regexpcase "foo" */
3373 for (i = 0; cmds[i].command; i++) {
3374 const gchar *tmp_search_string = search_string;
3375 cmd_start = cmds[i].command;
3376 /* allow logical NOT */
3377 if (*tmp_search_string == '~')
3378 tmp_search_string++;
3379 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3382 if (cmds[i].command)
3385 matcherstr = g_string_sized_new(16);
3386 cmd_start = cmd_end = copy_str;
3387 while (cmd_end && *cmd_end) {
3388 /* skip all white spaces */
3389 while (*cmd_end && isspace(*cmd_end))
3392 /* extract a command */
3393 while (*cmd_end && !isspace(*cmd_end))
3396 /* save character */
3397 save_char = *cmd_end;
3403 /* ~ and ! mean logical NOT */
3404 if (*cmd_start == '~' || *cmd_start == '!')
3409 /* % means case sensitive match */
3410 if (*cmd_start == '%')
3416 /* find matching abbreviation */
3417 for (i = 0; cmds[i].command; i++) {
3418 if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3419 /* restore character */
3420 *cmd_end = save_char;
3423 if (matcherstr->len > 0) {
3424 g_string_append(matcherstr, " ");
3427 g_string_append(matcherstr, "~");
3428 g_string_append(matcherstr, cmds[i].command);
3429 g_string_append(matcherstr, " ");
3431 /* stop if no params required */
3432 if (cmds[i].numparams == 0)
3435 /* extract a parameter, allow quotes */
3437 cmd_start = cmd_end;
3438 if (*cmd_start == '"') {
3445 /* extract actual parameter */
3446 while ((*cmd_end) && (*cmd_end != term_char))
3449 if (*cmd_end && (*cmd_end != term_char))
3452 if (*cmd_end == '"')
3455 save_char = *cmd_end;
3458 if (cmds[i].qualifier) {
3460 g_string_append(matcherstr, "regexp ");
3462 g_string_append(matcherstr, "regexpcase ");
3465 /* do we need to add quotes ? */
3466 if (cmds[i].quotes && term_char != '"')
3467 g_string_append(matcherstr, "\"");
3469 /* copy actual parameter */
3470 g_string_append(matcherstr, cmd_start);
3472 /* do we need to add quotes ? */
3473 if (cmds[i].quotes && term_char != '"')
3474 g_string_append(matcherstr, "\"");
3476 /* restore original character */
3477 *cmd_end = save_char;
3485 cmd_start = cmd_end;
3490 returnstr = matcherstr->str;
3491 g_string_free(matcherstr, FALSE);
3495 guint g_stricase_hash(gconstpointer gptr)
3497 guint hash_result = 0;
3500 for (str = gptr; str && *str; str++) {
3501 if (isupper(*str)) hash_result += (*str + ' ');
3502 else hash_result += *str;
3508 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3510 const char *str1 = gptr1;
3511 const char *str2 = gptr2;
3513 return !strcasecmp(str1, str2);
3516 gint g_int_compare(gconstpointer a, gconstpointer b)
3518 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);