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>
45 #include <sys/utsname.h>
50 #include "../codeconv.h"
54 static gboolean debug_mode = FALSE;
56 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
58 void list_free_strings(GList *list)
60 list = g_list_first(list);
62 while (list != NULL) {
68 void slist_free_strings(GSList *list)
70 while (list != NULL) {
76 GSList *slist_concat_unique (GSList *first, GSList *second)
84 } else if (second == NULL)
87 for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
88 if (g_slist_find(ret, tmp->data) == NULL)
89 ret = g_slist_prepend(ret, tmp->data);
94 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
99 void hash_free_strings(GHashTable *table)
101 g_hash_table_foreach(table, hash_free_strings_func, NULL);
104 static void hash_free_value_mem_func(gpointer key, gpointer value,
110 void hash_free_value_mem(GHashTable *table)
112 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
115 gint str_case_equal(gconstpointer v, gconstpointer v2)
117 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
120 guint str_case_hash(gconstpointer key)
122 const gchar *p = key;
127 for (p += 1; *p != '\0'; p++)
128 h = (h << 5) - h + tolower(*p);
134 void ptr_array_free_strings(GPtrArray *array)
139 g_return_if_fail(array != NULL);
141 for (i = 0; i < array->len; i++) {
142 str = g_ptr_array_index(array, i);
147 gint to_number(const gchar *nstr)
149 register const guchar *p;
151 if (*nstr == '\0') return -1;
153 for (p = nstr; *p != '\0'; p++)
154 if (!isdigit(*p)) return -1;
159 /* convert integer into string,
160 nstr must be not lower than 11 characters length */
161 gchar *itos_buf(gchar *nstr, gint n)
163 g_snprintf(nstr, 11, "%d", n);
167 /* convert integer into string */
170 static gchar nstr[11];
172 return itos_buf(nstr, n);
175 gchar *to_human_readable(off_t size)
177 static gchar str[10];
180 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
181 else if (size >> 10 < 1024)
182 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
183 else if (size >> 20 < 1024)
184 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
186 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
191 /* strcmp with NULL-checking */
192 gint strcmp2(const gchar *s1, const gchar *s2)
194 if (s1 == NULL || s2 == NULL)
197 return strcmp(s1, s2);
199 /* strstr with NULL-checking */
200 gchar *strstr2(const gchar *s1, const gchar *s2)
202 if (s1 == NULL || s2 == NULL)
205 return strstr(s1, s2);
208 gint path_cmp(const gchar *s1, const gchar *s2)
212 if (s1 == NULL || s2 == NULL) return -1;
213 if (*s1 == '\0' || *s2 == '\0') return -1;
218 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
219 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
221 return strncmp(s1, s2, MAX(len1, len2));
224 /* remove trailing return code */
225 gchar *strretchomp(gchar *str)
229 if (!*str) return str;
231 for (s = str + strlen(str) - 1;
232 s >= str && (*s == '\n' || *s == '\r');
239 /* remove trailing character */
240 gchar *strtailchomp(gchar *str, gchar tail_char)
244 if (!*str) return str;
245 if (tail_char == '\0') return str;
247 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
253 /* remove CR (carriage return) */
254 gchar *strcrchomp(gchar *str)
258 if (!*str) return str;
260 s = str + strlen(str) - 1;
261 if (*s == '\n' && s > str && *(s - 1) == '\r') {
269 /* Similar to `strstr' but this function ignores the case of both strings. */
270 gchar *strcasestr(const gchar *haystack, const gchar *needle)
272 register size_t haystack_len, needle_len;
274 haystack_len = strlen(haystack);
275 needle_len = strlen(needle);
277 if (haystack_len < needle_len || needle_len == 0)
280 while (haystack_len >= needle_len) {
281 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
282 return (gchar *)haystack;
292 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
293 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
307 /* don't do zero fill */
312 int iswalnum(wint_t wc)
314 return isalnum((int)wc);
319 int iswspace(wint_t wc)
321 return isspace((int)wc);
326 wint_t towlower(wint_t wc)
328 if (wc >= L'A' && wc <= L'Z')
329 return wc + L'a' - L'A';
336 size_t wcslen(const wchar_t *s)
348 /* Copy SRC to DEST. */
349 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
357 } while (c != L'\0');
364 /* Copy no more than N wide-characters of SRC to DEST. */
365 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
375 } while (c != L'\0');
386 /* Duplicate S, returning an identical malloc'd string. */
387 wchar_t *wcsdup(const wchar_t *s)
392 new_str = g_new(wchar_t, wcslen(s) + 1);
400 /* Duplicate no more than N wide-characters of S,
401 returning an identical malloc'd string. */
402 wchar_t *wcsndup(const wchar_t *s, size_t n)
407 new_str = g_new(wchar_t, n + 1);
408 wcsncpy(new_str, s, n);
409 new_str[n] = (wchar_t)0;
416 wchar_t *strdup_mbstowcs(const gchar *s)
421 new_str = g_new(wchar_t, strlen(s) + 1);
422 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
426 new_str = g_realloc(new_str,
427 sizeof(wchar_t) * (wcslen(new_str) + 1));
434 gchar *strdup_wcstombs(const wchar_t *s)
440 len = wcslen(s) * MB_CUR_MAX + 1;
441 new_str = g_new(gchar, len);
442 if (wcstombs(new_str, s, len) < 0) {
446 new_str = g_realloc(new_str, strlen(new_str) + 1);
453 /* Compare S1 and S2, ignoring case. */
454 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
460 c1 = towlower(*s1++);
461 c2 = towlower(*s2++);
464 else if (c1 == 0 && c2 == 0)
471 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
472 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
474 register size_t haystack_len, needle_len;
476 haystack_len = wcslen(haystack);
477 needle_len = wcslen(needle);
479 if (haystack_len < needle_len || needle_len == 0)
482 while (haystack_len >= needle_len) {
483 if (!wcsncasecmp(haystack, needle, needle_len))
484 return (wchar_t *)haystack;
494 gint get_mbs_len(const gchar *s)
504 mb_len = mblen(p, MB_LEN_MAX);
518 /* Examine if next block is non-ASCII string */
519 gboolean is_next_nonascii(const guchar *s)
523 /* skip head space */
524 for (p = s; *p != '\0' && isspace(*p); p++)
526 for (; *p != '\0' && !isspace(*p); p++) {
527 if (*p > 127 || *p < 32)
534 gint get_next_word_len(const guchar *s)
538 for (; *s != '\0' && !isspace(*s); s++, len++)
544 /* compare subjects */
545 gint subject_compare(const gchar *s1, const gchar *s2)
549 if (!s1 || !s2) return -1;
550 if (!*s1 || !*s2) return -1;
552 Xstrdup_a(str1, s1, return -1);
553 Xstrdup_a(str2, s2, return -1);
555 trim_subject_for_compare(str1);
556 trim_subject_for_compare(str2);
558 if (!*str1 || !*str2) return -1;
560 return strcmp(str1, str2);
563 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
567 if (!s1 || !s2) return -1;
569 Xstrdup_a(str1, s1, return -1);
570 Xstrdup_a(str2, s2, return -1);
572 trim_subject_for_sort(str1);
573 trim_subject_for_sort(str2);
575 return g_utf8_collate(str1, str2);
578 void trim_subject_for_compare(gchar *str)
582 eliminate_parenthesis(str, '[', ']');
583 eliminate_parenthesis(str, '(', ')');
586 srcp = str + subject_get_prefix_length(str);
588 memmove(str, srcp, strlen(srcp) + 1);
591 void trim_subject_for_sort(gchar *str)
597 srcp = str + subject_get_prefix_length(str);
599 memmove(str, srcp, strlen(srcp) + 1);
602 void trim_subject(gchar *str)
604 register guchar *srcp, *destp;
608 destp = str + subject_get_prefix_length(str);
613 } else if (*destp == '(') {
624 else if (*srcp == cl)
630 while (isspace(*srcp)) srcp++;
631 memmove(destp, srcp, strlen(srcp) + 1);
634 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
636 register guchar *srcp, *destp;
641 while ((destp = strchr(destp, op))) {
647 else if (*srcp == cl)
653 while (isspace(*srcp)) srcp++;
654 memmove(destp, srcp, strlen(srcp) + 1);
658 void extract_parenthesis(gchar *str, gchar op, gchar cl)
660 register gchar *srcp, *destp;
665 while ((srcp = strchr(destp, op))) {
668 memmove(destp, srcp + 1, strlen(srcp));
673 else if (*destp == cl)
685 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
688 register gchar *srcp, *destp;
690 gboolean in_quote = FALSE;
694 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
697 memmove(destp, srcp + 1, strlen(srcp));
700 if (*destp == op && !in_quote)
702 else if (*destp == cl && !in_quote)
704 else if (*destp == quote_chr)
716 void eliminate_quote(gchar *str, gchar quote_chr)
718 register guchar *srcp, *destp;
722 while ((destp = strchr(destp, quote_chr))) {
723 if ((srcp = strchr(destp + 1, quote_chr))) {
725 while (isspace(*srcp)) srcp++;
726 memmove(destp, srcp, strlen(srcp) + 1);
734 void extract_quote(gchar *str, gchar quote_chr)
738 if ((str = strchr(str, quote_chr))) {
740 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
741 memmove(p - 1, p, strlen(p) + 1);
746 memmove(str, str + 1, p - str);
751 void eliminate_address_comment(gchar *str)
753 register guchar *srcp, *destp;
758 while ((destp = strchr(destp, '"'))) {
759 if ((srcp = strchr(destp + 1, '"'))) {
764 while (isspace(*srcp)) srcp++;
765 memmove(destp, srcp, strlen(srcp) + 1);
775 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
781 else if (*srcp == ')')
787 while (isspace(*srcp)) srcp++;
788 memmove(destp, srcp, strlen(srcp) + 1);
792 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
794 gboolean in_quote = FALSE;
797 if (*str == c && !in_quote)
799 if (*str == quote_chr)
807 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
809 gboolean in_quote = FALSE;
812 p = str + strlen(str) - 1;
814 if (*p == c && !in_quote)
824 void extract_address(gchar *str)
826 eliminate_address_comment(str);
827 if (strchr_with_skip_quote(str, '"', '<'))
828 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
832 void extract_list_id_str(gchar *str)
834 if (strchr_with_skip_quote(str, '"', '<'))
835 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
839 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
844 if (!str) return addr_list;
846 Xstrdup_a(work, str, return addr_list);
849 eliminate_address_comment(work);
852 while (workp && *workp) {
855 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
861 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
862 extract_parenthesis_with_skip_quote
863 (workp, '"', '<', '>');
867 addr_list = g_slist_append(addr_list, g_strdup(workp));
875 GSList *address_list_append(GSList *addr_list, const gchar *str)
877 return address_list_append_real(addr_list, str, TRUE);
880 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
882 return address_list_append_real(addr_list, str, FALSE);
885 GSList *references_list_append(GSList *msgid_list, const gchar *str)
889 if (!str) return msgid_list;
892 while (strp && *strp) {
893 const gchar *start, *end;
896 if ((start = strchr(strp, '<')) != NULL) {
897 end = strchr(start + 1, '>');
902 msgid = g_strndup(start + 1, end - start - 1);
905 msgid_list = g_slist_append(msgid_list, msgid);
915 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
920 if (!str) return group_list;
922 Xstrdup_a(work, str, return group_list);
926 while (workp && *workp) {
929 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
937 group_list = g_slist_append(group_list,
946 GList *add_history(GList *list, const gchar *str)
950 g_return_val_if_fail(str != NULL, list);
952 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
955 list = g_list_remove(list, old->data);
956 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
959 last = g_list_last(list);
962 g_list_remove(list, last->data);
966 list = g_list_prepend(list, g_strdup(str));
971 void remove_return(gchar *str)
973 register gchar *p = str;
976 if (*p == '\n' || *p == '\r')
977 memmove(p, p + 1, strlen(p));
983 void remove_space(gchar *str)
985 register guchar *p = str;
990 while (isspace(*(p + spc)))
993 memmove(p, p + spc, strlen(p + spc) + 1);
999 void unfold_line(gchar *str)
1001 register guchar *p = str;
1005 if (*p == '\n' || *p == '\r') {
1008 while (isspace(*(p + spc)))
1011 memmove(p, p + spc, strlen(p + spc) + 1);
1017 void subst_char(gchar *str, gchar orig, gchar subst)
1019 register gchar *p = str;
1028 void subst_chars(gchar *str, gchar *orig, gchar subst)
1030 register gchar *p = str;
1033 if (strchr(orig, *p) != NULL)
1039 void subst_for_filename(gchar *str)
1041 subst_chars(str, " \t\r\n\"/\\", '_');
1044 void subst_for_shellsafe_filename(gchar *str)
1046 subst_for_filename(str);
1047 subst_chars(str, "|&;()<>'!{}[]",'_');
1050 gboolean is_header_line(const gchar *str)
1052 if (str[0] == ':') return FALSE;
1054 while (*str != '\0' && *str != ' ') {
1063 gboolean is_ascii_str(const guchar *str)
1065 g_return_val_if_fail(str, FALSE);
1067 while (*str != '\0') {
1068 if (*str != '\t' && *str != ' ' &&
1069 *str != '\r' && *str != '\n' &&
1070 (*str < 32 || *str >= 127))
1078 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1080 const guchar *first_pos;
1081 const guchar *last_pos;
1082 const guchar *p = str;
1083 gint quote_level = -1;
1085 /* speed up line processing by only searching to the last '>' */
1086 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1087 /* skip a line if it contains a '<' before the initial '>' */
1088 if (memchr(str, '<', first_pos - (const guchar *)str) != NULL)
1090 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1094 while (p <= last_pos) {
1095 while (p < last_pos) {
1102 if (strchr(quote_chars, *p))
1104 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1105 /* any characters are allowed except '-' and space */
1107 && !strchr(quote_chars, *p)
1111 if (strchr(quote_chars, *p))
1123 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1125 gchar * position = NULL;
1126 gchar * tmp_pos = NULL;
1129 if (quote_chars == NULL)
1132 for (i = 0; i < strlen(quote_chars); i++) {
1133 tmp_pos = strchr (str, quote_chars[i]);
1135 || (tmp_pos != NULL && position >= tmp_pos) )
1141 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1143 gchar * position = NULL;
1144 gchar * tmp_pos = NULL;
1147 if (quote_chars == NULL)
1150 for (i = 0; i < strlen(quote_chars); i++) {
1151 tmp_pos = strrchr (str, quote_chars[i]);
1153 || (tmp_pos != NULL && position <= tmp_pos) )
1159 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1161 register guint haystack_len, needle_len;
1162 gboolean in_squote = FALSE, in_dquote = FALSE;
1164 haystack_len = strlen(haystack);
1165 needle_len = strlen(needle);
1167 if (haystack_len < needle_len || needle_len == 0)
1170 while (haystack_len >= needle_len) {
1171 if (!in_squote && !in_dquote &&
1172 !strncmp(haystack, needle, needle_len))
1173 return (gchar *)haystack;
1175 /* 'foo"bar"' -> foo"bar"
1176 "foo'bar'" -> foo'bar' */
1177 if (*haystack == '\'') {
1180 else if (!in_dquote)
1182 } else if (*haystack == '\"') {
1185 else if (!in_squote)
1196 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1199 gchar quote_chr = '"';
1201 gboolean in_quote = FALSE;
1205 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1209 if (*p == op && !in_quote)
1211 else if (*p == cl && !in_quote)
1213 else if (*p == quote_chr)
1226 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1229 GSList *string_list = NULL, *slist;
1231 const gchar *s_op, *s_cl;
1234 g_return_val_if_fail(str != NULL, NULL);
1237 max_tokens = G_MAXINT;
1239 s_op = strchr_with_skip_quote(str, '"', op);
1240 if (!s_op) return NULL;
1242 s_cl = strchr_parenthesis_close(str, op, cl);
1250 new_string = g_new(gchar, len + 1);
1251 strncpy(new_string, str, len);
1252 new_string[len] = 0;
1253 string_list = g_slist_prepend(string_list, new_string);
1257 while (*str && isspace(*(guchar *)str)) str++;
1259 string_list = g_slist_prepend(string_list,
1262 s_op = strchr_with_skip_quote(str, '"', op);
1263 if (!--max_tokens || !s_op) break;
1267 s_cl = strchr_parenthesis_close(str, op, cl);
1268 } while (--max_tokens && s_cl);
1271 str_array = g_new(gchar*, n);
1275 str_array[i--] = NULL;
1276 for (slist = string_list; slist; slist = slist->next)
1277 str_array[i--] = slist->data;
1279 g_slist_free(string_list);
1284 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1287 GSList *string_list = NULL, *slist;
1288 gchar **str_array, *s, *new_str;
1289 guint i, n = 1, len;
1291 g_return_val_if_fail(str != NULL, NULL);
1292 g_return_val_if_fail(delim != NULL, NULL);
1295 max_tokens = G_MAXINT;
1297 s = strstr_with_skip_quote(str, delim);
1299 guint delimiter_len = strlen(delim);
1303 new_str = g_strndup(str, len);
1305 if (new_str[0] == '\'' || new_str[0] == '\"') {
1306 if (new_str[len - 1] == new_str[0]) {
1307 new_str[len - 1] = '\0';
1308 memmove(new_str, new_str + 1, len - 1);
1311 string_list = g_slist_prepend(string_list, new_str);
1313 str = s + delimiter_len;
1314 s = strstr_with_skip_quote(str, delim);
1315 } while (--max_tokens && s);
1319 new_str = g_strdup(str);
1320 if (new_str[0] == '\'' || new_str[0] == '\"') {
1322 if (new_str[len - 1] == new_str[0]) {
1323 new_str[len - 1] = '\0';
1324 memmove(new_str, new_str + 1, len - 1);
1327 string_list = g_slist_prepend(string_list, new_str);
1331 str_array = g_new(gchar*, n);
1335 str_array[i--] = NULL;
1336 for (slist = string_list; slist; slist = slist->next)
1337 str_array[i--] = slist->data;
1339 g_slist_free(string_list);
1344 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1346 gchar *abbrev_group;
1348 const gchar *p = group;
1351 g_return_val_if_fail(group != NULL, NULL);
1353 last = group + strlen(group);
1354 abbrev_group = ap = g_malloc(strlen(group) + 1);
1359 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1361 while (*p != '.') p++;
1364 return abbrev_group;
1369 return abbrev_group;
1372 gchar *trim_string(const gchar *str, gint len)
1374 const gchar *p = str;
1379 if (!str) return NULL;
1380 if (strlen(str) <= len)
1381 return g_strdup(str);
1383 while (*p != '\0') {
1384 mb_len = mblen(p, MB_LEN_MAX);
1387 else if (mb_len < 0)
1388 return g_strdup(str);
1389 else if (new_len + mb_len > len)
1396 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1397 return g_strconcat(new_str, "...", NULL);
1400 GList *uri_list_extract_filenames(const gchar *uri_list)
1402 GList *result = NULL;
1404 gchar *escaped_utf8uri;
1411 while (isspace(*p)) p++;
1412 if (!strncmp(p, "file:", 5)) {
1415 while (*q && *q != '\n' && *q != '\r') q++;
1418 gchar *file, *locale_file = NULL;
1420 while (q > p && isspace(*q)) q--;
1421 Xalloca(escaped_utf8uri, q - p + 2,
1423 Xalloca(file, q - p + 2,
1426 strncpy(escaped_utf8uri, p, q - p + 1);
1427 escaped_utf8uri[q - p + 1] = '\0';
1428 decode_uri(file, escaped_utf8uri);
1429 #warning FIXME_GTK2 /* should we use g_filename_from_utf8()? */
1431 * g_filename_from_uri() rejects escaped/locale encoded uri
1432 * string which come from Nautilus.
1434 if (g_utf8_validate(file, -1, NULL))
1436 = conv_codeset_strdup(
1439 conv_get_current_charset_str());
1441 locale_file = g_strdup(file + 5);
1442 result = g_list_append(result, locale_file);
1446 p = strchr(p, '\n');
1453 #define HEX_TO_INT(val, hex) \
1457 if ('0' <= c && c <= '9') { \
1459 } else if ('a' <= c && c <= 'f') { \
1460 val = c - 'a' + 10; \
1461 } else if ('A' <= c && c <= 'F') { \
1462 val = c - 'A' + 10; \
1468 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1471 static gint axtoi(const gchar *hexstr)
1473 gint hi, lo, result;
1476 if ('0' <= hi && hi <= '9') {
1479 if ('a' <= hi && hi <= 'f') {
1482 if ('A' <= hi && hi <= 'F') {
1487 if ('0' <= lo && lo <= '9') {
1490 if ('a' <= lo && lo <= 'f') {
1493 if ('A' <= lo && lo <= 'F') {
1496 result = lo + (16 * hi);
1500 gboolean is_uri_string(const gchar *str)
1502 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1503 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1504 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1505 g_ascii_strncasecmp(str, "www.", 4) == 0);
1508 gchar *get_uri_path(const gchar *uri)
1510 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1511 return (gchar *)(uri + 7);
1512 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1513 return (gchar *)(uri + 8);
1514 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1515 return (gchar *)(uri + 6);
1517 return (gchar *)uri;
1520 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1521 * plusses, and escape characters are used)
1523 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1525 gchar *dec = decoded_uri;
1526 const gchar *enc = encoded_uri;
1531 if (isxdigit((guchar)enc[0]) &&
1532 isxdigit((guchar)enc[1])) {
1550 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1551 gchar **subject, gchar **body)
1556 Xstrdup_a(tmp_mailto, mailto, return -1);
1558 if (!strncmp(tmp_mailto, "mailto:", 7))
1561 p = strchr(tmp_mailto, '?');
1568 *to = g_strdup(tmp_mailto);
1571 gchar *field, *value;
1588 if (*value == '\0') continue;
1590 if (cc && !*cc && !g_ascii_strcasecmp(field, "cc")) {
1591 *cc = g_strdup(value);
1592 } else if (bcc && !*bcc && !g_ascii_strcasecmp(field, "bcc")) {
1593 *bcc = g_strdup(value);
1594 } else if (subject && !*subject &&
1595 !g_ascii_strcasecmp(field, "subject")) {
1596 *subject = g_malloc(strlen(value) + 1);
1597 decode_uri(*subject, value);
1598 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1599 *body = g_malloc(strlen(value) + 1);
1600 decode_uri(*body, value);
1608 * We need this wrapper around g_get_home_dir(), so that
1609 * we can fix some Windoze things here. Should be done in glibc of course
1610 * but as long as we are not able to do our own extensions to glibc, we do
1613 const gchar *get_home_dir(void)
1615 #if HAVE_DOSISH_SYSTEM
1616 static gchar *home_dir;
1619 home_dir = read_w32_registry_string(NULL,
1620 "Software\\Sylpheed", "HomeDir" );
1621 if (!home_dir || !*home_dir) {
1622 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1623 const char *s = g_get_home_dir();
1625 home_dir = g_strdup (s);
1627 if (!home_dir || !*home_dir)
1628 home_dir = g_strdup ("c:\\sylpheed");
1630 debug_print("initialized home_dir to `%s'\n", home_dir);
1633 #else /* standard glib */
1634 return g_get_home_dir();
1638 const gchar *get_rc_dir(void)
1640 static gchar *rc_dir = NULL;
1643 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1649 const gchar *get_news_cache_dir(void)
1651 static gchar *news_cache_dir = NULL;
1653 if (!news_cache_dir)
1654 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1655 NEWS_CACHE_DIR, NULL);
1657 return news_cache_dir;
1660 const gchar *get_imap_cache_dir(void)
1662 static gchar *imap_cache_dir = NULL;
1664 if (!imap_cache_dir)
1665 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1666 IMAP_CACHE_DIR, NULL);
1668 return imap_cache_dir;
1671 const gchar *get_mbox_cache_dir(void)
1673 static gchar *mbox_cache_dir = NULL;
1675 if (!mbox_cache_dir)
1676 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1677 MBOX_CACHE_DIR, NULL);
1679 return mbox_cache_dir;
1682 const gchar *get_mime_tmp_dir(void)
1684 static gchar *mime_tmp_dir = NULL;
1687 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1688 MIME_TMP_DIR, NULL);
1690 return mime_tmp_dir;
1693 const gchar *get_template_dir(void)
1695 static gchar *template_dir = NULL;
1698 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1699 TEMPLATE_DIR, NULL);
1701 return template_dir;
1704 const gchar *get_header_cache_dir(void)
1706 static gchar *header_dir = NULL;
1709 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1710 HEADER_CACHE_DIR, NULL);
1715 const gchar *get_tmp_dir(void)
1717 static gchar *tmp_dir = NULL;
1720 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1726 gchar *get_tmp_file(void)
1729 static guint32 id = 0;
1731 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1732 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1737 const gchar *get_domain_name(void)
1739 static gchar *domain_name = NULL;
1745 if (uname(&uts) < 0) {
1746 perror("gethostname");
1747 domain_name = "unknown";
1749 if ((hp = my_gethostbyname(uts.nodename)) == NULL) {
1750 perror("gethostbyname");
1751 domain_name = g_strdup(uts.nodename);
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_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2491 gint bytes_left, to_read;
2494 if (fseek(fp, offset, SEEK_SET) < 0) {
2499 bytes_left = length;
2500 to_read = MIN(bytes_left, sizeof(buf));
2502 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2503 if (n_read < to_read && ferror(fp))
2505 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2508 bytes_left -= n_read;
2509 if (bytes_left == 0)
2511 to_read = MIN(bytes_left, sizeof(buf));
2522 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2525 gboolean err = FALSE;
2527 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2528 FILE_OP_ERROR(dest, "fopen");
2532 if (change_file_mode_rw(dest_fp, dest) < 0) {
2533 FILE_OP_ERROR(dest, "chmod");
2534 g_warning("can't change file mode\n");
2537 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2540 if (!err && fclose(dest_fp) == EOF) {
2541 FILE_OP_ERROR(dest, "fclose");
2546 g_warning("writing to %s failed.\n", dest);
2554 /* convert line endings into CRLF. If the last line doesn't end with
2555 * linebreak, add it.
2557 gchar *canonicalize_str(const gchar *str)
2563 for (p = str; *p != '\0'; ++p) {
2570 if (p == str || *(p - 1) != '\n')
2573 out = outp = g_malloc(new_len + 1);
2574 for (p = str; *p != '\0'; ++p) {
2581 if (p == str || *(p - 1) != '\n') {
2590 gint canonicalize_file(const gchar *src, const gchar *dest)
2592 FILE *src_fp, *dest_fp;
2593 gchar buf[BUFFSIZE];
2595 gboolean err = FALSE;
2596 gboolean last_linebreak = FALSE;
2598 if ((src_fp = fopen(src, "rb")) == NULL) {
2599 FILE_OP_ERROR(src, "fopen");
2603 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2604 FILE_OP_ERROR(dest, "fopen");
2609 if (change_file_mode_rw(dest_fp, dest) < 0) {
2610 FILE_OP_ERROR(dest, "chmod");
2611 g_warning("can't change file mode\n");
2614 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2618 if (len == 0) break;
2619 last_linebreak = FALSE;
2621 if (buf[len - 1] != '\n') {
2622 last_linebreak = TRUE;
2623 r = fputs(buf, dest_fp);
2624 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2625 r = fputs(buf, dest_fp);
2628 r = fwrite(buf, len - 1, 1, dest_fp);
2633 r = fputs("\r\n", dest_fp);
2637 g_warning("writing to %s failed.\n", dest);
2645 if (last_linebreak == TRUE) {
2646 if (fputs("\r\n", dest_fp) == EOF)
2650 if (ferror(src_fp)) {
2651 FILE_OP_ERROR(src, "fgets");
2655 if (fclose(dest_fp) == EOF) {
2656 FILE_OP_ERROR(dest, "fclose");
2668 gint canonicalize_file_replace(const gchar *file)
2672 tmp_file = get_tmp_file();
2674 if (canonicalize_file(file, tmp_file) < 0) {
2679 if (move_file(tmp_file, file, TRUE) < 0) {
2680 g_warning("can't replace %s .\n", file);
2690 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2692 FILE *src_fp, *dest_fp;
2693 gchar buf[BUFFSIZE];
2694 gboolean err = FALSE;
2696 if ((src_fp = fopen(src, "rb")) == NULL) {
2697 FILE_OP_ERROR(src, "fopen");
2701 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2702 FILE_OP_ERROR(dest, "fopen");
2707 if (change_file_mode_rw(dest_fp, dest) < 0) {
2708 FILE_OP_ERROR(dest, "chmod");
2709 g_warning("can't change file mode\n");
2712 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2714 if (fputs(buf, dest_fp) == EOF) {
2715 g_warning("writing to %s failed.\n", dest);
2723 if (ferror(src_fp)) {
2724 FILE_OP_ERROR(src, "fgets");
2728 if (fclose(dest_fp) == EOF) {
2729 FILE_OP_ERROR(dest, "fclose");
2741 gint uncanonicalize_file_replace(const gchar *file)
2745 tmp_file = get_tmp_file();
2747 if (uncanonicalize_file(file, tmp_file) < 0) {
2752 if (move_file(tmp_file, file, TRUE) < 0) {
2753 g_warning("can't replace %s .\n", file);
2763 gchar *normalize_newlines(const gchar *str)
2765 const gchar *p = str;
2768 out = outp = g_malloc(strlen(str) + 1);
2769 for (p = str; *p != '\0'; ++p) {
2771 if (*(p + 1) != '\n')
2782 gchar *get_outgoing_rfc2822_str(FILE *fp)
2784 gchar buf[BUFFSIZE];
2788 str = g_string_new(NULL);
2790 /* output header part */
2791 while (fgets(buf, sizeof(buf), fp) != NULL) {
2793 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2800 else if (next != ' ' && next != '\t') {
2804 if (fgets(buf, sizeof(buf), fp) == NULL)
2808 g_string_append(str, buf);
2809 g_string_append(str, "\r\n");
2815 /* output body part */
2816 while (fgets(buf, sizeof(buf), fp) != NULL) {
2819 g_string_append_c(str, '.');
2820 g_string_append(str, buf);
2821 g_string_append(str, "\r\n");
2825 g_string_free(str, FALSE);
2831 * Create a new boundary in a way that it is very unlikely that this
2832 * will occur in the following text. It would be easy to ensure
2833 * uniqueness if everything is either quoted-printable or base64
2834 * encoded (note that conversion is allowed), but because MIME bodies
2835 * may be nested, it may happen that the same boundary has already
2836 * been used. We avoid scanning the message for conflicts and hope the
2839 * boundary := 0*69<bchars> bcharsnospace
2840 * bchars := bcharsnospace / " "
2841 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2842 * "+" / "_" / "," / "-" / "." /
2843 * "/" / ":" / "=" / "?"
2845 * some special characters removed because of buggy MTAs
2848 gchar *generate_mime_boundary(const gchar *prefix)
2850 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2851 "abcdefghijklmnopqrstuvwxyz"
2860 /* We make the boundary depend on the pid, so that all running
2861 * processes generate different values even when they have been
2862 * started within the same second and srandom(time(NULL)) has been
2863 * used. I can't see whether this is really an advantage but it
2864 * doesn't do any harm.
2866 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2867 buf_uniq[i] = tbl[(rand() ^ pid) % (sizeof(tbl) - 1)];
2870 get_rfc822_date(buf_date, sizeof(buf_date));
2871 subst_char(buf_date, ' ', '_');
2872 subst_char(buf_date, ',', '_');
2873 subst_char(buf_date, ':', '_');
2875 return g_strdup_printf("%s=_%s_%s", prefix ? prefix : "Multipart",
2876 buf_date, buf_uniq);
2879 gint change_file_mode_rw(FILE *fp, const gchar *file)
2882 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2884 return chmod(file, S_IRUSR|S_IWUSR);
2888 FILE *my_tmpfile(void)
2891 const gchar suffix[] = ".XXXXXX";
2892 const gchar *tmpdir;
2894 const gchar *progname;
2900 tmpdir = get_tmp_dir();
2901 tmplen = strlen(tmpdir);
2902 progname = g_get_prgname();
2903 proglen = strlen(progname);
2904 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2907 memcpy(fname, tmpdir, tmplen);
2908 fname[tmplen] = G_DIR_SEPARATOR;
2909 memcpy(fname + tmplen + 1, progname, proglen);
2910 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2912 fd = mkstemp(fname);
2918 fp = fdopen(fd, "w+b");
2923 #endif /* HAVE_MKSTEMP */
2928 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2932 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2933 fd = mkstemp(*filename);
2935 return fdopen(fd, "w+");
2938 FILE *str_open_as_stream(const gchar *str)
2943 g_return_val_if_fail(str != NULL, NULL);
2947 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2952 if (len == 0) return fp;
2954 if (fwrite(str, len, 1, fp) != 1) {
2955 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2964 gint str_write_to_file(const gchar *str, const gchar *file)
2969 g_return_val_if_fail(str != NULL, -1);
2970 g_return_val_if_fail(file != NULL, -1);
2972 if ((fp = fopen(file, "wb")) == NULL) {
2973 FILE_OP_ERROR(file, "fopen");
2983 if (fwrite(str, len, 1, fp) != 1) {
2984 FILE_OP_ERROR(file, "fwrite");
2990 if (fclose(fp) == EOF) {
2991 FILE_OP_ERROR(file, "fclose");
2999 gchar *file_read_to_str(const gchar *file)
3004 g_return_val_if_fail(file != NULL, NULL);
3006 if ((fp = fopen(file, "rb")) == NULL) {
3007 FILE_OP_ERROR(file, "fopen");
3011 str = file_read_stream_to_str(fp);
3018 gchar *file_read_stream_to_str(FILE *fp)
3025 g_return_val_if_fail(fp != NULL, NULL);
3027 array = g_byte_array_new();
3029 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3030 if (n_read < sizeof(buf) && ferror(fp))
3032 g_byte_array_append(array, buf, n_read);
3036 FILE_OP_ERROR("file stream", "fread");
3037 g_byte_array_free(array, TRUE);
3042 g_byte_array_append(array, buf, 1);
3043 str = (gchar *)array->data;
3044 g_byte_array_free(array, FALSE);
3046 if (!g_utf8_validate(str, -1, NULL)) {
3047 const gchar *src_codeset, *dest_codeset;
3049 src_codeset = conv_get_current_charset_str();
3050 dest_codeset = CS_UTF_8;
3051 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3059 gint execute_async(gchar *const argv[])
3064 if ((pid = fork()) < 0) {
3069 if (pid == 0) { /* child process */
3072 if ((gch_pid = fork()) < 0) {
3077 if (gch_pid == 0) { /* grandchild process */
3078 execvp(argv[0], argv);
3087 waitpid(pid, &status, 0);
3089 if (WIFEXITED(status))
3090 return WEXITSTATUS(status);
3095 gint execute_sync(gchar *const argv[])
3100 if ((pid = fork()) < 0) {
3105 if (pid == 0) { /* child process */
3106 execvp(argv[0], argv);
3112 waitpid(pid, &status, 0);
3114 if (WIFEXITED(status))
3115 return WEXITSTATUS(status);
3120 gint execute_command_line(const gchar *cmdline, gboolean async)
3125 debug_print("executing: %s\n", cmdline);
3127 argv = strsplit_with_quote(cmdline, " ", 0);
3130 ret = execute_async(argv);
3132 ret = execute_sync(argv);
3139 gchar *get_command_output(const gchar *cmdline)
3141 gchar buf[BUFFSIZE];
3146 g_return_val_if_fail(cmdline != NULL, NULL);
3148 if ((fp = popen(cmdline, "r")) == NULL) {
3149 FILE_OP_ERROR(cmdline, "popen");
3153 str = g_string_new("");
3155 while (fgets(buf, sizeof(buf), fp) != NULL)
3156 g_string_append(str, buf);
3161 g_string_free(str, FALSE);
3163 if (!g_utf8_validate(ret, -1, NULL)) {
3164 const gchar *src_codeset, *dest_codeset;
3166 src_codeset = conv_get_current_charset_str();
3167 dest_codeset = CS_UTF_8;
3168 tmp = conv_codeset_strdup(ret, src_codeset, dest_codeset);
3176 static gint is_unchanged_uri_char(char c)
3188 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3194 for(i = 0; i < strlen(uri) ; i++) {
3195 if (is_unchanged_uri_char(uri[i])) {
3196 if (k + 2 >= bufsize)
3198 encoded_uri[k++] = uri[i];
3201 char * hexa = "0123456789ABCDEF";
3203 if (k + 4 >= bufsize)
3205 encoded_uri[k++] = '%';
3206 encoded_uri[k++] = hexa[uri[i] / 16];
3207 encoded_uri[k++] = hexa[uri[i] % 16];
3213 gint open_uri(const gchar *uri, const gchar *cmdline)
3215 gchar buf[BUFFSIZE];
3217 gchar encoded_uri[BUFFSIZE];
3219 g_return_val_if_fail(uri != NULL, -1);
3221 /* an option to choose whether to use encode_uri or not ? */
3222 encode_uri(encoded_uri, BUFFSIZE, uri);
3225 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3226 !strchr(p + 2, '%'))
3227 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3230 g_warning("Open URI command line is invalid "
3231 "(there must be only one '%%s'): %s",
3233 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3236 execute_command_line(buf, TRUE);
3241 time_t remote_tzoffset_sec(const gchar *zone)
3243 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3249 time_t remoteoffset;
3251 strncpy(zone3, zone, 3);
3255 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3256 (c == '+' || c == '-')) {
3257 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3259 remoteoffset = -remoteoffset;
3260 } else if (!strncmp(zone, "UT" , 2) ||
3261 !strncmp(zone, "GMT", 2)) {
3263 } else if (strlen(zone3) == 3) {
3264 for (p = ustzstr; *p != '\0'; p += 3) {
3265 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3266 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3267 remoteoffset = iustz * 3600;
3273 } else if (strlen(zone3) == 1) {
3275 case 'Z': remoteoffset = 0; break;
3276 case 'A': remoteoffset = -1; break;
3277 case 'B': remoteoffset = -2; break;
3278 case 'C': remoteoffset = -3; break;
3279 case 'D': remoteoffset = -4; break;
3280 case 'E': remoteoffset = -5; break;
3281 case 'F': remoteoffset = -6; break;
3282 case 'G': remoteoffset = -7; break;
3283 case 'H': remoteoffset = -8; break;
3284 case 'I': remoteoffset = -9; break;
3285 case 'K': remoteoffset = -10; break; /* J is not used */
3286 case 'L': remoteoffset = -11; break;
3287 case 'M': remoteoffset = -12; break;
3288 case 'N': remoteoffset = 1; break;
3289 case 'O': remoteoffset = 2; break;
3290 case 'P': remoteoffset = 3; break;
3291 case 'Q': remoteoffset = 4; break;
3292 case 'R': remoteoffset = 5; break;
3293 case 'S': remoteoffset = 6; break;
3294 case 'T': remoteoffset = 7; break;
3295 case 'U': remoteoffset = 8; break;
3296 case 'V': remoteoffset = 9; break;
3297 case 'W': remoteoffset = 10; break;
3298 case 'X': remoteoffset = 11; break;
3299 case 'Y': remoteoffset = 12; break;
3300 default: remoteoffset = 0; break;
3302 remoteoffset = remoteoffset * 3600;
3306 return remoteoffset;
3309 time_t tzoffset_sec(time_t *now)
3315 lt = localtime(now);
3317 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3319 if (lt->tm_year < gmt.tm_year)
3321 else if (lt->tm_year > gmt.tm_year)
3323 else if (lt->tm_yday < gmt.tm_yday)
3325 else if (lt->tm_yday > gmt.tm_yday)
3328 if (off >= 24 * 60) /* should be impossible */
3329 off = 23 * 60 + 59; /* if not, insert silly value */
3330 if (off <= -24 * 60)
3331 off = -(23 * 60 + 59);
3336 /* calculate timezone offset */
3337 gchar *tzoffset(time_t *now)
3339 static gchar offset_string[6];
3345 lt = localtime(now);
3347 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3349 if (lt->tm_year < gmt.tm_year)
3351 else if (lt->tm_year > gmt.tm_year)
3353 else if (lt->tm_yday < gmt.tm_yday)
3355 else if (lt->tm_yday > gmt.tm_yday)
3363 if (off >= 24 * 60) /* should be impossible */
3364 off = 23 * 60 + 59; /* if not, insert silly value */
3366 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3368 return offset_string;
3371 void get_rfc822_date(gchar *buf, gint len)
3375 gchar day[4], mon[4];
3376 gint dd, hh, mm, ss, yyyy;
3381 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3382 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3383 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3384 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3387 void debug_set_mode(gboolean mode)
3392 gboolean debug_get_mode(void)
3397 void debug_print_real(const gchar *format, ...)
3400 gchar buf[BUFFSIZE];
3402 if (!debug_mode) return;
3404 va_start(args, format);
3405 g_vsnprintf(buf, sizeof(buf), format, args);
3411 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3413 if (subject == NULL)
3416 subject += subject_get_prefix_length(subject);
3418 return g_hash_table_lookup(subject_table, subject);
3421 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3424 if (subject == NULL || *subject == 0)
3426 subject += subject_get_prefix_length(subject);
3427 g_hash_table_insert(subject_table, subject, data);
3430 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3432 if (subject == NULL)
3435 subject += subject_get_prefix_length(subject);
3436 g_hash_table_remove(subject_table, subject);
3440 *\brief Check if a string is prefixed with known (combinations)
3441 * of prefixes. The function assumes that each prefix
3442 * is terminated by zero or exactly _one_ space.
3444 *\param str String to check for a prefixes
3446 *\return int Number of chars in the prefix that should be skipped
3447 * for a "clean" subject line. If no prefix was found, 0
3450 int subject_get_prefix_length(const gchar *subject)
3452 /*!< Array with allowable reply prefixes regexps. */
3453 static const gchar * const prefixes[] = {
3454 "Re\\:", /* "Re:" */
3455 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3456 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3457 "Aw\\:", /* "Aw:" (German) */
3458 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3459 "Res\\:", /* "Res:" (Brazilian Outlook) */
3460 "Fw\\:", /* "Fw:" Forward */
3461 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3462 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3463 "Rif\\:" /* "Rif:" (Italian Outlook) */
3466 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3469 static regex_t regex;
3470 static gboolean init_;
3472 if (!subject) return 0;
3473 if (!*subject) return 0;
3476 GString *s = g_string_new("");
3478 for (n = 0; n < PREFIXES; n++)
3479 /* Terminate each prefix regexpression by a
3480 * "\ ?" (zero or ONE space), and OR them */
3481 g_string_append_printf(s, "(%s\\ ?)%s",
3486 g_string_prepend(s, "(");
3487 g_string_append(s, ")+"); /* match at least once */
3488 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3491 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3492 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3493 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3494 debug_print("Error compiling regexp %s\n", s->str);
3495 g_string_free(s, TRUE);
3499 g_string_free(s, TRUE);
3503 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3509 guint g_stricase_hash(gconstpointer gptr)
3511 guint hash_result = 0;
3514 for (str = gptr; str && *str; str++) {
3515 if (isupper((guchar)*str)) hash_result += (*str + ' ');
3516 else hash_result += *str;
3522 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3524 const char *str1 = gptr1;
3525 const char *str2 = gptr2;
3527 return !g_utf8_collate(str1, str2);
3530 gint g_int_compare(gconstpointer a, gconstpointer b)
3532 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3535 gchar *generate_msgid(const gchar *address, gchar *buf, gint len)
3544 if (address && *address) {
3545 if (strchr(address, '@'))
3546 addr = g_strdup(address);
3548 addr = g_strconcat(address, "@", get_domain_name(), NULL);
3550 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3553 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3554 lt->tm_year + 1900, lt->tm_mon + 1,
3555 lt->tm_mday, lt->tm_hour,
3556 lt->tm_min, lt->tm_sec,
3557 (guint) rand(), addr);
3565 quote_cmd_argument()
3567 return a quoted string safely usable in argument of a command.
3569 code is extracted and adapted from etPan! project -- DINH V. HoĆ .
3572 gint quote_cmd_argument(gchar * result, guint size,
3582 for(p = path ; * p != '\0' ; p ++) {
3584 if (isalnum((guchar)*p) || (* p == '/')) {
3585 if (remaining > 0) {
3591 result[size - 1] = '\0';
3596 if (remaining >= 2) {
3604 result[size - 1] = '\0';
3609 if (remaining > 0) {
3613 result[size - 1] = '\0';
3627 static void g_node_map_recursive(GNode *node, gpointer data)
3629 GNodeMapData *mapdata = (GNodeMapData *) data;
3631 GNodeMapData newmapdata;
3634 newdata = mapdata->func(node->data, mapdata->data);
3635 if (newdata != NULL) {
3636 newnode = g_node_new(newdata);
3637 g_node_append(mapdata->parent, newnode);
3639 newmapdata.parent = newnode;
3640 newmapdata.func = mapdata->func;
3641 newmapdata.data = mapdata->data;
3643 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3647 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3650 GNodeMapData mapdata;
3652 g_return_val_if_fail(node != NULL, NULL);
3653 g_return_val_if_fail(func != NULL, NULL);
3655 root = g_node_new(func(node->data, data));
3657 mapdata.parent = root;
3658 mapdata.func = func;
3659 mapdata.data = data;
3661 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);