2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2004 Hiroyuki Yamamoto & The Sylpheed-Claws Team
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>
49 #include "../codeconv.h"
53 static gboolean debug_mode = FALSE;
55 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
57 void list_free_strings(GList *list)
59 list = g_list_first(list);
61 while (list != NULL) {
67 void slist_free_strings(GSList *list)
69 while (list != NULL) {
75 GSList *slist_concat_unique (GSList *first, GSList *second)
83 } else if (second == NULL)
86 for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
87 if (g_slist_find(ret, tmp->data) == NULL)
88 ret = g_slist_prepend(ret, tmp->data);
93 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
98 void hash_free_strings(GHashTable *table)
100 g_hash_table_foreach(table, hash_free_strings_func, NULL);
103 static void hash_free_value_mem_func(gpointer key, gpointer value,
109 void hash_free_value_mem(GHashTable *table)
111 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
114 gint str_case_equal(gconstpointer v, gconstpointer v2)
116 return strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
119 guint str_case_hash(gconstpointer key)
121 const gchar *p = key;
126 for (p += 1; *p != '\0'; p++)
127 h = (h << 5) - h + tolower(*p);
133 void ptr_array_free_strings(GPtrArray *array)
138 g_return_if_fail(array != NULL);
140 for (i = 0; i < array->len; i++) {
141 str = g_ptr_array_index(array, i);
146 gint to_number(const gchar *nstr)
148 register const guchar *p;
150 if (*nstr == '\0') return -1;
152 for (p = nstr; *p != '\0'; p++)
153 if (!isdigit(*p)) return -1;
158 /* convert integer into string,
159 nstr must be not lower than 11 characters length */
160 gchar *itos_buf(gchar *nstr, gint n)
162 g_snprintf(nstr, 11, "%d", n);
166 /* convert integer into string */
169 static gchar nstr[11];
171 return itos_buf(nstr, n);
174 gchar *to_human_readable(off_t size)
176 static gchar str[10];
179 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
180 else if (size >> 10 < 1024)
181 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
182 else if (size >> 20 < 1024)
183 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
185 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
190 /* strcmp with NULL-checking */
191 gint strcmp2(const gchar *s1, const gchar *s2)
193 if (s1 == NULL || s2 == NULL)
196 return strcmp(s1, s2);
198 /* strstr with NULL-checking */
199 gchar *strstr2(const gchar *s1, const gchar *s2)
201 if (s1 == NULL || s2 == NULL)
204 return strstr(s1, s2);
207 gint path_cmp(const gchar *s1, const gchar *s2)
211 if (s1 == NULL || s2 == NULL) return -1;
212 if (*s1 == '\0' || *s2 == '\0') return -1;
217 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
218 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
220 return strncmp(s1, s2, MAX(len1, len2));
223 /* remove trailing return code */
224 gchar *strretchomp(gchar *str)
228 if (!*str) return str;
230 for (s = str + strlen(str) - 1;
231 s >= str && (*s == '\n' || *s == '\r');
238 /* remove trailing character */
239 gchar *strtailchomp(gchar *str, gchar tail_char)
243 if (!*str) return str;
244 if (tail_char == '\0') return str;
246 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
252 /* remove CR (carriage return) */
253 gchar *strcrchomp(gchar *str)
257 if (!*str) return str;
259 s = str + strlen(str) - 1;
260 if (*s == '\n' && s > str && *(s - 1) == '\r') {
268 /* Similar to `strstr' but this function ignores the case of both strings. */
269 gchar *strcasestr(const gchar *haystack, const gchar *needle)
271 register size_t haystack_len, needle_len;
273 haystack_len = strlen(haystack);
274 needle_len = strlen(needle);
276 if (haystack_len < needle_len || needle_len == 0)
279 while (haystack_len >= needle_len) {
280 if (!strncasecmp(haystack, needle, needle_len))
281 return (gchar *)haystack;
291 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
292 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
306 /* don't do zero fill */
311 int iswalnum(wint_t wc)
313 return isalnum((int)wc);
318 int iswspace(wint_t wc)
320 return isspace((int)wc);
325 wint_t towlower(wint_t wc)
327 if (wc >= L'A' && wc <= L'Z')
328 return wc + L'a' - L'A';
335 size_t wcslen(const wchar_t *s)
347 /* Copy SRC to DEST. */
348 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
356 } while (c != L'\0');
363 /* Copy no more than N wide-characters of SRC to DEST. */
364 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
374 } while (c != L'\0');
385 /* Duplicate S, returning an identical malloc'd string. */
386 wchar_t *wcsdup(const wchar_t *s)
391 new_str = g_new(wchar_t, wcslen(s) + 1);
399 /* Duplicate no more than N wide-characters of S,
400 returning an identical malloc'd string. */
401 wchar_t *wcsndup(const wchar_t *s, size_t n)
406 new_str = g_new(wchar_t, n + 1);
407 wcsncpy(new_str, s, n);
408 new_str[n] = (wchar_t)0;
415 wchar_t *strdup_mbstowcs(const gchar *s)
420 new_str = g_new(wchar_t, strlen(s) + 1);
421 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
425 new_str = g_realloc(new_str,
426 sizeof(wchar_t) * (wcslen(new_str) + 1));
433 gchar *strdup_wcstombs(const wchar_t *s)
439 len = wcslen(s) * MB_CUR_MAX + 1;
440 new_str = g_new(gchar, len);
441 if (wcstombs(new_str, s, len) < 0) {
445 new_str = g_realloc(new_str, strlen(new_str) + 1);
452 /* Compare S1 and S2, ignoring case. */
453 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
459 c1 = towlower(*s1++);
460 c2 = towlower(*s2++);
463 else if (c1 == 0 && c2 == 0)
470 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
471 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
473 register size_t haystack_len, needle_len;
475 haystack_len = wcslen(haystack);
476 needle_len = wcslen(needle);
478 if (haystack_len < needle_len || needle_len == 0)
481 while (haystack_len >= needle_len) {
482 if (!wcsncasecmp(haystack, needle, needle_len))
483 return (wchar_t *)haystack;
493 gint get_mbs_len(const gchar *s)
503 mb_len = mblen(p, MB_LEN_MAX);
517 /* Examine if next block is non-ASCII string */
518 gboolean is_next_nonascii(const guchar *s)
522 /* skip head space */
523 for (p = s; *p != '\0' && isspace(*p); p++)
525 for (; *p != '\0' && !isspace(*p); p++) {
526 if (*p > 127 || *p < 32)
533 gint get_next_word_len(const guchar *s)
537 for (; *s != '\0' && !isspace(*s); s++, len++)
543 /* compare subjects */
544 gint subject_compare(const gchar *s1, const gchar *s2)
548 if (!s1 || !s2) return -1;
549 if (!*s1 || !*s2) return -1;
551 Xstrdup_a(str1, s1, return -1);
552 Xstrdup_a(str2, s2, return -1);
554 trim_subject_for_compare(str1);
555 trim_subject_for_compare(str2);
557 if (!*str1 || !*str2) return -1;
559 return strcmp(str1, str2);
562 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
566 if (!s1 || !s2) return -1;
568 Xstrdup_a(str1, s1, return -1);
569 Xstrdup_a(str2, s2, return -1);
571 trim_subject_for_sort(str1);
572 trim_subject_for_sort(str2);
574 return strcasecmp(str1, str2);
577 void trim_subject_for_compare(gchar *str)
581 eliminate_parenthesis(str, '[', ']');
582 eliminate_parenthesis(str, '(', ')');
585 srcp = str + subject_get_prefix_length(str);
587 memmove(str, srcp, strlen(srcp) + 1);
590 void trim_subject_for_sort(gchar *str)
596 srcp = str + subject_get_prefix_length(str);
598 memmove(str, srcp, strlen(srcp) + 1);
601 void trim_subject(gchar *str)
603 register guchar *srcp, *destp;
607 destp = str + subject_get_prefix_length(str);
612 } else if (*destp == '(') {
623 else if (*srcp == cl)
629 while (isspace(*srcp)) srcp++;
630 memmove(destp, srcp, strlen(srcp) + 1);
633 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
635 register guchar *srcp, *destp;
640 while ((destp = strchr(destp, op))) {
646 else if (*srcp == cl)
652 while (isspace(*srcp)) srcp++;
653 memmove(destp, srcp, strlen(srcp) + 1);
657 void extract_parenthesis(gchar *str, gchar op, gchar cl)
659 register gchar *srcp, *destp;
664 while ((srcp = strchr(destp, op))) {
667 memmove(destp, srcp + 1, strlen(srcp));
672 else if (*destp == cl)
684 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
687 register gchar *srcp, *destp;
689 gboolean in_quote = FALSE;
693 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
696 memmove(destp, srcp + 1, strlen(srcp));
699 if (*destp == op && !in_quote)
701 else if (*destp == cl && !in_quote)
703 else if (*destp == quote_chr)
715 void eliminate_quote(gchar *str, gchar quote_chr)
717 register guchar *srcp, *destp;
721 while ((destp = strchr(destp, quote_chr))) {
722 if ((srcp = strchr(destp + 1, quote_chr))) {
724 while (isspace(*srcp)) srcp++;
725 memmove(destp, srcp, strlen(srcp) + 1);
733 void extract_quote(gchar *str, gchar quote_chr)
737 if ((str = strchr(str, quote_chr))) {
739 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
740 memmove(p - 1, p, strlen(p) + 1);
745 memmove(str, str + 1, p - str);
750 void eliminate_address_comment(gchar *str)
752 register guchar *srcp, *destp;
757 while ((destp = strchr(destp, '"'))) {
758 if ((srcp = strchr(destp + 1, '"'))) {
763 while (isspace(*srcp)) srcp++;
764 memmove(destp, srcp, strlen(srcp) + 1);
774 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
780 else if (*srcp == ')')
786 while (isspace(*srcp)) srcp++;
787 memmove(destp, srcp, strlen(srcp) + 1);
791 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
793 gboolean in_quote = FALSE;
796 if (*str == c && !in_quote)
798 if (*str == quote_chr)
806 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
808 gboolean in_quote = FALSE;
811 p = str + strlen(str) - 1;
813 if (*p == c && !in_quote)
823 void extract_address(gchar *str)
825 eliminate_address_comment(str);
826 if (strchr_with_skip_quote(str, '"', '<'))
827 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
831 void extract_list_id_str(gchar *str)
833 if (strchr_with_skip_quote(str, '"', '<'))
834 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
838 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
843 if (!str) return addr_list;
845 Xstrdup_a(work, str, return addr_list);
848 eliminate_address_comment(work);
851 while (workp && *workp) {
854 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
860 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
861 extract_parenthesis_with_skip_quote
862 (workp, '"', '<', '>');
866 addr_list = g_slist_append(addr_list, g_strdup(workp));
874 GSList *address_list_append(GSList *addr_list, const gchar *str)
876 return address_list_append_real(addr_list, str, TRUE);
879 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
881 return address_list_append_real(addr_list, str, FALSE);
884 GSList *references_list_append(GSList *msgid_list, const gchar *str)
888 if (!str) return msgid_list;
891 while (strp && *strp) {
892 const gchar *start, *end;
895 if ((start = strchr(strp, '<')) != NULL) {
896 end = strchr(start + 1, '>');
901 msgid = g_strndup(start + 1, end - start - 1);
904 msgid_list = g_slist_append(msgid_list, msgid);
914 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
919 if (!str) return group_list;
921 Xstrdup_a(work, str, return group_list);
925 while (workp && *workp) {
928 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
936 group_list = g_slist_append(group_list,
945 GList *add_history(GList *list, const gchar *str)
949 g_return_val_if_fail(str != NULL, list);
951 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
954 list = g_list_remove(list, old->data);
955 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
958 last = g_list_last(list);
961 g_list_remove(list, last->data);
965 list = g_list_prepend(list, g_strdup(str));
970 void remove_return(gchar *str)
972 register gchar *p = str;
975 if (*p == '\n' || *p == '\r')
976 memmove(p, p + 1, strlen(p));
982 void remove_space(gchar *str)
984 register guchar *p = str;
989 while (isspace(*(p + spc)))
992 memmove(p, p + spc, strlen(p + spc) + 1);
998 void unfold_line(gchar *str)
1000 register guchar *p = str;
1004 if (*p == '\n' || *p == '\r') {
1007 while (isspace(*(p + spc)))
1010 memmove(p, p + spc, strlen(p + spc) + 1);
1016 void subst_char(gchar *str, gchar orig, gchar subst)
1018 register gchar *p = str;
1027 void subst_chars(gchar *str, gchar *orig, gchar subst)
1029 register gchar *p = str;
1032 if (strchr(orig, *p) != NULL)
1038 void subst_for_filename(gchar *str)
1040 subst_chars(str, " \t\r\n\"/\\", '_');
1043 void subst_for_shellsafe_filename(gchar *str)
1045 subst_for_filename(str);
1046 subst_chars(str, "|&;()<>'!{}[]",'_');
1049 gboolean is_header_line(const gchar *str)
1051 if (str[0] == ':') return FALSE;
1053 while (*str != '\0' && *str != ' ') {
1062 gboolean is_ascii_str(const guchar *str)
1064 g_return_val_if_fail(str, FALSE);
1066 while (*str != '\0') {
1067 if (*str != '\t' && *str != ' ' &&
1068 *str != '\r' && *str != '\n' &&
1069 (*str < 32 || *str >= 127))
1077 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1079 const guchar *first_pos;
1080 const guchar *last_pos;
1081 const guchar *p = str;
1082 gint quote_level = -1;
1084 /* speed up line processing by only searching to the last '>' */
1085 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1086 /* skip a line if it contains a '<' before the initial '>' */
1087 if (memchr(str, '<', first_pos - (const guchar *)str) != NULL)
1089 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1093 while (p <= last_pos) {
1094 while (p < last_pos) {
1101 if (strchr(quote_chars, *p))
1103 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1104 /* any characters are allowed except '-' and space */
1106 && !strchr(quote_chars, *p)
1110 if (strchr(quote_chars, *p))
1122 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1124 gchar * position = NULL;
1125 gchar * tmp_pos = NULL;
1128 if (quote_chars == NULL)
1131 for (i = 0; i < strlen(quote_chars); i++) {
1132 tmp_pos = strchr (str, quote_chars[i]);
1134 || (tmp_pos != NULL && position >= tmp_pos) )
1140 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1142 gchar * position = NULL;
1143 gchar * tmp_pos = NULL;
1146 if (quote_chars == NULL)
1149 for (i = 0; i < strlen(quote_chars); i++) {
1150 tmp_pos = strrchr (str, quote_chars[i]);
1152 || (tmp_pos != NULL && position <= tmp_pos) )
1158 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1160 register guint haystack_len, needle_len;
1161 gboolean in_squote = FALSE, in_dquote = FALSE;
1163 haystack_len = strlen(haystack);
1164 needle_len = strlen(needle);
1166 if (haystack_len < needle_len || needle_len == 0)
1169 while (haystack_len >= needle_len) {
1170 if (!in_squote && !in_dquote &&
1171 !strncmp(haystack, needle, needle_len))
1172 return (gchar *)haystack;
1174 /* 'foo"bar"' -> foo"bar"
1175 "foo'bar'" -> foo'bar' */
1176 if (*haystack == '\'') {
1179 else if (!in_dquote)
1181 } else if (*haystack == '\"') {
1184 else if (!in_squote)
1195 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1198 gchar quote_chr = '"';
1200 gboolean in_quote = FALSE;
1204 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1208 if (*p == op && !in_quote)
1210 else if (*p == cl && !in_quote)
1212 else if (*p == quote_chr)
1225 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1228 GSList *string_list = NULL, *slist;
1230 const gchar *s_op, *s_cl;
1233 g_return_val_if_fail(str != NULL, NULL);
1236 max_tokens = G_MAXINT;
1238 s_op = strchr_with_skip_quote(str, '"', op);
1239 if (!s_op) return NULL;
1241 s_cl = strchr_parenthesis_close(str, op, cl);
1249 new_string = g_new(gchar, len + 1);
1250 strncpy(new_string, str, len);
1251 new_string[len] = 0;
1252 string_list = g_slist_prepend(string_list, new_string);
1256 while (*str && isspace(*(guchar *)str)) str++;
1258 string_list = g_slist_prepend(string_list,
1261 s_op = strchr_with_skip_quote(str, '"', op);
1262 if (!--max_tokens || !s_op) break;
1266 s_cl = strchr_parenthesis_close(str, op, cl);
1267 } while (--max_tokens && s_cl);
1270 str_array = g_new(gchar*, n);
1274 str_array[i--] = NULL;
1275 for (slist = string_list; slist; slist = slist->next)
1276 str_array[i--] = slist->data;
1278 g_slist_free(string_list);
1283 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1286 GSList *string_list = NULL, *slist;
1287 gchar **str_array, *s, *new_str;
1288 guint i, n = 1, len;
1290 g_return_val_if_fail(str != NULL, NULL);
1291 g_return_val_if_fail(delim != NULL, NULL);
1294 max_tokens = G_MAXINT;
1296 s = strstr_with_skip_quote(str, delim);
1298 guint delimiter_len = strlen(delim);
1302 new_str = g_strndup(str, len);
1304 if (new_str[0] == '\'' || new_str[0] == '\"') {
1305 if (new_str[len - 1] == new_str[0]) {
1306 new_str[len - 1] = '\0';
1307 memmove(new_str, new_str + 1, len - 1);
1310 string_list = g_slist_prepend(string_list, new_str);
1312 str = s + delimiter_len;
1313 s = strstr_with_skip_quote(str, delim);
1314 } while (--max_tokens && s);
1318 new_str = g_strdup(str);
1319 if (new_str[0] == '\'' || new_str[0] == '\"') {
1321 if (new_str[len - 1] == new_str[0]) {
1322 new_str[len - 1] = '\0';
1323 memmove(new_str, new_str + 1, len - 1);
1326 string_list = g_slist_prepend(string_list, new_str);
1330 str_array = g_new(gchar*, n);
1334 str_array[i--] = NULL;
1335 for (slist = string_list; slist; slist = slist->next)
1336 str_array[i--] = slist->data;
1338 g_slist_free(string_list);
1343 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1345 gchar *abbrev_group;
1347 const gchar *p = group;
1350 g_return_val_if_fail(group != NULL, NULL);
1352 last = group + strlen(group);
1353 abbrev_group = ap = g_malloc(strlen(group) + 1);
1358 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1360 while (*p != '.') p++;
1363 return abbrev_group;
1368 return abbrev_group;
1371 gchar *trim_string(const gchar *str, gint len)
1373 const gchar *p = str;
1378 if (!str) return NULL;
1379 if (strlen(str) <= len)
1380 return g_strdup(str);
1382 while (*p != '\0') {
1383 mb_len = mblen(p, MB_LEN_MAX);
1386 else if (mb_len < 0)
1387 return g_strdup(str);
1388 else if (new_len + mb_len > len)
1395 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1396 return g_strconcat(new_str, "...", NULL);
1399 GList *uri_list_extract_filenames(const gchar *uri_list)
1401 GList *result = NULL;
1403 gchar *escaped_utf8uri;
1410 while (isspace(*p)) p++;
1411 if (!strncmp(p, "file:", 5)) {
1414 while (*q && *q != '\n' && *q != '\r') q++;
1417 gchar *file, *locale_file = NULL;
1419 while (q > p && isspace(*q)) q--;
1420 Xalloca(escaped_utf8uri, q - p + 2,
1422 Xalloca(file, q - p + 2,
1425 strncpy(escaped_utf8uri, p, q - p + 1);
1426 escaped_utf8uri[q - p + 1] = '\0';
1427 decode_uri(file, escaped_utf8uri);
1428 #warning FIXME_GTK2 /* should we use g_filename_from_utf8()? */
1430 * g_filename_from_uri() rejects escaped/locale encoded uri
1431 * string which come from Nautilus.
1433 if (g_utf8_validate(file, -1, NULL))
1435 = conv_codeset_strdup(
1438 conv_get_current_charset_str());
1440 locale_file = g_strdup(file + 5);
1441 result = g_list_append(result, locale_file);
1445 p = strchr(p, '\n');
1452 #define HEX_TO_INT(val, hex) \
1456 if ('0' <= c && c <= '9') { \
1458 } else if ('a' <= c && c <= 'f') { \
1459 val = c - 'a' + 10; \
1460 } else if ('A' <= c && c <= 'F') { \
1461 val = c - 'A' + 10; \
1467 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1470 static gint axtoi(const gchar *hexstr)
1472 gint hi, lo, result;
1475 if ('0' <= hi && hi <= '9') {
1478 if ('a' <= hi && hi <= 'f') {
1481 if ('A' <= hi && hi <= 'F') {
1486 if ('0' <= lo && lo <= '9') {
1489 if ('a' <= lo && lo <= 'f') {
1492 if ('A' <= lo && lo <= 'F') {
1495 result = lo + (16 * hi);
1499 gboolean is_uri_string(const gchar *str)
1501 return (g_strncasecmp(str, "http://", 7) == 0 ||
1502 g_strncasecmp(str, "https://", 8) == 0 ||
1503 g_strncasecmp(str, "ftp://", 6) == 0 ||
1504 g_strncasecmp(str, "www.", 4) == 0);
1507 gchar *get_uri_path(const gchar *uri)
1509 if (g_strncasecmp(uri, "http://", 7) == 0)
1510 return (gchar *)(uri + 7);
1511 else if (g_strncasecmp(uri, "https://", 8) == 0)
1512 return (gchar *)(uri + 8);
1513 else if (g_strncasecmp(uri, "ftp://", 6) == 0)
1514 return (gchar *)(uri + 6);
1516 return (gchar *)uri;
1519 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1520 * plusses, and escape characters are used)
1522 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1524 gchar *dec = decoded_uri;
1525 const gchar *enc = encoded_uri;
1530 if (isxdigit((guchar)enc[0]) &&
1531 isxdigit((guchar)enc[1])) {
1549 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1550 gchar **subject, gchar **body)
1555 Xstrdup_a(tmp_mailto, mailto, return -1);
1557 if (!strncmp(tmp_mailto, "mailto:", 7))
1560 p = strchr(tmp_mailto, '?');
1567 *to = g_strdup(tmp_mailto);
1570 gchar *field, *value;
1587 if (*value == '\0') continue;
1589 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1590 *cc = g_strdup(value);
1591 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1592 *bcc = g_strdup(value);
1593 } else if (subject && !*subject &&
1594 !g_strcasecmp(field, "subject")) {
1595 *subject = g_malloc(strlen(value) + 1);
1596 decode_uri(*subject, value);
1597 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1598 *body = g_malloc(strlen(value) + 1);
1599 decode_uri(*body, value);
1607 * We need this wrapper around g_get_home_dir(), so that
1608 * we can fix some Windoze things here. Should be done in glibc of course
1609 * but as long as we are not able to do our own extensions to glibc, we do
1612 const gchar *get_home_dir(void)
1614 #if HAVE_DOSISH_SYSTEM
1615 static gchar *home_dir;
1618 home_dir = read_w32_registry_string(NULL,
1619 "Software\\Sylpheed", "HomeDir" );
1620 if (!home_dir || !*home_dir) {
1621 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1622 const char *s = g_get_home_dir();
1624 home_dir = g_strdup (s);
1626 if (!home_dir || !*home_dir)
1627 home_dir = g_strdup ("c:\\sylpheed");
1629 debug_print("initialized home_dir to `%s'\n", home_dir);
1632 #else /* standard glib */
1633 return g_get_home_dir();
1637 const gchar *get_rc_dir(void)
1639 static gchar *rc_dir = NULL;
1642 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1648 const gchar *get_news_cache_dir(void)
1650 static gchar *news_cache_dir = NULL;
1652 if (!news_cache_dir)
1653 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1654 NEWS_CACHE_DIR, NULL);
1656 return news_cache_dir;
1659 const gchar *get_imap_cache_dir(void)
1661 static gchar *imap_cache_dir = NULL;
1663 if (!imap_cache_dir)
1664 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1665 IMAP_CACHE_DIR, NULL);
1667 return imap_cache_dir;
1670 const gchar *get_mbox_cache_dir(void)
1672 static gchar *mbox_cache_dir = NULL;
1674 if (!mbox_cache_dir)
1675 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1676 MBOX_CACHE_DIR, NULL);
1678 return mbox_cache_dir;
1681 const gchar *get_mime_tmp_dir(void)
1683 static gchar *mime_tmp_dir = NULL;
1686 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1687 MIME_TMP_DIR, NULL);
1689 return mime_tmp_dir;
1692 const gchar *get_template_dir(void)
1694 static gchar *template_dir = NULL;
1697 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1698 TEMPLATE_DIR, NULL);
1700 return template_dir;
1703 const gchar *get_header_cache_dir(void)
1705 static gchar *header_dir = NULL;
1708 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1709 HEADER_CACHE_DIR, NULL);
1714 const gchar *get_tmp_dir(void)
1716 static gchar *tmp_dir = NULL;
1719 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1725 gchar *get_tmp_file(void)
1728 static guint32 id = 0;
1730 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1731 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1736 const gchar *get_domain_name(void)
1738 static gchar *domain_name = NULL;
1741 gchar buf[128] = "";
1744 if (gethostname(buf, sizeof(buf)) < 0) {
1745 perror("gethostname");
1746 domain_name = "unknown";
1748 buf[sizeof(buf) - 1] = '\0';
1749 if ((hp = my_gethostbyname(buf)) == NULL) {
1750 perror("gethostbyname");
1751 domain_name = g_strdup(buf);
1753 domain_name = g_strdup(hp->h_name);
1757 debug_print("domain name = %s\n", domain_name);
1763 off_t get_file_size(const gchar *file)
1767 if (stat(file, &s) < 0) {
1768 FILE_OP_ERROR(file, "stat");
1775 off_t get_file_size_as_crlf(const gchar *file)
1779 gchar buf[BUFFSIZE];
1781 if ((fp = fopen(file, "rb")) == NULL) {
1782 FILE_OP_ERROR(file, "fopen");
1786 while (fgets(buf, sizeof(buf), fp) != NULL) {
1788 size += strlen(buf) + 2;
1792 FILE_OP_ERROR(file, "fgets");
1801 off_t get_left_file_size(FILE *fp)
1807 if ((pos = ftell(fp)) < 0) {
1811 if (fseek(fp, 0L, SEEK_END) < 0) {
1815 if ((end = ftell(fp)) < 0) {
1820 if (fseek(fp, pos, SEEK_SET) < 0) {
1828 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1835 if (stat(file, &s) < 0) {
1836 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1840 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1846 gboolean is_dir_exist(const gchar *dir)
1853 if (stat(dir, &s) < 0) {
1854 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1858 if (S_ISDIR(s.st_mode))
1864 gboolean is_file_entry_exist(const gchar *file)
1871 if (stat(file, &s) < 0) {
1872 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1879 gboolean dirent_is_regular_file(struct dirent *d)
1883 #ifdef HAVE_DIRENT_D_TYPE
1884 if (d->d_type == DT_REG)
1886 else if (d->d_type != DT_UNKNOWN)
1890 return (stat(d->d_name, &s) == 0 && S_ISREG(s.st_mode));
1893 gboolean dirent_is_directory(struct dirent *d)
1897 #ifdef HAVE_DIRENT_D_TYPE
1898 if (d->d_type == DT_DIR)
1900 else if (d->d_type != DT_UNKNOWN)
1904 return (stat(d->d_name, &s) == 0 && S_ISDIR(s.st_mode));
1907 gint change_dir(const gchar *dir)
1909 gchar *prevdir = NULL;
1912 prevdir = g_get_current_dir();
1914 if (chdir(dir) < 0) {
1915 FILE_OP_ERROR(dir, "chdir");
1916 if (debug_mode) g_free(prevdir);
1918 } else if (debug_mode) {
1921 cwd = g_get_current_dir();
1922 if (strcmp(prevdir, cwd) != 0)
1923 g_print("current dir: %s\n", cwd);
1931 gint make_dir(const gchar *dir)
1933 if (mkdir(dir, S_IRWXU) < 0) {
1934 FILE_OP_ERROR(dir, "mkdir");
1937 if (chmod(dir, S_IRWXU) < 0)
1938 FILE_OP_ERROR(dir, "chmod");
1943 gint make_dir_hier(const gchar *dir)
1948 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1949 parent_dir = g_strndup(dir, p - dir);
1950 if (*parent_dir != '\0') {
1951 if (!is_dir_exist(parent_dir)) {
1952 if (make_dir(parent_dir) < 0) {
1961 if (!is_dir_exist(dir)) {
1962 if (make_dir(dir) < 0)
1969 gint remove_all_files(const gchar *dir)
1975 prev_dir = g_get_current_dir();
1977 if (chdir(dir) < 0) {
1978 FILE_OP_ERROR(dir, "chdir");
1983 if ((dp = opendir(".")) == NULL) {
1984 FILE_OP_ERROR(dir, "opendir");
1989 while ((d = readdir(dp)) != NULL) {
1990 if (!strcmp(d->d_name, ".") ||
1991 !strcmp(d->d_name, ".."))
1994 if (unlink(d->d_name) < 0)
1995 FILE_OP_ERROR(d->d_name, "unlink");
2000 if (chdir(prev_dir) < 0) {
2001 FILE_OP_ERROR(prev_dir, "chdir");
2011 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2018 prev_dir = g_get_current_dir();
2020 if (chdir(dir) < 0) {
2021 FILE_OP_ERROR(dir, "chdir");
2026 if ((dp = opendir(".")) == NULL) {
2027 FILE_OP_ERROR(dir, "opendir");
2032 while ((d = readdir(dp)) != NULL) {
2033 fileno = to_number(d->d_name);
2034 if (fileno >= 0 && first <= fileno && fileno <= last) {
2035 if (is_dir_exist(d->d_name))
2037 if (unlink(d->d_name) < 0)
2038 FILE_OP_ERROR(d->d_name, "unlink");
2044 if (chdir(prev_dir) < 0) {
2045 FILE_OP_ERROR(prev_dir, "chdir");
2055 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2062 prev_dir = g_get_current_dir();
2064 if (chdir(dir) < 0) {
2065 FILE_OP_ERROR(dir, "chdir");
2070 if ((dp = opendir(".")) == NULL) {
2071 FILE_OP_ERROR(dir, "opendir");
2076 while ((d = readdir(dp)) != NULL) {
2077 fileno = to_number(d->d_name);
2078 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
2079 debug_print("removing unwanted file %d from %s\n", fileno, dir);
2080 if (is_dir_exist(d->d_name))
2082 if (unlink(d->d_name) < 0)
2083 FILE_OP_ERROR(d->d_name, "unlink");
2089 if (chdir(prev_dir) < 0) {
2090 FILE_OP_ERROR(prev_dir, "chdir");
2100 gint remove_all_numbered_files(const gchar *dir)
2102 return remove_numbered_files(dir, 0, UINT_MAX);
2105 gint remove_expired_files(const gchar *dir, guint hours)
2112 time_t mtime, now, expire_time;
2114 prev_dir = g_get_current_dir();
2116 if (chdir(dir) < 0) {
2117 FILE_OP_ERROR(dir, "chdir");
2122 if ((dp = opendir(".")) == NULL) {
2123 FILE_OP_ERROR(dir, "opendir");
2129 expire_time = hours * 60 * 60;
2131 while ((d = readdir(dp)) != NULL) {
2132 fileno = to_number(d->d_name);
2134 if (stat(d->d_name, &s) < 0) {
2135 FILE_OP_ERROR(d->d_name, "stat");
2138 if (S_ISDIR(s.st_mode))
2140 mtime = MAX(s.st_mtime, s.st_atime);
2141 if (now - mtime > expire_time) {
2142 if (unlink(d->d_name) < 0)
2143 FILE_OP_ERROR(d->d_name, "unlink");
2150 if (chdir(prev_dir) < 0) {
2151 FILE_OP_ERROR(prev_dir, "chdir");
2161 gint remove_dir_recursive(const gchar *dir)
2168 /* g_print("dir = %s\n", dir); */
2170 if (stat(dir, &s) < 0) {
2171 FILE_OP_ERROR(dir, "stat");
2172 if (ENOENT == errno) return 0;
2176 if (!S_ISDIR(s.st_mode)) {
2177 if (unlink(dir) < 0) {
2178 FILE_OP_ERROR(dir, "unlink");
2185 prev_dir = g_get_current_dir();
2186 /* g_print("prev_dir = %s\n", prev_dir); */
2188 if (!path_cmp(prev_dir, dir)) {
2190 if (chdir("..") < 0) {
2191 FILE_OP_ERROR(dir, "chdir");
2194 prev_dir = g_get_current_dir();
2197 if (chdir(dir) < 0) {
2198 FILE_OP_ERROR(dir, "chdir");
2203 if ((dp = opendir(".")) == NULL) {
2204 FILE_OP_ERROR(dir, "opendir");
2210 /* remove all files in the directory */
2211 while ((d = readdir(dp)) != NULL) {
2212 if (!strcmp(d->d_name, ".") ||
2213 !strcmp(d->d_name, ".."))
2216 /* g_print("removing %s\n", d->d_name); */
2218 if (dirent_is_directory(d)) {
2219 if (remove_dir_recursive(d->d_name) < 0) {
2220 g_warning("can't remove directory\n");
2224 if (unlink(d->d_name) < 0)
2225 FILE_OP_ERROR(d->d_name, "unlink");
2231 if (chdir(prev_dir) < 0) {
2232 FILE_OP_ERROR(prev_dir, "chdir");
2239 if (rmdir(dir) < 0) {
2240 FILE_OP_ERROR(dir, "rmdir");
2248 /* this seems to be slower than the stdio version... */
2249 gint copy_file(const gchar *src, const gchar *dest)
2251 gint src_fd, dest_fd;
2255 gchar *dest_bak = NULL;
2257 if ((src_fd = open(src, O_RDONLY)) < 0) {
2258 FILE_OP_ERROR(src, "open");
2262 if (is_file_exist(dest)) {
2263 dest_bak = g_strconcat(dest, ".bak", NULL);
2264 if (rename(dest, dest_bak) < 0) {
2265 FILE_OP_ERROR(dest, "rename");
2272 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2273 FILE_OP_ERROR(dest, "open");
2276 if (rename(dest_bak, dest) < 0)
2277 FILE_OP_ERROR(dest_bak, "rename");
2283 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2288 n_write = write(dest_fd, bufp, len);
2290 g_warning("writing to %s failed.\n", dest);
2295 if (rename(dest_bak, dest) < 0)
2296 FILE_OP_ERROR(dest_bak, "rename");
2309 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2310 g_warning("File copy from %s to %s failed.\n", src, dest);
2313 if (rename(dest_bak, dest) < 0)
2314 FILE_OP_ERROR(dest_bak, "rename");
2327 * Append src file body to the tail of dest file.
2328 * Now keep_backup has no effects.
2330 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2332 FILE *src_fp, *dest_fp;
2336 gboolean err = FALSE;
2338 if ((src_fp = fopen(src, "rb")) == NULL) {
2339 FILE_OP_ERROR(src, "fopen");
2343 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2344 FILE_OP_ERROR(dest, "fopen");
2349 if (change_file_mode_rw(dest_fp, dest) < 0) {
2350 FILE_OP_ERROR(dest, "chmod");
2351 g_warning("can't change file mode\n");
2354 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2355 if (n_read < sizeof(buf) && ferror(src_fp))
2357 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2358 g_warning("writing to %s failed.\n", dest);
2366 if (ferror(src_fp)) {
2367 FILE_OP_ERROR(src, "fread");
2371 if (fclose(dest_fp) == EOF) {
2372 FILE_OP_ERROR(dest, "fclose");
2384 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2386 FILE *src_fp, *dest_fp;
2389 gchar *dest_bak = NULL;
2390 gboolean err = FALSE;
2392 if ((src_fp = fopen(src, "rb")) == NULL) {
2393 FILE_OP_ERROR(src, "fopen");
2396 if (is_file_exist(dest)) {
2397 dest_bak = g_strconcat(dest, ".bak", NULL);
2398 if (rename(dest, dest_bak) < 0) {
2399 FILE_OP_ERROR(dest, "rename");
2406 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2407 FILE_OP_ERROR(dest, "fopen");
2410 if (rename(dest_bak, dest) < 0)
2411 FILE_OP_ERROR(dest_bak, "rename");
2417 if (change_file_mode_rw(dest_fp, dest) < 0) {
2418 FILE_OP_ERROR(dest, "chmod");
2419 g_warning("can't change file mode\n");
2422 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2423 if (n_read < sizeof(buf) && ferror(src_fp))
2425 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2426 g_warning("writing to %s failed.\n", dest);
2431 if (rename(dest_bak, dest) < 0)
2432 FILE_OP_ERROR(dest_bak, "rename");
2439 if (ferror(src_fp)) {
2440 FILE_OP_ERROR(src, "fread");
2444 if (fclose(dest_fp) == EOF) {
2445 FILE_OP_ERROR(dest, "fclose");
2452 if (rename(dest_bak, dest) < 0)
2453 FILE_OP_ERROR(dest_bak, "rename");
2459 if (keep_backup == FALSE && dest_bak)
2467 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2469 if (overwrite == FALSE && is_file_exist(dest)) {
2470 g_warning("move_file(): file %s already exists.", dest);
2474 if (rename(src, dest) == 0) return 0;
2476 if (EXDEV != errno) {
2477 FILE_OP_ERROR(src, "rename");
2481 if (copy_file(src, dest, FALSE) < 0) return -1;
2488 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2492 gint bytes_left, to_read;
2494 gboolean err = FALSE;
2496 if (fseek(fp, offset, SEEK_SET) < 0) {
2501 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2502 FILE_OP_ERROR(dest, "fopen");
2506 if (change_file_mode_rw(dest_fp, dest) < 0) {
2507 FILE_OP_ERROR(dest, "chmod");
2508 g_warning("can't change file mode\n");
2511 bytes_left = length;
2512 to_read = MIN(bytes_left, sizeof(buf));
2514 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2515 if (n_read < to_read && ferror(fp))
2517 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2518 g_warning("writing to %s failed.\n", dest);
2523 bytes_left -= n_read;
2524 if (bytes_left == 0)
2526 to_read = MIN(bytes_left, sizeof(buf));
2533 if (fclose(dest_fp) == EOF) {
2534 FILE_OP_ERROR(dest, "fclose");
2546 /* convert line endings into CRLF. If the last line doesn't end with
2547 * linebreak, add it.
2549 gchar *canonicalize_str(const gchar *str)
2555 for (p = str; *p != '\0'; ++p) {
2562 if (p == str || *(p - 1) != '\n')
2565 out = outp = g_malloc(new_len + 1);
2566 for (p = str; *p != '\0'; ++p) {
2573 if (p == str || *(p - 1) != '\n') {
2582 gint canonicalize_file(const gchar *src, const gchar *dest)
2584 FILE *src_fp, *dest_fp;
2585 gchar buf[BUFFSIZE];
2587 gboolean err = FALSE;
2588 gboolean last_linebreak = FALSE;
2590 if ((src_fp = fopen(src, "rb")) == NULL) {
2591 FILE_OP_ERROR(src, "fopen");
2595 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2596 FILE_OP_ERROR(dest, "fopen");
2601 if (change_file_mode_rw(dest_fp, dest) < 0) {
2602 FILE_OP_ERROR(dest, "chmod");
2603 g_warning("can't change file mode\n");
2606 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2610 if (len == 0) break;
2611 last_linebreak = FALSE;
2613 if (buf[len - 1] != '\n') {
2614 last_linebreak = TRUE;
2615 r = fputs(buf, dest_fp);
2616 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2617 r = fputs(buf, dest_fp);
2620 r = fwrite(buf, len - 1, 1, dest_fp);
2625 r = fputs("\r\n", dest_fp);
2629 g_warning("writing to %s failed.\n", dest);
2637 if (last_linebreak == TRUE) {
2638 if (fputs("\r\n", dest_fp) == EOF)
2642 if (ferror(src_fp)) {
2643 FILE_OP_ERROR(src, "fgets");
2647 if (fclose(dest_fp) == EOF) {
2648 FILE_OP_ERROR(dest, "fclose");
2660 gint canonicalize_file_replace(const gchar *file)
2664 tmp_file = get_tmp_file();
2666 if (canonicalize_file(file, tmp_file) < 0) {
2671 if (move_file(tmp_file, file, TRUE) < 0) {
2672 g_warning("can't replace %s .\n", file);
2682 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2684 FILE *src_fp, *dest_fp;
2685 gchar buf[BUFFSIZE];
2686 gboolean err = FALSE;
2688 if ((src_fp = fopen(src, "rb")) == NULL) {
2689 FILE_OP_ERROR(src, "fopen");
2693 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2694 FILE_OP_ERROR(dest, "fopen");
2699 if (change_file_mode_rw(dest_fp, dest) < 0) {
2700 FILE_OP_ERROR(dest, "chmod");
2701 g_warning("can't change file mode\n");
2704 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2706 if (fputs(buf, dest_fp) == EOF) {
2707 g_warning("writing to %s failed.\n", dest);
2715 if (ferror(src_fp)) {
2716 FILE_OP_ERROR(src, "fgets");
2720 if (fclose(dest_fp) == EOF) {
2721 FILE_OP_ERROR(dest, "fclose");
2733 gint uncanonicalize_file_replace(const gchar *file)
2737 tmp_file = get_tmp_file();
2739 if (uncanonicalize_file(file, tmp_file) < 0) {
2744 if (move_file(tmp_file, file, TRUE) < 0) {
2745 g_warning("can't replace %s .\n", file);
2755 gchar *normalize_newlines(const gchar *str)
2757 const gchar *p = str;
2760 out = outp = g_malloc(strlen(str) + 1);
2761 for (p = str; *p != '\0'; ++p) {
2763 if (*(p + 1) != '\n')
2774 gchar *get_outgoing_rfc2822_str(FILE *fp)
2776 gchar buf[BUFFSIZE];
2780 str = g_string_new(NULL);
2782 /* output header part */
2783 while (fgets(buf, sizeof(buf), fp) != NULL) {
2785 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2792 else if (next != ' ' && next != '\t') {
2796 if (fgets(buf, sizeof(buf), fp) == NULL)
2800 g_string_append(str, buf);
2801 g_string_append(str, "\r\n");
2807 /* output body part */
2808 while (fgets(buf, sizeof(buf), fp) != NULL) {
2811 g_string_append_c(str, '.');
2812 g_string_append(str, buf);
2813 g_string_append(str, "\r\n");
2817 g_string_free(str, FALSE);
2823 * Create a new boundary in a way that it is very unlikely that this
2824 * will occur in the following text. It would be easy to ensure
2825 * uniqueness if everything is either quoted-printable or base64
2826 * encoded (note that conversion is allowed), but because MIME bodies
2827 * may be nested, it may happen that the same boundary has already
2828 * been used. We avoid scanning the message for conflicts and hope the
2831 * boundary := 0*69<bchars> bcharsnospace
2832 * bchars := bcharsnospace / " "
2833 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2834 * "+" / "_" / "," / "-" / "." /
2835 * "/" / ":" / "=" / "?"
2837 * some special characters removed because of buggy MTAs
2840 gchar *generate_mime_boundary(const gchar *prefix)
2842 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2843 "abcdefghijklmnopqrstuvwxyz"
2852 /* We make the boundary depend on the pid, so that all running
2853 * processes generate different values even when they have been
2854 * started within the same second and srandom(time(NULL)) has been
2855 * used. I can't see whether this is really an advantage but it
2856 * doesn't do any harm.
2858 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2859 buf_uniq[i] = tbl[(random() ^ pid) % (sizeof(tbl) - 1)];
2862 get_rfc822_date(buf_date, sizeof(buf_date));
2863 subst_char(buf_date, ' ', '_');
2864 subst_char(buf_date, ',', '_');
2865 subst_char(buf_date, ':', '_');
2867 return g_strdup_printf("%s=_%s_%s", prefix ? prefix : "Multipart",
2868 buf_date, buf_uniq);
2871 gint change_file_mode_rw(FILE *fp, const gchar *file)
2874 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2876 return chmod(file, S_IRUSR|S_IWUSR);
2880 FILE *my_tmpfile(void)
2883 const gchar suffix[] = ".XXXXXX";
2884 const gchar *tmpdir;
2886 const gchar *progname;
2892 tmpdir = get_tmp_dir();
2893 tmplen = strlen(tmpdir);
2894 progname = g_get_prgname();
2895 proglen = strlen(progname);
2896 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2899 memcpy(fname, tmpdir, tmplen);
2900 fname[tmplen] = G_DIR_SEPARATOR;
2901 memcpy(fname + tmplen + 1, progname, proglen);
2902 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2904 fd = mkstemp(fname);
2910 fp = fdopen(fd, "w+b");
2915 #endif /* HAVE_MKSTEMP */
2920 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2924 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2925 fd = mkstemp(*filename);
2927 return fdopen(fd, "w+");
2930 FILE *str_open_as_stream(const gchar *str)
2935 g_return_val_if_fail(str != NULL, NULL);
2939 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2944 if (len == 0) return fp;
2946 if (fwrite(str, len, 1, fp) != 1) {
2947 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2956 gint str_write_to_file(const gchar *str, const gchar *file)
2961 g_return_val_if_fail(str != NULL, -1);
2962 g_return_val_if_fail(file != NULL, -1);
2964 if ((fp = fopen(file, "wb")) == NULL) {
2965 FILE_OP_ERROR(file, "fopen");
2975 if (fwrite(str, len, 1, fp) != 1) {
2976 FILE_OP_ERROR(file, "fwrite");
2982 if (fclose(fp) == EOF) {
2983 FILE_OP_ERROR(file, "fclose");
2991 gchar *file_read_to_str(const gchar *file)
2996 g_return_val_if_fail(file != NULL, NULL);
2998 if ((fp = fopen(file, "rb")) == NULL) {
2999 FILE_OP_ERROR(file, "fopen");
3003 str = file_read_stream_to_str(fp);
3010 gchar *file_read_stream_to_str(FILE *fp)
3017 g_return_val_if_fail(fp != NULL, NULL);
3019 array = g_byte_array_new();
3021 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3022 if (n_read < sizeof(buf) && ferror(fp))
3024 g_byte_array_append(array, buf, n_read);
3028 FILE_OP_ERROR("file stream", "fread");
3029 g_byte_array_free(array, TRUE);
3034 g_byte_array_append(array, buf, 1);
3035 str = (gchar *)array->data;
3036 g_byte_array_free(array, FALSE);
3038 if (!g_utf8_validate(str, -1, NULL)) {
3039 const gchar *src_codeset, *dest_codeset;
3041 src_codeset = conv_get_current_charset_str();
3042 dest_codeset = CS_UTF_8;
3043 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3051 gint execute_async(gchar *const argv[])
3056 if ((pid = fork()) < 0) {
3061 if (pid == 0) { /* child process */
3064 if ((gch_pid = fork()) < 0) {
3069 if (gch_pid == 0) { /* grandchild process */
3070 execvp(argv[0], argv);
3079 waitpid(pid, &status, 0);
3081 if (WIFEXITED(status))
3082 return WEXITSTATUS(status);
3087 gint execute_sync(gchar *const argv[])
3092 if ((pid = fork()) < 0) {
3097 if (pid == 0) { /* child process */
3098 execvp(argv[0], argv);
3104 waitpid(pid, &status, 0);
3106 if (WIFEXITED(status))
3107 return WEXITSTATUS(status);
3112 gint execute_command_line(const gchar *cmdline, gboolean async)
3117 debug_print("executing: %s\n", cmdline);
3119 argv = strsplit_with_quote(cmdline, " ", 0);
3122 ret = execute_async(argv);
3124 ret = execute_sync(argv);
3131 gchar *get_command_output(const gchar *cmdline)
3133 gchar buf[BUFFSIZE];
3138 g_return_val_if_fail(cmdline != NULL, NULL);
3140 if ((fp = popen(cmdline, "r")) == NULL) {
3141 FILE_OP_ERROR(cmdline, "popen");
3145 str = g_string_new("");
3147 while (fgets(buf, sizeof(buf), fp) != NULL)
3148 g_string_append(str, buf);
3153 g_string_free(str, FALSE);
3155 if (!g_utf8_validate(ret, -1, NULL)) {
3156 const gchar *src_codeset, *dest_codeset;
3158 src_codeset = conv_get_current_charset_str();
3159 dest_codeset = CS_UTF_8;
3160 tmp = conv_codeset_strdup(ret, src_codeset, dest_codeset);
3168 static gint is_unchanged_uri_char(char c)
3180 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3186 for(i = 0; i < strlen(uri) ; i++) {
3187 if (is_unchanged_uri_char(uri[i])) {
3188 if (k + 2 >= bufsize)
3190 encoded_uri[k++] = uri[i];
3193 char * hexa = "0123456789ABCDEF";
3195 if (k + 4 >= bufsize)
3197 encoded_uri[k++] = '%';
3198 encoded_uri[k++] = hexa[uri[i] / 16];
3199 encoded_uri[k++] = hexa[uri[i] % 16];
3205 gint open_uri(const gchar *uri, const gchar *cmdline)
3207 gchar buf[BUFFSIZE];
3209 gchar encoded_uri[BUFFSIZE];
3211 g_return_val_if_fail(uri != NULL, -1);
3213 /* an option to choose whether to use encode_uri or not ? */
3214 encode_uri(encoded_uri, BUFFSIZE, uri);
3217 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3218 !strchr(p + 2, '%'))
3219 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3222 g_warning("Open URI command line is invalid "
3223 "(there must be only one '%%s'): %s",
3225 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3228 execute_command_line(buf, TRUE);
3233 time_t remote_tzoffset_sec(const gchar *zone)
3235 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3241 time_t remoteoffset;
3243 strncpy(zone3, zone, 3);
3247 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3248 (c == '+' || c == '-')) {
3249 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3251 remoteoffset = -remoteoffset;
3252 } else if (!strncmp(zone, "UT" , 2) ||
3253 !strncmp(zone, "GMT", 2)) {
3255 } else if (strlen(zone3) == 3) {
3256 for (p = ustzstr; *p != '\0'; p += 3) {
3257 if (!strncasecmp(p, zone3, 3)) {
3258 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3259 remoteoffset = iustz * 3600;
3265 } else if (strlen(zone3) == 1) {
3267 case 'Z': remoteoffset = 0; break;
3268 case 'A': remoteoffset = -1; break;
3269 case 'B': remoteoffset = -2; break;
3270 case 'C': remoteoffset = -3; break;
3271 case 'D': remoteoffset = -4; break;
3272 case 'E': remoteoffset = -5; break;
3273 case 'F': remoteoffset = -6; break;
3274 case 'G': remoteoffset = -7; break;
3275 case 'H': remoteoffset = -8; break;
3276 case 'I': remoteoffset = -9; break;
3277 case 'K': remoteoffset = -10; break; /* J is not used */
3278 case 'L': remoteoffset = -11; break;
3279 case 'M': remoteoffset = -12; break;
3280 case 'N': remoteoffset = 1; break;
3281 case 'O': remoteoffset = 2; break;
3282 case 'P': remoteoffset = 3; break;
3283 case 'Q': remoteoffset = 4; break;
3284 case 'R': remoteoffset = 5; break;
3285 case 'S': remoteoffset = 6; break;
3286 case 'T': remoteoffset = 7; break;
3287 case 'U': remoteoffset = 8; break;
3288 case 'V': remoteoffset = 9; break;
3289 case 'W': remoteoffset = 10; break;
3290 case 'X': remoteoffset = 11; break;
3291 case 'Y': remoteoffset = 12; break;
3292 default: remoteoffset = 0; break;
3294 remoteoffset = remoteoffset * 3600;
3298 return remoteoffset;
3301 time_t tzoffset_sec(time_t *now)
3307 lt = localtime(now);
3309 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3311 if (lt->tm_year < gmt.tm_year)
3313 else if (lt->tm_year > gmt.tm_year)
3315 else if (lt->tm_yday < gmt.tm_yday)
3317 else if (lt->tm_yday > gmt.tm_yday)
3320 if (off >= 24 * 60) /* should be impossible */
3321 off = 23 * 60 + 59; /* if not, insert silly value */
3322 if (off <= -24 * 60)
3323 off = -(23 * 60 + 59);
3328 /* calculate timezone offset */
3329 gchar *tzoffset(time_t *now)
3331 static gchar offset_string[6];
3337 lt = localtime(now);
3339 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3341 if (lt->tm_year < gmt.tm_year)
3343 else if (lt->tm_year > gmt.tm_year)
3345 else if (lt->tm_yday < gmt.tm_yday)
3347 else if (lt->tm_yday > gmt.tm_yday)
3355 if (off >= 24 * 60) /* should be impossible */
3356 off = 23 * 60 + 59; /* if not, insert silly value */
3358 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3360 return offset_string;
3363 void get_rfc822_date(gchar *buf, gint len)
3367 gchar day[4], mon[4];
3368 gint dd, hh, mm, ss, yyyy;
3373 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3374 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3375 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3376 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3379 void debug_set_mode(gboolean mode)
3384 gboolean debug_get_mode(void)
3389 void debug_print_real(const gchar *format, ...)
3392 gchar buf[BUFFSIZE];
3394 if (!debug_mode) return;
3396 va_start(args, format);
3397 g_vsnprintf(buf, sizeof(buf), format, args);
3403 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3405 if (subject == NULL)
3408 subject += subject_get_prefix_length(subject);
3410 return g_hash_table_lookup(subject_table, subject);
3413 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3416 if (subject == NULL || *subject == 0)
3418 subject += subject_get_prefix_length(subject);
3419 g_hash_table_insert(subject_table, subject, data);
3422 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3424 if (subject == NULL)
3427 subject += subject_get_prefix_length(subject);
3428 g_hash_table_remove(subject_table, subject);
3432 *\brief Check if a string is prefixed with known (combinations)
3433 * of prefixes. The function assumes that each prefix
3434 * is terminated by zero or exactly _one_ space.
3436 *\param str String to check for a prefixes
3438 *\return int Number of chars in the prefix that should be skipped
3439 * for a "clean" subject line. If no prefix was found, 0
3442 int subject_get_prefix_length(const gchar *subject)
3444 /*!< Array with allowable reply prefixes regexps. */
3445 static const gchar * const prefixes[] = {
3446 "Re\\:", /* "Re:" */
3447 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3448 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3449 "Aw\\:", /* "Aw:" (German) */
3450 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3451 "Res\\:", /* "Res:" (Brazilian Outlook) */
3452 "Fw\\:", /* "Fw:" Forward */
3453 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3454 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3455 "Rif\\:" /* "Rif:" (Italian Outlook) */
3458 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3461 static regex_t regex;
3462 static gboolean init_;
3464 if (!subject) return 0;
3465 if (!*subject) return 0;
3468 GString *s = g_string_new("");
3470 for (n = 0; n < PREFIXES; n++)
3471 /* Terminate each prefix regexpression by a
3472 * "\ ?" (zero or ONE space), and OR them */
3473 g_string_sprintfa(s, "(%s\\ ?)%s",
3478 g_string_prepend(s, "(");
3479 g_string_append(s, ")+"); /* match at least once */
3480 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3483 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3484 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3485 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3486 debug_print("Error compiling regexp %s\n", s->str);
3487 g_string_free(s, TRUE);
3491 g_string_free(s, TRUE);
3495 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3501 guint g_stricase_hash(gconstpointer gptr)
3503 guint hash_result = 0;
3506 for (str = gptr; str && *str; str++) {
3507 if (isupper((guchar)*str)) hash_result += (*str + ' ');
3508 else hash_result += *str;
3514 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3516 const char *str1 = gptr1;
3517 const char *str2 = gptr2;
3519 return !strcasecmp(str1, str2);
3522 gint g_int_compare(gconstpointer a, gconstpointer b)
3524 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3527 gchar *generate_msgid(const gchar *address, gchar *buf, gint len)
3529 /* steal from compose.c::compose_generate_msgid() */
3537 if (address && *address) {
3538 if (strchr(address, '@'))
3539 addr = g_strdup(address);
3541 addr = g_strconcat(address, "@", get_domain_name(), NULL);
3543 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3546 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3547 lt->tm_year + 1900, lt->tm_mon + 1,
3548 lt->tm_mday, lt->tm_hour,
3549 lt->tm_min, lt->tm_sec,
3550 (guint)random(), addr);
3558 quote_cmd_argument()
3560 return a quoted string safely usable in argument of a command.
3562 code is extracted and adapted from etPan! project -- DINH V. HoĆ .
3565 gint quote_cmd_argument(gchar * result, guint size,
3575 for(p = path ; * p != '\0' ; p ++) {
3577 if (isalnum((guchar)*p) || (* p == '/')) {
3578 if (remaining > 0) {
3584 result[size - 1] = '\0';
3589 if (remaining >= 2) {
3597 result[size - 1] = '\0';
3602 if (remaining > 0) {
3606 result[size - 1] = '\0';
3620 static void g_node_map_recursive(GNode *node, gpointer data)
3622 GNodeMapData *mapdata = (GNodeMapData *) data;
3624 GNodeMapData newmapdata;
3627 newdata = mapdata->func(node->data, mapdata->data);
3628 if (newdata != NULL) {
3629 newnode = g_node_new(newdata);
3630 g_node_append(mapdata->parent, newnode);
3632 newmapdata.parent = newnode;
3633 newmapdata.func = mapdata->func;
3634 newmapdata.data = mapdata->data;
3636 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3640 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3643 GNodeMapData mapdata;
3645 g_return_val_if_fail(node != NULL, NULL);
3646 g_return_val_if_fail(func != NULL, NULL);
3648 root = g_node_new(func(node->data, data));
3650 mapdata.parent = root;
3651 mapdata.func = func;
3652 mapdata.data = data;
3654 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);