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>
91 static gboolean debug_mode = FALSE;
93 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
95 #if GLIB_CHECK_VERSION(2, 34, 0)
96 return g_slist_copy_deep(list, func, NULL);
98 GSList *res = g_slist_copy(list);
101 walk->data = func(walk->data, NULL);
108 void list_free_strings_full(GList *list)
110 g_list_free_full(list, (GDestroyNotify)g_free);
113 void slist_free_strings_full(GSList *list)
115 g_slist_free_full(list, (GDestroyNotify)g_free);
118 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
123 void hash_free_strings(GHashTable *table)
125 g_hash_table_foreach(table, hash_free_strings_func, NULL);
128 gint str_case_equal(gconstpointer v, gconstpointer v2)
130 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
133 guint str_case_hash(gconstpointer key)
135 const gchar *p = key;
139 h = g_ascii_tolower(h);
140 for (p += 1; *p != '\0'; p++)
141 h = (h << 5) - h + g_ascii_tolower(*p);
147 gint to_number(const gchar *nstr)
149 register const gchar *p;
151 if (*nstr == '\0') return -1;
153 for (p = nstr; *p != '\0'; p++)
154 if (!g_ascii_isdigit(*p)) return -1;
159 /* convert integer into string,
160 nstr must be not lower than 11 characters length */
161 gchar *itos_buf(gchar *nstr, gint n)
163 g_snprintf(nstr, 11, "%d", n);
167 /* convert integer into string */
170 static gchar nstr[11];
172 return itos_buf(nstr, n);
175 #define divide(num,divisor,i,d) \
177 i = num >> divisor; \
178 d = num & ((1<<divisor)-1); \
179 d = (d*100) >> divisor; \
184 * \brief Convert a given size in bytes in a human-readable string
186 * \param size The size expressed in bytes to convert in string
187 * \return The string that respresents the size in an human-readable way
189 gchar *to_human_readable(goffset size)
191 static gchar str[14];
192 static gchar *b_format = NULL, *kb_format = NULL,
193 *mb_format = NULL, *gb_format = NULL;
194 register int t = 0, r = 0;
195 if (b_format == NULL) {
197 kb_format = _("%d.%02dKB");
198 mb_format = _("%d.%02dMB");
199 gb_format = _("%.2fGB");
202 if (size < (goffset)1024) {
203 g_snprintf(str, sizeof(str), b_format, (gint)size);
205 } else if (size >> 10 < (goffset)1024) {
206 divide(size, 10, t, r);
207 g_snprintf(str, sizeof(str), kb_format, t, r);
209 } else if (size >> 20 < (goffset)1024) {
210 divide(size, 20, t, r);
211 g_snprintf(str, sizeof(str), mb_format, t, r);
214 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
219 /* strcmp with NULL-checking */
220 gint strcmp2(const gchar *s1, const gchar *s2)
222 if (s1 == NULL || s2 == NULL)
225 return strcmp(s1, s2);
227 /* strstr with NULL-checking */
228 gchar *strstr2(const gchar *s1, const gchar *s2)
230 if (s1 == NULL || s2 == NULL)
233 return strstr(s1, s2);
236 gint path_cmp(const gchar *s1, const gchar *s2)
241 gchar *s1buf, *s2buf;
244 if (s1 == NULL || s2 == NULL) return -1;
245 if (*s1 == '\0' || *s2 == '\0') return -1;
248 s1buf = g_strdup (s1);
249 s2buf = g_strdup (s2);
250 subst_char (s1buf, '/', G_DIR_SEPARATOR);
251 subst_char (s2buf, '/', G_DIR_SEPARATOR);
254 #endif /* !G_OS_WIN32 */
259 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
260 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
262 rc = strncmp(s1, s2, MAX(len1, len2));
266 #endif /* !G_OS_WIN32 */
270 /* remove trailing return code */
271 gchar *strretchomp(gchar *str)
275 if (!*str) return str;
277 for (s = str + strlen(str) - 1;
278 s >= str && (*s == '\n' || *s == '\r');
285 /* remove trailing character */
286 gchar *strtailchomp(gchar *str, gchar tail_char)
290 if (!*str) return str;
291 if (tail_char == '\0') return str;
293 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
299 /* remove CR (carriage return) */
300 gchar *strcrchomp(gchar *str)
304 if (!*str) return str;
306 s = str + strlen(str) - 1;
307 if (*s == '\n' && s > str && *(s - 1) == '\r') {
315 gint file_strip_crs(const gchar *file)
317 FILE *fp = NULL, *outfp = NULL;
319 gchar *out = get_tmp_file();
323 fp = g_fopen(file, "rb");
327 outfp = g_fopen(out, "wb");
333 while (fgets(buf, sizeof (buf), fp) != NULL) {
335 if (fputs(buf, outfp) == EOF) {
343 if (fclose(outfp) == EOF) {
347 if (move_file(out, file, TRUE) < 0)
359 /* Similar to `strstr' but this function ignores the case of both strings. */
360 gchar *strcasestr(const gchar *haystack, const gchar *needle)
362 size_t haystack_len = strlen(haystack);
364 return strncasestr(haystack, haystack_len, needle);
367 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
369 register size_t needle_len;
371 needle_len = strlen(needle);
373 if (haystack_len < needle_len || needle_len == 0)
376 while (haystack_len >= needle_len) {
377 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
378 return (gchar *)haystack;
388 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
389 gconstpointer needle, size_t needlelen)
391 const gchar *haystack_ = (const gchar *)haystack;
392 const gchar *needle_ = (const gchar *)needle;
393 const gchar *haystack_cur = (const gchar *)haystack;
394 size_t haystack_left = haystacklen;
397 return memchr(haystack_, *needle_, haystacklen);
399 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
401 if (haystacklen - (haystack_cur - haystack_) < needlelen)
403 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
404 return (gpointer)haystack_cur;
407 haystack_left = haystacklen - (haystack_cur - haystack_);
414 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
415 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
417 register const gchar *s = src;
418 register gchar *d = dest;
428 /* Examine if next block is non-ASCII string */
429 gboolean is_next_nonascii(const gchar *s)
433 /* skip head space */
434 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
436 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
437 if (*(guchar *)p > 127 || *(guchar *)p < 32)
444 gint get_next_word_len(const gchar *s)
448 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
454 static void trim_subject_for_compare(gchar *str)
458 eliminate_parenthesis(str, '[', ']');
459 eliminate_parenthesis(str, '(', ')');
462 srcp = str + subject_get_prefix_length(str);
464 memmove(str, srcp, strlen(srcp) + 1);
467 static void trim_subject_for_sort(gchar *str)
473 srcp = str + subject_get_prefix_length(str);
475 memmove(str, srcp, strlen(srcp) + 1);
478 /* compare subjects */
479 gint subject_compare(const gchar *s1, const gchar *s2)
483 if (!s1 || !s2) return -1;
484 if (!*s1 || !*s2) return -1;
486 Xstrdup_a(str1, s1, return -1);
487 Xstrdup_a(str2, s2, return -1);
489 trim_subject_for_compare(str1);
490 trim_subject_for_compare(str2);
492 if (!*str1 || !*str2) return -1;
494 return strcmp(str1, str2);
497 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
501 if (!s1 || !s2) return -1;
503 Xstrdup_a(str1, s1, return -1);
504 Xstrdup_a(str2, s2, return -1);
506 trim_subject_for_sort(str1);
507 trim_subject_for_sort(str2);
509 return g_utf8_collate(str1, str2);
512 void trim_subject(gchar *str)
514 register gchar *srcp;
520 srcp = str + subject_get_prefix_length(str);
525 } else if (*srcp == '(') {
537 else if (*srcp == cl)
544 while (g_ascii_isspace(*srcp)) srcp++;
545 memmove(str, srcp, strlen(srcp) + 1);
548 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
550 register gchar *srcp, *destp;
555 while ((destp = strchr(destp, op))) {
561 else if (*srcp == cl)
567 while (g_ascii_isspace(*srcp)) srcp++;
568 memmove(destp, srcp, strlen(srcp) + 1);
572 void extract_parenthesis(gchar *str, gchar op, gchar cl)
574 register gchar *srcp, *destp;
579 while ((srcp = strchr(destp, op))) {
582 memmove(destp, srcp + 1, strlen(srcp));
587 else if (*destp == cl)
599 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
602 register gchar *srcp, *destp;
604 gboolean in_quote = FALSE;
608 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
611 memmove(destp, srcp + 1, strlen(srcp));
614 if (*destp == op && !in_quote)
616 else if (*destp == cl && !in_quote)
618 else if (*destp == quote_chr)
630 void extract_quote(gchar *str, gchar quote_chr)
634 if ((str = strchr(str, quote_chr))) {
636 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
637 memmove(p - 1, p, strlen(p) + 1);
642 memmove(str, str + 1, p - str);
647 /* Returns a newly allocated string with all quote_chr not at the beginning
648 or the end of str escaped with '\' or the given str if not required. */
649 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
651 register gchar *p, *q;
655 if (str == NULL || *str == '\0')
658 /* search for unescaped quote_chr */
663 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
667 if (!k) /* nothing to escape */
670 /* unescaped quote_chr found */
671 qstr = g_malloc(l + k + 1);
674 if (*p == quote_chr) {
679 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
688 void eliminate_address_comment(gchar *str)
690 register gchar *srcp, *destp;
695 while ((destp = strchr(destp, '"'))) {
696 if ((srcp = strchr(destp + 1, '"'))) {
701 while (g_ascii_isspace(*srcp)) srcp++;
702 memmove(destp, srcp, strlen(srcp) + 1);
712 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
718 else if (*srcp == ')')
724 while (g_ascii_isspace(*srcp)) srcp++;
725 memmove(destp, srcp, strlen(srcp) + 1);
729 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
731 gboolean in_quote = FALSE;
734 if (*str == c && !in_quote)
736 if (*str == quote_chr)
744 void extract_address(gchar *str)
746 cm_return_if_fail(str != NULL);
747 eliminate_address_comment(str);
748 if (strchr_with_skip_quote(str, '"', '<'))
749 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
753 void extract_list_id_str(gchar *str)
755 if (strchr_with_skip_quote(str, '"', '<'))
756 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
760 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
765 if (!str) return addr_list;
767 Xstrdup_a(work, str, return addr_list);
770 eliminate_address_comment(work);
773 while (workp && *workp) {
776 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
782 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
783 extract_parenthesis_with_skip_quote
784 (workp, '"', '<', '>');
788 addr_list = g_slist_append(addr_list, g_strdup(workp));
796 GSList *address_list_append(GSList *addr_list, const gchar *str)
798 return address_list_append_real(addr_list, str, TRUE);
801 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
803 return address_list_append_real(addr_list, str, FALSE);
806 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
810 if (!str) return msgid_list;
813 while (strp && *strp) {
814 const gchar *start, *end;
817 if ((start = strchr(strp, '<')) != NULL) {
818 end = strchr(start + 1, '>');
823 msgid = g_strndup(start + 1, end - start - 1);
826 msgid_list = g_slist_prepend(msgid_list, msgid);
836 GSList *references_list_append(GSList *msgid_list, const gchar *str)
840 list = references_list_prepend(NULL, str);
841 list = g_slist_reverse(list);
842 msgid_list = g_slist_concat(msgid_list, list);
847 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
852 if (!str) return group_list;
854 Xstrdup_a(work, str, return group_list);
858 while (workp && *workp) {
861 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
869 group_list = g_slist_append(group_list,
878 GList *add_history(GList *list, const gchar *str)
883 cm_return_val_if_fail(str != NULL, list);
885 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
888 list = g_list_remove(list, old->data);
890 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
893 last = g_list_last(list);
896 list = g_list_remove(list, last->data);
901 list = g_list_prepend(list, g_strdup(str));
906 void remove_return(gchar *str)
908 register gchar *p = str;
911 if (*p == '\n' || *p == '\r')
912 memmove(p, p + 1, strlen(p));
918 void remove_space(gchar *str)
920 register gchar *p = str;
925 while (g_ascii_isspace(*(p + spc)))
928 memmove(p, p + spc, strlen(p + spc) + 1);
934 void unfold_line(gchar *str)
940 ch = str; /* iterator for source string */
943 c = g_utf8_get_char_validated(ch, -1);
945 if (c == (gunichar)-1 || c == (gunichar)-2) {
946 /* non-unicode byte, move past it */
951 len = g_unichar_to_utf8(c, NULL);
953 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
954 g_unichar_isspace(c)) {
955 /* replace anything bad or whitespacey with a single space */
959 /* move rest of the string forwards, since we just replaced
960 * a multi-byte sequence with one byte */
961 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
964 /* A valid unicode character, copy it. */
970 void subst_char(gchar *str, gchar orig, gchar subst)
972 register gchar *p = str;
981 void subst_chars(gchar *str, gchar *orig, gchar subst)
983 register gchar *p = str;
986 if (strchr(orig, *p) != NULL)
992 void subst_for_filename(gchar *str)
997 subst_chars(str, "\t\r\n\\/*?:", '_');
999 subst_chars(str, "\t\r\n\\/*", '_');
1003 void subst_for_shellsafe_filename(gchar *str)
1007 subst_for_filename(str);
1008 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1011 gboolean is_ascii_str(const gchar *str)
1013 const guchar *p = (const guchar *)str;
1015 while (*p != '\0') {
1016 if (*p != '\t' && *p != ' ' &&
1017 *p != '\r' && *p != '\n' &&
1018 (*p < 32 || *p >= 127))
1026 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1028 gchar * position = NULL;
1029 gchar * tmp_pos = NULL;
1032 if (str == NULL || quote_chars == NULL)
1035 for (i = 0; i < strlen(quote_chars); i++) {
1036 tmp_pos = strrchr (str, quote_chars[i]);
1038 || (tmp_pos != NULL && position <= tmp_pos) )
1044 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1046 const gchar *first_pos;
1047 const gchar *last_pos;
1048 const gchar *p = str;
1049 gint quote_level = -1;
1051 /* speed up line processing by only searching to the last '>' */
1052 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1053 /* skip a line if it contains a '<' before the initial '>' */
1054 if (memchr(str, '<', first_pos - str) != NULL)
1056 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1060 while (p <= last_pos) {
1061 while (p < last_pos) {
1062 if (g_ascii_isspace(*p))
1068 if (strchr(quote_chars, *p))
1070 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1071 /* any characters are allowed except '-','<' and space */
1072 while (*p != '-' && *p != '<'
1073 && !strchr(quote_chars, *p)
1074 && !g_ascii_isspace(*p)
1077 if (strchr(quote_chars, *p))
1089 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1091 const gchar *p = str, *q;
1092 gint cur_line = 0, len;
1094 while ((q = strchr(p, '\n')) != NULL) {
1096 if (len > max_chars) {
1106 if (len > max_chars) {
1115 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1117 gchar * position = NULL;
1118 gchar * tmp_pos = NULL;
1121 if (str == NULL || quote_chars == NULL)
1124 for (i = 0; i < strlen(quote_chars); i++) {
1125 tmp_pos = strchr (str, quote_chars[i]);
1127 || (tmp_pos != NULL && position >= tmp_pos) )
1133 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1135 register guint haystack_len, needle_len;
1136 gboolean in_squote = FALSE, in_dquote = FALSE;
1138 haystack_len = strlen(haystack);
1139 needle_len = strlen(needle);
1141 if (haystack_len < needle_len || needle_len == 0)
1144 while (haystack_len >= needle_len) {
1145 if (!in_squote && !in_dquote &&
1146 !strncmp(haystack, needle, needle_len))
1147 return (gchar *)haystack;
1149 /* 'foo"bar"' -> foo"bar"
1150 "foo'bar'" -> foo'bar' */
1151 if (*haystack == '\'') {
1154 else if (!in_dquote)
1156 } else if (*haystack == '\"') {
1159 else if (!in_squote)
1161 } else if (*haystack == '\\') {
1173 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1176 GSList *string_list = NULL, *slist;
1177 gchar **str_array, *s, *new_str;
1178 guint i, n = 1, len;
1180 cm_return_val_if_fail(str != NULL, NULL);
1181 cm_return_val_if_fail(delim != NULL, NULL);
1184 max_tokens = G_MAXINT;
1186 s = strstr_with_skip_quote(str, delim);
1188 guint delimiter_len = strlen(delim);
1192 new_str = g_strndup(str, len);
1194 if (new_str[0] == '\'' || new_str[0] == '\"') {
1195 if (new_str[len - 1] == new_str[0]) {
1196 new_str[len - 1] = '\0';
1197 memmove(new_str, new_str + 1, len - 1);
1200 string_list = g_slist_prepend(string_list, new_str);
1202 str = s + delimiter_len;
1203 s = strstr_with_skip_quote(str, delim);
1204 } while (--max_tokens && s);
1208 new_str = g_strdup(str);
1209 if (new_str[0] == '\'' || new_str[0] == '\"') {
1211 if (new_str[len - 1] == new_str[0]) {
1212 new_str[len - 1] = '\0';
1213 memmove(new_str, new_str + 1, len - 1);
1216 string_list = g_slist_prepend(string_list, new_str);
1220 str_array = g_new(gchar*, n);
1224 str_array[i--] = NULL;
1225 for (slist = string_list; slist; slist = slist->next)
1226 str_array[i--] = slist->data;
1228 g_slist_free(string_list);
1233 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1235 gchar *abbrev_group;
1237 const gchar *p = group;
1240 cm_return_val_if_fail(group != NULL, NULL);
1242 last = group + strlen(group);
1243 abbrev_group = ap = g_malloc(strlen(group) + 1);
1248 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1250 while (*p != '.') p++;
1253 return abbrev_group;
1258 return abbrev_group;
1261 gchar *trim_string(const gchar *str, gint len)
1263 const gchar *p = str;
1268 if (!str) return NULL;
1269 if (strlen(str) <= len)
1270 return g_strdup(str);
1271 if (g_utf8_validate(str, -1, NULL) == FALSE)
1272 return g_strdup(str);
1274 while (*p != '\0') {
1275 mb_len = g_utf8_skip[*(guchar *)p];
1278 else if (new_len + mb_len > len)
1285 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1286 return g_strconcat(new_str, "...", NULL);
1289 GList *uri_list_extract_filenames(const gchar *uri_list)
1291 GList *result = NULL;
1293 gchar *escaped_utf8uri;
1299 while (g_ascii_isspace(*p)) p++;
1300 if (!strncmp(p, "file:", 5)) {
1303 while (*q && *q != '\n' && *q != '\r') q++;
1306 gchar *file, *locale_file = NULL;
1308 while (q > p && g_ascii_isspace(*q))
1310 Xalloca(escaped_utf8uri, q - p + 2,
1312 Xalloca(file, q - p + 2,
1315 strncpy(escaped_utf8uri, p, q - p + 1);
1316 escaped_utf8uri[q - p + 1] = '\0';
1317 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1319 * g_filename_from_uri() rejects escaped/locale encoded uri
1320 * string which come from Nautilus.
1323 if (g_utf8_validate(file, -1, NULL))
1325 = conv_codeset_strdup(
1328 conv_get_locale_charset_str());
1330 locale_file = g_strdup(file + 5);
1332 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1334 result = g_list_append(result, locale_file);
1338 p = strchr(p, '\n');
1345 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1348 static gint axtoi(const gchar *hexstr)
1350 gint hi, lo, result;
1353 if ('0' <= hi && hi <= '9') {
1356 if ('a' <= hi && hi <= 'f') {
1359 if ('A' <= hi && hi <= 'F') {
1364 if ('0' <= lo && lo <= '9') {
1367 if ('a' <= lo && lo <= 'f') {
1370 if ('A' <= lo && lo <= 'F') {
1373 result = lo + (16 * hi);
1377 gboolean is_uri_string(const gchar *str)
1379 while (str && *str && g_ascii_isspace(*str))
1381 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1382 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1383 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1384 g_ascii_strncasecmp(str, "www.", 4) == 0);
1387 gchar *get_uri_path(const gchar *uri)
1389 while (uri && *uri && g_ascii_isspace(*uri))
1391 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1392 return (gchar *)(uri + 7);
1393 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1394 return (gchar *)(uri + 8);
1395 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1396 return (gchar *)(uri + 6);
1398 return (gchar *)uri;
1401 gint get_uri_len(const gchar *str)
1405 if (is_uri_string(str)) {
1406 for (p = str; *p != '\0'; p++) {
1407 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1416 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1417 * plusses, and escape characters are used)
1419 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1421 gchar *dec = decoded_uri;
1422 const gchar *enc = encoded_uri;
1427 if (isxdigit((guchar)enc[0]) &&
1428 isxdigit((guchar)enc[1])) {
1434 if (with_plus && *enc == '+')
1446 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1448 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1451 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1453 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1454 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1458 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1459 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1463 const gchar *forbidden_uris[] = { ".gnupg/",
1469 gint num_attach = 0;
1470 gchar **my_att = NULL;
1472 Xstrdup_a(tmp_mailto, mailto, return -1);
1474 if (!strncmp(tmp_mailto, "mailto:", 7))
1477 p = strchr(tmp_mailto, '?');
1484 *to = decode_uri_gdup(tmp_mailto);
1486 my_att = g_malloc(sizeof(char *));
1490 gchar *field, *value;
1507 if (*value == '\0') continue;
1509 if (from && !g_ascii_strcasecmp(field, "from")) {
1511 *from = decode_uri_gdup(value);
1513 gchar *tmp = decode_uri_gdup(value);
1514 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1518 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1520 *cc = decode_uri_gdup(value);
1522 gchar *tmp = decode_uri_gdup(value);
1523 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1527 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1529 *bcc = decode_uri_gdup(value);
1531 gchar *tmp = decode_uri_gdup(value);
1532 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1536 } else if (subject && !*subject &&
1537 !g_ascii_strcasecmp(field, "subject")) {
1538 *subject = decode_uri_gdup(value);
1539 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1540 *body = decode_uri_gdup(value);
1541 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1542 gchar *tmp = decode_uri_gdup(value);
1543 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1544 g_warning("couldn't set insert file '%s' in body", value);
1547 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1549 gchar *tmp = decode_uri_gdup(value);
1550 for (; forbidden_uris[i]; i++) {
1551 if (strstr(tmp, forbidden_uris[i])) {
1552 g_print("Refusing to attach '%s', potential private data leak\n",
1559 /* attach is correct */
1561 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1562 my_att[num_attach-1] = tmp;
1563 my_att[num_attach] = NULL;
1565 } else if (inreplyto && !*inreplyto &&
1566 !g_ascii_strcasecmp(field, "in-reply-to")) {
1567 *inreplyto = decode_uri_gdup(value);
1578 #include <windows.h>
1579 #ifndef CSIDL_APPDATA
1580 #define CSIDL_APPDATA 0x001a
1582 #ifndef CSIDL_LOCAL_APPDATA
1583 #define CSIDL_LOCAL_APPDATA 0x001c
1585 #ifndef CSIDL_FLAG_CREATE
1586 #define CSIDL_FLAG_CREATE 0x8000
1588 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1592 w32_strerror (int w32_errno)
1594 static char strerr[256];
1595 int ec = (int)GetLastError ();
1599 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1600 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1601 strerr, DIM (strerr)-1, NULL);
1605 static __inline__ void *
1606 dlopen (const char * name, int flag)
1608 void * hd = LoadLibrary (name);
1612 static __inline__ void *
1613 dlsym (void * hd, const char * sym)
1617 void * fnc = GetProcAddress (hd, sym);
1626 static __inline__ const char *
1629 return w32_strerror (0);
1633 static __inline__ int
1645 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1647 static int initialized;
1648 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1652 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1658 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1660 handle = dlopen (dllnames[i], RTLD_LAZY);
1663 func = dlsym (handle, "SHGetFolderPathW");
1674 return func (a,b,c,d,e);
1679 /* Returns a static string with the directroy from which the module
1680 has been loaded. Returns an empty string on error. */
1681 static char *w32_get_module_dir(void)
1683 static char *moddir;
1686 char name[MAX_PATH+10];
1689 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1692 p = strrchr (name, '\\');
1698 moddir = g_strdup (name);
1702 #endif /* G_OS_WIN32 */
1704 /* Return a static string with the locale dir. */
1705 const gchar *get_locale_dir(void)
1707 static gchar *loc_dir;
1711 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1712 "\\share\\locale", NULL);
1715 loc_dir = LOCALEDIR;
1721 const gchar *get_home_dir(void)
1724 static char home_dir_utf16[MAX_PATH] = "";
1725 static gchar *home_dir_utf8 = NULL;
1726 if (home_dir_utf16[0] == '\0') {
1727 if (w32_shgetfolderpath
1728 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1729 NULL, 0, home_dir_utf16) < 0)
1730 strcpy (home_dir_utf16, "C:\\Claws Mail");
1731 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1733 return home_dir_utf8;
1735 static const gchar *homeenv = NULL;
1740 if (!homeenv && g_getenv("HOME") != NULL)
1741 homeenv = g_strdup(g_getenv("HOME"));
1743 homeenv = g_get_home_dir();
1749 static gchar *claws_rc_dir = NULL;
1750 static gboolean rc_dir_alt = FALSE;
1751 const gchar *get_rc_dir(void)
1754 if (!claws_rc_dir) {
1755 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1757 debug_print("using default rc_dir %s\n", claws_rc_dir);
1759 return claws_rc_dir;
1762 void set_rc_dir(const gchar *dir)
1764 gchar *canonical_dir;
1765 if (claws_rc_dir != NULL) {
1766 g_print("Error: rc_dir already set\n");
1768 int err = cm_canonicalize_filename(dir, &canonical_dir);
1772 g_print("Error looking for %s: %d(%s)\n",
1773 dir, -err, g_strerror(-err));
1778 claws_rc_dir = canonical_dir;
1780 len = strlen(claws_rc_dir);
1781 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1782 claws_rc_dir[len - 1] = '\0';
1784 debug_print("set rc_dir to %s\n", claws_rc_dir);
1785 if (!is_dir_exist(claws_rc_dir)) {
1786 if (make_dir_hier(claws_rc_dir) != 0) {
1787 g_print("Error: can't create %s\n",
1795 gboolean rc_dir_is_alt(void) {
1799 const gchar *get_mail_base_dir(void)
1801 return get_home_dir();
1804 const gchar *get_news_cache_dir(void)
1806 static gchar *news_cache_dir = NULL;
1807 if (!news_cache_dir)
1808 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1809 NEWS_CACHE_DIR, NULL);
1811 return news_cache_dir;
1814 const gchar *get_imap_cache_dir(void)
1816 static gchar *imap_cache_dir = NULL;
1818 if (!imap_cache_dir)
1819 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1820 IMAP_CACHE_DIR, NULL);
1822 return imap_cache_dir;
1825 const gchar *get_mime_tmp_dir(void)
1827 static gchar *mime_tmp_dir = NULL;
1830 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1831 MIME_TMP_DIR, NULL);
1833 return mime_tmp_dir;
1836 const gchar *get_template_dir(void)
1838 static gchar *template_dir = NULL;
1841 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1842 TEMPLATE_DIR, NULL);
1844 return template_dir;
1848 const gchar *w32_get_cert_file(void)
1850 const gchar *cert_file = NULL;
1852 cert_file = g_strconcat(w32_get_module_dir(),
1853 "\\share\\claws-mail\\",
1854 "ca-certificates.crt",
1860 /* Return the filepath of the claws-mail.desktop file */
1861 const gchar *get_desktop_file(void)
1863 #ifdef DESKTOPFILEPATH
1864 return DESKTOPFILEPATH;
1870 /* Return the default directory for Plugins. */
1871 const gchar *get_plugin_dir(void)
1874 static gchar *plugin_dir = NULL;
1877 plugin_dir = g_strconcat(w32_get_module_dir(),
1878 "\\lib\\claws-mail\\plugins\\",
1882 if (is_dir_exist(PLUGINDIR))
1885 static gchar *plugin_dir = NULL;
1887 plugin_dir = g_strconcat(get_rc_dir(),
1888 G_DIR_SEPARATOR_S, "plugins",
1889 G_DIR_SEPARATOR_S, NULL);
1897 /* Return the default directory for Themes. */
1898 const gchar *w32_get_themes_dir(void)
1900 static gchar *themes_dir = NULL;
1903 themes_dir = g_strconcat(w32_get_module_dir(),
1904 "\\share\\claws-mail\\themes",
1910 const gchar *get_tmp_dir(void)
1912 static gchar *tmp_dir = NULL;
1915 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1921 gchar *get_tmp_file(void)
1924 static guint32 id = 0;
1926 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1927 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1932 const gchar *get_domain_name(void)
1935 static gchar *domain_name = NULL;
1936 struct addrinfo hints, *res;
1941 if (gethostname(hostname, sizeof(hostname)) != 0) {
1942 perror("gethostname");
1943 domain_name = "localhost";
1945 memset(&hints, 0, sizeof(struct addrinfo));
1946 hints.ai_family = AF_UNSPEC;
1947 hints.ai_socktype = 0;
1948 hints.ai_flags = AI_CANONNAME;
1949 hints.ai_protocol = 0;
1951 s = getaddrinfo(hostname, NULL, &hints, &res);
1953 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1954 domain_name = g_strdup(hostname);
1956 domain_name = g_strdup(res->ai_canonname);
1960 debug_print("domain name = %s\n", domain_name);
1969 off_t get_file_size(const gchar *file)
1974 GError *error = NULL;
1977 f = g_file_new_for_path(file);
1978 fi = g_file_query_info(f, "standard::size",
1979 G_FILE_QUERY_INFO_NONE, NULL, &error);
1980 if (error != NULL) {
1981 debug_print("get_file_size error: %s\n", error->message);
1982 g_error_free(error);
1986 size = g_file_info_get_size(fi);
1994 if (g_stat(file, &s) < 0) {
1995 FILE_OP_ERROR(file, "stat");
2003 time_t get_file_mtime(const gchar *file)
2007 if (g_stat(file, &s) < 0) {
2008 FILE_OP_ERROR(file, "stat");
2015 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2022 if (g_stat(file, &s) < 0) {
2023 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2027 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2034 /* Test on whether FILE is a relative file name. This is
2035 * straightforward for Unix but more complex for Windows. */
2036 gboolean is_relative_filename(const gchar *file)
2041 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2042 return FALSE; /* Prefixed with a hostname - this can't
2043 * be a relative name. */
2045 if ( ((*file >= 'a' && *file <= 'z')
2046 || (*file >= 'A' && *file <= 'Z'))
2048 file += 2; /* Skip drive letter. */
2050 return !(*file == '\\' || *file == '/');
2052 return !(*file == G_DIR_SEPARATOR);
2057 gboolean is_dir_exist(const gchar *dir)
2062 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2065 gboolean is_file_entry_exist(const gchar *file)
2070 return g_file_test(file, G_FILE_TEST_EXISTS);
2073 gboolean dirent_is_regular_file(struct dirent *d)
2075 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2076 if (d->d_type == DT_REG)
2078 else if (d->d_type != DT_UNKNOWN)
2082 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2085 gint change_dir(const gchar *dir)
2087 gchar *prevdir = NULL;
2090 prevdir = g_get_current_dir();
2092 if (g_chdir(dir) < 0) {
2093 FILE_OP_ERROR(dir, "chdir");
2094 if (debug_mode) g_free(prevdir);
2096 } else if (debug_mode) {
2099 cwd = g_get_current_dir();
2100 if (strcmp(prevdir, cwd) != 0)
2101 g_print("current dir: %s\n", cwd);
2109 gint make_dir(const gchar *dir)
2111 if (g_mkdir(dir, S_IRWXU) < 0) {
2112 FILE_OP_ERROR(dir, "mkdir");
2115 if (g_chmod(dir, S_IRWXU) < 0)
2116 FILE_OP_ERROR(dir, "chmod");
2121 gint make_dir_hier(const gchar *dir)
2126 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2127 parent_dir = g_strndup(dir, p - dir);
2128 if (*parent_dir != '\0') {
2129 if (!is_dir_exist(parent_dir)) {
2130 if (make_dir(parent_dir) < 0) {
2139 if (!is_dir_exist(dir)) {
2140 if (make_dir(dir) < 0)
2147 gint remove_all_files(const gchar *dir)
2150 const gchar *file_name;
2153 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2154 g_warning("failed to open directory: %s", dir);
2158 while ((file_name = g_dir_read_name(dp)) != NULL) {
2159 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2160 if (claws_unlink(tmp) < 0)
2161 FILE_OP_ERROR(tmp, "unlink");
2170 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2173 const gchar *dir_name;
2177 if (first == last) {
2178 /* Skip all the dir reading part. */
2179 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2180 if (is_dir_exist(filename)) {
2181 /* a numbered directory with this name exists,
2182 * remove the dot-file instead */
2184 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2186 if (claws_unlink(filename) < 0) {
2187 FILE_OP_ERROR(filename, "unlink");
2195 prev_dir = g_get_current_dir();
2197 if (g_chdir(dir) < 0) {
2198 FILE_OP_ERROR(dir, "chdir");
2203 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2204 g_warning("failed to open directory: %s", dir);
2209 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2210 file_no = to_number(dir_name);
2211 if (file_no > 0 && first <= file_no && file_no <= last) {
2212 if (is_dir_exist(dir_name)) {
2213 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2214 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2215 FILE_OP_ERROR(dot_file, "unlink");
2220 if (claws_unlink(dir_name) < 0)
2221 FILE_OP_ERROR(dir_name, "unlink");
2227 if (g_chdir(prev_dir) < 0) {
2228 FILE_OP_ERROR(prev_dir, "chdir");
2238 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2241 const gchar *dir_name;
2244 GHashTable *wanted_files;
2246 GError *error = NULL;
2248 if (numberlist == NULL)
2251 prev_dir = g_get_current_dir();
2253 if (g_chdir(dir) < 0) {
2254 FILE_OP_ERROR(dir, "chdir");
2259 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2260 g_message("Couldn't open current directory: %s (%d).\n",
2261 error->message, error->code);
2262 g_error_free(error);
2267 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2268 for (cur = numberlist; cur != NULL; cur = cur->next) {
2269 /* numberlist->data is expected to be GINT_TO_POINTER */
2270 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2273 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2274 file_no = to_number(dir_name);
2275 if (is_dir_exist(dir_name))
2277 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2278 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2279 if (is_dir_exist(dir_name)) {
2280 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2281 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2282 FILE_OP_ERROR(dot_file, "unlink");
2287 if (claws_unlink(dir_name) < 0)
2288 FILE_OP_ERROR(dir_name, "unlink");
2293 g_hash_table_destroy(wanted_files);
2295 if (g_chdir(prev_dir) < 0) {
2296 FILE_OP_ERROR(prev_dir, "chdir");
2306 gint remove_all_numbered_files(const gchar *dir)
2308 return remove_numbered_files(dir, 0, UINT_MAX);
2311 gint remove_dir_recursive(const gchar *dir)
2315 const gchar *dir_name;
2318 if (g_stat(dir, &s) < 0) {
2319 FILE_OP_ERROR(dir, "stat");
2320 if (ENOENT == errno) return 0;
2324 if (!S_ISDIR(s.st_mode)) {
2325 if (claws_unlink(dir) < 0) {
2326 FILE_OP_ERROR(dir, "unlink");
2333 prev_dir = g_get_current_dir();
2334 /* g_print("prev_dir = %s\n", prev_dir); */
2336 if (!path_cmp(prev_dir, dir)) {
2338 if (g_chdir("..") < 0) {
2339 FILE_OP_ERROR(dir, "chdir");
2342 prev_dir = g_get_current_dir();
2345 if (g_chdir(dir) < 0) {
2346 FILE_OP_ERROR(dir, "chdir");
2351 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2352 g_warning("failed to open directory: %s", dir);
2358 /* remove all files in the directory */
2359 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2360 /* g_print("removing %s\n", dir_name); */
2362 if (is_dir_exist(dir_name)) {
2365 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2366 g_warning("can't remove directory: %s", dir_name);
2370 if (claws_unlink(dir_name) < 0)
2371 FILE_OP_ERROR(dir_name, "unlink");
2377 if (g_chdir(prev_dir) < 0) {
2378 FILE_OP_ERROR(prev_dir, "chdir");
2385 if (g_rmdir(dir) < 0) {
2386 FILE_OP_ERROR(dir, "rmdir");
2393 gint rename_force(const gchar *oldpath, const gchar *newpath)
2396 if (!is_file_entry_exist(oldpath)) {
2400 if (is_file_exist(newpath)) {
2401 if (claws_unlink(newpath) < 0)
2402 FILE_OP_ERROR(newpath, "unlink");
2405 return g_rename(oldpath, newpath);
2409 * Append src file body to the tail of dest file.
2410 * Now keep_backup has no effects.
2412 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2414 FILE *src_fp, *dest_fp;
2418 gboolean err = FALSE;
2420 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2421 FILE_OP_ERROR(src, "g_fopen");
2425 if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2426 FILE_OP_ERROR(dest, "g_fopen");
2431 if (change_file_mode_rw(dest_fp, dest) < 0) {
2432 FILE_OP_ERROR(dest, "chmod");
2433 g_warning("can't change file mode: %s", dest);
2436 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2437 if (n_read < sizeof(buf) && ferror(src_fp))
2439 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2440 g_warning("writing to %s failed.", dest);
2448 if (ferror(src_fp)) {
2449 FILE_OP_ERROR(src, "fread");
2453 if (fclose(dest_fp) == EOF) {
2454 FILE_OP_ERROR(dest, "fclose");
2466 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2468 FILE *src_fp, *dest_fp;
2471 gchar *dest_bak = NULL;
2472 gboolean err = FALSE;
2474 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2475 FILE_OP_ERROR(src, "g_fopen");
2478 if (is_file_exist(dest)) {
2479 dest_bak = g_strconcat(dest, ".bak", NULL);
2480 if (rename_force(dest, dest_bak) < 0) {
2481 FILE_OP_ERROR(dest, "rename");
2488 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2489 FILE_OP_ERROR(dest, "g_fopen");
2492 if (rename_force(dest_bak, dest) < 0)
2493 FILE_OP_ERROR(dest_bak, "rename");
2499 if (change_file_mode_rw(dest_fp, dest) < 0) {
2500 FILE_OP_ERROR(dest, "chmod");
2501 g_warning("can't change file mode: %s", dest);
2504 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2505 if (n_read < sizeof(buf) && ferror(src_fp))
2507 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2508 g_warning("writing to %s failed.", dest);
2513 if (rename_force(dest_bak, dest) < 0)
2514 FILE_OP_ERROR(dest_bak, "rename");
2521 if (ferror(src_fp)) {
2522 FILE_OP_ERROR(src, "fread");
2526 if (fclose(dest_fp) == EOF) {
2527 FILE_OP_ERROR(dest, "fclose");
2534 if (rename_force(dest_bak, dest) < 0)
2535 FILE_OP_ERROR(dest_bak, "rename");
2541 if (keep_backup == FALSE && dest_bak)
2542 claws_unlink(dest_bak);
2549 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2551 if (overwrite == FALSE && is_file_exist(dest)) {
2552 g_warning("move_file(): file %s already exists.", dest);
2556 if (rename_force(src, dest) == 0) return 0;
2558 if (EXDEV != errno) {
2559 FILE_OP_ERROR(src, "rename");
2563 if (copy_file(src, dest, FALSE) < 0) return -1;
2570 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2573 gint bytes_left, to_read;
2576 if (fseek(fp, offset, SEEK_SET) < 0) {
2581 bytes_left = length;
2582 to_read = MIN(bytes_left, sizeof(buf));
2584 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2585 if (n_read < to_read && ferror(fp))
2587 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2590 bytes_left -= n_read;
2591 if (bytes_left == 0)
2593 to_read = MIN(bytes_left, sizeof(buf));
2604 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2607 gboolean err = FALSE;
2609 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2610 FILE_OP_ERROR(dest, "g_fopen");
2614 if (change_file_mode_rw(dest_fp, dest) < 0) {
2615 FILE_OP_ERROR(dest, "chmod");
2616 g_warning("can't change file mode: %s", dest);
2619 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2622 if (fclose(dest_fp) == EOF) {
2623 FILE_OP_ERROR(dest, "fclose");
2628 g_warning("writing to %s failed.", dest);
2636 /* convert line endings into CRLF. If the last line doesn't end with
2637 * linebreak, add it.
2639 gchar *canonicalize_str(const gchar *str)
2645 for (p = str; *p != '\0'; ++p) {
2652 if (p == str || *(p - 1) != '\n')
2655 out = outp = g_malloc(new_len + 1);
2656 for (p = str; *p != '\0'; ++p) {
2663 if (p == str || *(p - 1) != '\n') {
2672 gint canonicalize_file(const gchar *src, const gchar *dest)
2674 FILE *src_fp, *dest_fp;
2675 gchar buf[BUFFSIZE];
2677 gboolean err = FALSE;
2678 gboolean last_linebreak = FALSE;
2680 if (src == NULL || dest == NULL)
2683 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2684 FILE_OP_ERROR(src, "g_fopen");
2688 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2689 FILE_OP_ERROR(dest, "g_fopen");
2694 if (change_file_mode_rw(dest_fp, dest) < 0) {
2695 FILE_OP_ERROR(dest, "chmod");
2696 g_warning("can't change file mode: %s", dest);
2699 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2703 if (len == 0) break;
2704 last_linebreak = FALSE;
2706 if (buf[len - 1] != '\n') {
2707 last_linebreak = TRUE;
2708 r = fputs(buf, dest_fp);
2709 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2710 r = fputs(buf, dest_fp);
2713 r = fwrite(buf, 1, len - 1, dest_fp);
2718 r = fputs("\r\n", dest_fp);
2722 g_warning("writing to %s failed.", dest);
2730 if (last_linebreak == TRUE) {
2731 if (fputs("\r\n", dest_fp) == EOF)
2735 if (ferror(src_fp)) {
2736 FILE_OP_ERROR(src, "fgets");
2740 if (fclose(dest_fp) == EOF) {
2741 FILE_OP_ERROR(dest, "fclose");
2753 gint canonicalize_file_replace(const gchar *file)
2757 tmp_file = get_tmp_file();
2759 if (canonicalize_file(file, tmp_file) < 0) {
2764 if (move_file(tmp_file, file, TRUE) < 0) {
2765 g_warning("can't replace file: %s", file);
2766 claws_unlink(tmp_file);
2775 gchar *normalize_newlines(const gchar *str)
2780 out = outp = g_malloc(strlen(str) + 1);
2781 for (p = str; *p != '\0'; ++p) {
2783 if (*(p + 1) != '\n')
2794 gchar *get_outgoing_rfc2822_str(FILE *fp)
2796 gchar buf[BUFFSIZE];
2800 str = g_string_new(NULL);
2802 /* output header part */
2803 while (fgets(buf, sizeof(buf), fp) != NULL) {
2805 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2812 else if (next != ' ' && next != '\t') {
2816 if (fgets(buf, sizeof(buf), fp) == NULL)
2820 g_string_append(str, buf);
2821 g_string_append(str, "\r\n");
2827 /* output body part */
2828 while (fgets(buf, sizeof(buf), fp) != NULL) {
2831 g_string_append_c(str, '.');
2832 g_string_append(str, buf);
2833 g_string_append(str, "\r\n");
2837 g_string_free(str, FALSE);
2843 * Create a new boundary in a way that it is very unlikely that this
2844 * will occur in the following text. It would be easy to ensure
2845 * uniqueness if everything is either quoted-printable or base64
2846 * encoded (note that conversion is allowed), but because MIME bodies
2847 * may be nested, it may happen that the same boundary has already
2850 * boundary := 0*69<bchars> bcharsnospace
2851 * bchars := bcharsnospace / " "
2852 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2853 * "+" / "_" / "," / "-" / "." /
2854 * "/" / ":" / "=" / "?"
2856 * some special characters removed because of buggy MTAs
2859 gchar *generate_mime_boundary(const gchar *prefix)
2861 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2862 "abcdefghijklmnopqrstuvwxyz"
2867 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2868 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2871 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2875 gint change_file_mode_rw(FILE *fp, const gchar *file)
2878 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2880 return g_chmod(file, S_IRUSR|S_IWUSR);
2884 FILE *my_tmpfile(void)
2886 const gchar suffix[] = ".XXXXXX";
2887 const gchar *tmpdir;
2889 const gchar *progname;
2898 tmpdir = get_tmp_dir();
2899 tmplen = strlen(tmpdir);
2900 progname = g_get_prgname();
2901 if (progname == NULL)
2902 progname = "claws-mail";
2903 proglen = strlen(progname);
2904 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2907 memcpy(fname, tmpdir, tmplen);
2908 fname[tmplen] = G_DIR_SEPARATOR;
2909 memcpy(fname + tmplen + 1, progname, proglen);
2910 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2912 fd = g_mkstemp(fname);
2917 claws_unlink(fname);
2919 /* verify that we can write in the file after unlinking */
2920 if (write(fd, buf, 1) < 0) {
2927 fp = fdopen(fd, "w+b");
2938 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2941 *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
2942 fd = g_mkstemp(*filename);
2945 return fdopen(fd, "w+");
2948 FILE *str_open_as_stream(const gchar *str)
2953 cm_return_val_if_fail(str != NULL, NULL);
2957 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2962 if (len == 0) return fp;
2964 if (fwrite(str, 1, len, fp) != len) {
2965 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2974 gint str_write_to_file(const gchar *str, const gchar *file)
2979 cm_return_val_if_fail(str != NULL, -1);
2980 cm_return_val_if_fail(file != NULL, -1);
2982 if ((fp = g_fopen(file, "wb")) == NULL) {
2983 FILE_OP_ERROR(file, "g_fopen");
2993 if (fwrite(str, 1, len, fp) != len) {
2994 FILE_OP_ERROR(file, "fwrite");
3000 if (fclose(fp) == EOF) {
3001 FILE_OP_ERROR(file, "fclose");
3009 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3016 cm_return_val_if_fail(fp != NULL, NULL);
3018 array = g_byte_array_new();
3020 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3021 if (n_read < sizeof(buf) && ferror(fp))
3023 g_byte_array_append(array, buf, n_read);
3027 FILE_OP_ERROR("file stream", "fread");
3028 g_byte_array_free(array, TRUE);
3033 g_byte_array_append(array, buf, 1);
3034 str = (gchar *)array->data;
3035 g_byte_array_free(array, FALSE);
3037 if (recode && !g_utf8_validate(str, -1, NULL)) {
3038 const gchar *src_codeset, *dest_codeset;
3040 src_codeset = conv_get_locale_charset_str();
3041 dest_codeset = CS_UTF_8;
3042 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3050 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3057 struct timeval timeout = {1, 0};
3062 cm_return_val_if_fail(file != NULL, NULL);
3064 if (g_stat(file, &s) != 0) {
3065 FILE_OP_ERROR(file, "stat");
3068 if (S_ISDIR(s.st_mode)) {
3069 g_warning("%s: is a directory", file);
3074 fp = g_fopen (file, "rb");
3076 FILE_OP_ERROR(file, "open");
3080 /* test whether the file is readable without blocking */
3081 fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3083 FILE_OP_ERROR(file, "open");
3090 /* allow for one second */
3091 err = select(fd+1, &fds, NULL, NULL, &timeout);
3092 if (err <= 0 || !FD_ISSET(fd, &fds)) {
3094 FILE_OP_ERROR(file, "select");
3096 g_warning("%s: doesn't seem readable", file);
3102 /* Now clear O_NONBLOCK */
3103 if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3104 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3108 if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3109 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3114 /* get the FILE pointer */
3115 fp = fdopen(fd, "rb");
3118 FILE_OP_ERROR(file, "fdopen");
3119 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3124 str = file_read_stream_to_str_full(fp, recode);
3131 gchar *file_read_to_str(const gchar *file)
3133 return file_read_to_str_full(file, TRUE);
3135 gchar *file_read_stream_to_str(FILE *fp)
3137 return file_read_stream_to_str_full(fp, TRUE);
3140 gchar *file_read_to_str_no_recode(const gchar *file)
3142 return file_read_to_str_full(file, FALSE);
3144 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3146 return file_read_stream_to_str_full(fp, FALSE);
3149 char *fgets_crlf(char *buf, int size, FILE *stream)
3151 gboolean is_cr = FALSE;
3152 gboolean last_was_cr = FALSE;
3157 while (--size > 0 && (c = getc(stream)) != EOF)
3160 is_cr = (c == '\r');
3170 last_was_cr = is_cr;
3172 if (c == EOF && cs == buf)
3180 static gint execute_async(gchar *const argv[], const gchar *working_directory)
3182 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3184 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3185 NULL, NULL, NULL, FALSE) == FALSE) {
3186 g_warning("couldn't execute command: %s", argv[0]);
3193 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
3197 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3200 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3201 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3202 g_warning("couldn't execute command: %s", argv[0]);
3206 if (WIFEXITED(status))
3207 return WEXITSTATUS(status);
3211 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
3212 G_SPAWN_SEARCH_PATH|
3213 G_SPAWN_CHILD_INHERITS_STDIN|
3214 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3215 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3216 g_warning("couldn't execute command: %s", argv[0]);
3224 gint execute_command_line(const gchar *cmdline, gboolean async,
3225 const gchar *working_directory)
3230 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3232 argv = strsplit_with_quote(cmdline, " ", 0);
3235 ret = execute_async(argv, working_directory);
3237 ret = execute_sync(argv, working_directory);
3244 gchar *get_command_output(const gchar *cmdline)
3246 gchar *child_stdout;
3249 cm_return_val_if_fail(cmdline != NULL, NULL);
3251 debug_print("get_command_output(): executing: %s\n", cmdline);
3253 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3255 g_warning("couldn't execute command: %s", cmdline);
3259 return child_stdout;
3262 static gint is_unchanged_uri_char(char c)
3273 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3279 for(i = 0; i < strlen(uri) ; i++) {
3280 if (is_unchanged_uri_char(uri[i])) {
3281 if (k + 2 >= bufsize)
3283 encoded_uri[k++] = uri[i];
3286 char * hexa = "0123456789ABCDEF";
3288 if (k + 4 >= bufsize)
3290 encoded_uri[k++] = '%';
3291 encoded_uri[k++] = hexa[uri[i] / 16];
3292 encoded_uri[k++] = hexa[uri[i] % 16];
3298 gint open_uri(const gchar *uri, const gchar *cmdline)
3302 gchar buf[BUFFSIZE];
3304 gchar encoded_uri[BUFFSIZE];
3305 cm_return_val_if_fail(uri != NULL, -1);
3307 /* an option to choose whether to use encode_uri or not ? */
3308 encode_uri(encoded_uri, BUFFSIZE, uri);
3311 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3312 !strchr(p + 2, '%'))
3313 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3316 g_warning("Open URI command-line is invalid "
3317 "(there must be only one '%%s'): %s",
3319 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3322 execute_command_line(buf, TRUE, NULL);
3324 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3329 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3331 gchar buf[BUFFSIZE];
3334 cm_return_val_if_fail(filepath != NULL, -1);
3337 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3338 !strchr(p + 2, '%'))
3339 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3342 g_warning("Open Text Editor command-line is invalid "
3343 "(there must be only one '%%s'): %s",
3345 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3348 execute_command_line(buf, TRUE, NULL);
3353 time_t remote_tzoffset_sec(const gchar *zone)
3355 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3361 time_t remoteoffset;
3363 strncpy(zone3, zone, 3);
3367 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3368 (c == '+' || c == '-')) {
3369 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3371 remoteoffset = -remoteoffset;
3372 } else if (!strncmp(zone, "UT" , 2) ||
3373 !strncmp(zone, "GMT", 3)) {
3375 } else if (strlen(zone3) == 3) {
3376 for (p = ustzstr; *p != '\0'; p += 3) {
3377 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3378 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3379 remoteoffset = iustz * 3600;
3385 } else if (strlen(zone3) == 1) {
3387 case 'Z': remoteoffset = 0; break;
3388 case 'A': remoteoffset = -1; break;
3389 case 'B': remoteoffset = -2; break;
3390 case 'C': remoteoffset = -3; break;
3391 case 'D': remoteoffset = -4; break;
3392 case 'E': remoteoffset = -5; break;
3393 case 'F': remoteoffset = -6; break;
3394 case 'G': remoteoffset = -7; break;
3395 case 'H': remoteoffset = -8; break;
3396 case 'I': remoteoffset = -9; break;
3397 case 'K': remoteoffset = -10; break; /* J is not used */
3398 case 'L': remoteoffset = -11; break;
3399 case 'M': remoteoffset = -12; break;
3400 case 'N': remoteoffset = 1; break;
3401 case 'O': remoteoffset = 2; break;
3402 case 'P': remoteoffset = 3; break;
3403 case 'Q': remoteoffset = 4; break;
3404 case 'R': remoteoffset = 5; break;
3405 case 'S': remoteoffset = 6; break;
3406 case 'T': remoteoffset = 7; break;
3407 case 'U': remoteoffset = 8; break;
3408 case 'V': remoteoffset = 9; break;
3409 case 'W': remoteoffset = 10; break;
3410 case 'X': remoteoffset = 11; break;
3411 case 'Y': remoteoffset = 12; break;
3412 default: remoteoffset = 0; break;
3414 remoteoffset = remoteoffset * 3600;
3418 return remoteoffset;
3421 time_t tzoffset_sec(time_t *now)
3425 struct tm buf1, buf2;
3427 if (now && *now < 0)
3430 gmt = *gmtime_r(now, &buf1);
3431 lt = localtime_r(now, &buf2);
3433 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3435 if (lt->tm_year < gmt.tm_year)
3437 else if (lt->tm_year > gmt.tm_year)
3439 else if (lt->tm_yday < gmt.tm_yday)
3441 else if (lt->tm_yday > gmt.tm_yday)
3444 if (off >= 24 * 60) /* should be impossible */
3445 off = 23 * 60 + 59; /* if not, insert silly value */
3446 if (off <= -24 * 60)
3447 off = -(23 * 60 + 59);
3452 /* calculate timezone offset */
3453 gchar *tzoffset(time_t *now)
3455 static gchar offset_string[6];
3459 struct tm buf1, buf2;
3461 if (now && *now < 0)
3464 gmt = *gmtime_r(now, &buf1);
3465 lt = localtime_r(now, &buf2);
3467 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3469 if (lt->tm_year < gmt.tm_year)
3471 else if (lt->tm_year > gmt.tm_year)
3473 else if (lt->tm_yday < gmt.tm_yday)
3475 else if (lt->tm_yday > gmt.tm_yday)
3483 if (off >= 24 * 60) /* should be impossible */
3484 off = 23 * 60 + 59; /* if not, insert silly value */
3486 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3488 return offset_string;
3491 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
3495 gchar day[4], mon[4];
3496 gint dd, hh, mm, ss, yyyy;
3498 gchar buf2[RFC822_DATE_BUFFSIZE];
3502 lt = gmtime_r(&t, &buf1);
3504 lt = localtime_r(&t, &buf1);
3506 if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
3507 day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
3508 g_warning("failed reading date/time");
3510 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3511 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
3514 void get_rfc822_date(gchar *buf, gint len)
3516 _get_rfc822_date(buf, len, FALSE);
3519 void get_rfc822_date_hide_tz(gchar *buf, gint len)
3521 _get_rfc822_date(buf, len, TRUE);
3524 void debug_set_mode(gboolean mode)
3529 gboolean debug_get_mode(void)
3534 void debug_print_real(const gchar *format, ...)
3537 gchar buf[BUFFSIZE];
3539 if (!debug_mode) return;
3541 va_start(args, format);
3542 g_vsnprintf(buf, sizeof(buf), format, args);
3549 const char * debug_srcname(const char *file)
3551 const char *s = strrchr (file, '/');
3556 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3558 if (subject == NULL)
3561 subject += subject_get_prefix_length(subject);
3563 return g_hash_table_lookup(subject_table, subject);
3566 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3569 if (subject == NULL || *subject == 0)
3571 subject += subject_get_prefix_length(subject);
3572 g_hash_table_insert(subject_table, subject, data);
3575 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3577 if (subject == NULL)
3580 subject += subject_get_prefix_length(subject);
3581 g_hash_table_remove(subject_table, subject);
3584 static regex_t u_regex;
3585 static gboolean u_init_;
3587 void utils_free_regex(void)
3596 *\brief Check if a string is prefixed with known (combinations)
3597 * of prefixes. The function assumes that each prefix
3598 * is terminated by zero or exactly _one_ space.
3600 *\param str String to check for a prefixes
3602 *\return int Number of chars in the prefix that should be skipped
3603 * for a "clean" subject line. If no prefix was found, 0
3606 int subject_get_prefix_length(const gchar *subject)
3608 /*!< Array with allowable reply prefixes regexps. */
3609 static const gchar * const prefixes[] = {
3610 "Re\\:", /* "Re:" */
3611 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3612 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3613 "Aw\\:", /* "Aw:" (German) */
3614 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3615 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3616 "Fw\\:", /* "Fw:" Forward */
3617 "Fwd\\:", /* "Fwd:" Forward */
3618 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3619 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3620 "Rif\\:", /* "Rif:" (Italian Outlook) */
3621 "Sv\\:", /* "Sv" (Norwegian) */
3622 "Vs\\:", /* "Vs" (Norwegian) */
3623 "Ad\\:", /* "Ad" (Norwegian) */
3624 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3625 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3626 "Re \\:", /* "Re :" (French Yahoo Mail) */
3629 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3633 if (!subject) return 0;
3634 if (!*subject) return 0;
3637 GString *s = g_string_new("");
3639 for (n = 0; n < PREFIXES; n++)
3640 /* Terminate each prefix regexpression by a
3641 * "\ ?" (zero or ONE space), and OR them */
3642 g_string_append_printf(s, "(%s\\ ?)%s",
3647 g_string_prepend(s, "(");
3648 g_string_append(s, ")+"); /* match at least once */
3649 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3652 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3653 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3654 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3655 debug_print("Error compiling regexp %s\n", s->str);
3656 g_string_free(s, TRUE);
3660 g_string_free(s, TRUE);
3664 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3670 static guint g_stricase_hash(gconstpointer gptr)
3672 guint hash_result = 0;
3675 for (str = gptr; str && *str; str++) {
3676 hash_result += toupper(*str);
3682 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3684 const char *str1 = gptr1;
3685 const char *str2 = gptr2;
3687 return !strcasecmp(str1, str2);
3690 gint g_int_compare(gconstpointer a, gconstpointer b)
3692 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3696 quote_cmd_argument()
3698 return a quoted string safely usable in argument of a command.
3700 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3703 gint quote_cmd_argument(gchar * result, guint size,
3713 for(p = path ; * p != '\0' ; p ++) {
3715 if (isalnum((guchar)*p) || (* p == '/')) {
3716 if (remaining > 0) {
3722 result[size - 1] = '\0';
3727 if (remaining >= 2) {
3735 result[size - 1] = '\0';
3740 if (remaining > 0) {
3744 result[size - 1] = '\0';
3758 static void g_node_map_recursive(GNode *node, gpointer data)
3760 GNodeMapData *mapdata = (GNodeMapData *) data;
3762 GNodeMapData newmapdata;
3765 newdata = mapdata->func(node->data, mapdata->data);
3766 if (newdata != NULL) {
3767 newnode = g_node_new(newdata);
3768 g_node_append(mapdata->parent, newnode);
3770 newmapdata.parent = newnode;
3771 newmapdata.func = mapdata->func;
3772 newmapdata.data = mapdata->data;
3774 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3778 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3781 GNodeMapData mapdata;
3783 cm_return_val_if_fail(node != NULL, NULL);
3784 cm_return_val_if_fail(func != NULL, NULL);
3786 root = g_node_new(func(node->data, data));
3788 mapdata.parent = root;
3789 mapdata.func = func;
3790 mapdata.data = data;
3792 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3797 #define HEX_TO_INT(val, hex) \
3801 if ('0' <= c && c <= '9') { \
3803 } else if ('a' <= c && c <= 'f') { \
3804 val = c - 'a' + 10; \
3805 } else if ('A' <= c && c <= 'F') { \
3806 val = c - 'A' + 10; \
3812 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3819 if (hi == -1 || lo == -1)
3822 *out = (hi << 4) + lo;
3826 #define INT_TO_HEX(hex, val) \
3829 hex = '0' + (val); \
3831 hex = 'A' + (val) - 10; \
3834 void get_hex_str(gchar *out, guchar ch)
3838 INT_TO_HEX(hex, ch >> 4);
3840 INT_TO_HEX(hex, ch & 0x0f);
3846 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3848 #define G_PRINT_REF g_print
3852 *\brief Register ref counted pointer. It is based on GBoxed, so should
3853 * work with anything that uses the GType system. The semantics
3854 * are similar to a C++ auto pointer, with the exception that
3855 * C doesn't have automatic closure (calling destructors) when
3856 * exiting a block scope.
3857 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3858 * function directly.
3860 *\return GType A GType type.
3862 GType g_auto_pointer_register(void)
3864 static GType auto_pointer_type;
3865 if (!auto_pointer_type)
3867 g_boxed_type_register_static
3868 ("G_TYPE_AUTO_POINTER",
3869 (GBoxedCopyFunc) g_auto_pointer_copy,
3870 (GBoxedFreeFunc) g_auto_pointer_free);
3871 return auto_pointer_type;
3875 *\brief Structure with g_new() allocated pointer guarded by the
3878 typedef struct AutoPointerRef {
3879 void (*free) (gpointer);
3885 *\brief The auto pointer opaque structure that references the
3886 * pointer guard block.
3888 typedef struct AutoPointer {
3889 AutoPointerRef *ref;
3890 gpointer ptr; /*!< access to protected pointer */
3894 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3898 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3899 * ... when assigning, copying and freeing storage elements
3901 * gtk_list_store_new(N_S_COLUMNS,
3902 * G_TYPE_AUTO_POINTER,
3906 * Template *precious_data = g_new0(Template, 1);
3907 * g_pointer protect = g_auto_pointer_new(precious_data);
3909 * gtk_list_store_set(container, &iter,
3913 * ... the gtk_list_store has copied the pointer and
3914 * ... incremented its reference count, we should free
3915 * ... the auto pointer (in C++ a destructor would do
3916 * ... this for us when leaving block scope)
3918 * g_auto_pointer_free(protect);
3920 * ... gtk_list_store_set() now manages the data. When
3921 * ... *explicitly* requesting a pointer from the list
3922 * ... store, don't forget you get a copy that should be
3923 * ... freed with g_auto_pointer_free() eventually.
3927 *\param pointer Pointer to be guarded.
3929 *\return GAuto * Pointer that should be used in containers with
3932 GAuto *g_auto_pointer_new(gpointer p)
3934 AutoPointerRef *ref;
3940 ref = g_new0(AutoPointerRef, 1);
3941 ptr = g_new0(AutoPointer, 1);
3951 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3957 *\brief Allocate an autopointer using the passed \a free function to
3958 * free the guarded pointer
3960 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3967 aptr = g_auto_pointer_new(p);
3968 aptr->ref->free = free_;
3972 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3974 if (auto_ptr == NULL)
3976 return ((AutoPointer *) auto_ptr)->ptr;
3980 *\brief Copies an auto pointer by. It's mostly not necessary
3981 * to call this function directly, unless you copy/assign
3982 * the guarded pointer.
3984 *\param auto_ptr Auto pointer returned by previous call to
3985 * g_auto_pointer_new_XXX()
3987 *\return gpointer An auto pointer
3989 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3992 AutoPointerRef *ref;
3995 if (auto_ptr == NULL)
4000 newp = g_new0(AutoPointer, 1);
4003 newp->ptr = ref->pointer;
4007 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4013 *\brief Free an auto pointer
4015 void g_auto_pointer_free(GAuto *auto_ptr)
4018 AutoPointerRef *ref;
4020 if (auto_ptr == NULL)
4026 if (--(ref->cnt) == 0) {
4028 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4030 ref->free(ref->pointer);
4035 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4040 void replace_returns(gchar *str)
4045 while (strstr(str, "\n")) {
4046 *strstr(str, "\n") = ' ';
4048 while (strstr(str, "\r")) {
4049 *strstr(str, "\r") = ' ';
4053 /* get_uri_part() - retrieves a URI starting from scanpos.
4054 Returns TRUE if successful */
4055 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
4056 const gchar **bp, const gchar **ep, gboolean hdr)
4059 gint parenthese_cnt = 0;
4061 cm_return_val_if_fail(start != NULL, FALSE);
4062 cm_return_val_if_fail(scanpos != NULL, FALSE);
4063 cm_return_val_if_fail(bp != NULL, FALSE);
4064 cm_return_val_if_fail(ep != NULL, FALSE);
4068 /* find end point of URI */
4069 for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
4070 if (!g_ascii_isgraph(*(const guchar *)ep_) ||
4071 !IS_ASCII(*(const guchar *)ep_) ||
4072 strchr("[]{}<>\"", *ep_)) {
4074 } else if (strchr("(", *ep_)) {
4076 } else if (strchr(")", *ep_)) {
4077 if (parenthese_cnt > 0)
4084 /* no punctuation at end of string */
4086 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
4087 * should pass some URI type to this function and decide on that whether
4088 * to perform punctuation stripping */
4090 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
4092 for (; ep_ - 1 > scanpos + 1 &&
4093 IS_REAL_PUNCT(*(ep_ - 1));
4097 #undef IS_REAL_PUNCT
4104 gchar *make_uri_string(const gchar *bp, const gchar *ep)
4106 while (bp && *bp && g_ascii_isspace(*bp))
4108 return g_strndup(bp, ep - bp);
4111 /* valid mail address characters */
4112 #define IS_RFC822_CHAR(ch) \
4116 !g_ascii_isspace(ch) && \
4117 !strchr("(),;<>\"", (ch)))
4119 /* alphabet and number within 7bit ASCII */
4120 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
4121 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
4123 static GHashTable *create_domain_tab(void)
4126 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
4128 cm_return_val_if_fail(htab, NULL);
4129 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
4130 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
4134 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
4136 const gint MAX_LVL_DOM_NAME_LEN = 6;
4137 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
4138 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
4141 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
4144 for (p = buf; p < m && first < last; *p++ = *first++)
4148 return g_hash_table_lookup(tab, buf) != NULL;
4151 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
4152 gboolean get_email_part(const gchar *start, const gchar *scanpos,
4153 const gchar **bp, const gchar **ep, gboolean hdr)
4155 /* more complex than the uri part because we need to scan back and forward starting from
4156 * the scan position. */
4157 gboolean result = FALSE;
4158 const gchar *bp_ = NULL;
4159 const gchar *ep_ = NULL;
4160 static GHashTable *dom_tab;
4161 const gchar *last_dot = NULL;
4162 const gchar *prelast_dot = NULL;
4163 const gchar *last_tld_char = NULL;
4165 /* the informative part of the email address (describing the name
4166 * of the email address owner) may contain quoted parts. the
4167 * closure stack stores the last encountered quotes. */
4168 gchar closure_stack[128];
4169 gchar *ptr = closure_stack;
4171 cm_return_val_if_fail(start != NULL, FALSE);
4172 cm_return_val_if_fail(scanpos != NULL, FALSE);
4173 cm_return_val_if_fail(bp != NULL, FALSE);
4174 cm_return_val_if_fail(ep != NULL, FALSE);
4177 const gchar *start_quote = NULL;
4178 const gchar *end_quote = NULL;
4180 /* go to the real start */
4181 if (start[0] == ',')
4183 if (start[0] == ';')
4185 while (start[0] == '\n' || start[0] == '\r')
4187 while (start[0] == ' ' || start[0] == '\t')
4192 /* check if there are quotes (to skip , in them) */
4193 if (*start == '"') {
4194 start_quote = start;
4196 end_quote = strstr(start, "\"");
4202 /* skip anything between quotes */
4203 if (start_quote && end_quote) {
4208 /* find end (either , or ; or end of line) */
4209 if (strstr(start, ",") && strstr(start, ";"))
4210 *ep = strstr(start,",") < strstr(start, ";")
4211 ? strstr(start, ",") : strstr(start, ";");
4212 else if (strstr(start, ","))
4213 *ep = strstr(start, ",");
4214 else if (strstr(start, ";"))
4215 *ep = strstr(start, ";");
4217 *ep = start+strlen(start);
4219 /* go back to real start */
4220 if (start_quote && end_quote) {
4221 start = start_quote;
4224 /* check there's still an @ in that, or search
4225 * further if possible */
4226 if (strstr(start, "@") && strstr(start, "@") < *ep)
4228 else if (*ep < start+strlen(start)) {
4231 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
4239 dom_tab = create_domain_tab();
4240 cm_return_val_if_fail(dom_tab, FALSE);
4242 /* scan start of address */
4243 for (bp_ = scanpos - 1;
4244 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
4247 /* TODO: should start with an alnum? */
4249 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
4252 if (bp_ != scanpos) {
4253 /* scan end of address */
4254 for (ep_ = scanpos + 1;
4255 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
4257 prelast_dot = last_dot;
4259 if (*(last_dot + 1) == '.') {
4260 if (prelast_dot == NULL)
4262 last_dot = prelast_dot;
4267 /* TODO: really should terminate with an alnum? */
4268 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
4273 if (last_dot == NULL)
4275 if (last_dot >= ep_)
4276 last_dot = prelast_dot;
4277 if (last_dot == NULL || (scanpos + 1 >= last_dot))
4281 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
4282 if (*last_tld_char == '?')
4285 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
4292 if (!result) return FALSE;
4294 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
4295 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
4296 && IS_RFC822_CHAR(*(ep_ + 3))) {
4297 /* this informative part with an @ in it is
4298 * followed by the email address */
4301 /* go to matching '>' (or next non-rfc822 char, like \n) */
4302 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
4305 /* include the bracket */
4306 if (*ep_ == '>') ep_++;
4308 /* include the leading quote */
4316 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
4317 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
4320 /* see if this is <bracketed>; in this case we also scan for the informative part. */
4321 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
4324 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
4325 #define IN_STACK() (ptr > closure_stack)
4326 /* has underrun check */
4327 #define POP_STACK() if(IN_STACK()) --ptr
4328 /* has overrun check */
4329 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
4330 /* has underrun check */
4331 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
4335 /* scan for the informative part. */
4336 for (bp_ -= 2; bp_ >= start; bp_--) {
4337 /* if closure on the stack keep scanning */
4338 if (PEEK_STACK() == *bp_) {
4342 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
4347 /* if nothing in the closure stack, do the special conditions
4348 * the following if..else expression simply checks whether
4349 * a token is acceptable. if not acceptable, the clause
4350 * should terminate the loop with a 'break' */
4351 if (!PEEK_STACK()) {
4353 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
4354 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
4355 /* hyphens are allowed, but only in
4357 } else if (strchr(" \"'", *bp_)) {
4358 /* but anything not being a punctiation
4361 break; /* anything else is rejected */
4368 /* scan forward (should start with an alnum) */
4369 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
4385 #undef IS_ASCII_ALNUM
4386 #undef IS_RFC822_CHAR
4388 gchar *make_email_string(const gchar *bp, const gchar *ep)
4390 /* returns a mailto: URI; mailto: is also used to detect the
4391 * uri type later on in the button_pressed signal handler */
4396 tmp = g_strndup(bp, ep - bp);
4398 /* If there is a colon in the username part of the address,
4399 * we're dealing with an URI for some other protocol - do
4400 * not prefix with mailto: in such case. */
4401 colon = strchr(tmp, ':');
4402 at = strchr(tmp, '@');
4403 if (colon != NULL && at != NULL && colon < at) {
4406 result = g_strconcat("mailto:", tmp, NULL);
4413 gchar *make_http_string(const gchar *bp, const gchar *ep)
4415 /* returns an http: URI; */
4419 while (bp && *bp && g_ascii_isspace(*bp))
4421 tmp = g_strndup(bp, ep - bp);
4422 result = g_strconcat("http://", tmp, NULL);
4428 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
4430 FILE *fp = g_fopen(path, "rb");
4431 gchar buf[BUFFSIZE];
4432 gchar *result = NULL;
4435 while (fgets(buf, sizeof (buf), fp) != NULL) {
4436 gchar **parts = g_strsplit(buf, ";", 3);
4437 gchar *trimmed = parts[0];
4438 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4440 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4441 trimmed[strlen(trimmed)-1] = '\0';
4443 if (!strcmp(trimmed, type)) {
4444 gboolean needsterminal = FALSE;
4445 if (parts[2] && strstr(parts[2], "needsterminal")) {
4446 needsterminal = TRUE;
4448 if (parts[2] && strstr(parts[2], "test=")) {
4449 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
4450 gchar *testcmd = orig_testcmd;
4451 if (strstr(testcmd,";"))
4452 *(strstr(testcmd,";")) = '\0';
4453 while (testcmd[0] == ' ' || testcmd[0] == '\t')
4455 while (testcmd[strlen(testcmd)-1] == '\n')
4456 testcmd[strlen(testcmd)-1] = '\0';
4457 while (testcmd[strlen(testcmd)-1] == '\r')
4458 testcmd[strlen(testcmd)-1] = '\0';
4459 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
4460 testcmd[strlen(testcmd)-1] = '\0';
4462 if (strstr(testcmd, "%s")) {
4463 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
4464 gint res = system(tmp);
4466 g_free(orig_testcmd);
4473 gint res = system(testcmd);
4474 g_free(orig_testcmd);
4484 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4486 while (trimmed[strlen(trimmed)-1] == '\n')
4487 trimmed[strlen(trimmed)-1] = '\0';
4488 while (trimmed[strlen(trimmed)-1] == '\r')
4489 trimmed[strlen(trimmed)-1] = '\0';
4490 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4491 trimmed[strlen(trimmed)-1] = '\0';
4492 result = g_strdup(trimmed);
4495 if (needsterminal) {
4496 gchar *tmp = g_strdup_printf("xterm -e %s", result);
4507 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
4509 gchar *result = NULL;
4513 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4514 result = mailcap_get_command_in_file(path, type, file_to_open);
4518 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
4522 void mailcap_update_default(const gchar *type, const gchar *command)
4524 gchar *path = NULL, *outpath = NULL;
4525 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4526 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
4527 FILE *fp = g_fopen(path, "rb");
4529 gchar buf[BUFFSIZE];
4530 gboolean err = FALSE;
4533 fp = g_fopen(path, "a");
4535 g_warning("failed to create file %s", path);
4540 fp = g_freopen(path, "rb", fp);
4542 g_warning("failed to reopen file %s", path);
4549 outfp = g_fopen(outpath, "wb");
4551 g_warning("failed to create file %s", outpath);
4557 while (fp && fgets(buf, sizeof (buf), fp) != NULL) {
4558 gchar **parts = g_strsplit(buf, ";", 3);
4559 gchar *trimmed = parts[0];
4560 while (trimmed[0] == ' ')
4562 while (trimmed[strlen(trimmed)-1] == ' ')
4563 trimmed[strlen(trimmed)-1] = '\0';
4565 if (!strcmp(trimmed, type)) {
4570 if(fputs(buf, outfp) == EOF) {
4577 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4583 if (fclose(outfp) == EOF)
4587 g_rename(outpath, path);
4593 gint copy_dir(const gchar *src, const gchar *dst)
4598 if ((dir = g_dir_open(src, 0, NULL)) == NULL) {
4599 g_warning("failed to open directory: %s", src);
4603 if (make_dir(dst) < 0)
4606 while ((name = g_dir_read_name(dir)) != NULL) {
4607 gchar *old_file, *new_file;
4608 old_file = g_strconcat(src, G_DIR_SEPARATOR_S, name, NULL);
4609 new_file = g_strconcat(dst, G_DIR_SEPARATOR_S, name, NULL);
4610 debug_print("copying: %s -> %s\n", old_file, new_file);
4611 if (g_file_test(old_file, G_FILE_TEST_IS_REGULAR)) {
4612 gint r = copy_file(old_file, new_file, TRUE);
4619 /* Windows has no symlinks. Or well, Vista seems to
4620 have something like this but the semantics might be
4621 different. Thus we don't use it under Windows. */
4622 else if (g_file_test(old_file, G_FILE_TEST_IS_SYMLINK)) {
4623 GError *error = NULL;
4625 gchar *target = g_file_read_link(old_file, &error);
4627 r = symlink(target, new_file);
4634 #endif /*G_OS_WIN32*/
4635 else if (g_file_test(old_file, G_FILE_TEST_IS_DIR)) {
4636 gint r = copy_dir(old_file, new_file);
4647 /* crude test to see if a file is an email. */
4648 gboolean file_is_email (const gchar *filename)
4654 if (filename == NULL)
4656 if ((fp = g_fopen(filename, "rb")) == NULL)
4658 while (i < 60 && score < 3
4659 && fgets(buffer, sizeof (buffer), fp) != NULL) {
4660 if (!strncmp(buffer, "From:", strlen("From:")))
4662 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4664 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4666 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4671 return (score >= 3);
4674 gboolean sc_g_list_bigger(GList *list, gint max)
4678 while (cur && i <= max+1) {
4685 gboolean sc_g_slist_bigger(GSList *list, gint max)
4689 while (cur && i <= max+1) {
4696 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4697 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4698 NULL, NULL, NULL, NULL, NULL, NULL};
4699 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4700 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4701 NULL, NULL, NULL, NULL, NULL, NULL};
4703 gint daynames_len[] = {0,0,0,0,0,0,0};
4704 gint monthnames_len[] = {0,0,0,0,0,0,
4706 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4707 gint s_monthnames_len[] = {0,0,0,0,0,0,
4709 const gchar *s_am_up = NULL;
4710 const gchar *s_pm_up = NULL;
4711 const gchar *s_am_low = NULL;
4712 const gchar *s_pm_low = NULL;
4714 gint s_am_up_len = 0;
4715 gint s_pm_up_len = 0;
4716 gint s_am_low_len = 0;
4717 gint s_pm_low_len = 0;
4719 static gboolean time_names_init_done = FALSE;
4721 static void init_time_names(void)
4725 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4726 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4727 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4728 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4729 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4730 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4731 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4733 monthnames[0] = C_("Complete month name for use by strftime", "January");
4734 monthnames[1] = C_("Complete month name for use by strftime", "February");
4735 monthnames[2] = C_("Complete month name for use by strftime", "March");
4736 monthnames[3] = C_("Complete month name for use by strftime", "April");
4737 monthnames[4] = C_("Complete month name for use by strftime", "May");
4738 monthnames[5] = C_("Complete month name for use by strftime", "June");
4739 monthnames[6] = C_("Complete month name for use by strftime", "July");
4740 monthnames[7] = C_("Complete month name for use by strftime", "August");
4741 monthnames[8] = C_("Complete month name for use by strftime", "September");
4742 monthnames[9] = C_("Complete month name for use by strftime", "October");
4743 monthnames[10] = C_("Complete month name for use by strftime", "November");
4744 monthnames[11] = C_("Complete month name for use by strftime", "December");
4746 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4747 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4748 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4749 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4750 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4751 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4752 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4754 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4755 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4756 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4757 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4758 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4759 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4760 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4761 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4762 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4763 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4764 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4765 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4767 for (i = 0; i < 7; i++) {
4768 daynames_len[i] = strlen(daynames[i]);
4769 s_daynames_len[i] = strlen(s_daynames[i]);
4771 for (i = 0; i < 12; i++) {
4772 monthnames_len[i] = strlen(monthnames[i]);
4773 s_monthnames_len[i] = strlen(s_monthnames[i]);
4776 s_am_up = C_("For use by strftime (morning)", "AM");
4777 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4778 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4779 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4781 s_am_up_len = strlen(s_am_up);
4782 s_pm_up_len = strlen(s_pm_up);
4783 s_am_low_len = strlen(s_am_low);
4784 s_pm_low_len = strlen(s_pm_low);
4786 time_names_init_done = TRUE;
4789 #define CHECK_SIZE() { \
4790 total_done += len; \
4791 if (total_done >= buflen) { \
4792 buf[buflen-1] = '\0'; \
4797 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4799 gchar *curpos = buf;
4800 gint total_done = 0;
4801 gchar subbuf[64], subfmt[64];
4802 static time_t last_tzset = (time_t)0;
4804 if (!time_names_init_done)
4807 if (format == NULL || lt == NULL)
4810 if (last_tzset != time(NULL)) {
4812 last_tzset = time(NULL);
4815 if (*format == '%') {
4816 gint len = 0, tmp = 0;
4820 len = 1; CHECK_SIZE();
4824 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4825 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4828 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4829 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4833 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4834 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4837 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4838 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4841 strftime(subbuf, 64, "%c", lt);
4842 len = strlen(subbuf); CHECK_SIZE();
4843 strncpy2(curpos, subbuf, buflen - total_done);
4846 total_done += 2; CHECK_SIZE();
4847 tmp = (lt->tm_year + 1900)/100;
4848 *curpos++ = '0'+(tmp / 10);
4849 *curpos++ = '0'+(tmp % 10);
4852 total_done += 2; CHECK_SIZE();
4853 *curpos++ = '0'+(lt->tm_mday / 10);
4854 *curpos++ = '0'+(lt->tm_mday % 10);
4857 total_done += 8; CHECK_SIZE();
4858 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4859 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4861 *curpos++ = '0'+(lt->tm_mday / 10);
4862 *curpos++ = '0'+(lt->tm_mday % 10);
4864 tmp = lt->tm_year%100;
4865 *curpos++ = '0'+(tmp / 10);
4866 *curpos++ = '0'+(tmp % 10);
4869 len = 2; CHECK_SIZE();
4870 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4873 len = 10; CHECK_SIZE();
4874 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4875 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4878 total_done += 2; CHECK_SIZE();
4879 *curpos++ = '0'+(lt->tm_hour / 10);
4880 *curpos++ = '0'+(lt->tm_hour % 10);
4883 total_done += 2; CHECK_SIZE();
4889 *curpos++ = '0'+(tmp / 10);
4890 *curpos++ = '0'+(tmp % 10);
4893 len = 3; CHECK_SIZE();
4894 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4897 len = 2; CHECK_SIZE();
4898 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4901 len = 2; CHECK_SIZE();
4907 snprintf(curpos, buflen - total_done, "%2d", tmp);
4910 total_done += 2; CHECK_SIZE();
4911 tmp = lt->tm_mon + 1;
4912 *curpos++ = '0'+(tmp / 10);
4913 *curpos++ = '0'+(tmp % 10);
4916 total_done += 2; CHECK_SIZE();
4917 *curpos++ = '0'+(lt->tm_min / 10);
4918 *curpos++ = '0'+(lt->tm_min % 10);
4921 len = 1; CHECK_SIZE();
4925 if (lt->tm_hour >= 12) {
4926 len = s_pm_up_len; CHECK_SIZE();
4927 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4929 len = s_am_up_len; CHECK_SIZE();
4930 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4934 if (lt->tm_hour >= 12) {
4935 len = s_pm_low_len; CHECK_SIZE();
4936 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4938 len = s_am_low_len; CHECK_SIZE();
4939 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4943 strftime(subbuf, 64, "%r", lt);
4944 len = strlen(subbuf); CHECK_SIZE();
4945 strncpy2(curpos, subbuf, buflen - total_done);
4948 total_done += 5; CHECK_SIZE();
4949 *curpos++ = '0'+(lt->tm_hour / 10);
4950 *curpos++ = '0'+(lt->tm_hour % 10);
4952 *curpos++ = '0'+(lt->tm_min / 10);
4953 *curpos++ = '0'+(lt->tm_min % 10);
4956 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
4957 len = strlen(subbuf); CHECK_SIZE();
4958 strncpy2(curpos, subbuf, buflen - total_done);
4961 total_done += 2; CHECK_SIZE();
4962 *curpos++ = '0'+(lt->tm_sec / 10);
4963 *curpos++ = '0'+(lt->tm_sec % 10);
4966 len = 1; CHECK_SIZE();
4970 total_done += 8; CHECK_SIZE();
4971 *curpos++ = '0'+(lt->tm_hour / 10);
4972 *curpos++ = '0'+(lt->tm_hour % 10);
4974 *curpos++ = '0'+(lt->tm_min / 10);
4975 *curpos++ = '0'+(lt->tm_min % 10);
4977 *curpos++ = '0'+(lt->tm_sec / 10);
4978 *curpos++ = '0'+(lt->tm_sec % 10);
4981 len = 1; CHECK_SIZE();
4982 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
4985 len = 1; CHECK_SIZE();
4986 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
4989 strftime(subbuf, 64, "%x", lt);
4990 len = strlen(subbuf); CHECK_SIZE();
4991 strncpy2(curpos, subbuf, buflen - total_done);
4994 strftime(subbuf, 64, "%X", lt);
4995 len = strlen(subbuf); CHECK_SIZE();
4996 strncpy2(curpos, subbuf, buflen - total_done);
4999 total_done += 2; CHECK_SIZE();
5000 tmp = lt->tm_year%100;
5001 *curpos++ = '0'+(tmp / 10);
5002 *curpos++ = '0'+(tmp % 10);
5005 len = 4; CHECK_SIZE();
5006 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
5016 /* let these complicated ones be done with the libc */
5017 snprintf(subfmt, 64, "%%%c", *format);
5018 strftime(subbuf, 64, subfmt, lt);
5019 len = strlen(subbuf); CHECK_SIZE();
5020 strncpy2(curpos, subbuf, buflen - total_done);
5024 /* let these complicated modifiers be done with the libc */
5025 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
5026 strftime(subbuf, 64, subfmt, lt);
5027 len = strlen(subbuf); CHECK_SIZE();
5028 strncpy2(curpos, subbuf, buflen - total_done);
5032 g_warning("format error (%c)", *format);
5039 int len = 1; CHECK_SIZE();
5040 *curpos++ = *format++;
5047 gboolean prefs_common_get_use_shred(void);
5051 #define WEXITSTATUS(x) (x)
5054 int claws_unlink(const gchar *filename)
5057 static int found_shred = -1;
5058 static const gchar *args[4];
5060 if (filename == NULL)
5063 if (prefs_common_get_use_shred()) {
5064 if (found_shred == -1) {
5066 args[0] = g_find_program_in_path("shred");
5067 debug_print("found shred: %s\n", args[0]);
5068 found_shred = (args[0] != NULL) ? 1:0;
5072 if (found_shred == 1) {
5073 if (g_stat(filename, &s) == 0 && S_ISREG(s.st_mode)) {
5074 if (s.st_nlink == 1) {
5077 g_spawn_sync(NULL, (gchar **)args, NULL, 0,
5078 NULL, NULL, NULL, NULL, &status, NULL);
5079 debug_print("%s %s exited with status %d\n",
5080 args[0], filename, WEXITSTATUS(status));
5081 if (truncate(filename, 0) < 0)
5082 g_warning("couln't truncate: %s", filename);
5087 return g_unlink(filename);
5090 GMutex *cm_mutex_new(void) {
5091 #if GLIB_CHECK_VERSION(2,32,0)
5092 GMutex *m = g_new0(GMutex, 1);
5096 return g_mutex_new();
5100 void cm_mutex_free(GMutex *mutex) {
5101 #if GLIB_CHECK_VERSION(2,32,0)
5102 g_mutex_clear(mutex);
5105 g_mutex_free(mutex);
5109 static gchar *canonical_list_to_file(GSList *list)
5111 GString *result = g_string_new(NULL);
5112 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
5117 result = g_string_append(result, G_DIR_SEPARATOR_S);
5119 if (pathlist->data) {
5120 const gchar *root = (gchar *)pathlist->data;
5121 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
5123 /* drive - don't prepend dir separator */
5125 result = g_string_append(result, G_DIR_SEPARATOR_S);
5130 for (cur = pathlist; cur; cur = cur->next) {
5131 result = g_string_append(result, (gchar *)cur->data);
5133 result = g_string_append(result, G_DIR_SEPARATOR_S);
5135 g_slist_free(pathlist);
5138 g_string_free(result, FALSE);
5143 static GSList *cm_split_path(const gchar *filename, int depth)
5146 GSList *canonical_parts = NULL;
5150 gboolean follow_symlinks = TRUE;
5157 errno = EINVAL; /* can't happen, no symlink handling */
5162 if (!g_path_is_absolute(filename)) {
5167 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
5169 for (i = 0; path_parts[i] != NULL; i++) {
5170 if (!strcmp(path_parts[i], ""))
5172 if (!strcmp(path_parts[i], "."))
5174 else if (!strcmp(path_parts[i], "..")) {
5179 else /* Remove the last inserted element */
5181 g_slist_delete_link(canonical_parts,
5186 canonical_parts = g_slist_prepend(canonical_parts,
5187 g_strdup(path_parts[i]));
5189 tmp_path = canonical_list_to_file(canonical_parts);
5191 if(g_stat(tmp_path, &st) < 0) {
5192 if (errno == ENOENT) {
5195 follow_symlinks = FALSE;
5200 slist_free_strings_full(canonical_parts);
5201 g_strfreev(path_parts);
5207 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
5208 GError *error = NULL;
5209 gchar *target = g_file_read_link(tmp_path, &error);
5211 if (!g_path_is_absolute(target)) {
5212 /* remove the last inserted element */
5214 g_slist_delete_link(canonical_parts,
5216 /* add the target */
5217 canonical_parts = g_slist_prepend(canonical_parts,
5221 /* and get the new target */
5222 target = canonical_list_to_file(canonical_parts);
5225 /* restart from absolute target */
5226 slist_free_strings_full(canonical_parts);
5227 canonical_parts = NULL;
5229 canonical_parts = cm_split_path(target, depth + 1);
5231 g_error_free(error);
5232 if (canonical_parts == NULL) {
5234 g_strfreev(path_parts);
5243 g_strfreev(path_parts);
5244 return canonical_parts;
5248 * Canonicalize a filename, resolving symlinks along the way.
5249 * Returns a negative errno in case of error.
5251 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
5252 GSList *canonical_parts;
5253 gboolean is_absolute;
5255 if (filename == NULL)
5257 if (canonical_name == NULL)
5259 *canonical_name = NULL;
5261 is_absolute = g_path_is_absolute(filename);
5263 /* Always work on absolute filenames. */
5264 gchar *cur = g_get_current_dir();
5265 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
5268 canonical_parts = cm_split_path(absolute_filename, 0);
5269 g_free(absolute_filename);
5272 canonical_parts = cm_split_path(filename, 0);
5274 if (canonical_parts == NULL)
5277 *canonical_name = canonical_list_to_file(canonical_parts);
5278 slist_free_strings_full(canonical_parts);
5282 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
5283 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
5285 gchar *tmp = g_base64_decode(text, out_len);
5286 gchar *out = g_strndup(tmp, *out_len);
5290 if (strlen(out) != *out_len) {
5291 g_warning ("strlen(out) %zd != *out_len %" G_GSIZE_FORMAT, strlen(out), *out_len);
5297 #if !GLIB_CHECK_VERSION(2, 30, 0)
5300 * @str: a UTF-8 encoded string
5301 * @start_pos: a character offset within @str
5302 * @end_pos: another character offset within @str
5304 * Copies a substring out of a UTF-8 encoded string.
5305 * The substring will contain @end_pos - @start_pos
5308 * Returns: a newly allocated copy of the requested
5309 * substring. Free with g_free() when no longer needed.
5314 g_utf8_substring (const gchar *str,
5318 gchar *start, *end, *out;
5320 start = g_utf8_offset_to_pointer (str, start_pos);
5321 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
5323 out = g_malloc (end - start + 1);
5324 memcpy (out, start, end - start);
5325 out[end - start] = 0;
5331 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
5332 * It is up to the caller to make sure there is at least count bytes
5333 * available at buf. */
5335 get_random_bytes(void *buf, size_t count)
5337 /* Open our prng source. */
5338 #if defined G_OS_WIN32
5341 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
5342 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
5343 debug_print("Could not acquire a CSP handle.\n");
5350 rnd = open("/dev/urandom", O_RDONLY);
5352 FILE_OP_ERROR("/dev/urandom", "open");
5353 debug_print("Could not open /dev/urandom.\n");
5358 /* Read data from the source into buf. */
5359 #if defined G_OS_WIN32
5360 if (!CryptGenRandom(rnd, count, buf)) {
5361 debug_print("Could not read %zd random bytes.\n", count);
5362 CryptReleaseContext(rnd, 0);
5366 ret = read(rnd, buf, count);
5368 FILE_OP_ERROR("/dev/urandom", "read");
5369 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
5375 /* Close the prng source. */
5376 #if defined G_OS_WIN32
5377 CryptReleaseContext(rnd, 0);