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 void ptr_array_free_strings(GPtrArray *array)
117 g_return_if_fail(array != NULL);
119 for (i = 0; i < array->len; i++) {
120 str = g_ptr_array_index(array, i);
125 gint to_number(const gchar *nstr)
127 register const gchar *p;
129 if (*nstr == '\0') return -1;
131 for (p = nstr; *p != '\0'; p++)
132 if (!isdigit(*p)) return -1;
137 /* convert integer into string,
138 nstr must be not lower than 11 characters length */
139 gchar *itos_buf(gchar *nstr, gint n)
141 g_snprintf(nstr, 11, "%d", n);
145 /* convert integer into string */
148 static gchar nstr[11];
150 return itos_buf(nstr, n);
153 gchar *to_human_readable(off_t size)
155 static gchar str[10];
158 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
159 else if (size >> 10 < 1024)
160 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
161 else if (size >> 20 < 1024)
162 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
164 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
169 /* strcmp with NULL-checking */
170 gint strcmp2(const gchar *s1, const gchar *s2)
172 if (s1 == NULL || s2 == NULL)
175 return strcmp(s1, s2);
177 /* strstr with NULL-checking */
178 gchar *strstr2(const gchar *s1, const gchar *s2)
180 if (s1 == NULL || s2 == NULL)
183 return strstr(s1, s2);
186 gint path_cmp(const gchar *s1, const gchar *s2)
190 if (s1 == NULL || s2 == NULL) return -1;
191 if (*s1 == '\0' || *s2 == '\0') return -1;
196 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
197 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
199 return strncmp(s1, s2, MAX(len1, len2));
202 /* remove trailing return code */
203 gchar *strretchomp(gchar *str)
207 if (!*str) return str;
209 for (s = str + strlen(str) - 1;
210 s >= str && (*s == '\n' || *s == '\r');
217 /* remove trailing character */
218 gchar *strtailchomp(gchar *str, gchar tail_char)
222 if (!*str) return str;
223 if (tail_char == '\0') return str;
225 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
231 /* remove CR (carriage return) */
232 gchar *strcrchomp(gchar *str)
236 if (!*str) return str;
238 s = str + strlen(str) - 1;
239 if (*s == '\n' && s > str && *(s - 1) == '\r') {
247 /* Similar to `strstr' but this function ignores the case of both strings. */
248 gchar *strcasestr(const gchar *haystack, const gchar *needle)
250 register size_t haystack_len, needle_len;
252 haystack_len = strlen(haystack);
253 needle_len = strlen(needle);
255 if (haystack_len < needle_len || needle_len == 0)
258 while (haystack_len >= needle_len) {
259 if (!strncasecmp(haystack, needle, needle_len))
260 return (gchar *)haystack;
270 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
271 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
285 /* don't do zero fill */
290 int iswalnum(wint_t wc)
292 return isalnum((int)wc);
297 int iswspace(wint_t wc)
299 return isspace((int)wc);
304 wint_t towlower(wint_t wc)
306 if (wc >= L'A' && wc <= L'Z')
307 return wc + L'a' - L'A';
314 size_t wcslen(const wchar_t *s)
326 /* Copy SRC to DEST. */
327 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
335 } while (c != L'\0');
342 /* Copy no more than N wide-characters of SRC to DEST. */
343 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
353 } while (c != L'\0');
364 /* Duplicate S, returning an identical malloc'd string. */
365 wchar_t *wcsdup(const wchar_t *s)
370 new_str = g_new(wchar_t, wcslen(s) + 1);
378 /* Duplicate no more than N wide-characters of S,
379 returning an identical malloc'd string. */
380 wchar_t *wcsndup(const wchar_t *s, size_t n)
385 new_str = g_new(wchar_t, n + 1);
386 wcsncpy(new_str, s, n);
387 new_str[n] = (wchar_t)0;
394 wchar_t *strdup_mbstowcs(const gchar *s)
399 new_str = g_new(wchar_t, strlen(s) + 1);
400 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
404 new_str = g_realloc(new_str,
405 sizeof(wchar_t) * (wcslen(new_str) + 1));
412 gchar *strdup_wcstombs(const wchar_t *s)
418 len = wcslen(s) * MB_CUR_MAX + 1;
419 new_str = g_new(gchar, len);
420 if (wcstombs(new_str, s, len) < 0) {
424 new_str = g_realloc(new_str, strlen(new_str) + 1);
431 /* Compare S1 and S2, ignoring case. */
432 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
438 c1 = towlower(*s1++);
439 c2 = towlower(*s2++);
442 else if (c1 == 0 && c2 == 0)
449 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
450 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
452 register size_t haystack_len, needle_len;
454 haystack_len = wcslen(haystack);
455 needle_len = wcslen(needle);
457 if (haystack_len < needle_len || needle_len == 0)
460 while (haystack_len >= needle_len) {
461 if (!wcsncasecmp(haystack, needle, needle_len))
462 return (wchar_t *)haystack;
472 gint get_wcs_len(const gchar *s)
482 mb_len = mblen(p, MB_LEN_MAX);
496 /* Examine if next block is non-ASCII string */
497 gboolean is_next_nonascii(const guchar *s)
501 /* skip head space */
502 for (p = s; *p != '\0' && isspace(*p); p++)
504 for (; *p != '\0' && !isspace(*p); p++) {
505 if (*p > 127 || *p < 32)
512 gint get_next_word_len(const gchar *s)
516 for (; *s != '\0' && !isspace(*s); s++, len++)
522 /* compare subjects */
523 gint subject_compare(const gchar *s1, const gchar *s2)
527 if (!s1 || !s2) return -1;
528 if (!*s1 || !*s2) return -1;
530 Xstrdup_a(str1, s1, return -1);
531 Xstrdup_a(str2, s2, return -1);
533 trim_subject_for_compare(str1);
534 trim_subject_for_compare(str2);
536 if (!*str1 || !*str2) return -1;
538 return strcmp(str1, str2);
541 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
545 if (!s1 || !s2) return -1;
547 Xstrdup_a(str1, s1, return -1);
548 Xstrdup_a(str2, s2, return -1);
550 trim_subject_for_sort(str1);
551 trim_subject_for_sort(str2);
553 return strcasecmp(str1, str2);
556 void trim_subject_for_compare(gchar *str)
560 eliminate_parenthesis(str, '[', ']');
561 eliminate_parenthesis(str, '(', ')');
564 while (!strncasecmp(str, "Re:", 3)) {
566 while (isspace(*srcp)) srcp++;
567 memmove(str, srcp, strlen(srcp) + 1);
571 void trim_subject_for_sort(gchar *str)
577 while (!strncasecmp(str, "Re:", 3)) {
579 while (isspace(*srcp)) srcp++;
580 memmove(str, srcp, strlen(srcp) + 1);
584 void trim_subject(gchar *str)
586 register gchar *srcp, *destp;
591 while (!strncasecmp(destp, "Re:", 3)) {
593 while (isspace(*destp)) destp++;
599 } else if (*destp == '(') {
610 else if (*srcp == cl)
616 while (isspace(*srcp)) srcp++;
617 memmove(destp, srcp, strlen(srcp) + 1);
620 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
622 register gchar *srcp, *destp;
627 while ((destp = strchr(destp, op))) {
633 else if (*srcp == cl)
639 while (isspace(*srcp)) srcp++;
640 memmove(destp, srcp, strlen(srcp) + 1);
644 void extract_parenthesis(gchar *str, gchar op, gchar cl)
646 register gchar *srcp, *destp;
651 while ((srcp = strchr(destp, op))) {
654 memmove(destp, srcp + 1, strlen(srcp));
659 else if (*destp == cl)
671 void extract_one_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
674 register gchar *srcp, *destp;
676 gboolean in_quote = FALSE;
680 if ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
681 memmove(destp, srcp + 1, strlen(srcp));
684 if (*destp == op && !in_quote)
686 else if (*destp == cl && !in_quote)
688 else if (*destp == quote_chr)
700 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
703 register gchar *srcp, *destp;
705 gboolean in_quote = FALSE;
709 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
712 memmove(destp, srcp + 1, strlen(srcp));
715 if (*destp == op && !in_quote)
717 else if (*destp == cl && !in_quote)
719 else if (*destp == quote_chr)
731 void eliminate_quote(gchar *str, gchar quote_chr)
733 register gchar *srcp, *destp;
737 while ((destp = strchr(destp, quote_chr))) {
738 if ((srcp = strchr(destp + 1, quote_chr))) {
740 while (isspace(*srcp)) srcp++;
741 memmove(destp, srcp, strlen(srcp) + 1);
749 void extract_quote(gchar *str, gchar quote_chr)
753 if ((str = strchr(str, quote_chr))) {
755 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
756 memmove(p - 1, p, strlen(p) + 1);
761 memmove(str, str + 1, p - str);
766 void eliminate_address_comment(gchar *str)
768 register gchar *srcp, *destp;
773 while ((destp = strchr(destp, '"'))) {
774 if ((srcp = strchr(destp + 1, '"'))) {
779 while (isspace(*srcp)) srcp++;
780 memmove(destp, srcp, strlen(srcp) + 1);
790 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
796 else if (*srcp == ')')
802 while (isspace(*srcp)) srcp++;
803 memmove(destp, srcp, strlen(srcp) + 1);
807 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
809 gboolean in_quote = FALSE;
812 if (*str == c && !in_quote)
814 if (*str == quote_chr)
822 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
824 gboolean in_quote = FALSE;
827 p = str + strlen(str) - 1;
829 if (*p == c && !in_quote)
839 void extract_address(gchar *str)
841 eliminate_address_comment(str);
842 if (strchr_with_skip_quote(str, '"', '<'))
843 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
847 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
852 if (!str) return addr_list;
854 Xstrdup_a(work, str, return addr_list);
857 eliminate_address_comment(work);
860 while (workp && *workp) {
863 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
869 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
870 extract_parenthesis_with_skip_quote
871 (workp, '"', '<', '>');
875 addr_list = g_slist_append(addr_list, g_strdup(workp));
883 GSList *address_list_append(GSList *addr_list, const gchar *str)
885 return address_list_append_real(addr_list, str, TRUE);
888 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
890 return address_list_append_real(addr_list, str, FALSE);
893 GSList *references_list_append(GSList *msgid_list, const gchar *str)
897 if (!str) return msgid_list;
900 while (strp && *strp) {
901 const gchar *start, *end;
904 if ((start = strchr(strp, '<')) != NULL) {
905 end = strchr(start + 1, '>');
910 msgid = g_strndup(start + 1, end - start - 1);
913 msgid_list = g_slist_append(msgid_list, msgid);
923 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
928 if (!str) return group_list;
930 Xstrdup_a(work, str, return group_list);
934 while (workp && *workp) {
937 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
945 group_list = g_slist_append(group_list,
954 GList *add_history(GList *list, const gchar *str)
958 g_return_val_if_fail(str != NULL, list);
960 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
963 list = g_list_remove(list, old->data);
964 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
967 last = g_list_last(list);
970 g_list_remove(list, last->data);
974 list = g_list_prepend(list, g_strdup(str));
979 void remove_return(gchar *str)
981 register gchar *p = str;
984 if (*p == '\n' || *p == '\r')
985 memmove(p, p + 1, strlen(p));
991 void remove_space(gchar *str)
993 register gchar *p = str;
998 while (isspace(*(p + spc)))
1001 memmove(p, p + spc, strlen(p + spc) + 1);
1007 void unfold_line(gchar *str)
1009 register gchar *p = str;
1013 if (*p == '\n' || *p == '\r') {
1016 while (isspace(*(p + spc)))
1019 memmove(p, p + spc, strlen(p + spc) + 1);
1025 void subst_char(gchar *str, gchar orig, gchar subst)
1027 register gchar *p = str;
1036 void subst_chars(gchar *str, gchar *orig, gchar subst)
1038 register gchar *p = str;
1041 if (strchr(orig, *p) != NULL)
1047 void subst_for_filename(gchar *str)
1049 subst_chars(str, " \t\r\n\"/\\", '_');
1052 gboolean is_header_line(const gchar *str)
1054 if (str[0] == ':') return FALSE;
1056 while (*str != '\0' && *str != ' ') {
1065 gboolean is_ascii_str(const guchar *str)
1067 while (*str != '\0') {
1068 if (*str != '\t' && *str != ' ' &&
1069 *str != '\r' && *str != '\n' &&
1070 (*str < 32 || *str >= 127))
1078 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1080 const gchar *first_pos;
1081 const gchar *last_pos;
1082 const gchar *p = str;
1083 gint quote_level = -1;
1085 /* speed up line processing by only searching to the last '>' */
1086 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1087 /* skip a line if it contains a '<' before the initial '>' */
1088 if (memchr(str, '<', first_pos - str) != NULL)
1090 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1094 while (p <= last_pos) {
1095 while (p < last_pos) {
1102 if (strchr(quote_chars, *p))
1104 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1105 /* any characters are allowed except '-' and space */
1107 && !strchr(quote_chars, *p)
1111 if (strchr(quote_chars, *p))
1123 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1125 gchar * position = NULL;
1126 gchar * tmp_pos = NULL;
1129 if (quote_chars == NULL)
1132 for (i = 0; i < strlen(quote_chars); i++) {
1133 tmp_pos = strchr (str, quote_chars[i]);
1135 || (tmp_pos != NULL && position >= tmp_pos) )
1141 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1143 gchar * position = NULL;
1144 gchar * tmp_pos = NULL;
1147 if (quote_chars == NULL)
1150 for (i = 0; i < strlen(quote_chars); i++) {
1151 tmp_pos = strrchr (str, quote_chars[i]);
1153 || (tmp_pos != NULL && position <= tmp_pos) )
1159 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1161 register guint haystack_len, needle_len;
1162 gboolean in_squote = FALSE, in_dquote = FALSE;
1164 haystack_len = strlen(haystack);
1165 needle_len = strlen(needle);
1167 if (haystack_len < needle_len || needle_len == 0)
1170 while (haystack_len >= needle_len) {
1171 if (!in_squote && !in_dquote &&
1172 !strncmp(haystack, needle, needle_len))
1173 return (gchar *)haystack;
1175 /* 'foo"bar"' -> foo"bar"
1176 "foo'bar'" -> foo'bar' */
1177 if (*haystack == '\'') {
1180 else if (!in_dquote)
1182 } else if (*haystack == '\"') {
1185 else if (!in_squote)
1196 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1199 gchar quote_chr = '"';
1201 gboolean in_quote = FALSE;
1205 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1209 if (*p == op && !in_quote)
1211 else if (*p == cl && !in_quote)
1213 else if (*p == quote_chr)
1226 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1229 GSList *string_list = NULL, *slist;
1231 const gchar *s_op, *s_cl;
1234 g_return_val_if_fail(str != NULL, NULL);
1237 max_tokens = G_MAXINT;
1239 s_op = strchr_with_skip_quote(str, '"', op);
1240 if (!s_op) return NULL;
1242 s_cl = strchr_parenthesis_close(str, op, cl);
1250 new_string = g_new(gchar, len + 1);
1251 strncpy(new_string, str, len);
1252 new_string[len] = 0;
1253 string_list = g_slist_prepend(string_list, new_string);
1257 while (*str && isspace(*str)) str++;
1259 string_list = g_slist_prepend(string_list,
1262 s_op = strchr_with_skip_quote(str, '"', op);
1263 if (!--max_tokens || !s_op) break;
1267 s_cl = strchr_parenthesis_close(str, op, cl);
1268 } while (--max_tokens && s_cl);
1271 str_array = g_new(gchar*, n);
1275 str_array[i--] = NULL;
1276 for (slist = string_list; slist; slist = slist->next)
1277 str_array[i--] = slist->data;
1279 g_slist_free(string_list);
1284 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1287 GSList *string_list = NULL, *slist;
1288 gchar **str_array, *s, *new_str;
1289 guint i, n = 1, len;
1291 g_return_val_if_fail(str != NULL, NULL);
1292 g_return_val_if_fail(delim != NULL, NULL);
1295 max_tokens = G_MAXINT;
1297 s = strstr_with_skip_quote(str, delim);
1299 guint delimiter_len = strlen(delim);
1303 new_str = g_strndup(str, len);
1305 if (new_str[0] == '\'' || new_str[0] == '\"') {
1306 if (new_str[len - 1] == new_str[0]) {
1307 new_str[len - 1] = '\0';
1308 memmove(new_str, new_str + 1, len - 1);
1311 string_list = g_slist_prepend(string_list, new_str);
1313 str = s + delimiter_len;
1314 s = strstr_with_skip_quote(str, delim);
1315 } while (--max_tokens && s);
1319 new_str = g_strdup(str);
1320 if (new_str[0] == '\'' || new_str[0] == '\"') {
1322 if (new_str[len - 1] == new_str[0]) {
1323 new_str[len - 1] = '\0';
1324 memmove(new_str, new_str + 1, len - 1);
1327 string_list = g_slist_prepend(string_list, new_str);
1331 str_array = g_new(gchar*, n);
1335 str_array[i--] = NULL;
1336 for (slist = string_list; slist; slist = slist->next)
1337 str_array[i--] = slist->data;
1339 g_slist_free(string_list);
1344 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1346 gchar *abbrev_group;
1348 const gchar *p = group;
1351 g_return_val_if_fail(group != NULL, NULL);
1353 last = group + strlen(group);
1354 abbrev_group = ap = g_malloc(strlen(group) + 1);
1359 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1361 while (*p != '.') p++;
1364 return abbrev_group;
1369 return abbrev_group;
1372 gchar *trim_string(const gchar *str, gint len)
1374 const gchar *p = str;
1379 if (!str) return NULL;
1380 if (strlen(str) <= len)
1381 return g_strdup(str);
1383 while (*p != '\0') {
1384 mb_len = mblen(p, MB_LEN_MAX);
1387 else if (mb_len < 0)
1388 return g_strdup(str);
1389 else if (new_len + mb_len > len)
1396 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1397 return g_strconcat(new_str, "...", NULL);
1400 GList *uri_list_extract_filenames(const gchar *uri_list)
1402 GList *result = NULL;
1410 while (isspace(*p)) p++;
1411 if (!strncmp(p, "file:", 5)) {
1414 while (*q && *q != '\n' && *q != '\r') q++;
1418 while (q > p && isspace(*q)) q--;
1419 file = g_malloc(q - p + 2);
1420 strncpy(file, p, q - p + 1);
1421 file[q - p + 1] = '\0';
1422 result = g_list_append(result,file);
1426 p = strchr(p, '\n');
1433 #define HEX_TO_INT(val, hex) \
1437 if ('0' <= c && c <= '9') { \
1439 } else if ('a' <= c && c <= 'f') { \
1440 val = c - 'a' + 10; \
1441 } else if ('A' <= c && c <= 'F') { \
1442 val = c - 'A' + 10; \
1448 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1449 gchar **subject, gchar **body)
1454 Xstrdup_a(tmp_mailto, mailto, return -1);
1456 if (!strncmp(tmp_mailto, "mailto:", 7))
1459 p = strchr(tmp_mailto, '?');
1466 *to = g_strdup(tmp_mailto);
1469 gchar *field, *value;
1486 if (*value == '\0') continue;
1488 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1489 *cc = g_strdup(value);
1490 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1491 *bcc = g_strdup(value);
1492 } else if (subject && !*subject &&
1493 !g_strcasecmp(field, "subject")) {
1494 *subject = g_malloc(strlen(value) + 1);
1495 decode_uri(*subject, value);
1496 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1497 *body = g_malloc(strlen(value) + 1);
1498 decode_uri(*body, value);
1506 * We need this wrapper around g_get_home_dir(), so that
1507 * we can fix some Windoze things here. Should be done in glibc of course
1508 * but as long as we are not able to do our own extensions to glibc, we do
1511 gchar *get_home_dir(void)
1513 #if HAVE_DOSISH_SYSTEM
1514 static gchar *home_dir;
1517 home_dir = read_w32_registry_string(NULL,
1518 "Software\\Sylpheed", "HomeDir" );
1519 if (!home_dir || !*home_dir) {
1520 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1521 const char *s = g_get_home_dir();
1523 home_dir = g_strdup (s);
1525 if (!home_dir || !*home_dir)
1526 home_dir = g_strdup ("c:\\sylpheed");
1528 debug_print("initialized home_dir to `%s'\n", home_dir);
1531 #else /* standard glib */
1532 return g_get_home_dir();
1536 gchar *get_rc_dir(void)
1538 static gchar *rc_dir = NULL;
1541 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1547 gchar *get_news_cache_dir(void)
1549 static gchar *news_cache_dir = NULL;
1551 if (!news_cache_dir)
1552 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1553 NEWS_CACHE_DIR, NULL);
1555 return news_cache_dir;
1558 gchar *get_imap_cache_dir(void)
1560 static gchar *imap_cache_dir = NULL;
1562 if (!imap_cache_dir)
1563 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1564 IMAP_CACHE_DIR, NULL);
1566 return imap_cache_dir;
1569 gchar *get_mbox_cache_dir(void)
1571 static gchar *mbox_cache_dir = NULL;
1573 if (!mbox_cache_dir)
1574 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1575 MBOX_CACHE_DIR, NULL);
1577 return mbox_cache_dir;
1580 gchar *get_mime_tmp_dir(void)
1582 static gchar *mime_tmp_dir = NULL;
1585 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1586 MIME_TMP_DIR, NULL);
1588 return mime_tmp_dir;
1591 gchar *get_template_dir(void)
1593 static gchar *template_dir = NULL;
1596 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1597 TEMPLATE_DIR, NULL);
1599 return template_dir;
1602 gchar *get_header_cache_dir(void)
1604 static gchar *header_dir = NULL;
1607 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1608 HEADER_CACHE_DIR, NULL);
1613 gchar *get_tmp_dir(void)
1615 static gchar *tmp_dir = NULL;
1618 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1624 gchar *get_tmp_file(void)
1627 static guint32 id = 0;
1629 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1630 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1635 gchar *get_domain_name(void)
1637 static gchar *domain_name = NULL;
1640 gchar buf[128] = "";
1643 if (gethostname(buf, sizeof(buf)) < 0) {
1644 perror("gethostname");
1645 domain_name = "unknown";
1647 buf[sizeof(buf) - 1] = '\0';
1648 if ((hp = my_gethostbyname(buf)) == NULL) {
1649 perror("gethostbyname");
1650 domain_name = g_strdup(buf);
1652 domain_name = g_strdup(hp->h_name);
1656 debug_print("domain name = %s\n", domain_name);
1662 off_t get_file_size(const gchar *file)
1666 if (stat(file, &s) < 0) {
1667 FILE_OP_ERROR(file, "stat");
1674 off_t get_file_size_as_crlf(const gchar *file)
1678 gchar buf[BUFFSIZE];
1680 if ((fp = fopen(file, "rb")) == NULL) {
1681 FILE_OP_ERROR(file, "fopen");
1685 while (fgets(buf, sizeof(buf), fp) != NULL) {
1687 size += strlen(buf) + 2;
1691 FILE_OP_ERROR(file, "fgets");
1700 off_t get_left_file_size(FILE *fp)
1706 if ((pos = ftell(fp)) < 0) {
1710 if (fseek(fp, 0L, SEEK_END) < 0) {
1714 if ((end = ftell(fp)) < 0) {
1719 if (fseek(fp, pos, SEEK_SET) < 0) {
1727 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1734 if (stat(file, &s) < 0) {
1735 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1739 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1745 gboolean is_dir_exist(const gchar *dir)
1752 if (stat(dir, &s) < 0) {
1753 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1757 if (S_ISDIR(s.st_mode))
1763 gboolean is_file_entry_exist(const gchar *file)
1770 if (stat(file, &s) < 0) {
1771 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1778 gint change_dir(const gchar *dir)
1780 gchar *prevdir = NULL;
1783 prevdir = g_get_current_dir();
1785 if (chdir(dir) < 0) {
1786 FILE_OP_ERROR(dir, "chdir");
1787 if (debug_mode) g_free(prevdir);
1789 } else if (debug_mode) {
1792 cwd = g_get_current_dir();
1793 if (strcmp(prevdir, cwd) != 0)
1794 g_print("current dir: %s\n", cwd);
1802 gint make_dir(const gchar *dir)
1804 if (mkdir(dir, S_IRWXU) < 0) {
1805 FILE_OP_ERROR(dir, "mkdir");
1808 if (chmod(dir, S_IRWXU) < 0)
1809 FILE_OP_ERROR(dir, "chmod");
1814 gint make_dir_hier(const gchar *dir)
1819 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1820 parent_dir = g_strndup(dir, p - dir);
1821 if (*parent_dir != '\0') {
1822 if (!is_dir_exist(parent_dir)) {
1823 if (make_dir(parent_dir) < 0) {
1832 if (!is_dir_exist(dir)) {
1833 if (make_dir(dir) < 0)
1840 gint remove_all_files(const gchar *dir)
1846 prev_dir = g_get_current_dir();
1848 if (chdir(dir) < 0) {
1849 FILE_OP_ERROR(dir, "chdir");
1854 if ((dp = opendir(".")) == NULL) {
1855 FILE_OP_ERROR(dir, "opendir");
1860 while ((d = readdir(dp)) != NULL) {
1861 if (!strcmp(d->d_name, ".") ||
1862 !strcmp(d->d_name, ".."))
1865 if (unlink(d->d_name) < 0)
1866 FILE_OP_ERROR(d->d_name, "unlink");
1871 if (chdir(prev_dir) < 0) {
1872 FILE_OP_ERROR(prev_dir, "chdir");
1882 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1889 prev_dir = g_get_current_dir();
1891 if (chdir(dir) < 0) {
1892 FILE_OP_ERROR(dir, "chdir");
1897 if ((dp = opendir(".")) == NULL) {
1898 FILE_OP_ERROR(dir, "opendir");
1903 while ((d = readdir(dp)) != NULL) {
1904 fileno = to_number(d->d_name);
1905 if (fileno >= 0 && first <= fileno && fileno <= last) {
1906 if (is_dir_exist(d->d_name))
1908 if (unlink(d->d_name) < 0)
1909 FILE_OP_ERROR(d->d_name, "unlink");
1915 if (chdir(prev_dir) < 0) {
1916 FILE_OP_ERROR(prev_dir, "chdir");
1926 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1933 prev_dir = g_get_current_dir();
1935 if (chdir(dir) < 0) {
1936 FILE_OP_ERROR(dir, "chdir");
1941 if ((dp = opendir(".")) == NULL) {
1942 FILE_OP_ERROR(dir, "opendir");
1947 while ((d = readdir(dp)) != NULL) {
1948 fileno = to_number(d->d_name);
1949 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1950 debug_print("removing unwanted file %d from %s\n", fileno, dir);
1951 if (is_dir_exist(d->d_name))
1953 if (unlink(d->d_name) < 0)
1954 FILE_OP_ERROR(d->d_name, "unlink");
1960 if (chdir(prev_dir) < 0) {
1961 FILE_OP_ERROR(prev_dir, "chdir");
1971 gint remove_all_numbered_files(const gchar *dir)
1973 return remove_numbered_files(dir, 0, UINT_MAX);
1976 gint remove_expired_files(const gchar *dir, guint hours)
1983 time_t mtime, now, expire_time;
1985 prev_dir = g_get_current_dir();
1987 if (chdir(dir) < 0) {
1988 FILE_OP_ERROR(dir, "chdir");
1993 if ((dp = opendir(".")) == NULL) {
1994 FILE_OP_ERROR(dir, "opendir");
2000 expire_time = hours * 60 * 60;
2002 while ((d = readdir(dp)) != NULL) {
2003 fileno = to_number(d->d_name);
2005 if (stat(d->d_name, &s) < 0) {
2006 FILE_OP_ERROR(d->d_name, "stat");
2009 if (S_ISDIR(s.st_mode))
2011 mtime = MAX(s.st_mtime, s.st_atime);
2012 if (now - mtime > expire_time) {
2013 if (unlink(d->d_name) < 0)
2014 FILE_OP_ERROR(d->d_name, "unlink");
2021 if (chdir(prev_dir) < 0) {
2022 FILE_OP_ERROR(prev_dir, "chdir");
2032 gint remove_dir_recursive(const gchar *dir)
2039 /* g_print("dir = %s\n", dir); */
2041 if (stat(dir, &s) < 0) {
2042 FILE_OP_ERROR(dir, "stat");
2043 if (ENOENT == errno) return 0;
2047 if (!S_ISDIR(s.st_mode)) {
2048 if (unlink(dir) < 0) {
2049 FILE_OP_ERROR(dir, "unlink");
2056 prev_dir = g_get_current_dir();
2057 /* g_print("prev_dir = %s\n", prev_dir); */
2059 if (!path_cmp(prev_dir, dir)) {
2061 if (chdir("..") < 0) {
2062 FILE_OP_ERROR(dir, "chdir");
2065 prev_dir = g_get_current_dir();
2068 if (chdir(dir) < 0) {
2069 FILE_OP_ERROR(dir, "chdir");
2074 if ((dp = opendir(".")) == NULL) {
2075 FILE_OP_ERROR(dir, "opendir");
2081 /* remove all files in the directory */
2082 while ((d = readdir(dp)) != NULL) {
2083 if (!strcmp(d->d_name, ".") ||
2084 !strcmp(d->d_name, ".."))
2087 if (stat(d->d_name, &s) < 0) {
2088 FILE_OP_ERROR(d->d_name, "stat");
2092 /* g_print("removing %s\n", d->d_name); */
2094 if (S_ISDIR(s.st_mode)) {
2095 if (remove_dir_recursive(d->d_name) < 0) {
2096 g_warning("can't remove directory\n");
2100 if (unlink(d->d_name) < 0)
2101 FILE_OP_ERROR(d->d_name, "unlink");
2107 if (chdir(prev_dir) < 0) {
2108 FILE_OP_ERROR(prev_dir, "chdir");
2115 if (rmdir(dir) < 0) {
2116 FILE_OP_ERROR(dir, "rmdir");
2124 /* this seems to be slower than the stdio version... */
2125 gint copy_file(const gchar *src, const gchar *dest)
2127 gint src_fd, dest_fd;
2131 gchar *dest_bak = NULL;
2133 if ((src_fd = open(src, O_RDONLY)) < 0) {
2134 FILE_OP_ERROR(src, "open");
2138 if (is_file_exist(dest)) {
2139 dest_bak = g_strconcat(dest, ".bak", NULL);
2140 if (rename(dest, dest_bak) < 0) {
2141 FILE_OP_ERROR(dest, "rename");
2148 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2149 FILE_OP_ERROR(dest, "open");
2152 if (rename(dest_bak, dest) < 0)
2153 FILE_OP_ERROR(dest_bak, "rename");
2159 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2164 n_write = write(dest_fd, bufp, len);
2166 g_warning("writing to %s failed.\n", dest);
2171 if (rename(dest_bak, dest) < 0)
2172 FILE_OP_ERROR(dest_bak, "rename");
2185 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2186 g_warning("File copy from %s to %s failed.\n", src, dest);
2189 if (rename(dest_bak, dest) < 0)
2190 FILE_OP_ERROR(dest_bak, "rename");
2203 * Append src file body to the tail of dest file.
2204 * Now keep_backup has no effects.
2206 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2208 FILE *src_fp, *dest_fp;
2212 gboolean err = FALSE;
2214 if ((src_fp = fopen(src, "rb")) == NULL) {
2215 FILE_OP_ERROR(src, "fopen");
2219 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2220 FILE_OP_ERROR(dest, "fopen");
2225 if (change_file_mode_rw(dest_fp, dest) < 0) {
2226 FILE_OP_ERROR(dest, "chmod");
2227 g_warning("can't change file mode\n");
2230 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2231 if (n_read < sizeof(buf) && ferror(src_fp))
2233 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2234 g_warning("writing to %s failed.\n", dest);
2242 if (ferror(src_fp)) {
2243 FILE_OP_ERROR(src, "fread");
2247 if (fclose(dest_fp) == EOF) {
2248 FILE_OP_ERROR(dest, "fclose");
2260 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2262 FILE *src_fp, *dest_fp;
2265 gchar *dest_bak = NULL;
2266 gboolean err = FALSE;
2268 if ((src_fp = fopen(src, "rb")) == NULL) {
2269 FILE_OP_ERROR(src, "fopen");
2272 if (is_file_exist(dest)) {
2273 dest_bak = g_strconcat(dest, ".bak", NULL);
2274 if (rename(dest, dest_bak) < 0) {
2275 FILE_OP_ERROR(dest, "rename");
2282 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2283 FILE_OP_ERROR(dest, "fopen");
2286 if (rename(dest_bak, dest) < 0)
2287 FILE_OP_ERROR(dest_bak, "rename");
2293 if (change_file_mode_rw(dest_fp, dest) < 0) {
2294 FILE_OP_ERROR(dest, "chmod");
2295 g_warning("can't change file mode\n");
2298 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2299 if (n_read < sizeof(buf) && ferror(src_fp))
2301 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2302 g_warning("writing to %s failed.\n", dest);
2307 if (rename(dest_bak, dest) < 0)
2308 FILE_OP_ERROR(dest_bak, "rename");
2315 if (ferror(src_fp)) {
2316 FILE_OP_ERROR(src, "fread");
2320 if (fclose(dest_fp) == EOF) {
2321 FILE_OP_ERROR(dest, "fclose");
2328 if (rename(dest_bak, dest) < 0)
2329 FILE_OP_ERROR(dest_bak, "rename");
2335 if (keep_backup == FALSE && dest_bak)
2343 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2345 if (overwrite == FALSE && is_file_exist(dest)) {
2346 g_warning("move_file(): file %s already exists.", dest);
2350 if (rename(src, dest) == 0) return 0;
2352 if (EXDEV != errno) {
2353 FILE_OP_ERROR(src, "rename");
2357 if (copy_file(src, dest, FALSE) < 0) return -1;
2364 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2368 gint bytes_left, to_read;
2370 gboolean err = FALSE;
2372 if (fseek(fp, offset, SEEK_SET) < 0) {
2377 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2378 FILE_OP_ERROR(dest, "fopen");
2382 if (change_file_mode_rw(dest_fp, dest) < 0) {
2383 FILE_OP_ERROR(dest, "chmod");
2384 g_warning("can't change file mode\n");
2387 bytes_left = length;
2388 to_read = MIN(bytes_left, sizeof(buf));
2390 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2391 if (n_read < to_read && ferror(fp))
2393 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2394 g_warning("writing to %s failed.\n", dest);
2399 bytes_left -= n_read;
2400 if (bytes_left == 0)
2402 to_read = MIN(bytes_left, sizeof(buf));
2409 if (fclose(dest_fp) == EOF) {
2410 FILE_OP_ERROR(dest, "fclose");
2422 /* convert line endings into CRLF. If the last line doesn't end with
2423 * linebreak, add it.
2425 gchar *canonicalize_str(const gchar *str)
2431 for (p = str; *p != '\0'; ++p) {
2438 if (p == str || *(p - 1) != '\n')
2441 out = outp = g_malloc(new_len + 1);
2442 for (p = str; *p != '\0'; ++p) {
2449 if (p == str || *(p - 1) != '\n') {
2458 gint canonicalize_file(const gchar *src, const gchar *dest)
2460 FILE *src_fp, *dest_fp;
2461 gchar buf[BUFFSIZE];
2463 gboolean err = FALSE;
2464 gboolean last_linebreak = FALSE;
2466 if ((src_fp = fopen(src, "rb")) == NULL) {
2467 FILE_OP_ERROR(src, "fopen");
2471 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2472 FILE_OP_ERROR(dest, "fopen");
2477 if (change_file_mode_rw(dest_fp, dest) < 0) {
2478 FILE_OP_ERROR(dest, "chmod");
2479 g_warning("can't change file mode\n");
2482 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2486 if (len == 0) break;
2487 last_linebreak = FALSE;
2489 if (buf[len - 1] != '\n') {
2490 last_linebreak = TRUE;
2491 r = fputs(buf, dest_fp);
2492 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2493 r = fputs(buf, dest_fp);
2496 r = fwrite(buf, len - 1, 1, dest_fp);
2501 r = fputs("\r\n", dest_fp);
2505 g_warning("writing to %s failed.\n", dest);
2513 if (last_linebreak == TRUE) {
2514 if (fputs("\r\n", dest_fp) == EOF)
2518 if (ferror(src_fp)) {
2519 FILE_OP_ERROR(src, "fgets");
2523 if (fclose(dest_fp) == EOF) {
2524 FILE_OP_ERROR(dest, "fclose");
2536 gint canonicalize_file_replace(const gchar *file)
2540 tmp_file = get_tmp_file();
2542 if (canonicalize_file(file, tmp_file) < 0) {
2547 if (move_file(tmp_file, file, TRUE) < 0) {
2548 g_warning("can't replace %s .\n", file);
2558 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2560 FILE *src_fp, *dest_fp;
2561 gchar buf[BUFFSIZE];
2562 gboolean err = FALSE;
2564 if ((src_fp = fopen(src, "rb")) == NULL) {
2565 FILE_OP_ERROR(src, "fopen");
2569 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2570 FILE_OP_ERROR(dest, "fopen");
2575 if (change_file_mode_rw(dest_fp, dest) < 0) {
2576 FILE_OP_ERROR(dest, "chmod");
2577 g_warning("can't change file mode\n");
2580 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2582 if (fputs(buf, dest_fp) == EOF) {
2583 g_warning("writing to %s failed.\n", dest);
2591 if (ferror(src_fp)) {
2592 FILE_OP_ERROR(src, "fgets");
2596 if (fclose(dest_fp) == EOF) {
2597 FILE_OP_ERROR(dest, "fclose");
2609 gint uncanonicalize_file_replace(const gchar *file)
2613 tmp_file = get_tmp_file();
2615 if (uncanonicalize_file(file, tmp_file) < 0) {
2620 if (move_file(tmp_file, file, TRUE) < 0) {
2621 g_warning("can't replace %s .\n", file);
2631 gchar *normalize_newlines(const gchar *str)
2633 const gchar *p = str;
2636 out = outp = g_malloc(strlen(str) + 1);
2637 for (p = str; *p != '\0'; ++p) {
2639 if (*(p + 1) != '\n')
2650 gchar *get_outgoing_rfc2822_str(FILE *fp)
2652 gchar buf[BUFFSIZE];
2656 str = g_string_new(NULL);
2658 /* output header part */
2659 while (fgets(buf, sizeof(buf), fp) != NULL) {
2661 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2668 else if (next != ' ' && next != '\t') {
2672 if (fgets(buf, sizeof(buf), fp) == NULL)
2676 g_string_append(str, buf);
2677 g_string_append(str, "\r\n");
2683 /* output body part */
2684 while (fgets(buf, sizeof(buf), fp) != NULL) {
2687 g_string_append_c(str, '.');
2688 g_string_append(str, buf);
2689 g_string_append(str, "\r\n");
2693 g_string_free(str, FALSE);
2698 gint change_file_mode_rw(FILE *fp, const gchar *file)
2701 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2703 return chmod(file, S_IRUSR|S_IWUSR);
2707 FILE *my_tmpfile(void)
2710 const gchar suffix[] = ".XXXXXX";
2711 const gchar *tmpdir;
2713 const gchar *progname;
2719 tmpdir = get_tmp_dir();
2720 tmplen = strlen(tmpdir);
2721 progname = g_get_prgname();
2722 proglen = strlen(progname);
2723 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2726 memcpy(fname, tmpdir, tmplen);
2727 fname[tmplen] = G_DIR_SEPARATOR;
2728 memcpy(fname + tmplen + 1, progname, proglen);
2729 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2731 fd = mkstemp(fname);
2737 fp = fdopen(fd, "w+b");
2742 #endif /* HAVE_MKSTEMP */
2747 FILE *str_open_as_stream(const gchar *str)
2752 g_return_val_if_fail(str != NULL, NULL);
2756 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2761 if (len == 0) return fp;
2763 if (fwrite(str, len, 1, fp) != 1) {
2764 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2773 gint str_write_to_file(const gchar *str, const gchar *file)
2778 g_return_val_if_fail(str != NULL, -1);
2779 g_return_val_if_fail(file != NULL, -1);
2781 if ((fp = fopen(file, "wb")) == NULL) {
2782 FILE_OP_ERROR(file, "fopen");
2792 if (fwrite(str, len, 1, fp) != 1) {
2793 FILE_OP_ERROR(file, "fwrite");
2799 if (fclose(fp) == EOF) {
2800 FILE_OP_ERROR(file, "fclose");
2808 gchar *file_read_to_str(const gchar *file)
2813 g_return_val_if_fail(file != NULL, NULL);
2815 if ((fp = fopen(file, "rb")) == NULL) {
2816 FILE_OP_ERROR(file, "fopen");
2820 str = file_read_stream_to_str(fp);
2827 gchar *file_read_stream_to_str(FILE *fp)
2834 g_return_val_if_fail(fp != NULL, NULL);
2836 array = g_byte_array_new();
2838 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2839 if (n_read < sizeof(buf) && ferror(fp))
2841 g_byte_array_append(array, buf, n_read);
2845 FILE_OP_ERROR("file stream", "fread");
2846 g_byte_array_free(array, TRUE);
2851 g_byte_array_append(array, buf, 1);
2852 str = (gchar *)array->data;
2853 g_byte_array_free(array, FALSE);
2858 gint execute_async(gchar *const argv[])
2862 if ((pid = fork()) < 0) {
2867 if (pid == 0) { /* child process */
2870 if ((gch_pid = fork()) < 0) {
2875 if (gch_pid == 0) { /* grandchild process */
2876 execvp(argv[0], argv);
2885 waitpid(pid, NULL, 0);
2890 gint execute_sync(gchar *const argv[])
2894 if ((pid = fork()) < 0) {
2899 if (pid == 0) { /* child process */
2900 execvp(argv[0], argv);
2906 waitpid(pid, NULL, 0);
2911 gint execute_command_line(const gchar *cmdline, gboolean async)
2916 argv = strsplit_with_quote(cmdline, " ", 0);
2919 ret = execute_async(argv);
2921 ret = execute_sync(argv);
2927 gchar *get_command_output(const gchar *cmdline)
2929 gchar buf[BUFFSIZE];
2934 g_return_val_if_fail(cmdline != NULL, NULL);
2936 if ((fp = popen(cmdline, "r")) == NULL) {
2937 FILE_OP_ERROR(cmdline, "popen");
2941 str = g_string_new("");
2943 while (fgets(buf, sizeof(buf), fp) != NULL)
2944 g_string_append(str, buf);
2949 g_string_free(str, FALSE);
2954 static gint is_unchanged_uri_char(char c)
2966 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2972 for(i = 0; i < strlen(uri) ; i++) {
2973 if (is_unchanged_uri_char(uri[i])) {
2974 if (k + 2 >= bufsize)
2976 encoded_uri[k++] = uri[i];
2979 char * hexa = "0123456789ABCDEF";
2981 if (k + 4 >= bufsize)
2983 encoded_uri[k++] = '%';
2984 encoded_uri[k++] = hexa[uri[i] / 16];
2985 encoded_uri[k++] = hexa[uri[i] % 16];
2991 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
2994 static gint axtoi(const gchar *hexstr)
2996 gint hi, lo, result;
2999 if ('0' <= hi && hi <= '9') {
3002 if ('a' <= hi && hi <= 'f') {
3005 if ('A' <= hi && hi <= 'F') {
3010 if ('0' <= lo && lo <= '9') {
3013 if ('a' <= lo && lo <= 'f') {
3016 if ('A' <= lo && lo <= 'F') {
3019 result = lo + (16 * hi);
3024 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
3025 * plusses, and escape characters are used)
3028 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
3030 const gchar *encoded;
3033 encoded = encoded_uri;
3034 decoded = decoded_uri;
3037 if (*encoded == '%') {
3039 if (isxdigit(encoded[0])
3040 && isxdigit(encoded[1])) {
3041 *decoded = (gchar) axtoi(encoded);
3046 else if (*encoded == '+') {
3052 *decoded = *encoded;
3062 gint open_uri(const gchar *uri, const gchar *cmdline)
3064 gchar buf[BUFFSIZE];
3066 gchar encoded_uri[BUFFSIZE];
3068 g_return_val_if_fail(uri != NULL, -1);
3070 /* an option to choose whether to use encode_uri or not ? */
3071 encode_uri(encoded_uri, BUFFSIZE, uri);
3074 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3075 !strchr(p + 2, '%'))
3076 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3079 g_warning("Open URI command line is invalid: `%s'",
3081 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3084 execute_command_line(buf, TRUE);
3089 time_t remote_tzoffset_sec(const gchar *zone)
3091 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3097 time_t remoteoffset;
3099 strncpy(zone3, zone, 3);
3103 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3104 (c == '+' || c == '-')) {
3105 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3107 remoteoffset = -remoteoffset;
3108 } else if (!strncmp(zone, "UT" , 2) ||
3109 !strncmp(zone, "GMT", 2)) {
3111 } else if (strlen(zone3) == 3 &&
3112 (p = strstr(ustzstr, zone3)) != NULL &&
3113 (p - ustzstr) % 3 == 0) {
3114 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3115 remoteoffset = iustz * 3600;
3116 } else if (strlen(zone3) == 1) {
3118 case 'Z': remoteoffset = 0; break;
3119 case 'A': remoteoffset = -1; break;
3120 case 'B': remoteoffset = -2; break;
3121 case 'C': remoteoffset = -3; break;
3122 case 'D': remoteoffset = -4; break;
3123 case 'E': remoteoffset = -5; break;
3124 case 'F': remoteoffset = -6; break;
3125 case 'G': remoteoffset = -7; break;
3126 case 'H': remoteoffset = -8; break;
3127 case 'I': remoteoffset = -9; break;
3128 case 'K': remoteoffset = -10; break; /* J is not used */
3129 case 'L': remoteoffset = -11; break;
3130 case 'M': remoteoffset = -12; break;
3131 case 'N': remoteoffset = 1; break;
3132 case 'O': remoteoffset = 2; break;
3133 case 'P': remoteoffset = 3; break;
3134 case 'Q': remoteoffset = 4; break;
3135 case 'R': remoteoffset = 5; break;
3136 case 'S': remoteoffset = 6; break;
3137 case 'T': remoteoffset = 7; break;
3138 case 'U': remoteoffset = 8; break;
3139 case 'V': remoteoffset = 9; break;
3140 case 'W': remoteoffset = 10; break;
3141 case 'X': remoteoffset = 11; break;
3142 case 'Y': remoteoffset = 12; break;
3143 default: remoteoffset = 0; break;
3145 remoteoffset = remoteoffset * 3600;
3148 return remoteoffset;
3151 time_t tzoffset_sec(time_t *now)
3157 lt = localtime(now);
3159 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3161 if (lt->tm_year < gmt.tm_year)
3163 else if (lt->tm_year > gmt.tm_year)
3165 else if (lt->tm_yday < gmt.tm_yday)
3167 else if (lt->tm_yday > gmt.tm_yday)
3170 if (off >= 24 * 60) /* should be impossible */
3171 off = 23 * 60 + 59; /* if not, insert silly value */
3172 if (off <= -24 * 60)
3173 off = -(23 * 60 + 59);
3178 /* calculate timezone offset */
3179 gchar *tzoffset(time_t *now)
3181 static gchar offset_string[6];
3187 lt = localtime(now);
3189 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3191 if (lt->tm_year < gmt.tm_year)
3193 else if (lt->tm_year > gmt.tm_year)
3195 else if (lt->tm_yday < gmt.tm_yday)
3197 else if (lt->tm_yday > gmt.tm_yday)
3205 if (off >= 24 * 60) /* should be impossible */
3206 off = 23 * 60 + 59; /* if not, insert silly value */
3208 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3210 return offset_string;
3213 void get_rfc822_date(gchar *buf, gint len)
3217 gchar day[4], mon[4];
3218 gint dd, hh, mm, ss, yyyy;
3223 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3224 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3225 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3226 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3229 void debug_set_mode(gboolean mode)
3234 gboolean debug_get_mode()
3239 void debug_print_real(const gchar *format, ...)
3242 gchar buf[BUFFSIZE];
3244 if (!debug_mode) return;
3246 va_start(args, format);
3247 g_vsnprintf(buf, sizeof(buf), format, args);
3253 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3255 if (subject == NULL)
3258 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3259 return g_hash_table_lookup(subject_table, subject + 4);
3261 return g_hash_table_lookup(subject_table, subject);
3264 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3267 if (subject == NULL)
3271 if (g_strcasecmp(subject, "Re:") == 0)
3273 if (g_strcasecmp(subject, "Re: ") == 0)
3276 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3277 g_hash_table_insert(subject_table, subject + 4, data);
3279 g_hash_table_insert(subject_table, subject, data);
3282 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3284 if (subject == NULL)
3287 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3288 g_hash_table_remove(subject_table, subject + 4);
3290 g_hash_table_remove(subject_table, subject);
3293 gboolean subject_is_reply(const gchar *subject)
3295 /* XXX: just simply here so someone can handle really
3296 * advanced Re: detection like "Re[4]", "ANTW:" or
3297 * Re: Re: Re: Re: Re: Re: Re: Re:" stuff. */
3298 if (subject == NULL) return FALSE;
3299 else return 0 == g_strncasecmp(subject, "Re: ", 4);
3302 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
3306 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
3307 fd = mkstemp(*filename);
3309 return fdopen(fd, "w+");
3312 /* allow Mutt-like patterns in quick search */
3313 gchar *expand_search_string(const gchar *search_string)
3316 gchar term_char, save_char;
3317 gchar *cmd_start, *cmd_end;
3318 GString *matcherstr;
3319 gchar *returnstr = NULL;
3321 gboolean casesens, dontmatch;
3322 /* list of allowed pattern abbreviations */
3324 gchar *abbreviated; /* abbreviation */
3325 gchar *command; /* actual matcher command */
3326 gint numparams; /* number of params for cmd */
3327 gboolean qualifier; /* do we append regexpcase */
3328 gboolean quotes; /* do we need quotes */
3331 { "a", "all", 0, FALSE, FALSE },
3332 { "ag", "age_greater", 1, FALSE, FALSE },
3333 { "al", "age_lower", 1, FALSE, FALSE },
3334 { "b", "body_part", 1, TRUE, TRUE },
3335 { "B", "message", 1, TRUE, TRUE },
3336 { "c", "cc", 1, TRUE, TRUE },
3337 { "C", "to_or_cc", 1, TRUE, TRUE },
3338 { "D", "deleted", 0, FALSE, FALSE },
3339 { "e", "header \"Sender\"", 1, TRUE, TRUE },
3340 { "E", "execute", 1, FALSE, TRUE },
3341 { "f", "from", 1, TRUE, TRUE },
3342 { "F", "forwarded", 0, FALSE, FALSE },
3343 { "h", "headers_part", 1, TRUE, TRUE },
3344 { "i", "header \"Message-Id\"", 1, TRUE, TRUE },
3345 { "I", "inreplyto", 1, TRUE, TRUE },
3346 { "L", "locked", 0, FALSE, FALSE },
3347 { "n", "newsgroups", 1, TRUE, TRUE },
3348 { "N", "new", 0, FALSE, FALSE },
3349 { "O", "~new", 0, FALSE, FALSE },
3350 { "r", "replied", 0, FALSE, FALSE },
3351 { "R", "~unread", 0, FALSE, FALSE },
3352 { "s", "subject", 1, TRUE, TRUE },
3353 { "se", "score_equal", 1, FALSE, FALSE },
3354 { "sg", "score_greater", 1, FALSE, FALSE },
3355 { "sl", "score_lower", 1, FALSE, FALSE },
3356 { "Se", "size_equal", 1, FALSE, FALSE },
3357 { "Sg", "size_greater", 1, FALSE, FALSE },
3358 { "Ss", "size_smaller", 1, FALSE, FALSE },
3359 { "t", "to", 1, TRUE, TRUE },
3360 { "T", "marked", 0, FALSE, FALSE },
3361 { "U", "unread", 0, FALSE, FALSE },
3362 { "x", "header \"References\"", 1, TRUE, TRUE },
3363 { "y", "header \"X-Label\"", 1, TRUE, TRUE },
3364 { "&", "&", 0, FALSE, FALSE },
3365 { "|", "|", 0, FALSE, FALSE },
3366 { NULL, NULL, 0, FALSE, FALSE }
3369 if (search_string == NULL)
3372 copy_str = g_strdup(search_string);
3374 /* if it's a full command don't process it so users
3375 can still do something like from regexpcase "foo" */
3376 for (i = 0; cmds[i].command; i++) {
3377 const gchar *tmp_search_string = search_string;
3378 cmd_start = cmds[i].command;
3379 /* allow logical NOT */
3380 if (*tmp_search_string == '~')
3381 tmp_search_string++;
3382 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3385 if (cmds[i].command)
3388 matcherstr = g_string_sized_new(16);
3389 cmd_start = cmd_end = copy_str;
3390 while (cmd_end && *cmd_end) {
3391 /* skip all white spaces */
3392 while (*cmd_end && isspace(*cmd_end))
3395 /* extract a command */
3396 while (*cmd_end && !isspace(*cmd_end))
3399 /* save character */
3400 save_char = *cmd_end;
3406 /* ~ and ! mean logical NOT */
3407 if (*cmd_start == '~' || *cmd_start == '!')
3412 /* % means case sensitive match */
3413 if (*cmd_start == '%')
3419 /* find matching abbreviation */
3420 for (i = 0; cmds[i].command; i++) {
3421 if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3422 /* restore character */
3423 *cmd_end = save_char;
3426 if (matcherstr->len > 0) {
3427 g_string_append(matcherstr, " ");
3430 g_string_append(matcherstr, "~");
3431 g_string_append(matcherstr, cmds[i].command);
3432 g_string_append(matcherstr, " ");
3434 /* stop if no params required */
3435 if (cmds[i].numparams == 0)
3438 /* extract a parameter, allow quotes */
3440 cmd_start = cmd_end;
3441 if (*cmd_start == '"') {
3448 /* extract actual parameter */
3449 while ((*cmd_end) && (*cmd_end != term_char))
3452 if (*cmd_end && (*cmd_end != term_char))
3455 if (*cmd_end == '"')
3458 save_char = *cmd_end;
3461 if (cmds[i].qualifier) {
3463 g_string_append(matcherstr, "regexp ");
3465 g_string_append(matcherstr, "regexpcase ");
3468 /* do we need to add quotes ? */
3469 if (cmds[i].quotes && term_char != '"')
3470 g_string_append(matcherstr, "\"");
3472 /* copy actual parameter */
3473 g_string_append(matcherstr, cmd_start);
3475 /* do we need to add quotes ? */
3476 if (cmds[i].quotes && term_char != '"')
3477 g_string_append(matcherstr, "\"");
3479 /* restore original character */
3480 *cmd_end = save_char;
3488 cmd_start = cmd_end;
3493 returnstr = matcherstr->str;
3494 g_string_free(matcherstr, FALSE);
3498 guint g_stricase_hash(gconstpointer gptr)
3500 guint hash_result = 0;
3503 for (str = gptr; str && *str; str++) {
3504 if (isupper(*str)) hash_result += (*str + ' ');
3505 else hash_result += *str;
3511 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3513 const char *str1 = gptr1;
3514 const char *str2 = gptr2;
3516 return !strcasecmp(str1, str2);
3519 gint g_int_compare(gconstpointer a, gconstpointer b)
3521 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);