2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2003 Hiroyuki Yamamoto
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
40 #include <sys/types.h>
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 gchar *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 gchar *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 gchar *srcp, *destp;
607 destp = str + subject_get_prefix_length(str);
612 } else if (*destp == '(') {
623 else if (*srcp == cl)
629 while (isspace(*srcp)) srcp++;
630 memmove(destp, srcp, strlen(srcp) + 1);
633 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
635 register gchar *srcp, *destp;
640 while ((destp = strchr(destp, op))) {
646 else if (*srcp == cl)
652 while (isspace(*srcp)) srcp++;
653 memmove(destp, srcp, strlen(srcp) + 1);
657 void extract_parenthesis(gchar *str, gchar op, gchar cl)
659 register gchar *srcp, *destp;
664 while ((srcp = strchr(destp, op))) {
667 memmove(destp, srcp + 1, strlen(srcp));
672 else if (*destp == cl)
684 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
687 register gchar *srcp, *destp;
689 gboolean in_quote = FALSE;
693 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
696 memmove(destp, srcp + 1, strlen(srcp));
699 if (*destp == op && !in_quote)
701 else if (*destp == cl && !in_quote)
703 else if (*destp == quote_chr)
715 void eliminate_quote(gchar *str, gchar quote_chr)
717 register gchar *srcp, *destp;
721 while ((destp = strchr(destp, quote_chr))) {
722 if ((srcp = strchr(destp + 1, quote_chr))) {
724 while (isspace(*srcp)) srcp++;
725 memmove(destp, srcp, strlen(srcp) + 1);
733 void extract_quote(gchar *str, gchar quote_chr)
737 if ((str = strchr(str, quote_chr))) {
739 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
740 memmove(p - 1, p, strlen(p) + 1);
745 memmove(str, str + 1, p - str);
750 void eliminate_address_comment(gchar *str)
752 register gchar *srcp, *destp;
757 while ((destp = strchr(destp, '"'))) {
758 if ((srcp = strchr(destp + 1, '"'))) {
763 while (isspace(*srcp)) srcp++;
764 memmove(destp, srcp, strlen(srcp) + 1);
774 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
780 else if (*srcp == ')')
786 while (isspace(*srcp)) srcp++;
787 memmove(destp, srcp, strlen(srcp) + 1);
791 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
793 gboolean in_quote = FALSE;
796 if (*str == c && !in_quote)
798 if (*str == quote_chr)
806 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
808 gboolean in_quote = FALSE;
811 p = str + strlen(str) - 1;
813 if (*p == c && !in_quote)
823 void extract_address(gchar *str)
825 eliminate_address_comment(str);
826 if (strchr_with_skip_quote(str, '"', '<'))
827 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
831 void extract_list_id_str(gchar *str)
833 if (strchr_with_skip_quote(str, '"', '<'))
834 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
838 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
843 if (!str) return addr_list;
845 Xstrdup_a(work, str, return addr_list);
848 eliminate_address_comment(work);
851 while (workp && *workp) {
854 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
860 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
861 extract_parenthesis_with_skip_quote
862 (workp, '"', '<', '>');
866 addr_list = g_slist_append(addr_list, g_strdup(workp));
874 GSList *address_list_append(GSList *addr_list, const gchar *str)
876 return address_list_append_real(addr_list, str, TRUE);
879 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
881 return address_list_append_real(addr_list, str, FALSE);
884 GSList *references_list_append(GSList *msgid_list, const gchar *str)
888 if (!str) return msgid_list;
891 while (strp && *strp) {
892 const gchar *start, *end;
895 if ((start = strchr(strp, '<')) != NULL) {
896 end = strchr(start + 1, '>');
901 msgid = g_strndup(start + 1, end - start - 1);
904 msgid_list = g_slist_append(msgid_list, msgid);
914 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
919 if (!str) return group_list;
921 Xstrdup_a(work, str, return group_list);
925 while (workp && *workp) {
928 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
936 group_list = g_slist_append(group_list,
945 GList *add_history(GList *list, const gchar *str)
949 g_return_val_if_fail(str != NULL, list);
951 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
954 list = g_list_remove(list, old->data);
955 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
958 last = g_list_last(list);
961 g_list_remove(list, last->data);
965 list = g_list_prepend(list, g_strdup(str));
970 void remove_return(gchar *str)
972 register gchar *p = str;
975 if (*p == '\n' || *p == '\r')
976 memmove(p, p + 1, strlen(p));
982 void remove_space(gchar *str)
984 register gchar *p = str;
989 while (isspace(*(p + spc)))
992 memmove(p, p + spc, strlen(p + spc) + 1);
998 void unfold_line(gchar *str)
1000 register gchar *p = str;
1004 if (*p == '\n' || *p == '\r') {
1007 while (isspace(*(p + spc)))
1010 memmove(p, p + spc, strlen(p + spc) + 1);
1016 void subst_char(gchar *str, gchar orig, gchar subst)
1018 register gchar *p = str;
1027 void subst_chars(gchar *str, gchar *orig, gchar subst)
1029 register gchar *p = str;
1032 if (strchr(orig, *p) != NULL)
1038 void subst_for_filename(gchar *str)
1040 subst_chars(str, " \t\r\n\"/\\", '_');
1043 gboolean is_header_line(const gchar *str)
1045 if (str[0] == ':') return FALSE;
1047 while (*str != '\0' && *str != ' ') {
1056 gboolean is_ascii_str(const guchar *str)
1058 g_return_val_if_fail(str, FALSE);
1060 while (*str != '\0') {
1061 if (*str != '\t' && *str != ' ' &&
1062 *str != '\r' && *str != '\n' &&
1063 (*str < 32 || *str >= 127))
1071 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1073 const gchar *first_pos;
1074 const gchar *last_pos;
1075 const gchar *p = str;
1076 gint quote_level = -1;
1078 /* speed up line processing by only searching to the last '>' */
1079 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1080 /* skip a line if it contains a '<' before the initial '>' */
1081 if (memchr(str, '<', first_pos - str) != NULL)
1083 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1087 while (p <= last_pos) {
1088 while (p < last_pos) {
1095 if (strchr(quote_chars, *p))
1097 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1098 /* any characters are allowed except '-' and space */
1100 && !strchr(quote_chars, *p)
1104 if (strchr(quote_chars, *p))
1116 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1118 gchar * position = NULL;
1119 gchar * tmp_pos = NULL;
1122 if (quote_chars == NULL)
1125 for (i = 0; i < strlen(quote_chars); i++) {
1126 tmp_pos = strchr (str, quote_chars[i]);
1128 || (tmp_pos != NULL && position >= tmp_pos) )
1134 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1136 gchar * position = NULL;
1137 gchar * tmp_pos = NULL;
1140 if (quote_chars == NULL)
1143 for (i = 0; i < strlen(quote_chars); i++) {
1144 tmp_pos = strrchr (str, quote_chars[i]);
1146 || (tmp_pos != NULL && position <= tmp_pos) )
1152 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1154 register guint haystack_len, needle_len;
1155 gboolean in_squote = FALSE, in_dquote = FALSE;
1157 haystack_len = strlen(haystack);
1158 needle_len = strlen(needle);
1160 if (haystack_len < needle_len || needle_len == 0)
1163 while (haystack_len >= needle_len) {
1164 if (!in_squote && !in_dquote &&
1165 !strncmp(haystack, needle, needle_len))
1166 return (gchar *)haystack;
1168 /* 'foo"bar"' -> foo"bar"
1169 "foo'bar'" -> foo'bar' */
1170 if (*haystack == '\'') {
1173 else if (!in_dquote)
1175 } else if (*haystack == '\"') {
1178 else if (!in_squote)
1189 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1192 gchar quote_chr = '"';
1194 gboolean in_quote = FALSE;
1198 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1202 if (*p == op && !in_quote)
1204 else if (*p == cl && !in_quote)
1206 else if (*p == quote_chr)
1219 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1222 GSList *string_list = NULL, *slist;
1224 const gchar *s_op, *s_cl;
1227 g_return_val_if_fail(str != NULL, NULL);
1230 max_tokens = G_MAXINT;
1232 s_op = strchr_with_skip_quote(str, '"', op);
1233 if (!s_op) return NULL;
1235 s_cl = strchr_parenthesis_close(str, op, cl);
1243 new_string = g_new(gchar, len + 1);
1244 strncpy(new_string, str, len);
1245 new_string[len] = 0;
1246 string_list = g_slist_prepend(string_list, new_string);
1250 while (*str && isspace(*str)) str++;
1252 string_list = g_slist_prepend(string_list,
1255 s_op = strchr_with_skip_quote(str, '"', op);
1256 if (!--max_tokens || !s_op) break;
1260 s_cl = strchr_parenthesis_close(str, op, cl);
1261 } while (--max_tokens && s_cl);
1264 str_array = g_new(gchar*, n);
1268 str_array[i--] = NULL;
1269 for (slist = string_list; slist; slist = slist->next)
1270 str_array[i--] = slist->data;
1272 g_slist_free(string_list);
1277 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1280 GSList *string_list = NULL, *slist;
1281 gchar **str_array, *s, *new_str;
1282 guint i, n = 1, len;
1284 g_return_val_if_fail(str != NULL, NULL);
1285 g_return_val_if_fail(delim != NULL, NULL);
1288 max_tokens = G_MAXINT;
1290 s = strstr_with_skip_quote(str, delim);
1292 guint delimiter_len = strlen(delim);
1296 new_str = g_strndup(str, len);
1298 if (new_str[0] == '\'' || new_str[0] == '\"') {
1299 if (new_str[len - 1] == new_str[0]) {
1300 new_str[len - 1] = '\0';
1301 memmove(new_str, new_str + 1, len - 1);
1304 string_list = g_slist_prepend(string_list, new_str);
1306 str = s + delimiter_len;
1307 s = strstr_with_skip_quote(str, delim);
1308 } while (--max_tokens && s);
1312 new_str = g_strdup(str);
1313 if (new_str[0] == '\'' || new_str[0] == '\"') {
1315 if (new_str[len - 1] == new_str[0]) {
1316 new_str[len - 1] = '\0';
1317 memmove(new_str, new_str + 1, len - 1);
1320 string_list = g_slist_prepend(string_list, new_str);
1324 str_array = g_new(gchar*, n);
1328 str_array[i--] = NULL;
1329 for (slist = string_list; slist; slist = slist->next)
1330 str_array[i--] = slist->data;
1332 g_slist_free(string_list);
1337 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1339 gchar *abbrev_group;
1341 const gchar *p = group;
1344 g_return_val_if_fail(group != NULL, NULL);
1346 last = group + strlen(group);
1347 abbrev_group = ap = g_malloc(strlen(group) + 1);
1352 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1354 while (*p != '.') p++;
1357 return abbrev_group;
1362 return abbrev_group;
1365 gchar *trim_string(const gchar *str, gint len)
1367 const gchar *p = str;
1372 if (!str) return NULL;
1373 if (strlen(str) <= len)
1374 return g_strdup(str);
1376 while (*p != '\0') {
1377 mb_len = mblen(p, MB_LEN_MAX);
1380 else if (mb_len < 0)
1381 return g_strdup(str);
1382 else if (new_len + mb_len > len)
1389 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1390 return g_strconcat(new_str, "...", NULL);
1393 GList *uri_list_extract_filenames(const gchar *uri_list)
1395 GList *result = NULL;
1397 gchar *escaped_utf8uri;
1403 while (isspace(*p)) p++;
1404 if (!strncmp(p, "file:", 5)) {
1407 while (*q && *q != '\n' && *q != '\r') q++;
1410 gchar *file, *locale_file = NULL;
1412 while (q > p && isspace(*q)) q--;
1413 Xalloca(escaped_utf8uri, q - p + 2,
1415 Xalloca(file, q - p + 2,
1418 strncpy(escaped_utf8uri, p, q - p + 1);
1419 escaped_utf8uri[q - p + 1] = '\0';
1420 decode_uri(file, escaped_utf8uri);
1421 #warning FIXME_GTK2 /* should we use g_filename_from_utf8()? */
1423 * g_filename_from_uri() rejects escaped/locale encoded uri
1424 * string which come from Nautilus.
1426 if (g_utf8_validate(file, -1, NULL))
1428 = conv_codeset_strdup(
1431 conv_get_current_charset_str());
1433 locale_file = g_strdup(file + 5);
1434 result = g_list_append(result, locale_file);
1438 p = strchr(p, '\n');
1445 #define HEX_TO_INT(val, hex) \
1449 if ('0' <= c && c <= '9') { \
1451 } else if ('a' <= c && c <= 'f') { \
1452 val = c - 'a' + 10; \
1453 } else if ('A' <= c && c <= 'F') { \
1454 val = c - 'A' + 10; \
1460 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1461 gchar **subject, gchar **body)
1466 Xstrdup_a(tmp_mailto, mailto, return -1);
1468 if (!strncmp(tmp_mailto, "mailto:", 7))
1471 p = strchr(tmp_mailto, '?');
1478 *to = g_strdup(tmp_mailto);
1481 gchar *field, *value;
1498 if (*value == '\0') continue;
1500 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1501 *cc = g_strdup(value);
1502 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1503 *bcc = g_strdup(value);
1504 } else if (subject && !*subject &&
1505 !g_strcasecmp(field, "subject")) {
1506 *subject = g_malloc(strlen(value) + 1);
1507 decode_uri(*subject, value);
1508 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1509 *body = g_malloc(strlen(value) + 1);
1510 decode_uri(*body, value);
1518 * We need this wrapper around g_get_home_dir(), so that
1519 * we can fix some Windoze things here. Should be done in glibc of course
1520 * but as long as we are not able to do our own extensions to glibc, we do
1523 const gchar *get_home_dir(void)
1525 #if HAVE_DOSISH_SYSTEM
1526 static gchar *home_dir;
1529 home_dir = read_w32_registry_string(NULL,
1530 "Software\\Sylpheed", "HomeDir" );
1531 if (!home_dir || !*home_dir) {
1532 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1533 const char *s = g_get_home_dir();
1535 home_dir = g_strdup (s);
1537 if (!home_dir || !*home_dir)
1538 home_dir = g_strdup ("c:\\sylpheed");
1540 debug_print("initialized home_dir to `%s'\n", home_dir);
1543 #else /* standard glib */
1544 return g_get_home_dir();
1548 const gchar *get_rc_dir(void)
1550 static gchar *rc_dir = NULL;
1553 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1559 const gchar *get_news_cache_dir(void)
1561 static gchar *news_cache_dir = NULL;
1563 if (!news_cache_dir)
1564 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1565 NEWS_CACHE_DIR, NULL);
1567 return news_cache_dir;
1570 const gchar *get_imap_cache_dir(void)
1572 static gchar *imap_cache_dir = NULL;
1574 if (!imap_cache_dir)
1575 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1576 IMAP_CACHE_DIR, NULL);
1578 return imap_cache_dir;
1581 const gchar *get_mbox_cache_dir(void)
1583 static gchar *mbox_cache_dir = NULL;
1585 if (!mbox_cache_dir)
1586 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1587 MBOX_CACHE_DIR, NULL);
1589 return mbox_cache_dir;
1592 const gchar *get_mime_tmp_dir(void)
1594 static gchar *mime_tmp_dir = NULL;
1597 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1598 MIME_TMP_DIR, NULL);
1600 return mime_tmp_dir;
1603 const gchar *get_template_dir(void)
1605 static gchar *template_dir = NULL;
1608 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1609 TEMPLATE_DIR, NULL);
1611 return template_dir;
1614 const gchar *get_header_cache_dir(void)
1616 static gchar *header_dir = NULL;
1619 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1620 HEADER_CACHE_DIR, NULL);
1625 const gchar *get_tmp_dir(void)
1627 static gchar *tmp_dir = NULL;
1630 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1636 gchar *get_tmp_file(void)
1639 static guint32 id = 0;
1641 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1642 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1647 const gchar *get_domain_name(void)
1649 static gchar *domain_name = NULL;
1652 gchar buf[128] = "";
1655 if (gethostname(buf, sizeof(buf)) < 0) {
1656 perror("gethostname");
1657 domain_name = "unknown";
1659 buf[sizeof(buf) - 1] = '\0';
1660 if ((hp = my_gethostbyname(buf)) == NULL) {
1661 perror("gethostbyname");
1662 domain_name = g_strdup(buf);
1664 domain_name = g_strdup(hp->h_name);
1668 debug_print("domain name = %s\n", domain_name);
1674 off_t get_file_size(const gchar *file)
1678 if (stat(file, &s) < 0) {
1679 FILE_OP_ERROR(file, "stat");
1686 off_t get_file_size_as_crlf(const gchar *file)
1690 gchar buf[BUFFSIZE];
1692 if ((fp = fopen(file, "rb")) == NULL) {
1693 FILE_OP_ERROR(file, "fopen");
1697 while (fgets(buf, sizeof(buf), fp) != NULL) {
1699 size += strlen(buf) + 2;
1703 FILE_OP_ERROR(file, "fgets");
1712 off_t get_left_file_size(FILE *fp)
1718 if ((pos = ftell(fp)) < 0) {
1722 if (fseek(fp, 0L, SEEK_END) < 0) {
1726 if ((end = ftell(fp)) < 0) {
1731 if (fseek(fp, pos, SEEK_SET) < 0) {
1739 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1746 if (stat(file, &s) < 0) {
1747 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1751 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1757 gboolean is_dir_exist(const gchar *dir)
1764 if (stat(dir, &s) < 0) {
1765 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1769 if (S_ISDIR(s.st_mode))
1775 gboolean is_file_entry_exist(const gchar *file)
1782 if (stat(file, &s) < 0) {
1783 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1790 gint change_dir(const gchar *dir)
1792 gchar *prevdir = NULL;
1795 prevdir = g_get_current_dir();
1797 if (chdir(dir) < 0) {
1798 FILE_OP_ERROR(dir, "chdir");
1799 if (debug_mode) g_free(prevdir);
1801 } else if (debug_mode) {
1804 cwd = g_get_current_dir();
1805 if (strcmp(prevdir, cwd) != 0)
1806 g_print("current dir: %s\n", cwd);
1814 gint make_dir(const gchar *dir)
1816 if (mkdir(dir, S_IRWXU) < 0) {
1817 FILE_OP_ERROR(dir, "mkdir");
1820 if (chmod(dir, S_IRWXU) < 0)
1821 FILE_OP_ERROR(dir, "chmod");
1826 gint make_dir_hier(const gchar *dir)
1831 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1832 parent_dir = g_strndup(dir, p - dir);
1833 if (*parent_dir != '\0') {
1834 if (!is_dir_exist(parent_dir)) {
1835 if (make_dir(parent_dir) < 0) {
1844 if (!is_dir_exist(dir)) {
1845 if (make_dir(dir) < 0)
1852 gint remove_all_files(const gchar *dir)
1858 prev_dir = g_get_current_dir();
1860 if (chdir(dir) < 0) {
1861 FILE_OP_ERROR(dir, "chdir");
1866 if ((dp = opendir(".")) == NULL) {
1867 FILE_OP_ERROR(dir, "opendir");
1872 while ((d = readdir(dp)) != NULL) {
1873 if (!strcmp(d->d_name, ".") ||
1874 !strcmp(d->d_name, ".."))
1877 if (unlink(d->d_name) < 0)
1878 FILE_OP_ERROR(d->d_name, "unlink");
1883 if (chdir(prev_dir) < 0) {
1884 FILE_OP_ERROR(prev_dir, "chdir");
1894 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1901 prev_dir = g_get_current_dir();
1903 if (chdir(dir) < 0) {
1904 FILE_OP_ERROR(dir, "chdir");
1909 if ((dp = opendir(".")) == NULL) {
1910 FILE_OP_ERROR(dir, "opendir");
1915 while ((d = readdir(dp)) != NULL) {
1916 fileno = to_number(d->d_name);
1917 if (fileno >= 0 && first <= fileno && fileno <= last) {
1918 if (is_dir_exist(d->d_name))
1920 if (unlink(d->d_name) < 0)
1921 FILE_OP_ERROR(d->d_name, "unlink");
1927 if (chdir(prev_dir) < 0) {
1928 FILE_OP_ERROR(prev_dir, "chdir");
1938 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1945 prev_dir = g_get_current_dir();
1947 if (chdir(dir) < 0) {
1948 FILE_OP_ERROR(dir, "chdir");
1953 if ((dp = opendir(".")) == NULL) {
1954 FILE_OP_ERROR(dir, "opendir");
1959 while ((d = readdir(dp)) != NULL) {
1960 fileno = to_number(d->d_name);
1961 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1962 debug_print("removing unwanted file %d from %s\n", fileno, dir);
1963 if (is_dir_exist(d->d_name))
1965 if (unlink(d->d_name) < 0)
1966 FILE_OP_ERROR(d->d_name, "unlink");
1972 if (chdir(prev_dir) < 0) {
1973 FILE_OP_ERROR(prev_dir, "chdir");
1983 gint remove_all_numbered_files(const gchar *dir)
1985 return remove_numbered_files(dir, 0, UINT_MAX);
1988 gint remove_expired_files(const gchar *dir, guint hours)
1995 time_t mtime, now, expire_time;
1997 prev_dir = g_get_current_dir();
1999 if (chdir(dir) < 0) {
2000 FILE_OP_ERROR(dir, "chdir");
2005 if ((dp = opendir(".")) == NULL) {
2006 FILE_OP_ERROR(dir, "opendir");
2012 expire_time = hours * 60 * 60;
2014 while ((d = readdir(dp)) != NULL) {
2015 fileno = to_number(d->d_name);
2017 if (stat(d->d_name, &s) < 0) {
2018 FILE_OP_ERROR(d->d_name, "stat");
2021 if (S_ISDIR(s.st_mode))
2023 mtime = MAX(s.st_mtime, s.st_atime);
2024 if (now - mtime > expire_time) {
2025 if (unlink(d->d_name) < 0)
2026 FILE_OP_ERROR(d->d_name, "unlink");
2033 if (chdir(prev_dir) < 0) {
2034 FILE_OP_ERROR(prev_dir, "chdir");
2044 gint remove_dir_recursive(const gchar *dir)
2051 /* g_print("dir = %s\n", dir); */
2053 if (stat(dir, &s) < 0) {
2054 FILE_OP_ERROR(dir, "stat");
2055 if (ENOENT == errno) return 0;
2059 if (!S_ISDIR(s.st_mode)) {
2060 if (unlink(dir) < 0) {
2061 FILE_OP_ERROR(dir, "unlink");
2068 prev_dir = g_get_current_dir();
2069 /* g_print("prev_dir = %s\n", prev_dir); */
2071 if (!path_cmp(prev_dir, dir)) {
2073 if (chdir("..") < 0) {
2074 FILE_OP_ERROR(dir, "chdir");
2077 prev_dir = g_get_current_dir();
2080 if (chdir(dir) < 0) {
2081 FILE_OP_ERROR(dir, "chdir");
2086 if ((dp = opendir(".")) == NULL) {
2087 FILE_OP_ERROR(dir, "opendir");
2093 /* remove all files in the directory */
2094 while ((d = readdir(dp)) != NULL) {
2095 if (!strcmp(d->d_name, ".") ||
2096 !strcmp(d->d_name, ".."))
2099 if (stat(d->d_name, &s) < 0) {
2100 FILE_OP_ERROR(d->d_name, "stat");
2104 /* g_print("removing %s\n", d->d_name); */
2106 if (S_ISDIR(s.st_mode)) {
2107 if (remove_dir_recursive(d->d_name) < 0) {
2108 g_warning("can't remove directory\n");
2112 if (unlink(d->d_name) < 0)
2113 FILE_OP_ERROR(d->d_name, "unlink");
2119 if (chdir(prev_dir) < 0) {
2120 FILE_OP_ERROR(prev_dir, "chdir");
2127 if (rmdir(dir) < 0) {
2128 FILE_OP_ERROR(dir, "rmdir");
2136 /* this seems to be slower than the stdio version... */
2137 gint copy_file(const gchar *src, const gchar *dest)
2139 gint src_fd, dest_fd;
2143 gchar *dest_bak = NULL;
2145 if ((src_fd = open(src, O_RDONLY)) < 0) {
2146 FILE_OP_ERROR(src, "open");
2150 if (is_file_exist(dest)) {
2151 dest_bak = g_strconcat(dest, ".bak", NULL);
2152 if (rename(dest, dest_bak) < 0) {
2153 FILE_OP_ERROR(dest, "rename");
2160 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2161 FILE_OP_ERROR(dest, "open");
2164 if (rename(dest_bak, dest) < 0)
2165 FILE_OP_ERROR(dest_bak, "rename");
2171 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2176 n_write = write(dest_fd, bufp, len);
2178 g_warning("writing to %s failed.\n", dest);
2183 if (rename(dest_bak, dest) < 0)
2184 FILE_OP_ERROR(dest_bak, "rename");
2197 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2198 g_warning("File copy from %s to %s failed.\n", src, dest);
2201 if (rename(dest_bak, dest) < 0)
2202 FILE_OP_ERROR(dest_bak, "rename");
2215 * Append src file body to the tail of dest file.
2216 * Now keep_backup has no effects.
2218 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2220 FILE *src_fp, *dest_fp;
2224 gboolean err = FALSE;
2226 if ((src_fp = fopen(src, "rb")) == NULL) {
2227 FILE_OP_ERROR(src, "fopen");
2231 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2232 FILE_OP_ERROR(dest, "fopen");
2237 if (change_file_mode_rw(dest_fp, dest) < 0) {
2238 FILE_OP_ERROR(dest, "chmod");
2239 g_warning("can't change file mode\n");
2242 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2243 if (n_read < sizeof(buf) && ferror(src_fp))
2245 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2246 g_warning("writing to %s failed.\n", dest);
2254 if (ferror(src_fp)) {
2255 FILE_OP_ERROR(src, "fread");
2259 if (fclose(dest_fp) == EOF) {
2260 FILE_OP_ERROR(dest, "fclose");
2272 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2274 FILE *src_fp, *dest_fp;
2277 gchar *dest_bak = NULL;
2278 gboolean err = FALSE;
2280 if ((src_fp = fopen(src, "rb")) == NULL) {
2281 FILE_OP_ERROR(src, "fopen");
2284 if (is_file_exist(dest)) {
2285 dest_bak = g_strconcat(dest, ".bak", NULL);
2286 if (rename(dest, dest_bak) < 0) {
2287 FILE_OP_ERROR(dest, "rename");
2294 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2295 FILE_OP_ERROR(dest, "fopen");
2298 if (rename(dest_bak, dest) < 0)
2299 FILE_OP_ERROR(dest_bak, "rename");
2305 if (change_file_mode_rw(dest_fp, dest) < 0) {
2306 FILE_OP_ERROR(dest, "chmod");
2307 g_warning("can't change file mode\n");
2310 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2311 if (n_read < sizeof(buf) && ferror(src_fp))
2313 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2314 g_warning("writing to %s failed.\n", dest);
2319 if (rename(dest_bak, dest) < 0)
2320 FILE_OP_ERROR(dest_bak, "rename");
2327 if (ferror(src_fp)) {
2328 FILE_OP_ERROR(src, "fread");
2332 if (fclose(dest_fp) == EOF) {
2333 FILE_OP_ERROR(dest, "fclose");
2340 if (rename(dest_bak, dest) < 0)
2341 FILE_OP_ERROR(dest_bak, "rename");
2347 if (keep_backup == FALSE && dest_bak)
2355 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2357 if (overwrite == FALSE && is_file_exist(dest)) {
2358 g_warning("move_file(): file %s already exists.", dest);
2362 if (rename(src, dest) == 0) return 0;
2364 if (EXDEV != errno) {
2365 FILE_OP_ERROR(src, "rename");
2369 if (copy_file(src, dest, FALSE) < 0) return -1;
2376 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2380 gint bytes_left, to_read;
2382 gboolean err = FALSE;
2384 if (fseek(fp, offset, SEEK_SET) < 0) {
2389 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2390 FILE_OP_ERROR(dest, "fopen");
2394 if (change_file_mode_rw(dest_fp, dest) < 0) {
2395 FILE_OP_ERROR(dest, "chmod");
2396 g_warning("can't change file mode\n");
2399 bytes_left = length;
2400 to_read = MIN(bytes_left, sizeof(buf));
2402 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2403 if (n_read < to_read && ferror(fp))
2405 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2406 g_warning("writing to %s failed.\n", dest);
2411 bytes_left -= n_read;
2412 if (bytes_left == 0)
2414 to_read = MIN(bytes_left, sizeof(buf));
2421 if (fclose(dest_fp) == EOF) {
2422 FILE_OP_ERROR(dest, "fclose");
2434 /* convert line endings into CRLF. If the last line doesn't end with
2435 * linebreak, add it.
2437 gchar *canonicalize_str(const gchar *str)
2443 for (p = str; *p != '\0'; ++p) {
2450 if (p == str || *(p - 1) != '\n')
2453 out = outp = g_malloc(new_len + 1);
2454 for (p = str; *p != '\0'; ++p) {
2461 if (p == str || *(p - 1) != '\n') {
2470 gint canonicalize_file(const gchar *src, const gchar *dest)
2472 FILE *src_fp, *dest_fp;
2473 gchar buf[BUFFSIZE];
2475 gboolean err = FALSE;
2476 gboolean last_linebreak = FALSE;
2478 if ((src_fp = fopen(src, "rb")) == NULL) {
2479 FILE_OP_ERROR(src, "fopen");
2483 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2484 FILE_OP_ERROR(dest, "fopen");
2489 if (change_file_mode_rw(dest_fp, dest) < 0) {
2490 FILE_OP_ERROR(dest, "chmod");
2491 g_warning("can't change file mode\n");
2494 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2498 if (len == 0) break;
2499 last_linebreak = FALSE;
2501 if (buf[len - 1] != '\n') {
2502 last_linebreak = TRUE;
2503 r = fputs(buf, dest_fp);
2504 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2505 r = fputs(buf, dest_fp);
2508 r = fwrite(buf, len - 1, 1, dest_fp);
2513 r = fputs("\r\n", dest_fp);
2517 g_warning("writing to %s failed.\n", dest);
2525 if (last_linebreak == TRUE) {
2526 if (fputs("\r\n", dest_fp) == EOF)
2530 if (ferror(src_fp)) {
2531 FILE_OP_ERROR(src, "fgets");
2535 if (fclose(dest_fp) == EOF) {
2536 FILE_OP_ERROR(dest, "fclose");
2548 gint canonicalize_file_replace(const gchar *file)
2552 tmp_file = get_tmp_file();
2554 if (canonicalize_file(file, tmp_file) < 0) {
2559 if (move_file(tmp_file, file, TRUE) < 0) {
2560 g_warning("can't replace %s .\n", file);
2570 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2572 FILE *src_fp, *dest_fp;
2573 gchar buf[BUFFSIZE];
2574 gboolean err = FALSE;
2576 if ((src_fp = fopen(src, "rb")) == NULL) {
2577 FILE_OP_ERROR(src, "fopen");
2581 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2582 FILE_OP_ERROR(dest, "fopen");
2587 if (change_file_mode_rw(dest_fp, dest) < 0) {
2588 FILE_OP_ERROR(dest, "chmod");
2589 g_warning("can't change file mode\n");
2592 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2594 if (fputs(buf, dest_fp) == EOF) {
2595 g_warning("writing to %s failed.\n", dest);
2603 if (ferror(src_fp)) {
2604 FILE_OP_ERROR(src, "fgets");
2608 if (fclose(dest_fp) == EOF) {
2609 FILE_OP_ERROR(dest, "fclose");
2621 gint uncanonicalize_file_replace(const gchar *file)
2625 tmp_file = get_tmp_file();
2627 if (uncanonicalize_file(file, tmp_file) < 0) {
2632 if (move_file(tmp_file, file, TRUE) < 0) {
2633 g_warning("can't replace %s .\n", file);
2643 gchar *normalize_newlines(const gchar *str)
2645 const gchar *p = str;
2648 out = outp = g_malloc(strlen(str) + 1);
2649 for (p = str; *p != '\0'; ++p) {
2651 if (*(p + 1) != '\n')
2662 gchar *get_outgoing_rfc2822_str(FILE *fp)
2664 gchar buf[BUFFSIZE];
2668 str = g_string_new(NULL);
2670 /* output header part */
2671 while (fgets(buf, sizeof(buf), fp) != NULL) {
2673 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2680 else if (next != ' ' && next != '\t') {
2684 if (fgets(buf, sizeof(buf), fp) == NULL)
2688 g_string_append(str, buf);
2689 g_string_append(str, "\r\n");
2695 /* output body part */
2696 while (fgets(buf, sizeof(buf), fp) != NULL) {
2699 g_string_append_c(str, '.');
2700 g_string_append(str, buf);
2701 g_string_append(str, "\r\n");
2705 g_string_free(str, FALSE);
2710 gint change_file_mode_rw(FILE *fp, const gchar *file)
2713 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2715 return chmod(file, S_IRUSR|S_IWUSR);
2719 FILE *my_tmpfile(void)
2722 const gchar suffix[] = ".XXXXXX";
2723 const gchar *tmpdir;
2725 const gchar *progname;
2731 tmpdir = get_tmp_dir();
2732 tmplen = strlen(tmpdir);
2733 progname = g_get_prgname();
2734 proglen = strlen(progname);
2735 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2738 memcpy(fname, tmpdir, tmplen);
2739 fname[tmplen] = G_DIR_SEPARATOR;
2740 memcpy(fname + tmplen + 1, progname, proglen);
2741 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2743 fd = mkstemp(fname);
2749 fp = fdopen(fd, "w+b");
2754 #endif /* HAVE_MKSTEMP */
2759 FILE *str_open_as_stream(const gchar *str)
2764 g_return_val_if_fail(str != NULL, NULL);
2768 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2773 if (len == 0) return fp;
2775 if (fwrite(str, len, 1, fp) != 1) {
2776 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2785 gint str_write_to_file(const gchar *str, const gchar *file)
2790 g_return_val_if_fail(str != NULL, -1);
2791 g_return_val_if_fail(file != NULL, -1);
2793 if ((fp = fopen(file, "wb")) == NULL) {
2794 FILE_OP_ERROR(file, "fopen");
2804 if (fwrite(str, len, 1, fp) != 1) {
2805 FILE_OP_ERROR(file, "fwrite");
2811 if (fclose(fp) == EOF) {
2812 FILE_OP_ERROR(file, "fclose");
2820 gchar *file_read_to_str(const gchar *file)
2825 g_return_val_if_fail(file != NULL, NULL);
2827 if ((fp = fopen(file, "rb")) == NULL) {
2828 FILE_OP_ERROR(file, "fopen");
2832 str = file_read_stream_to_str(fp);
2839 gchar *file_read_stream_to_str(FILE *fp)
2846 g_return_val_if_fail(fp != NULL, NULL);
2848 array = g_byte_array_new();
2850 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2851 if (n_read < sizeof(buf) && ferror(fp))
2853 g_byte_array_append(array, buf, n_read);
2857 FILE_OP_ERROR("file stream", "fread");
2858 g_byte_array_free(array, TRUE);
2863 g_byte_array_append(array, buf, 1);
2864 str = (gchar *)array->data;
2865 g_byte_array_free(array, FALSE);
2870 gint execute_async(gchar *const argv[])
2874 if ((pid = fork()) < 0) {
2879 if (pid == 0) { /* child process */
2882 if ((gch_pid = fork()) < 0) {
2887 if (gch_pid == 0) { /* grandchild process */
2888 execvp(argv[0], argv);
2897 waitpid(pid, NULL, 0);
2902 gint execute_sync(gchar *const argv[])
2906 if ((pid = fork()) < 0) {
2911 if (pid == 0) { /* child process */
2912 execvp(argv[0], argv);
2918 waitpid(pid, NULL, 0);
2923 gint execute_command_line(const gchar *cmdline, gboolean async)
2928 argv = strsplit_with_quote(cmdline, " ", 0);
2931 ret = execute_async(argv);
2933 ret = execute_sync(argv);
2939 gchar *get_command_output(const gchar *cmdline)
2941 gchar buf[BUFFSIZE];
2946 g_return_val_if_fail(cmdline != NULL, NULL);
2948 if ((fp = popen(cmdline, "r")) == NULL) {
2949 FILE_OP_ERROR(cmdline, "popen");
2953 str = g_string_new("");
2955 while (fgets(buf, sizeof(buf), fp) != NULL)
2956 g_string_append(str, buf);
2961 g_string_free(str, FALSE);
2966 static gint is_unchanged_uri_char(char c)
2978 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2984 for(i = 0; i < strlen(uri) ; i++) {
2985 if (is_unchanged_uri_char(uri[i])) {
2986 if (k + 2 >= bufsize)
2988 encoded_uri[k++] = uri[i];
2991 char * hexa = "0123456789ABCDEF";
2993 if (k + 4 >= bufsize)
2995 encoded_uri[k++] = '%';
2996 encoded_uri[k++] = hexa[uri[i] / 16];
2997 encoded_uri[k++] = hexa[uri[i] % 16];
3003 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
3006 static gint axtoi(const gchar *hexstr)
3008 gint hi, lo, result;
3011 if ('0' <= hi && hi <= '9') {
3014 if ('a' <= hi && hi <= 'f') {
3017 if ('A' <= hi && hi <= 'F') {
3022 if ('0' <= lo && lo <= '9') {
3025 if ('a' <= lo && lo <= 'f') {
3028 if ('A' <= lo && lo <= 'F') {
3031 result = lo + (16 * hi);
3036 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
3037 * plusses, and escape characters are used)
3040 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
3042 const gchar *encoded;
3045 encoded = encoded_uri;
3046 decoded = decoded_uri;
3049 if (*encoded == '%') {
3051 if (isxdigit(encoded[0])
3052 && isxdigit(encoded[1])) {
3053 *decoded = (gchar) axtoi(encoded);
3058 else if (*encoded == '+') {
3064 *decoded = *encoded;
3074 gint open_uri(const gchar *uri, const gchar *cmdline)
3076 gchar buf[BUFFSIZE];
3078 gchar encoded_uri[BUFFSIZE];
3080 g_return_val_if_fail(uri != NULL, -1);
3082 /* an option to choose whether to use encode_uri or not ? */
3083 encode_uri(encoded_uri, BUFFSIZE, uri);
3086 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3087 !strchr(p + 2, '%'))
3088 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3091 g_warning("Open URI command line is invalid: `%s'",
3093 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3096 execute_command_line(buf, TRUE);
3101 time_t remote_tzoffset_sec(const gchar *zone)
3103 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3109 time_t remoteoffset;
3111 strncpy(zone3, zone, 3);
3115 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3116 (c == '+' || c == '-')) {
3117 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3119 remoteoffset = -remoteoffset;
3120 } else if (!strncmp(zone, "UT" , 2) ||
3121 !strncmp(zone, "GMT", 2)) {
3123 } else if (strlen(zone3) == 3) {
3124 for (p = ustzstr; *p != '\0'; p += 3) {
3125 if (!strncasecmp(p, zone3, 3)) {
3126 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3127 remoteoffset = iustz * 3600;
3133 } else if (strlen(zone3) == 1) {
3135 case 'Z': remoteoffset = 0; break;
3136 case 'A': remoteoffset = -1; break;
3137 case 'B': remoteoffset = -2; break;
3138 case 'C': remoteoffset = -3; break;
3139 case 'D': remoteoffset = -4; break;
3140 case 'E': remoteoffset = -5; break;
3141 case 'F': remoteoffset = -6; break;
3142 case 'G': remoteoffset = -7; break;
3143 case 'H': remoteoffset = -8; break;
3144 case 'I': remoteoffset = -9; break;
3145 case 'K': remoteoffset = -10; break; /* J is not used */
3146 case 'L': remoteoffset = -11; break;
3147 case 'M': remoteoffset = -12; break;
3148 case 'N': remoteoffset = 1; break;
3149 case 'O': remoteoffset = 2; break;
3150 case 'P': remoteoffset = 3; break;
3151 case 'Q': remoteoffset = 4; break;
3152 case 'R': remoteoffset = 5; break;
3153 case 'S': remoteoffset = 6; break;
3154 case 'T': remoteoffset = 7; break;
3155 case 'U': remoteoffset = 8; break;
3156 case 'V': remoteoffset = 9; break;
3157 case 'W': remoteoffset = 10; break;
3158 case 'X': remoteoffset = 11; break;
3159 case 'Y': remoteoffset = 12; break;
3160 default: remoteoffset = 0; break;
3162 remoteoffset = remoteoffset * 3600;
3166 return remoteoffset;
3169 time_t tzoffset_sec(time_t *now)
3175 lt = localtime(now);
3177 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3179 if (lt->tm_year < gmt.tm_year)
3181 else if (lt->tm_year > gmt.tm_year)
3183 else if (lt->tm_yday < gmt.tm_yday)
3185 else if (lt->tm_yday > gmt.tm_yday)
3188 if (off >= 24 * 60) /* should be impossible */
3189 off = 23 * 60 + 59; /* if not, insert silly value */
3190 if (off <= -24 * 60)
3191 off = -(23 * 60 + 59);
3196 /* calculate timezone offset */
3197 gchar *tzoffset(time_t *now)
3199 static gchar offset_string[6];
3205 lt = localtime(now);
3207 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3209 if (lt->tm_year < gmt.tm_year)
3211 else if (lt->tm_year > gmt.tm_year)
3213 else if (lt->tm_yday < gmt.tm_yday)
3215 else if (lt->tm_yday > gmt.tm_yday)
3223 if (off >= 24 * 60) /* should be impossible */
3224 off = 23 * 60 + 59; /* if not, insert silly value */
3226 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3228 return offset_string;
3231 void get_rfc822_date(gchar *buf, gint len)
3235 gchar day[4], mon[4];
3236 gint dd, hh, mm, ss, yyyy;
3241 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3242 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3243 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3244 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3247 void debug_set_mode(gboolean mode)
3252 gboolean debug_get_mode(void)
3257 void debug_print_real(const gchar *format, ...)
3260 gchar buf[BUFFSIZE];
3262 if (!debug_mode) return;
3264 va_start(args, format);
3265 g_vsnprintf(buf, sizeof(buf), format, args);
3271 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3273 if (subject == NULL)
3276 subject += subject_get_prefix_length(subject);
3278 return g_hash_table_lookup(subject_table, subject);
3281 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3284 if (subject == NULL || *subject == 0)
3286 subject += subject_get_prefix_length(subject);
3287 g_hash_table_insert(subject_table, subject, data);
3290 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3292 if (subject == NULL)
3295 subject += subject_get_prefix_length(subject);
3296 g_hash_table_remove(subject_table, subject);
3300 *\brief Check if a string is prefixed with known (combinations)
3301 * of prefixes. The function assumes that each prefix
3302 * is terminated by zero or exactly _one_ space.
3304 *\param str String to check for a prefixes
3306 *\return int Number of chars in the prefix that should be skipped
3307 * for a "clean" subject line. If no prefix was found, 0
3310 int subject_get_prefix_length(const gchar *subject)
3312 /*!< Array with allowable reply prefixes regexps. */
3313 static const gchar * const prefixes[] = {
3314 "Re\\:", /* "Re:" */
3315 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3316 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3317 "Aw\\:", /* "Aw:" (German) */
3318 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3319 "Res\\:", /* "Res:" (Brazilian Outlook) */
3320 "Fw\\:", /* "Fw:" Forward */
3321 "Enc\\:" /* "Enc:" Forward (Brazilian Outlook) */
3324 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3327 static regex_t regex;
3328 static gboolean init_;
3330 if (!subject) return 0;
3331 if (!*subject) return 0;
3334 GString *s = g_string_new("");
3336 for (n = 0; n < PREFIXES; n++)
3337 /* Terminate each prefix regexpression by a
3338 * "\ ?" (zero or ONE space), and OR them */
3339 g_string_sprintfa(s, "(%s\\ ?)%s",
3344 g_string_prepend(s, "(");
3345 g_string_append(s, ")+"); /* match at least once */
3346 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3349 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3350 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3351 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3352 debug_print("Error compiling regexp %s\n", s->str);
3353 g_string_free(s, TRUE);
3357 g_string_free(s, TRUE);
3361 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3367 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
3371 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
3372 fd = mkstemp(*filename);
3374 return fdopen(fd, "w+");
3377 /* allow Mutt-like patterns in quick search */
3378 gchar *expand_search_string(const gchar *search_string)
3381 gchar term_char, save_char;
3382 gchar *cmd_start, *cmd_end;
3383 GString *matcherstr;
3384 gchar *returnstr = NULL;
3386 gboolean casesens, dontmatch;
3387 /* list of allowed pattern abbreviations */
3389 gchar *abbreviated; /* abbreviation */
3390 gchar *command; /* actual matcher command */
3391 gint numparams; /* number of params for cmd */
3392 gboolean qualifier; /* do we append regexpcase */
3393 gboolean quotes; /* do we need quotes */
3396 { "a", "all", 0, FALSE, FALSE },
3397 { "ag", "age_greater", 1, FALSE, FALSE },
3398 { "al", "age_lower", 1, FALSE, FALSE },
3399 { "b", "body_part", 1, TRUE, TRUE },
3400 { "B", "message", 1, TRUE, TRUE },
3401 { "c", "cc", 1, TRUE, TRUE },
3402 { "C", "to_or_cc", 1, TRUE, TRUE },
3403 { "D", "deleted", 0, FALSE, FALSE },
3404 { "e", "header \"Sender\"", 1, TRUE, TRUE },
3405 { "E", "execute", 1, FALSE, TRUE },
3406 { "f", "from", 1, TRUE, TRUE },
3407 { "F", "forwarded", 0, FALSE, FALSE },
3408 { "h", "headers_part", 1, TRUE, TRUE },
3409 { "i", "header \"Message-Id\"", 1, TRUE, TRUE },
3410 { "I", "inreplyto", 1, TRUE, TRUE },
3411 { "L", "locked", 0, FALSE, FALSE },
3412 { "n", "newsgroups", 1, TRUE, TRUE },
3413 { "N", "new", 0, FALSE, FALSE },
3414 { "O", "~new", 0, FALSE, FALSE },
3415 { "r", "replied", 0, FALSE, FALSE },
3416 { "R", "~unread", 0, FALSE, FALSE },
3417 { "s", "subject", 1, TRUE, TRUE },
3418 { "se", "score_equal", 1, FALSE, FALSE },
3419 { "sg", "score_greater", 1, FALSE, FALSE },
3420 { "sl", "score_lower", 1, FALSE, FALSE },
3421 { "Se", "size_equal", 1, FALSE, FALSE },
3422 { "Sg", "size_greater", 1, FALSE, FALSE },
3423 { "Ss", "size_smaller", 1, FALSE, FALSE },
3424 { "t", "to", 1, TRUE, TRUE },
3425 { "T", "marked", 0, FALSE, FALSE },
3426 { "U", "unread", 0, FALSE, FALSE },
3427 { "x", "header \"References\"", 1, TRUE, TRUE },
3428 { "y", "header \"X-Label\"", 1, TRUE, TRUE },
3429 { "&", "&", 0, FALSE, FALSE },
3430 { "|", "|", 0, FALSE, FALSE },
3431 { NULL, NULL, 0, FALSE, FALSE }
3434 if (search_string == NULL)
3437 copy_str = g_strdup(search_string);
3439 /* if it's a full command don't process it so users
3440 can still do something like from regexpcase "foo" */
3441 for (i = 0; cmds[i].command; i++) {
3442 const gchar *tmp_search_string = search_string;
3443 cmd_start = cmds[i].command;
3444 /* allow logical NOT */
3445 if (*tmp_search_string == '~')
3446 tmp_search_string++;
3447 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3450 if (cmds[i].command)
3453 matcherstr = g_string_sized_new(16);
3454 cmd_start = cmd_end = copy_str;
3455 while (cmd_end && *cmd_end) {
3456 /* skip all white spaces */
3457 while (*cmd_end && isspace(*cmd_end))
3460 /* extract a command */
3461 while (*cmd_end && !isspace(*cmd_end))
3464 /* save character */
3465 save_char = *cmd_end;
3471 /* ~ and ! mean logical NOT */
3472 if (*cmd_start == '~' || *cmd_start == '!')
3477 /* % means case sensitive match */
3478 if (*cmd_start == '%')
3484 /* find matching abbreviation */
3485 for (i = 0; cmds[i].command; i++) {
3486 if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3487 /* restore character */
3488 *cmd_end = save_char;
3491 if (matcherstr->len > 0) {
3492 g_string_append(matcherstr, " ");
3495 g_string_append(matcherstr, "~");
3496 g_string_append(matcherstr, cmds[i].command);
3497 g_string_append(matcherstr, " ");
3499 /* stop if no params required */
3500 if (cmds[i].numparams == 0)
3503 /* extract a parameter, allow quotes */
3505 cmd_start = cmd_end;
3506 if (*cmd_start == '"') {
3513 /* extract actual parameter */
3514 while ((*cmd_end) && (*cmd_end != term_char))
3517 if (*cmd_end && (*cmd_end != term_char))
3520 if (*cmd_end == '"')
3523 save_char = *cmd_end;
3526 if (cmds[i].qualifier) {
3528 g_string_append(matcherstr, "regexp ");
3530 g_string_append(matcherstr, "regexpcase ");
3533 /* do we need to add quotes ? */
3534 if (cmds[i].quotes && term_char != '"')
3535 g_string_append(matcherstr, "\"");
3537 /* copy actual parameter */
3538 g_string_append(matcherstr, cmd_start);
3540 /* do we need to add quotes ? */
3541 if (cmds[i].quotes && term_char != '"')
3542 g_string_append(matcherstr, "\"");
3544 /* restore original character */
3545 *cmd_end = save_char;
3553 cmd_start = cmd_end;
3558 returnstr = matcherstr->str;
3559 g_string_free(matcherstr, FALSE);
3563 guint g_stricase_hash(gconstpointer gptr)
3565 guint hash_result = 0;
3568 for (str = gptr; str && *str; str++) {
3569 if (isupper(*str)) hash_result += (*str + ' ');
3570 else hash_result += *str;
3576 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3578 const char *str1 = gptr1;
3579 const char *str2 = gptr2;
3581 return !strcasecmp(str1, str2);
3584 gint g_int_compare(gconstpointer a, gconstpointer b)
3586 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3589 gchar *generate_msgid(const gchar *address, gchar *buf, gint len)
3591 /* steal from compose.c::compose_generate_msgid() */
3599 if (address && *address) {
3600 if (strchr(address, '@'))
3601 addr = g_strdup(address);
3603 addr = g_strconcat(address, "@", get_domain_name(), NULL);
3605 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3608 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3609 lt->tm_year + 1900, lt->tm_mon + 1,
3610 lt->tm_mday, lt->tm_hour,
3611 lt->tm_min, lt->tm_sec,
3612 (guint)random(), addr);
3619 * Create a new boundary in a way that it is very unlikely that this
3620 * will occur in the following text. It would be easy to ensure
3621 * uniqueness if everything is either quoted-printable or base64
3622 * encoded (note that conversion is allowed), but because MIME bodies
3623 * may be nested, it may happen that the same boundary has already
3624 * been used. We avoid scanning the message for conflicts and hope the
3627 * boundary := 0*69<bchars> bcharsnospace
3628 * bchars := bcharsnospace / " "
3629 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
3630 * "+" / "_" / "," / "-" / "." /
3631 * "/" / ":" / "=" / "?"
3633 * ":" and "," removed because of buggy MTAs
3636 gchar *generate_mime_boundary(void)
3638 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3639 "abcdefghijklmnopqrstuvwxyz"
3640 "1234567890'()+_./=?";
3642 gchar bufdate[BUFFSIZE];
3648 /* We make the boundary depend on the pid, so that all running
3649 * processed generate different values even when they have been
3650 * started within the same second and srand48(time(NULL)) has been
3651 * used. I can't see whether this is really an advantage but it
3652 * doesn't do any harm.
3655 for (i = 0; i < sizeof(bufuniq) - 1; i++) {
3656 bufuniq[i] = tbl[(lrand48() ^ pid) % (sizeof(tbl) - 1)]; /* fill with random */
3657 if (bufuniq[i] == '=' && equal == -1)
3662 /* now make sure that we do have the sequence "=." in it which cannot
3663 * be matched by quoted-printable or base64 encoding */
3664 if (equal != -1 && (equal + 1) < i)
3665 bufuniq[equal + 1] = '.';
3671 get_rfc822_date(bufdate, sizeof(bufdate));
3672 subst_char(bufdate, ' ', '_');
3673 subst_char(bufdate, ',', '_');
3674 subst_char(bufdate, ':', '_');
3676 return g_strdup_printf("Multipart_%s_%s",