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_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
674 register gchar *srcp, *destp;
676 gboolean in_quote = FALSE;
680 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
683 memmove(destp, srcp + 1, strlen(srcp));
686 if (*destp == op && !in_quote)
688 else if (*destp == cl && !in_quote)
690 else if (*destp == quote_chr)
702 void eliminate_quote(gchar *str, gchar quote_chr)
704 register gchar *srcp, *destp;
708 while ((destp = strchr(destp, quote_chr))) {
709 if ((srcp = strchr(destp + 1, quote_chr))) {
711 while (isspace(*srcp)) srcp++;
712 memmove(destp, srcp, strlen(srcp) + 1);
720 void extract_quote(gchar *str, gchar quote_chr)
724 if ((str = strchr(str, quote_chr))) {
726 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
727 memmove(p - 1, p, strlen(p) + 1);
732 memmove(str, str + 1, p - str);
737 void eliminate_address_comment(gchar *str)
739 register gchar *srcp, *destp;
744 while ((destp = strchr(destp, '"'))) {
745 if ((srcp = strchr(destp + 1, '"'))) {
750 while (isspace(*srcp)) srcp++;
751 memmove(destp, srcp, strlen(srcp) + 1);
761 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
767 else if (*srcp == ')')
773 while (isspace(*srcp)) srcp++;
774 memmove(destp, srcp, strlen(srcp) + 1);
778 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
780 gboolean in_quote = FALSE;
783 if (*str == c && !in_quote)
785 if (*str == quote_chr)
793 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
795 gboolean in_quote = FALSE;
798 p = str + strlen(str) - 1;
800 if (*p == c && !in_quote)
810 void extract_address(gchar *str)
812 eliminate_address_comment(str);
813 if (strchr_with_skip_quote(str, '"', '<'))
814 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
818 void extract_list_id_str(gchar *str)
820 if (strchr_with_skip_quote(str, '"', '<'))
821 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
825 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
830 if (!str) return addr_list;
832 Xstrdup_a(work, str, return addr_list);
835 eliminate_address_comment(work);
838 while (workp && *workp) {
841 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
847 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
848 extract_parenthesis_with_skip_quote
849 (workp, '"', '<', '>');
853 addr_list = g_slist_append(addr_list, g_strdup(workp));
861 GSList *address_list_append(GSList *addr_list, const gchar *str)
863 return address_list_append_real(addr_list, str, TRUE);
866 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
868 return address_list_append_real(addr_list, str, FALSE);
871 GSList *references_list_append(GSList *msgid_list, const gchar *str)
875 if (!str) return msgid_list;
878 while (strp && *strp) {
879 const gchar *start, *end;
882 if ((start = strchr(strp, '<')) != NULL) {
883 end = strchr(start + 1, '>');
888 msgid = g_strndup(start + 1, end - start - 1);
891 msgid_list = g_slist_append(msgid_list, msgid);
901 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
906 if (!str) return group_list;
908 Xstrdup_a(work, str, return group_list);
912 while (workp && *workp) {
915 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
923 group_list = g_slist_append(group_list,
932 GList *add_history(GList *list, const gchar *str)
936 g_return_val_if_fail(str != NULL, list);
938 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
941 list = g_list_remove(list, old->data);
942 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
945 last = g_list_last(list);
948 g_list_remove(list, last->data);
952 list = g_list_prepend(list, g_strdup(str));
957 void remove_return(gchar *str)
959 register gchar *p = str;
962 if (*p == '\n' || *p == '\r')
963 memmove(p, p + 1, strlen(p));
969 void remove_space(gchar *str)
971 register gchar *p = str;
976 while (isspace(*(p + spc)))
979 memmove(p, p + spc, strlen(p + spc) + 1);
985 void unfold_line(gchar *str)
987 register gchar *p = str;
991 if (*p == '\n' || *p == '\r') {
994 while (isspace(*(p + spc)))
997 memmove(p, p + spc, strlen(p + spc) + 1);
1003 void subst_char(gchar *str, gchar orig, gchar subst)
1005 register gchar *p = str;
1014 void subst_chars(gchar *str, gchar *orig, gchar subst)
1016 register gchar *p = str;
1019 if (strchr(orig, *p) != NULL)
1025 void subst_for_filename(gchar *str)
1027 subst_chars(str, " \t\r\n\"/\\", '_');
1030 gboolean is_header_line(const gchar *str)
1032 if (str[0] == ':') return FALSE;
1034 while (*str != '\0' && *str != ' ') {
1043 gboolean is_ascii_str(const guchar *str)
1045 while (*str != '\0') {
1046 if (*str != '\t' && *str != ' ' &&
1047 *str != '\r' && *str != '\n' &&
1048 (*str < 32 || *str >= 127))
1056 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1058 const gchar *first_pos;
1059 const gchar *last_pos;
1060 const gchar *p = str;
1061 gint quote_level = -1;
1063 /* speed up line processing by only searching to the last '>' */
1064 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1065 /* skip a line if it contains a '<' before the initial '>' */
1066 if (memchr(str, '<', first_pos - str) != NULL)
1068 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1072 while (p <= last_pos) {
1073 while (p < last_pos) {
1080 if (strchr(quote_chars, *p))
1082 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1083 /* any characters are allowed except '-' and space */
1085 && !strchr(quote_chars, *p)
1089 if (strchr(quote_chars, *p))
1101 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1103 gchar * position = NULL;
1104 gchar * tmp_pos = NULL;
1107 if (quote_chars == NULL)
1110 for (i = 0; i < strlen(quote_chars); i++) {
1111 tmp_pos = strchr (str, quote_chars[i]);
1113 || (tmp_pos != NULL && position >= tmp_pos) )
1119 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1121 gchar * position = NULL;
1122 gchar * tmp_pos = NULL;
1125 if (quote_chars == NULL)
1128 for (i = 0; i < strlen(quote_chars); i++) {
1129 tmp_pos = strrchr (str, quote_chars[i]);
1131 || (tmp_pos != NULL && position <= tmp_pos) )
1137 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1139 register guint haystack_len, needle_len;
1140 gboolean in_squote = FALSE, in_dquote = FALSE;
1142 haystack_len = strlen(haystack);
1143 needle_len = strlen(needle);
1145 if (haystack_len < needle_len || needle_len == 0)
1148 while (haystack_len >= needle_len) {
1149 if (!in_squote && !in_dquote &&
1150 !strncmp(haystack, needle, needle_len))
1151 return (gchar *)haystack;
1153 /* 'foo"bar"' -> foo"bar"
1154 "foo'bar'" -> foo'bar' */
1155 if (*haystack == '\'') {
1158 else if (!in_dquote)
1160 } else if (*haystack == '\"') {
1163 else if (!in_squote)
1174 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1177 gchar quote_chr = '"';
1179 gboolean in_quote = FALSE;
1183 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1187 if (*p == op && !in_quote)
1189 else if (*p == cl && !in_quote)
1191 else if (*p == quote_chr)
1204 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1207 GSList *string_list = NULL, *slist;
1209 const gchar *s_op, *s_cl;
1212 g_return_val_if_fail(str != NULL, NULL);
1215 max_tokens = G_MAXINT;
1217 s_op = strchr_with_skip_quote(str, '"', op);
1218 if (!s_op) return NULL;
1220 s_cl = strchr_parenthesis_close(str, op, cl);
1228 new_string = g_new(gchar, len + 1);
1229 strncpy(new_string, str, len);
1230 new_string[len] = 0;
1231 string_list = g_slist_prepend(string_list, new_string);
1235 while (*str && isspace(*str)) str++;
1237 string_list = g_slist_prepend(string_list,
1240 s_op = strchr_with_skip_quote(str, '"', op);
1241 if (!--max_tokens || !s_op) break;
1245 s_cl = strchr_parenthesis_close(str, op, cl);
1246 } while (--max_tokens && s_cl);
1249 str_array = g_new(gchar*, n);
1253 str_array[i--] = NULL;
1254 for (slist = string_list; slist; slist = slist->next)
1255 str_array[i--] = slist->data;
1257 g_slist_free(string_list);
1262 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1265 GSList *string_list = NULL, *slist;
1266 gchar **str_array, *s, *new_str;
1267 guint i, n = 1, len;
1269 g_return_val_if_fail(str != NULL, NULL);
1270 g_return_val_if_fail(delim != NULL, NULL);
1273 max_tokens = G_MAXINT;
1275 s = strstr_with_skip_quote(str, delim);
1277 guint delimiter_len = strlen(delim);
1281 new_str = g_strndup(str, len);
1283 if (new_str[0] == '\'' || new_str[0] == '\"') {
1284 if (new_str[len - 1] == new_str[0]) {
1285 new_str[len - 1] = '\0';
1286 memmove(new_str, new_str + 1, len - 1);
1289 string_list = g_slist_prepend(string_list, new_str);
1291 str = s + delimiter_len;
1292 s = strstr_with_skip_quote(str, delim);
1293 } while (--max_tokens && s);
1297 new_str = g_strdup(str);
1298 if (new_str[0] == '\'' || new_str[0] == '\"') {
1300 if (new_str[len - 1] == new_str[0]) {
1301 new_str[len - 1] = '\0';
1302 memmove(new_str, new_str + 1, len - 1);
1305 string_list = g_slist_prepend(string_list, new_str);
1309 str_array = g_new(gchar*, n);
1313 str_array[i--] = NULL;
1314 for (slist = string_list; slist; slist = slist->next)
1315 str_array[i--] = slist->data;
1317 g_slist_free(string_list);
1322 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1324 gchar *abbrev_group;
1326 const gchar *p = group;
1329 g_return_val_if_fail(group != NULL, NULL);
1331 last = group + strlen(group);
1332 abbrev_group = ap = g_malloc(strlen(group) + 1);
1337 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1339 while (*p != '.') p++;
1342 return abbrev_group;
1347 return abbrev_group;
1350 gchar *trim_string(const gchar *str, gint len)
1352 const gchar *p = str;
1357 if (!str) return NULL;
1358 if (strlen(str) <= len)
1359 return g_strdup(str);
1361 while (*p != '\0') {
1362 mb_len = mblen(p, MB_LEN_MAX);
1365 else if (mb_len < 0)
1366 return g_strdup(str);
1367 else if (new_len + mb_len > len)
1374 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1375 return g_strconcat(new_str, "...", NULL);
1378 GList *uri_list_extract_filenames(const gchar *uri_list)
1380 GList *result = NULL;
1388 while (isspace(*p)) p++;
1389 if (!strncmp(p, "file:", 5)) {
1392 while (*q && *q != '\n' && *q != '\r') q++;
1396 while (q > p && isspace(*q)) q--;
1397 file = g_malloc(q - p + 2);
1398 strncpy(file, p, q - p + 1);
1399 file[q - p + 1] = '\0';
1400 result = g_list_append(result,file);
1404 p = strchr(p, '\n');
1411 #define HEX_TO_INT(val, hex) \
1415 if ('0' <= c && c <= '9') { \
1417 } else if ('a' <= c && c <= 'f') { \
1418 val = c - 'a' + 10; \
1419 } else if ('A' <= c && c <= 'F') { \
1420 val = c - 'A' + 10; \
1426 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1427 gchar **subject, gchar **body)
1432 Xstrdup_a(tmp_mailto, mailto, return -1);
1434 if (!strncmp(tmp_mailto, "mailto:", 7))
1437 p = strchr(tmp_mailto, '?');
1444 *to = g_strdup(tmp_mailto);
1447 gchar *field, *value;
1464 if (*value == '\0') continue;
1466 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1467 *cc = g_strdup(value);
1468 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1469 *bcc = g_strdup(value);
1470 } else if (subject && !*subject &&
1471 !g_strcasecmp(field, "subject")) {
1472 *subject = g_malloc(strlen(value) + 1);
1473 decode_uri(*subject, value);
1474 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1475 *body = g_malloc(strlen(value) + 1);
1476 decode_uri(*body, value);
1484 * We need this wrapper around g_get_home_dir(), so that
1485 * we can fix some Windoze things here. Should be done in glibc of course
1486 * but as long as we are not able to do our own extensions to glibc, we do
1489 gchar *get_home_dir(void)
1491 #if HAVE_DOSISH_SYSTEM
1492 static gchar *home_dir;
1495 home_dir = read_w32_registry_string(NULL,
1496 "Software\\Sylpheed", "HomeDir" );
1497 if (!home_dir || !*home_dir) {
1498 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1499 const char *s = g_get_home_dir();
1501 home_dir = g_strdup (s);
1503 if (!home_dir || !*home_dir)
1504 home_dir = g_strdup ("c:\\sylpheed");
1506 debug_print("initialized home_dir to `%s'\n", home_dir);
1509 #else /* standard glib */
1510 return g_get_home_dir();
1514 gchar *get_rc_dir(void)
1516 static gchar *rc_dir = NULL;
1519 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1525 gchar *get_news_cache_dir(void)
1527 static gchar *news_cache_dir = NULL;
1529 if (!news_cache_dir)
1530 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1531 NEWS_CACHE_DIR, NULL);
1533 return news_cache_dir;
1536 gchar *get_imap_cache_dir(void)
1538 static gchar *imap_cache_dir = NULL;
1540 if (!imap_cache_dir)
1541 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1542 IMAP_CACHE_DIR, NULL);
1544 return imap_cache_dir;
1547 gchar *get_mbox_cache_dir(void)
1549 static gchar *mbox_cache_dir = NULL;
1551 if (!mbox_cache_dir)
1552 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1553 MBOX_CACHE_DIR, NULL);
1555 return mbox_cache_dir;
1558 gchar *get_mime_tmp_dir(void)
1560 static gchar *mime_tmp_dir = NULL;
1563 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1564 MIME_TMP_DIR, NULL);
1566 return mime_tmp_dir;
1569 gchar *get_template_dir(void)
1571 static gchar *template_dir = NULL;
1574 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1575 TEMPLATE_DIR, NULL);
1577 return template_dir;
1580 gchar *get_header_cache_dir(void)
1582 static gchar *header_dir = NULL;
1585 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1586 HEADER_CACHE_DIR, NULL);
1591 gchar *get_tmp_dir(void)
1593 static gchar *tmp_dir = NULL;
1596 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1602 gchar *get_tmp_file(void)
1605 static guint32 id = 0;
1607 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1608 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1613 gchar *get_domain_name(void)
1615 static gchar *domain_name = NULL;
1618 gchar buf[128] = "";
1621 if (gethostname(buf, sizeof(buf)) < 0) {
1622 perror("gethostname");
1623 domain_name = "unknown";
1625 buf[sizeof(buf) - 1] = '\0';
1626 if ((hp = my_gethostbyname(buf)) == NULL) {
1627 perror("gethostbyname");
1628 domain_name = g_strdup(buf);
1630 domain_name = g_strdup(hp->h_name);
1634 debug_print("domain name = %s\n", domain_name);
1640 off_t get_file_size(const gchar *file)
1644 if (stat(file, &s) < 0) {
1645 FILE_OP_ERROR(file, "stat");
1652 off_t get_file_size_as_crlf(const gchar *file)
1656 gchar buf[BUFFSIZE];
1658 if ((fp = fopen(file, "rb")) == NULL) {
1659 FILE_OP_ERROR(file, "fopen");
1663 while (fgets(buf, sizeof(buf), fp) != NULL) {
1665 size += strlen(buf) + 2;
1669 FILE_OP_ERROR(file, "fgets");
1678 off_t get_left_file_size(FILE *fp)
1684 if ((pos = ftell(fp)) < 0) {
1688 if (fseek(fp, 0L, SEEK_END) < 0) {
1692 if ((end = ftell(fp)) < 0) {
1697 if (fseek(fp, pos, SEEK_SET) < 0) {
1705 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1712 if (stat(file, &s) < 0) {
1713 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1717 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1723 gboolean is_dir_exist(const gchar *dir)
1730 if (stat(dir, &s) < 0) {
1731 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1735 if (S_ISDIR(s.st_mode))
1741 gboolean is_file_entry_exist(const gchar *file)
1748 if (stat(file, &s) < 0) {
1749 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1756 gint change_dir(const gchar *dir)
1758 gchar *prevdir = NULL;
1761 prevdir = g_get_current_dir();
1763 if (chdir(dir) < 0) {
1764 FILE_OP_ERROR(dir, "chdir");
1765 if (debug_mode) g_free(prevdir);
1767 } else if (debug_mode) {
1770 cwd = g_get_current_dir();
1771 if (strcmp(prevdir, cwd) != 0)
1772 g_print("current dir: %s\n", cwd);
1780 gint make_dir(const gchar *dir)
1782 if (mkdir(dir, S_IRWXU) < 0) {
1783 FILE_OP_ERROR(dir, "mkdir");
1786 if (chmod(dir, S_IRWXU) < 0)
1787 FILE_OP_ERROR(dir, "chmod");
1792 gint make_dir_hier(const gchar *dir)
1797 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1798 parent_dir = g_strndup(dir, p - dir);
1799 if (*parent_dir != '\0') {
1800 if (!is_dir_exist(parent_dir)) {
1801 if (make_dir(parent_dir) < 0) {
1810 if (!is_dir_exist(dir)) {
1811 if (make_dir(dir) < 0)
1818 gint remove_all_files(const gchar *dir)
1824 prev_dir = g_get_current_dir();
1826 if (chdir(dir) < 0) {
1827 FILE_OP_ERROR(dir, "chdir");
1832 if ((dp = opendir(".")) == NULL) {
1833 FILE_OP_ERROR(dir, "opendir");
1838 while ((d = readdir(dp)) != NULL) {
1839 if (!strcmp(d->d_name, ".") ||
1840 !strcmp(d->d_name, ".."))
1843 if (unlink(d->d_name) < 0)
1844 FILE_OP_ERROR(d->d_name, "unlink");
1849 if (chdir(prev_dir) < 0) {
1850 FILE_OP_ERROR(prev_dir, "chdir");
1860 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1867 prev_dir = g_get_current_dir();
1869 if (chdir(dir) < 0) {
1870 FILE_OP_ERROR(dir, "chdir");
1875 if ((dp = opendir(".")) == NULL) {
1876 FILE_OP_ERROR(dir, "opendir");
1881 while ((d = readdir(dp)) != NULL) {
1882 fileno = to_number(d->d_name);
1883 if (fileno >= 0 && first <= fileno && fileno <= last) {
1884 if (is_dir_exist(d->d_name))
1886 if (unlink(d->d_name) < 0)
1887 FILE_OP_ERROR(d->d_name, "unlink");
1893 if (chdir(prev_dir) < 0) {
1894 FILE_OP_ERROR(prev_dir, "chdir");
1904 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1911 prev_dir = g_get_current_dir();
1913 if (chdir(dir) < 0) {
1914 FILE_OP_ERROR(dir, "chdir");
1919 if ((dp = opendir(".")) == NULL) {
1920 FILE_OP_ERROR(dir, "opendir");
1925 while ((d = readdir(dp)) != NULL) {
1926 fileno = to_number(d->d_name);
1927 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1928 debug_print("removing unwanted file %d from %s\n", fileno, dir);
1929 if (is_dir_exist(d->d_name))
1931 if (unlink(d->d_name) < 0)
1932 FILE_OP_ERROR(d->d_name, "unlink");
1938 if (chdir(prev_dir) < 0) {
1939 FILE_OP_ERROR(prev_dir, "chdir");
1949 gint remove_all_numbered_files(const gchar *dir)
1951 return remove_numbered_files(dir, 0, UINT_MAX);
1954 gint remove_expired_files(const gchar *dir, guint hours)
1961 time_t mtime, now, expire_time;
1963 prev_dir = g_get_current_dir();
1965 if (chdir(dir) < 0) {
1966 FILE_OP_ERROR(dir, "chdir");
1971 if ((dp = opendir(".")) == NULL) {
1972 FILE_OP_ERROR(dir, "opendir");
1978 expire_time = hours * 60 * 60;
1980 while ((d = readdir(dp)) != NULL) {
1981 fileno = to_number(d->d_name);
1983 if (stat(d->d_name, &s) < 0) {
1984 FILE_OP_ERROR(d->d_name, "stat");
1987 if (S_ISDIR(s.st_mode))
1989 mtime = MAX(s.st_mtime, s.st_atime);
1990 if (now - mtime > expire_time) {
1991 if (unlink(d->d_name) < 0)
1992 FILE_OP_ERROR(d->d_name, "unlink");
1999 if (chdir(prev_dir) < 0) {
2000 FILE_OP_ERROR(prev_dir, "chdir");
2010 gint remove_dir_recursive(const gchar *dir)
2017 /* g_print("dir = %s\n", dir); */
2019 if (stat(dir, &s) < 0) {
2020 FILE_OP_ERROR(dir, "stat");
2021 if (ENOENT == errno) return 0;
2025 if (!S_ISDIR(s.st_mode)) {
2026 if (unlink(dir) < 0) {
2027 FILE_OP_ERROR(dir, "unlink");
2034 prev_dir = g_get_current_dir();
2035 /* g_print("prev_dir = %s\n", prev_dir); */
2037 if (!path_cmp(prev_dir, dir)) {
2039 if (chdir("..") < 0) {
2040 FILE_OP_ERROR(dir, "chdir");
2043 prev_dir = g_get_current_dir();
2046 if (chdir(dir) < 0) {
2047 FILE_OP_ERROR(dir, "chdir");
2052 if ((dp = opendir(".")) == NULL) {
2053 FILE_OP_ERROR(dir, "opendir");
2059 /* remove all files in the directory */
2060 while ((d = readdir(dp)) != NULL) {
2061 if (!strcmp(d->d_name, ".") ||
2062 !strcmp(d->d_name, ".."))
2065 if (stat(d->d_name, &s) < 0) {
2066 FILE_OP_ERROR(d->d_name, "stat");
2070 /* g_print("removing %s\n", d->d_name); */
2072 if (S_ISDIR(s.st_mode)) {
2073 if (remove_dir_recursive(d->d_name) < 0) {
2074 g_warning("can't remove directory\n");
2078 if (unlink(d->d_name) < 0)
2079 FILE_OP_ERROR(d->d_name, "unlink");
2085 if (chdir(prev_dir) < 0) {
2086 FILE_OP_ERROR(prev_dir, "chdir");
2093 if (rmdir(dir) < 0) {
2094 FILE_OP_ERROR(dir, "rmdir");
2102 /* this seems to be slower than the stdio version... */
2103 gint copy_file(const gchar *src, const gchar *dest)
2105 gint src_fd, dest_fd;
2109 gchar *dest_bak = NULL;
2111 if ((src_fd = open(src, O_RDONLY)) < 0) {
2112 FILE_OP_ERROR(src, "open");
2116 if (is_file_exist(dest)) {
2117 dest_bak = g_strconcat(dest, ".bak", NULL);
2118 if (rename(dest, dest_bak) < 0) {
2119 FILE_OP_ERROR(dest, "rename");
2126 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2127 FILE_OP_ERROR(dest, "open");
2130 if (rename(dest_bak, dest) < 0)
2131 FILE_OP_ERROR(dest_bak, "rename");
2137 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2142 n_write = write(dest_fd, bufp, len);
2144 g_warning("writing to %s failed.\n", dest);
2149 if (rename(dest_bak, dest) < 0)
2150 FILE_OP_ERROR(dest_bak, "rename");
2163 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2164 g_warning("File copy from %s to %s failed.\n", src, dest);
2167 if (rename(dest_bak, dest) < 0)
2168 FILE_OP_ERROR(dest_bak, "rename");
2181 * Append src file body to the tail of dest file.
2182 * Now keep_backup has no effects.
2184 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2186 FILE *src_fp, *dest_fp;
2190 gboolean err = FALSE;
2192 if ((src_fp = fopen(src, "rb")) == NULL) {
2193 FILE_OP_ERROR(src, "fopen");
2197 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2198 FILE_OP_ERROR(dest, "fopen");
2203 if (change_file_mode_rw(dest_fp, dest) < 0) {
2204 FILE_OP_ERROR(dest, "chmod");
2205 g_warning("can't change file mode\n");
2208 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2209 if (n_read < sizeof(buf) && ferror(src_fp))
2211 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2212 g_warning("writing to %s failed.\n", dest);
2220 if (ferror(src_fp)) {
2221 FILE_OP_ERROR(src, "fread");
2225 if (fclose(dest_fp) == EOF) {
2226 FILE_OP_ERROR(dest, "fclose");
2238 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2240 FILE *src_fp, *dest_fp;
2243 gchar *dest_bak = NULL;
2244 gboolean err = FALSE;
2246 if ((src_fp = fopen(src, "rb")) == NULL) {
2247 FILE_OP_ERROR(src, "fopen");
2250 if (is_file_exist(dest)) {
2251 dest_bak = g_strconcat(dest, ".bak", NULL);
2252 if (rename(dest, dest_bak) < 0) {
2253 FILE_OP_ERROR(dest, "rename");
2260 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2261 FILE_OP_ERROR(dest, "fopen");
2264 if (rename(dest_bak, dest) < 0)
2265 FILE_OP_ERROR(dest_bak, "rename");
2271 if (change_file_mode_rw(dest_fp, dest) < 0) {
2272 FILE_OP_ERROR(dest, "chmod");
2273 g_warning("can't change file mode\n");
2276 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2277 if (n_read < sizeof(buf) && ferror(src_fp))
2279 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2280 g_warning("writing to %s failed.\n", dest);
2285 if (rename(dest_bak, dest) < 0)
2286 FILE_OP_ERROR(dest_bak, "rename");
2293 if (ferror(src_fp)) {
2294 FILE_OP_ERROR(src, "fread");
2298 if (fclose(dest_fp) == EOF) {
2299 FILE_OP_ERROR(dest, "fclose");
2306 if (rename(dest_bak, dest) < 0)
2307 FILE_OP_ERROR(dest_bak, "rename");
2313 if (keep_backup == FALSE && dest_bak)
2321 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2323 if (overwrite == FALSE && is_file_exist(dest)) {
2324 g_warning("move_file(): file %s already exists.", dest);
2328 if (rename(src, dest) == 0) return 0;
2330 if (EXDEV != errno) {
2331 FILE_OP_ERROR(src, "rename");
2335 if (copy_file(src, dest, FALSE) < 0) return -1;
2342 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2346 gint bytes_left, to_read;
2348 gboolean err = FALSE;
2350 if (fseek(fp, offset, SEEK_SET) < 0) {
2355 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2356 FILE_OP_ERROR(dest, "fopen");
2360 if (change_file_mode_rw(dest_fp, dest) < 0) {
2361 FILE_OP_ERROR(dest, "chmod");
2362 g_warning("can't change file mode\n");
2365 bytes_left = length;
2366 to_read = MIN(bytes_left, sizeof(buf));
2368 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2369 if (n_read < to_read && ferror(fp))
2371 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2372 g_warning("writing to %s failed.\n", dest);
2377 bytes_left -= n_read;
2378 if (bytes_left == 0)
2380 to_read = MIN(bytes_left, sizeof(buf));
2387 if (fclose(dest_fp) == EOF) {
2388 FILE_OP_ERROR(dest, "fclose");
2400 /* convert line endings into CRLF. If the last line doesn't end with
2401 * linebreak, add it.
2403 gchar *canonicalize_str(const gchar *str)
2409 for (p = str; *p != '\0'; ++p) {
2416 if (p == str || *(p - 1) != '\n')
2419 out = outp = g_malloc(new_len + 1);
2420 for (p = str; *p != '\0'; ++p) {
2427 if (p == str || *(p - 1) != '\n') {
2436 gint canonicalize_file(const gchar *src, const gchar *dest)
2438 FILE *src_fp, *dest_fp;
2439 gchar buf[BUFFSIZE];
2441 gboolean err = FALSE;
2442 gboolean last_linebreak = FALSE;
2444 if ((src_fp = fopen(src, "rb")) == NULL) {
2445 FILE_OP_ERROR(src, "fopen");
2449 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2450 FILE_OP_ERROR(dest, "fopen");
2455 if (change_file_mode_rw(dest_fp, dest) < 0) {
2456 FILE_OP_ERROR(dest, "chmod");
2457 g_warning("can't change file mode\n");
2460 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2464 if (len == 0) break;
2465 last_linebreak = FALSE;
2467 if (buf[len - 1] != '\n') {
2468 last_linebreak = TRUE;
2469 r = fputs(buf, dest_fp);
2470 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2471 r = fputs(buf, dest_fp);
2474 r = fwrite(buf, len - 1, 1, dest_fp);
2479 r = fputs("\r\n", dest_fp);
2483 g_warning("writing to %s failed.\n", dest);
2491 if (last_linebreak == TRUE) {
2492 if (fputs("\r\n", dest_fp) == EOF)
2496 if (ferror(src_fp)) {
2497 FILE_OP_ERROR(src, "fgets");
2501 if (fclose(dest_fp) == EOF) {
2502 FILE_OP_ERROR(dest, "fclose");
2514 gint canonicalize_file_replace(const gchar *file)
2518 tmp_file = get_tmp_file();
2520 if (canonicalize_file(file, tmp_file) < 0) {
2525 if (move_file(tmp_file, file, TRUE) < 0) {
2526 g_warning("can't replace %s .\n", file);
2536 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2538 FILE *src_fp, *dest_fp;
2539 gchar buf[BUFFSIZE];
2540 gboolean err = FALSE;
2542 if ((src_fp = fopen(src, "rb")) == NULL) {
2543 FILE_OP_ERROR(src, "fopen");
2547 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2548 FILE_OP_ERROR(dest, "fopen");
2553 if (change_file_mode_rw(dest_fp, dest) < 0) {
2554 FILE_OP_ERROR(dest, "chmod");
2555 g_warning("can't change file mode\n");
2558 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2560 if (fputs(buf, dest_fp) == EOF) {
2561 g_warning("writing to %s failed.\n", dest);
2569 if (ferror(src_fp)) {
2570 FILE_OP_ERROR(src, "fgets");
2574 if (fclose(dest_fp) == EOF) {
2575 FILE_OP_ERROR(dest, "fclose");
2587 gint uncanonicalize_file_replace(const gchar *file)
2591 tmp_file = get_tmp_file();
2593 if (uncanonicalize_file(file, tmp_file) < 0) {
2598 if (move_file(tmp_file, file, TRUE) < 0) {
2599 g_warning("can't replace %s .\n", file);
2609 gchar *normalize_newlines(const gchar *str)
2611 const gchar *p = str;
2614 out = outp = g_malloc(strlen(str) + 1);
2615 for (p = str; *p != '\0'; ++p) {
2617 if (*(p + 1) != '\n')
2628 gchar *get_outgoing_rfc2822_str(FILE *fp)
2630 gchar buf[BUFFSIZE];
2634 str = g_string_new(NULL);
2636 /* output header part */
2637 while (fgets(buf, sizeof(buf), fp) != NULL) {
2639 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2646 else if (next != ' ' && next != '\t') {
2650 if (fgets(buf, sizeof(buf), fp) == NULL)
2654 g_string_append(str, buf);
2655 g_string_append(str, "\r\n");
2661 /* output body part */
2662 while (fgets(buf, sizeof(buf), fp) != NULL) {
2665 g_string_append_c(str, '.');
2666 g_string_append(str, buf);
2667 g_string_append(str, "\r\n");
2671 g_string_free(str, FALSE);
2676 gint change_file_mode_rw(FILE *fp, const gchar *file)
2679 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2681 return chmod(file, S_IRUSR|S_IWUSR);
2685 FILE *my_tmpfile(void)
2688 const gchar suffix[] = ".XXXXXX";
2689 const gchar *tmpdir;
2691 const gchar *progname;
2697 tmpdir = get_tmp_dir();
2698 tmplen = strlen(tmpdir);
2699 progname = g_get_prgname();
2700 proglen = strlen(progname);
2701 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2704 memcpy(fname, tmpdir, tmplen);
2705 fname[tmplen] = G_DIR_SEPARATOR;
2706 memcpy(fname + tmplen + 1, progname, proglen);
2707 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2709 fd = mkstemp(fname);
2715 fp = fdopen(fd, "w+b");
2720 #endif /* HAVE_MKSTEMP */
2725 FILE *str_open_as_stream(const gchar *str)
2730 g_return_val_if_fail(str != NULL, NULL);
2734 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2739 if (len == 0) return fp;
2741 if (fwrite(str, len, 1, fp) != 1) {
2742 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2751 gint str_write_to_file(const gchar *str, const gchar *file)
2756 g_return_val_if_fail(str != NULL, -1);
2757 g_return_val_if_fail(file != NULL, -1);
2759 if ((fp = fopen(file, "wb")) == NULL) {
2760 FILE_OP_ERROR(file, "fopen");
2770 if (fwrite(str, len, 1, fp) != 1) {
2771 FILE_OP_ERROR(file, "fwrite");
2777 if (fclose(fp) == EOF) {
2778 FILE_OP_ERROR(file, "fclose");
2786 gchar *file_read_to_str(const gchar *file)
2791 g_return_val_if_fail(file != NULL, NULL);
2793 if ((fp = fopen(file, "rb")) == NULL) {
2794 FILE_OP_ERROR(file, "fopen");
2798 str = file_read_stream_to_str(fp);
2805 gchar *file_read_stream_to_str(FILE *fp)
2812 g_return_val_if_fail(fp != NULL, NULL);
2814 array = g_byte_array_new();
2816 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2817 if (n_read < sizeof(buf) && ferror(fp))
2819 g_byte_array_append(array, buf, n_read);
2823 FILE_OP_ERROR("file stream", "fread");
2824 g_byte_array_free(array, TRUE);
2829 g_byte_array_append(array, buf, 1);
2830 str = (gchar *)array->data;
2831 g_byte_array_free(array, FALSE);
2836 gint execute_async(gchar *const argv[])
2840 if ((pid = fork()) < 0) {
2845 if (pid == 0) { /* child process */
2848 if ((gch_pid = fork()) < 0) {
2853 if (gch_pid == 0) { /* grandchild process */
2854 execvp(argv[0], argv);
2863 waitpid(pid, NULL, 0);
2868 gint execute_sync(gchar *const argv[])
2872 if ((pid = fork()) < 0) {
2877 if (pid == 0) { /* child process */
2878 execvp(argv[0], argv);
2884 waitpid(pid, NULL, 0);
2889 gint execute_command_line(const gchar *cmdline, gboolean async)
2894 argv = strsplit_with_quote(cmdline, " ", 0);
2897 ret = execute_async(argv);
2899 ret = execute_sync(argv);
2905 gchar *get_command_output(const gchar *cmdline)
2907 gchar buf[BUFFSIZE];
2912 g_return_val_if_fail(cmdline != NULL, NULL);
2914 if ((fp = popen(cmdline, "r")) == NULL) {
2915 FILE_OP_ERROR(cmdline, "popen");
2919 str = g_string_new("");
2921 while (fgets(buf, sizeof(buf), fp) != NULL)
2922 g_string_append(str, buf);
2927 g_string_free(str, FALSE);
2932 static gint is_unchanged_uri_char(char c)
2944 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2950 for(i = 0; i < strlen(uri) ; i++) {
2951 if (is_unchanged_uri_char(uri[i])) {
2952 if (k + 2 >= bufsize)
2954 encoded_uri[k++] = uri[i];
2957 char * hexa = "0123456789ABCDEF";
2959 if (k + 4 >= bufsize)
2961 encoded_uri[k++] = '%';
2962 encoded_uri[k++] = hexa[uri[i] / 16];
2963 encoded_uri[k++] = hexa[uri[i] % 16];
2969 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
2972 static gint axtoi(const gchar *hexstr)
2974 gint hi, lo, result;
2977 if ('0' <= hi && hi <= '9') {
2980 if ('a' <= hi && hi <= 'f') {
2983 if ('A' <= hi && hi <= 'F') {
2988 if ('0' <= lo && lo <= '9') {
2991 if ('a' <= lo && lo <= 'f') {
2994 if ('A' <= lo && lo <= 'F') {
2997 result = lo + (16 * hi);
3002 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
3003 * plusses, and escape characters are used)
3006 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
3008 const gchar *encoded;
3011 encoded = encoded_uri;
3012 decoded = decoded_uri;
3015 if (*encoded == '%') {
3017 if (isxdigit(encoded[0])
3018 && isxdigit(encoded[1])) {
3019 *decoded = (gchar) axtoi(encoded);
3024 else if (*encoded == '+') {
3030 *decoded = *encoded;
3040 gint open_uri(const gchar *uri, const gchar *cmdline)
3042 gchar buf[BUFFSIZE];
3044 gchar encoded_uri[BUFFSIZE];
3046 g_return_val_if_fail(uri != NULL, -1);
3048 /* an option to choose whether to use encode_uri or not ? */
3049 encode_uri(encoded_uri, BUFFSIZE, uri);
3052 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3053 !strchr(p + 2, '%'))
3054 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3057 g_warning("Open URI command line is invalid: `%s'",
3059 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3062 execute_command_line(buf, TRUE);
3067 time_t remote_tzoffset_sec(const gchar *zone)
3069 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3075 time_t remoteoffset;
3077 strncpy(zone3, zone, 3);
3081 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3082 (c == '+' || c == '-')) {
3083 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3085 remoteoffset = -remoteoffset;
3086 } else if (!strncmp(zone, "UT" , 2) ||
3087 !strncmp(zone, "GMT", 2)) {
3089 } else if (strlen(zone3) == 3 &&
3090 (p = strstr(ustzstr, zone3)) != NULL &&
3091 (p - ustzstr) % 3 == 0) {
3092 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3093 remoteoffset = iustz * 3600;
3094 } else if (strlen(zone3) == 1) {
3096 case 'Z': remoteoffset = 0; break;
3097 case 'A': remoteoffset = -1; break;
3098 case 'B': remoteoffset = -2; break;
3099 case 'C': remoteoffset = -3; break;
3100 case 'D': remoteoffset = -4; break;
3101 case 'E': remoteoffset = -5; break;
3102 case 'F': remoteoffset = -6; break;
3103 case 'G': remoteoffset = -7; break;
3104 case 'H': remoteoffset = -8; break;
3105 case 'I': remoteoffset = -9; break;
3106 case 'K': remoteoffset = -10; break; /* J is not used */
3107 case 'L': remoteoffset = -11; break;
3108 case 'M': remoteoffset = -12; break;
3109 case 'N': remoteoffset = 1; break;
3110 case 'O': remoteoffset = 2; break;
3111 case 'P': remoteoffset = 3; break;
3112 case 'Q': remoteoffset = 4; break;
3113 case 'R': remoteoffset = 5; break;
3114 case 'S': remoteoffset = 6; break;
3115 case 'T': remoteoffset = 7; break;
3116 case 'U': remoteoffset = 8; break;
3117 case 'V': remoteoffset = 9; break;
3118 case 'W': remoteoffset = 10; break;
3119 case 'X': remoteoffset = 11; break;
3120 case 'Y': remoteoffset = 12; break;
3121 default: remoteoffset = 0; break;
3123 remoteoffset = remoteoffset * 3600;
3126 return remoteoffset;
3129 time_t tzoffset_sec(time_t *now)
3135 lt = localtime(now);
3137 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3139 if (lt->tm_year < gmt.tm_year)
3141 else if (lt->tm_year > gmt.tm_year)
3143 else if (lt->tm_yday < gmt.tm_yday)
3145 else if (lt->tm_yday > gmt.tm_yday)
3148 if (off >= 24 * 60) /* should be impossible */
3149 off = 23 * 60 + 59; /* if not, insert silly value */
3150 if (off <= -24 * 60)
3151 off = -(23 * 60 + 59);
3156 /* calculate timezone offset */
3157 gchar *tzoffset(time_t *now)
3159 static gchar offset_string[6];
3165 lt = localtime(now);
3167 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3169 if (lt->tm_year < gmt.tm_year)
3171 else if (lt->tm_year > gmt.tm_year)
3173 else if (lt->tm_yday < gmt.tm_yday)
3175 else if (lt->tm_yday > gmt.tm_yday)
3183 if (off >= 24 * 60) /* should be impossible */
3184 off = 23 * 60 + 59; /* if not, insert silly value */
3186 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3188 return offset_string;
3191 void get_rfc822_date(gchar *buf, gint len)
3195 gchar day[4], mon[4];
3196 gint dd, hh, mm, ss, yyyy;
3201 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3202 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3203 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3204 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3207 void debug_set_mode(gboolean mode)
3212 gboolean debug_get_mode()
3217 void debug_print_real(const gchar *format, ...)
3220 gchar buf[BUFFSIZE];
3222 if (!debug_mode) return;
3224 va_start(args, format);
3225 g_vsnprintf(buf, sizeof(buf), format, args);
3231 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3233 if (subject == NULL)
3236 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3237 return g_hash_table_lookup(subject_table, subject + 4);
3239 return g_hash_table_lookup(subject_table, subject);
3242 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3245 if (subject == NULL)
3249 if (g_strcasecmp(subject, "Re:") == 0)
3251 if (g_strcasecmp(subject, "Re: ") == 0)
3254 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3255 g_hash_table_insert(subject_table, subject + 4, data);
3257 g_hash_table_insert(subject_table, subject, data);
3260 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3262 if (subject == NULL)
3265 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3266 g_hash_table_remove(subject_table, subject + 4);
3268 g_hash_table_remove(subject_table, subject);
3271 gboolean subject_is_reply(const gchar *subject)
3273 /* XXX: just simply here so someone can handle really
3274 * advanced Re: detection like "Re[4]", "ANTW:" or
3275 * Re: Re: Re: Re: Re: Re: Re: Re:" stuff. */
3276 if (subject == NULL) return FALSE;
3277 else return 0 == g_strncasecmp(subject, "Re: ", 4);
3280 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
3284 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
3285 fd = mkstemp(*filename);
3287 return fdopen(fd, "w+");
3290 /* allow Mutt-like patterns in quick search */
3291 gchar *expand_search_string(const gchar *search_string)
3294 gchar term_char, save_char;
3295 gchar *cmd_start, *cmd_end;
3296 GString *matcherstr;
3297 gchar *returnstr = NULL;
3299 gboolean casesens, dontmatch;
3300 /* list of allowed pattern abbreviations */
3302 gchar *abbreviated; /* abbreviation */
3303 gchar *command; /* actual matcher command */
3304 gint numparams; /* number of params for cmd */
3305 gboolean qualifier; /* do we append regexpcase */
3306 gboolean quotes; /* do we need quotes */
3309 { "a", "all", 0, FALSE, FALSE },
3310 { "ag", "age_greater", 1, FALSE, FALSE },
3311 { "al", "age_lower", 1, FALSE, FALSE },
3312 { "b", "body_part", 1, TRUE, TRUE },
3313 { "B", "message", 1, TRUE, TRUE },
3314 { "c", "cc", 1, TRUE, TRUE },
3315 { "C", "to_or_cc", 1, TRUE, TRUE },
3316 { "D", "deleted", 0, FALSE, FALSE },
3317 { "e", "header \"Sender\"", 1, TRUE, TRUE },
3318 { "E", "execute", 1, FALSE, TRUE },
3319 { "f", "from", 1, TRUE, TRUE },
3320 { "F", "forwarded", 0, FALSE, FALSE },
3321 { "h", "headers_part", 1, TRUE, TRUE },
3322 { "i", "header \"Message-Id\"", 1, TRUE, TRUE },
3323 { "I", "inreplyto", 1, TRUE, TRUE },
3324 { "L", "locked", 0, FALSE, FALSE },
3325 { "n", "newsgroups", 1, TRUE, TRUE },
3326 { "N", "new", 0, FALSE, FALSE },
3327 { "O", "~new", 0, FALSE, FALSE },
3328 { "r", "replied", 0, FALSE, FALSE },
3329 { "R", "~unread", 0, FALSE, FALSE },
3330 { "s", "subject", 1, TRUE, TRUE },
3331 { "se", "score_equal", 1, FALSE, FALSE },
3332 { "sg", "score_greater", 1, FALSE, FALSE },
3333 { "sl", "score_lower", 1, FALSE, FALSE },
3334 { "Se", "size_equal", 1, FALSE, FALSE },
3335 { "Sg", "size_greater", 1, FALSE, FALSE },
3336 { "Ss", "size_smaller", 1, FALSE, FALSE },
3337 { "t", "to", 1, TRUE, TRUE },
3338 { "T", "marked", 0, FALSE, FALSE },
3339 { "U", "unread", 0, FALSE, FALSE },
3340 { "x", "header \"References\"", 1, TRUE, TRUE },
3341 { "y", "header \"X-Label\"", 1, TRUE, TRUE },
3342 { "&", "&", 0, FALSE, FALSE },
3343 { "|", "|", 0, FALSE, FALSE },
3344 { NULL, NULL, 0, FALSE, FALSE }
3347 if (search_string == NULL)
3350 copy_str = g_strdup(search_string);
3352 /* if it's a full command don't process it so users
3353 can still do something like from regexpcase "foo" */
3354 for (i = 0; cmds[i].command; i++) {
3355 const gchar *tmp_search_string = search_string;
3356 cmd_start = cmds[i].command;
3357 /* allow logical NOT */
3358 if (*tmp_search_string == '~')
3359 tmp_search_string++;
3360 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3363 if (cmds[i].command)
3366 matcherstr = g_string_sized_new(16);
3367 cmd_start = cmd_end = copy_str;
3368 while (cmd_end && *cmd_end) {
3369 /* skip all white spaces */
3370 while (*cmd_end && isspace(*cmd_end))
3373 /* extract a command */
3374 while (*cmd_end && !isspace(*cmd_end))
3377 /* save character */
3378 save_char = *cmd_end;
3384 /* ~ and ! mean logical NOT */
3385 if (*cmd_start == '~' || *cmd_start == '!')
3390 /* % means case sensitive match */
3391 if (*cmd_start == '%')
3397 /* find matching abbreviation */
3398 for (i = 0; cmds[i].command; i++) {
3399 if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3400 /* restore character */
3401 *cmd_end = save_char;
3404 if (matcherstr->len > 0) {
3405 g_string_append(matcherstr, " ");
3408 g_string_append(matcherstr, "~");
3409 g_string_append(matcherstr, cmds[i].command);
3410 g_string_append(matcherstr, " ");
3412 /* stop if no params required */
3413 if (cmds[i].numparams == 0)
3416 /* extract a parameter, allow quotes */
3418 cmd_start = cmd_end;
3419 if (*cmd_start == '"') {
3426 /* extract actual parameter */
3427 while ((*cmd_end) && (*cmd_end != term_char))
3430 if (*cmd_end && (*cmd_end != term_char))
3433 if (*cmd_end == '"')
3436 save_char = *cmd_end;
3439 if (cmds[i].qualifier) {
3441 g_string_append(matcherstr, "regexp ");
3443 g_string_append(matcherstr, "regexpcase ");
3446 /* do we need to add quotes ? */
3447 if (cmds[i].quotes && term_char != '"')
3448 g_string_append(matcherstr, "\"");
3450 /* copy actual parameter */
3451 g_string_append(matcherstr, cmd_start);
3453 /* do we need to add quotes ? */
3454 if (cmds[i].quotes && term_char != '"')
3455 g_string_append(matcherstr, "\"");
3457 /* restore original character */
3458 *cmd_end = save_char;
3466 cmd_start = cmd_end;
3471 returnstr = matcherstr->str;
3472 g_string_free(matcherstr, FALSE);
3476 guint g_stricase_hash(gconstpointer gptr)
3478 guint hash_result = 0;
3481 for (str = gptr; str && *str; str++) {
3482 if (isupper(*str)) hash_result += (*str + ' ');
3483 else hash_result += *str;
3489 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3491 const char *str1 = gptr1;
3492 const char *str2 = gptr2;
3494 return !strcasecmp(str1, str2);
3497 gint g_int_compare(gconstpointer a, gconstpointer b)
3499 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);