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>
52 static gboolean debug_mode = FALSE;
54 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
56 void list_free_strings(GList *list)
58 list = g_list_first(list);
60 while (list != NULL) {
66 void slist_free_strings(GSList *list)
68 while (list != NULL) {
74 GSList *slist_concat_unique (GSList *first, GSList *second)
82 } else if (second == NULL)
85 for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
86 if (g_slist_find(ret, tmp->data) == NULL)
87 ret = g_slist_prepend(ret, tmp->data);
92 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
97 void hash_free_strings(GHashTable *table)
99 g_hash_table_foreach(table, hash_free_strings_func, NULL);
102 static void hash_free_value_mem_func(gpointer key, gpointer value,
108 void hash_free_value_mem(GHashTable *table)
110 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
113 gint str_case_equal(gconstpointer v, gconstpointer v2)
115 return strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
118 guint str_case_hash(gconstpointer key)
120 const gchar *p = key;
125 for (p += 1; *p != '\0'; p++)
126 h = (h << 5) - h + tolower(*p);
132 void ptr_array_free_strings(GPtrArray *array)
137 g_return_if_fail(array != NULL);
139 for (i = 0; i < array->len; i++) {
140 str = g_ptr_array_index(array, i);
145 gint to_number(const gchar *nstr)
147 register const gchar *p;
149 if (*nstr == '\0') return -1;
151 for (p = nstr; *p != '\0'; p++)
152 if (!isdigit(*p)) return -1;
157 /* convert integer into string,
158 nstr must be not lower than 11 characters length */
159 gchar *itos_buf(gchar *nstr, gint n)
161 g_snprintf(nstr, 11, "%d", n);
165 /* convert integer into string */
168 static gchar nstr[11];
170 return itos_buf(nstr, n);
173 gchar *to_human_readable(off_t size)
175 static gchar str[10];
178 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
179 else if (size >> 10 < 1024)
180 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
181 else if (size >> 20 < 1024)
182 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
184 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
189 /* strcmp with NULL-checking */
190 gint strcmp2(const gchar *s1, const gchar *s2)
192 if (s1 == NULL || s2 == NULL)
195 return strcmp(s1, s2);
197 /* strstr with NULL-checking */
198 gchar *strstr2(const gchar *s1, const gchar *s2)
200 if (s1 == NULL || s2 == NULL)
203 return strstr(s1, s2);
206 gint path_cmp(const gchar *s1, const gchar *s2)
210 if (s1 == NULL || s2 == NULL) return -1;
211 if (*s1 == '\0' || *s2 == '\0') return -1;
216 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
217 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
219 return strncmp(s1, s2, MAX(len1, len2));
222 /* remove trailing return code */
223 gchar *strretchomp(gchar *str)
227 if (!*str) return str;
229 for (s = str + strlen(str) - 1;
230 s >= str && (*s == '\n' || *s == '\r');
237 /* remove trailing character */
238 gchar *strtailchomp(gchar *str, gchar tail_char)
242 if (!*str) return str;
243 if (tail_char == '\0') return str;
245 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
251 /* remove CR (carriage return) */
252 gchar *strcrchomp(gchar *str)
256 if (!*str) return str;
258 s = str + strlen(str) - 1;
259 if (*s == '\n' && s > str && *(s - 1) == '\r') {
267 /* Similar to `strstr' but this function ignores the case of both strings. */
268 gchar *strcasestr(const gchar *haystack, const gchar *needle)
270 register size_t haystack_len, needle_len;
272 haystack_len = strlen(haystack);
273 needle_len = strlen(needle);
275 if (haystack_len < needle_len || needle_len == 0)
278 while (haystack_len >= needle_len) {
279 if (!strncasecmp(haystack, needle, needle_len))
280 return (gchar *)haystack;
290 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
291 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
305 /* don't do zero fill */
310 int iswalnum(wint_t wc)
312 return isalnum((int)wc);
317 int iswspace(wint_t wc)
319 return isspace((int)wc);
324 wint_t towlower(wint_t wc)
326 if (wc >= L'A' && wc <= L'Z')
327 return wc + L'a' - L'A';
334 size_t wcslen(const wchar_t *s)
346 /* Copy SRC to DEST. */
347 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
355 } while (c != L'\0');
362 /* Copy no more than N wide-characters of SRC to DEST. */
363 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
373 } while (c != L'\0');
384 /* Duplicate S, returning an identical malloc'd string. */
385 wchar_t *wcsdup(const wchar_t *s)
390 new_str = g_new(wchar_t, wcslen(s) + 1);
398 /* Duplicate no more than N wide-characters of S,
399 returning an identical malloc'd string. */
400 wchar_t *wcsndup(const wchar_t *s, size_t n)
405 new_str = g_new(wchar_t, n + 1);
406 wcsncpy(new_str, s, n);
407 new_str[n] = (wchar_t)0;
414 wchar_t *strdup_mbstowcs(const gchar *s)
419 new_str = g_new(wchar_t, strlen(s) + 1);
420 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
424 new_str = g_realloc(new_str,
425 sizeof(wchar_t) * (wcslen(new_str) + 1));
432 gchar *strdup_wcstombs(const wchar_t *s)
438 len = wcslen(s) * MB_CUR_MAX + 1;
439 new_str = g_new(gchar, len);
440 if (wcstombs(new_str, s, len) < 0) {
444 new_str = g_realloc(new_str, strlen(new_str) + 1);
451 /* Compare S1 and S2, ignoring case. */
452 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
458 c1 = towlower(*s1++);
459 c2 = towlower(*s2++);
462 else if (c1 == 0 && c2 == 0)
469 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
470 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
472 register size_t haystack_len, needle_len;
474 haystack_len = wcslen(haystack);
475 needle_len = wcslen(needle);
477 if (haystack_len < needle_len || needle_len == 0)
480 while (haystack_len >= needle_len) {
481 if (!wcsncasecmp(haystack, needle, needle_len))
482 return (wchar_t *)haystack;
492 gint get_mbs_len(const gchar *s)
502 mb_len = mblen(p, MB_LEN_MAX);
516 /* Examine if next block is non-ASCII string */
517 gboolean is_next_nonascii(const guchar *s)
521 /* skip head space */
522 for (p = s; *p != '\0' && isspace(*p); p++)
524 for (; *p != '\0' && !isspace(*p); p++) {
525 if (*p > 127 || *p < 32)
532 gint get_next_word_len(const gchar *s)
536 for (; *s != '\0' && !isspace(*s); s++, len++)
542 /* compare subjects */
543 gint subject_compare(const gchar *s1, const gchar *s2)
547 if (!s1 || !s2) return -1;
548 if (!*s1 || !*s2) return -1;
550 Xstrdup_a(str1, s1, return -1);
551 Xstrdup_a(str2, s2, return -1);
553 trim_subject_for_compare(str1);
554 trim_subject_for_compare(str2);
556 if (!*str1 || !*str2) return -1;
558 return strcmp(str1, str2);
561 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
565 if (!s1 || !s2) return -1;
567 Xstrdup_a(str1, s1, return -1);
568 Xstrdup_a(str2, s2, return -1);
570 trim_subject_for_sort(str1);
571 trim_subject_for_sort(str2);
573 return strcasecmp(str1, str2);
576 void trim_subject_for_compare(gchar *str)
581 eliminate_parenthesis(str, '[', ']');
582 eliminate_parenthesis(str, '(', ')');
585 srcp = str + subject_get_prefix_length(str);
587 memmove(str, srcp, strlen(srcp) + 1);
590 void trim_subject_for_sort(gchar *str)
596 srcp = str + subject_get_prefix_length(str);
598 memmove(str, srcp, strlen(srcp) + 1);
601 void trim_subject(gchar *str)
603 register gchar *srcp, *destp;
607 destp = str + subject_get_prefix_length(str);
612 } else if (*destp == '(') {
623 else if (*srcp == cl)
629 while (isspace(*srcp)) srcp++;
630 memmove(destp, srcp, strlen(srcp) + 1);
633 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
635 register gchar *srcp, *destp;
640 while ((destp = strchr(destp, op))) {
646 else if (*srcp == cl)
652 while (isspace(*srcp)) srcp++;
653 memmove(destp, srcp, strlen(srcp) + 1);
657 void extract_parenthesis(gchar *str, gchar op, gchar cl)
659 register gchar *srcp, *destp;
664 while ((srcp = strchr(destp, op))) {
667 memmove(destp, srcp + 1, strlen(srcp));
672 else if (*destp == cl)
684 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
687 register gchar *srcp, *destp;
689 gboolean in_quote = FALSE;
693 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
696 memmove(destp, srcp + 1, strlen(srcp));
699 if (*destp == op && !in_quote)
701 else if (*destp == cl && !in_quote)
703 else if (*destp == quote_chr)
715 void eliminate_quote(gchar *str, gchar quote_chr)
717 register gchar *srcp, *destp;
721 while ((destp = strchr(destp, quote_chr))) {
722 if ((srcp = strchr(destp + 1, quote_chr))) {
724 while (isspace(*srcp)) srcp++;
725 memmove(destp, srcp, strlen(srcp) + 1);
733 void extract_quote(gchar *str, gchar quote_chr)
737 if ((str = strchr(str, quote_chr))) {
739 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
740 memmove(p - 1, p, strlen(p) + 1);
745 memmove(str, str + 1, p - str);
750 void eliminate_address_comment(gchar *str)
752 register gchar *srcp, *destp;
757 while ((destp = strchr(destp, '"'))) {
758 if ((srcp = strchr(destp + 1, '"'))) {
763 while (isspace(*srcp)) srcp++;
764 memmove(destp, srcp, strlen(srcp) + 1);
774 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
780 else if (*srcp == ')')
786 while (isspace(*srcp)) srcp++;
787 memmove(destp, srcp, strlen(srcp) + 1);
791 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
793 gboolean in_quote = FALSE;
796 if (*str == c && !in_quote)
798 if (*str == quote_chr)
806 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
808 gboolean in_quote = FALSE;
811 p = str + strlen(str) - 1;
813 if (*p == c && !in_quote)
823 void extract_address(gchar *str)
825 eliminate_address_comment(str);
826 if (strchr_with_skip_quote(str, '"', '<'))
827 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
831 void extract_list_id_str(gchar *str)
833 if (strchr_with_skip_quote(str, '"', '<'))
834 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
838 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
843 if (!str) return addr_list;
845 Xstrdup_a(work, str, return addr_list);
848 eliminate_address_comment(work);
851 while (workp && *workp) {
854 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
860 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
861 extract_parenthesis_with_skip_quote
862 (workp, '"', '<', '>');
866 addr_list = g_slist_append(addr_list, g_strdup(workp));
874 GSList *address_list_append(GSList *addr_list, const gchar *str)
876 return address_list_append_real(addr_list, str, TRUE);
879 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
881 return address_list_append_real(addr_list, str, FALSE);
884 GSList *references_list_append(GSList *msgid_list, const gchar *str)
888 if (!str) return msgid_list;
891 while (strp && *strp) {
892 const gchar *start, *end;
895 if ((start = strchr(strp, '<')) != NULL) {
896 end = strchr(start + 1, '>');
901 msgid = g_strndup(start + 1, end - start - 1);
904 msgid_list = g_slist_append(msgid_list, msgid);
914 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
919 if (!str) return group_list;
921 Xstrdup_a(work, str, return group_list);
925 while (workp && *workp) {
928 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
936 group_list = g_slist_append(group_list,
945 GList *add_history(GList *list, const gchar *str)
949 g_return_val_if_fail(str != NULL, list);
951 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
954 list = g_list_remove(list, old->data);
955 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
958 last = g_list_last(list);
961 g_list_remove(list, last->data);
965 list = g_list_prepend(list, g_strdup(str));
970 void remove_return(gchar *str)
972 register gchar *p = str;
975 if (*p == '\n' || *p == '\r')
976 memmove(p, p + 1, strlen(p));
982 void remove_space(gchar *str)
984 register gchar *p = str;
989 while (isspace(*(p + spc)))
992 memmove(p, p + spc, strlen(p + spc) + 1);
998 void unfold_line(gchar *str)
1000 register gchar *p = str;
1004 if (*p == '\n' || *p == '\r') {
1007 while (isspace(*(p + spc)))
1010 memmove(p, p + spc, strlen(p + spc) + 1);
1016 void subst_char(gchar *str, gchar orig, gchar subst)
1018 register gchar *p = str;
1027 void subst_chars(gchar *str, gchar *orig, gchar subst)
1029 register gchar *p = str;
1032 if (strchr(orig, *p) != NULL)
1038 void subst_for_filename(gchar *str)
1040 subst_chars(str, " \t\r\n\"/\\", '_');
1043 gboolean is_header_line(const gchar *str)
1045 if (str[0] == ':') return FALSE;
1047 while (*str != '\0' && *str != ' ') {
1056 gboolean is_ascii_str(const guchar *str)
1058 g_return_val_if_fail(str, FALSE);
1060 while (*str != '\0') {
1061 if (*str != '\t' && *str != ' ' &&
1062 *str != '\r' && *str != '\n' &&
1063 (*str < 32 || *str >= 127))
1071 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1073 const gchar *first_pos;
1074 const gchar *last_pos;
1075 const gchar *p = str;
1076 gint quote_level = -1;
1078 /* speed up line processing by only searching to the last '>' */
1079 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1080 /* skip a line if it contains a '<' before the initial '>' */
1081 if (memchr(str, '<', first_pos - str) != NULL)
1083 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1087 while (p <= last_pos) {
1088 while (p < last_pos) {
1095 if (strchr(quote_chars, *p))
1097 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1098 /* any characters are allowed except '-' and space */
1100 && !strchr(quote_chars, *p)
1104 if (strchr(quote_chars, *p))
1116 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1118 gchar * position = NULL;
1119 gchar * tmp_pos = NULL;
1122 if (quote_chars == NULL)
1125 for (i = 0; i < strlen(quote_chars); i++) {
1126 tmp_pos = strchr (str, quote_chars[i]);
1128 || (tmp_pos != NULL && position >= tmp_pos) )
1134 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1136 gchar * position = NULL;
1137 gchar * tmp_pos = NULL;
1140 if (quote_chars == NULL)
1143 for (i = 0; i < strlen(quote_chars); i++) {
1144 tmp_pos = strrchr (str, quote_chars[i]);
1146 || (tmp_pos != NULL && position <= tmp_pos) )
1152 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1154 register guint haystack_len, needle_len;
1155 gboolean in_squote = FALSE, in_dquote = FALSE;
1157 haystack_len = strlen(haystack);
1158 needle_len = strlen(needle);
1160 if (haystack_len < needle_len || needle_len == 0)
1163 while (haystack_len >= needle_len) {
1164 if (!in_squote && !in_dquote &&
1165 !strncmp(haystack, needle, needle_len))
1166 return (gchar *)haystack;
1168 /* 'foo"bar"' -> foo"bar"
1169 "foo'bar'" -> foo'bar' */
1170 if (*haystack == '\'') {
1173 else if (!in_dquote)
1175 } else if (*haystack == '\"') {
1178 else if (!in_squote)
1189 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1192 gchar quote_chr = '"';
1194 gboolean in_quote = FALSE;
1198 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1202 if (*p == op && !in_quote)
1204 else if (*p == cl && !in_quote)
1206 else if (*p == quote_chr)
1219 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1222 GSList *string_list = NULL, *slist;
1224 const gchar *s_op, *s_cl;
1227 g_return_val_if_fail(str != NULL, NULL);
1230 max_tokens = G_MAXINT;
1232 s_op = strchr_with_skip_quote(str, '"', op);
1233 if (!s_op) return NULL;
1235 s_cl = strchr_parenthesis_close(str, op, cl);
1243 new_string = g_new(gchar, len + 1);
1244 strncpy(new_string, str, len);
1245 new_string[len] = 0;
1246 string_list = g_slist_prepend(string_list, new_string);
1250 while (*str && isspace(*str)) str++;
1252 string_list = g_slist_prepend(string_list,
1255 s_op = strchr_with_skip_quote(str, '"', op);
1256 if (!--max_tokens || !s_op) break;
1260 s_cl = strchr_parenthesis_close(str, op, cl);
1261 } while (--max_tokens && s_cl);
1264 str_array = g_new(gchar*, n);
1268 str_array[i--] = NULL;
1269 for (slist = string_list; slist; slist = slist->next)
1270 str_array[i--] = slist->data;
1272 g_slist_free(string_list);
1277 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1280 GSList *string_list = NULL, *slist;
1281 gchar **str_array, *s, *new_str;
1282 guint i, n = 1, len;
1284 g_return_val_if_fail(str != NULL, NULL);
1285 g_return_val_if_fail(delim != NULL, NULL);
1288 max_tokens = G_MAXINT;
1290 s = strstr_with_skip_quote(str, delim);
1292 guint delimiter_len = strlen(delim);
1296 new_str = g_strndup(str, len);
1298 if (new_str[0] == '\'' || new_str[0] == '\"') {
1299 if (new_str[len - 1] == new_str[0]) {
1300 new_str[len - 1] = '\0';
1301 memmove(new_str, new_str + 1, len - 1);
1304 string_list = g_slist_prepend(string_list, new_str);
1306 str = s + delimiter_len;
1307 s = strstr_with_skip_quote(str, delim);
1308 } while (--max_tokens && s);
1312 new_str = g_strdup(str);
1313 if (new_str[0] == '\'' || new_str[0] == '\"') {
1315 if (new_str[len - 1] == new_str[0]) {
1316 new_str[len - 1] = '\0';
1317 memmove(new_str, new_str + 1, len - 1);
1320 string_list = g_slist_prepend(string_list, new_str);
1324 str_array = g_new(gchar*, n);
1328 str_array[i--] = NULL;
1329 for (slist = string_list; slist; slist = slist->next)
1330 str_array[i--] = slist->data;
1332 g_slist_free(string_list);
1337 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1339 gchar *abbrev_group;
1341 const gchar *p = group;
1344 g_return_val_if_fail(group != NULL, NULL);
1346 last = group + strlen(group);
1347 abbrev_group = ap = g_malloc(strlen(group) + 1);
1352 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1354 while (*p != '.') p++;
1357 return abbrev_group;
1362 return abbrev_group;
1365 gchar *trim_string(const gchar *str, gint len)
1367 const gchar *p = str;
1372 if (!str) return NULL;
1373 if (strlen(str) <= len)
1374 return g_strdup(str);
1376 while (*p != '\0') {
1377 mb_len = mblen(p, MB_LEN_MAX);
1380 else if (mb_len < 0)
1381 return g_strdup(str);
1382 else if (new_len + mb_len > len)
1389 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1390 return g_strconcat(new_str, "...", NULL);
1393 GList *uri_list_extract_filenames(const gchar *uri_list)
1395 GList *result = NULL;
1403 while (isspace(*p)) p++;
1404 if (!strncmp(p, "file:", 5)) {
1407 while (*q && *q != '\n' && *q != '\r') q++;
1411 while (q > p && isspace(*q)) q--;
1412 file = g_malloc(q - p + 2);
1413 strncpy(file, p, q - p + 1);
1414 file[q - p + 1] = '\0';
1415 result = g_list_append(result,file);
1419 p = strchr(p, '\n');
1426 #define HEX_TO_INT(val, hex) \
1430 if ('0' <= c && c <= '9') { \
1432 } else if ('a' <= c && c <= 'f') { \
1433 val = c - 'a' + 10; \
1434 } else if ('A' <= c && c <= 'F') { \
1435 val = c - 'A' + 10; \
1441 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1442 gchar **subject, gchar **body)
1447 Xstrdup_a(tmp_mailto, mailto, return -1);
1449 if (!strncmp(tmp_mailto, "mailto:", 7))
1452 p = strchr(tmp_mailto, '?');
1459 *to = g_strdup(tmp_mailto);
1462 gchar *field, *value;
1479 if (*value == '\0') continue;
1481 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1482 *cc = g_strdup(value);
1483 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1484 *bcc = g_strdup(value);
1485 } else if (subject && !*subject &&
1486 !g_strcasecmp(field, "subject")) {
1487 *subject = g_malloc(strlen(value) + 1);
1488 decode_uri(*subject, value);
1489 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1490 *body = g_malloc(strlen(value) + 1);
1491 decode_uri(*body, value);
1499 * We need this wrapper around g_get_home_dir(), so that
1500 * we can fix some Windoze things here. Should be done in glibc of course
1501 * but as long as we are not able to do our own extensions to glibc, we do
1504 gchar *get_home_dir(void)
1506 #if HAVE_DOSISH_SYSTEM
1507 static gchar *home_dir;
1510 home_dir = read_w32_registry_string(NULL,
1511 "Software\\Sylpheed", "HomeDir" );
1512 if (!home_dir || !*home_dir) {
1513 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1514 const char *s = g_get_home_dir();
1516 home_dir = g_strdup (s);
1518 if (!home_dir || !*home_dir)
1519 home_dir = g_strdup ("c:\\sylpheed");
1521 debug_print("initialized home_dir to `%s'\n", home_dir);
1524 #else /* standard glib */
1525 return g_get_home_dir();
1529 gchar *get_rc_dir(void)
1531 static gchar *rc_dir = NULL;
1534 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1540 gchar *get_news_cache_dir(void)
1542 static gchar *news_cache_dir = NULL;
1544 if (!news_cache_dir)
1545 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1546 NEWS_CACHE_DIR, NULL);
1548 return news_cache_dir;
1551 gchar *get_imap_cache_dir(void)
1553 static gchar *imap_cache_dir = NULL;
1555 if (!imap_cache_dir)
1556 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1557 IMAP_CACHE_DIR, NULL);
1559 return imap_cache_dir;
1562 gchar *get_mbox_cache_dir(void)
1564 static gchar *mbox_cache_dir = NULL;
1566 if (!mbox_cache_dir)
1567 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1568 MBOX_CACHE_DIR, NULL);
1570 return mbox_cache_dir;
1573 gchar *get_mime_tmp_dir(void)
1575 static gchar *mime_tmp_dir = NULL;
1578 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1579 MIME_TMP_DIR, NULL);
1581 return mime_tmp_dir;
1584 gchar *get_template_dir(void)
1586 static gchar *template_dir = NULL;
1589 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1590 TEMPLATE_DIR, NULL);
1592 return template_dir;
1595 gchar *get_header_cache_dir(void)
1597 static gchar *header_dir = NULL;
1600 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1601 HEADER_CACHE_DIR, NULL);
1606 gchar *get_tmp_dir(void)
1608 static gchar *tmp_dir = NULL;
1611 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1617 gchar *get_tmp_file(void)
1620 static guint32 id = 0;
1622 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1623 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1628 gchar *get_domain_name(void)
1630 static gchar *domain_name = NULL;
1633 gchar buf[128] = "";
1636 if (gethostname(buf, sizeof(buf)) < 0) {
1637 perror("gethostname");
1638 domain_name = "unknown";
1640 buf[sizeof(buf) - 1] = '\0';
1641 if ((hp = my_gethostbyname(buf)) == NULL) {
1642 perror("gethostbyname");
1643 domain_name = g_strdup(buf);
1645 domain_name = g_strdup(hp->h_name);
1649 debug_print("domain name = %s\n", domain_name);
1655 off_t get_file_size(const gchar *file)
1659 if (stat(file, &s) < 0) {
1660 FILE_OP_ERROR(file, "stat");
1667 off_t get_file_size_as_crlf(const gchar *file)
1671 gchar buf[BUFFSIZE];
1673 if ((fp = fopen(file, "rb")) == NULL) {
1674 FILE_OP_ERROR(file, "fopen");
1678 while (fgets(buf, sizeof(buf), fp) != NULL) {
1680 size += strlen(buf) + 2;
1684 FILE_OP_ERROR(file, "fgets");
1693 off_t get_left_file_size(FILE *fp)
1699 if ((pos = ftell(fp)) < 0) {
1703 if (fseek(fp, 0L, SEEK_END) < 0) {
1707 if ((end = ftell(fp)) < 0) {
1712 if (fseek(fp, pos, SEEK_SET) < 0) {
1720 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1727 if (stat(file, &s) < 0) {
1728 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1732 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1738 gboolean is_dir_exist(const gchar *dir)
1745 if (stat(dir, &s) < 0) {
1746 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1750 if (S_ISDIR(s.st_mode))
1756 gboolean is_file_entry_exist(const gchar *file)
1763 if (stat(file, &s) < 0) {
1764 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1771 gint change_dir(const gchar *dir)
1773 gchar *prevdir = NULL;
1776 prevdir = g_get_current_dir();
1778 if (chdir(dir) < 0) {
1779 FILE_OP_ERROR(dir, "chdir");
1780 if (debug_mode) g_free(prevdir);
1782 } else if (debug_mode) {
1785 cwd = g_get_current_dir();
1786 if (strcmp(prevdir, cwd) != 0)
1787 g_print("current dir: %s\n", cwd);
1795 gint make_dir(const gchar *dir)
1797 if (mkdir(dir, S_IRWXU) < 0) {
1798 FILE_OP_ERROR(dir, "mkdir");
1801 if (chmod(dir, S_IRWXU) < 0)
1802 FILE_OP_ERROR(dir, "chmod");
1807 gint make_dir_hier(const gchar *dir)
1812 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1813 parent_dir = g_strndup(dir, p - dir);
1814 if (*parent_dir != '\0') {
1815 if (!is_dir_exist(parent_dir)) {
1816 if (make_dir(parent_dir) < 0) {
1825 if (!is_dir_exist(dir)) {
1826 if (make_dir(dir) < 0)
1833 gint remove_all_files(const gchar *dir)
1839 prev_dir = g_get_current_dir();
1841 if (chdir(dir) < 0) {
1842 FILE_OP_ERROR(dir, "chdir");
1847 if ((dp = opendir(".")) == NULL) {
1848 FILE_OP_ERROR(dir, "opendir");
1853 while ((d = readdir(dp)) != NULL) {
1854 if (!strcmp(d->d_name, ".") ||
1855 !strcmp(d->d_name, ".."))
1858 if (unlink(d->d_name) < 0)
1859 FILE_OP_ERROR(d->d_name, "unlink");
1864 if (chdir(prev_dir) < 0) {
1865 FILE_OP_ERROR(prev_dir, "chdir");
1875 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1882 prev_dir = g_get_current_dir();
1884 if (chdir(dir) < 0) {
1885 FILE_OP_ERROR(dir, "chdir");
1890 if ((dp = opendir(".")) == NULL) {
1891 FILE_OP_ERROR(dir, "opendir");
1896 while ((d = readdir(dp)) != NULL) {
1897 fileno = to_number(d->d_name);
1898 if (fileno >= 0 && first <= fileno && fileno <= last) {
1899 if (is_dir_exist(d->d_name))
1901 if (unlink(d->d_name) < 0)
1902 FILE_OP_ERROR(d->d_name, "unlink");
1908 if (chdir(prev_dir) < 0) {
1909 FILE_OP_ERROR(prev_dir, "chdir");
1919 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1926 prev_dir = g_get_current_dir();
1928 if (chdir(dir) < 0) {
1929 FILE_OP_ERROR(dir, "chdir");
1934 if ((dp = opendir(".")) == NULL) {
1935 FILE_OP_ERROR(dir, "opendir");
1940 while ((d = readdir(dp)) != NULL) {
1941 fileno = to_number(d->d_name);
1942 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1943 debug_print("removing unwanted file %d from %s\n", fileno, dir);
1944 if (is_dir_exist(d->d_name))
1946 if (unlink(d->d_name) < 0)
1947 FILE_OP_ERROR(d->d_name, "unlink");
1953 if (chdir(prev_dir) < 0) {
1954 FILE_OP_ERROR(prev_dir, "chdir");
1964 gint remove_all_numbered_files(const gchar *dir)
1966 return remove_numbered_files(dir, 0, UINT_MAX);
1969 gint remove_expired_files(const gchar *dir, guint hours)
1976 time_t mtime, now, expire_time;
1978 prev_dir = g_get_current_dir();
1980 if (chdir(dir) < 0) {
1981 FILE_OP_ERROR(dir, "chdir");
1986 if ((dp = opendir(".")) == NULL) {
1987 FILE_OP_ERROR(dir, "opendir");
1993 expire_time = hours * 60 * 60;
1995 while ((d = readdir(dp)) != NULL) {
1996 fileno = to_number(d->d_name);
1998 if (stat(d->d_name, &s) < 0) {
1999 FILE_OP_ERROR(d->d_name, "stat");
2002 if (S_ISDIR(s.st_mode))
2004 mtime = MAX(s.st_mtime, s.st_atime);
2005 if (now - mtime > expire_time) {
2006 if (unlink(d->d_name) < 0)
2007 FILE_OP_ERROR(d->d_name, "unlink");
2014 if (chdir(prev_dir) < 0) {
2015 FILE_OP_ERROR(prev_dir, "chdir");
2025 gint remove_dir_recursive(const gchar *dir)
2032 /* g_print("dir = %s\n", dir); */
2034 if (stat(dir, &s) < 0) {
2035 FILE_OP_ERROR(dir, "stat");
2036 if (ENOENT == errno) return 0;
2040 if (!S_ISDIR(s.st_mode)) {
2041 if (unlink(dir) < 0) {
2042 FILE_OP_ERROR(dir, "unlink");
2049 prev_dir = g_get_current_dir();
2050 /* g_print("prev_dir = %s\n", prev_dir); */
2052 if (!path_cmp(prev_dir, dir)) {
2054 if (chdir("..") < 0) {
2055 FILE_OP_ERROR(dir, "chdir");
2058 prev_dir = g_get_current_dir();
2061 if (chdir(dir) < 0) {
2062 FILE_OP_ERROR(dir, "chdir");
2067 if ((dp = opendir(".")) == NULL) {
2068 FILE_OP_ERROR(dir, "opendir");
2074 /* remove all files in the directory */
2075 while ((d = readdir(dp)) != NULL) {
2076 if (!strcmp(d->d_name, ".") ||
2077 !strcmp(d->d_name, ".."))
2080 if (stat(d->d_name, &s) < 0) {
2081 FILE_OP_ERROR(d->d_name, "stat");
2085 /* g_print("removing %s\n", d->d_name); */
2087 if (S_ISDIR(s.st_mode)) {
2088 if (remove_dir_recursive(d->d_name) < 0) {
2089 g_warning("can't remove directory\n");
2093 if (unlink(d->d_name) < 0)
2094 FILE_OP_ERROR(d->d_name, "unlink");
2100 if (chdir(prev_dir) < 0) {
2101 FILE_OP_ERROR(prev_dir, "chdir");
2108 if (rmdir(dir) < 0) {
2109 FILE_OP_ERROR(dir, "rmdir");
2117 /* this seems to be slower than the stdio version... */
2118 gint copy_file(const gchar *src, const gchar *dest)
2120 gint src_fd, dest_fd;
2124 gchar *dest_bak = NULL;
2126 if ((src_fd = open(src, O_RDONLY)) < 0) {
2127 FILE_OP_ERROR(src, "open");
2131 if (is_file_exist(dest)) {
2132 dest_bak = g_strconcat(dest, ".bak", NULL);
2133 if (rename(dest, dest_bak) < 0) {
2134 FILE_OP_ERROR(dest, "rename");
2141 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2142 FILE_OP_ERROR(dest, "open");
2145 if (rename(dest_bak, dest) < 0)
2146 FILE_OP_ERROR(dest_bak, "rename");
2152 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2157 n_write = write(dest_fd, bufp, len);
2159 g_warning("writing to %s failed.\n", dest);
2164 if (rename(dest_bak, dest) < 0)
2165 FILE_OP_ERROR(dest_bak, "rename");
2178 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2179 g_warning("File copy from %s to %s failed.\n", src, dest);
2182 if (rename(dest_bak, dest) < 0)
2183 FILE_OP_ERROR(dest_bak, "rename");
2196 * Append src file body to the tail of dest file.
2197 * Now keep_backup has no effects.
2199 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2201 FILE *src_fp, *dest_fp;
2205 gboolean err = FALSE;
2207 if ((src_fp = fopen(src, "rb")) == NULL) {
2208 FILE_OP_ERROR(src, "fopen");
2212 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2213 FILE_OP_ERROR(dest, "fopen");
2218 if (change_file_mode_rw(dest_fp, dest) < 0) {
2219 FILE_OP_ERROR(dest, "chmod");
2220 g_warning("can't change file mode\n");
2223 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2224 if (n_read < sizeof(buf) && ferror(src_fp))
2226 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2227 g_warning("writing to %s failed.\n", dest);
2235 if (ferror(src_fp)) {
2236 FILE_OP_ERROR(src, "fread");
2240 if (fclose(dest_fp) == EOF) {
2241 FILE_OP_ERROR(dest, "fclose");
2253 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2255 FILE *src_fp, *dest_fp;
2258 gchar *dest_bak = NULL;
2259 gboolean err = FALSE;
2261 if ((src_fp = fopen(src, "rb")) == NULL) {
2262 FILE_OP_ERROR(src, "fopen");
2265 if (is_file_exist(dest)) {
2266 dest_bak = g_strconcat(dest, ".bak", NULL);
2267 if (rename(dest, dest_bak) < 0) {
2268 FILE_OP_ERROR(dest, "rename");
2275 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2276 FILE_OP_ERROR(dest, "fopen");
2279 if (rename(dest_bak, dest) < 0)
2280 FILE_OP_ERROR(dest_bak, "rename");
2286 if (change_file_mode_rw(dest_fp, dest) < 0) {
2287 FILE_OP_ERROR(dest, "chmod");
2288 g_warning("can't change file mode\n");
2291 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2292 if (n_read < sizeof(buf) && ferror(src_fp))
2294 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2295 g_warning("writing to %s failed.\n", dest);
2300 if (rename(dest_bak, dest) < 0)
2301 FILE_OP_ERROR(dest_bak, "rename");
2308 if (ferror(src_fp)) {
2309 FILE_OP_ERROR(src, "fread");
2313 if (fclose(dest_fp) == EOF) {
2314 FILE_OP_ERROR(dest, "fclose");
2321 if (rename(dest_bak, dest) < 0)
2322 FILE_OP_ERROR(dest_bak, "rename");
2328 if (keep_backup == FALSE && dest_bak)
2336 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2338 if (overwrite == FALSE && is_file_exist(dest)) {
2339 g_warning("move_file(): file %s already exists.", dest);
2343 if (rename(src, dest) == 0) return 0;
2345 if (EXDEV != errno) {
2346 FILE_OP_ERROR(src, "rename");
2350 if (copy_file(src, dest, FALSE) < 0) return -1;
2357 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2361 gint bytes_left, to_read;
2363 gboolean err = FALSE;
2365 if (fseek(fp, offset, SEEK_SET) < 0) {
2370 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2371 FILE_OP_ERROR(dest, "fopen");
2375 if (change_file_mode_rw(dest_fp, dest) < 0) {
2376 FILE_OP_ERROR(dest, "chmod");
2377 g_warning("can't change file mode\n");
2380 bytes_left = length;
2381 to_read = MIN(bytes_left, sizeof(buf));
2383 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2384 if (n_read < to_read && ferror(fp))
2386 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2387 g_warning("writing to %s failed.\n", dest);
2392 bytes_left -= n_read;
2393 if (bytes_left == 0)
2395 to_read = MIN(bytes_left, sizeof(buf));
2402 if (fclose(dest_fp) == EOF) {
2403 FILE_OP_ERROR(dest, "fclose");
2415 /* convert line endings into CRLF. If the last line doesn't end with
2416 * linebreak, add it.
2418 gchar *canonicalize_str(const gchar *str)
2424 for (p = str; *p != '\0'; ++p) {
2431 if (p == str || *(p - 1) != '\n')
2434 out = outp = g_malloc(new_len + 1);
2435 for (p = str; *p != '\0'; ++p) {
2442 if (p == str || *(p - 1) != '\n') {
2451 gint canonicalize_file(const gchar *src, const gchar *dest)
2453 FILE *src_fp, *dest_fp;
2454 gchar buf[BUFFSIZE];
2456 gboolean err = FALSE;
2457 gboolean last_linebreak = FALSE;
2459 if ((src_fp = fopen(src, "rb")) == NULL) {
2460 FILE_OP_ERROR(src, "fopen");
2464 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2465 FILE_OP_ERROR(dest, "fopen");
2470 if (change_file_mode_rw(dest_fp, dest) < 0) {
2471 FILE_OP_ERROR(dest, "chmod");
2472 g_warning("can't change file mode\n");
2475 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2479 if (len == 0) break;
2480 last_linebreak = FALSE;
2482 if (buf[len - 1] != '\n') {
2483 last_linebreak = TRUE;
2484 r = fputs(buf, dest_fp);
2485 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2486 r = fputs(buf, dest_fp);
2489 r = fwrite(buf, len - 1, 1, dest_fp);
2494 r = fputs("\r\n", dest_fp);
2498 g_warning("writing to %s failed.\n", dest);
2506 if (last_linebreak == TRUE) {
2507 if (fputs("\r\n", dest_fp) == EOF)
2511 if (ferror(src_fp)) {
2512 FILE_OP_ERROR(src, "fgets");
2516 if (fclose(dest_fp) == EOF) {
2517 FILE_OP_ERROR(dest, "fclose");
2529 gint canonicalize_file_replace(const gchar *file)
2533 tmp_file = get_tmp_file();
2535 if (canonicalize_file(file, tmp_file) < 0) {
2540 if (move_file(tmp_file, file, TRUE) < 0) {
2541 g_warning("can't replace %s .\n", file);
2551 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2553 FILE *src_fp, *dest_fp;
2554 gchar buf[BUFFSIZE];
2555 gboolean err = FALSE;
2557 if ((src_fp = fopen(src, "rb")) == NULL) {
2558 FILE_OP_ERROR(src, "fopen");
2562 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2563 FILE_OP_ERROR(dest, "fopen");
2568 if (change_file_mode_rw(dest_fp, dest) < 0) {
2569 FILE_OP_ERROR(dest, "chmod");
2570 g_warning("can't change file mode\n");
2573 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2575 if (fputs(buf, dest_fp) == EOF) {
2576 g_warning("writing to %s failed.\n", dest);
2584 if (ferror(src_fp)) {
2585 FILE_OP_ERROR(src, "fgets");
2589 if (fclose(dest_fp) == EOF) {
2590 FILE_OP_ERROR(dest, "fclose");
2602 gint uncanonicalize_file_replace(const gchar *file)
2606 tmp_file = get_tmp_file();
2608 if (uncanonicalize_file(file, tmp_file) < 0) {
2613 if (move_file(tmp_file, file, TRUE) < 0) {
2614 g_warning("can't replace %s .\n", file);
2624 gchar *normalize_newlines(const gchar *str)
2626 const gchar *p = str;
2629 out = outp = g_malloc(strlen(str) + 1);
2630 for (p = str; *p != '\0'; ++p) {
2632 if (*(p + 1) != '\n')
2643 gchar *get_outgoing_rfc2822_str(FILE *fp)
2645 gchar buf[BUFFSIZE];
2649 str = g_string_new(NULL);
2651 /* output header part */
2652 while (fgets(buf, sizeof(buf), fp) != NULL) {
2654 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2661 else if (next != ' ' && next != '\t') {
2665 if (fgets(buf, sizeof(buf), fp) == NULL)
2669 g_string_append(str, buf);
2670 g_string_append(str, "\r\n");
2676 /* output body part */
2677 while (fgets(buf, sizeof(buf), fp) != NULL) {
2680 g_string_append_c(str, '.');
2681 g_string_append(str, buf);
2682 g_string_append(str, "\r\n");
2686 g_string_free(str, FALSE);
2691 gint change_file_mode_rw(FILE *fp, const gchar *file)
2694 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2696 return chmod(file, S_IRUSR|S_IWUSR);
2700 FILE *my_tmpfile(void)
2703 const gchar suffix[] = ".XXXXXX";
2704 const gchar *tmpdir;
2706 const gchar *progname;
2712 tmpdir = get_tmp_dir();
2713 tmplen = strlen(tmpdir);
2714 progname = g_get_prgname();
2715 proglen = strlen(progname);
2716 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2719 memcpy(fname, tmpdir, tmplen);
2720 fname[tmplen] = G_DIR_SEPARATOR;
2721 memcpy(fname + tmplen + 1, progname, proglen);
2722 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2724 fd = mkstemp(fname);
2730 fp = fdopen(fd, "w+b");
2735 #endif /* HAVE_MKSTEMP */
2740 FILE *str_open_as_stream(const gchar *str)
2745 g_return_val_if_fail(str != NULL, NULL);
2749 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2754 if (len == 0) return fp;
2756 if (fwrite(str, len, 1, fp) != 1) {
2757 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2766 gint str_write_to_file(const gchar *str, const gchar *file)
2771 g_return_val_if_fail(str != NULL, -1);
2772 g_return_val_if_fail(file != NULL, -1);
2774 if ((fp = fopen(file, "wb")) == NULL) {
2775 FILE_OP_ERROR(file, "fopen");
2785 if (fwrite(str, len, 1, fp) != 1) {
2786 FILE_OP_ERROR(file, "fwrite");
2792 if (fclose(fp) == EOF) {
2793 FILE_OP_ERROR(file, "fclose");
2801 gchar *file_read_to_str(const gchar *file)
2806 g_return_val_if_fail(file != NULL, NULL);
2808 if ((fp = fopen(file, "rb")) == NULL) {
2809 FILE_OP_ERROR(file, "fopen");
2813 str = file_read_stream_to_str(fp);
2820 gchar *file_read_stream_to_str(FILE *fp)
2827 g_return_val_if_fail(fp != NULL, NULL);
2829 array = g_byte_array_new();
2831 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2832 if (n_read < sizeof(buf) && ferror(fp))
2834 g_byte_array_append(array, buf, n_read);
2838 FILE_OP_ERROR("file stream", "fread");
2839 g_byte_array_free(array, TRUE);
2844 g_byte_array_append(array, buf, 1);
2845 str = (gchar *)array->data;
2846 g_byte_array_free(array, FALSE);
2851 gint execute_async(gchar *const argv[])
2855 if ((pid = fork()) < 0) {
2860 if (pid == 0) { /* child process */
2863 if ((gch_pid = fork()) < 0) {
2868 if (gch_pid == 0) { /* grandchild process */
2869 execvp(argv[0], argv);
2878 waitpid(pid, NULL, 0);
2883 gint execute_sync(gchar *const argv[])
2887 if ((pid = fork()) < 0) {
2892 if (pid == 0) { /* child process */
2893 execvp(argv[0], argv);
2899 waitpid(pid, NULL, 0);
2904 gint execute_command_line(const gchar *cmdline, gboolean async)
2909 argv = strsplit_with_quote(cmdline, " ", 0);
2912 ret = execute_async(argv);
2914 ret = execute_sync(argv);
2920 gchar *get_command_output(const gchar *cmdline)
2922 gchar buf[BUFFSIZE];
2927 g_return_val_if_fail(cmdline != NULL, NULL);
2929 if ((fp = popen(cmdline, "r")) == NULL) {
2930 FILE_OP_ERROR(cmdline, "popen");
2934 str = g_string_new("");
2936 while (fgets(buf, sizeof(buf), fp) != NULL)
2937 g_string_append(str, buf);
2942 g_string_free(str, FALSE);
2947 static gint is_unchanged_uri_char(char c)
2959 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2965 for(i = 0; i < strlen(uri) ; i++) {
2966 if (is_unchanged_uri_char(uri[i])) {
2967 if (k + 2 >= bufsize)
2969 encoded_uri[k++] = uri[i];
2972 char * hexa = "0123456789ABCDEF";
2974 if (k + 4 >= bufsize)
2976 encoded_uri[k++] = '%';
2977 encoded_uri[k++] = hexa[uri[i] / 16];
2978 encoded_uri[k++] = hexa[uri[i] % 16];
2984 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
2987 static gint axtoi(const gchar *hexstr)
2989 gint hi, lo, result;
2992 if ('0' <= hi && hi <= '9') {
2995 if ('a' <= hi && hi <= 'f') {
2998 if ('A' <= hi && hi <= 'F') {
3003 if ('0' <= lo && lo <= '9') {
3006 if ('a' <= lo && lo <= 'f') {
3009 if ('A' <= lo && lo <= 'F') {
3012 result = lo + (16 * hi);
3017 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
3018 * plusses, and escape characters are used)
3021 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
3023 const gchar *encoded;
3026 encoded = encoded_uri;
3027 decoded = decoded_uri;
3030 if (*encoded == '%') {
3032 if (isxdigit(encoded[0])
3033 && isxdigit(encoded[1])) {
3034 *decoded = (gchar) axtoi(encoded);
3039 else if (*encoded == '+') {
3045 *decoded = *encoded;
3055 gint open_uri(const gchar *uri, const gchar *cmdline)
3057 gchar buf[BUFFSIZE];
3059 gchar encoded_uri[BUFFSIZE];
3061 g_return_val_if_fail(uri != NULL, -1);
3063 /* an option to choose whether to use encode_uri or not ? */
3064 encode_uri(encoded_uri, BUFFSIZE, uri);
3067 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3068 !strchr(p + 2, '%'))
3069 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3072 g_warning("Open URI command line is invalid: `%s'",
3074 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3077 execute_command_line(buf, TRUE);
3082 time_t remote_tzoffset_sec(const gchar *zone)
3084 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3090 time_t remoteoffset;
3092 strncpy(zone3, zone, 3);
3096 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3097 (c == '+' || c == '-')) {
3098 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3100 remoteoffset = -remoteoffset;
3101 } else if (!strncmp(zone, "UT" , 2) ||
3102 !strncmp(zone, "GMT", 2)) {
3104 } else if (strlen(zone3) == 3) {
3105 for (p = ustzstr; *p != '\0'; p += 3) {
3106 if (!strncasecmp(p, zone3, 3)) {
3107 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3108 remoteoffset = iustz * 3600;
3114 } else if (strlen(zone3) == 1) {
3116 case 'Z': remoteoffset = 0; break;
3117 case 'A': remoteoffset = -1; break;
3118 case 'B': remoteoffset = -2; break;
3119 case 'C': remoteoffset = -3; break;
3120 case 'D': remoteoffset = -4; break;
3121 case 'E': remoteoffset = -5; break;
3122 case 'F': remoteoffset = -6; break;
3123 case 'G': remoteoffset = -7; break;
3124 case 'H': remoteoffset = -8; break;
3125 case 'I': remoteoffset = -9; break;
3126 case 'K': remoteoffset = -10; break; /* J is not used */
3127 case 'L': remoteoffset = -11; break;
3128 case 'M': remoteoffset = -12; break;
3129 case 'N': remoteoffset = 1; break;
3130 case 'O': remoteoffset = 2; break;
3131 case 'P': remoteoffset = 3; break;
3132 case 'Q': remoteoffset = 4; break;
3133 case 'R': remoteoffset = 5; break;
3134 case 'S': remoteoffset = 6; break;
3135 case 'T': remoteoffset = 7; break;
3136 case 'U': remoteoffset = 8; break;
3137 case 'V': remoteoffset = 9; break;
3138 case 'W': remoteoffset = 10; break;
3139 case 'X': remoteoffset = 11; break;
3140 case 'Y': remoteoffset = 12; break;
3141 default: remoteoffset = 0; break;
3143 remoteoffset = remoteoffset * 3600;
3147 return remoteoffset;
3150 time_t tzoffset_sec(time_t *now)
3156 lt = localtime(now);
3158 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3160 if (lt->tm_year < gmt.tm_year)
3162 else if (lt->tm_year > gmt.tm_year)
3164 else if (lt->tm_yday < gmt.tm_yday)
3166 else if (lt->tm_yday > gmt.tm_yday)
3169 if (off >= 24 * 60) /* should be impossible */
3170 off = 23 * 60 + 59; /* if not, insert silly value */
3171 if (off <= -24 * 60)
3172 off = -(23 * 60 + 59);
3177 /* calculate timezone offset */
3178 gchar *tzoffset(time_t *now)
3180 static gchar offset_string[6];
3186 lt = localtime(now);
3188 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3190 if (lt->tm_year < gmt.tm_year)
3192 else if (lt->tm_year > gmt.tm_year)
3194 else if (lt->tm_yday < gmt.tm_yday)
3196 else if (lt->tm_yday > gmt.tm_yday)
3204 if (off >= 24 * 60) /* should be impossible */
3205 off = 23 * 60 + 59; /* if not, insert silly value */
3207 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3209 return offset_string;
3212 void get_rfc822_date(gchar *buf, gint len)
3216 gchar day[4], mon[4];
3217 gint dd, hh, mm, ss, yyyy;
3222 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3223 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3224 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3225 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3228 void debug_set_mode(gboolean mode)
3233 gboolean debug_get_mode(void)
3238 void debug_print_real(const gchar *format, ...)
3241 gchar buf[BUFFSIZE];
3243 if (!debug_mode) return;
3245 va_start(args, format);
3246 g_vsnprintf(buf, sizeof(buf), format, args);
3252 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3254 if (subject == NULL)
3257 subject += subject_get_prefix_length(subject);
3259 return g_hash_table_lookup(subject_table, subject);
3262 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3265 if (subject == NULL || *subject == 0)
3267 subject += subject_get_prefix_length(subject);
3268 g_hash_table_insert(subject_table, subject, data);
3271 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3273 if (subject == NULL)
3276 subject += subject_get_prefix_length(subject);
3277 g_hash_table_remove(subject_table, subject);
3281 *\brief Check if a string is prefixed with known (combinations)
3282 * of prefixes. The function assumes that each prefix
3283 * is terminated by zero or exactly _one_ space.
3285 *\param str String to check for a prefixes
3287 *\return int Number of chars in the prefix that should be skipped
3288 * for a "clean" subject line. If no prefix was found, 0
3291 int subject_get_prefix_length(const gchar *subject)
3293 /*!< Array with allowable reply prefixes regexps. */
3294 static const gchar * const prefixes[] = {
3295 "Re\\:", /* "Re:" */
3296 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3297 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3298 "Aw\\:", /* "Aw:" (German) */
3299 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3300 "Res\\:", /* "Res:" (Brazilian Outlook) */
3301 "Fw\\:", /* "Fw:" Forward */
3302 "Enc\\:" /* "Enc:" Forward (Brazilian Outlook) */
3305 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3308 static regex_t regex;
3309 static gboolean init_;
3311 if (!subject) return 0;
3312 if (!*subject) return 0;
3315 GString *s = g_string_new("");
3317 for (n = 0; n < PREFIXES; n++)
3318 /* Terminate each prefix regexpression by a
3319 * "\ ?" (zero or ONE space), and OR them */
3320 g_string_sprintfa(s, "(%s\\ ?)%s",
3325 g_string_prepend(s, "(");
3326 g_string_append(s, ")+"); /* match at least once */
3327 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3330 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3331 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3332 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3333 debug_print("Error compiling regexp %s\n", s->str);
3334 g_string_free(s, TRUE);
3338 g_string_free(s, TRUE);
3342 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3348 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
3352 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
3353 fd = mkstemp(*filename);
3355 return fdopen(fd, "w+");
3358 /* allow Mutt-like patterns in quick search */
3359 gchar *expand_search_string(const gchar *search_string)
3362 gchar term_char, save_char;
3363 gchar *cmd_start, *cmd_end;
3364 GString *matcherstr;
3365 gchar *returnstr = NULL;
3367 gboolean casesens, dontmatch;
3368 /* list of allowed pattern abbreviations */
3370 gchar *abbreviated; /* abbreviation */
3371 gchar *command; /* actual matcher command */
3372 gint numparams; /* number of params for cmd */
3373 gboolean qualifier; /* do we append regexpcase */
3374 gboolean quotes; /* do we need quotes */
3377 { "a", "all", 0, FALSE, FALSE },
3378 { "ag", "age_greater", 1, FALSE, FALSE },
3379 { "al", "age_lower", 1, FALSE, FALSE },
3380 { "b", "body_part", 1, TRUE, TRUE },
3381 { "B", "message", 1, TRUE, TRUE },
3382 { "c", "cc", 1, TRUE, TRUE },
3383 { "C", "to_or_cc", 1, TRUE, TRUE },
3384 { "D", "deleted", 0, FALSE, FALSE },
3385 { "e", "header \"Sender\"", 1, TRUE, TRUE },
3386 { "E", "execute", 1, FALSE, TRUE },
3387 { "f", "from", 1, TRUE, TRUE },
3388 { "F", "forwarded", 0, FALSE, FALSE },
3389 { "h", "headers_part", 1, TRUE, TRUE },
3390 { "i", "header \"Message-Id\"", 1, TRUE, TRUE },
3391 { "I", "inreplyto", 1, TRUE, TRUE },
3392 { "L", "locked", 0, FALSE, FALSE },
3393 { "n", "newsgroups", 1, TRUE, TRUE },
3394 { "N", "new", 0, FALSE, FALSE },
3395 { "O", "~new", 0, FALSE, FALSE },
3396 { "r", "replied", 0, FALSE, FALSE },
3397 { "R", "~unread", 0, FALSE, FALSE },
3398 { "s", "subject", 1, TRUE, TRUE },
3399 { "se", "score_equal", 1, FALSE, FALSE },
3400 { "sg", "score_greater", 1, FALSE, FALSE },
3401 { "sl", "score_lower", 1, FALSE, FALSE },
3402 { "Se", "size_equal", 1, FALSE, FALSE },
3403 { "Sg", "size_greater", 1, FALSE, FALSE },
3404 { "Ss", "size_smaller", 1, FALSE, FALSE },
3405 { "t", "to", 1, TRUE, TRUE },
3406 { "T", "marked", 0, FALSE, FALSE },
3407 { "U", "unread", 0, FALSE, FALSE },
3408 { "x", "header \"References\"", 1, TRUE, TRUE },
3409 { "y", "header \"X-Label\"", 1, TRUE, TRUE },
3410 { "&", "&", 0, FALSE, FALSE },
3411 { "|", "|", 0, FALSE, FALSE },
3412 { NULL, NULL, 0, FALSE, FALSE }
3415 if (search_string == NULL)
3418 copy_str = g_strdup(search_string);
3420 /* if it's a full command don't process it so users
3421 can still do something like from regexpcase "foo" */
3422 for (i = 0; cmds[i].command; i++) {
3423 const gchar *tmp_search_string = search_string;
3424 cmd_start = cmds[i].command;
3425 /* allow logical NOT */
3426 if (*tmp_search_string == '~')
3427 tmp_search_string++;
3428 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3431 if (cmds[i].command)
3434 matcherstr = g_string_sized_new(16);
3435 cmd_start = cmd_end = copy_str;
3436 while (cmd_end && *cmd_end) {
3437 /* skip all white spaces */
3438 while (*cmd_end && isspace(*cmd_end))
3441 /* extract a command */
3442 while (*cmd_end && !isspace(*cmd_end))
3445 /* save character */
3446 save_char = *cmd_end;
3452 /* ~ and ! mean logical NOT */
3453 if (*cmd_start == '~' || *cmd_start == '!')
3458 /* % means case sensitive match */
3459 if (*cmd_start == '%')
3465 /* find matching abbreviation */
3466 for (i = 0; cmds[i].command; i++) {
3467 if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3468 /* restore character */
3469 *cmd_end = save_char;
3472 if (matcherstr->len > 0) {
3473 g_string_append(matcherstr, " ");
3476 g_string_append(matcherstr, "~");
3477 g_string_append(matcherstr, cmds[i].command);
3478 g_string_append(matcherstr, " ");
3480 /* stop if no params required */
3481 if (cmds[i].numparams == 0)
3484 /* extract a parameter, allow quotes */
3486 cmd_start = cmd_end;
3487 if (*cmd_start == '"') {
3494 /* extract actual parameter */
3495 while ((*cmd_end) && (*cmd_end != term_char))
3498 if (*cmd_end && (*cmd_end != term_char))
3501 if (*cmd_end == '"')
3504 save_char = *cmd_end;
3507 if (cmds[i].qualifier) {
3509 g_string_append(matcherstr, "regexp ");
3511 g_string_append(matcherstr, "regexpcase ");
3514 /* do we need to add quotes ? */
3515 if (cmds[i].quotes && term_char != '"')
3516 g_string_append(matcherstr, "\"");
3518 /* copy actual parameter */
3519 g_string_append(matcherstr, cmd_start);
3521 /* do we need to add quotes ? */
3522 if (cmds[i].quotes && term_char != '"')
3523 g_string_append(matcherstr, "\"");
3525 /* restore original character */
3526 *cmd_end = save_char;
3534 cmd_start = cmd_end;
3539 returnstr = matcherstr->str;
3540 g_string_free(matcherstr, FALSE);
3544 guint g_stricase_hash(gconstpointer gptr)
3546 guint hash_result = 0;
3549 for (str = gptr; str && *str; str++) {
3550 if (isupper(*str)) hash_result += (*str + ' ');
3551 else hash_result += *str;
3557 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3559 const char *str1 = gptr1;
3560 const char *str2 = gptr2;
3562 return !strcasecmp(str1, str2);
3565 gint g_int_compare(gconstpointer a, gconstpointer b)
3567 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);