2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2016 Hiroyuki Yamamoto & The Claws Mail Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 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, see <http://www.gnu.org/licenses/>.
18 * The code of the g_utf8_substring function below is owned by
19 * Matthias Clasen <matthiasc@src.gnome.org>/<mclasen@redhat.com>
20 * and is got from GLIB 2.30: https://git.gnome.org/browse/glib/commit/
21 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
23 * GLib 2.30 is licensed under GPL v2 or later and:
24 * Copyright (C) 1999 Tom Tromey
25 * Copyright (C) 2000 Red Hat, Inc.
27 * https://git.gnome.org/browse/glib/tree/glib/gutf8.c
28 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
33 #include "claws-features.h"
41 #include <glib/gi18n.h>
51 #include <sys/param.h>
53 #include <sys/socket.h>
56 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
64 #include <sys/types.h>
66 # include <sys/wait.h>
73 #include <sys/utsname.h>
86 #include "../codeconv.h"
91 static gboolean debug_mode = FALSE;
93 #if !GLIB_CHECK_VERSION(2, 26, 0)
94 guchar *g_base64_decode_wa(const gchar *text, gsize *out_len)
101 input_length = strlen(text);
103 ret = g_malloc0((input_length / 4) * 3 + 1);
105 *out_len = g_base64_decode_step(text, input_length, ret, &state, &save);
111 /* Return true if we are running as root. This function should beused
112 instead of getuid () == 0. */
113 gboolean superuser_p (void)
116 return w32_is_administrator ();
122 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
124 #if GLIB_CHECK_VERSION(2, 34, 0)
125 return g_slist_copy_deep(list, func, NULL);
127 GSList *res = g_slist_copy(list);
130 walk->data = func(walk->data, NULL);
137 void list_free_strings(GList *list)
139 list = g_list_first(list);
141 while (list != NULL) {
147 void slist_free_strings(GSList *list)
149 while (list != NULL) {
155 void slist_free_strings_full(GSList *list)
157 #if GLIB_CHECK_VERSION(2,28,0)
158 g_slist_free_full(list, (GDestroyNotify)g_free);
160 g_slist_foreach(list, (GFunc)g_free, NULL);
165 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
170 void hash_free_strings(GHashTable *table)
172 g_hash_table_foreach(table, hash_free_strings_func, NULL);
175 gint str_case_equal(gconstpointer v, gconstpointer v2)
177 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
180 guint str_case_hash(gconstpointer key)
182 const gchar *p = key;
186 h = g_ascii_tolower(h);
187 for (p += 1; *p != '\0'; p++)
188 h = (h << 5) - h + g_ascii_tolower(*p);
194 void ptr_array_free_strings(GPtrArray *array)
199 cm_return_if_fail(array != NULL);
201 for (i = 0; i < array->len; i++) {
202 str = g_ptr_array_index(array, i);
207 gint to_number(const gchar *nstr)
209 register const gchar *p;
211 if (*nstr == '\0') return -1;
213 for (p = nstr; *p != '\0'; p++)
214 if (!g_ascii_isdigit(*p)) return -1;
219 /* convert integer into string,
220 nstr must be not lower than 11 characters length */
221 gchar *itos_buf(gchar *nstr, gint n)
223 g_snprintf(nstr, 11, "%d", n);
227 /* convert integer into string */
230 static gchar nstr[11];
232 return itos_buf(nstr, n);
235 #define divide(num,divisor,i,d) \
237 i = num >> divisor; \
238 d = num & ((1<<divisor)-1); \
239 d = (d*100) >> divisor; \
244 * \brief Convert a given size in bytes in a human-readable string
246 * \param size The size expressed in bytes to convert in string
247 * \return The string that respresents the size in an human-readable way
249 gchar *to_human_readable(goffset size)
251 static gchar str[14];
252 static gchar *b_format = NULL, *kb_format = NULL,
253 *mb_format = NULL, *gb_format = NULL;
254 register int t = 0, r = 0;
255 if (b_format == NULL) {
257 kb_format = _("%d.%02dKB");
258 mb_format = _("%d.%02dMB");
259 gb_format = _("%.2fGB");
262 if (size < (goffset)1024) {
263 g_snprintf(str, sizeof(str), b_format, (gint)size);
265 } else if (size >> 10 < (goffset)1024) {
266 divide(size, 10, t, r);
267 g_snprintf(str, sizeof(str), kb_format, t, r);
269 } else if (size >> 20 < (goffset)1024) {
270 divide(size, 20, t, r);
271 g_snprintf(str, sizeof(str), mb_format, t, r);
274 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
279 /* strcmp with NULL-checking */
280 gint strcmp2(const gchar *s1, const gchar *s2)
282 if (s1 == NULL || s2 == NULL)
285 return strcmp(s1, s2);
287 /* strstr with NULL-checking */
288 gchar *strstr2(const gchar *s1, const gchar *s2)
290 if (s1 == NULL || s2 == NULL)
293 return strstr(s1, s2);
296 gint path_cmp(const gchar *s1, const gchar *s2)
301 gchar *s1buf, *s2buf;
304 if (s1 == NULL || s2 == NULL) return -1;
305 if (*s1 == '\0' || *s2 == '\0') return -1;
308 s1buf = g_strdup (s1);
309 s2buf = g_strdup (s2);
310 subst_char (s1buf, '/', G_DIR_SEPARATOR);
311 subst_char (s2buf, '/', G_DIR_SEPARATOR);
314 #endif /* !G_OS_WIN32 */
319 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
320 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
322 rc = strncmp(s1, s2, MAX(len1, len2));
326 #endif /* !G_OS_WIN32 */
330 /* remove trailing return code */
331 gchar *strretchomp(gchar *str)
335 if (!*str) return str;
337 for (s = str + strlen(str) - 1;
338 s >= str && (*s == '\n' || *s == '\r');
345 /* remove trailing character */
346 gchar *strtailchomp(gchar *str, gchar tail_char)
350 if (!*str) return str;
351 if (tail_char == '\0') return str;
353 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
359 /* remove CR (carriage return) */
360 gchar *strcrchomp(gchar *str)
364 if (!*str) return str;
366 s = str + strlen(str) - 1;
367 if (*s == '\n' && s > str && *(s - 1) == '\r') {
375 gint file_strip_crs(const gchar *file)
377 FILE *fp = NULL, *outfp = NULL;
379 gchar *out = get_tmp_file();
383 fp = g_fopen(file, "rb");
387 outfp = g_fopen(out, "wb");
393 while (fgets(buf, sizeof (buf), fp) != NULL) {
395 if (fputs(buf, outfp) == EOF) {
403 if (fclose(outfp) == EOF) {
407 if (move_file(out, file, TRUE) < 0)
419 /* Similar to `strstr' but this function ignores the case of both strings. */
420 gchar *strcasestr(const gchar *haystack, const gchar *needle)
422 size_t haystack_len = strlen(haystack);
424 return strncasestr(haystack, haystack_len, needle);
427 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
429 register size_t needle_len;
431 needle_len = strlen(needle);
433 if (haystack_len < needle_len || needle_len == 0)
436 while (haystack_len >= needle_len) {
437 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
438 return (gchar *)haystack;
448 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
449 gconstpointer needle, size_t needlelen)
451 const gchar *haystack_ = (const gchar *)haystack;
452 const gchar *needle_ = (const gchar *)needle;
453 const gchar *haystack_cur = (const gchar *)haystack;
454 size_t haystack_left = haystacklen;
457 return memchr(haystack_, *needle_, haystacklen);
459 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
461 if (haystacklen - (haystack_cur - haystack_) < needlelen)
463 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
464 return (gpointer)haystack_cur;
467 haystack_left = haystacklen - (haystack_cur - haystack_);
474 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
475 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
477 register const gchar *s = src;
478 register gchar *d = dest;
488 /* Examine if next block is non-ASCII string */
489 gboolean is_next_nonascii(const gchar *s)
493 /* skip head space */
494 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
496 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
497 if (*(guchar *)p > 127 || *(guchar *)p < 32)
504 gint get_next_word_len(const gchar *s)
508 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
514 static void trim_subject_for_compare(gchar *str)
518 eliminate_parenthesis(str, '[', ']');
519 eliminate_parenthesis(str, '(', ')');
522 srcp = str + subject_get_prefix_length(str);
524 memmove(str, srcp, strlen(srcp) + 1);
527 static void trim_subject_for_sort(gchar *str)
533 srcp = str + subject_get_prefix_length(str);
535 memmove(str, srcp, strlen(srcp) + 1);
538 /* compare subjects */
539 gint subject_compare(const gchar *s1, const gchar *s2)
543 if (!s1 || !s2) return -1;
544 if (!*s1 || !*s2) return -1;
546 Xstrdup_a(str1, s1, return -1);
547 Xstrdup_a(str2, s2, return -1);
549 trim_subject_for_compare(str1);
550 trim_subject_for_compare(str2);
552 if (!*str1 || !*str2) return -1;
554 return strcmp(str1, str2);
557 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
561 if (!s1 || !s2) return -1;
563 Xstrdup_a(str1, s1, return -1);
564 Xstrdup_a(str2, s2, return -1);
566 trim_subject_for_sort(str1);
567 trim_subject_for_sort(str2);
569 return g_utf8_collate(str1, str2);
572 void trim_subject(gchar *str)
574 register gchar *srcp;
580 srcp = str + subject_get_prefix_length(str);
585 } else if (*srcp == '(') {
597 else if (*srcp == cl)
604 while (g_ascii_isspace(*srcp)) srcp++;
605 memmove(str, srcp, strlen(srcp) + 1);
608 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
610 register gchar *srcp, *destp;
615 while ((destp = strchr(destp, op))) {
621 else if (*srcp == cl)
627 while (g_ascii_isspace(*srcp)) srcp++;
628 memmove(destp, srcp, strlen(srcp) + 1);
632 void extract_parenthesis(gchar *str, gchar op, gchar cl)
634 register gchar *srcp, *destp;
639 while ((srcp = strchr(destp, op))) {
642 memmove(destp, srcp + 1, strlen(srcp));
647 else if (*destp == cl)
659 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
662 register gchar *srcp, *destp;
664 gboolean in_quote = FALSE;
668 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
671 memmove(destp, srcp + 1, strlen(srcp));
674 if (*destp == op && !in_quote)
676 else if (*destp == cl && !in_quote)
678 else if (*destp == quote_chr)
690 void extract_quote(gchar *str, gchar quote_chr)
694 if ((str = strchr(str, quote_chr))) {
696 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
697 memmove(p - 1, p, strlen(p) + 1);
702 memmove(str, str + 1, p - str);
707 /* Returns a newly allocated string with all quote_chr not at the beginning
708 or the end of str escaped with '\' or the given str if not required. */
709 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
711 register gchar *p, *q;
715 if (str == NULL || *str == '\0')
718 /* search for unescaped quote_chr */
723 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
727 if (!k) /* nothing to escape */
730 /* unescaped quote_chr found */
731 qstr = g_malloc(l + k + 1);
734 if (*p == quote_chr) {
739 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
748 void eliminate_address_comment(gchar *str)
750 register gchar *srcp, *destp;
755 while ((destp = strchr(destp, '"'))) {
756 if ((srcp = strchr(destp + 1, '"'))) {
761 while (g_ascii_isspace(*srcp)) srcp++;
762 memmove(destp, srcp, strlen(srcp) + 1);
772 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
778 else if (*srcp == ')')
784 while (g_ascii_isspace(*srcp)) srcp++;
785 memmove(destp, srcp, strlen(srcp) + 1);
789 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
791 gboolean in_quote = FALSE;
794 if (*str == c && !in_quote)
796 if (*str == quote_chr)
804 void extract_address(gchar *str)
806 cm_return_if_fail(str != NULL);
807 eliminate_address_comment(str);
808 if (strchr_with_skip_quote(str, '"', '<'))
809 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
813 void extract_list_id_str(gchar *str)
815 if (strchr_with_skip_quote(str, '"', '<'))
816 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
820 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
825 if (!str) return addr_list;
827 Xstrdup_a(work, str, return addr_list);
830 eliminate_address_comment(work);
833 while (workp && *workp) {
836 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
842 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
843 extract_parenthesis_with_skip_quote
844 (workp, '"', '<', '>');
848 addr_list = g_slist_append(addr_list, g_strdup(workp));
856 GSList *address_list_append(GSList *addr_list, const gchar *str)
858 return address_list_append_real(addr_list, str, TRUE);
861 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
863 return address_list_append_real(addr_list, str, FALSE);
866 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
870 if (!str) return msgid_list;
873 while (strp && *strp) {
874 const gchar *start, *end;
877 if ((start = strchr(strp, '<')) != NULL) {
878 end = strchr(start + 1, '>');
883 msgid = g_strndup(start + 1, end - start - 1);
886 msgid_list = g_slist_prepend(msgid_list, msgid);
896 GSList *references_list_append(GSList *msgid_list, const gchar *str)
900 list = references_list_prepend(NULL, str);
901 list = g_slist_reverse(list);
902 msgid_list = g_slist_concat(msgid_list, list);
907 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
912 if (!str) return group_list;
914 Xstrdup_a(work, str, return group_list);
918 while (workp && *workp) {
921 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
929 group_list = g_slist_append(group_list,
938 GList *add_history(GList *list, const gchar *str)
943 cm_return_val_if_fail(str != NULL, list);
945 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
948 list = g_list_remove(list, old->data);
950 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
953 last = g_list_last(list);
956 list = g_list_remove(list, last->data);
961 list = g_list_prepend(list, g_strdup(str));
966 void remove_return(gchar *str)
968 register gchar *p = str;
971 if (*p == '\n' || *p == '\r')
972 memmove(p, p + 1, strlen(p));
978 void remove_space(gchar *str)
980 register gchar *p = str;
985 while (g_ascii_isspace(*(p + spc)))
988 memmove(p, p + spc, strlen(p + spc) + 1);
994 void unfold_line(gchar *str)
1000 ch = str; /* iterator for source string */
1003 c = g_utf8_get_char_validated(ch, -1);
1005 if (c == (gunichar)-1 || c == (gunichar)-2) {
1006 /* non-unicode byte, move past it */
1011 len = g_unichar_to_utf8(c, NULL);
1013 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
1014 g_unichar_isspace(c)) {
1015 /* replace anything bad or whitespacey with a single space */
1019 /* move rest of the string forwards, since we just replaced
1020 * a multi-byte sequence with one byte */
1021 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
1024 /* A valid unicode character, copy it. */
1030 void subst_char(gchar *str, gchar orig, gchar subst)
1032 register gchar *p = str;
1041 void subst_chars(gchar *str, gchar *orig, gchar subst)
1043 register gchar *p = str;
1046 if (strchr(orig, *p) != NULL)
1052 void subst_for_filename(gchar *str)
1057 subst_chars(str, "\t\r\n\\/*:", '_');
1059 subst_chars(str, "\t\r\n\\/*", '_');
1063 void subst_for_shellsafe_filename(gchar *str)
1067 subst_for_filename(str);
1068 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1071 gboolean is_ascii_str(const gchar *str)
1073 const guchar *p = (const guchar *)str;
1075 while (*p != '\0') {
1076 if (*p != '\t' && *p != ' ' &&
1077 *p != '\r' && *p != '\n' &&
1078 (*p < 32 || *p >= 127))
1086 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1088 gchar * position = NULL;
1089 gchar * tmp_pos = NULL;
1092 if (str == NULL || quote_chars == NULL)
1095 for (i = 0; i < strlen(quote_chars); i++) {
1096 tmp_pos = strrchr (str, quote_chars[i]);
1098 || (tmp_pos != NULL && position <= tmp_pos) )
1104 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1106 const gchar *first_pos;
1107 const gchar *last_pos;
1108 const gchar *p = str;
1109 gint quote_level = -1;
1111 /* speed up line processing by only searching to the last '>' */
1112 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1113 /* skip a line if it contains a '<' before the initial '>' */
1114 if (memchr(str, '<', first_pos - str) != NULL)
1116 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1120 while (p <= last_pos) {
1121 while (p < last_pos) {
1122 if (g_ascii_isspace(*p))
1128 if (strchr(quote_chars, *p))
1130 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1131 /* any characters are allowed except '-','<' and space */
1132 while (*p != '-' && *p != '<'
1133 && !strchr(quote_chars, *p)
1134 && !g_ascii_isspace(*p)
1137 if (strchr(quote_chars, *p))
1149 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1151 const gchar *p = str, *q;
1152 gint cur_line = 0, len;
1154 while ((q = strchr(p, '\n')) != NULL) {
1156 if (len > max_chars) {
1166 if (len > max_chars) {
1175 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1177 gchar * position = NULL;
1178 gchar * tmp_pos = NULL;
1181 if (str == NULL || quote_chars == NULL)
1184 for (i = 0; i < strlen(quote_chars); i++) {
1185 tmp_pos = strchr (str, quote_chars[i]);
1187 || (tmp_pos != NULL && position >= tmp_pos) )
1193 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1195 register guint haystack_len, needle_len;
1196 gboolean in_squote = FALSE, in_dquote = FALSE;
1198 haystack_len = strlen(haystack);
1199 needle_len = strlen(needle);
1201 if (haystack_len < needle_len || needle_len == 0)
1204 while (haystack_len >= needle_len) {
1205 if (!in_squote && !in_dquote &&
1206 !strncmp(haystack, needle, needle_len))
1207 return (gchar *)haystack;
1209 /* 'foo"bar"' -> foo"bar"
1210 "foo'bar'" -> foo'bar' */
1211 if (*haystack == '\'') {
1214 else if (!in_dquote)
1216 } else if (*haystack == '\"') {
1219 else if (!in_squote)
1221 } else if (*haystack == '\\') {
1233 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1236 GSList *string_list = NULL, *slist;
1237 gchar **str_array, *s, *new_str;
1238 guint i, n = 1, len;
1240 cm_return_val_if_fail(str != NULL, NULL);
1241 cm_return_val_if_fail(delim != NULL, NULL);
1244 max_tokens = G_MAXINT;
1246 s = strstr_with_skip_quote(str, delim);
1248 guint delimiter_len = strlen(delim);
1252 new_str = g_strndup(str, len);
1254 if (new_str[0] == '\'' || new_str[0] == '\"') {
1255 if (new_str[len - 1] == new_str[0]) {
1256 new_str[len - 1] = '\0';
1257 memmove(new_str, new_str + 1, len - 1);
1260 string_list = g_slist_prepend(string_list, new_str);
1262 str = s + delimiter_len;
1263 s = strstr_with_skip_quote(str, delim);
1264 } while (--max_tokens && s);
1268 new_str = g_strdup(str);
1269 if (new_str[0] == '\'' || new_str[0] == '\"') {
1271 if (new_str[len - 1] == new_str[0]) {
1272 new_str[len - 1] = '\0';
1273 memmove(new_str, new_str + 1, len - 1);
1276 string_list = g_slist_prepend(string_list, new_str);
1280 str_array = g_new(gchar*, n);
1284 str_array[i--] = NULL;
1285 for (slist = string_list; slist; slist = slist->next)
1286 str_array[i--] = slist->data;
1288 g_slist_free(string_list);
1293 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1295 gchar *abbrev_group;
1297 const gchar *p = group;
1300 cm_return_val_if_fail(group != NULL, NULL);
1302 last = group + strlen(group);
1303 abbrev_group = ap = g_malloc(strlen(group) + 1);
1308 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1310 while (*p != '.') p++;
1313 return abbrev_group;
1318 return abbrev_group;
1321 gchar *trim_string(const gchar *str, gint len)
1323 const gchar *p = str;
1328 if (!str) return NULL;
1329 if (strlen(str) <= len)
1330 return g_strdup(str);
1331 if (g_utf8_validate(str, -1, NULL) == FALSE)
1332 return g_strdup(str);
1334 while (*p != '\0') {
1335 mb_len = g_utf8_skip[*(guchar *)p];
1338 else if (new_len + mb_len > len)
1345 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1346 return g_strconcat(new_str, "...", NULL);
1349 GList *uri_list_extract_filenames(const gchar *uri_list)
1351 GList *result = NULL;
1353 gchar *escaped_utf8uri;
1359 while (g_ascii_isspace(*p)) p++;
1360 if (!strncmp(p, "file:", 5)) {
1363 while (*q && *q != '\n' && *q != '\r') q++;
1366 gchar *file, *locale_file = NULL;
1368 while (q > p && g_ascii_isspace(*q))
1370 Xalloca(escaped_utf8uri, q - p + 2,
1372 Xalloca(file, q - p + 2,
1375 strncpy(escaped_utf8uri, p, q - p + 1);
1376 escaped_utf8uri[q - p + 1] = '\0';
1377 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1379 * g_filename_from_uri() rejects escaped/locale encoded uri
1380 * string which come from Nautilus.
1383 if (g_utf8_validate(file, -1, NULL))
1385 = conv_codeset_strdup(
1388 conv_get_locale_charset_str());
1390 locale_file = g_strdup(file + 5);
1392 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1394 result = g_list_append(result, locale_file);
1398 p = strchr(p, '\n');
1405 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1408 static gint axtoi(const gchar *hexstr)
1410 gint hi, lo, result;
1413 if ('0' <= hi && hi <= '9') {
1416 if ('a' <= hi && hi <= 'f') {
1419 if ('A' <= hi && hi <= 'F') {
1424 if ('0' <= lo && lo <= '9') {
1427 if ('a' <= lo && lo <= 'f') {
1430 if ('A' <= lo && lo <= 'F') {
1433 result = lo + (16 * hi);
1437 gboolean is_uri_string(const gchar *str)
1439 while (str && *str && g_ascii_isspace(*str))
1441 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1442 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1443 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1444 g_ascii_strncasecmp(str, "www.", 4) == 0);
1447 gchar *get_uri_path(const gchar *uri)
1449 while (uri && *uri && g_ascii_isspace(*uri))
1451 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1452 return (gchar *)(uri + 7);
1453 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1454 return (gchar *)(uri + 8);
1455 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1456 return (gchar *)(uri + 6);
1458 return (gchar *)uri;
1461 gint get_uri_len(const gchar *str)
1465 if (is_uri_string(str)) {
1466 for (p = str; *p != '\0'; p++) {
1467 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1476 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1477 * plusses, and escape characters are used)
1479 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1481 gchar *dec = decoded_uri;
1482 const gchar *enc = encoded_uri;
1487 if (isxdigit((guchar)enc[0]) &&
1488 isxdigit((guchar)enc[1])) {
1494 if (with_plus && *enc == '+')
1506 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1508 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1511 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1513 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1514 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1518 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1519 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1523 const gchar *forbidden_uris[] = { ".gnupg/",
1529 gint num_attach = 0;
1530 gchar **my_att = NULL;
1532 Xstrdup_a(tmp_mailto, mailto, return -1);
1534 if (!strncmp(tmp_mailto, "mailto:", 7))
1537 p = strchr(tmp_mailto, '?');
1544 *to = decode_uri_gdup(tmp_mailto);
1546 my_att = g_malloc(sizeof(char *));
1550 gchar *field, *value;
1567 if (*value == '\0') continue;
1569 if (from && !g_ascii_strcasecmp(field, "from")) {
1571 *from = decode_uri_gdup(value);
1573 gchar *tmp = decode_uri_gdup(value);
1574 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1578 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1580 *cc = decode_uri_gdup(value);
1582 gchar *tmp = decode_uri_gdup(value);
1583 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1587 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1589 *bcc = decode_uri_gdup(value);
1591 gchar *tmp = decode_uri_gdup(value);
1592 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1596 } else if (subject && !*subject &&
1597 !g_ascii_strcasecmp(field, "subject")) {
1598 *subject = decode_uri_gdup(value);
1599 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1600 *body = decode_uri_gdup(value);
1601 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1602 gchar *tmp = decode_uri_gdup(value);
1603 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1604 g_warning("couldn't set insert file '%s' in body", value);
1607 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1609 gchar *tmp = decode_uri_gdup(value);
1610 for (; forbidden_uris[i]; i++) {
1611 if (strstr(tmp, forbidden_uris[i])) {
1612 g_print("Refusing to attach '%s', potential private data leak\n",
1619 /* attach is correct */
1621 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1622 my_att[num_attach-1] = tmp;
1623 my_att[num_attach] = NULL;
1625 } else if (inreplyto && !*inreplyto &&
1626 !g_ascii_strcasecmp(field, "in-reply-to")) {
1627 *inreplyto = decode_uri_gdup(value);
1638 #include <windows.h>
1639 #ifndef CSIDL_APPDATA
1640 #define CSIDL_APPDATA 0x001a
1642 #ifndef CSIDL_LOCAL_APPDATA
1643 #define CSIDL_LOCAL_APPDATA 0x001c
1645 #ifndef CSIDL_FLAG_CREATE
1646 #define CSIDL_FLAG_CREATE 0x8000
1648 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1652 w32_strerror (int w32_errno)
1654 static char strerr[256];
1655 int ec = (int)GetLastError ();
1659 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1660 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1661 strerr, DIM (strerr)-1, NULL);
1665 static __inline__ void *
1666 dlopen (const char * name, int flag)
1668 void * hd = LoadLibrary (name);
1672 static __inline__ void *
1673 dlsym (void * hd, const char * sym)
1677 void * fnc = GetProcAddress (hd, sym);
1686 static __inline__ const char *
1689 return w32_strerror (0);
1693 static __inline__ int
1705 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1707 static int initialized;
1708 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1712 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1718 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1720 handle = dlopen (dllnames[i], RTLD_LAZY);
1723 func = dlsym (handle, "SHGetFolderPathW");
1734 return func (a,b,c,d,e);
1739 /* Returns a static string with the directroy from which the module
1740 has been loaded. Returns an empty string on error. */
1741 static char *w32_get_module_dir(void)
1743 static char *moddir;
1746 char name[MAX_PATH+10];
1749 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1752 p = strrchr (name, '\\');
1758 moddir = g_strdup (name);
1762 #endif /* G_OS_WIN32 */
1764 /* Return a static string with the locale dir. */
1765 const gchar *get_locale_dir(void)
1767 static gchar *loc_dir;
1771 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1772 "\\share\\locale", NULL);
1775 loc_dir = LOCALEDIR;
1781 const gchar *get_home_dir(void)
1784 static char home_dir_utf16[MAX_PATH] = "";
1785 static gchar *home_dir_utf8 = NULL;
1786 if (home_dir_utf16[0] == '\0') {
1787 if (w32_shgetfolderpath
1788 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1789 NULL, 0, home_dir_utf16) < 0)
1790 strcpy (home_dir_utf16, "C:\\Claws Mail");
1791 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1793 return home_dir_utf8;
1795 static const gchar *homeenv = NULL;
1800 if (!homeenv && g_getenv("HOME") != NULL)
1801 homeenv = g_strdup(g_getenv("HOME"));
1803 homeenv = g_get_home_dir();
1809 static gchar *claws_rc_dir = NULL;
1810 static gboolean rc_dir_alt = FALSE;
1811 const gchar *get_rc_dir(void)
1814 if (!claws_rc_dir) {
1815 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1817 debug_print("using default rc_dir %s\n", claws_rc_dir);
1819 return claws_rc_dir;
1822 void set_rc_dir(const gchar *dir)
1824 gchar *canonical_dir;
1825 if (claws_rc_dir != NULL) {
1826 g_print("Error: rc_dir already set\n");
1828 int err = cm_canonicalize_filename(dir, &canonical_dir);
1832 g_print("Error looking for %s: %d(%s)\n",
1833 dir, -err, g_strerror(-err));
1838 claws_rc_dir = canonical_dir;
1840 len = strlen(claws_rc_dir);
1841 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1842 claws_rc_dir[len - 1] = '\0';
1844 debug_print("set rc_dir to %s\n", claws_rc_dir);
1845 if (!is_dir_exist(claws_rc_dir)) {
1846 if (make_dir_hier(claws_rc_dir) != 0) {
1847 g_print("Error: can't create %s\n",
1855 gboolean rc_dir_is_alt(void) {
1859 const gchar *get_mail_base_dir(void)
1861 return get_home_dir();
1864 const gchar *get_news_cache_dir(void)
1866 static gchar *news_cache_dir = NULL;
1867 if (!news_cache_dir)
1868 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1869 NEWS_CACHE_DIR, NULL);
1871 return news_cache_dir;
1874 const gchar *get_imap_cache_dir(void)
1876 static gchar *imap_cache_dir = NULL;
1878 if (!imap_cache_dir)
1879 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1880 IMAP_CACHE_DIR, NULL);
1882 return imap_cache_dir;
1885 const gchar *get_mime_tmp_dir(void)
1887 static gchar *mime_tmp_dir = NULL;
1890 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1891 MIME_TMP_DIR, NULL);
1893 return mime_tmp_dir;
1896 const gchar *get_template_dir(void)
1898 static gchar *template_dir = NULL;
1901 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1902 TEMPLATE_DIR, NULL);
1904 return template_dir;
1908 const gchar *w32_get_cert_file(void)
1910 const gchar *cert_file = NULL;
1912 cert_file = g_strconcat(w32_get_module_dir(),
1913 "\\share\\claws-mail\\",
1914 "ca-certificates.crt",
1920 /* Return the filepath of the claws-mail.desktop file */
1921 const gchar *get_desktop_file(void)
1923 #ifdef DESKTOPFILEPATH
1924 return DESKTOPFILEPATH;
1930 /* Return the default directory for Plugins. */
1931 const gchar *get_plugin_dir(void)
1934 static gchar *plugin_dir = NULL;
1937 plugin_dir = g_strconcat(w32_get_module_dir(),
1938 "\\lib\\claws-mail\\plugins\\",
1942 if (is_dir_exist(PLUGINDIR))
1945 static gchar *plugin_dir = NULL;
1947 plugin_dir = g_strconcat(get_rc_dir(),
1948 G_DIR_SEPARATOR_S, "plugins",
1949 G_DIR_SEPARATOR_S, NULL);
1957 /* Return the default directory for Themes. */
1958 const gchar *w32_get_themes_dir(void)
1960 static gchar *themes_dir = NULL;
1963 themes_dir = g_strconcat(w32_get_module_dir(),
1964 "\\share\\claws-mail\\themes",
1970 const gchar *get_tmp_dir(void)
1972 static gchar *tmp_dir = NULL;
1975 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1981 gchar *get_tmp_file(void)
1984 static guint32 id = 0;
1986 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1987 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1992 const gchar *get_domain_name(void)
1995 static gchar *domain_name = NULL;
1996 struct addrinfo hints, *res;
2001 if (gethostname(hostname, sizeof(hostname)) != 0) {
2002 perror("gethostname");
2003 domain_name = "localhost";
2005 memset(&hints, 0, sizeof(struct addrinfo));
2006 hints.ai_family = AF_UNSPEC;
2007 hints.ai_socktype = 0;
2008 hints.ai_flags = AI_CANONNAME;
2009 hints.ai_protocol = 0;
2011 s = getaddrinfo(hostname, NULL, &hints, &res);
2013 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
2014 domain_name = g_strdup(hostname);
2016 domain_name = g_strdup(res->ai_canonname);
2020 debug_print("domain name = %s\n", domain_name);
2029 off_t get_file_size(const gchar *file)
2033 if (g_stat(file, &s) < 0) {
2034 FILE_OP_ERROR(file, "stat");
2041 time_t get_file_mtime(const gchar *file)
2045 if (g_stat(file, &s) < 0) {
2046 FILE_OP_ERROR(file, "stat");
2053 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2060 if (g_stat(file, &s) < 0) {
2061 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2065 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2072 /* Test on whether FILE is a relative file name. This is
2073 * straightforward for Unix but more complex for Windows. */
2074 gboolean is_relative_filename(const gchar *file)
2079 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2080 return FALSE; /* Prefixed with a hostname - this can't
2081 * be a relative name. */
2083 if ( ((*file >= 'a' && *file <= 'z')
2084 || (*file >= 'A' && *file <= 'Z'))
2086 file += 2; /* Skip drive letter. */
2088 return !(*file == '\\' || *file == '/');
2090 return !(*file == G_DIR_SEPARATOR);
2095 gboolean is_dir_exist(const gchar *dir)
2100 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2103 gboolean is_file_entry_exist(const gchar *file)
2108 return g_file_test(file, G_FILE_TEST_EXISTS);
2111 gboolean dirent_is_regular_file(struct dirent *d)
2113 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2114 if (d->d_type == DT_REG)
2116 else if (d->d_type != DT_UNKNOWN)
2120 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2123 gint change_dir(const gchar *dir)
2125 gchar *prevdir = NULL;
2128 prevdir = g_get_current_dir();
2130 if (g_chdir(dir) < 0) {
2131 FILE_OP_ERROR(dir, "chdir");
2132 if (debug_mode) g_free(prevdir);
2134 } else if (debug_mode) {
2137 cwd = g_get_current_dir();
2138 if (strcmp(prevdir, cwd) != 0)
2139 g_print("current dir: %s\n", cwd);
2147 gint make_dir(const gchar *dir)
2149 if (g_mkdir(dir, S_IRWXU) < 0) {
2150 FILE_OP_ERROR(dir, "mkdir");
2153 if (g_chmod(dir, S_IRWXU) < 0)
2154 FILE_OP_ERROR(dir, "chmod");
2159 gint make_dir_hier(const gchar *dir)
2164 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2165 parent_dir = g_strndup(dir, p - dir);
2166 if (*parent_dir != '\0') {
2167 if (!is_dir_exist(parent_dir)) {
2168 if (make_dir(parent_dir) < 0) {
2177 if (!is_dir_exist(dir)) {
2178 if (make_dir(dir) < 0)
2185 gint remove_all_files(const gchar *dir)
2188 const gchar *file_name;
2191 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2192 g_warning("failed to open directory: %s", dir);
2196 while ((file_name = g_dir_read_name(dp)) != NULL) {
2197 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2198 if (claws_unlink(tmp) < 0)
2199 FILE_OP_ERROR(tmp, "unlink");
2208 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2211 const gchar *dir_name;
2215 if (first == last) {
2216 /* Skip all the dir reading part. */
2217 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2218 if (is_dir_exist(filename)) {
2219 /* a numbered directory with this name exists,
2220 * remove the dot-file instead */
2222 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2224 if (claws_unlink(filename) < 0) {
2225 FILE_OP_ERROR(filename, "unlink");
2233 prev_dir = g_get_current_dir();
2235 if (g_chdir(dir) < 0) {
2236 FILE_OP_ERROR(dir, "chdir");
2241 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2242 g_warning("failed to open directory: %s", dir);
2247 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2248 file_no = to_number(dir_name);
2249 if (file_no > 0 && first <= file_no && file_no <= last) {
2250 if (is_dir_exist(dir_name)) {
2251 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2252 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2253 FILE_OP_ERROR(dot_file, "unlink");
2258 if (claws_unlink(dir_name) < 0)
2259 FILE_OP_ERROR(dir_name, "unlink");
2265 if (g_chdir(prev_dir) < 0) {
2266 FILE_OP_ERROR(prev_dir, "chdir");
2276 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2279 const gchar *dir_name;
2282 GHashTable *wanted_files;
2284 GError *error = NULL;
2286 if (numberlist == NULL)
2289 prev_dir = g_get_current_dir();
2291 if (g_chdir(dir) < 0) {
2292 FILE_OP_ERROR(dir, "chdir");
2297 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2298 g_message("Couldn't open current directory: %s (%d).\n",
2299 error->message, error->code);
2300 g_error_free(error);
2305 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2306 for (cur = numberlist; cur != NULL; cur = cur->next) {
2307 /* numberlist->data is expected to be GINT_TO_POINTER */
2308 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2311 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2312 file_no = to_number(dir_name);
2313 if (is_dir_exist(dir_name))
2315 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2316 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2317 if (is_dir_exist(dir_name)) {
2318 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2319 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2320 FILE_OP_ERROR(dot_file, "unlink");
2325 if (claws_unlink(dir_name) < 0)
2326 FILE_OP_ERROR(dir_name, "unlink");
2331 g_hash_table_destroy(wanted_files);
2333 if (g_chdir(prev_dir) < 0) {
2334 FILE_OP_ERROR(prev_dir, "chdir");
2344 gint remove_all_numbered_files(const gchar *dir)
2346 return remove_numbered_files(dir, 0, UINT_MAX);
2349 gint remove_dir_recursive(const gchar *dir)
2353 const gchar *dir_name;
2356 if (g_stat(dir, &s) < 0) {
2357 FILE_OP_ERROR(dir, "stat");
2358 if (ENOENT == errno) return 0;
2362 if (!S_ISDIR(s.st_mode)) {
2363 if (claws_unlink(dir) < 0) {
2364 FILE_OP_ERROR(dir, "unlink");
2371 prev_dir = g_get_current_dir();
2372 /* g_print("prev_dir = %s\n", prev_dir); */
2374 if (!path_cmp(prev_dir, dir)) {
2376 if (g_chdir("..") < 0) {
2377 FILE_OP_ERROR(dir, "chdir");
2380 prev_dir = g_get_current_dir();
2383 if (g_chdir(dir) < 0) {
2384 FILE_OP_ERROR(dir, "chdir");
2389 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2390 g_warning("failed to open directory: %s", dir);
2396 /* remove all files in the directory */
2397 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2398 /* g_print("removing %s\n", dir_name); */
2400 if (is_dir_exist(dir_name)) {
2403 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2404 g_warning("can't remove directory: %s", dir_name);
2408 if (claws_unlink(dir_name) < 0)
2409 FILE_OP_ERROR(dir_name, "unlink");
2415 if (g_chdir(prev_dir) < 0) {
2416 FILE_OP_ERROR(prev_dir, "chdir");
2423 if (g_rmdir(dir) < 0) {
2424 FILE_OP_ERROR(dir, "rmdir");
2431 gint rename_force(const gchar *oldpath, const gchar *newpath)
2434 if (!is_file_entry_exist(oldpath)) {
2438 if (is_file_exist(newpath)) {
2439 if (claws_unlink(newpath) < 0)
2440 FILE_OP_ERROR(newpath, "unlink");
2443 return g_rename(oldpath, newpath);
2447 * Append src file body to the tail of dest file.
2448 * Now keep_backup has no effects.
2450 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2452 FILE *src_fp, *dest_fp;
2456 gboolean err = FALSE;
2458 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2459 FILE_OP_ERROR(src, "g_fopen");
2463 if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2464 FILE_OP_ERROR(dest, "g_fopen");
2469 if (change_file_mode_rw(dest_fp, dest) < 0) {
2470 FILE_OP_ERROR(dest, "chmod");
2471 g_warning("can't change file mode: %s", dest);
2474 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2475 if (n_read < sizeof(buf) && ferror(src_fp))
2477 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2478 g_warning("writing to %s failed.", dest);
2486 if (ferror(src_fp)) {
2487 FILE_OP_ERROR(src, "fread");
2491 if (fclose(dest_fp) == EOF) {
2492 FILE_OP_ERROR(dest, "fclose");
2504 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2506 FILE *src_fp, *dest_fp;
2509 gchar *dest_bak = NULL;
2510 gboolean err = FALSE;
2512 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2513 FILE_OP_ERROR(src, "g_fopen");
2516 if (is_file_exist(dest)) {
2517 dest_bak = g_strconcat(dest, ".bak", NULL);
2518 if (rename_force(dest, dest_bak) < 0) {
2519 FILE_OP_ERROR(dest, "rename");
2526 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2527 FILE_OP_ERROR(dest, "g_fopen");
2530 if (rename_force(dest_bak, dest) < 0)
2531 FILE_OP_ERROR(dest_bak, "rename");
2537 if (change_file_mode_rw(dest_fp, dest) < 0) {
2538 FILE_OP_ERROR(dest, "chmod");
2539 g_warning("can't change file mode: %s", dest);
2542 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2543 if (n_read < sizeof(buf) && ferror(src_fp))
2545 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2546 g_warning("writing to %s failed.", dest);
2551 if (rename_force(dest_bak, dest) < 0)
2552 FILE_OP_ERROR(dest_bak, "rename");
2559 if (ferror(src_fp)) {
2560 FILE_OP_ERROR(src, "fread");
2564 if (fclose(dest_fp) == EOF) {
2565 FILE_OP_ERROR(dest, "fclose");
2572 if (rename_force(dest_bak, dest) < 0)
2573 FILE_OP_ERROR(dest_bak, "rename");
2579 if (keep_backup == FALSE && dest_bak)
2580 claws_unlink(dest_bak);
2587 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2589 if (overwrite == FALSE && is_file_exist(dest)) {
2590 g_warning("move_file(): file %s already exists.", dest);
2594 if (rename_force(src, dest) == 0) return 0;
2596 if (EXDEV != errno) {
2597 FILE_OP_ERROR(src, "rename");
2601 if (copy_file(src, dest, FALSE) < 0) return -1;
2608 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2611 gint bytes_left, to_read;
2614 if (fseek(fp, offset, SEEK_SET) < 0) {
2619 bytes_left = length;
2620 to_read = MIN(bytes_left, sizeof(buf));
2622 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2623 if (n_read < to_read && ferror(fp))
2625 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2628 bytes_left -= n_read;
2629 if (bytes_left == 0)
2631 to_read = MIN(bytes_left, sizeof(buf));
2642 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2645 gboolean err = FALSE;
2647 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2648 FILE_OP_ERROR(dest, "g_fopen");
2652 if (change_file_mode_rw(dest_fp, dest) < 0) {
2653 FILE_OP_ERROR(dest, "chmod");
2654 g_warning("can't change file mode: %s", dest);
2657 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2660 if (!err && fclose(dest_fp) == EOF) {
2661 FILE_OP_ERROR(dest, "fclose");
2666 g_warning("writing to %s failed.", dest);
2674 /* convert line endings into CRLF. If the last line doesn't end with
2675 * linebreak, add it.
2677 gchar *canonicalize_str(const gchar *str)
2683 for (p = str; *p != '\0'; ++p) {
2690 if (p == str || *(p - 1) != '\n')
2693 out = outp = g_malloc(new_len + 1);
2694 for (p = str; *p != '\0'; ++p) {
2701 if (p == str || *(p - 1) != '\n') {
2710 gint canonicalize_file(const gchar *src, const gchar *dest)
2712 FILE *src_fp, *dest_fp;
2713 gchar buf[BUFFSIZE];
2715 gboolean err = FALSE;
2716 gboolean last_linebreak = FALSE;
2718 if (src == NULL || dest == NULL)
2721 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2722 FILE_OP_ERROR(src, "g_fopen");
2726 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2727 FILE_OP_ERROR(dest, "g_fopen");
2732 if (change_file_mode_rw(dest_fp, dest) < 0) {
2733 FILE_OP_ERROR(dest, "chmod");
2734 g_warning("can't change file mode: %s", dest);
2737 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2741 if (len == 0) break;
2742 last_linebreak = FALSE;
2744 if (buf[len - 1] != '\n') {
2745 last_linebreak = TRUE;
2746 r = fputs(buf, dest_fp);
2747 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2748 r = fputs(buf, dest_fp);
2751 r = fwrite(buf, 1, len - 1, dest_fp);
2756 r = fputs("\r\n", dest_fp);
2760 g_warning("writing to %s failed.", dest);
2768 if (last_linebreak == TRUE) {
2769 if (fputs("\r\n", dest_fp) == EOF)
2773 if (ferror(src_fp)) {
2774 FILE_OP_ERROR(src, "fgets");
2778 if (fclose(dest_fp) == EOF) {
2779 FILE_OP_ERROR(dest, "fclose");
2791 gint canonicalize_file_replace(const gchar *file)
2795 tmp_file = get_tmp_file();
2797 if (canonicalize_file(file, tmp_file) < 0) {
2802 if (move_file(tmp_file, file, TRUE) < 0) {
2803 g_warning("can't replace file: %s", file);
2804 claws_unlink(tmp_file);
2813 gchar *normalize_newlines(const gchar *str)
2818 out = outp = g_malloc(strlen(str) + 1);
2819 for (p = str; *p != '\0'; ++p) {
2821 if (*(p + 1) != '\n')
2832 gchar *get_outgoing_rfc2822_str(FILE *fp)
2834 gchar buf[BUFFSIZE];
2838 str = g_string_new(NULL);
2840 /* output header part */
2841 while (fgets(buf, sizeof(buf), fp) != NULL) {
2843 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2850 else if (next != ' ' && next != '\t') {
2854 if (fgets(buf, sizeof(buf), fp) == NULL)
2858 g_string_append(str, buf);
2859 g_string_append(str, "\r\n");
2865 /* output body part */
2866 while (fgets(buf, sizeof(buf), fp) != NULL) {
2869 g_string_append_c(str, '.');
2870 g_string_append(str, buf);
2871 g_string_append(str, "\r\n");
2875 g_string_free(str, FALSE);
2881 * Create a new boundary in a way that it is very unlikely that this
2882 * will occur in the following text. It would be easy to ensure
2883 * uniqueness if everything is either quoted-printable or base64
2884 * encoded (note that conversion is allowed), but because MIME bodies
2885 * may be nested, it may happen that the same boundary has already
2888 * boundary := 0*69<bchars> bcharsnospace
2889 * bchars := bcharsnospace / " "
2890 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2891 * "+" / "_" / "," / "-" / "." /
2892 * "/" / ":" / "=" / "?"
2894 * some special characters removed because of buggy MTAs
2897 gchar *generate_mime_boundary(const gchar *prefix)
2899 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2900 "abcdefghijklmnopqrstuvwxyz"
2905 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2906 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2909 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2913 gint change_file_mode_rw(FILE *fp, const gchar *file)
2916 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2918 return g_chmod(file, S_IRUSR|S_IWUSR);
2922 FILE *my_tmpfile(void)
2924 const gchar suffix[] = ".XXXXXX";
2925 const gchar *tmpdir;
2927 const gchar *progname;
2936 tmpdir = get_tmp_dir();
2937 tmplen = strlen(tmpdir);
2938 progname = g_get_prgname();
2939 if (progname == NULL)
2940 progname = "claws-mail";
2941 proglen = strlen(progname);
2942 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2945 memcpy(fname, tmpdir, tmplen);
2946 fname[tmplen] = G_DIR_SEPARATOR;
2947 memcpy(fname + tmplen + 1, progname, proglen);
2948 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2950 fd = g_mkstemp(fname);
2955 claws_unlink(fname);
2957 /* verify that we can write in the file after unlinking */
2958 if (write(fd, buf, 1) < 0) {
2965 fp = fdopen(fd, "w+b");
2976 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2979 *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
2980 fd = g_mkstemp(*filename);
2983 return fdopen(fd, "w+");
2986 FILE *str_open_as_stream(const gchar *str)
2991 cm_return_val_if_fail(str != NULL, NULL);
2995 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3000 if (len == 0) return fp;
3002 if (fwrite(str, 1, len, fp) != len) {
3003 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3012 gint str_write_to_file(const gchar *str, const gchar *file)
3017 cm_return_val_if_fail(str != NULL, -1);
3018 cm_return_val_if_fail(file != NULL, -1);
3020 if ((fp = g_fopen(file, "wb")) == NULL) {
3021 FILE_OP_ERROR(file, "g_fopen");
3031 if (fwrite(str, 1, len, fp) != len) {
3032 FILE_OP_ERROR(file, "fwrite");
3038 if (fclose(fp) == EOF) {
3039 FILE_OP_ERROR(file, "fclose");
3047 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3054 cm_return_val_if_fail(fp != NULL, NULL);
3056 array = g_byte_array_new();
3058 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3059 if (n_read < sizeof(buf) && ferror(fp))
3061 g_byte_array_append(array, buf, n_read);
3065 FILE_OP_ERROR("file stream", "fread");
3066 g_byte_array_free(array, TRUE);
3071 g_byte_array_append(array, buf, 1);
3072 str = (gchar *)array->data;
3073 g_byte_array_free(array, FALSE);
3075 if (recode && !g_utf8_validate(str, -1, NULL)) {
3076 const gchar *src_codeset, *dest_codeset;
3078 src_codeset = conv_get_locale_charset_str();
3079 dest_codeset = CS_UTF_8;
3080 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3088 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3095 struct timeval timeout = {1, 0};
3100 cm_return_val_if_fail(file != NULL, NULL);
3102 if (g_stat(file, &s) != 0) {
3103 FILE_OP_ERROR(file, "stat");
3106 if (S_ISDIR(s.st_mode)) {
3107 g_warning("%s: is a directory", file);
3112 fp = g_fopen (file, "rb");
3114 FILE_OP_ERROR(file, "open");
3118 /* test whether the file is readable without blocking */
3119 fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3121 FILE_OP_ERROR(file, "open");
3128 /* allow for one second */
3129 err = select(fd+1, &fds, NULL, NULL, &timeout);
3130 if (err <= 0 || !FD_ISSET(fd, &fds)) {
3132 FILE_OP_ERROR(file, "select");
3134 g_warning("%s: doesn't seem readable", file);
3140 /* Now clear O_NONBLOCK */
3141 if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3142 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3146 if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3147 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3152 /* get the FILE pointer */
3153 fp = fdopen(fd, "rb");
3156 FILE_OP_ERROR(file, "fdopen");
3157 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3162 str = file_read_stream_to_str_full(fp, recode);
3169 gchar *file_read_to_str(const gchar *file)
3171 return file_read_to_str_full(file, TRUE);
3173 gchar *file_read_stream_to_str(FILE *fp)
3175 return file_read_stream_to_str_full(fp, TRUE);
3178 gchar *file_read_to_str_no_recode(const gchar *file)
3180 return file_read_to_str_full(file, FALSE);
3182 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3184 return file_read_stream_to_str_full(fp, FALSE);
3187 char *fgets_crlf(char *buf, int size, FILE *stream)
3189 gboolean is_cr = FALSE;
3190 gboolean last_was_cr = FALSE;
3195 while (--size > 0 && (c = getc(stream)) != EOF)
3198 is_cr = (c == '\r');
3208 last_was_cr = is_cr;
3210 if (c == EOF && cs == buf)
3218 static gint execute_async(gchar *const argv[], const gchar *working_directory)
3220 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3222 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3223 NULL, NULL, NULL, FALSE) == FALSE) {
3224 g_warning("couldn't execute command: %s", argv[0]);
3231 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
3235 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3238 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3239 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3240 g_warning("couldn't execute command: %s", argv[0]);
3244 if (WIFEXITED(status))
3245 return WEXITSTATUS(status);
3249 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
3250 G_SPAWN_SEARCH_PATH|
3251 G_SPAWN_CHILD_INHERITS_STDIN|
3252 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3253 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3254 g_warning("couldn't execute command: %s", argv[0]);
3262 gint execute_command_line(const gchar *cmdline, gboolean async,
3263 const gchar *working_directory)
3268 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3270 argv = strsplit_with_quote(cmdline, " ", 0);
3273 ret = execute_async(argv, working_directory);
3275 ret = execute_sync(argv, working_directory);
3282 gchar *get_command_output(const gchar *cmdline)
3284 gchar *child_stdout;
3287 cm_return_val_if_fail(cmdline != NULL, NULL);
3289 debug_print("get_command_output(): executing: %s\n", cmdline);
3291 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3293 g_warning("couldn't execute command: %s", cmdline);
3297 return child_stdout;
3300 static gint is_unchanged_uri_char(char c)
3311 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3317 for(i = 0; i < strlen(uri) ; i++) {
3318 if (is_unchanged_uri_char(uri[i])) {
3319 if (k + 2 >= bufsize)
3321 encoded_uri[k++] = uri[i];
3324 char * hexa = "0123456789ABCDEF";
3326 if (k + 4 >= bufsize)
3328 encoded_uri[k++] = '%';
3329 encoded_uri[k++] = hexa[uri[i] / 16];
3330 encoded_uri[k++] = hexa[uri[i] % 16];
3336 gint open_uri(const gchar *uri, const gchar *cmdline)
3340 gchar buf[BUFFSIZE];
3342 gchar encoded_uri[BUFFSIZE];
3343 cm_return_val_if_fail(uri != NULL, -1);
3345 /* an option to choose whether to use encode_uri or not ? */
3346 encode_uri(encoded_uri, BUFFSIZE, uri);
3349 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3350 !strchr(p + 2, '%'))
3351 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3354 g_warning("Open URI command-line is invalid "
3355 "(there must be only one '%%s'): %s",
3357 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3360 execute_command_line(buf, TRUE, NULL);
3362 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3367 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3369 gchar buf[BUFFSIZE];
3372 cm_return_val_if_fail(filepath != NULL, -1);
3375 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3376 !strchr(p + 2, '%'))
3377 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3380 g_warning("Open Text Editor command-line is invalid "
3381 "(there must be only one '%%s'): %s",
3383 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3386 execute_command_line(buf, TRUE, NULL);
3391 time_t remote_tzoffset_sec(const gchar *zone)
3393 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3399 time_t remoteoffset;
3401 strncpy(zone3, zone, 3);
3405 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3406 (c == '+' || c == '-')) {
3407 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3409 remoteoffset = -remoteoffset;
3410 } else if (!strncmp(zone, "UT" , 2) ||
3411 !strncmp(zone, "GMT", 3)) {
3413 } else if (strlen(zone3) == 3) {
3414 for (p = ustzstr; *p != '\0'; p += 3) {
3415 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3416 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3417 remoteoffset = iustz * 3600;
3423 } else if (strlen(zone3) == 1) {
3425 case 'Z': remoteoffset = 0; break;
3426 case 'A': remoteoffset = -1; break;
3427 case 'B': remoteoffset = -2; break;
3428 case 'C': remoteoffset = -3; break;
3429 case 'D': remoteoffset = -4; break;
3430 case 'E': remoteoffset = -5; break;
3431 case 'F': remoteoffset = -6; break;
3432 case 'G': remoteoffset = -7; break;
3433 case 'H': remoteoffset = -8; break;
3434 case 'I': remoteoffset = -9; break;
3435 case 'K': remoteoffset = -10; break; /* J is not used */
3436 case 'L': remoteoffset = -11; break;
3437 case 'M': remoteoffset = -12; break;
3438 case 'N': remoteoffset = 1; break;
3439 case 'O': remoteoffset = 2; break;
3440 case 'P': remoteoffset = 3; break;
3441 case 'Q': remoteoffset = 4; break;
3442 case 'R': remoteoffset = 5; break;
3443 case 'S': remoteoffset = 6; break;
3444 case 'T': remoteoffset = 7; break;
3445 case 'U': remoteoffset = 8; break;
3446 case 'V': remoteoffset = 9; break;
3447 case 'W': remoteoffset = 10; break;
3448 case 'X': remoteoffset = 11; break;
3449 case 'Y': remoteoffset = 12; break;
3450 default: remoteoffset = 0; break;
3452 remoteoffset = remoteoffset * 3600;
3456 return remoteoffset;
3459 time_t tzoffset_sec(time_t *now)
3463 struct tm buf1, buf2;
3465 if (now && *now < 0)
3468 gmt = *gmtime_r(now, &buf1);
3469 lt = localtime_r(now, &buf2);
3471 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3473 if (lt->tm_year < gmt.tm_year)
3475 else if (lt->tm_year > gmt.tm_year)
3477 else if (lt->tm_yday < gmt.tm_yday)
3479 else if (lt->tm_yday > gmt.tm_yday)
3482 if (off >= 24 * 60) /* should be impossible */
3483 off = 23 * 60 + 59; /* if not, insert silly value */
3484 if (off <= -24 * 60)
3485 off = -(23 * 60 + 59);
3490 /* calculate timezone offset */
3491 gchar *tzoffset(time_t *now)
3493 static gchar offset_string[6];
3497 struct tm buf1, buf2;
3499 if (now && *now < 0)
3502 gmt = *gmtime_r(now, &buf1);
3503 lt = localtime_r(now, &buf2);
3505 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3507 if (lt->tm_year < gmt.tm_year)
3509 else if (lt->tm_year > gmt.tm_year)
3511 else if (lt->tm_yday < gmt.tm_yday)
3513 else if (lt->tm_yday > gmt.tm_yday)
3521 if (off >= 24 * 60) /* should be impossible */
3522 off = 23 * 60 + 59; /* if not, insert silly value */
3524 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3526 return offset_string;
3529 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
3533 gchar day[4], mon[4];
3534 gint dd, hh, mm, ss, yyyy;
3536 gchar buf2[RFC822_DATE_BUFFSIZE];
3539 lt = localtime_r(&t, &buf1);
3541 sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
3542 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3544 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3545 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
3548 void get_rfc822_date(gchar *buf, gint len)
3550 _get_rfc822_date(buf, len, FALSE);
3553 void get_rfc822_date_hide_tz(gchar *buf, gint len)
3555 _get_rfc822_date(buf, len, TRUE);
3558 void debug_set_mode(gboolean mode)
3563 gboolean debug_get_mode(void)
3568 void debug_print_real(const gchar *format, ...)
3571 gchar buf[BUFFSIZE];
3573 if (!debug_mode) return;
3575 va_start(args, format);
3576 g_vsnprintf(buf, sizeof(buf), format, args);
3583 const char * debug_srcname(const char *file)
3585 const char *s = strrchr (file, '/');
3590 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3592 if (subject == NULL)
3595 subject += subject_get_prefix_length(subject);
3597 return g_hash_table_lookup(subject_table, subject);
3600 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3603 if (subject == NULL || *subject == 0)
3605 subject += subject_get_prefix_length(subject);
3606 g_hash_table_insert(subject_table, subject, data);
3609 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3611 if (subject == NULL)
3614 subject += subject_get_prefix_length(subject);
3615 g_hash_table_remove(subject_table, subject);
3618 static regex_t u_regex;
3619 static gboolean u_init_;
3621 void utils_free_regex(void)
3630 *\brief Check if a string is prefixed with known (combinations)
3631 * of prefixes. The function assumes that each prefix
3632 * is terminated by zero or exactly _one_ space.
3634 *\param str String to check for a prefixes
3636 *\return int Number of chars in the prefix that should be skipped
3637 * for a "clean" subject line. If no prefix was found, 0
3640 int subject_get_prefix_length(const gchar *subject)
3642 /*!< Array with allowable reply prefixes regexps. */
3643 static const gchar * const prefixes[] = {
3644 "Re\\:", /* "Re:" */
3645 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3646 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3647 "Aw\\:", /* "Aw:" (German) */
3648 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3649 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3650 "Fw\\:", /* "Fw:" Forward */
3651 "Fwd\\:", /* "Fwd:" Forward */
3652 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3653 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3654 "Rif\\:", /* "Rif:" (Italian Outlook) */
3655 "Sv\\:", /* "Sv" (Norwegian) */
3656 "Vs\\:", /* "Vs" (Norwegian) */
3657 "Ad\\:", /* "Ad" (Norwegian) */
3658 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3659 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3660 "Re \\:", /* "Re :" (French Yahoo Mail) */
3663 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3667 if (!subject) return 0;
3668 if (!*subject) return 0;
3671 GString *s = g_string_new("");
3673 for (n = 0; n < PREFIXES; n++)
3674 /* Terminate each prefix regexpression by a
3675 * "\ ?" (zero or ONE space), and OR them */
3676 g_string_append_printf(s, "(%s\\ ?)%s",
3681 g_string_prepend(s, "(");
3682 g_string_append(s, ")+"); /* match at least once */
3683 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3686 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3687 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3688 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3689 debug_print("Error compiling regexp %s\n", s->str);
3690 g_string_free(s, TRUE);
3694 g_string_free(s, TRUE);
3698 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3704 static guint g_stricase_hash(gconstpointer gptr)
3706 guint hash_result = 0;
3709 for (str = gptr; str && *str; str++) {
3710 hash_result += toupper(*str);
3716 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3718 const char *str1 = gptr1;
3719 const char *str2 = gptr2;
3721 return !strcasecmp(str1, str2);
3724 gint g_int_compare(gconstpointer a, gconstpointer b)
3726 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3730 quote_cmd_argument()
3732 return a quoted string safely usable in argument of a command.
3734 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3737 gint quote_cmd_argument(gchar * result, guint size,
3747 for(p = path ; * p != '\0' ; p ++) {
3749 if (isalnum((guchar)*p) || (* p == '/')) {
3750 if (remaining > 0) {
3756 result[size - 1] = '\0';
3761 if (remaining >= 2) {
3769 result[size - 1] = '\0';
3774 if (remaining > 0) {
3778 result[size - 1] = '\0';
3792 static void g_node_map_recursive(GNode *node, gpointer data)
3794 GNodeMapData *mapdata = (GNodeMapData *) data;
3796 GNodeMapData newmapdata;
3799 newdata = mapdata->func(node->data, mapdata->data);
3800 if (newdata != NULL) {
3801 newnode = g_node_new(newdata);
3802 g_node_append(mapdata->parent, newnode);
3804 newmapdata.parent = newnode;
3805 newmapdata.func = mapdata->func;
3806 newmapdata.data = mapdata->data;
3808 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3812 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3815 GNodeMapData mapdata;
3817 cm_return_val_if_fail(node != NULL, NULL);
3818 cm_return_val_if_fail(func != NULL, NULL);
3820 root = g_node_new(func(node->data, data));
3822 mapdata.parent = root;
3823 mapdata.func = func;
3824 mapdata.data = data;
3826 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3831 #define HEX_TO_INT(val, hex) \
3835 if ('0' <= c && c <= '9') { \
3837 } else if ('a' <= c && c <= 'f') { \
3838 val = c - 'a' + 10; \
3839 } else if ('A' <= c && c <= 'F') { \
3840 val = c - 'A' + 10; \
3846 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3853 if (hi == -1 || lo == -1)
3856 *out = (hi << 4) + lo;
3860 #define INT_TO_HEX(hex, val) \
3863 hex = '0' + (val); \
3865 hex = 'A' + (val) - 10; \
3868 void get_hex_str(gchar *out, guchar ch)
3872 INT_TO_HEX(hex, ch >> 4);
3874 INT_TO_HEX(hex, ch & 0x0f);
3880 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3882 #define G_PRINT_REF g_print
3886 *\brief Register ref counted pointer. It is based on GBoxed, so should
3887 * work with anything that uses the GType system. The semantics
3888 * are similar to a C++ auto pointer, with the exception that
3889 * C doesn't have automatic closure (calling destructors) when
3890 * exiting a block scope.
3891 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3892 * function directly.
3894 *\return GType A GType type.
3896 GType g_auto_pointer_register(void)
3898 static GType auto_pointer_type;
3899 if (!auto_pointer_type)
3901 g_boxed_type_register_static
3902 ("G_TYPE_AUTO_POINTER",
3903 (GBoxedCopyFunc) g_auto_pointer_copy,
3904 (GBoxedFreeFunc) g_auto_pointer_free);
3905 return auto_pointer_type;
3909 *\brief Structure with g_new() allocated pointer guarded by the
3912 typedef struct AutoPointerRef {
3913 void (*free) (gpointer);
3919 *\brief The auto pointer opaque structure that references the
3920 * pointer guard block.
3922 typedef struct AutoPointer {
3923 AutoPointerRef *ref;
3924 gpointer ptr; /*!< access to protected pointer */
3928 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3932 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3933 * ... when assigning, copying and freeing storage elements
3935 * gtk_list_store_new(N_S_COLUMNS,
3936 * G_TYPE_AUTO_POINTER,
3940 * Template *precious_data = g_new0(Template, 1);
3941 * g_pointer protect = g_auto_pointer_new(precious_data);
3943 * gtk_list_store_set(container, &iter,
3947 * ... the gtk_list_store has copied the pointer and
3948 * ... incremented its reference count, we should free
3949 * ... the auto pointer (in C++ a destructor would do
3950 * ... this for us when leaving block scope)
3952 * g_auto_pointer_free(protect);
3954 * ... gtk_list_store_set() now manages the data. When
3955 * ... *explicitly* requesting a pointer from the list
3956 * ... store, don't forget you get a copy that should be
3957 * ... freed with g_auto_pointer_free() eventually.
3961 *\param pointer Pointer to be guarded.
3963 *\return GAuto * Pointer that should be used in containers with
3966 GAuto *g_auto_pointer_new(gpointer p)
3968 AutoPointerRef *ref;
3974 ref = g_new0(AutoPointerRef, 1);
3975 ptr = g_new0(AutoPointer, 1);
3985 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3991 *\brief Allocate an autopointer using the passed \a free function to
3992 * free the guarded pointer
3994 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
4001 aptr = g_auto_pointer_new(p);
4002 aptr->ref->free = free_;
4006 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
4008 if (auto_ptr == NULL)
4010 return ((AutoPointer *) auto_ptr)->ptr;
4014 *\brief Copies an auto pointer by. It's mostly not necessary
4015 * to call this function directly, unless you copy/assign
4016 * the guarded pointer.
4018 *\param auto_ptr Auto pointer returned by previous call to
4019 * g_auto_pointer_new_XXX()
4021 *\return gpointer An auto pointer
4023 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
4026 AutoPointerRef *ref;
4029 if (auto_ptr == NULL)
4034 newp = g_new0(AutoPointer, 1);
4037 newp->ptr = ref->pointer;
4041 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4047 *\brief Free an auto pointer
4049 void g_auto_pointer_free(GAuto *auto_ptr)
4052 AutoPointerRef *ref;
4054 if (auto_ptr == NULL)
4060 if (--(ref->cnt) == 0) {
4062 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4064 ref->free(ref->pointer);
4069 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4074 void replace_returns(gchar *str)
4079 while (strstr(str, "\n")) {
4080 *strstr(str, "\n") = ' ';
4082 while (strstr(str, "\r")) {
4083 *strstr(str, "\r") = ' ';
4087 /* get_uri_part() - retrieves a URI starting from scanpos.
4088 Returns TRUE if successful */
4089 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
4090 const gchar **bp, const gchar **ep, gboolean hdr)
4093 gint parenthese_cnt = 0;
4095 cm_return_val_if_fail(start != NULL, FALSE);
4096 cm_return_val_if_fail(scanpos != NULL, FALSE);
4097 cm_return_val_if_fail(bp != NULL, FALSE);
4098 cm_return_val_if_fail(ep != NULL, FALSE);
4102 /* find end point of URI */
4103 for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
4104 if (!g_ascii_isgraph(*(const guchar *)ep_) ||
4105 !IS_ASCII(*(const guchar *)ep_) ||
4106 strchr("[]{}<>\"", *ep_)) {
4108 } else if (strchr("(", *ep_)) {
4110 } else if (strchr(")", *ep_)) {
4111 if (parenthese_cnt > 0)
4118 /* no punctuation at end of string */
4120 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
4121 * should pass some URI type to this function and decide on that whether
4122 * to perform punctuation stripping */
4124 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
4126 for (; ep_ - 1 > scanpos + 1 &&
4127 IS_REAL_PUNCT(*(ep_ - 1));
4131 #undef IS_REAL_PUNCT
4138 gchar *make_uri_string(const gchar *bp, const gchar *ep)
4140 while (bp && *bp && g_ascii_isspace(*bp))
4142 return g_strndup(bp, ep - bp);
4145 /* valid mail address characters */
4146 #define IS_RFC822_CHAR(ch) \
4150 !g_ascii_isspace(ch) && \
4151 !strchr("(),;<>\"", (ch)))
4153 /* alphabet and number within 7bit ASCII */
4154 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
4155 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
4157 static GHashTable *create_domain_tab(void)
4160 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
4162 cm_return_val_if_fail(htab, NULL);
4163 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
4164 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
4168 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
4170 const gint MAX_LVL_DOM_NAME_LEN = 6;
4171 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
4172 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
4175 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
4178 for (p = buf; p < m && first < last; *p++ = *first++)
4182 return g_hash_table_lookup(tab, buf) != NULL;
4185 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
4186 gboolean get_email_part(const gchar *start, const gchar *scanpos,
4187 const gchar **bp, const gchar **ep, gboolean hdr)
4189 /* more complex than the uri part because we need to scan back and forward starting from
4190 * the scan position. */
4191 gboolean result = FALSE;
4192 const gchar *bp_ = NULL;
4193 const gchar *ep_ = NULL;
4194 static GHashTable *dom_tab;
4195 const gchar *last_dot = NULL;
4196 const gchar *prelast_dot = NULL;
4197 const gchar *last_tld_char = NULL;
4199 /* the informative part of the email address (describing the name
4200 * of the email address owner) may contain quoted parts. the
4201 * closure stack stores the last encountered quotes. */
4202 gchar closure_stack[128];
4203 gchar *ptr = closure_stack;
4205 cm_return_val_if_fail(start != NULL, FALSE);
4206 cm_return_val_if_fail(scanpos != NULL, FALSE);
4207 cm_return_val_if_fail(bp != NULL, FALSE);
4208 cm_return_val_if_fail(ep != NULL, FALSE);
4211 const gchar *start_quote = NULL;
4212 const gchar *end_quote = NULL;
4214 /* go to the real start */
4215 if (start[0] == ',')
4217 if (start[0] == ';')
4219 while (start[0] == '\n' || start[0] == '\r')
4221 while (start[0] == ' ' || start[0] == '\t')
4226 /* check if there are quotes (to skip , in them) */
4227 if (*start == '"') {
4228 start_quote = start;
4230 end_quote = strstr(start, "\"");
4236 /* skip anything between quotes */
4237 if (start_quote && end_quote) {
4242 /* find end (either , or ; or end of line) */
4243 if (strstr(start, ",") && strstr(start, ";"))
4244 *ep = strstr(start,",") < strstr(start, ";")
4245 ? strstr(start, ",") : strstr(start, ";");
4246 else if (strstr(start, ","))
4247 *ep = strstr(start, ",");
4248 else if (strstr(start, ";"))
4249 *ep = strstr(start, ";");
4251 *ep = start+strlen(start);
4253 /* go back to real start */
4254 if (start_quote && end_quote) {
4255 start = start_quote;
4258 /* check there's still an @ in that, or search
4259 * further if possible */
4260 if (strstr(start, "@") && strstr(start, "@") < *ep)
4262 else if (*ep < start+strlen(start)) {
4265 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
4273 dom_tab = create_domain_tab();
4274 cm_return_val_if_fail(dom_tab, FALSE);
4276 /* scan start of address */
4277 for (bp_ = scanpos - 1;
4278 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
4281 /* TODO: should start with an alnum? */
4283 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
4286 if (bp_ != scanpos) {
4287 /* scan end of address */
4288 for (ep_ = scanpos + 1;
4289 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
4291 prelast_dot = last_dot;
4293 if (*(last_dot + 1) == '.') {
4294 if (prelast_dot == NULL)
4296 last_dot = prelast_dot;
4301 /* TODO: really should terminate with an alnum? */
4302 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
4307 if (last_dot == NULL)
4309 if (last_dot >= ep_)
4310 last_dot = prelast_dot;
4311 if (last_dot == NULL || (scanpos + 1 >= last_dot))
4315 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
4316 if (*last_tld_char == '?')
4319 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
4326 if (!result) return FALSE;
4328 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
4329 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
4330 && IS_RFC822_CHAR(*(ep_ + 3))) {
4331 /* this informative part with an @ in it is
4332 * followed by the email address */
4335 /* go to matching '>' (or next non-rfc822 char, like \n) */
4336 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
4339 /* include the bracket */
4340 if (*ep_ == '>') ep_++;
4342 /* include the leading quote */
4350 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
4351 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
4354 /* see if this is <bracketed>; in this case we also scan for the informative part. */
4355 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
4358 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
4359 #define IN_STACK() (ptr > closure_stack)
4360 /* has underrun check */
4361 #define POP_STACK() if(IN_STACK()) --ptr
4362 /* has overrun check */
4363 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
4364 /* has underrun check */
4365 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
4369 /* scan for the informative part. */
4370 for (bp_ -= 2; bp_ >= start; bp_--) {
4371 /* if closure on the stack keep scanning */
4372 if (PEEK_STACK() == *bp_) {
4376 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
4381 /* if nothing in the closure stack, do the special conditions
4382 * the following if..else expression simply checks whether
4383 * a token is acceptable. if not acceptable, the clause
4384 * should terminate the loop with a 'break' */
4385 if (!PEEK_STACK()) {
4387 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
4388 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
4389 /* hyphens are allowed, but only in
4391 } else if (strchr(" \"'", *bp_)) {
4392 /* but anything not being a punctiation
4395 break; /* anything else is rejected */
4402 /* scan forward (should start with an alnum) */
4403 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
4419 #undef IS_ASCII_ALNUM
4420 #undef IS_RFC822_CHAR
4422 gchar *make_email_string(const gchar *bp, const gchar *ep)
4424 /* returns a mailto: URI; mailto: is also used to detect the
4425 * uri type later on in the button_pressed signal handler */
4430 tmp = g_strndup(bp, ep - bp);
4432 /* If there is a colon in the username part of the address,
4433 * we're dealing with an URI for some other protocol - do
4434 * not prefix with mailto: in such case. */
4435 colon = strchr(tmp, ':');
4436 at = strchr(tmp, '@');
4437 if (colon != NULL && at != NULL && colon < at) {
4440 result = g_strconcat("mailto:", tmp, NULL);
4447 gchar *make_http_string(const gchar *bp, const gchar *ep)
4449 /* returns an http: URI; */
4453 while (bp && *bp && g_ascii_isspace(*bp))
4455 tmp = g_strndup(bp, ep - bp);
4456 result = g_strconcat("http://", tmp, NULL);
4462 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
4464 FILE *fp = g_fopen(path, "rb");
4465 gchar buf[BUFFSIZE];
4466 gchar *result = NULL;
4469 while (fgets(buf, sizeof (buf), fp) != NULL) {
4470 gchar **parts = g_strsplit(buf, ";", 3);
4471 gchar *trimmed = parts[0];
4472 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4474 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4475 trimmed[strlen(trimmed)-1] = '\0';
4477 if (!strcmp(trimmed, type)) {
4478 gboolean needsterminal = FALSE;
4479 if (parts[2] && strstr(parts[2], "needsterminal")) {
4480 needsterminal = TRUE;
4482 if (parts[2] && strstr(parts[2], "test=")) {
4483 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
4484 gchar *testcmd = orig_testcmd;
4485 if (strstr(testcmd,";"))
4486 *(strstr(testcmd,";")) = '\0';
4487 while (testcmd[0] == ' ' || testcmd[0] == '\t')
4489 while (testcmd[strlen(testcmd)-1] == '\n')
4490 testcmd[strlen(testcmd)-1] = '\0';
4491 while (testcmd[strlen(testcmd)-1] == '\r')
4492 testcmd[strlen(testcmd)-1] = '\0';
4493 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
4494 testcmd[strlen(testcmd)-1] = '\0';
4496 if (strstr(testcmd, "%s")) {
4497 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
4498 gint res = system(tmp);
4500 g_free(orig_testcmd);
4507 gint res = system(testcmd);
4508 g_free(orig_testcmd);
4518 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4520 while (trimmed[strlen(trimmed)-1] == '\n')
4521 trimmed[strlen(trimmed)-1] = '\0';
4522 while (trimmed[strlen(trimmed)-1] == '\r')
4523 trimmed[strlen(trimmed)-1] = '\0';
4524 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4525 trimmed[strlen(trimmed)-1] = '\0';
4526 result = g_strdup(trimmed);
4529 if (needsterminal) {
4530 gchar *tmp = g_strdup_printf("xterm -e %s", result);
4541 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
4543 gchar *result = NULL;
4547 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4548 result = mailcap_get_command_in_file(path, type, file_to_open);
4552 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
4556 void mailcap_update_default(const gchar *type, const gchar *command)
4558 gchar *path = NULL, *outpath = NULL;
4559 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4560 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
4561 FILE *fp = g_fopen(path, "rb");
4563 gchar buf[BUFFSIZE];
4564 gboolean err = FALSE;
4567 fp = g_fopen(path, "a");
4569 g_warning("failed to create file %s", path);
4574 fp = g_freopen(path, "rb", fp);
4576 g_warning("failed to reopen file %s", path);
4583 outfp = g_fopen(outpath, "wb");
4585 g_warning("failed to create file %s", outpath);
4591 while (fp && fgets(buf, sizeof (buf), fp) != NULL) {
4592 gchar **parts = g_strsplit(buf, ";", 3);
4593 gchar *trimmed = parts[0];
4594 while (trimmed[0] == ' ')
4596 while (trimmed[strlen(trimmed)-1] == ' ')
4597 trimmed[strlen(trimmed)-1] = '\0';
4599 if (!strcmp(trimmed, type)) {
4604 if(fputs(buf, outfp) == EOF) {
4611 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4617 if (fclose(outfp) == EOF)
4621 g_rename(outpath, path);
4627 gint copy_dir(const gchar *src, const gchar *dst)
4632 if ((dir = g_dir_open(src, 0, NULL)) == NULL) {
4633 g_warning("failed to open directory: %s", src);
4637 if (make_dir(dst) < 0)
4640 while ((name = g_dir_read_name(dir)) != NULL) {
4641 gchar *old_file, *new_file;
4642 old_file = g_strconcat(src, G_DIR_SEPARATOR_S, name, NULL);
4643 new_file = g_strconcat(dst, G_DIR_SEPARATOR_S, name, NULL);
4644 debug_print("copying: %s -> %s\n", old_file, new_file);
4645 if (g_file_test(old_file, G_FILE_TEST_IS_REGULAR)) {
4646 gint r = copy_file(old_file, new_file, TRUE);
4653 /* Windows has no symlinks. Or well, Vista seems to
4654 have something like this but the semantics might be
4655 different. Thus we don't use it under Windows. */
4656 else if (g_file_test(old_file, G_FILE_TEST_IS_SYMLINK)) {
4657 GError *error = NULL;
4659 gchar *target = g_file_read_link(old_file, &error);
4661 r = symlink(target, new_file);
4668 #endif /*G_OS_WIN32*/
4669 else if (g_file_test(old_file, G_FILE_TEST_IS_DIR)) {
4670 gint r = copy_dir(old_file, new_file);
4681 /* crude test to see if a file is an email. */
4682 gboolean file_is_email (const gchar *filename)
4688 if (filename == NULL)
4690 if ((fp = g_fopen(filename, "rb")) == NULL)
4692 while (i < 60 && score < 3
4693 && fgets(buffer, sizeof (buffer), fp) != NULL) {
4694 if (!strncmp(buffer, "From:", strlen("From:")))
4696 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4698 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4700 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4705 return (score >= 3);
4708 gboolean sc_g_list_bigger(GList *list, gint max)
4712 while (cur && i <= max+1) {
4719 gboolean sc_g_slist_bigger(GSList *list, gint max)
4723 while (cur && i <= max+1) {
4730 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4731 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4732 NULL, NULL, NULL, NULL, NULL, NULL};
4733 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4734 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4735 NULL, NULL, NULL, NULL, NULL, NULL};
4737 gint daynames_len[] = {0,0,0,0,0,0,0};
4738 gint monthnames_len[] = {0,0,0,0,0,0,
4740 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4741 gint s_monthnames_len[] = {0,0,0,0,0,0,
4743 const gchar *s_am_up = NULL;
4744 const gchar *s_pm_up = NULL;
4745 const gchar *s_am_low = NULL;
4746 const gchar *s_pm_low = NULL;
4748 gint s_am_up_len = 0;
4749 gint s_pm_up_len = 0;
4750 gint s_am_low_len = 0;
4751 gint s_pm_low_len = 0;
4753 static gboolean time_names_init_done = FALSE;
4755 static void init_time_names(void)
4759 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4760 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4761 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4762 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4763 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4764 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4765 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4767 monthnames[0] = C_("Complete month name for use by strftime", "January");
4768 monthnames[1] = C_("Complete month name for use by strftime", "February");
4769 monthnames[2] = C_("Complete month name for use by strftime", "March");
4770 monthnames[3] = C_("Complete month name for use by strftime", "April");
4771 monthnames[4] = C_("Complete month name for use by strftime", "May");
4772 monthnames[5] = C_("Complete month name for use by strftime", "June");
4773 monthnames[6] = C_("Complete month name for use by strftime", "July");
4774 monthnames[7] = C_("Complete month name for use by strftime", "August");
4775 monthnames[8] = C_("Complete month name for use by strftime", "September");
4776 monthnames[9] = C_("Complete month name for use by strftime", "October");
4777 monthnames[10] = C_("Complete month name for use by strftime", "November");
4778 monthnames[11] = C_("Complete month name for use by strftime", "December");
4780 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4781 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4782 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4783 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4784 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4785 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4786 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4788 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4789 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4790 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4791 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4792 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4793 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4794 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4795 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4796 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4797 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4798 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4799 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4801 for (i = 0; i < 7; i++) {
4802 daynames_len[i] = strlen(daynames[i]);
4803 s_daynames_len[i] = strlen(s_daynames[i]);
4805 for (i = 0; i < 12; i++) {
4806 monthnames_len[i] = strlen(monthnames[i]);
4807 s_monthnames_len[i] = strlen(s_monthnames[i]);
4810 s_am_up = C_("For use by strftime (morning)", "AM");
4811 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4812 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4813 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4815 s_am_up_len = strlen(s_am_up);
4816 s_pm_up_len = strlen(s_pm_up);
4817 s_am_low_len = strlen(s_am_low);
4818 s_pm_low_len = strlen(s_pm_low);
4820 time_names_init_done = TRUE;
4823 #define CHECK_SIZE() { \
4824 total_done += len; \
4825 if (total_done >= buflen) { \
4826 buf[buflen-1] = '\0'; \
4831 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4833 gchar *curpos = buf;
4834 gint total_done = 0;
4835 gchar subbuf[64], subfmt[64];
4836 static time_t last_tzset = (time_t)0;
4838 if (!time_names_init_done)
4841 if (format == NULL || lt == NULL)
4844 if (last_tzset != time(NULL)) {
4846 last_tzset = time(NULL);
4849 if (*format == '%') {
4850 gint len = 0, tmp = 0;
4854 len = 1; CHECK_SIZE();
4858 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4859 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4862 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4863 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4867 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4868 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4871 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4872 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4875 strftime(subbuf, 64, "%c", lt);
4876 len = strlen(subbuf); CHECK_SIZE();
4877 strncpy2(curpos, subbuf, buflen - total_done);
4880 total_done += 2; CHECK_SIZE();
4881 tmp = (lt->tm_year + 1900)/100;
4882 *curpos++ = '0'+(tmp / 10);
4883 *curpos++ = '0'+(tmp % 10);
4886 total_done += 2; CHECK_SIZE();
4887 *curpos++ = '0'+(lt->tm_mday / 10);
4888 *curpos++ = '0'+(lt->tm_mday % 10);
4891 total_done += 8; CHECK_SIZE();
4892 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4893 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4895 *curpos++ = '0'+(lt->tm_mday / 10);
4896 *curpos++ = '0'+(lt->tm_mday % 10);
4898 tmp = lt->tm_year%100;
4899 *curpos++ = '0'+(tmp / 10);
4900 *curpos++ = '0'+(tmp % 10);
4903 len = 2; CHECK_SIZE();
4904 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4907 len = 10; CHECK_SIZE();
4908 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4909 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4912 total_done += 2; CHECK_SIZE();
4913 *curpos++ = '0'+(lt->tm_hour / 10);
4914 *curpos++ = '0'+(lt->tm_hour % 10);
4917 total_done += 2; CHECK_SIZE();
4923 *curpos++ = '0'+(tmp / 10);
4924 *curpos++ = '0'+(tmp % 10);
4927 len = 3; CHECK_SIZE();
4928 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4931 len = 2; CHECK_SIZE();
4932 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4935 len = 2; CHECK_SIZE();
4941 snprintf(curpos, buflen - total_done, "%2d", tmp);
4944 total_done += 2; CHECK_SIZE();
4945 tmp = lt->tm_mon + 1;
4946 *curpos++ = '0'+(tmp / 10);
4947 *curpos++ = '0'+(tmp % 10);
4950 total_done += 2; CHECK_SIZE();
4951 *curpos++ = '0'+(lt->tm_min / 10);
4952 *curpos++ = '0'+(lt->tm_min % 10);
4955 len = 1; CHECK_SIZE();
4959 if (lt->tm_hour >= 12) {
4960 len = s_pm_up_len; CHECK_SIZE();
4961 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4963 len = s_am_up_len; CHECK_SIZE();
4964 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4968 if (lt->tm_hour >= 12) {
4969 len = s_pm_low_len; CHECK_SIZE();
4970 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4972 len = s_am_low_len; CHECK_SIZE();
4973 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4977 strftime(subbuf, 64, "%r", lt);
4978 len = strlen(subbuf); CHECK_SIZE();
4979 strncpy2(curpos, subbuf, buflen - total_done);
4982 total_done += 5; CHECK_SIZE();
4983 *curpos++ = '0'+(lt->tm_hour / 10);
4984 *curpos++ = '0'+(lt->tm_hour % 10);
4986 *curpos++ = '0'+(lt->tm_min / 10);
4987 *curpos++ = '0'+(lt->tm_min % 10);
4990 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
4991 len = strlen(subbuf); CHECK_SIZE();
4992 strncpy2(curpos, subbuf, buflen - total_done);
4995 total_done += 2; CHECK_SIZE();
4996 *curpos++ = '0'+(lt->tm_sec / 10);
4997 *curpos++ = '0'+(lt->tm_sec % 10);
5000 len = 1; CHECK_SIZE();
5004 total_done += 8; CHECK_SIZE();
5005 *curpos++ = '0'+(lt->tm_hour / 10);
5006 *curpos++ = '0'+(lt->tm_hour % 10);
5008 *curpos++ = '0'+(lt->tm_min / 10);
5009 *curpos++ = '0'+(lt->tm_min % 10);
5011 *curpos++ = '0'+(lt->tm_sec / 10);
5012 *curpos++ = '0'+(lt->tm_sec % 10);
5015 len = 1; CHECK_SIZE();
5016 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
5019 len = 1; CHECK_SIZE();
5020 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
5023 strftime(subbuf, 64, "%x", lt);
5024 len = strlen(subbuf); CHECK_SIZE();
5025 strncpy2(curpos, subbuf, buflen - total_done);
5028 strftime(subbuf, 64, "%X", lt);
5029 len = strlen(subbuf); CHECK_SIZE();
5030 strncpy2(curpos, subbuf, buflen - total_done);
5033 total_done += 2; CHECK_SIZE();
5034 tmp = lt->tm_year%100;
5035 *curpos++ = '0'+(tmp / 10);
5036 *curpos++ = '0'+(tmp % 10);
5039 len = 4; CHECK_SIZE();
5040 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
5050 /* let these complicated ones be done with the libc */
5051 snprintf(subfmt, 64, "%%%c", *format);
5052 strftime(subbuf, 64, subfmt, lt);
5053 len = strlen(subbuf); CHECK_SIZE();
5054 strncpy2(curpos, subbuf, buflen - total_done);
5058 /* let these complicated modifiers be done with the libc */
5059 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
5060 strftime(subbuf, 64, subfmt, lt);
5061 len = strlen(subbuf); CHECK_SIZE();
5062 strncpy2(curpos, subbuf, buflen - total_done);
5066 g_warning("format error (%c)", *format);
5073 int len = 1; CHECK_SIZE();
5074 *curpos++ = *format++;
5081 gboolean prefs_common_get_use_shred(void);
5085 #define WEXITSTATUS(x) (x)
5088 int claws_unlink(const gchar *filename)
5091 static int found_shred = -1;
5092 static const gchar *args[4];
5094 if (filename == NULL)
5097 if (prefs_common_get_use_shred()) {
5098 if (found_shred == -1) {
5100 args[0] = g_find_program_in_path("shred");
5101 debug_print("found shred: %s\n", args[0]);
5102 found_shred = (args[0] != NULL) ? 1:0;
5106 if (found_shred == 1) {
5107 if (g_stat(filename, &s) == 0 && S_ISREG(s.st_mode)) {
5108 if (s.st_nlink == 1) {
5111 g_spawn_sync(NULL, (gchar **)args, NULL, 0,
5112 NULL, NULL, NULL, NULL, &status, NULL);
5113 debug_print("%s %s exited with status %d\n",
5114 args[0], filename, WEXITSTATUS(status));
5115 if (truncate(filename, 0) < 0)
5116 g_warning("couln't truncate: %s", filename);
5121 return g_unlink(filename);
5124 GMutex *cm_mutex_new(void) {
5125 #if GLIB_CHECK_VERSION(2,32,0)
5126 GMutex *m = g_new0(GMutex, 1);
5130 return g_mutex_new();
5134 void cm_mutex_free(GMutex *mutex) {
5135 #if GLIB_CHECK_VERSION(2,32,0)
5136 g_mutex_clear(mutex);
5139 g_mutex_free(mutex);
5143 static gchar *canonical_list_to_file(GSList *list)
5145 GString *result = g_string_new(NULL);
5146 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
5151 result = g_string_append(result, G_DIR_SEPARATOR_S);
5153 if (pathlist->data) {
5154 const gchar *root = (gchar *)pathlist->data;
5155 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
5157 /* drive - don't prepend dir separator */
5159 result = g_string_append(result, G_DIR_SEPARATOR_S);
5164 for (cur = pathlist; cur; cur = cur->next) {
5165 result = g_string_append(result, (gchar *)cur->data);
5167 result = g_string_append(result, G_DIR_SEPARATOR_S);
5169 g_slist_free(pathlist);
5172 g_string_free(result, FALSE);
5177 static GSList *cm_split_path(const gchar *filename, int depth)
5180 GSList *canonical_parts = NULL;
5184 gboolean follow_symlinks = TRUE;
5191 errno = EINVAL; /* can't happen, no symlink handling */
5196 if (!g_path_is_absolute(filename)) {
5201 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
5203 for (i = 0; path_parts[i] != NULL; i++) {
5204 if (!strcmp(path_parts[i], ""))
5206 if (!strcmp(path_parts[i], "."))
5208 else if (!strcmp(path_parts[i], "..")) {
5213 else /* Remove the last inserted element */
5215 g_slist_delete_link(canonical_parts,
5220 canonical_parts = g_slist_prepend(canonical_parts,
5221 g_strdup(path_parts[i]));
5223 tmp_path = canonical_list_to_file(canonical_parts);
5225 if(g_stat(tmp_path, &st) < 0) {
5226 if (errno == ENOENT) {
5229 follow_symlinks = FALSE;
5234 slist_free_strings_full(canonical_parts);
5235 g_strfreev(path_parts);
5241 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
5242 GError *error = NULL;
5243 gchar *target = g_file_read_link(tmp_path, &error);
5245 if (!g_path_is_absolute(target)) {
5246 /* remove the last inserted element */
5248 g_slist_delete_link(canonical_parts,
5250 /* add the target */
5251 canonical_parts = g_slist_prepend(canonical_parts,
5255 /* and get the new target */
5256 target = canonical_list_to_file(canonical_parts);
5259 /* restart from absolute target */
5260 slist_free_strings_full(canonical_parts);
5261 canonical_parts = NULL;
5263 canonical_parts = cm_split_path(target, depth + 1);
5265 g_error_free(error);
5266 if (canonical_parts == NULL) {
5268 g_strfreev(path_parts);
5277 g_strfreev(path_parts);
5278 return canonical_parts;
5282 * Canonicalize a filename, resolving symlinks along the way.
5283 * Returns a negative errno in case of error.
5285 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
5286 GSList *canonical_parts;
5287 gboolean is_absolute;
5289 if (filename == NULL)
5291 if (canonical_name == NULL)
5293 *canonical_name = NULL;
5295 is_absolute = g_path_is_absolute(filename);
5297 /* Always work on absolute filenames. */
5298 gchar *cur = g_get_current_dir();
5299 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
5302 canonical_parts = cm_split_path(absolute_filename, 0);
5303 g_free(absolute_filename);
5306 canonical_parts = cm_split_path(filename, 0);
5308 if (canonical_parts == NULL)
5311 *canonical_name = canonical_list_to_file(canonical_parts);
5312 slist_free_strings_full(canonical_parts);
5316 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
5317 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
5319 gchar *tmp = g_base64_decode(text, out_len);
5320 gchar *out = g_strndup(tmp, *out_len);
5324 if (strlen(out) != *out_len) {
5325 g_warning ("strlen(out) %zd != *out_len %" G_GSIZE_FORMAT, strlen(out), *out_len);
5331 #if !GLIB_CHECK_VERSION(2, 30, 0)
5334 * @str: a UTF-8 encoded string
5335 * @start_pos: a character offset within @str
5336 * @end_pos: another character offset within @str
5338 * Copies a substring out of a UTF-8 encoded string.
5339 * The substring will contain @end_pos - @start_pos
5342 * Returns: a newly allocated copy of the requested
5343 * substring. Free with g_free() when no longer needed.
5348 g_utf8_substring (const gchar *str,
5352 gchar *start, *end, *out;
5354 start = g_utf8_offset_to_pointer (str, start_pos);
5355 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
5357 out = g_malloc (end - start + 1);
5358 memcpy (out, start, end - start);
5359 out[end - start] = 0;
5365 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
5366 * It is up to the caller to make sure there is at least count bytes
5367 * available at buf. */
5369 get_random_bytes(void *buf, size_t count)
5371 /* Open our prng source. */
5372 #if defined G_OS_WIN32
5375 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
5376 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
5377 debug_print("Could not acquire a CSP handle.\n");
5384 rnd = open("/dev/urandom", O_RDONLY);
5386 FILE_OP_ERROR("/dev/urandom", "open");
5387 debug_print("Could not open /dev/urandom.\n");
5392 /* Read data from the source into buf. */
5393 #if defined G_OS_WIN32
5394 if (!CryptGenRandom(rnd, count, buf)) {
5395 debug_print("Could not read %zd random bytes.\n", count);
5396 CryptReleaseContext(rnd, 0);
5400 ret = read(rnd, buf, count);
5402 FILE_OP_ERROR("/dev/urandom", "read");
5403 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
5409 /* Close the prng source. */
5410 #if defined G_OS_WIN32
5411 CryptReleaseContext(rnd, 0);