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 /* Return true if we are running as root. This function should beused
94 instead of getuid () == 0. */
95 gboolean superuser_p (void)
98 return w32_is_administrator ();
104 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
106 #if GLIB_CHECK_VERSION(2, 34, 0)
107 return g_slist_copy_deep(list, func, NULL);
109 GSList *res = g_slist_copy(list);
112 walk->data = func(walk->data, NULL);
119 void list_free_strings_full(GList *list)
121 g_list_free_full(list, (GDestroyNotify)g_free);
124 void slist_free_strings_full(GSList *list)
126 g_slist_free_full(list, (GDestroyNotify)g_free);
129 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
134 void hash_free_strings(GHashTable *table)
136 g_hash_table_foreach(table, hash_free_strings_func, NULL);
139 gint str_case_equal(gconstpointer v, gconstpointer v2)
141 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
144 guint str_case_hash(gconstpointer key)
146 const gchar *p = key;
150 h = g_ascii_tolower(h);
151 for (p += 1; *p != '\0'; p++)
152 h = (h << 5) - h + g_ascii_tolower(*p);
158 void ptr_array_free_strings(GPtrArray *array)
163 cm_return_if_fail(array != NULL);
165 for (i = 0; i < array->len; i++) {
166 str = g_ptr_array_index(array, i);
171 gint to_number(const gchar *nstr)
173 register const gchar *p;
175 if (*nstr == '\0') return -1;
177 for (p = nstr; *p != '\0'; p++)
178 if (!g_ascii_isdigit(*p)) return -1;
183 /* convert integer into string,
184 nstr must be not lower than 11 characters length */
185 gchar *itos_buf(gchar *nstr, gint n)
187 g_snprintf(nstr, 11, "%d", n);
191 /* convert integer into string */
194 static gchar nstr[11];
196 return itos_buf(nstr, n);
199 #define divide(num,divisor,i,d) \
201 i = num >> divisor; \
202 d = num & ((1<<divisor)-1); \
203 d = (d*100) >> divisor; \
208 * \brief Convert a given size in bytes in a human-readable string
210 * \param size The size expressed in bytes to convert in string
211 * \return The string that respresents the size in an human-readable way
213 gchar *to_human_readable(goffset size)
215 static gchar str[14];
216 static gchar *b_format = NULL, *kb_format = NULL,
217 *mb_format = NULL, *gb_format = NULL;
218 register int t = 0, r = 0;
219 if (b_format == NULL) {
221 kb_format = _("%d.%02dKB");
222 mb_format = _("%d.%02dMB");
223 gb_format = _("%.2fGB");
226 if (size < (goffset)1024) {
227 g_snprintf(str, sizeof(str), b_format, (gint)size);
229 } else if (size >> 10 < (goffset)1024) {
230 divide(size, 10, t, r);
231 g_snprintf(str, sizeof(str), kb_format, t, r);
233 } else if (size >> 20 < (goffset)1024) {
234 divide(size, 20, t, r);
235 g_snprintf(str, sizeof(str), mb_format, t, r);
238 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
243 /* strcmp with NULL-checking */
244 gint strcmp2(const gchar *s1, const gchar *s2)
246 if (s1 == NULL || s2 == NULL)
249 return strcmp(s1, s2);
251 /* strstr with NULL-checking */
252 gchar *strstr2(const gchar *s1, const gchar *s2)
254 if (s1 == NULL || s2 == NULL)
257 return strstr(s1, s2);
260 gint path_cmp(const gchar *s1, const gchar *s2)
265 gchar *s1buf, *s2buf;
268 if (s1 == NULL || s2 == NULL) return -1;
269 if (*s1 == '\0' || *s2 == '\0') return -1;
272 s1buf = g_strdup (s1);
273 s2buf = g_strdup (s2);
274 subst_char (s1buf, '/', G_DIR_SEPARATOR);
275 subst_char (s2buf, '/', G_DIR_SEPARATOR);
278 #endif /* !G_OS_WIN32 */
283 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
284 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
286 rc = strncmp(s1, s2, MAX(len1, len2));
290 #endif /* !G_OS_WIN32 */
294 /* remove trailing return code */
295 gchar *strretchomp(gchar *str)
299 if (!*str) return str;
301 for (s = str + strlen(str) - 1;
302 s >= str && (*s == '\n' || *s == '\r');
309 /* remove trailing character */
310 gchar *strtailchomp(gchar *str, gchar tail_char)
314 if (!*str) return str;
315 if (tail_char == '\0') return str;
317 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
323 /* remove CR (carriage return) */
324 gchar *strcrchomp(gchar *str)
328 if (!*str) return str;
330 s = str + strlen(str) - 1;
331 if (*s == '\n' && s > str && *(s - 1) == '\r') {
339 gint file_strip_crs(const gchar *file)
341 FILE *fp = NULL, *outfp = NULL;
343 gchar *out = get_tmp_file();
347 fp = g_fopen(file, "rb");
351 outfp = g_fopen(out, "wb");
357 while (fgets(buf, sizeof (buf), fp) != NULL) {
359 if (fputs(buf, outfp) == EOF) {
367 if (fclose(outfp) == EOF) {
371 if (move_file(out, file, TRUE) < 0)
383 /* Similar to `strstr' but this function ignores the case of both strings. */
384 gchar *strcasestr(const gchar *haystack, const gchar *needle)
386 size_t haystack_len = strlen(haystack);
388 return strncasestr(haystack, haystack_len, needle);
391 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
393 register size_t needle_len;
395 needle_len = strlen(needle);
397 if (haystack_len < needle_len || needle_len == 0)
400 while (haystack_len >= needle_len) {
401 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
402 return (gchar *)haystack;
412 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
413 gconstpointer needle, size_t needlelen)
415 const gchar *haystack_ = (const gchar *)haystack;
416 const gchar *needle_ = (const gchar *)needle;
417 const gchar *haystack_cur = (const gchar *)haystack;
418 size_t haystack_left = haystacklen;
421 return memchr(haystack_, *needle_, haystacklen);
423 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
425 if (haystacklen - (haystack_cur - haystack_) < needlelen)
427 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
428 return (gpointer)haystack_cur;
431 haystack_left = haystacklen - (haystack_cur - haystack_);
438 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
439 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
441 register const gchar *s = src;
442 register gchar *d = dest;
452 /* Examine if next block is non-ASCII string */
453 gboolean is_next_nonascii(const gchar *s)
457 /* skip head space */
458 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
460 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
461 if (*(guchar *)p > 127 || *(guchar *)p < 32)
468 gint get_next_word_len(const gchar *s)
472 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
478 static void trim_subject_for_compare(gchar *str)
482 eliminate_parenthesis(str, '[', ']');
483 eliminate_parenthesis(str, '(', ')');
486 srcp = str + subject_get_prefix_length(str);
488 memmove(str, srcp, strlen(srcp) + 1);
491 static void trim_subject_for_sort(gchar *str)
497 srcp = str + subject_get_prefix_length(str);
499 memmove(str, srcp, strlen(srcp) + 1);
502 /* compare subjects */
503 gint subject_compare(const gchar *s1, const gchar *s2)
507 if (!s1 || !s2) return -1;
508 if (!*s1 || !*s2) return -1;
510 Xstrdup_a(str1, s1, return -1);
511 Xstrdup_a(str2, s2, return -1);
513 trim_subject_for_compare(str1);
514 trim_subject_for_compare(str2);
516 if (!*str1 || !*str2) return -1;
518 return strcmp(str1, str2);
521 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
525 if (!s1 || !s2) return -1;
527 Xstrdup_a(str1, s1, return -1);
528 Xstrdup_a(str2, s2, return -1);
530 trim_subject_for_sort(str1);
531 trim_subject_for_sort(str2);
533 return g_utf8_collate(str1, str2);
536 void trim_subject(gchar *str)
538 register gchar *srcp;
544 srcp = str + subject_get_prefix_length(str);
549 } else if (*srcp == '(') {
561 else if (*srcp == cl)
568 while (g_ascii_isspace(*srcp)) srcp++;
569 memmove(str, srcp, strlen(srcp) + 1);
572 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
574 register gchar *srcp, *destp;
579 while ((destp = strchr(destp, op))) {
585 else if (*srcp == cl)
591 while (g_ascii_isspace(*srcp)) srcp++;
592 memmove(destp, srcp, strlen(srcp) + 1);
596 void extract_parenthesis(gchar *str, gchar op, gchar cl)
598 register gchar *srcp, *destp;
603 while ((srcp = strchr(destp, op))) {
606 memmove(destp, srcp + 1, strlen(srcp));
611 else if (*destp == cl)
623 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
626 register gchar *srcp, *destp;
628 gboolean in_quote = FALSE;
632 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
635 memmove(destp, srcp + 1, strlen(srcp));
638 if (*destp == op && !in_quote)
640 else if (*destp == cl && !in_quote)
642 else if (*destp == quote_chr)
654 void extract_quote(gchar *str, gchar quote_chr)
658 if ((str = strchr(str, quote_chr))) {
660 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
661 memmove(p - 1, p, strlen(p) + 1);
666 memmove(str, str + 1, p - str);
671 /* Returns a newly allocated string with all quote_chr not at the beginning
672 or the end of str escaped with '\' or the given str if not required. */
673 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
675 register gchar *p, *q;
679 if (str == NULL || *str == '\0')
682 /* search for unescaped quote_chr */
687 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
691 if (!k) /* nothing to escape */
694 /* unescaped quote_chr found */
695 qstr = g_malloc(l + k + 1);
698 if (*p == quote_chr) {
703 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
712 void eliminate_address_comment(gchar *str)
714 register gchar *srcp, *destp;
719 while ((destp = strchr(destp, '"'))) {
720 if ((srcp = strchr(destp + 1, '"'))) {
725 while (g_ascii_isspace(*srcp)) srcp++;
726 memmove(destp, srcp, strlen(srcp) + 1);
736 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
742 else if (*srcp == ')')
748 while (g_ascii_isspace(*srcp)) srcp++;
749 memmove(destp, srcp, strlen(srcp) + 1);
753 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
755 gboolean in_quote = FALSE;
758 if (*str == c && !in_quote)
760 if (*str == quote_chr)
768 void extract_address(gchar *str)
770 cm_return_if_fail(str != NULL);
771 eliminate_address_comment(str);
772 if (strchr_with_skip_quote(str, '"', '<'))
773 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
777 void extract_list_id_str(gchar *str)
779 if (strchr_with_skip_quote(str, '"', '<'))
780 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
784 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
789 if (!str) return addr_list;
791 Xstrdup_a(work, str, return addr_list);
794 eliminate_address_comment(work);
797 while (workp && *workp) {
800 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
806 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
807 extract_parenthesis_with_skip_quote
808 (workp, '"', '<', '>');
812 addr_list = g_slist_append(addr_list, g_strdup(workp));
820 GSList *address_list_append(GSList *addr_list, const gchar *str)
822 return address_list_append_real(addr_list, str, TRUE);
825 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
827 return address_list_append_real(addr_list, str, FALSE);
830 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
834 if (!str) return msgid_list;
837 while (strp && *strp) {
838 const gchar *start, *end;
841 if ((start = strchr(strp, '<')) != NULL) {
842 end = strchr(start + 1, '>');
847 msgid = g_strndup(start + 1, end - start - 1);
850 msgid_list = g_slist_prepend(msgid_list, msgid);
860 GSList *references_list_append(GSList *msgid_list, const gchar *str)
864 list = references_list_prepend(NULL, str);
865 list = g_slist_reverse(list);
866 msgid_list = g_slist_concat(msgid_list, list);
871 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
876 if (!str) return group_list;
878 Xstrdup_a(work, str, return group_list);
882 while (workp && *workp) {
885 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
893 group_list = g_slist_append(group_list,
902 GList *add_history(GList *list, const gchar *str)
907 cm_return_val_if_fail(str != NULL, list);
909 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
912 list = g_list_remove(list, old->data);
914 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
917 last = g_list_last(list);
920 list = g_list_remove(list, last->data);
925 list = g_list_prepend(list, g_strdup(str));
930 void remove_return(gchar *str)
932 register gchar *p = str;
935 if (*p == '\n' || *p == '\r')
936 memmove(p, p + 1, strlen(p));
942 void remove_space(gchar *str)
944 register gchar *p = str;
949 while (g_ascii_isspace(*(p + spc)))
952 memmove(p, p + spc, strlen(p + spc) + 1);
958 void unfold_line(gchar *str)
964 ch = str; /* iterator for source string */
967 c = g_utf8_get_char_validated(ch, -1);
969 if (c == (gunichar)-1 || c == (gunichar)-2) {
970 /* non-unicode byte, move past it */
975 len = g_unichar_to_utf8(c, NULL);
977 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
978 g_unichar_isspace(c)) {
979 /* replace anything bad or whitespacey with a single space */
983 /* move rest of the string forwards, since we just replaced
984 * a multi-byte sequence with one byte */
985 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
988 /* A valid unicode character, copy it. */
994 void subst_char(gchar *str, gchar orig, gchar subst)
996 register gchar *p = str;
1005 void subst_chars(gchar *str, gchar *orig, gchar subst)
1007 register gchar *p = str;
1010 if (strchr(orig, *p) != NULL)
1016 void subst_for_filename(gchar *str)
1021 subst_chars(str, "\t\r\n\\/*?:", '_');
1023 subst_chars(str, "\t\r\n\\/*", '_');
1027 void subst_for_shellsafe_filename(gchar *str)
1031 subst_for_filename(str);
1032 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1035 gboolean is_ascii_str(const gchar *str)
1037 const guchar *p = (const guchar *)str;
1039 while (*p != '\0') {
1040 if (*p != '\t' && *p != ' ' &&
1041 *p != '\r' && *p != '\n' &&
1042 (*p < 32 || *p >= 127))
1050 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1052 gchar * position = NULL;
1053 gchar * tmp_pos = NULL;
1056 if (str == NULL || quote_chars == NULL)
1059 for (i = 0; i < strlen(quote_chars); i++) {
1060 tmp_pos = strrchr (str, quote_chars[i]);
1062 || (tmp_pos != NULL && position <= tmp_pos) )
1068 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1070 const gchar *first_pos;
1071 const gchar *last_pos;
1072 const gchar *p = str;
1073 gint quote_level = -1;
1075 /* speed up line processing by only searching to the last '>' */
1076 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1077 /* skip a line if it contains a '<' before the initial '>' */
1078 if (memchr(str, '<', first_pos - str) != NULL)
1080 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1084 while (p <= last_pos) {
1085 while (p < last_pos) {
1086 if (g_ascii_isspace(*p))
1092 if (strchr(quote_chars, *p))
1094 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1095 /* any characters are allowed except '-','<' and space */
1096 while (*p != '-' && *p != '<'
1097 && !strchr(quote_chars, *p)
1098 && !g_ascii_isspace(*p)
1101 if (strchr(quote_chars, *p))
1113 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1115 const gchar *p = str, *q;
1116 gint cur_line = 0, len;
1118 while ((q = strchr(p, '\n')) != NULL) {
1120 if (len > max_chars) {
1130 if (len > max_chars) {
1139 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1141 gchar * position = NULL;
1142 gchar * tmp_pos = NULL;
1145 if (str == NULL || quote_chars == NULL)
1148 for (i = 0; i < strlen(quote_chars); i++) {
1149 tmp_pos = strchr (str, quote_chars[i]);
1151 || (tmp_pos != NULL && position >= tmp_pos) )
1157 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1159 register guint haystack_len, needle_len;
1160 gboolean in_squote = FALSE, in_dquote = FALSE;
1162 haystack_len = strlen(haystack);
1163 needle_len = strlen(needle);
1165 if (haystack_len < needle_len || needle_len == 0)
1168 while (haystack_len >= needle_len) {
1169 if (!in_squote && !in_dquote &&
1170 !strncmp(haystack, needle, needle_len))
1171 return (gchar *)haystack;
1173 /* 'foo"bar"' -> foo"bar"
1174 "foo'bar'" -> foo'bar' */
1175 if (*haystack == '\'') {
1178 else if (!in_dquote)
1180 } else if (*haystack == '\"') {
1183 else if (!in_squote)
1185 } else if (*haystack == '\\') {
1197 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1200 GSList *string_list = NULL, *slist;
1201 gchar **str_array, *s, *new_str;
1202 guint i, n = 1, len;
1204 cm_return_val_if_fail(str != NULL, NULL);
1205 cm_return_val_if_fail(delim != NULL, NULL);
1208 max_tokens = G_MAXINT;
1210 s = strstr_with_skip_quote(str, delim);
1212 guint delimiter_len = strlen(delim);
1216 new_str = g_strndup(str, len);
1218 if (new_str[0] == '\'' || new_str[0] == '\"') {
1219 if (new_str[len - 1] == new_str[0]) {
1220 new_str[len - 1] = '\0';
1221 memmove(new_str, new_str + 1, len - 1);
1224 string_list = g_slist_prepend(string_list, new_str);
1226 str = s + delimiter_len;
1227 s = strstr_with_skip_quote(str, delim);
1228 } while (--max_tokens && s);
1232 new_str = g_strdup(str);
1233 if (new_str[0] == '\'' || new_str[0] == '\"') {
1235 if (new_str[len - 1] == new_str[0]) {
1236 new_str[len - 1] = '\0';
1237 memmove(new_str, new_str + 1, len - 1);
1240 string_list = g_slist_prepend(string_list, new_str);
1244 str_array = g_new(gchar*, n);
1248 str_array[i--] = NULL;
1249 for (slist = string_list; slist; slist = slist->next)
1250 str_array[i--] = slist->data;
1252 g_slist_free(string_list);
1257 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1259 gchar *abbrev_group;
1261 const gchar *p = group;
1264 cm_return_val_if_fail(group != NULL, NULL);
1266 last = group + strlen(group);
1267 abbrev_group = ap = g_malloc(strlen(group) + 1);
1272 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1274 while (*p != '.') p++;
1277 return abbrev_group;
1282 return abbrev_group;
1285 gchar *trim_string(const gchar *str, gint len)
1287 const gchar *p = str;
1292 if (!str) return NULL;
1293 if (strlen(str) <= len)
1294 return g_strdup(str);
1295 if (g_utf8_validate(str, -1, NULL) == FALSE)
1296 return g_strdup(str);
1298 while (*p != '\0') {
1299 mb_len = g_utf8_skip[*(guchar *)p];
1302 else if (new_len + mb_len > len)
1309 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1310 return g_strconcat(new_str, "...", NULL);
1313 GList *uri_list_extract_filenames(const gchar *uri_list)
1315 GList *result = NULL;
1317 gchar *escaped_utf8uri;
1323 while (g_ascii_isspace(*p)) p++;
1324 if (!strncmp(p, "file:", 5)) {
1327 while (*q && *q != '\n' && *q != '\r') q++;
1330 gchar *file, *locale_file = NULL;
1332 while (q > p && g_ascii_isspace(*q))
1334 Xalloca(escaped_utf8uri, q - p + 2,
1336 Xalloca(file, q - p + 2,
1339 strncpy(escaped_utf8uri, p, q - p + 1);
1340 escaped_utf8uri[q - p + 1] = '\0';
1341 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1343 * g_filename_from_uri() rejects escaped/locale encoded uri
1344 * string which come from Nautilus.
1347 if (g_utf8_validate(file, -1, NULL))
1349 = conv_codeset_strdup(
1352 conv_get_locale_charset_str());
1354 locale_file = g_strdup(file + 5);
1356 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1358 result = g_list_append(result, locale_file);
1362 p = strchr(p, '\n');
1369 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1372 static gint axtoi(const gchar *hexstr)
1374 gint hi, lo, result;
1377 if ('0' <= hi && hi <= '9') {
1380 if ('a' <= hi && hi <= 'f') {
1383 if ('A' <= hi && hi <= 'F') {
1388 if ('0' <= lo && lo <= '9') {
1391 if ('a' <= lo && lo <= 'f') {
1394 if ('A' <= lo && lo <= 'F') {
1397 result = lo + (16 * hi);
1401 gboolean is_uri_string(const gchar *str)
1403 while (str && *str && g_ascii_isspace(*str))
1405 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1406 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1407 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1408 g_ascii_strncasecmp(str, "www.", 4) == 0);
1411 gchar *get_uri_path(const gchar *uri)
1413 while (uri && *uri && g_ascii_isspace(*uri))
1415 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1416 return (gchar *)(uri + 7);
1417 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1418 return (gchar *)(uri + 8);
1419 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1420 return (gchar *)(uri + 6);
1422 return (gchar *)uri;
1425 gint get_uri_len(const gchar *str)
1429 if (is_uri_string(str)) {
1430 for (p = str; *p != '\0'; p++) {
1431 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1440 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1441 * plusses, and escape characters are used)
1443 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1445 gchar *dec = decoded_uri;
1446 const gchar *enc = encoded_uri;
1451 if (isxdigit((guchar)enc[0]) &&
1452 isxdigit((guchar)enc[1])) {
1458 if (with_plus && *enc == '+')
1470 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1472 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1475 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1477 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1478 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1482 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1483 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1487 const gchar *forbidden_uris[] = { ".gnupg/",
1493 gint num_attach = 0;
1494 gchar **my_att = NULL;
1496 Xstrdup_a(tmp_mailto, mailto, return -1);
1498 if (!strncmp(tmp_mailto, "mailto:", 7))
1501 p = strchr(tmp_mailto, '?');
1508 *to = decode_uri_gdup(tmp_mailto);
1510 my_att = g_malloc(sizeof(char *));
1514 gchar *field, *value;
1531 if (*value == '\0') continue;
1533 if (from && !g_ascii_strcasecmp(field, "from")) {
1535 *from = decode_uri_gdup(value);
1537 gchar *tmp = decode_uri_gdup(value);
1538 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1542 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1544 *cc = decode_uri_gdup(value);
1546 gchar *tmp = decode_uri_gdup(value);
1547 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1551 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1553 *bcc = decode_uri_gdup(value);
1555 gchar *tmp = decode_uri_gdup(value);
1556 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1560 } else if (subject && !*subject &&
1561 !g_ascii_strcasecmp(field, "subject")) {
1562 *subject = decode_uri_gdup(value);
1563 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1564 *body = decode_uri_gdup(value);
1565 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1566 gchar *tmp = decode_uri_gdup(value);
1567 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1568 g_warning("couldn't set insert file '%s' in body", value);
1571 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1573 gchar *tmp = decode_uri_gdup(value);
1574 for (; forbidden_uris[i]; i++) {
1575 if (strstr(tmp, forbidden_uris[i])) {
1576 g_print("Refusing to attach '%s', potential private data leak\n",
1583 /* attach is correct */
1585 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1586 my_att[num_attach-1] = tmp;
1587 my_att[num_attach] = NULL;
1589 } else if (inreplyto && !*inreplyto &&
1590 !g_ascii_strcasecmp(field, "in-reply-to")) {
1591 *inreplyto = decode_uri_gdup(value);
1602 #include <windows.h>
1603 #ifndef CSIDL_APPDATA
1604 #define CSIDL_APPDATA 0x001a
1606 #ifndef CSIDL_LOCAL_APPDATA
1607 #define CSIDL_LOCAL_APPDATA 0x001c
1609 #ifndef CSIDL_FLAG_CREATE
1610 #define CSIDL_FLAG_CREATE 0x8000
1612 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1616 w32_strerror (int w32_errno)
1618 static char strerr[256];
1619 int ec = (int)GetLastError ();
1623 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1624 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1625 strerr, DIM (strerr)-1, NULL);
1629 static __inline__ void *
1630 dlopen (const char * name, int flag)
1632 void * hd = LoadLibrary (name);
1636 static __inline__ void *
1637 dlsym (void * hd, const char * sym)
1641 void * fnc = GetProcAddress (hd, sym);
1650 static __inline__ const char *
1653 return w32_strerror (0);
1657 static __inline__ int
1669 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1671 static int initialized;
1672 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1676 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1682 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1684 handle = dlopen (dllnames[i], RTLD_LAZY);
1687 func = dlsym (handle, "SHGetFolderPathW");
1698 return func (a,b,c,d,e);
1703 /* Returns a static string with the directroy from which the module
1704 has been loaded. Returns an empty string on error. */
1705 static char *w32_get_module_dir(void)
1707 static char *moddir;
1710 char name[MAX_PATH+10];
1713 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1716 p = strrchr (name, '\\');
1722 moddir = g_strdup (name);
1726 #endif /* G_OS_WIN32 */
1728 /* Return a static string with the locale dir. */
1729 const gchar *get_locale_dir(void)
1731 static gchar *loc_dir;
1735 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1736 "\\share\\locale", NULL);
1739 loc_dir = LOCALEDIR;
1745 const gchar *get_home_dir(void)
1748 static char home_dir_utf16[MAX_PATH] = "";
1749 static gchar *home_dir_utf8 = NULL;
1750 if (home_dir_utf16[0] == '\0') {
1751 if (w32_shgetfolderpath
1752 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1753 NULL, 0, home_dir_utf16) < 0)
1754 strcpy (home_dir_utf16, "C:\\Claws Mail");
1755 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1757 return home_dir_utf8;
1759 static const gchar *homeenv = NULL;
1764 if (!homeenv && g_getenv("HOME") != NULL)
1765 homeenv = g_strdup(g_getenv("HOME"));
1767 homeenv = g_get_home_dir();
1773 static gchar *claws_rc_dir = NULL;
1774 static gboolean rc_dir_alt = FALSE;
1775 const gchar *get_rc_dir(void)
1778 if (!claws_rc_dir) {
1779 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1781 debug_print("using default rc_dir %s\n", claws_rc_dir);
1783 return claws_rc_dir;
1786 void set_rc_dir(const gchar *dir)
1788 gchar *canonical_dir;
1789 if (claws_rc_dir != NULL) {
1790 g_print("Error: rc_dir already set\n");
1792 int err = cm_canonicalize_filename(dir, &canonical_dir);
1796 g_print("Error looking for %s: %d(%s)\n",
1797 dir, -err, g_strerror(-err));
1802 claws_rc_dir = canonical_dir;
1804 len = strlen(claws_rc_dir);
1805 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1806 claws_rc_dir[len - 1] = '\0';
1808 debug_print("set rc_dir to %s\n", claws_rc_dir);
1809 if (!is_dir_exist(claws_rc_dir)) {
1810 if (make_dir_hier(claws_rc_dir) != 0) {
1811 g_print("Error: can't create %s\n",
1819 gboolean rc_dir_is_alt(void) {
1823 const gchar *get_mail_base_dir(void)
1825 return get_home_dir();
1828 const gchar *get_news_cache_dir(void)
1830 static gchar *news_cache_dir = NULL;
1831 if (!news_cache_dir)
1832 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1833 NEWS_CACHE_DIR, NULL);
1835 return news_cache_dir;
1838 const gchar *get_imap_cache_dir(void)
1840 static gchar *imap_cache_dir = NULL;
1842 if (!imap_cache_dir)
1843 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1844 IMAP_CACHE_DIR, NULL);
1846 return imap_cache_dir;
1849 const gchar *get_mime_tmp_dir(void)
1851 static gchar *mime_tmp_dir = NULL;
1854 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1855 MIME_TMP_DIR, NULL);
1857 return mime_tmp_dir;
1860 const gchar *get_template_dir(void)
1862 static gchar *template_dir = NULL;
1865 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1866 TEMPLATE_DIR, NULL);
1868 return template_dir;
1872 const gchar *w32_get_cert_file(void)
1874 const gchar *cert_file = NULL;
1876 cert_file = g_strconcat(w32_get_module_dir(),
1877 "\\share\\claws-mail\\",
1878 "ca-certificates.crt",
1884 /* Return the filepath of the claws-mail.desktop file */
1885 const gchar *get_desktop_file(void)
1887 #ifdef DESKTOPFILEPATH
1888 return DESKTOPFILEPATH;
1894 /* Return the default directory for Plugins. */
1895 const gchar *get_plugin_dir(void)
1898 static gchar *plugin_dir = NULL;
1901 plugin_dir = g_strconcat(w32_get_module_dir(),
1902 "\\lib\\claws-mail\\plugins\\",
1906 if (is_dir_exist(PLUGINDIR))
1909 static gchar *plugin_dir = NULL;
1911 plugin_dir = g_strconcat(get_rc_dir(),
1912 G_DIR_SEPARATOR_S, "plugins",
1913 G_DIR_SEPARATOR_S, NULL);
1921 /* Return the default directory for Themes. */
1922 const gchar *w32_get_themes_dir(void)
1924 static gchar *themes_dir = NULL;
1927 themes_dir = g_strconcat(w32_get_module_dir(),
1928 "\\share\\claws-mail\\themes",
1934 const gchar *get_tmp_dir(void)
1936 static gchar *tmp_dir = NULL;
1939 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1945 gchar *get_tmp_file(void)
1948 static guint32 id = 0;
1950 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1951 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1956 const gchar *get_domain_name(void)
1959 static gchar *domain_name = NULL;
1960 struct addrinfo hints, *res;
1965 if (gethostname(hostname, sizeof(hostname)) != 0) {
1966 perror("gethostname");
1967 domain_name = "localhost";
1969 memset(&hints, 0, sizeof(struct addrinfo));
1970 hints.ai_family = AF_UNSPEC;
1971 hints.ai_socktype = 0;
1972 hints.ai_flags = AI_CANONNAME;
1973 hints.ai_protocol = 0;
1975 s = getaddrinfo(hostname, NULL, &hints, &res);
1977 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1978 domain_name = g_strdup(hostname);
1980 domain_name = g_strdup(res->ai_canonname);
1984 debug_print("domain name = %s\n", domain_name);
1993 off_t get_file_size(const gchar *file)
1998 GError *error = NULL;
2001 f = g_file_new_for_path(file);
2002 fi = g_file_query_info(f, "standard::size",
2003 G_FILE_QUERY_INFO_NONE, NULL, &error);
2004 if (error != NULL) {
2005 debug_print("get_file_size error: %s\n", error->message);
2006 g_error_free(error);
2010 size = g_file_info_get_size(fi);
2018 if (g_stat(file, &s) < 0) {
2019 FILE_OP_ERROR(file, "stat");
2027 time_t get_file_mtime(const gchar *file)
2031 if (g_stat(file, &s) < 0) {
2032 FILE_OP_ERROR(file, "stat");
2039 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2046 if (g_stat(file, &s) < 0) {
2047 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2051 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2058 /* Test on whether FILE is a relative file name. This is
2059 * straightforward for Unix but more complex for Windows. */
2060 gboolean is_relative_filename(const gchar *file)
2065 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2066 return FALSE; /* Prefixed with a hostname - this can't
2067 * be a relative name. */
2069 if ( ((*file >= 'a' && *file <= 'z')
2070 || (*file >= 'A' && *file <= 'Z'))
2072 file += 2; /* Skip drive letter. */
2074 return !(*file == '\\' || *file == '/');
2076 return !(*file == G_DIR_SEPARATOR);
2081 gboolean is_dir_exist(const gchar *dir)
2086 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2089 gboolean is_file_entry_exist(const gchar *file)
2094 return g_file_test(file, G_FILE_TEST_EXISTS);
2097 gboolean dirent_is_regular_file(struct dirent *d)
2099 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2100 if (d->d_type == DT_REG)
2102 else if (d->d_type != DT_UNKNOWN)
2106 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2109 gint change_dir(const gchar *dir)
2111 gchar *prevdir = NULL;
2114 prevdir = g_get_current_dir();
2116 if (g_chdir(dir) < 0) {
2117 FILE_OP_ERROR(dir, "chdir");
2118 if (debug_mode) g_free(prevdir);
2120 } else if (debug_mode) {
2123 cwd = g_get_current_dir();
2124 if (strcmp(prevdir, cwd) != 0)
2125 g_print("current dir: %s\n", cwd);
2133 gint make_dir(const gchar *dir)
2135 if (g_mkdir(dir, S_IRWXU) < 0) {
2136 FILE_OP_ERROR(dir, "mkdir");
2139 if (g_chmod(dir, S_IRWXU) < 0)
2140 FILE_OP_ERROR(dir, "chmod");
2145 gint make_dir_hier(const gchar *dir)
2150 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2151 parent_dir = g_strndup(dir, p - dir);
2152 if (*parent_dir != '\0') {
2153 if (!is_dir_exist(parent_dir)) {
2154 if (make_dir(parent_dir) < 0) {
2163 if (!is_dir_exist(dir)) {
2164 if (make_dir(dir) < 0)
2171 gint remove_all_files(const gchar *dir)
2174 const gchar *file_name;
2177 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2178 g_warning("failed to open directory: %s", dir);
2182 while ((file_name = g_dir_read_name(dp)) != NULL) {
2183 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2184 if (claws_unlink(tmp) < 0)
2185 FILE_OP_ERROR(tmp, "unlink");
2194 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2197 const gchar *dir_name;
2201 if (first == last) {
2202 /* Skip all the dir reading part. */
2203 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2204 if (is_dir_exist(filename)) {
2205 /* a numbered directory with this name exists,
2206 * remove the dot-file instead */
2208 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2210 if (claws_unlink(filename) < 0) {
2211 FILE_OP_ERROR(filename, "unlink");
2219 prev_dir = g_get_current_dir();
2221 if (g_chdir(dir) < 0) {
2222 FILE_OP_ERROR(dir, "chdir");
2227 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2228 g_warning("failed to open directory: %s", dir);
2233 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2234 file_no = to_number(dir_name);
2235 if (file_no > 0 && first <= file_no && file_no <= last) {
2236 if (is_dir_exist(dir_name)) {
2237 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2238 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2239 FILE_OP_ERROR(dot_file, "unlink");
2244 if (claws_unlink(dir_name) < 0)
2245 FILE_OP_ERROR(dir_name, "unlink");
2251 if (g_chdir(prev_dir) < 0) {
2252 FILE_OP_ERROR(prev_dir, "chdir");
2262 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2265 const gchar *dir_name;
2268 GHashTable *wanted_files;
2270 GError *error = NULL;
2272 if (numberlist == NULL)
2275 prev_dir = g_get_current_dir();
2277 if (g_chdir(dir) < 0) {
2278 FILE_OP_ERROR(dir, "chdir");
2283 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2284 g_message("Couldn't open current directory: %s (%d).\n",
2285 error->message, error->code);
2286 g_error_free(error);
2291 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2292 for (cur = numberlist; cur != NULL; cur = cur->next) {
2293 /* numberlist->data is expected to be GINT_TO_POINTER */
2294 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2297 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2298 file_no = to_number(dir_name);
2299 if (is_dir_exist(dir_name))
2301 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2302 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2303 if (is_dir_exist(dir_name)) {
2304 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2305 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2306 FILE_OP_ERROR(dot_file, "unlink");
2311 if (claws_unlink(dir_name) < 0)
2312 FILE_OP_ERROR(dir_name, "unlink");
2317 g_hash_table_destroy(wanted_files);
2319 if (g_chdir(prev_dir) < 0) {
2320 FILE_OP_ERROR(prev_dir, "chdir");
2330 gint remove_all_numbered_files(const gchar *dir)
2332 return remove_numbered_files(dir, 0, UINT_MAX);
2335 gint remove_dir_recursive(const gchar *dir)
2339 const gchar *dir_name;
2342 if (g_stat(dir, &s) < 0) {
2343 FILE_OP_ERROR(dir, "stat");
2344 if (ENOENT == errno) return 0;
2348 if (!S_ISDIR(s.st_mode)) {
2349 if (claws_unlink(dir) < 0) {
2350 FILE_OP_ERROR(dir, "unlink");
2357 prev_dir = g_get_current_dir();
2358 /* g_print("prev_dir = %s\n", prev_dir); */
2360 if (!path_cmp(prev_dir, dir)) {
2362 if (g_chdir("..") < 0) {
2363 FILE_OP_ERROR(dir, "chdir");
2366 prev_dir = g_get_current_dir();
2369 if (g_chdir(dir) < 0) {
2370 FILE_OP_ERROR(dir, "chdir");
2375 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2376 g_warning("failed to open directory: %s", dir);
2382 /* remove all files in the directory */
2383 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2384 /* g_print("removing %s\n", dir_name); */
2386 if (is_dir_exist(dir_name)) {
2389 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2390 g_warning("can't remove directory: %s", dir_name);
2394 if (claws_unlink(dir_name) < 0)
2395 FILE_OP_ERROR(dir_name, "unlink");
2401 if (g_chdir(prev_dir) < 0) {
2402 FILE_OP_ERROR(prev_dir, "chdir");
2409 if (g_rmdir(dir) < 0) {
2410 FILE_OP_ERROR(dir, "rmdir");
2417 gint rename_force(const gchar *oldpath, const gchar *newpath)
2420 if (!is_file_entry_exist(oldpath)) {
2424 if (is_file_exist(newpath)) {
2425 if (claws_unlink(newpath) < 0)
2426 FILE_OP_ERROR(newpath, "unlink");
2429 return g_rename(oldpath, newpath);
2433 * Append src file body to the tail of dest file.
2434 * Now keep_backup has no effects.
2436 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2438 FILE *src_fp, *dest_fp;
2442 gboolean err = FALSE;
2444 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2445 FILE_OP_ERROR(src, "g_fopen");
2449 if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2450 FILE_OP_ERROR(dest, "g_fopen");
2455 if (change_file_mode_rw(dest_fp, dest) < 0) {
2456 FILE_OP_ERROR(dest, "chmod");
2457 g_warning("can't change file mode: %s", dest);
2460 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2461 if (n_read < sizeof(buf) && ferror(src_fp))
2463 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2464 g_warning("writing to %s failed.", dest);
2472 if (ferror(src_fp)) {
2473 FILE_OP_ERROR(src, "fread");
2477 if (fclose(dest_fp) == EOF) {
2478 FILE_OP_ERROR(dest, "fclose");
2490 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2492 FILE *src_fp, *dest_fp;
2495 gchar *dest_bak = NULL;
2496 gboolean err = FALSE;
2498 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2499 FILE_OP_ERROR(src, "g_fopen");
2502 if (is_file_exist(dest)) {
2503 dest_bak = g_strconcat(dest, ".bak", NULL);
2504 if (rename_force(dest, dest_bak) < 0) {
2505 FILE_OP_ERROR(dest, "rename");
2512 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2513 FILE_OP_ERROR(dest, "g_fopen");
2516 if (rename_force(dest_bak, dest) < 0)
2517 FILE_OP_ERROR(dest_bak, "rename");
2523 if (change_file_mode_rw(dest_fp, dest) < 0) {
2524 FILE_OP_ERROR(dest, "chmod");
2525 g_warning("can't change file mode: %s", dest);
2528 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2529 if (n_read < sizeof(buf) && ferror(src_fp))
2531 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2532 g_warning("writing to %s failed.", dest);
2537 if (rename_force(dest_bak, dest) < 0)
2538 FILE_OP_ERROR(dest_bak, "rename");
2545 if (ferror(src_fp)) {
2546 FILE_OP_ERROR(src, "fread");
2550 if (fclose(dest_fp) == EOF) {
2551 FILE_OP_ERROR(dest, "fclose");
2558 if (rename_force(dest_bak, dest) < 0)
2559 FILE_OP_ERROR(dest_bak, "rename");
2565 if (keep_backup == FALSE && dest_bak)
2566 claws_unlink(dest_bak);
2573 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2575 if (overwrite == FALSE && is_file_exist(dest)) {
2576 g_warning("move_file(): file %s already exists.", dest);
2580 if (rename_force(src, dest) == 0) return 0;
2582 if (EXDEV != errno) {
2583 FILE_OP_ERROR(src, "rename");
2587 if (copy_file(src, dest, FALSE) < 0) return -1;
2594 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2597 gint bytes_left, to_read;
2600 if (fseek(fp, offset, SEEK_SET) < 0) {
2605 bytes_left = length;
2606 to_read = MIN(bytes_left, sizeof(buf));
2608 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2609 if (n_read < to_read && ferror(fp))
2611 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2614 bytes_left -= n_read;
2615 if (bytes_left == 0)
2617 to_read = MIN(bytes_left, sizeof(buf));
2628 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2631 gboolean err = FALSE;
2633 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2634 FILE_OP_ERROR(dest, "g_fopen");
2638 if (change_file_mode_rw(dest_fp, dest) < 0) {
2639 FILE_OP_ERROR(dest, "chmod");
2640 g_warning("can't change file mode: %s", dest);
2643 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2646 if (!err && fclose(dest_fp) == EOF) {
2647 FILE_OP_ERROR(dest, "fclose");
2652 g_warning("writing to %s failed.", dest);
2660 /* convert line endings into CRLF. If the last line doesn't end with
2661 * linebreak, add it.
2663 gchar *canonicalize_str(const gchar *str)
2669 for (p = str; *p != '\0'; ++p) {
2676 if (p == str || *(p - 1) != '\n')
2679 out = outp = g_malloc(new_len + 1);
2680 for (p = str; *p != '\0'; ++p) {
2687 if (p == str || *(p - 1) != '\n') {
2696 gint canonicalize_file(const gchar *src, const gchar *dest)
2698 FILE *src_fp, *dest_fp;
2699 gchar buf[BUFFSIZE];
2701 gboolean err = FALSE;
2702 gboolean last_linebreak = FALSE;
2704 if (src == NULL || dest == NULL)
2707 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2708 FILE_OP_ERROR(src, "g_fopen");
2712 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2713 FILE_OP_ERROR(dest, "g_fopen");
2718 if (change_file_mode_rw(dest_fp, dest) < 0) {
2719 FILE_OP_ERROR(dest, "chmod");
2720 g_warning("can't change file mode: %s", dest);
2723 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2727 if (len == 0) break;
2728 last_linebreak = FALSE;
2730 if (buf[len - 1] != '\n') {
2731 last_linebreak = TRUE;
2732 r = fputs(buf, dest_fp);
2733 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2734 r = fputs(buf, dest_fp);
2737 r = fwrite(buf, 1, len - 1, dest_fp);
2742 r = fputs("\r\n", dest_fp);
2746 g_warning("writing to %s failed.", dest);
2754 if (last_linebreak == TRUE) {
2755 if (fputs("\r\n", dest_fp) == EOF)
2759 if (ferror(src_fp)) {
2760 FILE_OP_ERROR(src, "fgets");
2764 if (fclose(dest_fp) == EOF) {
2765 FILE_OP_ERROR(dest, "fclose");
2777 gint canonicalize_file_replace(const gchar *file)
2781 tmp_file = get_tmp_file();
2783 if (canonicalize_file(file, tmp_file) < 0) {
2788 if (move_file(tmp_file, file, TRUE) < 0) {
2789 g_warning("can't replace file: %s", file);
2790 claws_unlink(tmp_file);
2799 gchar *normalize_newlines(const gchar *str)
2804 out = outp = g_malloc(strlen(str) + 1);
2805 for (p = str; *p != '\0'; ++p) {
2807 if (*(p + 1) != '\n')
2818 gchar *get_outgoing_rfc2822_str(FILE *fp)
2820 gchar buf[BUFFSIZE];
2824 str = g_string_new(NULL);
2826 /* output header part */
2827 while (fgets(buf, sizeof(buf), fp) != NULL) {
2829 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2836 else if (next != ' ' && next != '\t') {
2840 if (fgets(buf, sizeof(buf), fp) == NULL)
2844 g_string_append(str, buf);
2845 g_string_append(str, "\r\n");
2851 /* output body part */
2852 while (fgets(buf, sizeof(buf), fp) != NULL) {
2855 g_string_append_c(str, '.');
2856 g_string_append(str, buf);
2857 g_string_append(str, "\r\n");
2861 g_string_free(str, FALSE);
2867 * Create a new boundary in a way that it is very unlikely that this
2868 * will occur in the following text. It would be easy to ensure
2869 * uniqueness if everything is either quoted-printable or base64
2870 * encoded (note that conversion is allowed), but because MIME bodies
2871 * may be nested, it may happen that the same boundary has already
2874 * boundary := 0*69<bchars> bcharsnospace
2875 * bchars := bcharsnospace / " "
2876 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2877 * "+" / "_" / "," / "-" / "." /
2878 * "/" / ":" / "=" / "?"
2880 * some special characters removed because of buggy MTAs
2883 gchar *generate_mime_boundary(const gchar *prefix)
2885 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2886 "abcdefghijklmnopqrstuvwxyz"
2891 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2892 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2895 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2899 gint change_file_mode_rw(FILE *fp, const gchar *file)
2902 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2904 return g_chmod(file, S_IRUSR|S_IWUSR);
2908 FILE *my_tmpfile(void)
2910 const gchar suffix[] = ".XXXXXX";
2911 const gchar *tmpdir;
2913 const gchar *progname;
2922 tmpdir = get_tmp_dir();
2923 tmplen = strlen(tmpdir);
2924 progname = g_get_prgname();
2925 if (progname == NULL)
2926 progname = "claws-mail";
2927 proglen = strlen(progname);
2928 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2931 memcpy(fname, tmpdir, tmplen);
2932 fname[tmplen] = G_DIR_SEPARATOR;
2933 memcpy(fname + tmplen + 1, progname, proglen);
2934 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2936 fd = g_mkstemp(fname);
2941 claws_unlink(fname);
2943 /* verify that we can write in the file after unlinking */
2944 if (write(fd, buf, 1) < 0) {
2951 fp = fdopen(fd, "w+b");
2962 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2965 *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
2966 fd = g_mkstemp(*filename);
2969 return fdopen(fd, "w+");
2972 FILE *str_open_as_stream(const gchar *str)
2977 cm_return_val_if_fail(str != NULL, NULL);
2981 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2986 if (len == 0) return fp;
2988 if (fwrite(str, 1, len, fp) != len) {
2989 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2998 gint str_write_to_file(const gchar *str, const gchar *file)
3003 cm_return_val_if_fail(str != NULL, -1);
3004 cm_return_val_if_fail(file != NULL, -1);
3006 if ((fp = g_fopen(file, "wb")) == NULL) {
3007 FILE_OP_ERROR(file, "g_fopen");
3017 if (fwrite(str, 1, len, fp) != len) {
3018 FILE_OP_ERROR(file, "fwrite");
3024 if (fclose(fp) == EOF) {
3025 FILE_OP_ERROR(file, "fclose");
3033 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3040 cm_return_val_if_fail(fp != NULL, NULL);
3042 array = g_byte_array_new();
3044 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3045 if (n_read < sizeof(buf) && ferror(fp))
3047 g_byte_array_append(array, buf, n_read);
3051 FILE_OP_ERROR("file stream", "fread");
3052 g_byte_array_free(array, TRUE);
3057 g_byte_array_append(array, buf, 1);
3058 str = (gchar *)array->data;
3059 g_byte_array_free(array, FALSE);
3061 if (recode && !g_utf8_validate(str, -1, NULL)) {
3062 const gchar *src_codeset, *dest_codeset;
3064 src_codeset = conv_get_locale_charset_str();
3065 dest_codeset = CS_UTF_8;
3066 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3074 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3081 struct timeval timeout = {1, 0};
3086 cm_return_val_if_fail(file != NULL, NULL);
3088 if (g_stat(file, &s) != 0) {
3089 FILE_OP_ERROR(file, "stat");
3092 if (S_ISDIR(s.st_mode)) {
3093 g_warning("%s: is a directory", file);
3098 fp = g_fopen (file, "rb");
3100 FILE_OP_ERROR(file, "open");
3104 /* test whether the file is readable without blocking */
3105 fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3107 FILE_OP_ERROR(file, "open");
3114 /* allow for one second */
3115 err = select(fd+1, &fds, NULL, NULL, &timeout);
3116 if (err <= 0 || !FD_ISSET(fd, &fds)) {
3118 FILE_OP_ERROR(file, "select");
3120 g_warning("%s: doesn't seem readable", file);
3126 /* Now clear O_NONBLOCK */
3127 if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3128 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3132 if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3133 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3138 /* get the FILE pointer */
3139 fp = fdopen(fd, "rb");
3142 FILE_OP_ERROR(file, "fdopen");
3143 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3148 str = file_read_stream_to_str_full(fp, recode);
3155 gchar *file_read_to_str(const gchar *file)
3157 return file_read_to_str_full(file, TRUE);
3159 gchar *file_read_stream_to_str(FILE *fp)
3161 return file_read_stream_to_str_full(fp, TRUE);
3164 gchar *file_read_to_str_no_recode(const gchar *file)
3166 return file_read_to_str_full(file, FALSE);
3168 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3170 return file_read_stream_to_str_full(fp, FALSE);
3173 char *fgets_crlf(char *buf, int size, FILE *stream)
3175 gboolean is_cr = FALSE;
3176 gboolean last_was_cr = FALSE;
3181 while (--size > 0 && (c = getc(stream)) != EOF)
3184 is_cr = (c == '\r');
3194 last_was_cr = is_cr;
3196 if (c == EOF && cs == buf)
3204 static gint execute_async(gchar *const argv[], const gchar *working_directory)
3206 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3208 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3209 NULL, NULL, NULL, FALSE) == FALSE) {
3210 g_warning("couldn't execute command: %s", argv[0]);
3217 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
3221 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3224 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3225 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3226 g_warning("couldn't execute command: %s", argv[0]);
3230 if (WIFEXITED(status))
3231 return WEXITSTATUS(status);
3235 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
3236 G_SPAWN_SEARCH_PATH|
3237 G_SPAWN_CHILD_INHERITS_STDIN|
3238 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3239 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3240 g_warning("couldn't execute command: %s", argv[0]);
3248 gint execute_command_line(const gchar *cmdline, gboolean async,
3249 const gchar *working_directory)
3254 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3256 argv = strsplit_with_quote(cmdline, " ", 0);
3259 ret = execute_async(argv, working_directory);
3261 ret = execute_sync(argv, working_directory);
3268 gchar *get_command_output(const gchar *cmdline)
3270 gchar *child_stdout;
3273 cm_return_val_if_fail(cmdline != NULL, NULL);
3275 debug_print("get_command_output(): executing: %s\n", cmdline);
3277 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3279 g_warning("couldn't execute command: %s", cmdline);
3283 return child_stdout;
3286 static gint is_unchanged_uri_char(char c)
3297 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3303 for(i = 0; i < strlen(uri) ; i++) {
3304 if (is_unchanged_uri_char(uri[i])) {
3305 if (k + 2 >= bufsize)
3307 encoded_uri[k++] = uri[i];
3310 char * hexa = "0123456789ABCDEF";
3312 if (k + 4 >= bufsize)
3314 encoded_uri[k++] = '%';
3315 encoded_uri[k++] = hexa[uri[i] / 16];
3316 encoded_uri[k++] = hexa[uri[i] % 16];
3322 gint open_uri(const gchar *uri, const gchar *cmdline)
3326 gchar buf[BUFFSIZE];
3328 gchar encoded_uri[BUFFSIZE];
3329 cm_return_val_if_fail(uri != NULL, -1);
3331 /* an option to choose whether to use encode_uri or not ? */
3332 encode_uri(encoded_uri, BUFFSIZE, uri);
3335 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3336 !strchr(p + 2, '%'))
3337 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3340 g_warning("Open URI command-line is invalid "
3341 "(there must be only one '%%s'): %s",
3343 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3346 execute_command_line(buf, TRUE, NULL);
3348 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3353 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3355 gchar buf[BUFFSIZE];
3358 cm_return_val_if_fail(filepath != NULL, -1);
3361 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3362 !strchr(p + 2, '%'))
3363 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3366 g_warning("Open Text Editor command-line is invalid "
3367 "(there must be only one '%%s'): %s",
3369 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3372 execute_command_line(buf, TRUE, NULL);
3377 time_t remote_tzoffset_sec(const gchar *zone)
3379 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3385 time_t remoteoffset;
3387 strncpy(zone3, zone, 3);
3391 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3392 (c == '+' || c == '-')) {
3393 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3395 remoteoffset = -remoteoffset;
3396 } else if (!strncmp(zone, "UT" , 2) ||
3397 !strncmp(zone, "GMT", 3)) {
3399 } else if (strlen(zone3) == 3) {
3400 for (p = ustzstr; *p != '\0'; p += 3) {
3401 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3402 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3403 remoteoffset = iustz * 3600;
3409 } else if (strlen(zone3) == 1) {
3411 case 'Z': remoteoffset = 0; break;
3412 case 'A': remoteoffset = -1; break;
3413 case 'B': remoteoffset = -2; break;
3414 case 'C': remoteoffset = -3; break;
3415 case 'D': remoteoffset = -4; break;
3416 case 'E': remoteoffset = -5; break;
3417 case 'F': remoteoffset = -6; break;
3418 case 'G': remoteoffset = -7; break;
3419 case 'H': remoteoffset = -8; break;
3420 case 'I': remoteoffset = -9; break;
3421 case 'K': remoteoffset = -10; break; /* J is not used */
3422 case 'L': remoteoffset = -11; break;
3423 case 'M': remoteoffset = -12; break;
3424 case 'N': remoteoffset = 1; break;
3425 case 'O': remoteoffset = 2; break;
3426 case 'P': remoteoffset = 3; break;
3427 case 'Q': remoteoffset = 4; break;
3428 case 'R': remoteoffset = 5; break;
3429 case 'S': remoteoffset = 6; break;
3430 case 'T': remoteoffset = 7; break;
3431 case 'U': remoteoffset = 8; break;
3432 case 'V': remoteoffset = 9; break;
3433 case 'W': remoteoffset = 10; break;
3434 case 'X': remoteoffset = 11; break;
3435 case 'Y': remoteoffset = 12; break;
3436 default: remoteoffset = 0; break;
3438 remoteoffset = remoteoffset * 3600;
3442 return remoteoffset;
3445 time_t tzoffset_sec(time_t *now)
3449 struct tm buf1, buf2;
3451 if (now && *now < 0)
3454 gmt = *gmtime_r(now, &buf1);
3455 lt = localtime_r(now, &buf2);
3457 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3459 if (lt->tm_year < gmt.tm_year)
3461 else if (lt->tm_year > gmt.tm_year)
3463 else if (lt->tm_yday < gmt.tm_yday)
3465 else if (lt->tm_yday > gmt.tm_yday)
3468 if (off >= 24 * 60) /* should be impossible */
3469 off = 23 * 60 + 59; /* if not, insert silly value */
3470 if (off <= -24 * 60)
3471 off = -(23 * 60 + 59);
3476 /* calculate timezone offset */
3477 gchar *tzoffset(time_t *now)
3479 static gchar offset_string[6];
3483 struct tm buf1, buf2;
3485 if (now && *now < 0)
3488 gmt = *gmtime_r(now, &buf1);
3489 lt = localtime_r(now, &buf2);
3491 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3493 if (lt->tm_year < gmt.tm_year)
3495 else if (lt->tm_year > gmt.tm_year)
3497 else if (lt->tm_yday < gmt.tm_yday)
3499 else if (lt->tm_yday > gmt.tm_yday)
3507 if (off >= 24 * 60) /* should be impossible */
3508 off = 23 * 60 + 59; /* if not, insert silly value */
3510 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3512 return offset_string;
3515 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
3519 gchar day[4], mon[4];
3520 gint dd, hh, mm, ss, yyyy;
3522 gchar buf2[RFC822_DATE_BUFFSIZE];
3526 lt = gmtime_r(&t, &buf1);
3528 lt = localtime_r(&t, &buf1);
3530 if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
3531 day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
3532 g_warning("failed reading date/time");
3534 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3535 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
3538 void get_rfc822_date(gchar *buf, gint len)
3540 _get_rfc822_date(buf, len, FALSE);
3543 void get_rfc822_date_hide_tz(gchar *buf, gint len)
3545 _get_rfc822_date(buf, len, TRUE);
3548 void debug_set_mode(gboolean mode)
3553 gboolean debug_get_mode(void)
3558 void debug_print_real(const gchar *format, ...)
3561 gchar buf[BUFFSIZE];
3563 if (!debug_mode) return;
3565 va_start(args, format);
3566 g_vsnprintf(buf, sizeof(buf), format, args);
3573 const char * debug_srcname(const char *file)
3575 const char *s = strrchr (file, '/');
3580 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3582 if (subject == NULL)
3585 subject += subject_get_prefix_length(subject);
3587 return g_hash_table_lookup(subject_table, subject);
3590 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3593 if (subject == NULL || *subject == 0)
3595 subject += subject_get_prefix_length(subject);
3596 g_hash_table_insert(subject_table, subject, data);
3599 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3601 if (subject == NULL)
3604 subject += subject_get_prefix_length(subject);
3605 g_hash_table_remove(subject_table, subject);
3608 static regex_t u_regex;
3609 static gboolean u_init_;
3611 void utils_free_regex(void)
3620 *\brief Check if a string is prefixed with known (combinations)
3621 * of prefixes. The function assumes that each prefix
3622 * is terminated by zero or exactly _one_ space.
3624 *\param str String to check for a prefixes
3626 *\return int Number of chars in the prefix that should be skipped
3627 * for a "clean" subject line. If no prefix was found, 0
3630 int subject_get_prefix_length(const gchar *subject)
3632 /*!< Array with allowable reply prefixes regexps. */
3633 static const gchar * const prefixes[] = {
3634 "Re\\:", /* "Re:" */
3635 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3636 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3637 "Aw\\:", /* "Aw:" (German) */
3638 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3639 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3640 "Fw\\:", /* "Fw:" Forward */
3641 "Fwd\\:", /* "Fwd:" Forward */
3642 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3643 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3644 "Rif\\:", /* "Rif:" (Italian Outlook) */
3645 "Sv\\:", /* "Sv" (Norwegian) */
3646 "Vs\\:", /* "Vs" (Norwegian) */
3647 "Ad\\:", /* "Ad" (Norwegian) */
3648 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3649 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3650 "Re \\:", /* "Re :" (French Yahoo Mail) */
3653 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3657 if (!subject) return 0;
3658 if (!*subject) return 0;
3661 GString *s = g_string_new("");
3663 for (n = 0; n < PREFIXES; n++)
3664 /* Terminate each prefix regexpression by a
3665 * "\ ?" (zero or ONE space), and OR them */
3666 g_string_append_printf(s, "(%s\\ ?)%s",
3671 g_string_prepend(s, "(");
3672 g_string_append(s, ")+"); /* match at least once */
3673 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3676 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3677 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3678 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3679 debug_print("Error compiling regexp %s\n", s->str);
3680 g_string_free(s, TRUE);
3684 g_string_free(s, TRUE);
3688 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3694 static guint g_stricase_hash(gconstpointer gptr)
3696 guint hash_result = 0;
3699 for (str = gptr; str && *str; str++) {
3700 hash_result += toupper(*str);
3706 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3708 const char *str1 = gptr1;
3709 const char *str2 = gptr2;
3711 return !strcasecmp(str1, str2);
3714 gint g_int_compare(gconstpointer a, gconstpointer b)
3716 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3720 quote_cmd_argument()
3722 return a quoted string safely usable in argument of a command.
3724 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3727 gint quote_cmd_argument(gchar * result, guint size,
3737 for(p = path ; * p != '\0' ; p ++) {
3739 if (isalnum((guchar)*p) || (* p == '/')) {
3740 if (remaining > 0) {
3746 result[size - 1] = '\0';
3751 if (remaining >= 2) {
3759 result[size - 1] = '\0';
3764 if (remaining > 0) {
3768 result[size - 1] = '\0';
3782 static void g_node_map_recursive(GNode *node, gpointer data)
3784 GNodeMapData *mapdata = (GNodeMapData *) data;
3786 GNodeMapData newmapdata;
3789 newdata = mapdata->func(node->data, mapdata->data);
3790 if (newdata != NULL) {
3791 newnode = g_node_new(newdata);
3792 g_node_append(mapdata->parent, newnode);
3794 newmapdata.parent = newnode;
3795 newmapdata.func = mapdata->func;
3796 newmapdata.data = mapdata->data;
3798 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3802 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3805 GNodeMapData mapdata;
3807 cm_return_val_if_fail(node != NULL, NULL);
3808 cm_return_val_if_fail(func != NULL, NULL);
3810 root = g_node_new(func(node->data, data));
3812 mapdata.parent = root;
3813 mapdata.func = func;
3814 mapdata.data = data;
3816 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3821 #define HEX_TO_INT(val, hex) \
3825 if ('0' <= c && c <= '9') { \
3827 } else if ('a' <= c && c <= 'f') { \
3828 val = c - 'a' + 10; \
3829 } else if ('A' <= c && c <= 'F') { \
3830 val = c - 'A' + 10; \
3836 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3843 if (hi == -1 || lo == -1)
3846 *out = (hi << 4) + lo;
3850 #define INT_TO_HEX(hex, val) \
3853 hex = '0' + (val); \
3855 hex = 'A' + (val) - 10; \
3858 void get_hex_str(gchar *out, guchar ch)
3862 INT_TO_HEX(hex, ch >> 4);
3864 INT_TO_HEX(hex, ch & 0x0f);
3870 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3872 #define G_PRINT_REF g_print
3876 *\brief Register ref counted pointer. It is based on GBoxed, so should
3877 * work with anything that uses the GType system. The semantics
3878 * are similar to a C++ auto pointer, with the exception that
3879 * C doesn't have automatic closure (calling destructors) when
3880 * exiting a block scope.
3881 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3882 * function directly.
3884 *\return GType A GType type.
3886 GType g_auto_pointer_register(void)
3888 static GType auto_pointer_type;
3889 if (!auto_pointer_type)
3891 g_boxed_type_register_static
3892 ("G_TYPE_AUTO_POINTER",
3893 (GBoxedCopyFunc) g_auto_pointer_copy,
3894 (GBoxedFreeFunc) g_auto_pointer_free);
3895 return auto_pointer_type;
3899 *\brief Structure with g_new() allocated pointer guarded by the
3902 typedef struct AutoPointerRef {
3903 void (*free) (gpointer);
3909 *\brief The auto pointer opaque structure that references the
3910 * pointer guard block.
3912 typedef struct AutoPointer {
3913 AutoPointerRef *ref;
3914 gpointer ptr; /*!< access to protected pointer */
3918 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3922 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3923 * ... when assigning, copying and freeing storage elements
3925 * gtk_list_store_new(N_S_COLUMNS,
3926 * G_TYPE_AUTO_POINTER,
3930 * Template *precious_data = g_new0(Template, 1);
3931 * g_pointer protect = g_auto_pointer_new(precious_data);
3933 * gtk_list_store_set(container, &iter,
3937 * ... the gtk_list_store has copied the pointer and
3938 * ... incremented its reference count, we should free
3939 * ... the auto pointer (in C++ a destructor would do
3940 * ... this for us when leaving block scope)
3942 * g_auto_pointer_free(protect);
3944 * ... gtk_list_store_set() now manages the data. When
3945 * ... *explicitly* requesting a pointer from the list
3946 * ... store, don't forget you get a copy that should be
3947 * ... freed with g_auto_pointer_free() eventually.
3951 *\param pointer Pointer to be guarded.
3953 *\return GAuto * Pointer that should be used in containers with
3956 GAuto *g_auto_pointer_new(gpointer p)
3958 AutoPointerRef *ref;
3964 ref = g_new0(AutoPointerRef, 1);
3965 ptr = g_new0(AutoPointer, 1);
3975 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3981 *\brief Allocate an autopointer using the passed \a free function to
3982 * free the guarded pointer
3984 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3991 aptr = g_auto_pointer_new(p);
3992 aptr->ref->free = free_;
3996 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3998 if (auto_ptr == NULL)
4000 return ((AutoPointer *) auto_ptr)->ptr;
4004 *\brief Copies an auto pointer by. It's mostly not necessary
4005 * to call this function directly, unless you copy/assign
4006 * the guarded pointer.
4008 *\param auto_ptr Auto pointer returned by previous call to
4009 * g_auto_pointer_new_XXX()
4011 *\return gpointer An auto pointer
4013 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
4016 AutoPointerRef *ref;
4019 if (auto_ptr == NULL)
4024 newp = g_new0(AutoPointer, 1);
4027 newp->ptr = ref->pointer;
4031 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4037 *\brief Free an auto pointer
4039 void g_auto_pointer_free(GAuto *auto_ptr)
4042 AutoPointerRef *ref;
4044 if (auto_ptr == NULL)
4050 if (--(ref->cnt) == 0) {
4052 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4054 ref->free(ref->pointer);
4059 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4064 void replace_returns(gchar *str)
4069 while (strstr(str, "\n")) {
4070 *strstr(str, "\n") = ' ';
4072 while (strstr(str, "\r")) {
4073 *strstr(str, "\r") = ' ';
4077 /* get_uri_part() - retrieves a URI starting from scanpos.
4078 Returns TRUE if successful */
4079 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
4080 const gchar **bp, const gchar **ep, gboolean hdr)
4083 gint parenthese_cnt = 0;
4085 cm_return_val_if_fail(start != NULL, FALSE);
4086 cm_return_val_if_fail(scanpos != NULL, FALSE);
4087 cm_return_val_if_fail(bp != NULL, FALSE);
4088 cm_return_val_if_fail(ep != NULL, FALSE);
4092 /* find end point of URI */
4093 for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
4094 if (!g_ascii_isgraph(*(const guchar *)ep_) ||
4095 !IS_ASCII(*(const guchar *)ep_) ||
4096 strchr("[]{}<>\"", *ep_)) {
4098 } else if (strchr("(", *ep_)) {
4100 } else if (strchr(")", *ep_)) {
4101 if (parenthese_cnt > 0)
4108 /* no punctuation at end of string */
4110 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
4111 * should pass some URI type to this function and decide on that whether
4112 * to perform punctuation stripping */
4114 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
4116 for (; ep_ - 1 > scanpos + 1 &&
4117 IS_REAL_PUNCT(*(ep_ - 1));
4121 #undef IS_REAL_PUNCT
4128 gchar *make_uri_string(const gchar *bp, const gchar *ep)
4130 while (bp && *bp && g_ascii_isspace(*bp))
4132 return g_strndup(bp, ep - bp);
4135 /* valid mail address characters */
4136 #define IS_RFC822_CHAR(ch) \
4140 !g_ascii_isspace(ch) && \
4141 !strchr("(),;<>\"", (ch)))
4143 /* alphabet and number within 7bit ASCII */
4144 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
4145 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
4147 static GHashTable *create_domain_tab(void)
4150 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
4152 cm_return_val_if_fail(htab, NULL);
4153 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
4154 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
4158 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
4160 const gint MAX_LVL_DOM_NAME_LEN = 6;
4161 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
4162 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
4165 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
4168 for (p = buf; p < m && first < last; *p++ = *first++)
4172 return g_hash_table_lookup(tab, buf) != NULL;
4175 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
4176 gboolean get_email_part(const gchar *start, const gchar *scanpos,
4177 const gchar **bp, const gchar **ep, gboolean hdr)
4179 /* more complex than the uri part because we need to scan back and forward starting from
4180 * the scan position. */
4181 gboolean result = FALSE;
4182 const gchar *bp_ = NULL;
4183 const gchar *ep_ = NULL;
4184 static GHashTable *dom_tab;
4185 const gchar *last_dot = NULL;
4186 const gchar *prelast_dot = NULL;
4187 const gchar *last_tld_char = NULL;
4189 /* the informative part of the email address (describing the name
4190 * of the email address owner) may contain quoted parts. the
4191 * closure stack stores the last encountered quotes. */
4192 gchar closure_stack[128];
4193 gchar *ptr = closure_stack;
4195 cm_return_val_if_fail(start != NULL, FALSE);
4196 cm_return_val_if_fail(scanpos != NULL, FALSE);
4197 cm_return_val_if_fail(bp != NULL, FALSE);
4198 cm_return_val_if_fail(ep != NULL, FALSE);
4201 const gchar *start_quote = NULL;
4202 const gchar *end_quote = NULL;
4204 /* go to the real start */
4205 if (start[0] == ',')
4207 if (start[0] == ';')
4209 while (start[0] == '\n' || start[0] == '\r')
4211 while (start[0] == ' ' || start[0] == '\t')
4216 /* check if there are quotes (to skip , in them) */
4217 if (*start == '"') {
4218 start_quote = start;
4220 end_quote = strstr(start, "\"");
4226 /* skip anything between quotes */
4227 if (start_quote && end_quote) {
4232 /* find end (either , or ; or end of line) */
4233 if (strstr(start, ",") && strstr(start, ";"))
4234 *ep = strstr(start,",") < strstr(start, ";")
4235 ? strstr(start, ",") : strstr(start, ";");
4236 else if (strstr(start, ","))
4237 *ep = strstr(start, ",");
4238 else if (strstr(start, ";"))
4239 *ep = strstr(start, ";");
4241 *ep = start+strlen(start);
4243 /* go back to real start */
4244 if (start_quote && end_quote) {
4245 start = start_quote;
4248 /* check there's still an @ in that, or search
4249 * further if possible */
4250 if (strstr(start, "@") && strstr(start, "@") < *ep)
4252 else if (*ep < start+strlen(start)) {
4255 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
4263 dom_tab = create_domain_tab();
4264 cm_return_val_if_fail(dom_tab, FALSE);
4266 /* scan start of address */
4267 for (bp_ = scanpos - 1;
4268 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
4271 /* TODO: should start with an alnum? */
4273 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
4276 if (bp_ != scanpos) {
4277 /* scan end of address */
4278 for (ep_ = scanpos + 1;
4279 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
4281 prelast_dot = last_dot;
4283 if (*(last_dot + 1) == '.') {
4284 if (prelast_dot == NULL)
4286 last_dot = prelast_dot;
4291 /* TODO: really should terminate with an alnum? */
4292 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
4297 if (last_dot == NULL)
4299 if (last_dot >= ep_)
4300 last_dot = prelast_dot;
4301 if (last_dot == NULL || (scanpos + 1 >= last_dot))
4305 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
4306 if (*last_tld_char == '?')
4309 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
4316 if (!result) return FALSE;
4318 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
4319 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
4320 && IS_RFC822_CHAR(*(ep_ + 3))) {
4321 /* this informative part with an @ in it is
4322 * followed by the email address */
4325 /* go to matching '>' (or next non-rfc822 char, like \n) */
4326 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
4329 /* include the bracket */
4330 if (*ep_ == '>') ep_++;
4332 /* include the leading quote */
4340 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
4341 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
4344 /* see if this is <bracketed>; in this case we also scan for the informative part. */
4345 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
4348 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
4349 #define IN_STACK() (ptr > closure_stack)
4350 /* has underrun check */
4351 #define POP_STACK() if(IN_STACK()) --ptr
4352 /* has overrun check */
4353 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
4354 /* has underrun check */
4355 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
4359 /* scan for the informative part. */
4360 for (bp_ -= 2; bp_ >= start; bp_--) {
4361 /* if closure on the stack keep scanning */
4362 if (PEEK_STACK() == *bp_) {
4366 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
4371 /* if nothing in the closure stack, do the special conditions
4372 * the following if..else expression simply checks whether
4373 * a token is acceptable. if not acceptable, the clause
4374 * should terminate the loop with a 'break' */
4375 if (!PEEK_STACK()) {
4377 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
4378 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
4379 /* hyphens are allowed, but only in
4381 } else if (strchr(" \"'", *bp_)) {
4382 /* but anything not being a punctiation
4385 break; /* anything else is rejected */
4392 /* scan forward (should start with an alnum) */
4393 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
4409 #undef IS_ASCII_ALNUM
4410 #undef IS_RFC822_CHAR
4412 gchar *make_email_string(const gchar *bp, const gchar *ep)
4414 /* returns a mailto: URI; mailto: is also used to detect the
4415 * uri type later on in the button_pressed signal handler */
4420 tmp = g_strndup(bp, ep - bp);
4422 /* If there is a colon in the username part of the address,
4423 * we're dealing with an URI for some other protocol - do
4424 * not prefix with mailto: in such case. */
4425 colon = strchr(tmp, ':');
4426 at = strchr(tmp, '@');
4427 if (colon != NULL && at != NULL && colon < at) {
4430 result = g_strconcat("mailto:", tmp, NULL);
4437 gchar *make_http_string(const gchar *bp, const gchar *ep)
4439 /* returns an http: URI; */
4443 while (bp && *bp && g_ascii_isspace(*bp))
4445 tmp = g_strndup(bp, ep - bp);
4446 result = g_strconcat("http://", tmp, NULL);
4452 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
4454 FILE *fp = g_fopen(path, "rb");
4455 gchar buf[BUFFSIZE];
4456 gchar *result = NULL;
4459 while (fgets(buf, sizeof (buf), fp) != NULL) {
4460 gchar **parts = g_strsplit(buf, ";", 3);
4461 gchar *trimmed = parts[0];
4462 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4464 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4465 trimmed[strlen(trimmed)-1] = '\0';
4467 if (!strcmp(trimmed, type)) {
4468 gboolean needsterminal = FALSE;
4469 if (parts[2] && strstr(parts[2], "needsterminal")) {
4470 needsterminal = TRUE;
4472 if (parts[2] && strstr(parts[2], "test=")) {
4473 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
4474 gchar *testcmd = orig_testcmd;
4475 if (strstr(testcmd,";"))
4476 *(strstr(testcmd,";")) = '\0';
4477 while (testcmd[0] == ' ' || testcmd[0] == '\t')
4479 while (testcmd[strlen(testcmd)-1] == '\n')
4480 testcmd[strlen(testcmd)-1] = '\0';
4481 while (testcmd[strlen(testcmd)-1] == '\r')
4482 testcmd[strlen(testcmd)-1] = '\0';
4483 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
4484 testcmd[strlen(testcmd)-1] = '\0';
4486 if (strstr(testcmd, "%s")) {
4487 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
4488 gint res = system(tmp);
4490 g_free(orig_testcmd);
4497 gint res = system(testcmd);
4498 g_free(orig_testcmd);
4508 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4510 while (trimmed[strlen(trimmed)-1] == '\n')
4511 trimmed[strlen(trimmed)-1] = '\0';
4512 while (trimmed[strlen(trimmed)-1] == '\r')
4513 trimmed[strlen(trimmed)-1] = '\0';
4514 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4515 trimmed[strlen(trimmed)-1] = '\0';
4516 result = g_strdup(trimmed);
4519 if (needsterminal) {
4520 gchar *tmp = g_strdup_printf("xterm -e %s", result);
4531 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
4533 gchar *result = NULL;
4537 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4538 result = mailcap_get_command_in_file(path, type, file_to_open);
4542 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
4546 void mailcap_update_default(const gchar *type, const gchar *command)
4548 gchar *path = NULL, *outpath = NULL;
4549 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4550 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
4551 FILE *fp = g_fopen(path, "rb");
4553 gchar buf[BUFFSIZE];
4554 gboolean err = FALSE;
4557 fp = g_fopen(path, "a");
4559 g_warning("failed to create file %s", path);
4564 fp = g_freopen(path, "rb", fp);
4566 g_warning("failed to reopen file %s", path);
4573 outfp = g_fopen(outpath, "wb");
4575 g_warning("failed to create file %s", outpath);
4581 while (fp && fgets(buf, sizeof (buf), fp) != NULL) {
4582 gchar **parts = g_strsplit(buf, ";", 3);
4583 gchar *trimmed = parts[0];
4584 while (trimmed[0] == ' ')
4586 while (trimmed[strlen(trimmed)-1] == ' ')
4587 trimmed[strlen(trimmed)-1] = '\0';
4589 if (!strcmp(trimmed, type)) {
4594 if(fputs(buf, outfp) == EOF) {
4601 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4607 if (fclose(outfp) == EOF)
4611 g_rename(outpath, path);
4617 gint copy_dir(const gchar *src, const gchar *dst)
4622 if ((dir = g_dir_open(src, 0, NULL)) == NULL) {
4623 g_warning("failed to open directory: %s", src);
4627 if (make_dir(dst) < 0)
4630 while ((name = g_dir_read_name(dir)) != NULL) {
4631 gchar *old_file, *new_file;
4632 old_file = g_strconcat(src, G_DIR_SEPARATOR_S, name, NULL);
4633 new_file = g_strconcat(dst, G_DIR_SEPARATOR_S, name, NULL);
4634 debug_print("copying: %s -> %s\n", old_file, new_file);
4635 if (g_file_test(old_file, G_FILE_TEST_IS_REGULAR)) {
4636 gint r = copy_file(old_file, new_file, TRUE);
4643 /* Windows has no symlinks. Or well, Vista seems to
4644 have something like this but the semantics might be
4645 different. Thus we don't use it under Windows. */
4646 else if (g_file_test(old_file, G_FILE_TEST_IS_SYMLINK)) {
4647 GError *error = NULL;
4649 gchar *target = g_file_read_link(old_file, &error);
4651 r = symlink(target, new_file);
4658 #endif /*G_OS_WIN32*/
4659 else if (g_file_test(old_file, G_FILE_TEST_IS_DIR)) {
4660 gint r = copy_dir(old_file, new_file);
4671 /* crude test to see if a file is an email. */
4672 gboolean file_is_email (const gchar *filename)
4678 if (filename == NULL)
4680 if ((fp = g_fopen(filename, "rb")) == NULL)
4682 while (i < 60 && score < 3
4683 && fgets(buffer, sizeof (buffer), fp) != NULL) {
4684 if (!strncmp(buffer, "From:", strlen("From:")))
4686 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4688 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4690 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4695 return (score >= 3);
4698 gboolean sc_g_list_bigger(GList *list, gint max)
4702 while (cur && i <= max+1) {
4709 gboolean sc_g_slist_bigger(GSList *list, gint max)
4713 while (cur && i <= max+1) {
4720 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4721 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4722 NULL, NULL, NULL, NULL, NULL, NULL};
4723 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4724 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4725 NULL, NULL, NULL, NULL, NULL, NULL};
4727 gint daynames_len[] = {0,0,0,0,0,0,0};
4728 gint monthnames_len[] = {0,0,0,0,0,0,
4730 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4731 gint s_monthnames_len[] = {0,0,0,0,0,0,
4733 const gchar *s_am_up = NULL;
4734 const gchar *s_pm_up = NULL;
4735 const gchar *s_am_low = NULL;
4736 const gchar *s_pm_low = NULL;
4738 gint s_am_up_len = 0;
4739 gint s_pm_up_len = 0;
4740 gint s_am_low_len = 0;
4741 gint s_pm_low_len = 0;
4743 static gboolean time_names_init_done = FALSE;
4745 static void init_time_names(void)
4749 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4750 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4751 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4752 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4753 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4754 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4755 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4757 monthnames[0] = C_("Complete month name for use by strftime", "January");
4758 monthnames[1] = C_("Complete month name for use by strftime", "February");
4759 monthnames[2] = C_("Complete month name for use by strftime", "March");
4760 monthnames[3] = C_("Complete month name for use by strftime", "April");
4761 monthnames[4] = C_("Complete month name for use by strftime", "May");
4762 monthnames[5] = C_("Complete month name for use by strftime", "June");
4763 monthnames[6] = C_("Complete month name for use by strftime", "July");
4764 monthnames[7] = C_("Complete month name for use by strftime", "August");
4765 monthnames[8] = C_("Complete month name for use by strftime", "September");
4766 monthnames[9] = C_("Complete month name for use by strftime", "October");
4767 monthnames[10] = C_("Complete month name for use by strftime", "November");
4768 monthnames[11] = C_("Complete month name for use by strftime", "December");
4770 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4771 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4772 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4773 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4774 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4775 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4776 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4778 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4779 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4780 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4781 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4782 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4783 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4784 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4785 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4786 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4787 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4788 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4789 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4791 for (i = 0; i < 7; i++) {
4792 daynames_len[i] = strlen(daynames[i]);
4793 s_daynames_len[i] = strlen(s_daynames[i]);
4795 for (i = 0; i < 12; i++) {
4796 monthnames_len[i] = strlen(monthnames[i]);
4797 s_monthnames_len[i] = strlen(s_monthnames[i]);
4800 s_am_up = C_("For use by strftime (morning)", "AM");
4801 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4802 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4803 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4805 s_am_up_len = strlen(s_am_up);
4806 s_pm_up_len = strlen(s_pm_up);
4807 s_am_low_len = strlen(s_am_low);
4808 s_pm_low_len = strlen(s_pm_low);
4810 time_names_init_done = TRUE;
4813 #define CHECK_SIZE() { \
4814 total_done += len; \
4815 if (total_done >= buflen) { \
4816 buf[buflen-1] = '\0'; \
4821 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4823 gchar *curpos = buf;
4824 gint total_done = 0;
4825 gchar subbuf[64], subfmt[64];
4826 static time_t last_tzset = (time_t)0;
4828 if (!time_names_init_done)
4831 if (format == NULL || lt == NULL)
4834 if (last_tzset != time(NULL)) {
4836 last_tzset = time(NULL);
4839 if (*format == '%') {
4840 gint len = 0, tmp = 0;
4844 len = 1; CHECK_SIZE();
4848 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4849 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4852 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4853 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4857 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4858 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4861 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4862 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4865 strftime(subbuf, 64, "%c", lt);
4866 len = strlen(subbuf); CHECK_SIZE();
4867 strncpy2(curpos, subbuf, buflen - total_done);
4870 total_done += 2; CHECK_SIZE();
4871 tmp = (lt->tm_year + 1900)/100;
4872 *curpos++ = '0'+(tmp / 10);
4873 *curpos++ = '0'+(tmp % 10);
4876 total_done += 2; CHECK_SIZE();
4877 *curpos++ = '0'+(lt->tm_mday / 10);
4878 *curpos++ = '0'+(lt->tm_mday % 10);
4881 total_done += 8; CHECK_SIZE();
4882 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4883 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4885 *curpos++ = '0'+(lt->tm_mday / 10);
4886 *curpos++ = '0'+(lt->tm_mday % 10);
4888 tmp = lt->tm_year%100;
4889 *curpos++ = '0'+(tmp / 10);
4890 *curpos++ = '0'+(tmp % 10);
4893 len = 2; CHECK_SIZE();
4894 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4897 len = 10; CHECK_SIZE();
4898 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4899 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4902 total_done += 2; CHECK_SIZE();
4903 *curpos++ = '0'+(lt->tm_hour / 10);
4904 *curpos++ = '0'+(lt->tm_hour % 10);
4907 total_done += 2; CHECK_SIZE();
4913 *curpos++ = '0'+(tmp / 10);
4914 *curpos++ = '0'+(tmp % 10);
4917 len = 3; CHECK_SIZE();
4918 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4921 len = 2; CHECK_SIZE();
4922 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4925 len = 2; CHECK_SIZE();
4931 snprintf(curpos, buflen - total_done, "%2d", tmp);
4934 total_done += 2; CHECK_SIZE();
4935 tmp = lt->tm_mon + 1;
4936 *curpos++ = '0'+(tmp / 10);
4937 *curpos++ = '0'+(tmp % 10);
4940 total_done += 2; CHECK_SIZE();
4941 *curpos++ = '0'+(lt->tm_min / 10);
4942 *curpos++ = '0'+(lt->tm_min % 10);
4945 len = 1; CHECK_SIZE();
4949 if (lt->tm_hour >= 12) {
4950 len = s_pm_up_len; CHECK_SIZE();
4951 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4953 len = s_am_up_len; CHECK_SIZE();
4954 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4958 if (lt->tm_hour >= 12) {
4959 len = s_pm_low_len; CHECK_SIZE();
4960 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4962 len = s_am_low_len; CHECK_SIZE();
4963 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4967 strftime(subbuf, 64, "%r", lt);
4968 len = strlen(subbuf); CHECK_SIZE();
4969 strncpy2(curpos, subbuf, buflen - total_done);
4972 total_done += 5; CHECK_SIZE();
4973 *curpos++ = '0'+(lt->tm_hour / 10);
4974 *curpos++ = '0'+(lt->tm_hour % 10);
4976 *curpos++ = '0'+(lt->tm_min / 10);
4977 *curpos++ = '0'+(lt->tm_min % 10);
4980 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
4981 len = strlen(subbuf); CHECK_SIZE();
4982 strncpy2(curpos, subbuf, buflen - total_done);
4985 total_done += 2; CHECK_SIZE();
4986 *curpos++ = '0'+(lt->tm_sec / 10);
4987 *curpos++ = '0'+(lt->tm_sec % 10);
4990 len = 1; CHECK_SIZE();
4994 total_done += 8; CHECK_SIZE();
4995 *curpos++ = '0'+(lt->tm_hour / 10);
4996 *curpos++ = '0'+(lt->tm_hour % 10);
4998 *curpos++ = '0'+(lt->tm_min / 10);
4999 *curpos++ = '0'+(lt->tm_min % 10);
5001 *curpos++ = '0'+(lt->tm_sec / 10);
5002 *curpos++ = '0'+(lt->tm_sec % 10);
5005 len = 1; CHECK_SIZE();
5006 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
5009 len = 1; CHECK_SIZE();
5010 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
5013 strftime(subbuf, 64, "%x", lt);
5014 len = strlen(subbuf); CHECK_SIZE();
5015 strncpy2(curpos, subbuf, buflen - total_done);
5018 strftime(subbuf, 64, "%X", lt);
5019 len = strlen(subbuf); CHECK_SIZE();
5020 strncpy2(curpos, subbuf, buflen - total_done);
5023 total_done += 2; CHECK_SIZE();
5024 tmp = lt->tm_year%100;
5025 *curpos++ = '0'+(tmp / 10);
5026 *curpos++ = '0'+(tmp % 10);
5029 len = 4; CHECK_SIZE();
5030 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
5040 /* let these complicated ones be done with the libc */
5041 snprintf(subfmt, 64, "%%%c", *format);
5042 strftime(subbuf, 64, subfmt, lt);
5043 len = strlen(subbuf); CHECK_SIZE();
5044 strncpy2(curpos, subbuf, buflen - total_done);
5048 /* let these complicated modifiers be done with the libc */
5049 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
5050 strftime(subbuf, 64, subfmt, lt);
5051 len = strlen(subbuf); CHECK_SIZE();
5052 strncpy2(curpos, subbuf, buflen - total_done);
5056 g_warning("format error (%c)", *format);
5063 int len = 1; CHECK_SIZE();
5064 *curpos++ = *format++;
5071 gboolean prefs_common_get_use_shred(void);
5075 #define WEXITSTATUS(x) (x)
5078 int claws_unlink(const gchar *filename)
5081 static int found_shred = -1;
5082 static const gchar *args[4];
5084 if (filename == NULL)
5087 if (prefs_common_get_use_shred()) {
5088 if (found_shred == -1) {
5090 args[0] = g_find_program_in_path("shred");
5091 debug_print("found shred: %s\n", args[0]);
5092 found_shred = (args[0] != NULL) ? 1:0;
5096 if (found_shred == 1) {
5097 if (g_stat(filename, &s) == 0 && S_ISREG(s.st_mode)) {
5098 if (s.st_nlink == 1) {
5101 g_spawn_sync(NULL, (gchar **)args, NULL, 0,
5102 NULL, NULL, NULL, NULL, &status, NULL);
5103 debug_print("%s %s exited with status %d\n",
5104 args[0], filename, WEXITSTATUS(status));
5105 if (truncate(filename, 0) < 0)
5106 g_warning("couln't truncate: %s", filename);
5111 return g_unlink(filename);
5114 GMutex *cm_mutex_new(void) {
5115 #if GLIB_CHECK_VERSION(2,32,0)
5116 GMutex *m = g_new0(GMutex, 1);
5120 return g_mutex_new();
5124 void cm_mutex_free(GMutex *mutex) {
5125 #if GLIB_CHECK_VERSION(2,32,0)
5126 g_mutex_clear(mutex);
5129 g_mutex_free(mutex);
5133 static gchar *canonical_list_to_file(GSList *list)
5135 GString *result = g_string_new(NULL);
5136 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
5141 result = g_string_append(result, G_DIR_SEPARATOR_S);
5143 if (pathlist->data) {
5144 const gchar *root = (gchar *)pathlist->data;
5145 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
5147 /* drive - don't prepend dir separator */
5149 result = g_string_append(result, G_DIR_SEPARATOR_S);
5154 for (cur = pathlist; cur; cur = cur->next) {
5155 result = g_string_append(result, (gchar *)cur->data);
5157 result = g_string_append(result, G_DIR_SEPARATOR_S);
5159 g_slist_free(pathlist);
5162 g_string_free(result, FALSE);
5167 static GSList *cm_split_path(const gchar *filename, int depth)
5170 GSList *canonical_parts = NULL;
5174 gboolean follow_symlinks = TRUE;
5181 errno = EINVAL; /* can't happen, no symlink handling */
5186 if (!g_path_is_absolute(filename)) {
5191 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
5193 for (i = 0; path_parts[i] != NULL; i++) {
5194 if (!strcmp(path_parts[i], ""))
5196 if (!strcmp(path_parts[i], "."))
5198 else if (!strcmp(path_parts[i], "..")) {
5203 else /* Remove the last inserted element */
5205 g_slist_delete_link(canonical_parts,
5210 canonical_parts = g_slist_prepend(canonical_parts,
5211 g_strdup(path_parts[i]));
5213 tmp_path = canonical_list_to_file(canonical_parts);
5215 if(g_stat(tmp_path, &st) < 0) {
5216 if (errno == ENOENT) {
5219 follow_symlinks = FALSE;
5224 slist_free_strings_full(canonical_parts);
5225 g_strfreev(path_parts);
5231 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
5232 GError *error = NULL;
5233 gchar *target = g_file_read_link(tmp_path, &error);
5235 if (!g_path_is_absolute(target)) {
5236 /* remove the last inserted element */
5238 g_slist_delete_link(canonical_parts,
5240 /* add the target */
5241 canonical_parts = g_slist_prepend(canonical_parts,
5245 /* and get the new target */
5246 target = canonical_list_to_file(canonical_parts);
5249 /* restart from absolute target */
5250 slist_free_strings_full(canonical_parts);
5251 canonical_parts = NULL;
5253 canonical_parts = cm_split_path(target, depth + 1);
5255 g_error_free(error);
5256 if (canonical_parts == NULL) {
5258 g_strfreev(path_parts);
5267 g_strfreev(path_parts);
5268 return canonical_parts;
5272 * Canonicalize a filename, resolving symlinks along the way.
5273 * Returns a negative errno in case of error.
5275 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
5276 GSList *canonical_parts;
5277 gboolean is_absolute;
5279 if (filename == NULL)
5281 if (canonical_name == NULL)
5283 *canonical_name = NULL;
5285 is_absolute = g_path_is_absolute(filename);
5287 /* Always work on absolute filenames. */
5288 gchar *cur = g_get_current_dir();
5289 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
5292 canonical_parts = cm_split_path(absolute_filename, 0);
5293 g_free(absolute_filename);
5296 canonical_parts = cm_split_path(filename, 0);
5298 if (canonical_parts == NULL)
5301 *canonical_name = canonical_list_to_file(canonical_parts);
5302 slist_free_strings_full(canonical_parts);
5306 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
5307 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
5309 gchar *tmp = g_base64_decode(text, out_len);
5310 gchar *out = g_strndup(tmp, *out_len);
5314 if (strlen(out) != *out_len) {
5315 g_warning ("strlen(out) %zd != *out_len %" G_GSIZE_FORMAT, strlen(out), *out_len);
5321 #if !GLIB_CHECK_VERSION(2, 30, 0)
5324 * @str: a UTF-8 encoded string
5325 * @start_pos: a character offset within @str
5326 * @end_pos: another character offset within @str
5328 * Copies a substring out of a UTF-8 encoded string.
5329 * The substring will contain @end_pos - @start_pos
5332 * Returns: a newly allocated copy of the requested
5333 * substring. Free with g_free() when no longer needed.
5338 g_utf8_substring (const gchar *str,
5342 gchar *start, *end, *out;
5344 start = g_utf8_offset_to_pointer (str, start_pos);
5345 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
5347 out = g_malloc (end - start + 1);
5348 memcpy (out, start, end - start);
5349 out[end - start] = 0;
5355 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
5356 * It is up to the caller to make sure there is at least count bytes
5357 * available at buf. */
5359 get_random_bytes(void *buf, size_t count)
5361 /* Open our prng source. */
5362 #if defined G_OS_WIN32
5365 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
5366 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
5367 debug_print("Could not acquire a CSP handle.\n");
5374 rnd = open("/dev/urandom", O_RDONLY);
5376 FILE_OP_ERROR("/dev/urandom", "open");
5377 debug_print("Could not open /dev/urandom.\n");
5382 /* Read data from the source into buf. */
5383 #if defined G_OS_WIN32
5384 if (!CryptGenRandom(rnd, count, buf)) {
5385 debug_print("Could not read %zd random bytes.\n", count);
5386 CryptReleaseContext(rnd, 0);
5390 ret = read(rnd, buf, count);
5392 FILE_OP_ERROR("/dev/urandom", "read");
5393 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
5399 /* Close the prng source. */
5400 #if defined G_OS_WIN32
5401 CryptReleaseContext(rnd, 0);