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>
52 static gboolean debug_mode = FALSE;
54 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
56 void list_free_strings(GList *list)
58 list = g_list_first(list);
60 while (list != NULL) {
66 void slist_free_strings(GSList *list)
68 while (list != NULL) {
74 GSList *slist_concat_unique (GSList *first, GSList *second)
82 } else if (second == NULL)
85 for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
86 if (g_slist_find(ret, tmp->data) == NULL)
87 ret = g_slist_prepend(ret, tmp->data);
92 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
97 void hash_free_strings(GHashTable *table)
99 g_hash_table_foreach(table, hash_free_strings_func, NULL);
102 static void hash_free_value_mem_func(gpointer key, gpointer value,
108 void hash_free_value_mem(GHashTable *table)
110 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
113 gint str_case_equal(gconstpointer v, gconstpointer v2)
115 return strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
118 guint str_case_hash(gconstpointer key)
120 const gchar *p = key;
125 for (p += 1; *p != '\0'; p++)
126 h = (h << 5) - h + tolower(*p);
132 void ptr_array_free_strings(GPtrArray *array)
137 g_return_if_fail(array != NULL);
139 for (i = 0; i < array->len; i++) {
140 str = g_ptr_array_index(array, i);
145 gint to_number(const gchar *nstr)
147 register const gchar *p;
149 if (*nstr == '\0') return -1;
151 for (p = nstr; *p != '\0'; p++)
152 if (!isdigit(*p)) return -1;
157 /* convert integer into string,
158 nstr must be not lower than 11 characters length */
159 gchar *itos_buf(gchar *nstr, gint n)
161 g_snprintf(nstr, 11, "%d", n);
165 /* convert integer into string */
168 static gchar nstr[11];
170 return itos_buf(nstr, n);
173 gchar *to_human_readable(off_t size)
175 static gchar str[10];
178 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
179 else if (size >> 10 < 1024)
180 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
181 else if (size >> 20 < 1024)
182 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
184 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
189 /* strcmp with NULL-checking */
190 gint strcmp2(const gchar *s1, const gchar *s2)
192 if (s1 == NULL || s2 == NULL)
195 return strcmp(s1, s2);
197 /* strstr with NULL-checking */
198 gchar *strstr2(const gchar *s1, const gchar *s2)
200 if (s1 == NULL || s2 == NULL)
203 return strstr(s1, s2);
206 gint path_cmp(const gchar *s1, const gchar *s2)
210 if (s1 == NULL || s2 == NULL) return -1;
211 if (*s1 == '\0' || *s2 == '\0') return -1;
216 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
217 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
219 return strncmp(s1, s2, MAX(len1, len2));
222 /* remove trailing return code */
223 gchar *strretchomp(gchar *str)
227 if (!*str) return str;
229 for (s = str + strlen(str) - 1;
230 s >= str && (*s == '\n' || *s == '\r');
237 /* remove trailing character */
238 gchar *strtailchomp(gchar *str, gchar tail_char)
242 if (!*str) return str;
243 if (tail_char == '\0') return str;
245 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
251 /* remove CR (carriage return) */
252 gchar *strcrchomp(gchar *str)
256 if (!*str) return str;
258 s = str + strlen(str) - 1;
259 if (*s == '\n' && s > str && *(s - 1) == '\r') {
267 /* Similar to `strstr' but this function ignores the case of both strings. */
268 gchar *strcasestr(const gchar *haystack, const gchar *needle)
270 register size_t haystack_len, needle_len;
272 haystack_len = strlen(haystack);
273 needle_len = strlen(needle);
275 if (haystack_len < needle_len || needle_len == 0)
278 while (haystack_len >= needle_len) {
279 if (!strncasecmp(haystack, needle, needle_len))
280 return (gchar *)haystack;
290 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
291 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
305 /* don't do zero fill */
310 int iswalnum(wint_t wc)
312 return isalnum((int)wc);
317 int iswspace(wint_t wc)
319 return isspace((int)wc);
324 wint_t towlower(wint_t wc)
326 if (wc >= L'A' && wc <= L'Z')
327 return wc + L'a' - L'A';
334 size_t wcslen(const wchar_t *s)
346 /* Copy SRC to DEST. */
347 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
355 } while (c != L'\0');
362 /* Copy no more than N wide-characters of SRC to DEST. */
363 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
373 } while (c != L'\0');
384 /* Duplicate S, returning an identical malloc'd string. */
385 wchar_t *wcsdup(const wchar_t *s)
390 new_str = g_new(wchar_t, wcslen(s) + 1);
398 /* Duplicate no more than N wide-characters of S,
399 returning an identical malloc'd string. */
400 wchar_t *wcsndup(const wchar_t *s, size_t n)
405 new_str = g_new(wchar_t, n + 1);
406 wcsncpy(new_str, s, n);
407 new_str[n] = (wchar_t)0;
414 wchar_t *strdup_mbstowcs(const gchar *s)
419 new_str = g_new(wchar_t, strlen(s) + 1);
420 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
424 new_str = g_realloc(new_str,
425 sizeof(wchar_t) * (wcslen(new_str) + 1));
432 gchar *strdup_wcstombs(const wchar_t *s)
438 len = wcslen(s) * MB_CUR_MAX + 1;
439 new_str = g_new(gchar, len);
440 if (wcstombs(new_str, s, len) < 0) {
444 new_str = g_realloc(new_str, strlen(new_str) + 1);
451 /* Compare S1 and S2, ignoring case. */
452 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
458 c1 = towlower(*s1++);
459 c2 = towlower(*s2++);
462 else if (c1 == 0 && c2 == 0)
469 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
470 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
472 register size_t haystack_len, needle_len;
474 haystack_len = wcslen(haystack);
475 needle_len = wcslen(needle);
477 if (haystack_len < needle_len || needle_len == 0)
480 while (haystack_len >= needle_len) {
481 if (!wcsncasecmp(haystack, needle, needle_len))
482 return (wchar_t *)haystack;
492 gint get_mbs_len(const gchar *s)
502 mb_len = mblen(p, MB_LEN_MAX);
516 /* Examine if next block is non-ASCII string */
517 gboolean is_next_nonascii(const guchar *s)
521 /* skip head space */
522 for (p = s; *p != '\0' && isspace(*p); p++)
524 for (; *p != '\0' && !isspace(*p); p++) {
525 if (*p > 127 || *p < 32)
532 gint get_next_word_len(const gchar *s)
536 for (; *s != '\0' && !isspace(*s); s++, len++)
542 /* compare subjects */
543 gint subject_compare(const gchar *s1, const gchar *s2)
547 if (!s1 || !s2) return -1;
548 if (!*s1 || !*s2) return -1;
550 Xstrdup_a(str1, s1, return -1);
551 Xstrdup_a(str2, s2, return -1);
553 trim_subject_for_compare(str1);
554 trim_subject_for_compare(str2);
556 if (!*str1 || !*str2) return -1;
558 return strcmp(str1, str2);
561 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
565 if (!s1 || !s2) return -1;
567 Xstrdup_a(str1, s1, return -1);
568 Xstrdup_a(str2, s2, return -1);
570 trim_subject_for_sort(str1);
571 trim_subject_for_sort(str2);
573 return strcasecmp(str1, str2);
576 void trim_subject_for_compare(gchar *str)
580 eliminate_parenthesis(str, '[', ']');
581 eliminate_parenthesis(str, '(', ')');
584 srcp = str + subject_get_prefix_length(str);
586 memmove(str, srcp, strlen(srcp) + 1);
589 void trim_subject_for_sort(gchar *str)
595 srcp = str + subject_get_prefix_length(str);
597 memmove(str, srcp, strlen(srcp) + 1);
600 void trim_subject(gchar *str)
602 register gchar *srcp, *destp;
606 destp = str + subject_get_prefix_length(str);
611 } else if (*destp == '(') {
622 else if (*srcp == cl)
628 while (isspace(*srcp)) srcp++;
629 memmove(destp, srcp, strlen(srcp) + 1);
632 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
634 register gchar *srcp, *destp;
639 while ((destp = strchr(destp, op))) {
645 else if (*srcp == cl)
651 while (isspace(*srcp)) srcp++;
652 memmove(destp, srcp, strlen(srcp) + 1);
656 void extract_parenthesis(gchar *str, gchar op, gchar cl)
658 register gchar *srcp, *destp;
663 while ((srcp = strchr(destp, op))) {
666 memmove(destp, srcp + 1, strlen(srcp));
671 else if (*destp == cl)
683 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
686 register gchar *srcp, *destp;
688 gboolean in_quote = FALSE;
692 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
695 memmove(destp, srcp + 1, strlen(srcp));
698 if (*destp == op && !in_quote)
700 else if (*destp == cl && !in_quote)
702 else if (*destp == quote_chr)
714 void eliminate_quote(gchar *str, gchar quote_chr)
716 register gchar *srcp, *destp;
720 while ((destp = strchr(destp, quote_chr))) {
721 if ((srcp = strchr(destp + 1, quote_chr))) {
723 while (isspace(*srcp)) srcp++;
724 memmove(destp, srcp, strlen(srcp) + 1);
732 void extract_quote(gchar *str, gchar quote_chr)
736 if ((str = strchr(str, quote_chr))) {
738 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
739 memmove(p - 1, p, strlen(p) + 1);
744 memmove(str, str + 1, p - str);
749 void eliminate_address_comment(gchar *str)
751 register gchar *srcp, *destp;
756 while ((destp = strchr(destp, '"'))) {
757 if ((srcp = strchr(destp + 1, '"'))) {
762 while (isspace(*srcp)) srcp++;
763 memmove(destp, srcp, strlen(srcp) + 1);
773 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
779 else if (*srcp == ')')
785 while (isspace(*srcp)) srcp++;
786 memmove(destp, srcp, strlen(srcp) + 1);
790 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
792 gboolean in_quote = FALSE;
795 if (*str == c && !in_quote)
797 if (*str == quote_chr)
805 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
807 gboolean in_quote = FALSE;
810 p = str + strlen(str) - 1;
812 if (*p == c && !in_quote)
822 void extract_address(gchar *str)
824 eliminate_address_comment(str);
825 if (strchr_with_skip_quote(str, '"', '<'))
826 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
830 void extract_list_id_str(gchar *str)
832 if (strchr_with_skip_quote(str, '"', '<'))
833 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
837 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
842 if (!str) return addr_list;
844 Xstrdup_a(work, str, return addr_list);
847 eliminate_address_comment(work);
850 while (workp && *workp) {
853 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
859 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
860 extract_parenthesis_with_skip_quote
861 (workp, '"', '<', '>');
865 addr_list = g_slist_append(addr_list, g_strdup(workp));
873 GSList *address_list_append(GSList *addr_list, const gchar *str)
875 return address_list_append_real(addr_list, str, TRUE);
878 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
880 return address_list_append_real(addr_list, str, FALSE);
883 GSList *references_list_append(GSList *msgid_list, const gchar *str)
887 if (!str) return msgid_list;
890 while (strp && *strp) {
891 const gchar *start, *end;
894 if ((start = strchr(strp, '<')) != NULL) {
895 end = strchr(start + 1, '>');
900 msgid = g_strndup(start + 1, end - start - 1);
903 msgid_list = g_slist_append(msgid_list, msgid);
913 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
918 if (!str) return group_list;
920 Xstrdup_a(work, str, return group_list);
924 while (workp && *workp) {
927 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
935 group_list = g_slist_append(group_list,
944 GList *add_history(GList *list, const gchar *str)
948 g_return_val_if_fail(str != NULL, list);
950 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
953 list = g_list_remove(list, old->data);
954 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
957 last = g_list_last(list);
960 g_list_remove(list, last->data);
964 list = g_list_prepend(list, g_strdup(str));
969 void remove_return(gchar *str)
971 register gchar *p = str;
974 if (*p == '\n' || *p == '\r')
975 memmove(p, p + 1, strlen(p));
981 void remove_space(gchar *str)
983 register gchar *p = str;
988 while (isspace(*(p + spc)))
991 memmove(p, p + spc, strlen(p + spc) + 1);
997 void unfold_line(gchar *str)
999 register gchar *p = str;
1003 if (*p == '\n' || *p == '\r') {
1006 while (isspace(*(p + spc)))
1009 memmove(p, p + spc, strlen(p + spc) + 1);
1015 void subst_char(gchar *str, gchar orig, gchar subst)
1017 register gchar *p = str;
1026 void subst_chars(gchar *str, gchar *orig, gchar subst)
1028 register gchar *p = str;
1031 if (strchr(orig, *p) != NULL)
1037 void subst_for_filename(gchar *str)
1039 subst_chars(str, " \t\r\n\"/\\", '_');
1042 void subst_for_shellsafe_filename(gchar *str)
1044 subst_for_filename(str);
1045 subst_chars(str, "|&;()<>'!{}[]",'_');
1048 gboolean is_header_line(const gchar *str)
1050 if (str[0] == ':') return FALSE;
1052 while (*str != '\0' && *str != ' ') {
1061 gboolean is_ascii_str(const guchar *str)
1063 g_return_val_if_fail(str, FALSE);
1065 while (*str != '\0') {
1066 if (*str != '\t' && *str != ' ' &&
1067 *str != '\r' && *str != '\n' &&
1068 (*str < 32 || *str >= 127))
1076 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1078 const gchar *first_pos;
1079 const gchar *last_pos;
1080 const gchar *p = str;
1081 gint quote_level = -1;
1083 /* speed up line processing by only searching to the last '>' */
1084 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1085 /* skip a line if it contains a '<' before the initial '>' */
1086 if (memchr(str, '<', first_pos - str) != NULL)
1088 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1092 while (p <= last_pos) {
1093 while (p < last_pos) {
1100 if (strchr(quote_chars, *p))
1102 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1103 /* any characters are allowed except '-' and space */
1105 && !strchr(quote_chars, *p)
1109 if (strchr(quote_chars, *p))
1121 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1123 gchar * position = NULL;
1124 gchar * tmp_pos = NULL;
1127 if (quote_chars == NULL)
1130 for (i = 0; i < strlen(quote_chars); i++) {
1131 tmp_pos = strchr (str, quote_chars[i]);
1133 || (tmp_pos != NULL && position >= tmp_pos) )
1139 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1141 gchar * position = NULL;
1142 gchar * tmp_pos = NULL;
1145 if (quote_chars == NULL)
1148 for (i = 0; i < strlen(quote_chars); i++) {
1149 tmp_pos = strrchr (str, quote_chars[i]);
1151 || (tmp_pos != NULL && position <= tmp_pos) )
1157 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1159 register guint haystack_len, needle_len;
1160 gboolean in_squote = FALSE, in_dquote = FALSE;
1162 haystack_len = strlen(haystack);
1163 needle_len = strlen(needle);
1165 if (haystack_len < needle_len || needle_len == 0)
1168 while (haystack_len >= needle_len) {
1169 if (!in_squote && !in_dquote &&
1170 !strncmp(haystack, needle, needle_len))
1171 return (gchar *)haystack;
1173 /* 'foo"bar"' -> foo"bar"
1174 "foo'bar'" -> foo'bar' */
1175 if (*haystack == '\'') {
1178 else if (!in_dquote)
1180 } else if (*haystack == '\"') {
1183 else if (!in_squote)
1194 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1197 gchar quote_chr = '"';
1199 gboolean in_quote = FALSE;
1203 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1207 if (*p == op && !in_quote)
1209 else if (*p == cl && !in_quote)
1211 else if (*p == quote_chr)
1224 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1227 GSList *string_list = NULL, *slist;
1229 const gchar *s_op, *s_cl;
1232 g_return_val_if_fail(str != NULL, NULL);
1235 max_tokens = G_MAXINT;
1237 s_op = strchr_with_skip_quote(str, '"', op);
1238 if (!s_op) return NULL;
1240 s_cl = strchr_parenthesis_close(str, op, cl);
1248 new_string = g_new(gchar, len + 1);
1249 strncpy(new_string, str, len);
1250 new_string[len] = 0;
1251 string_list = g_slist_prepend(string_list, new_string);
1255 while (*str && isspace(*str)) str++;
1257 string_list = g_slist_prepend(string_list,
1260 s_op = strchr_with_skip_quote(str, '"', op);
1261 if (!--max_tokens || !s_op) break;
1265 s_cl = strchr_parenthesis_close(str, op, cl);
1266 } while (--max_tokens && s_cl);
1269 str_array = g_new(gchar*, n);
1273 str_array[i--] = NULL;
1274 for (slist = string_list; slist; slist = slist->next)
1275 str_array[i--] = slist->data;
1277 g_slist_free(string_list);
1282 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1285 GSList *string_list = NULL, *slist;
1286 gchar **str_array, *s, *new_str;
1287 guint i, n = 1, len;
1289 g_return_val_if_fail(str != NULL, NULL);
1290 g_return_val_if_fail(delim != NULL, NULL);
1293 max_tokens = G_MAXINT;
1295 s = strstr_with_skip_quote(str, delim);
1297 guint delimiter_len = strlen(delim);
1301 new_str = g_strndup(str, len);
1303 if (new_str[0] == '\'' || new_str[0] == '\"') {
1304 if (new_str[len - 1] == new_str[0]) {
1305 new_str[len - 1] = '\0';
1306 memmove(new_str, new_str + 1, len - 1);
1309 string_list = g_slist_prepend(string_list, new_str);
1311 str = s + delimiter_len;
1312 s = strstr_with_skip_quote(str, delim);
1313 } while (--max_tokens && s);
1317 new_str = g_strdup(str);
1318 if (new_str[0] == '\'' || new_str[0] == '\"') {
1320 if (new_str[len - 1] == new_str[0]) {
1321 new_str[len - 1] = '\0';
1322 memmove(new_str, new_str + 1, len - 1);
1325 string_list = g_slist_prepend(string_list, new_str);
1329 str_array = g_new(gchar*, n);
1333 str_array[i--] = NULL;
1334 for (slist = string_list; slist; slist = slist->next)
1335 str_array[i--] = slist->data;
1337 g_slist_free(string_list);
1342 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1344 gchar *abbrev_group;
1346 const gchar *p = group;
1349 g_return_val_if_fail(group != NULL, NULL);
1351 last = group + strlen(group);
1352 abbrev_group = ap = g_malloc(strlen(group) + 1);
1357 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1359 while (*p != '.') p++;
1362 return abbrev_group;
1367 return abbrev_group;
1370 gchar *trim_string(const gchar *str, gint len)
1372 const gchar *p = str;
1377 if (!str) return NULL;
1378 if (strlen(str) <= len)
1379 return g_strdup(str);
1381 while (*p != '\0') {
1382 mb_len = mblen(p, MB_LEN_MAX);
1385 else if (mb_len < 0)
1386 return g_strdup(str);
1387 else if (new_len + mb_len > len)
1394 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1395 return g_strconcat(new_str, "...", NULL);
1398 GList *uri_list_extract_filenames(const gchar *uri_list)
1400 GList *result = NULL;
1408 while (isspace(*p)) p++;
1409 if (!strncmp(p, "file:", 5)) {
1412 while (*q && *q != '\n' && *q != '\r') q++;
1416 while (q > p && isspace(*q)) q--;
1417 file = g_malloc(q - p + 2);
1418 strncpy(file, p, q - p + 1);
1419 file[q - p + 1] = '\0';
1420 result = g_list_append(result,file);
1424 p = strchr(p, '\n');
1431 #define HEX_TO_INT(val, hex) \
1435 if ('0' <= c && c <= '9') { \
1437 } else if ('a' <= c && c <= 'f') { \
1438 val = c - 'a' + 10; \
1439 } else if ('A' <= c && c <= 'F') { \
1440 val = c - 'A' + 10; \
1446 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1447 gchar **subject, gchar **body)
1452 Xstrdup_a(tmp_mailto, mailto, return -1);
1454 if (!strncmp(tmp_mailto, "mailto:", 7))
1457 p = strchr(tmp_mailto, '?');
1464 *to = g_strdup(tmp_mailto);
1467 gchar *field, *value;
1484 if (*value == '\0') continue;
1486 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1487 *cc = g_strdup(value);
1488 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1489 *bcc = g_strdup(value);
1490 } else if (subject && !*subject &&
1491 !g_strcasecmp(field, "subject")) {
1492 *subject = g_malloc(strlen(value) + 1);
1493 decode_uri(*subject, value);
1494 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1495 *body = g_malloc(strlen(value) + 1);
1496 decode_uri(*body, value);
1504 * We need this wrapper around g_get_home_dir(), so that
1505 * we can fix some Windoze things here. Should be done in glibc of course
1506 * but as long as we are not able to do our own extensions to glibc, we do
1509 gchar *get_home_dir(void)
1511 #if HAVE_DOSISH_SYSTEM
1512 static gchar *home_dir;
1515 home_dir = read_w32_registry_string(NULL,
1516 "Software\\Sylpheed", "HomeDir" );
1517 if (!home_dir || !*home_dir) {
1518 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1519 const char *s = g_get_home_dir();
1521 home_dir = g_strdup (s);
1523 if (!home_dir || !*home_dir)
1524 home_dir = g_strdup ("c:\\sylpheed");
1526 debug_print("initialized home_dir to `%s'\n", home_dir);
1529 #else /* standard glib */
1530 return g_get_home_dir();
1534 gchar *get_rc_dir(void)
1536 static gchar *rc_dir = NULL;
1539 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1545 gchar *get_news_cache_dir(void)
1547 static gchar *news_cache_dir = NULL;
1549 if (!news_cache_dir)
1550 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1551 NEWS_CACHE_DIR, NULL);
1553 return news_cache_dir;
1556 gchar *get_imap_cache_dir(void)
1558 static gchar *imap_cache_dir = NULL;
1560 if (!imap_cache_dir)
1561 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1562 IMAP_CACHE_DIR, NULL);
1564 return imap_cache_dir;
1567 gchar *get_mbox_cache_dir(void)
1569 static gchar *mbox_cache_dir = NULL;
1571 if (!mbox_cache_dir)
1572 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1573 MBOX_CACHE_DIR, NULL);
1575 return mbox_cache_dir;
1578 gchar *get_mime_tmp_dir(void)
1580 static gchar *mime_tmp_dir = NULL;
1583 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1584 MIME_TMP_DIR, NULL);
1586 return mime_tmp_dir;
1589 gchar *get_template_dir(void)
1591 static gchar *template_dir = NULL;
1594 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1595 TEMPLATE_DIR, NULL);
1597 return template_dir;
1600 gchar *get_header_cache_dir(void)
1602 static gchar *header_dir = NULL;
1605 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1606 HEADER_CACHE_DIR, NULL);
1611 gchar *get_tmp_dir(void)
1613 static gchar *tmp_dir = NULL;
1616 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1622 gchar *get_tmp_file(void)
1625 static guint32 id = 0;
1627 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1628 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1633 gchar *get_domain_name(void)
1635 static gchar *domain_name = NULL;
1638 gchar buf[128] = "";
1641 if (gethostname(buf, sizeof(buf)) < 0) {
1642 perror("gethostname");
1643 domain_name = "unknown";
1645 buf[sizeof(buf) - 1] = '\0';
1646 if ((hp = my_gethostbyname(buf)) == NULL) {
1647 perror("gethostbyname");
1648 domain_name = g_strdup(buf);
1650 domain_name = g_strdup(hp->h_name);
1654 debug_print("domain name = %s\n", domain_name);
1660 off_t get_file_size(const gchar *file)
1664 if (stat(file, &s) < 0) {
1665 FILE_OP_ERROR(file, "stat");
1672 off_t get_file_size_as_crlf(const gchar *file)
1676 gchar buf[BUFFSIZE];
1678 if ((fp = fopen(file, "rb")) == NULL) {
1679 FILE_OP_ERROR(file, "fopen");
1683 while (fgets(buf, sizeof(buf), fp) != NULL) {
1685 size += strlen(buf) + 2;
1689 FILE_OP_ERROR(file, "fgets");
1698 off_t get_left_file_size(FILE *fp)
1704 if ((pos = ftell(fp)) < 0) {
1708 if (fseek(fp, 0L, SEEK_END) < 0) {
1712 if ((end = ftell(fp)) < 0) {
1717 if (fseek(fp, pos, SEEK_SET) < 0) {
1725 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1732 if (stat(file, &s) < 0) {
1733 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1737 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1743 gboolean is_dir_exist(const gchar *dir)
1750 if (stat(dir, &s) < 0) {
1751 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1755 if (S_ISDIR(s.st_mode))
1761 gboolean is_file_entry_exist(const gchar *file)
1768 if (stat(file, &s) < 0) {
1769 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1776 gboolean dirent_is_regular_file(struct dirent *d)
1780 #ifdef HAVE_DIRENT_D_TYPE
1781 if (d->d_type == DT_REG)
1783 else if (d->d_type != DT_UNKNOWN)
1787 return (stat(d->d_name, &s) == 0 && S_ISREG(s.st_mode));
1790 gboolean dirent_is_directory(struct dirent *d)
1794 #ifdef HAVE_DIRENT_D_TYPE
1795 if (d->d_type == DT_DIR)
1797 else if (d->d_type != DT_UNKNOWN)
1801 return (stat(d->d_name, &s) == 0 && S_ISDIR(s.st_mode));
1804 gint change_dir(const gchar *dir)
1806 gchar *prevdir = NULL;
1809 prevdir = g_get_current_dir();
1811 if (chdir(dir) < 0) {
1812 FILE_OP_ERROR(dir, "chdir");
1813 if (debug_mode) g_free(prevdir);
1815 } else if (debug_mode) {
1818 cwd = g_get_current_dir();
1819 if (strcmp(prevdir, cwd) != 0)
1820 g_print("current dir: %s\n", cwd);
1828 gint make_dir(const gchar *dir)
1830 if (mkdir(dir, S_IRWXU) < 0) {
1831 FILE_OP_ERROR(dir, "mkdir");
1834 if (chmod(dir, S_IRWXU) < 0)
1835 FILE_OP_ERROR(dir, "chmod");
1840 gint make_dir_hier(const gchar *dir)
1845 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1846 parent_dir = g_strndup(dir, p - dir);
1847 if (*parent_dir != '\0') {
1848 if (!is_dir_exist(parent_dir)) {
1849 if (make_dir(parent_dir) < 0) {
1858 if (!is_dir_exist(dir)) {
1859 if (make_dir(dir) < 0)
1866 gint remove_all_files(const gchar *dir)
1872 prev_dir = g_get_current_dir();
1874 if (chdir(dir) < 0) {
1875 FILE_OP_ERROR(dir, "chdir");
1880 if ((dp = opendir(".")) == NULL) {
1881 FILE_OP_ERROR(dir, "opendir");
1886 while ((d = readdir(dp)) != NULL) {
1887 if (!strcmp(d->d_name, ".") ||
1888 !strcmp(d->d_name, ".."))
1891 if (unlink(d->d_name) < 0)
1892 FILE_OP_ERROR(d->d_name, "unlink");
1897 if (chdir(prev_dir) < 0) {
1898 FILE_OP_ERROR(prev_dir, "chdir");
1908 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1915 prev_dir = g_get_current_dir();
1917 if (chdir(dir) < 0) {
1918 FILE_OP_ERROR(dir, "chdir");
1923 if ((dp = opendir(".")) == NULL) {
1924 FILE_OP_ERROR(dir, "opendir");
1929 while ((d = readdir(dp)) != NULL) {
1930 fileno = to_number(d->d_name);
1931 if (fileno >= 0 && first <= fileno && fileno <= last) {
1932 if (is_dir_exist(d->d_name))
1934 if (unlink(d->d_name) < 0)
1935 FILE_OP_ERROR(d->d_name, "unlink");
1941 if (chdir(prev_dir) < 0) {
1942 FILE_OP_ERROR(prev_dir, "chdir");
1952 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1959 prev_dir = g_get_current_dir();
1961 if (chdir(dir) < 0) {
1962 FILE_OP_ERROR(dir, "chdir");
1967 if ((dp = opendir(".")) == NULL) {
1968 FILE_OP_ERROR(dir, "opendir");
1973 while ((d = readdir(dp)) != NULL) {
1974 fileno = to_number(d->d_name);
1975 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1976 debug_print("removing unwanted file %d from %s\n", fileno, dir);
1977 if (is_dir_exist(d->d_name))
1979 if (unlink(d->d_name) < 0)
1980 FILE_OP_ERROR(d->d_name, "unlink");
1986 if (chdir(prev_dir) < 0) {
1987 FILE_OP_ERROR(prev_dir, "chdir");
1997 gint remove_all_numbered_files(const gchar *dir)
1999 return remove_numbered_files(dir, 0, UINT_MAX);
2002 gint remove_expired_files(const gchar *dir, guint hours)
2009 time_t mtime, now, expire_time;
2011 prev_dir = g_get_current_dir();
2013 if (chdir(dir) < 0) {
2014 FILE_OP_ERROR(dir, "chdir");
2019 if ((dp = opendir(".")) == NULL) {
2020 FILE_OP_ERROR(dir, "opendir");
2026 expire_time = hours * 60 * 60;
2028 while ((d = readdir(dp)) != NULL) {
2029 fileno = to_number(d->d_name);
2031 if (stat(d->d_name, &s) < 0) {
2032 FILE_OP_ERROR(d->d_name, "stat");
2035 if (S_ISDIR(s.st_mode))
2037 mtime = MAX(s.st_mtime, s.st_atime);
2038 if (now - mtime > expire_time) {
2039 if (unlink(d->d_name) < 0)
2040 FILE_OP_ERROR(d->d_name, "unlink");
2047 if (chdir(prev_dir) < 0) {
2048 FILE_OP_ERROR(prev_dir, "chdir");
2058 gint remove_dir_recursive(const gchar *dir)
2065 /* g_print("dir = %s\n", dir); */
2067 if (stat(dir, &s) < 0) {
2068 FILE_OP_ERROR(dir, "stat");
2069 if (ENOENT == errno) return 0;
2073 if (!S_ISDIR(s.st_mode)) {
2074 if (unlink(dir) < 0) {
2075 FILE_OP_ERROR(dir, "unlink");
2082 prev_dir = g_get_current_dir();
2083 /* g_print("prev_dir = %s\n", prev_dir); */
2085 if (!path_cmp(prev_dir, dir)) {
2087 if (chdir("..") < 0) {
2088 FILE_OP_ERROR(dir, "chdir");
2091 prev_dir = g_get_current_dir();
2094 if (chdir(dir) < 0) {
2095 FILE_OP_ERROR(dir, "chdir");
2100 if ((dp = opendir(".")) == NULL) {
2101 FILE_OP_ERROR(dir, "opendir");
2107 /* remove all files in the directory */
2108 while ((d = readdir(dp)) != NULL) {
2109 if (!strcmp(d->d_name, ".") ||
2110 !strcmp(d->d_name, ".."))
2113 /* g_print("removing %s\n", d->d_name); */
2115 if (dirent_is_directory(d)) {
2116 if (remove_dir_recursive(d->d_name) < 0) {
2117 g_warning("can't remove directory\n");
2121 if (unlink(d->d_name) < 0)
2122 FILE_OP_ERROR(d->d_name, "unlink");
2128 if (chdir(prev_dir) < 0) {
2129 FILE_OP_ERROR(prev_dir, "chdir");
2136 if (rmdir(dir) < 0) {
2137 FILE_OP_ERROR(dir, "rmdir");
2145 /* this seems to be slower than the stdio version... */
2146 gint copy_file(const gchar *src, const gchar *dest)
2148 gint src_fd, dest_fd;
2152 gchar *dest_bak = NULL;
2154 if ((src_fd = open(src, O_RDONLY)) < 0) {
2155 FILE_OP_ERROR(src, "open");
2159 if (is_file_exist(dest)) {
2160 dest_bak = g_strconcat(dest, ".bak", NULL);
2161 if (rename(dest, dest_bak) < 0) {
2162 FILE_OP_ERROR(dest, "rename");
2169 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2170 FILE_OP_ERROR(dest, "open");
2173 if (rename(dest_bak, dest) < 0)
2174 FILE_OP_ERROR(dest_bak, "rename");
2180 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2185 n_write = write(dest_fd, bufp, len);
2187 g_warning("writing to %s failed.\n", dest);
2192 if (rename(dest_bak, dest) < 0)
2193 FILE_OP_ERROR(dest_bak, "rename");
2206 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2207 g_warning("File copy from %s to %s failed.\n", src, dest);
2210 if (rename(dest_bak, dest) < 0)
2211 FILE_OP_ERROR(dest_bak, "rename");
2224 * Append src file body to the tail of dest file.
2225 * Now keep_backup has no effects.
2227 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2229 FILE *src_fp, *dest_fp;
2233 gboolean err = FALSE;
2235 if ((src_fp = fopen(src, "rb")) == NULL) {
2236 FILE_OP_ERROR(src, "fopen");
2240 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2241 FILE_OP_ERROR(dest, "fopen");
2246 if (change_file_mode_rw(dest_fp, dest) < 0) {
2247 FILE_OP_ERROR(dest, "chmod");
2248 g_warning("can't change file mode\n");
2251 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2252 if (n_read < sizeof(buf) && ferror(src_fp))
2254 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2255 g_warning("writing to %s failed.\n", dest);
2263 if (ferror(src_fp)) {
2264 FILE_OP_ERROR(src, "fread");
2268 if (fclose(dest_fp) == EOF) {
2269 FILE_OP_ERROR(dest, "fclose");
2281 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2283 FILE *src_fp, *dest_fp;
2286 gchar *dest_bak = NULL;
2287 gboolean err = FALSE;
2289 if ((src_fp = fopen(src, "rb")) == NULL) {
2290 FILE_OP_ERROR(src, "fopen");
2293 if (is_file_exist(dest)) {
2294 dest_bak = g_strconcat(dest, ".bak", NULL);
2295 if (rename(dest, dest_bak) < 0) {
2296 FILE_OP_ERROR(dest, "rename");
2303 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2304 FILE_OP_ERROR(dest, "fopen");
2307 if (rename(dest_bak, dest) < 0)
2308 FILE_OP_ERROR(dest_bak, "rename");
2314 if (change_file_mode_rw(dest_fp, dest) < 0) {
2315 FILE_OP_ERROR(dest, "chmod");
2316 g_warning("can't change file mode\n");
2319 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2320 if (n_read < sizeof(buf) && ferror(src_fp))
2322 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2323 g_warning("writing to %s failed.\n", dest);
2328 if (rename(dest_bak, dest) < 0)
2329 FILE_OP_ERROR(dest_bak, "rename");
2336 if (ferror(src_fp)) {
2337 FILE_OP_ERROR(src, "fread");
2341 if (fclose(dest_fp) == EOF) {
2342 FILE_OP_ERROR(dest, "fclose");
2349 if (rename(dest_bak, dest) < 0)
2350 FILE_OP_ERROR(dest_bak, "rename");
2356 if (keep_backup == FALSE && dest_bak)
2364 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2366 if (overwrite == FALSE && is_file_exist(dest)) {
2367 g_warning("move_file(): file %s already exists.", dest);
2371 if (rename(src, dest) == 0) return 0;
2373 if (EXDEV != errno) {
2374 FILE_OP_ERROR(src, "rename");
2378 if (copy_file(src, dest, FALSE) < 0) return -1;
2385 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2389 gint bytes_left, to_read;
2391 gboolean err = FALSE;
2393 if (fseek(fp, offset, SEEK_SET) < 0) {
2398 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2399 FILE_OP_ERROR(dest, "fopen");
2403 if (change_file_mode_rw(dest_fp, dest) < 0) {
2404 FILE_OP_ERROR(dest, "chmod");
2405 g_warning("can't change file mode\n");
2408 bytes_left = length;
2409 to_read = MIN(bytes_left, sizeof(buf));
2411 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2412 if (n_read < to_read && ferror(fp))
2414 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2415 g_warning("writing to %s failed.\n", dest);
2420 bytes_left -= n_read;
2421 if (bytes_left == 0)
2423 to_read = MIN(bytes_left, sizeof(buf));
2430 if (fclose(dest_fp) == EOF) {
2431 FILE_OP_ERROR(dest, "fclose");
2443 /* convert line endings into CRLF. If the last line doesn't end with
2444 * linebreak, add it.
2446 gchar *canonicalize_str(const gchar *str)
2452 for (p = str; *p != '\0'; ++p) {
2459 if (p == str || *(p - 1) != '\n')
2462 out = outp = g_malloc(new_len + 1);
2463 for (p = str; *p != '\0'; ++p) {
2470 if (p == str || *(p - 1) != '\n') {
2479 gint canonicalize_file(const gchar *src, const gchar *dest)
2481 FILE *src_fp, *dest_fp;
2482 gchar buf[BUFFSIZE];
2484 gboolean err = FALSE;
2485 gboolean last_linebreak = FALSE;
2487 if ((src_fp = fopen(src, "rb")) == NULL) {
2488 FILE_OP_ERROR(src, "fopen");
2492 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2493 FILE_OP_ERROR(dest, "fopen");
2498 if (change_file_mode_rw(dest_fp, dest) < 0) {
2499 FILE_OP_ERROR(dest, "chmod");
2500 g_warning("can't change file mode\n");
2503 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2507 if (len == 0) break;
2508 last_linebreak = FALSE;
2510 if (buf[len - 1] != '\n') {
2511 last_linebreak = TRUE;
2512 r = fputs(buf, dest_fp);
2513 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2514 r = fputs(buf, dest_fp);
2517 r = fwrite(buf, len - 1, 1, dest_fp);
2522 r = fputs("\r\n", dest_fp);
2526 g_warning("writing to %s failed.\n", dest);
2534 if (last_linebreak == TRUE) {
2535 if (fputs("\r\n", dest_fp) == EOF)
2539 if (ferror(src_fp)) {
2540 FILE_OP_ERROR(src, "fgets");
2544 if (fclose(dest_fp) == EOF) {
2545 FILE_OP_ERROR(dest, "fclose");
2557 gint canonicalize_file_replace(const gchar *file)
2561 tmp_file = get_tmp_file();
2563 if (canonicalize_file(file, tmp_file) < 0) {
2568 if (move_file(tmp_file, file, TRUE) < 0) {
2569 g_warning("can't replace %s .\n", file);
2579 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2581 FILE *src_fp, *dest_fp;
2582 gchar buf[BUFFSIZE];
2583 gboolean err = FALSE;
2585 if ((src_fp = fopen(src, "rb")) == NULL) {
2586 FILE_OP_ERROR(src, "fopen");
2590 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2591 FILE_OP_ERROR(dest, "fopen");
2596 if (change_file_mode_rw(dest_fp, dest) < 0) {
2597 FILE_OP_ERROR(dest, "chmod");
2598 g_warning("can't change file mode\n");
2601 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2603 if (fputs(buf, dest_fp) == EOF) {
2604 g_warning("writing to %s failed.\n", dest);
2612 if (ferror(src_fp)) {
2613 FILE_OP_ERROR(src, "fgets");
2617 if (fclose(dest_fp) == EOF) {
2618 FILE_OP_ERROR(dest, "fclose");
2630 gint uncanonicalize_file_replace(const gchar *file)
2634 tmp_file = get_tmp_file();
2636 if (uncanonicalize_file(file, tmp_file) < 0) {
2641 if (move_file(tmp_file, file, TRUE) < 0) {
2642 g_warning("can't replace %s .\n", file);
2652 gchar *normalize_newlines(const gchar *str)
2654 const gchar *p = str;
2657 out = outp = g_malloc(strlen(str) + 1);
2658 for (p = str; *p != '\0'; ++p) {
2660 if (*(p + 1) != '\n')
2671 gchar *get_outgoing_rfc2822_str(FILE *fp)
2673 gchar buf[BUFFSIZE];
2677 str = g_string_new(NULL);
2679 /* output header part */
2680 while (fgets(buf, sizeof(buf), fp) != NULL) {
2682 if (!g_strncasecmp(buf, "Bcc:", 4)) {
2689 else if (next != ' ' && next != '\t') {
2693 if (fgets(buf, sizeof(buf), fp) == NULL)
2697 g_string_append(str, buf);
2698 g_string_append(str, "\r\n");
2704 /* output body part */
2705 while (fgets(buf, sizeof(buf), fp) != NULL) {
2708 g_string_append_c(str, '.');
2709 g_string_append(str, buf);
2710 g_string_append(str, "\r\n");
2714 g_string_free(str, FALSE);
2720 * Create a new boundary in a way that it is very unlikely that this
2721 * will occur in the following text. It would be easy to ensure
2722 * uniqueness if everything is either quoted-printable or base64
2723 * encoded (note that conversion is allowed), but because MIME bodies
2724 * may be nested, it may happen that the same boundary has already
2725 * been used. We avoid scanning the message for conflicts and hope the
2728 * boundary := 0*69<bchars> bcharsnospace
2729 * bchars := bcharsnospace / " "
2730 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2731 * "+" / "_" / "," / "-" / "." /
2732 * "/" / ":" / "=" / "?"
2734 * some special characters removed because of buggy MTAs
2737 gchar *generate_mime_boundary(const gchar *prefix)
2739 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2740 "abcdefghijklmnopqrstuvwxyz"
2749 /* We make the boundary depend on the pid, so that all running
2750 * processes generate different values even when they have been
2751 * started within the same second and srandom(time(NULL)) has been
2752 * used. I can't see whether this is really an advantage but it
2753 * doesn't do any harm.
2755 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2756 buf_uniq[i] = tbl[(random() ^ pid) % (sizeof(tbl) - 1)];
2759 get_rfc822_date(buf_date, sizeof(buf_date));
2760 subst_char(buf_date, ' ', '_');
2761 subst_char(buf_date, ',', '_');
2762 subst_char(buf_date, ':', '_');
2764 return g_strdup_printf("%s=_%s_%s", prefix ? prefix : "Multipart",
2765 buf_date, buf_uniq);
2768 gint change_file_mode_rw(FILE *fp, const gchar *file)
2771 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2773 return chmod(file, S_IRUSR|S_IWUSR);
2777 FILE *my_tmpfile(void)
2780 const gchar suffix[] = ".XXXXXX";
2781 const gchar *tmpdir;
2783 const gchar *progname;
2789 tmpdir = get_tmp_dir();
2790 tmplen = strlen(tmpdir);
2791 progname = g_get_prgname();
2792 proglen = strlen(progname);
2793 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2796 memcpy(fname, tmpdir, tmplen);
2797 fname[tmplen] = G_DIR_SEPARATOR;
2798 memcpy(fname + tmplen + 1, progname, proglen);
2799 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2801 fd = mkstemp(fname);
2807 fp = fdopen(fd, "w+b");
2812 #endif /* HAVE_MKSTEMP */
2817 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2821 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2822 fd = mkstemp(*filename);
2824 return fdopen(fd, "w+");
2827 FILE *str_open_as_stream(const gchar *str)
2832 g_return_val_if_fail(str != NULL, NULL);
2836 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2841 if (len == 0) return fp;
2843 if (fwrite(str, len, 1, fp) != 1) {
2844 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2853 gint str_write_to_file(const gchar *str, const gchar *file)
2858 g_return_val_if_fail(str != NULL, -1);
2859 g_return_val_if_fail(file != NULL, -1);
2861 if ((fp = fopen(file, "wb")) == NULL) {
2862 FILE_OP_ERROR(file, "fopen");
2872 if (fwrite(str, len, 1, fp) != 1) {
2873 FILE_OP_ERROR(file, "fwrite");
2879 if (fclose(fp) == EOF) {
2880 FILE_OP_ERROR(file, "fclose");
2888 gchar *file_read_to_str(const gchar *file)
2893 g_return_val_if_fail(file != NULL, NULL);
2895 if ((fp = fopen(file, "rb")) == NULL) {
2896 FILE_OP_ERROR(file, "fopen");
2900 str = file_read_stream_to_str(fp);
2907 gchar *file_read_stream_to_str(FILE *fp)
2914 g_return_val_if_fail(fp != NULL, NULL);
2916 array = g_byte_array_new();
2918 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2919 if (n_read < sizeof(buf) && ferror(fp))
2921 g_byte_array_append(array, buf, n_read);
2925 FILE_OP_ERROR("file stream", "fread");
2926 g_byte_array_free(array, TRUE);
2931 g_byte_array_append(array, buf, 1);
2932 str = (gchar *)array->data;
2933 g_byte_array_free(array, FALSE);
2938 gint execute_async(gchar *const argv[])
2942 if ((pid = fork()) < 0) {
2947 if (pid == 0) { /* child process */
2950 if ((gch_pid = fork()) < 0) {
2955 if (gch_pid == 0) { /* grandchild process */
2956 execvp(argv[0], argv);
2965 waitpid(pid, NULL, 0);
2970 gint execute_sync(gchar *const argv[])
2974 if ((pid = fork()) < 0) {
2979 if (pid == 0) { /* child process */
2980 execvp(argv[0], argv);
2986 waitpid(pid, NULL, 0);
2991 gint execute_command_line(const gchar *cmdline, gboolean async)
2996 argv = strsplit_with_quote(cmdline, " ", 0);
2999 ret = execute_async(argv);
3001 ret = execute_sync(argv);
3007 gchar *get_command_output(const gchar *cmdline)
3009 gchar buf[BUFFSIZE];
3014 g_return_val_if_fail(cmdline != NULL, NULL);
3016 if ((fp = popen(cmdline, "r")) == NULL) {
3017 FILE_OP_ERROR(cmdline, "popen");
3021 str = g_string_new("");
3023 while (fgets(buf, sizeof(buf), fp) != NULL)
3024 g_string_append(str, buf);
3029 g_string_free(str, FALSE);
3034 static gint is_unchanged_uri_char(char c)
3046 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3052 for(i = 0; i < strlen(uri) ; i++) {
3053 if (is_unchanged_uri_char(uri[i])) {
3054 if (k + 2 >= bufsize)
3056 encoded_uri[k++] = uri[i];
3059 char * hexa = "0123456789ABCDEF";
3061 if (k + 4 >= bufsize)
3063 encoded_uri[k++] = '%';
3064 encoded_uri[k++] = hexa[uri[i] / 16];
3065 encoded_uri[k++] = hexa[uri[i] % 16];
3071 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
3074 static gint axtoi(const gchar *hexstr)
3076 gint hi, lo, result;
3079 if ('0' <= hi && hi <= '9') {
3082 if ('a' <= hi && hi <= 'f') {
3085 if ('A' <= hi && hi <= 'F') {
3090 if ('0' <= lo && lo <= '9') {
3093 if ('a' <= lo && lo <= 'f') {
3096 if ('A' <= lo && lo <= 'F') {
3099 result = lo + (16 * hi);
3104 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
3105 * plusses, and escape characters are used)
3108 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
3110 const gchar *encoded;
3113 encoded = encoded_uri;
3114 decoded = decoded_uri;
3117 if (*encoded == '%') {
3119 if (isxdigit(encoded[0])
3120 && isxdigit(encoded[1])) {
3121 *decoded = (gchar) axtoi(encoded);
3126 else if (*encoded == '+') {
3132 *decoded = *encoded;
3142 gint open_uri(const gchar *uri, const gchar *cmdline)
3144 gchar buf[BUFFSIZE];
3146 gchar encoded_uri[BUFFSIZE];
3148 g_return_val_if_fail(uri != NULL, -1);
3150 /* an option to choose whether to use encode_uri or not ? */
3151 encode_uri(encoded_uri, BUFFSIZE, uri);
3154 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3155 !strchr(p + 2, '%'))
3156 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3159 g_warning("Open URI command line is invalid: `%s'",
3161 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3164 execute_command_line(buf, TRUE);
3169 time_t remote_tzoffset_sec(const gchar *zone)
3171 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3177 time_t remoteoffset;
3179 strncpy(zone3, zone, 3);
3183 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3184 (c == '+' || c == '-')) {
3185 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3187 remoteoffset = -remoteoffset;
3188 } else if (!strncmp(zone, "UT" , 2) ||
3189 !strncmp(zone, "GMT", 2)) {
3191 } else if (strlen(zone3) == 3) {
3192 for (p = ustzstr; *p != '\0'; p += 3) {
3193 if (!strncasecmp(p, zone3, 3)) {
3194 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3195 remoteoffset = iustz * 3600;
3201 } else if (strlen(zone3) == 1) {
3203 case 'Z': remoteoffset = 0; break;
3204 case 'A': remoteoffset = -1; break;
3205 case 'B': remoteoffset = -2; break;
3206 case 'C': remoteoffset = -3; break;
3207 case 'D': remoteoffset = -4; break;
3208 case 'E': remoteoffset = -5; break;
3209 case 'F': remoteoffset = -6; break;
3210 case 'G': remoteoffset = -7; break;
3211 case 'H': remoteoffset = -8; break;
3212 case 'I': remoteoffset = -9; break;
3213 case 'K': remoteoffset = -10; break; /* J is not used */
3214 case 'L': remoteoffset = -11; break;
3215 case 'M': remoteoffset = -12; break;
3216 case 'N': remoteoffset = 1; break;
3217 case 'O': remoteoffset = 2; break;
3218 case 'P': remoteoffset = 3; break;
3219 case 'Q': remoteoffset = 4; break;
3220 case 'R': remoteoffset = 5; break;
3221 case 'S': remoteoffset = 6; break;
3222 case 'T': remoteoffset = 7; break;
3223 case 'U': remoteoffset = 8; break;
3224 case 'V': remoteoffset = 9; break;
3225 case 'W': remoteoffset = 10; break;
3226 case 'X': remoteoffset = 11; break;
3227 case 'Y': remoteoffset = 12; break;
3228 default: remoteoffset = 0; break;
3230 remoteoffset = remoteoffset * 3600;
3234 return remoteoffset;
3237 time_t tzoffset_sec(time_t *now)
3243 lt = localtime(now);
3245 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3247 if (lt->tm_year < gmt.tm_year)
3249 else if (lt->tm_year > gmt.tm_year)
3251 else if (lt->tm_yday < gmt.tm_yday)
3253 else if (lt->tm_yday > gmt.tm_yday)
3256 if (off >= 24 * 60) /* should be impossible */
3257 off = 23 * 60 + 59; /* if not, insert silly value */
3258 if (off <= -24 * 60)
3259 off = -(23 * 60 + 59);
3264 /* calculate timezone offset */
3265 gchar *tzoffset(time_t *now)
3267 static gchar offset_string[6];
3273 lt = localtime(now);
3275 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3277 if (lt->tm_year < gmt.tm_year)
3279 else if (lt->tm_year > gmt.tm_year)
3281 else if (lt->tm_yday < gmt.tm_yday)
3283 else if (lt->tm_yday > gmt.tm_yday)
3291 if (off >= 24 * 60) /* should be impossible */
3292 off = 23 * 60 + 59; /* if not, insert silly value */
3294 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3296 return offset_string;
3299 void get_rfc822_date(gchar *buf, gint len)
3303 gchar day[4], mon[4];
3304 gint dd, hh, mm, ss, yyyy;
3309 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3310 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3311 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3312 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3315 void debug_set_mode(gboolean mode)
3320 gboolean debug_get_mode(void)
3325 void debug_print_real(const gchar *format, ...)
3328 gchar buf[BUFFSIZE];
3330 if (!debug_mode) return;
3332 va_start(args, format);
3333 g_vsnprintf(buf, sizeof(buf), format, args);
3339 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3341 if (subject == NULL)
3344 subject += subject_get_prefix_length(subject);
3346 return g_hash_table_lookup(subject_table, subject);
3349 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3352 if (subject == NULL || *subject == 0)
3354 subject += subject_get_prefix_length(subject);
3355 g_hash_table_insert(subject_table, subject, data);
3358 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3360 if (subject == NULL)
3363 subject += subject_get_prefix_length(subject);
3364 g_hash_table_remove(subject_table, subject);
3368 *\brief Check if a string is prefixed with known (combinations)
3369 * of prefixes. The function assumes that each prefix
3370 * is terminated by zero or exactly _one_ space.
3372 *\param str String to check for a prefixes
3374 *\return int Number of chars in the prefix that should be skipped
3375 * for a "clean" subject line. If no prefix was found, 0
3378 int subject_get_prefix_length(const gchar *subject)
3380 /*!< Array with allowable reply prefixes regexps. */
3381 static const gchar * const prefixes[] = {
3382 "Re\\:", /* "Re:" */
3383 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3384 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3385 "Aw\\:", /* "Aw:" (German) */
3386 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3387 "Res\\:", /* "Res:" (Brazilian Outlook) */
3388 "Fw\\:", /* "Fw:" Forward */
3389 "Enc\\:" /* "Enc:" Forward (Brazilian Outlook) */
3392 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3395 static regex_t regex;
3396 static gboolean init_;
3398 if (!subject) return 0;
3399 if (!*subject) return 0;
3402 GString *s = g_string_new("");
3404 for (n = 0; n < PREFIXES; n++)
3405 /* Terminate each prefix regexpression by a
3406 * "\ ?" (zero or ONE space), and OR them */
3407 g_string_sprintfa(s, "(%s\\ ?)%s",
3412 g_string_prepend(s, "(");
3413 g_string_append(s, ")+"); /* match at least once */
3414 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3417 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3418 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3419 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3420 debug_print("Error compiling regexp %s\n", s->str);
3421 g_string_free(s, TRUE);
3425 g_string_free(s, TRUE);
3429 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3435 /* allow Mutt-like patterns in quick search */
3436 gchar *expand_search_string(const gchar *search_string)
3439 gchar term_char, save_char;
3440 gchar *cmd_start, *cmd_end;
3441 GString *matcherstr;
3442 gchar *returnstr = NULL;
3444 gboolean casesens, dontmatch;
3445 /* list of allowed pattern abbreviations */
3447 gchar *abbreviated; /* abbreviation */
3448 gchar *command; /* actual matcher command */
3449 gint numparams; /* number of params for cmd */
3450 gboolean qualifier; /* do we append regexpcase */
3451 gboolean quotes; /* do we need quotes */
3454 { "a", "all", 0, FALSE, FALSE },
3455 { "ag", "age_greater", 1, FALSE, FALSE },
3456 { "al", "age_lower", 1, FALSE, FALSE },
3457 { "b", "body_part", 1, TRUE, TRUE },
3458 { "B", "message", 1, TRUE, TRUE },
3459 { "c", "cc", 1, TRUE, TRUE },
3460 { "C", "to_or_cc", 1, TRUE, TRUE },
3461 { "D", "deleted", 0, FALSE, FALSE },
3462 { "e", "header \"Sender\"", 1, TRUE, TRUE },
3463 { "E", "execute", 1, FALSE, TRUE },
3464 { "f", "from", 1, TRUE, TRUE },
3465 { "F", "forwarded", 0, FALSE, FALSE },
3466 { "h", "headers_part", 1, TRUE, TRUE },
3467 { "i", "header \"Message-Id\"", 1, TRUE, TRUE },
3468 { "I", "inreplyto", 1, TRUE, TRUE },
3469 { "L", "locked", 0, FALSE, FALSE },
3470 { "n", "newsgroups", 1, TRUE, TRUE },
3471 { "N", "new", 0, FALSE, FALSE },
3472 { "O", "~new", 0, FALSE, FALSE },
3473 { "r", "replied", 0, FALSE, FALSE },
3474 { "R", "~unread", 0, FALSE, FALSE },
3475 { "s", "subject", 1, TRUE, TRUE },
3476 { "se", "score_equal", 1, FALSE, FALSE },
3477 { "sg", "score_greater", 1, FALSE, FALSE },
3478 { "sl", "score_lower", 1, FALSE, FALSE },
3479 { "Se", "size_equal", 1, FALSE, FALSE },
3480 { "Sg", "size_greater", 1, FALSE, FALSE },
3481 { "Ss", "size_smaller", 1, FALSE, FALSE },
3482 { "t", "to", 1, TRUE, TRUE },
3483 { "T", "marked", 0, FALSE, FALSE },
3484 { "U", "unread", 0, FALSE, FALSE },
3485 { "x", "header \"References\"", 1, TRUE, TRUE },
3486 { "y", "header \"X-Label\"", 1, TRUE, TRUE },
3487 { "&", "&", 0, FALSE, FALSE },
3488 { "|", "|", 0, FALSE, FALSE },
3489 { NULL, NULL, 0, FALSE, FALSE }
3492 if (search_string == NULL)
3495 copy_str = g_strdup(search_string);
3497 /* if it's a full command don't process it so users
3498 can still do something like from regexpcase "foo" */
3499 for (i = 0; cmds[i].command; i++) {
3500 const gchar *tmp_search_string = search_string;
3501 cmd_start = cmds[i].command;
3502 /* allow logical NOT */
3503 if (*tmp_search_string == '~')
3504 tmp_search_string++;
3505 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3508 if (cmds[i].command)
3511 matcherstr = g_string_sized_new(16);
3512 cmd_start = cmd_end = copy_str;
3513 while (cmd_end && *cmd_end) {
3514 /* skip all white spaces */
3515 while (*cmd_end && isspace(*cmd_end))
3518 /* extract a command */
3519 while (*cmd_end && !isspace(*cmd_end))
3522 /* save character */
3523 save_char = *cmd_end;
3529 /* ~ and ! mean logical NOT */
3530 if (*cmd_start == '~' || *cmd_start == '!')
3535 /* % means case sensitive match */
3536 if (*cmd_start == '%')
3542 /* find matching abbreviation */
3543 for (i = 0; cmds[i].command; i++) {
3544 if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3545 /* restore character */
3546 *cmd_end = save_char;
3549 if (matcherstr->len > 0) {
3550 g_string_append(matcherstr, " ");
3553 g_string_append(matcherstr, "~");
3554 g_string_append(matcherstr, cmds[i].command);
3555 g_string_append(matcherstr, " ");
3557 /* stop if no params required */
3558 if (cmds[i].numparams == 0)
3561 /* extract a parameter, allow quotes */
3563 cmd_start = cmd_end;
3564 if (*cmd_start == '"') {
3571 /* extract actual parameter */
3572 while ((*cmd_end) && (*cmd_end != term_char))
3575 if (*cmd_end && (*cmd_end != term_char))
3578 if (*cmd_end == '"')
3581 save_char = *cmd_end;
3584 if (cmds[i].qualifier) {
3586 g_string_append(matcherstr, "regexp ");
3588 g_string_append(matcherstr, "regexpcase ");
3591 /* do we need to add quotes ? */
3592 if (cmds[i].quotes && term_char != '"')
3593 g_string_append(matcherstr, "\"");
3595 /* copy actual parameter */
3596 g_string_append(matcherstr, cmd_start);
3598 /* do we need to add quotes ? */
3599 if (cmds[i].quotes && term_char != '"')
3600 g_string_append(matcherstr, "\"");
3602 /* restore original character */
3603 *cmd_end = save_char;
3611 cmd_start = cmd_end;
3616 returnstr = matcherstr->str;
3617 g_string_free(matcherstr, FALSE);
3621 guint g_stricase_hash(gconstpointer gptr)
3623 guint hash_result = 0;
3626 for (str = gptr; str && *str; str++) {
3627 if (isupper(*str)) hash_result += (*str + ' ');
3628 else hash_result += *str;
3634 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3636 const char *str1 = gptr1;
3637 const char *str2 = gptr2;
3639 return !strcasecmp(str1, str2);
3642 gint g_int_compare(gconstpointer a, gconstpointer b)
3644 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3647 gchar *generate_msgid(const gchar *address, gchar *buf, gint len)
3649 /* steal from compose.c::compose_generate_msgid() */
3657 if (address && *address) {
3658 if (strchr(address, '@'))
3659 addr = g_strdup(address);
3661 addr = g_strconcat(address, "@", get_domain_name(), NULL);
3663 addr = g_strconcat(g_get_user_name(), "@", get_domain_name(),
3666 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x.%s",
3667 lt->tm_year + 1900, lt->tm_mon + 1,
3668 lt->tm_mday, lt->tm_hour,
3669 lt->tm_min, lt->tm_sec,
3670 (guint)random(), addr);
3678 quote_cmd_argument()
3680 return a quoted string safely usable in argument of a command.
3682 code is extracted and adapted from etPan! project -- DINH V. HoĆ .
3685 gint quote_cmd_argument(gchar * result, guint size,
3695 for(p = path ; * p != '\0' ; p ++) {
3697 if (isalnum(* p) || (* p == '/')) {
3698 if (remaining > 0) {
3704 result[size - 1] = '\0';
3709 if (remaining >= 2) {
3717 result[size - 1] = '\0';
3722 if (remaining > 0) {
3726 result[size - 1] = '\0';