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>
93 static gboolean debug_mode = FALSE;
95 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
97 #if GLIB_CHECK_VERSION(2, 34, 0)
98 return g_slist_copy_deep(list, func, NULL);
100 GSList *res = g_slist_copy(list);
103 walk->data = func(walk->data, NULL);
110 void list_free_strings_full(GList *list)
112 g_list_free_full(list, (GDestroyNotify)g_free);
115 void slist_free_strings_full(GSList *list)
117 g_slist_free_full(list, (GDestroyNotify)g_free);
120 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
125 void hash_free_strings(GHashTable *table)
127 g_hash_table_foreach(table, hash_free_strings_func, NULL);
130 gint str_case_equal(gconstpointer v, gconstpointer v2)
132 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
135 guint str_case_hash(gconstpointer key)
137 const gchar *p = key;
141 h = g_ascii_tolower(h);
142 for (p += 1; *p != '\0'; p++)
143 h = (h << 5) - h + g_ascii_tolower(*p);
149 gint to_number(const gchar *nstr)
151 register const gchar *p;
153 if (*nstr == '\0') return -1;
155 for (p = nstr; *p != '\0'; p++)
156 if (!g_ascii_isdigit(*p)) return -1;
161 /* convert integer into string,
162 nstr must be not lower than 11 characters length */
163 gchar *itos_buf(gchar *nstr, gint n)
165 g_snprintf(nstr, 11, "%d", n);
169 /* convert integer into string */
172 static gchar nstr[11];
174 return itos_buf(nstr, n);
177 #define divide(num,divisor,i,d) \
179 i = num >> divisor; \
180 d = num & ((1<<divisor)-1); \
181 d = (d*100) >> divisor; \
186 * \brief Convert a given size in bytes in a human-readable string
188 * \param size The size expressed in bytes to convert in string
189 * \return The string that respresents the size in an human-readable way
191 gchar *to_human_readable(goffset size)
193 static gchar str[14];
194 static gchar *b_format = NULL, *kb_format = NULL,
195 *mb_format = NULL, *gb_format = NULL;
196 register int t = 0, r = 0;
197 if (b_format == NULL) {
199 kb_format = _("%d.%02dKB");
200 mb_format = _("%d.%02dMB");
201 gb_format = _("%.2fGB");
204 if (size < (goffset)1024) {
205 g_snprintf(str, sizeof(str), b_format, (gint)size);
207 } else if (size >> 10 < (goffset)1024) {
208 divide(size, 10, t, r);
209 g_snprintf(str, sizeof(str), kb_format, t, r);
211 } else if (size >> 20 < (goffset)1024) {
212 divide(size, 20, t, r);
213 g_snprintf(str, sizeof(str), mb_format, t, r);
216 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
221 /* strcmp with NULL-checking */
222 gint strcmp2(const gchar *s1, const gchar *s2)
224 if (s1 == NULL || s2 == NULL)
227 return strcmp(s1, s2);
229 /* strstr with NULL-checking */
230 gchar *strstr2(const gchar *s1, const gchar *s2)
232 if (s1 == NULL || s2 == NULL)
235 return strstr(s1, s2);
238 gint path_cmp(const gchar *s1, const gchar *s2)
243 gchar *s1buf, *s2buf;
246 if (s1 == NULL || s2 == NULL) return -1;
247 if (*s1 == '\0' || *s2 == '\0') return -1;
250 s1buf = g_strdup (s1);
251 s2buf = g_strdup (s2);
252 subst_char (s1buf, '/', G_DIR_SEPARATOR);
253 subst_char (s2buf, '/', G_DIR_SEPARATOR);
256 #endif /* !G_OS_WIN32 */
261 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
262 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
264 rc = strncmp(s1, s2, MAX(len1, len2));
268 #endif /* !G_OS_WIN32 */
272 /* remove trailing return code */
273 gchar *strretchomp(gchar *str)
277 if (!*str) return str;
279 for (s = str + strlen(str) - 1;
280 s >= str && (*s == '\n' || *s == '\r');
287 /* remove trailing character */
288 gchar *strtailchomp(gchar *str, gchar tail_char)
292 if (!*str) return str;
293 if (tail_char == '\0') return str;
295 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
301 /* remove CR (carriage return) */
302 gchar *strcrchomp(gchar *str)
306 if (!*str) return str;
308 s = str + strlen(str) - 1;
309 if (*s == '\n' && s > str && *(s - 1) == '\r') {
317 gint file_strip_crs(const gchar *file)
319 FILE *fp = NULL, *outfp = NULL;
321 gchar *out = get_tmp_file();
325 fp = g_fopen(file, "rb");
329 outfp = g_fopen(out, "wb");
335 while (fgets(buf, sizeof (buf), fp) != NULL) {
337 if (fputs(buf, outfp) == EOF) {
345 if (safe_fclose(outfp) == EOF) {
349 if (move_file(out, file, TRUE) < 0)
361 /* Similar to `strstr' but this function ignores the case of both strings. */
362 gchar *strcasestr(const gchar *haystack, const gchar *needle)
364 size_t haystack_len = strlen(haystack);
366 return strncasestr(haystack, haystack_len, needle);
369 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
371 register size_t needle_len;
373 needle_len = strlen(needle);
375 if (haystack_len < needle_len || needle_len == 0)
378 while (haystack_len >= needle_len) {
379 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
380 return (gchar *)haystack;
390 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
391 gconstpointer needle, size_t needlelen)
393 const gchar *haystack_ = (const gchar *)haystack;
394 const gchar *needle_ = (const gchar *)needle;
395 const gchar *haystack_cur = (const gchar *)haystack;
396 size_t haystack_left = haystacklen;
399 return memchr(haystack_, *needle_, haystacklen);
401 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
403 if (haystacklen - (haystack_cur - haystack_) < needlelen)
405 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
406 return (gpointer)haystack_cur;
409 haystack_left = haystacklen - (haystack_cur - haystack_);
416 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
417 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
419 register const gchar *s = src;
420 register gchar *d = dest;
430 /* Examine if next block is non-ASCII string */
431 gboolean is_next_nonascii(const gchar *s)
435 /* skip head space */
436 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
438 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
439 if (*(guchar *)p > 127 || *(guchar *)p < 32)
446 gint get_next_word_len(const gchar *s)
450 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
456 static void trim_subject_for_compare(gchar *str)
460 eliminate_parenthesis(str, '[', ']');
461 eliminate_parenthesis(str, '(', ')');
464 srcp = str + subject_get_prefix_length(str);
466 memmove(str, srcp, strlen(srcp) + 1);
469 static void trim_subject_for_sort(gchar *str)
475 srcp = str + subject_get_prefix_length(str);
477 memmove(str, srcp, strlen(srcp) + 1);
480 /* compare subjects */
481 gint subject_compare(const gchar *s1, const gchar *s2)
485 if (!s1 || !s2) return -1;
486 if (!*s1 || !*s2) return -1;
488 Xstrdup_a(str1, s1, return -1);
489 Xstrdup_a(str2, s2, return -1);
491 trim_subject_for_compare(str1);
492 trim_subject_for_compare(str2);
494 if (!*str1 || !*str2) return -1;
496 return strcmp(str1, str2);
499 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
503 if (!s1 || !s2) return -1;
505 Xstrdup_a(str1, s1, return -1);
506 Xstrdup_a(str2, s2, return -1);
508 trim_subject_for_sort(str1);
509 trim_subject_for_sort(str2);
511 return g_utf8_collate(str1, str2);
514 void trim_subject(gchar *str)
516 register gchar *srcp;
522 srcp = str + subject_get_prefix_length(str);
527 } else if (*srcp == '(') {
539 else if (*srcp == cl)
546 while (g_ascii_isspace(*srcp)) srcp++;
547 memmove(str, srcp, strlen(srcp) + 1);
550 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
552 register gchar *srcp, *destp;
557 while ((destp = strchr(destp, op))) {
563 else if (*srcp == cl)
569 while (g_ascii_isspace(*srcp)) srcp++;
570 memmove(destp, srcp, strlen(srcp) + 1);
574 void extract_parenthesis(gchar *str, gchar op, gchar cl)
576 register gchar *srcp, *destp;
581 while ((srcp = strchr(destp, op))) {
584 memmove(destp, srcp + 1, strlen(srcp));
589 else if (*destp == cl)
601 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
604 register gchar *srcp, *destp;
606 gboolean in_quote = FALSE;
610 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
613 memmove(destp, srcp + 1, strlen(srcp));
616 if (*destp == op && !in_quote)
618 else if (*destp == cl && !in_quote)
620 else if (*destp == quote_chr)
632 void extract_quote(gchar *str, gchar quote_chr)
636 if ((str = strchr(str, quote_chr))) {
638 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
639 memmove(p - 1, p, strlen(p) + 1);
644 memmove(str, str + 1, p - str);
649 /* Returns a newly allocated string with all quote_chr not at the beginning
650 or the end of str escaped with '\' or the given str if not required. */
651 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
653 register gchar *p, *q;
657 if (str == NULL || *str == '\0')
660 /* search for unescaped quote_chr */
665 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
669 if (!k) /* nothing to escape */
672 /* unescaped quote_chr found */
673 qstr = g_malloc(l + k + 1);
676 if (*p == quote_chr) {
681 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
690 void eliminate_address_comment(gchar *str)
692 register gchar *srcp, *destp;
697 while ((destp = strchr(destp, '"'))) {
698 if ((srcp = strchr(destp + 1, '"'))) {
703 while (g_ascii_isspace(*srcp)) srcp++;
704 memmove(destp, srcp, strlen(srcp) + 1);
714 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
720 else if (*srcp == ')')
726 while (g_ascii_isspace(*srcp)) srcp++;
727 memmove(destp, srcp, strlen(srcp) + 1);
731 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
733 gboolean in_quote = FALSE;
736 if (*str == c && !in_quote)
738 if (*str == quote_chr)
746 void extract_address(gchar *str)
748 cm_return_if_fail(str != NULL);
749 eliminate_address_comment(str);
750 if (strchr_with_skip_quote(str, '"', '<'))
751 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
755 void extract_list_id_str(gchar *str)
757 if (strchr_with_skip_quote(str, '"', '<'))
758 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
762 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
767 if (!str) return addr_list;
769 Xstrdup_a(work, str, return addr_list);
772 eliminate_address_comment(work);
775 while (workp && *workp) {
778 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
784 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
785 extract_parenthesis_with_skip_quote
786 (workp, '"', '<', '>');
790 addr_list = g_slist_append(addr_list, g_strdup(workp));
798 GSList *address_list_append(GSList *addr_list, const gchar *str)
800 return address_list_append_real(addr_list, str, TRUE);
803 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
805 return address_list_append_real(addr_list, str, FALSE);
808 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
812 if (!str) return msgid_list;
815 while (strp && *strp) {
816 const gchar *start, *end;
819 if ((start = strchr(strp, '<')) != NULL) {
820 end = strchr(start + 1, '>');
825 msgid = g_strndup(start + 1, end - start - 1);
828 msgid_list = g_slist_prepend(msgid_list, msgid);
838 GSList *references_list_append(GSList *msgid_list, const gchar *str)
842 list = references_list_prepend(NULL, str);
843 list = g_slist_reverse(list);
844 msgid_list = g_slist_concat(msgid_list, list);
849 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
854 if (!str) return group_list;
856 Xstrdup_a(work, str, return group_list);
860 while (workp && *workp) {
863 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
871 group_list = g_slist_append(group_list,
880 GList *add_history(GList *list, const gchar *str)
885 cm_return_val_if_fail(str != NULL, list);
887 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
890 list = g_list_remove(list, old->data);
892 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
895 last = g_list_last(list);
898 list = g_list_remove(list, last->data);
903 list = g_list_prepend(list, g_strdup(str));
908 void remove_return(gchar *str)
910 register gchar *p = str;
913 if (*p == '\n' || *p == '\r')
914 memmove(p, p + 1, strlen(p));
920 void remove_space(gchar *str)
922 register gchar *p = str;
927 while (g_ascii_isspace(*(p + spc)))
930 memmove(p, p + spc, strlen(p + spc) + 1);
936 void unfold_line(gchar *str)
942 ch = str; /* iterator for source string */
945 c = g_utf8_get_char_validated(ch, -1);
947 if (c == (gunichar)-1 || c == (gunichar)-2) {
948 /* non-unicode byte, move past it */
953 len = g_unichar_to_utf8(c, NULL);
955 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
956 g_unichar_isspace(c)) {
957 /* replace anything bad or whitespacey with a single space */
961 /* move rest of the string forwards, since we just replaced
962 * a multi-byte sequence with one byte */
963 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
966 /* A valid unicode character, copy it. */
972 void subst_char(gchar *str, gchar orig, gchar subst)
974 register gchar *p = str;
983 void subst_chars(gchar *str, gchar *orig, gchar subst)
985 register gchar *p = str;
988 if (strchr(orig, *p) != NULL)
994 void subst_for_filename(gchar *str)
999 subst_chars(str, "\t\r\n\\/*?:", '_');
1001 subst_chars(str, "\t\r\n\\/*", '_');
1005 void subst_for_shellsafe_filename(gchar *str)
1009 subst_for_filename(str);
1010 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1013 gboolean is_ascii_str(const gchar *str)
1015 const guchar *p = (const guchar *)str;
1017 while (*p != '\0') {
1018 if (*p != '\t' && *p != ' ' &&
1019 *p != '\r' && *p != '\n' &&
1020 (*p < 32 || *p >= 127))
1028 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1030 gchar * position = NULL;
1031 gchar * tmp_pos = NULL;
1034 if (str == NULL || quote_chars == NULL)
1037 for (i = 0; i < strlen(quote_chars); i++) {
1038 tmp_pos = strrchr (str, quote_chars[i]);
1040 || (tmp_pos != NULL && position <= tmp_pos) )
1046 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1048 const gchar *first_pos;
1049 const gchar *last_pos;
1050 const gchar *p = str;
1051 gint quote_level = -1;
1053 /* speed up line processing by only searching to the last '>' */
1054 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1055 /* skip a line if it contains a '<' before the initial '>' */
1056 if (memchr(str, '<', first_pos - str) != NULL)
1058 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1062 while (p <= last_pos) {
1063 while (p < last_pos) {
1064 if (g_ascii_isspace(*p))
1070 if (strchr(quote_chars, *p))
1072 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1073 /* any characters are allowed except '-','<' and space */
1074 while (*p != '-' && *p != '<'
1075 && !strchr(quote_chars, *p)
1076 && !g_ascii_isspace(*p)
1079 if (strchr(quote_chars, *p))
1091 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1093 const gchar *p = str, *q;
1094 gint cur_line = 0, len;
1096 while ((q = strchr(p, '\n')) != NULL) {
1098 if (len > max_chars) {
1108 if (len > max_chars) {
1117 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1119 gchar * position = NULL;
1120 gchar * tmp_pos = NULL;
1123 if (str == NULL || quote_chars == NULL)
1126 for (i = 0; i < strlen(quote_chars); i++) {
1127 tmp_pos = strchr (str, quote_chars[i]);
1129 || (tmp_pos != NULL && position >= tmp_pos) )
1135 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1137 register guint haystack_len, needle_len;
1138 gboolean in_squote = FALSE, in_dquote = FALSE;
1140 haystack_len = strlen(haystack);
1141 needle_len = strlen(needle);
1143 if (haystack_len < needle_len || needle_len == 0)
1146 while (haystack_len >= needle_len) {
1147 if (!in_squote && !in_dquote &&
1148 !strncmp(haystack, needle, needle_len))
1149 return (gchar *)haystack;
1151 /* 'foo"bar"' -> foo"bar"
1152 "foo'bar'" -> foo'bar' */
1153 if (*haystack == '\'') {
1156 else if (!in_dquote)
1158 } else if (*haystack == '\"') {
1161 else if (!in_squote)
1163 } else if (*haystack == '\\') {
1175 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1178 GSList *string_list = NULL, *slist;
1179 gchar **str_array, *s, *new_str;
1180 guint i, n = 1, len;
1182 cm_return_val_if_fail(str != NULL, NULL);
1183 cm_return_val_if_fail(delim != NULL, NULL);
1186 max_tokens = G_MAXINT;
1188 s = strstr_with_skip_quote(str, delim);
1190 guint delimiter_len = strlen(delim);
1194 new_str = g_strndup(str, len);
1196 if (new_str[0] == '\'' || new_str[0] == '\"') {
1197 if (new_str[len - 1] == new_str[0]) {
1198 new_str[len - 1] = '\0';
1199 memmove(new_str, new_str + 1, len - 1);
1202 string_list = g_slist_prepend(string_list, new_str);
1204 str = s + delimiter_len;
1205 s = strstr_with_skip_quote(str, delim);
1206 } while (--max_tokens && s);
1210 new_str = g_strdup(str);
1211 if (new_str[0] == '\'' || new_str[0] == '\"') {
1213 if (new_str[len - 1] == new_str[0]) {
1214 new_str[len - 1] = '\0';
1215 memmove(new_str, new_str + 1, len - 1);
1218 string_list = g_slist_prepend(string_list, new_str);
1222 str_array = g_new(gchar*, n);
1226 str_array[i--] = NULL;
1227 for (slist = string_list; slist; slist = slist->next)
1228 str_array[i--] = slist->data;
1230 g_slist_free(string_list);
1235 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1237 gchar *abbrev_group;
1239 const gchar *p = group;
1242 cm_return_val_if_fail(group != NULL, NULL);
1244 last = group + strlen(group);
1245 abbrev_group = ap = g_malloc(strlen(group) + 1);
1250 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1252 while (*p != '.') p++;
1255 return abbrev_group;
1260 return abbrev_group;
1263 gchar *trim_string(const gchar *str, gint len)
1265 const gchar *p = str;
1270 if (!str) return NULL;
1271 if (strlen(str) <= len)
1272 return g_strdup(str);
1273 if (g_utf8_validate(str, -1, NULL) == FALSE)
1274 return g_strdup(str);
1276 while (*p != '\0') {
1277 mb_len = g_utf8_skip[*(guchar *)p];
1280 else if (new_len + mb_len > len)
1287 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1288 return g_strconcat(new_str, "...", NULL);
1291 GList *uri_list_extract_filenames(const gchar *uri_list)
1293 GList *result = NULL;
1295 gchar *escaped_utf8uri;
1301 while (g_ascii_isspace(*p)) p++;
1302 if (!strncmp(p, "file:", 5)) {
1305 while (*q && *q != '\n' && *q != '\r') q++;
1308 gchar *file, *locale_file = NULL;
1310 while (q > p && g_ascii_isspace(*q))
1312 Xalloca(escaped_utf8uri, q - p + 2,
1314 Xalloca(file, q - p + 2,
1317 strncpy(escaped_utf8uri, p, q - p + 1);
1318 escaped_utf8uri[q - p + 1] = '\0';
1319 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1321 * g_filename_from_uri() rejects escaped/locale encoded uri
1322 * string which come from Nautilus.
1325 if (g_utf8_validate(file, -1, NULL))
1327 = conv_codeset_strdup(
1330 conv_get_locale_charset_str());
1332 locale_file = g_strdup(file + 5);
1334 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1336 result = g_list_append(result, locale_file);
1340 p = strchr(p, '\n');
1347 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1350 static gint axtoi(const gchar *hexstr)
1352 gint hi, lo, result;
1355 if ('0' <= hi && hi <= '9') {
1358 if ('a' <= hi && hi <= 'f') {
1361 if ('A' <= hi && hi <= 'F') {
1366 if ('0' <= lo && lo <= '9') {
1369 if ('a' <= lo && lo <= 'f') {
1372 if ('A' <= lo && lo <= 'F') {
1375 result = lo + (16 * hi);
1379 gboolean is_uri_string(const gchar *str)
1381 while (str && *str && g_ascii_isspace(*str))
1383 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1384 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1385 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1386 g_ascii_strncasecmp(str, "www.", 4) == 0);
1389 gchar *get_uri_path(const gchar *uri)
1391 while (uri && *uri && g_ascii_isspace(*uri))
1393 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1394 return (gchar *)(uri + 7);
1395 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1396 return (gchar *)(uri + 8);
1397 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1398 return (gchar *)(uri + 6);
1400 return (gchar *)uri;
1403 gint get_uri_len(const gchar *str)
1407 if (is_uri_string(str)) {
1408 for (p = str; *p != '\0'; p++) {
1409 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1418 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1419 * plusses, and escape characters are used)
1421 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1423 gchar *dec = decoded_uri;
1424 const gchar *enc = encoded_uri;
1429 if (isxdigit((guchar)enc[0]) &&
1430 isxdigit((guchar)enc[1])) {
1436 if (with_plus && *enc == '+')
1448 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1450 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1453 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1455 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1456 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1460 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1461 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1465 const gchar *forbidden_uris[] = { ".gnupg/",
1471 gint num_attach = 0;
1472 gchar **my_att = NULL;
1474 Xstrdup_a(tmp_mailto, mailto, return -1);
1476 if (!strncmp(tmp_mailto, "mailto:", 7))
1479 p = strchr(tmp_mailto, '?');
1486 *to = decode_uri_gdup(tmp_mailto);
1488 my_att = g_malloc(sizeof(char *));
1492 gchar *field, *value;
1509 if (*value == '\0') continue;
1511 if (from && !g_ascii_strcasecmp(field, "from")) {
1513 *from = decode_uri_gdup(value);
1515 gchar *tmp = decode_uri_gdup(value);
1516 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1520 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1522 *cc = decode_uri_gdup(value);
1524 gchar *tmp = decode_uri_gdup(value);
1525 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1529 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1531 *bcc = decode_uri_gdup(value);
1533 gchar *tmp = decode_uri_gdup(value);
1534 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1538 } else if (subject && !*subject &&
1539 !g_ascii_strcasecmp(field, "subject")) {
1540 *subject = decode_uri_gdup(value);
1541 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1542 *body = decode_uri_gdup(value);
1543 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1544 gchar *tmp = decode_uri_gdup(value);
1545 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1546 g_warning("couldn't set insert file '%s' in body", value);
1549 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1551 gchar *tmp = decode_uri_gdup(value);
1552 for (; forbidden_uris[i]; i++) {
1553 if (strstr(tmp, forbidden_uris[i])) {
1554 g_print("Refusing to attach '%s', potential private data leak\n",
1561 /* attach is correct */
1563 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1564 my_att[num_attach-1] = tmp;
1565 my_att[num_attach] = NULL;
1567 } else if (inreplyto && !*inreplyto &&
1568 !g_ascii_strcasecmp(field, "in-reply-to")) {
1569 *inreplyto = decode_uri_gdup(value);
1580 #include <windows.h>
1581 #ifndef CSIDL_APPDATA
1582 #define CSIDL_APPDATA 0x001a
1584 #ifndef CSIDL_LOCAL_APPDATA
1585 #define CSIDL_LOCAL_APPDATA 0x001c
1587 #ifndef CSIDL_FLAG_CREATE
1588 #define CSIDL_FLAG_CREATE 0x8000
1590 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1594 w32_strerror (int w32_errno)
1596 static char strerr[256];
1597 int ec = (int)GetLastError ();
1601 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1602 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1603 strerr, DIM (strerr)-1, NULL);
1607 static __inline__ void *
1608 dlopen (const char * name, int flag)
1610 void * hd = LoadLibrary (name);
1614 static __inline__ void *
1615 dlsym (void * hd, const char * sym)
1619 void * fnc = GetProcAddress (hd, sym);
1628 static __inline__ const char *
1631 return w32_strerror (0);
1635 static __inline__ int
1647 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1649 static int initialized;
1650 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1654 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1660 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1662 handle = dlopen (dllnames[i], RTLD_LAZY);
1665 func = dlsym (handle, "SHGetFolderPathW");
1676 return func (a,b,c,d,e);
1681 /* Returns a static string with the directroy from which the module
1682 has been loaded. Returns an empty string on error. */
1683 static char *w32_get_module_dir(void)
1685 static char *moddir;
1688 char name[MAX_PATH+10];
1691 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1694 p = strrchr (name, '\\');
1700 moddir = g_strdup (name);
1704 #endif /* G_OS_WIN32 */
1706 /* Return a static string with the locale dir. */
1707 const gchar *get_locale_dir(void)
1709 static gchar *loc_dir;
1713 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1714 "\\share\\locale", NULL);
1717 loc_dir = LOCALEDIR;
1723 const gchar *get_home_dir(void)
1726 static char home_dir_utf16[MAX_PATH] = "";
1727 static gchar *home_dir_utf8 = NULL;
1728 if (home_dir_utf16[0] == '\0') {
1729 if (w32_shgetfolderpath
1730 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1731 NULL, 0, home_dir_utf16) < 0)
1732 strcpy (home_dir_utf16, "C:\\Claws Mail");
1733 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1735 return home_dir_utf8;
1737 static const gchar *homeenv = NULL;
1742 if (!homeenv && g_getenv("HOME") != NULL)
1743 homeenv = g_strdup(g_getenv("HOME"));
1745 homeenv = g_get_home_dir();
1751 static gchar *claws_rc_dir = NULL;
1752 static gboolean rc_dir_alt = FALSE;
1753 const gchar *get_rc_dir(void)
1756 if (!claws_rc_dir) {
1757 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1759 debug_print("using default rc_dir %s\n", claws_rc_dir);
1761 return claws_rc_dir;
1764 void set_rc_dir(const gchar *dir)
1766 gchar *canonical_dir;
1767 if (claws_rc_dir != NULL) {
1768 g_print("Error: rc_dir already set\n");
1770 int err = cm_canonicalize_filename(dir, &canonical_dir);
1774 g_print("Error looking for %s: %d(%s)\n",
1775 dir, -err, g_strerror(-err));
1780 claws_rc_dir = canonical_dir;
1782 len = strlen(claws_rc_dir);
1783 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1784 claws_rc_dir[len - 1] = '\0';
1786 debug_print("set rc_dir to %s\n", claws_rc_dir);
1787 if (!is_dir_exist(claws_rc_dir)) {
1788 if (make_dir_hier(claws_rc_dir) != 0) {
1789 g_print("Error: can't create %s\n",
1797 gboolean rc_dir_is_alt(void) {
1801 const gchar *get_mail_base_dir(void)
1803 return get_home_dir();
1806 const gchar *get_news_cache_dir(void)
1808 static gchar *news_cache_dir = NULL;
1809 if (!news_cache_dir)
1810 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1811 NEWS_CACHE_DIR, NULL);
1813 return news_cache_dir;
1816 const gchar *get_imap_cache_dir(void)
1818 static gchar *imap_cache_dir = NULL;
1820 if (!imap_cache_dir)
1821 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1822 IMAP_CACHE_DIR, NULL);
1824 return imap_cache_dir;
1827 const gchar *get_mime_tmp_dir(void)
1829 static gchar *mime_tmp_dir = NULL;
1832 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1833 MIME_TMP_DIR, NULL);
1835 return mime_tmp_dir;
1838 const gchar *get_template_dir(void)
1840 static gchar *template_dir = NULL;
1843 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1844 TEMPLATE_DIR, NULL);
1846 return template_dir;
1850 const gchar *w32_get_cert_file(void)
1852 const gchar *cert_file = NULL;
1854 cert_file = g_strconcat(w32_get_module_dir(),
1855 "\\share\\claws-mail\\",
1856 "ca-certificates.crt",
1862 /* Return the filepath of the claws-mail.desktop file */
1863 const gchar *get_desktop_file(void)
1865 #ifdef DESKTOPFILEPATH
1866 return DESKTOPFILEPATH;
1872 /* Return the default directory for Plugins. */
1873 const gchar *get_plugin_dir(void)
1876 static gchar *plugin_dir = NULL;
1879 plugin_dir = g_strconcat(w32_get_module_dir(),
1880 "\\lib\\claws-mail\\plugins\\",
1884 if (is_dir_exist(PLUGINDIR))
1887 static gchar *plugin_dir = NULL;
1889 plugin_dir = g_strconcat(get_rc_dir(),
1890 G_DIR_SEPARATOR_S, "plugins",
1891 G_DIR_SEPARATOR_S, NULL);
1899 /* Return the default directory for Themes. */
1900 const gchar *w32_get_themes_dir(void)
1902 static gchar *themes_dir = NULL;
1905 themes_dir = g_strconcat(w32_get_module_dir(),
1906 "\\share\\claws-mail\\themes",
1912 const gchar *get_tmp_dir(void)
1914 static gchar *tmp_dir = NULL;
1917 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1923 gchar *get_tmp_file(void)
1926 static guint32 id = 0;
1928 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1929 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1934 const gchar *get_domain_name(void)
1937 static gchar *domain_name = NULL;
1938 struct addrinfo hints, *res;
1943 if (gethostname(hostname, sizeof(hostname)) != 0) {
1944 perror("gethostname");
1945 domain_name = "localhost";
1947 memset(&hints, 0, sizeof(struct addrinfo));
1948 hints.ai_family = AF_UNSPEC;
1949 hints.ai_socktype = 0;
1950 hints.ai_flags = AI_CANONNAME;
1951 hints.ai_protocol = 0;
1953 s = getaddrinfo(hostname, NULL, &hints, &res);
1955 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1956 domain_name = g_strdup(hostname);
1958 domain_name = g_strdup(res->ai_canonname);
1962 debug_print("domain name = %s\n", domain_name);
1971 off_t get_file_size(const gchar *file)
1976 GError *error = NULL;
1979 f = g_file_new_for_path(file);
1980 fi = g_file_query_info(f, "standard::size",
1981 G_FILE_QUERY_INFO_NONE, NULL, &error);
1982 if (error != NULL) {
1983 debug_print("get_file_size error: %s\n", error->message);
1984 g_error_free(error);
1988 size = g_file_info_get_size(fi);
1996 if (g_stat(file, &s) < 0) {
1997 FILE_OP_ERROR(file, "stat");
2005 time_t get_file_mtime(const gchar *file)
2009 if (g_stat(file, &s) < 0) {
2010 FILE_OP_ERROR(file, "stat");
2017 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2024 if (g_stat(file, &s) < 0) {
2025 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2029 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2036 /* Test on whether FILE is a relative file name. This is
2037 * straightforward for Unix but more complex for Windows. */
2038 gboolean is_relative_filename(const gchar *file)
2043 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2044 return FALSE; /* Prefixed with a hostname - this can't
2045 * be a relative name. */
2047 if ( ((*file >= 'a' && *file <= 'z')
2048 || (*file >= 'A' && *file <= 'Z'))
2050 file += 2; /* Skip drive letter. */
2052 return !(*file == '\\' || *file == '/');
2054 return !(*file == G_DIR_SEPARATOR);
2059 gboolean is_dir_exist(const gchar *dir)
2064 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2067 gboolean is_file_entry_exist(const gchar *file)
2072 return g_file_test(file, G_FILE_TEST_EXISTS);
2075 gboolean dirent_is_regular_file(struct dirent *d)
2077 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2078 if (d->d_type == DT_REG)
2080 else if (d->d_type != DT_UNKNOWN)
2084 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2087 gint change_dir(const gchar *dir)
2089 gchar *prevdir = NULL;
2092 prevdir = g_get_current_dir();
2094 if (g_chdir(dir) < 0) {
2095 FILE_OP_ERROR(dir, "chdir");
2096 if (debug_mode) g_free(prevdir);
2098 } else if (debug_mode) {
2101 cwd = g_get_current_dir();
2102 if (strcmp(prevdir, cwd) != 0)
2103 g_print("current dir: %s\n", cwd);
2111 gint make_dir(const gchar *dir)
2113 if (g_mkdir(dir, S_IRWXU) < 0) {
2114 FILE_OP_ERROR(dir, "mkdir");
2117 if (g_chmod(dir, S_IRWXU) < 0)
2118 FILE_OP_ERROR(dir, "chmod");
2123 gint make_dir_hier(const gchar *dir)
2128 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2129 parent_dir = g_strndup(dir, p - dir);
2130 if (*parent_dir != '\0') {
2131 if (!is_dir_exist(parent_dir)) {
2132 if (make_dir(parent_dir) < 0) {
2141 if (!is_dir_exist(dir)) {
2142 if (make_dir(dir) < 0)
2149 gint remove_all_files(const gchar *dir)
2152 const gchar *file_name;
2155 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2156 g_warning("failed to open directory: %s", dir);
2160 while ((file_name = g_dir_read_name(dp)) != NULL) {
2161 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2162 if (claws_unlink(tmp) < 0)
2163 FILE_OP_ERROR(tmp, "unlink");
2172 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2175 const gchar *dir_name;
2179 if (first == last) {
2180 /* Skip all the dir reading part. */
2181 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2182 if (is_dir_exist(filename)) {
2183 /* a numbered directory with this name exists,
2184 * remove the dot-file instead */
2186 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2188 if (claws_unlink(filename) < 0) {
2189 FILE_OP_ERROR(filename, "unlink");
2197 prev_dir = g_get_current_dir();
2199 if (g_chdir(dir) < 0) {
2200 FILE_OP_ERROR(dir, "chdir");
2205 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2206 g_warning("failed to open directory: %s", dir);
2211 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2212 file_no = to_number(dir_name);
2213 if (file_no > 0 && first <= file_no && file_no <= last) {
2214 if (is_dir_exist(dir_name)) {
2215 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2216 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2217 FILE_OP_ERROR(dot_file, "unlink");
2222 if (claws_unlink(dir_name) < 0)
2223 FILE_OP_ERROR(dir_name, "unlink");
2229 if (g_chdir(prev_dir) < 0) {
2230 FILE_OP_ERROR(prev_dir, "chdir");
2240 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2243 const gchar *dir_name;
2246 GHashTable *wanted_files;
2248 GError *error = NULL;
2250 if (numberlist == NULL)
2253 prev_dir = g_get_current_dir();
2255 if (g_chdir(dir) < 0) {
2256 FILE_OP_ERROR(dir, "chdir");
2261 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2262 g_message("Couldn't open current directory: %s (%d).\n",
2263 error->message, error->code);
2264 g_error_free(error);
2269 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2270 for (cur = numberlist; cur != NULL; cur = cur->next) {
2271 /* numberlist->data is expected to be GINT_TO_POINTER */
2272 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2275 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2276 file_no = to_number(dir_name);
2277 if (is_dir_exist(dir_name))
2279 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2280 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2281 if (is_dir_exist(dir_name)) {
2282 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2283 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2284 FILE_OP_ERROR(dot_file, "unlink");
2289 if (claws_unlink(dir_name) < 0)
2290 FILE_OP_ERROR(dir_name, "unlink");
2295 g_hash_table_destroy(wanted_files);
2297 if (g_chdir(prev_dir) < 0) {
2298 FILE_OP_ERROR(prev_dir, "chdir");
2308 gint remove_all_numbered_files(const gchar *dir)
2310 return remove_numbered_files(dir, 0, UINT_MAX);
2313 gint remove_dir_recursive(const gchar *dir)
2317 const gchar *dir_name;
2320 if (g_stat(dir, &s) < 0) {
2321 FILE_OP_ERROR(dir, "stat");
2322 if (ENOENT == errno) return 0;
2326 if (!S_ISDIR(s.st_mode)) {
2327 if (claws_unlink(dir) < 0) {
2328 FILE_OP_ERROR(dir, "unlink");
2335 prev_dir = g_get_current_dir();
2336 /* g_print("prev_dir = %s\n", prev_dir); */
2338 if (!path_cmp(prev_dir, dir)) {
2340 if (g_chdir("..") < 0) {
2341 FILE_OP_ERROR(dir, "chdir");
2344 prev_dir = g_get_current_dir();
2347 if (g_chdir(dir) < 0) {
2348 FILE_OP_ERROR(dir, "chdir");
2353 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2354 g_warning("failed to open directory: %s", dir);
2360 /* remove all files in the directory */
2361 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2362 /* g_print("removing %s\n", dir_name); */
2364 if (is_dir_exist(dir_name)) {
2367 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2368 g_warning("can't remove directory: %s", dir_name);
2372 if (claws_unlink(dir_name) < 0)
2373 FILE_OP_ERROR(dir_name, "unlink");
2379 if (g_chdir(prev_dir) < 0) {
2380 FILE_OP_ERROR(prev_dir, "chdir");
2387 if (g_rmdir(dir) < 0) {
2388 FILE_OP_ERROR(dir, "rmdir");
2395 gint rename_force(const gchar *oldpath, const gchar *newpath)
2398 if (!is_file_entry_exist(oldpath)) {
2402 if (is_file_exist(newpath)) {
2403 if (claws_unlink(newpath) < 0)
2404 FILE_OP_ERROR(newpath, "unlink");
2407 return g_rename(oldpath, newpath);
2411 * Append src file body to the tail of dest file.
2412 * Now keep_backup has no effects.
2414 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2416 FILE *src_fp, *dest_fp;
2420 gboolean err = FALSE;
2422 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2423 FILE_OP_ERROR(src, "g_fopen");
2427 if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2428 FILE_OP_ERROR(dest, "g_fopen");
2433 if (change_file_mode_rw(dest_fp, dest) < 0) {
2434 FILE_OP_ERROR(dest, "chmod");
2435 g_warning("can't change file mode: %s", dest);
2438 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2439 if (n_read < sizeof(buf) && ferror(src_fp))
2441 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2442 g_warning("writing to %s failed.", dest);
2450 if (ferror(src_fp)) {
2451 FILE_OP_ERROR(src, "fread");
2455 if (fclose(dest_fp) == EOF) {
2456 FILE_OP_ERROR(dest, "fclose");
2468 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2470 FILE *src_fp, *dest_fp;
2473 gchar *dest_bak = NULL;
2474 gboolean err = FALSE;
2476 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2477 FILE_OP_ERROR(src, "g_fopen");
2480 if (is_file_exist(dest)) {
2481 dest_bak = g_strconcat(dest, ".bak", NULL);
2482 if (rename_force(dest, dest_bak) < 0) {
2483 FILE_OP_ERROR(dest, "rename");
2490 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2491 FILE_OP_ERROR(dest, "g_fopen");
2494 if (rename_force(dest_bak, dest) < 0)
2495 FILE_OP_ERROR(dest_bak, "rename");
2501 if (change_file_mode_rw(dest_fp, dest) < 0) {
2502 FILE_OP_ERROR(dest, "chmod");
2503 g_warning("can't change file mode: %s", dest);
2506 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2507 if (n_read < sizeof(buf) && ferror(src_fp))
2509 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2510 g_warning("writing to %s failed.", dest);
2515 if (rename_force(dest_bak, dest) < 0)
2516 FILE_OP_ERROR(dest_bak, "rename");
2523 if (ferror(src_fp)) {
2524 FILE_OP_ERROR(src, "fread");
2528 if (safe_fclose(dest_fp) == EOF) {
2529 FILE_OP_ERROR(dest, "fclose");
2536 if (rename_force(dest_bak, dest) < 0)
2537 FILE_OP_ERROR(dest_bak, "rename");
2543 if (keep_backup == FALSE && dest_bak)
2544 claws_unlink(dest_bak);
2551 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2553 if (overwrite == FALSE && is_file_exist(dest)) {
2554 g_warning("move_file(): file %s already exists.", dest);
2558 if (rename_force(src, dest) == 0) return 0;
2560 if (EXDEV != errno) {
2561 FILE_OP_ERROR(src, "rename");
2565 if (copy_file(src, dest, FALSE) < 0) return -1;
2572 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2575 gint bytes_left, to_read;
2578 if (fseek(fp, offset, SEEK_SET) < 0) {
2583 bytes_left = length;
2584 to_read = MIN(bytes_left, sizeof(buf));
2586 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2587 if (n_read < to_read && ferror(fp))
2589 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2592 bytes_left -= n_read;
2593 if (bytes_left == 0)
2595 to_read = MIN(bytes_left, sizeof(buf));
2606 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2609 gboolean err = FALSE;
2611 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2612 FILE_OP_ERROR(dest, "g_fopen");
2616 if (change_file_mode_rw(dest_fp, dest) < 0) {
2617 FILE_OP_ERROR(dest, "chmod");
2618 g_warning("can't change file mode: %s", dest);
2621 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2624 if (safe_fclose(dest_fp) == EOF) {
2625 FILE_OP_ERROR(dest, "fclose");
2630 g_warning("writing to %s failed.", dest);
2638 /* convert line endings into CRLF. If the last line doesn't end with
2639 * linebreak, add it.
2641 gchar *canonicalize_str(const gchar *str)
2647 for (p = str; *p != '\0'; ++p) {
2654 if (p == str || *(p - 1) != '\n')
2657 out = outp = g_malloc(new_len + 1);
2658 for (p = str; *p != '\0'; ++p) {
2665 if (p == str || *(p - 1) != '\n') {
2674 gint canonicalize_file(const gchar *src, const gchar *dest)
2676 FILE *src_fp, *dest_fp;
2677 gchar buf[BUFFSIZE];
2679 gboolean err = FALSE;
2680 gboolean last_linebreak = FALSE;
2682 if (src == NULL || dest == NULL)
2685 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2686 FILE_OP_ERROR(src, "g_fopen");
2690 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2691 FILE_OP_ERROR(dest, "g_fopen");
2696 if (change_file_mode_rw(dest_fp, dest) < 0) {
2697 FILE_OP_ERROR(dest, "chmod");
2698 g_warning("can't change file mode: %s", dest);
2701 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2705 if (len == 0) break;
2706 last_linebreak = FALSE;
2708 if (buf[len - 1] != '\n') {
2709 last_linebreak = TRUE;
2710 r = fputs(buf, dest_fp);
2711 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2712 r = fputs(buf, dest_fp);
2715 r = fwrite(buf, 1, len - 1, dest_fp);
2720 r = fputs("\r\n", dest_fp);
2724 g_warning("writing to %s failed.", dest);
2732 if (last_linebreak == TRUE) {
2733 if (fputs("\r\n", dest_fp) == EOF)
2737 if (ferror(src_fp)) {
2738 FILE_OP_ERROR(src, "fgets");
2742 if (safe_fclose(dest_fp) == EOF) {
2743 FILE_OP_ERROR(dest, "fclose");
2755 gint canonicalize_file_replace(const gchar *file)
2759 tmp_file = get_tmp_file();
2761 if (canonicalize_file(file, tmp_file) < 0) {
2766 if (move_file(tmp_file, file, TRUE) < 0) {
2767 g_warning("can't replace file: %s", file);
2768 claws_unlink(tmp_file);
2777 gchar *normalize_newlines(const gchar *str)
2782 out = outp = g_malloc(strlen(str) + 1);
2783 for (p = str; *p != '\0'; ++p) {
2785 if (*(p + 1) != '\n')
2796 gchar *get_outgoing_rfc2822_str(FILE *fp)
2798 gchar buf[BUFFSIZE];
2802 str = g_string_new(NULL);
2804 /* output header part */
2805 while (fgets(buf, sizeof(buf), fp) != NULL) {
2807 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2814 else if (next != ' ' && next != '\t') {
2818 if (fgets(buf, sizeof(buf), fp) == NULL)
2822 g_string_append(str, buf);
2823 g_string_append(str, "\r\n");
2829 /* output body part */
2830 while (fgets(buf, sizeof(buf), fp) != NULL) {
2833 g_string_append_c(str, '.');
2834 g_string_append(str, buf);
2835 g_string_append(str, "\r\n");
2839 g_string_free(str, FALSE);
2845 * Create a new boundary in a way that it is very unlikely that this
2846 * will occur in the following text. It would be easy to ensure
2847 * uniqueness if everything is either quoted-printable or base64
2848 * encoded (note that conversion is allowed), but because MIME bodies
2849 * may be nested, it may happen that the same boundary has already
2852 * boundary := 0*69<bchars> bcharsnospace
2853 * bchars := bcharsnospace / " "
2854 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2855 * "+" / "_" / "," / "-" / "." /
2856 * "/" / ":" / "=" / "?"
2858 * some special characters removed because of buggy MTAs
2861 gchar *generate_mime_boundary(const gchar *prefix)
2863 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2864 "abcdefghijklmnopqrstuvwxyz"
2869 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2870 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2873 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2877 gint change_file_mode_rw(FILE *fp, const gchar *file)
2880 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2882 return g_chmod(file, S_IRUSR|S_IWUSR);
2886 FILE *my_tmpfile(void)
2888 const gchar suffix[] = ".XXXXXX";
2889 const gchar *tmpdir;
2891 const gchar *progname;
2900 tmpdir = get_tmp_dir();
2901 tmplen = strlen(tmpdir);
2902 progname = g_get_prgname();
2903 if (progname == NULL)
2904 progname = "claws-mail";
2905 proglen = strlen(progname);
2906 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2909 memcpy(fname, tmpdir, tmplen);
2910 fname[tmplen] = G_DIR_SEPARATOR;
2911 memcpy(fname + tmplen + 1, progname, proglen);
2912 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2914 fd = g_mkstemp(fname);
2919 claws_unlink(fname);
2921 /* verify that we can write in the file after unlinking */
2922 if (write(fd, buf, 1) < 0) {
2929 fp = fdopen(fd, "w+b");
2940 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2943 *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
2944 fd = g_mkstemp(*filename);
2947 return fdopen(fd, "w+");
2950 FILE *str_open_as_stream(const gchar *str)
2955 cm_return_val_if_fail(str != NULL, NULL);
2959 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2964 if (len == 0) return fp;
2966 if (fwrite(str, 1, len, fp) != len) {
2967 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2976 gint str_write_to_file(const gchar *str, const gchar *file)
2981 cm_return_val_if_fail(str != NULL, -1);
2982 cm_return_val_if_fail(file != NULL, -1);
2984 if ((fp = g_fopen(file, "wb")) == NULL) {
2985 FILE_OP_ERROR(file, "g_fopen");
2995 if (fwrite(str, 1, len, fp) != len) {
2996 FILE_OP_ERROR(file, "fwrite");
3002 if (safe_fclose(fp) == EOF) {
3003 FILE_OP_ERROR(file, "fclose");
3011 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3018 cm_return_val_if_fail(fp != NULL, NULL);
3020 array = g_byte_array_new();
3022 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3023 if (n_read < sizeof(buf) && ferror(fp))
3025 g_byte_array_append(array, buf, n_read);
3029 FILE_OP_ERROR("file stream", "fread");
3030 g_byte_array_free(array, TRUE);
3035 g_byte_array_append(array, buf, 1);
3036 str = (gchar *)array->data;
3037 g_byte_array_free(array, FALSE);
3039 if (recode && !g_utf8_validate(str, -1, NULL)) {
3040 const gchar *src_codeset, *dest_codeset;
3042 src_codeset = conv_get_locale_charset_str();
3043 dest_codeset = CS_UTF_8;
3044 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3052 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3059 struct timeval timeout = {1, 0};
3064 cm_return_val_if_fail(file != NULL, NULL);
3066 if (g_stat(file, &s) != 0) {
3067 FILE_OP_ERROR(file, "stat");
3070 if (S_ISDIR(s.st_mode)) {
3071 g_warning("%s: is a directory", file);
3076 fp = g_fopen (file, "rb");
3078 FILE_OP_ERROR(file, "open");
3082 /* test whether the file is readable without blocking */
3083 fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3085 FILE_OP_ERROR(file, "open");
3092 /* allow for one second */
3093 err = select(fd+1, &fds, NULL, NULL, &timeout);
3094 if (err <= 0 || !FD_ISSET(fd, &fds)) {
3096 FILE_OP_ERROR(file, "select");
3098 g_warning("%s: doesn't seem readable", file);
3104 /* Now clear O_NONBLOCK */
3105 if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3106 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3110 if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3111 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3116 /* get the FILE pointer */
3117 fp = fdopen(fd, "rb");
3120 FILE_OP_ERROR(file, "fdopen");
3121 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3126 str = file_read_stream_to_str_full(fp, recode);
3133 gchar *file_read_to_str(const gchar *file)
3135 return file_read_to_str_full(file, TRUE);
3137 gchar *file_read_stream_to_str(FILE *fp)
3139 return file_read_stream_to_str_full(fp, TRUE);
3142 gchar *file_read_to_str_no_recode(const gchar *file)
3144 return file_read_to_str_full(file, FALSE);
3146 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3148 return file_read_stream_to_str_full(fp, FALSE);
3151 char *fgets_crlf(char *buf, int size, FILE *stream)
3153 gboolean is_cr = FALSE;
3154 gboolean last_was_cr = FALSE;
3159 while (--size > 0 && (c = getc(stream)) != EOF)
3162 is_cr = (c == '\r');
3172 last_was_cr = is_cr;
3174 if (c == EOF && cs == buf)
3182 static gint execute_async(gchar *const argv[], const gchar *working_directory)
3184 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3186 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3187 NULL, NULL, NULL, FALSE) == FALSE) {
3188 g_warning("couldn't execute command: %s", argv[0]);
3195 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
3199 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3202 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3203 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3204 g_warning("couldn't execute command: %s", argv[0]);
3208 if (WIFEXITED(status))
3209 return WEXITSTATUS(status);
3213 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
3214 G_SPAWN_SEARCH_PATH|
3215 G_SPAWN_CHILD_INHERITS_STDIN|
3216 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3217 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3218 g_warning("couldn't execute command: %s", argv[0]);
3226 gint execute_command_line(const gchar *cmdline, gboolean async,
3227 const gchar *working_directory)
3232 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3234 argv = strsplit_with_quote(cmdline, " ", 0);
3237 ret = execute_async(argv, working_directory);
3239 ret = execute_sync(argv, working_directory);
3246 gchar *get_command_output(const gchar *cmdline)
3248 gchar *child_stdout;
3251 cm_return_val_if_fail(cmdline != NULL, NULL);
3253 debug_print("get_command_output(): executing: %s\n", cmdline);
3255 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3257 g_warning("couldn't execute command: %s", cmdline);
3261 return child_stdout;
3264 static gint is_unchanged_uri_char(char c)
3275 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3281 for(i = 0; i < strlen(uri) ; i++) {
3282 if (is_unchanged_uri_char(uri[i])) {
3283 if (k + 2 >= bufsize)
3285 encoded_uri[k++] = uri[i];
3288 char * hexa = "0123456789ABCDEF";
3290 if (k + 4 >= bufsize)
3292 encoded_uri[k++] = '%';
3293 encoded_uri[k++] = hexa[uri[i] / 16];
3294 encoded_uri[k++] = hexa[uri[i] % 16];
3300 gint open_uri(const gchar *uri, const gchar *cmdline)
3304 gchar buf[BUFFSIZE];
3306 gchar encoded_uri[BUFFSIZE];
3307 cm_return_val_if_fail(uri != NULL, -1);
3309 /* an option to choose whether to use encode_uri or not ? */
3310 encode_uri(encoded_uri, BUFFSIZE, uri);
3313 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3314 !strchr(p + 2, '%'))
3315 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3318 g_warning("Open URI command-line is invalid "
3319 "(there must be only one '%%s'): %s",
3321 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3324 execute_command_line(buf, TRUE, NULL);
3326 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3331 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3333 gchar buf[BUFFSIZE];
3336 cm_return_val_if_fail(filepath != NULL, -1);
3339 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3340 !strchr(p + 2, '%'))
3341 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3344 g_warning("Open Text Editor command-line is invalid "
3345 "(there must be only one '%%s'): %s",
3347 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3350 execute_command_line(buf, TRUE, NULL);
3355 time_t remote_tzoffset_sec(const gchar *zone)
3357 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3363 time_t remoteoffset;
3365 strncpy(zone3, zone, 3);
3369 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3370 (c == '+' || c == '-')) {
3371 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3373 remoteoffset = -remoteoffset;
3374 } else if (!strncmp(zone, "UT" , 2) ||
3375 !strncmp(zone, "GMT", 3)) {
3377 } else if (strlen(zone3) == 3) {
3378 for (p = ustzstr; *p != '\0'; p += 3) {
3379 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3380 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3381 remoteoffset = iustz * 3600;
3387 } else if (strlen(zone3) == 1) {
3389 case 'Z': remoteoffset = 0; break;
3390 case 'A': remoteoffset = -1; break;
3391 case 'B': remoteoffset = -2; break;
3392 case 'C': remoteoffset = -3; break;
3393 case 'D': remoteoffset = -4; break;
3394 case 'E': remoteoffset = -5; break;
3395 case 'F': remoteoffset = -6; break;
3396 case 'G': remoteoffset = -7; break;
3397 case 'H': remoteoffset = -8; break;
3398 case 'I': remoteoffset = -9; break;
3399 case 'K': remoteoffset = -10; break; /* J is not used */
3400 case 'L': remoteoffset = -11; break;
3401 case 'M': remoteoffset = -12; break;
3402 case 'N': remoteoffset = 1; break;
3403 case 'O': remoteoffset = 2; break;
3404 case 'P': remoteoffset = 3; break;
3405 case 'Q': remoteoffset = 4; break;
3406 case 'R': remoteoffset = 5; break;
3407 case 'S': remoteoffset = 6; break;
3408 case 'T': remoteoffset = 7; break;
3409 case 'U': remoteoffset = 8; break;
3410 case 'V': remoteoffset = 9; break;
3411 case 'W': remoteoffset = 10; break;
3412 case 'X': remoteoffset = 11; break;
3413 case 'Y': remoteoffset = 12; break;
3414 default: remoteoffset = 0; break;
3416 remoteoffset = remoteoffset * 3600;
3420 return remoteoffset;
3423 time_t tzoffset_sec(time_t *now)
3427 struct tm buf1, buf2;
3429 if (now && *now < 0)
3432 gmt = *gmtime_r(now, &buf1);
3433 lt = localtime_r(now, &buf2);
3435 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3437 if (lt->tm_year < gmt.tm_year)
3439 else if (lt->tm_year > gmt.tm_year)
3441 else if (lt->tm_yday < gmt.tm_yday)
3443 else if (lt->tm_yday > gmt.tm_yday)
3446 if (off >= 24 * 60) /* should be impossible */
3447 off = 23 * 60 + 59; /* if not, insert silly value */
3448 if (off <= -24 * 60)
3449 off = -(23 * 60 + 59);
3454 /* calculate timezone offset */
3455 gchar *tzoffset(time_t *now)
3457 static gchar offset_string[6];
3461 struct tm buf1, buf2;
3463 if (now && *now < 0)
3466 gmt = *gmtime_r(now, &buf1);
3467 lt = localtime_r(now, &buf2);
3469 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3471 if (lt->tm_year < gmt.tm_year)
3473 else if (lt->tm_year > gmt.tm_year)
3475 else if (lt->tm_yday < gmt.tm_yday)
3477 else if (lt->tm_yday > gmt.tm_yday)
3485 if (off >= 24 * 60) /* should be impossible */
3486 off = 23 * 60 + 59; /* if not, insert silly value */
3488 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3490 return offset_string;
3493 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
3497 gchar day[4], mon[4];
3498 gint dd, hh, mm, ss, yyyy;
3500 gchar buf2[RFC822_DATE_BUFFSIZE];
3504 lt = gmtime_r(&t, &buf1);
3506 lt = localtime_r(&t, &buf1);
3508 if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
3509 day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
3510 g_warning("failed reading date/time");
3512 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3513 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
3516 void get_rfc822_date(gchar *buf, gint len)
3518 _get_rfc822_date(buf, len, FALSE);
3521 void get_rfc822_date_hide_tz(gchar *buf, gint len)
3523 _get_rfc822_date(buf, len, TRUE);
3526 void debug_set_mode(gboolean mode)
3531 gboolean debug_get_mode(void)
3536 void debug_print_real(const gchar *format, ...)
3539 gchar buf[BUFFSIZE];
3541 if (!debug_mode) return;
3543 va_start(args, format);
3544 g_vsnprintf(buf, sizeof(buf), format, args);
3551 const char * debug_srcname(const char *file)
3553 const char *s = strrchr (file, '/');
3558 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3560 if (subject == NULL)
3563 subject += subject_get_prefix_length(subject);
3565 return g_hash_table_lookup(subject_table, subject);
3568 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3571 if (subject == NULL || *subject == 0)
3573 subject += subject_get_prefix_length(subject);
3574 g_hash_table_insert(subject_table, subject, data);
3577 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3579 if (subject == NULL)
3582 subject += subject_get_prefix_length(subject);
3583 g_hash_table_remove(subject_table, subject);
3586 static regex_t u_regex;
3587 static gboolean u_init_;
3589 void utils_free_regex(void)
3598 *\brief Check if a string is prefixed with known (combinations)
3599 * of prefixes. The function assumes that each prefix
3600 * is terminated by zero or exactly _one_ space.
3602 *\param str String to check for a prefixes
3604 *\return int Number of chars in the prefix that should be skipped
3605 * for a "clean" subject line. If no prefix was found, 0
3608 int subject_get_prefix_length(const gchar *subject)
3610 /*!< Array with allowable reply prefixes regexps. */
3611 static const gchar * const prefixes[] = {
3612 "Re\\:", /* "Re:" */
3613 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3614 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3615 "Aw\\:", /* "Aw:" (German) */
3616 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3617 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3618 "Fw\\:", /* "Fw:" Forward */
3619 "Fwd\\:", /* "Fwd:" Forward */
3620 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3621 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3622 "Rif\\:", /* "Rif:" (Italian Outlook) */
3623 "Sv\\:", /* "Sv" (Norwegian) */
3624 "Vs\\:", /* "Vs" (Norwegian) */
3625 "Ad\\:", /* "Ad" (Norwegian) */
3626 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3627 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3628 "Re \\:", /* "Re :" (French Yahoo Mail) */
3631 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3635 if (!subject) return 0;
3636 if (!*subject) return 0;
3639 GString *s = g_string_new("");
3641 for (n = 0; n < PREFIXES; n++)
3642 /* Terminate each prefix regexpression by a
3643 * "\ ?" (zero or ONE space), and OR them */
3644 g_string_append_printf(s, "(%s\\ ?)%s",
3649 g_string_prepend(s, "(");
3650 g_string_append(s, ")+"); /* match at least once */
3651 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3654 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3655 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3656 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3657 debug_print("Error compiling regexp %s\n", s->str);
3658 g_string_free(s, TRUE);
3662 g_string_free(s, TRUE);
3666 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3672 static guint g_stricase_hash(gconstpointer gptr)
3674 guint hash_result = 0;
3677 for (str = gptr; str && *str; str++) {
3678 hash_result += toupper(*str);
3684 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3686 const char *str1 = gptr1;
3687 const char *str2 = gptr2;
3689 return !strcasecmp(str1, str2);
3692 gint g_int_compare(gconstpointer a, gconstpointer b)
3694 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3698 quote_cmd_argument()
3700 return a quoted string safely usable in argument of a command.
3702 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3705 gint quote_cmd_argument(gchar * result, guint size,
3715 for(p = path ; * p != '\0' ; p ++) {
3717 if (isalnum((guchar)*p) || (* p == '/')) {
3718 if (remaining > 0) {
3724 result[size - 1] = '\0';
3729 if (remaining >= 2) {
3737 result[size - 1] = '\0';
3742 if (remaining > 0) {
3746 result[size - 1] = '\0';
3760 static void g_node_map_recursive(GNode *node, gpointer data)
3762 GNodeMapData *mapdata = (GNodeMapData *) data;
3764 GNodeMapData newmapdata;
3767 newdata = mapdata->func(node->data, mapdata->data);
3768 if (newdata != NULL) {
3769 newnode = g_node_new(newdata);
3770 g_node_append(mapdata->parent, newnode);
3772 newmapdata.parent = newnode;
3773 newmapdata.func = mapdata->func;
3774 newmapdata.data = mapdata->data;
3776 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3780 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3783 GNodeMapData mapdata;
3785 cm_return_val_if_fail(node != NULL, NULL);
3786 cm_return_val_if_fail(func != NULL, NULL);
3788 root = g_node_new(func(node->data, data));
3790 mapdata.parent = root;
3791 mapdata.func = func;
3792 mapdata.data = data;
3794 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3799 #define HEX_TO_INT(val, hex) \
3803 if ('0' <= c && c <= '9') { \
3805 } else if ('a' <= c && c <= 'f') { \
3806 val = c - 'a' + 10; \
3807 } else if ('A' <= c && c <= 'F') { \
3808 val = c - 'A' + 10; \
3814 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3821 if (hi == -1 || lo == -1)
3824 *out = (hi << 4) + lo;
3828 #define INT_TO_HEX(hex, val) \
3831 hex = '0' + (val); \
3833 hex = 'A' + (val) - 10; \
3836 void get_hex_str(gchar *out, guchar ch)
3840 INT_TO_HEX(hex, ch >> 4);
3842 INT_TO_HEX(hex, ch & 0x0f);
3848 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3850 #define G_PRINT_REF g_print
3854 *\brief Register ref counted pointer. It is based on GBoxed, so should
3855 * work with anything that uses the GType system. The semantics
3856 * are similar to a C++ auto pointer, with the exception that
3857 * C doesn't have automatic closure (calling destructors) when
3858 * exiting a block scope.
3859 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3860 * function directly.
3862 *\return GType A GType type.
3864 GType g_auto_pointer_register(void)
3866 static GType auto_pointer_type;
3867 if (!auto_pointer_type)
3869 g_boxed_type_register_static
3870 ("G_TYPE_AUTO_POINTER",
3871 (GBoxedCopyFunc) g_auto_pointer_copy,
3872 (GBoxedFreeFunc) g_auto_pointer_free);
3873 return auto_pointer_type;
3877 *\brief Structure with g_new() allocated pointer guarded by the
3880 typedef struct AutoPointerRef {
3881 void (*free) (gpointer);
3887 *\brief The auto pointer opaque structure that references the
3888 * pointer guard block.
3890 typedef struct AutoPointer {
3891 AutoPointerRef *ref;
3892 gpointer ptr; /*!< access to protected pointer */
3896 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3900 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3901 * ... when assigning, copying and freeing storage elements
3903 * gtk_list_store_new(N_S_COLUMNS,
3904 * G_TYPE_AUTO_POINTER,
3908 * Template *precious_data = g_new0(Template, 1);
3909 * g_pointer protect = g_auto_pointer_new(precious_data);
3911 * gtk_list_store_set(container, &iter,
3915 * ... the gtk_list_store has copied the pointer and
3916 * ... incremented its reference count, we should free
3917 * ... the auto pointer (in C++ a destructor would do
3918 * ... this for us when leaving block scope)
3920 * g_auto_pointer_free(protect);
3922 * ... gtk_list_store_set() now manages the data. When
3923 * ... *explicitly* requesting a pointer from the list
3924 * ... store, don't forget you get a copy that should be
3925 * ... freed with g_auto_pointer_free() eventually.
3929 *\param pointer Pointer to be guarded.
3931 *\return GAuto * Pointer that should be used in containers with
3934 GAuto *g_auto_pointer_new(gpointer p)
3936 AutoPointerRef *ref;
3942 ref = g_new0(AutoPointerRef, 1);
3943 ptr = g_new0(AutoPointer, 1);
3953 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3959 *\brief Allocate an autopointer using the passed \a free function to
3960 * free the guarded pointer
3962 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3969 aptr = g_auto_pointer_new(p);
3970 aptr->ref->free = free_;
3974 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3976 if (auto_ptr == NULL)
3978 return ((AutoPointer *) auto_ptr)->ptr;
3982 *\brief Copies an auto pointer by. It's mostly not necessary
3983 * to call this function directly, unless you copy/assign
3984 * the guarded pointer.
3986 *\param auto_ptr Auto pointer returned by previous call to
3987 * g_auto_pointer_new_XXX()
3989 *\return gpointer An auto pointer
3991 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3994 AutoPointerRef *ref;
3997 if (auto_ptr == NULL)
4002 newp = g_new0(AutoPointer, 1);
4005 newp->ptr = ref->pointer;
4009 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4015 *\brief Free an auto pointer
4017 void g_auto_pointer_free(GAuto *auto_ptr)
4020 AutoPointerRef *ref;
4022 if (auto_ptr == NULL)
4028 if (--(ref->cnt) == 0) {
4030 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4032 ref->free(ref->pointer);
4037 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4042 void replace_returns(gchar *str)
4047 while (strstr(str, "\n")) {
4048 *strstr(str, "\n") = ' ';
4050 while (strstr(str, "\r")) {
4051 *strstr(str, "\r") = ' ';
4055 /* get_uri_part() - retrieves a URI starting from scanpos.
4056 Returns TRUE if successful */
4057 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
4058 const gchar **bp, const gchar **ep, gboolean hdr)
4061 gint parenthese_cnt = 0;
4063 cm_return_val_if_fail(start != NULL, FALSE);
4064 cm_return_val_if_fail(scanpos != NULL, FALSE);
4065 cm_return_val_if_fail(bp != NULL, FALSE);
4066 cm_return_val_if_fail(ep != NULL, FALSE);
4070 /* find end point of URI */
4071 for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
4072 if (!g_ascii_isgraph(*(const guchar *)ep_) ||
4073 !IS_ASCII(*(const guchar *)ep_) ||
4074 strchr("[]{}<>\"", *ep_)) {
4076 } else if (strchr("(", *ep_)) {
4078 } else if (strchr(")", *ep_)) {
4079 if (parenthese_cnt > 0)
4086 /* no punctuation at end of string */
4088 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
4089 * should pass some URI type to this function and decide on that whether
4090 * to perform punctuation stripping */
4092 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
4094 for (; ep_ - 1 > scanpos + 1 &&
4095 IS_REAL_PUNCT(*(ep_ - 1));
4099 #undef IS_REAL_PUNCT
4106 gchar *make_uri_string(const gchar *bp, const gchar *ep)
4108 while (bp && *bp && g_ascii_isspace(*bp))
4110 return g_strndup(bp, ep - bp);
4113 /* valid mail address characters */
4114 #define IS_RFC822_CHAR(ch) \
4118 !g_ascii_isspace(ch) && \
4119 !strchr("(),;<>\"", (ch)))
4121 /* alphabet and number within 7bit ASCII */
4122 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
4123 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
4125 static GHashTable *create_domain_tab(void)
4128 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
4130 cm_return_val_if_fail(htab, NULL);
4131 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
4132 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
4136 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
4138 const gint MAX_LVL_DOM_NAME_LEN = 6;
4139 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
4140 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
4143 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
4146 for (p = buf; p < m && first < last; *p++ = *first++)
4150 return g_hash_table_lookup(tab, buf) != NULL;
4153 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
4154 gboolean get_email_part(const gchar *start, const gchar *scanpos,
4155 const gchar **bp, const gchar **ep, gboolean hdr)
4157 /* more complex than the uri part because we need to scan back and forward starting from
4158 * the scan position. */
4159 gboolean result = FALSE;
4160 const gchar *bp_ = NULL;
4161 const gchar *ep_ = NULL;
4162 static GHashTable *dom_tab;
4163 const gchar *last_dot = NULL;
4164 const gchar *prelast_dot = NULL;
4165 const gchar *last_tld_char = NULL;
4167 /* the informative part of the email address (describing the name
4168 * of the email address owner) may contain quoted parts. the
4169 * closure stack stores the last encountered quotes. */
4170 gchar closure_stack[128];
4171 gchar *ptr = closure_stack;
4173 cm_return_val_if_fail(start != NULL, FALSE);
4174 cm_return_val_if_fail(scanpos != NULL, FALSE);
4175 cm_return_val_if_fail(bp != NULL, FALSE);
4176 cm_return_val_if_fail(ep != NULL, FALSE);
4179 const gchar *start_quote = NULL;
4180 const gchar *end_quote = NULL;
4182 /* go to the real start */
4183 if (start[0] == ',')
4185 if (start[0] == ';')
4187 while (start[0] == '\n' || start[0] == '\r')
4189 while (start[0] == ' ' || start[0] == '\t')
4194 /* check if there are quotes (to skip , in them) */
4195 if (*start == '"') {
4196 start_quote = start;
4198 end_quote = strstr(start, "\"");
4204 /* skip anything between quotes */
4205 if (start_quote && end_quote) {
4210 /* find end (either , or ; or end of line) */
4211 if (strstr(start, ",") && strstr(start, ";"))
4212 *ep = strstr(start,",") < strstr(start, ";")
4213 ? strstr(start, ",") : strstr(start, ";");
4214 else if (strstr(start, ","))
4215 *ep = strstr(start, ",");
4216 else if (strstr(start, ";"))
4217 *ep = strstr(start, ";");
4219 *ep = start+strlen(start);
4221 /* go back to real start */
4222 if (start_quote && end_quote) {
4223 start = start_quote;
4226 /* check there's still an @ in that, or search
4227 * further if possible */
4228 if (strstr(start, "@") && strstr(start, "@") < *ep)
4230 else if (*ep < start+strlen(start)) {
4233 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
4241 dom_tab = create_domain_tab();
4242 cm_return_val_if_fail(dom_tab, FALSE);
4244 /* scan start of address */
4245 for (bp_ = scanpos - 1;
4246 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
4249 /* TODO: should start with an alnum? */
4251 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
4254 if (bp_ != scanpos) {
4255 /* scan end of address */
4256 for (ep_ = scanpos + 1;
4257 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
4259 prelast_dot = last_dot;
4261 if (*(last_dot + 1) == '.') {
4262 if (prelast_dot == NULL)
4264 last_dot = prelast_dot;
4269 /* TODO: really should terminate with an alnum? */
4270 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
4275 if (last_dot == NULL)
4277 if (last_dot >= ep_)
4278 last_dot = prelast_dot;
4279 if (last_dot == NULL || (scanpos + 1 >= last_dot))
4283 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
4284 if (*last_tld_char == '?')
4287 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
4294 if (!result) return FALSE;
4296 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
4297 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
4298 && IS_RFC822_CHAR(*(ep_ + 3))) {
4299 /* this informative part with an @ in it is
4300 * followed by the email address */
4303 /* go to matching '>' (or next non-rfc822 char, like \n) */
4304 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
4307 /* include the bracket */
4308 if (*ep_ == '>') ep_++;
4310 /* include the leading quote */
4318 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
4319 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
4322 /* see if this is <bracketed>; in this case we also scan for the informative part. */
4323 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
4326 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
4327 #define IN_STACK() (ptr > closure_stack)
4328 /* has underrun check */
4329 #define POP_STACK() if(IN_STACK()) --ptr
4330 /* has overrun check */
4331 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
4332 /* has underrun check */
4333 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
4337 /* scan for the informative part. */
4338 for (bp_ -= 2; bp_ >= start; bp_--) {
4339 /* if closure on the stack keep scanning */
4340 if (PEEK_STACK() == *bp_) {
4344 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
4349 /* if nothing in the closure stack, do the special conditions
4350 * the following if..else expression simply checks whether
4351 * a token is acceptable. if not acceptable, the clause
4352 * should terminate the loop with a 'break' */
4353 if (!PEEK_STACK()) {
4355 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
4356 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
4357 /* hyphens are allowed, but only in
4359 } else if (strchr(" \"'", *bp_)) {
4360 /* but anything not being a punctiation
4363 break; /* anything else is rejected */
4370 /* scan forward (should start with an alnum) */
4371 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
4387 #undef IS_ASCII_ALNUM
4388 #undef IS_RFC822_CHAR
4390 gchar *make_email_string(const gchar *bp, const gchar *ep)
4392 /* returns a mailto: URI; mailto: is also used to detect the
4393 * uri type later on in the button_pressed signal handler */
4398 tmp = g_strndup(bp, ep - bp);
4400 /* If there is a colon in the username part of the address,
4401 * we're dealing with an URI for some other protocol - do
4402 * not prefix with mailto: in such case. */
4403 colon = strchr(tmp, ':');
4404 at = strchr(tmp, '@');
4405 if (colon != NULL && at != NULL && colon < at) {
4408 result = g_strconcat("mailto:", tmp, NULL);
4415 gchar *make_http_string(const gchar *bp, const gchar *ep)
4417 /* returns an http: URI; */
4421 while (bp && *bp && g_ascii_isspace(*bp))
4423 tmp = g_strndup(bp, ep - bp);
4424 result = g_strconcat("http://", tmp, NULL);
4430 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
4432 FILE *fp = g_fopen(path, "rb");
4433 gchar buf[BUFFSIZE];
4434 gchar *result = NULL;
4437 while (fgets(buf, sizeof (buf), fp) != NULL) {
4438 gchar **parts = g_strsplit(buf, ";", 3);
4439 gchar *trimmed = parts[0];
4440 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4442 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4443 trimmed[strlen(trimmed)-1] = '\0';
4445 if (!strcmp(trimmed, type)) {
4446 gboolean needsterminal = FALSE;
4447 if (parts[2] && strstr(parts[2], "needsterminal")) {
4448 needsterminal = TRUE;
4450 if (parts[2] && strstr(parts[2], "test=")) {
4451 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
4452 gchar *testcmd = orig_testcmd;
4453 if (strstr(testcmd,";"))
4454 *(strstr(testcmd,";")) = '\0';
4455 while (testcmd[0] == ' ' || testcmd[0] == '\t')
4457 while (testcmd[strlen(testcmd)-1] == '\n')
4458 testcmd[strlen(testcmd)-1] = '\0';
4459 while (testcmd[strlen(testcmd)-1] == '\r')
4460 testcmd[strlen(testcmd)-1] = '\0';
4461 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
4462 testcmd[strlen(testcmd)-1] = '\0';
4464 if (strstr(testcmd, "%s")) {
4465 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
4466 gint res = system(tmp);
4468 g_free(orig_testcmd);
4475 gint res = system(testcmd);
4476 g_free(orig_testcmd);
4486 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4488 while (trimmed[strlen(trimmed)-1] == '\n')
4489 trimmed[strlen(trimmed)-1] = '\0';
4490 while (trimmed[strlen(trimmed)-1] == '\r')
4491 trimmed[strlen(trimmed)-1] = '\0';
4492 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4493 trimmed[strlen(trimmed)-1] = '\0';
4494 result = g_strdup(trimmed);
4497 if (needsterminal) {
4498 gchar *tmp = g_strdup_printf("xterm -e %s", result);
4509 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
4511 gchar *result = NULL;
4515 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4516 result = mailcap_get_command_in_file(path, type, file_to_open);
4520 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
4524 void mailcap_update_default(const gchar *type, const gchar *command)
4526 gchar *path = NULL, *outpath = NULL;
4527 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4528 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
4529 FILE *fp = g_fopen(path, "rb");
4531 gchar buf[BUFFSIZE];
4532 gboolean err = FALSE;
4535 fp = g_fopen(path, "a");
4537 g_warning("failed to create file %s", path);
4542 fp = g_freopen(path, "rb", fp);
4544 g_warning("failed to reopen file %s", path);
4551 outfp = g_fopen(outpath, "wb");
4553 g_warning("failed to create file %s", outpath);
4559 while (fp && fgets(buf, sizeof (buf), fp) != NULL) {
4560 gchar **parts = g_strsplit(buf, ";", 3);
4561 gchar *trimmed = parts[0];
4562 while (trimmed[0] == ' ')
4564 while (trimmed[strlen(trimmed)-1] == ' ')
4565 trimmed[strlen(trimmed)-1] = '\0';
4567 if (!strcmp(trimmed, type)) {
4572 if(fputs(buf, outfp) == EOF) {
4579 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4585 if (safe_fclose(outfp) == EOF)
4589 g_rename(outpath, path);
4595 gint copy_dir(const gchar *src, const gchar *dst)
4600 if ((dir = g_dir_open(src, 0, NULL)) == NULL) {
4601 g_warning("failed to open directory: %s", src);
4605 if (make_dir(dst) < 0)
4608 while ((name = g_dir_read_name(dir)) != NULL) {
4609 gchar *old_file, *new_file;
4610 old_file = g_strconcat(src, G_DIR_SEPARATOR_S, name, NULL);
4611 new_file = g_strconcat(dst, G_DIR_SEPARATOR_S, name, NULL);
4612 debug_print("copying: %s -> %s\n", old_file, new_file);
4613 if (g_file_test(old_file, G_FILE_TEST_IS_REGULAR)) {
4614 gint r = copy_file(old_file, new_file, TRUE);
4621 /* Windows has no symlinks. Or well, Vista seems to
4622 have something like this but the semantics might be
4623 different. Thus we don't use it under Windows. */
4624 else if (g_file_test(old_file, G_FILE_TEST_IS_SYMLINK)) {
4625 GError *error = NULL;
4627 gchar *target = g_file_read_link(old_file, &error);
4629 r = symlink(target, new_file);
4636 #endif /*G_OS_WIN32*/
4637 else if (g_file_test(old_file, G_FILE_TEST_IS_DIR)) {
4638 gint r = copy_dir(old_file, new_file);
4649 /* crude test to see if a file is an email. */
4650 gboolean file_is_email (const gchar *filename)
4656 if (filename == NULL)
4658 if ((fp = g_fopen(filename, "rb")) == NULL)
4660 while (i < 60 && score < 3
4661 && fgets(buffer, sizeof (buffer), fp) != NULL) {
4662 if (!strncmp(buffer, "From:", strlen("From:")))
4664 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4666 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4668 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4673 return (score >= 3);
4676 gboolean sc_g_list_bigger(GList *list, gint max)
4680 while (cur && i <= max+1) {
4687 gboolean sc_g_slist_bigger(GSList *list, gint max)
4691 while (cur && i <= max+1) {
4698 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4699 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4700 NULL, NULL, NULL, NULL, NULL, NULL};
4701 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4702 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4703 NULL, NULL, NULL, NULL, NULL, NULL};
4705 gint daynames_len[] = {0,0,0,0,0,0,0};
4706 gint monthnames_len[] = {0,0,0,0,0,0,
4708 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4709 gint s_monthnames_len[] = {0,0,0,0,0,0,
4711 const gchar *s_am_up = NULL;
4712 const gchar *s_pm_up = NULL;
4713 const gchar *s_am_low = NULL;
4714 const gchar *s_pm_low = NULL;
4716 gint s_am_up_len = 0;
4717 gint s_pm_up_len = 0;
4718 gint s_am_low_len = 0;
4719 gint s_pm_low_len = 0;
4721 static gboolean time_names_init_done = FALSE;
4723 static void init_time_names(void)
4727 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4728 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4729 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4730 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4731 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4732 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4733 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4735 monthnames[0] = C_("Complete month name for use by strftime", "January");
4736 monthnames[1] = C_("Complete month name for use by strftime", "February");
4737 monthnames[2] = C_("Complete month name for use by strftime", "March");
4738 monthnames[3] = C_("Complete month name for use by strftime", "April");
4739 monthnames[4] = C_("Complete month name for use by strftime", "May");
4740 monthnames[5] = C_("Complete month name for use by strftime", "June");
4741 monthnames[6] = C_("Complete month name for use by strftime", "July");
4742 monthnames[7] = C_("Complete month name for use by strftime", "August");
4743 monthnames[8] = C_("Complete month name for use by strftime", "September");
4744 monthnames[9] = C_("Complete month name for use by strftime", "October");
4745 monthnames[10] = C_("Complete month name for use by strftime", "November");
4746 monthnames[11] = C_("Complete month name for use by strftime", "December");
4748 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4749 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4750 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4751 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4752 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4753 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4754 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4756 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4757 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4758 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4759 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4760 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4761 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4762 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4763 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4764 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4765 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4766 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4767 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4769 for (i = 0; i < 7; i++) {
4770 daynames_len[i] = strlen(daynames[i]);
4771 s_daynames_len[i] = strlen(s_daynames[i]);
4773 for (i = 0; i < 12; i++) {
4774 monthnames_len[i] = strlen(monthnames[i]);
4775 s_monthnames_len[i] = strlen(s_monthnames[i]);
4778 s_am_up = C_("For use by strftime (morning)", "AM");
4779 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4780 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4781 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4783 s_am_up_len = strlen(s_am_up);
4784 s_pm_up_len = strlen(s_pm_up);
4785 s_am_low_len = strlen(s_am_low);
4786 s_pm_low_len = strlen(s_pm_low);
4788 time_names_init_done = TRUE;
4791 #define CHECK_SIZE() { \
4792 total_done += len; \
4793 if (total_done >= buflen) { \
4794 buf[buflen-1] = '\0'; \
4799 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4801 gchar *curpos = buf;
4802 gint total_done = 0;
4803 gchar subbuf[64], subfmt[64];
4804 static time_t last_tzset = (time_t)0;
4806 if (!time_names_init_done)
4809 if (format == NULL || lt == NULL)
4812 if (last_tzset != time(NULL)) {
4814 last_tzset = time(NULL);
4817 if (*format == '%') {
4818 gint len = 0, tmp = 0;
4822 len = 1; CHECK_SIZE();
4826 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4827 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4830 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4831 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4835 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4836 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4839 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4840 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4843 strftime(subbuf, 64, "%c", lt);
4844 len = strlen(subbuf); CHECK_SIZE();
4845 strncpy2(curpos, subbuf, buflen - total_done);
4848 total_done += 2; CHECK_SIZE();
4849 tmp = (lt->tm_year + 1900)/100;
4850 *curpos++ = '0'+(tmp / 10);
4851 *curpos++ = '0'+(tmp % 10);
4854 total_done += 2; CHECK_SIZE();
4855 *curpos++ = '0'+(lt->tm_mday / 10);
4856 *curpos++ = '0'+(lt->tm_mday % 10);
4859 total_done += 8; CHECK_SIZE();
4860 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4861 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4863 *curpos++ = '0'+(lt->tm_mday / 10);
4864 *curpos++ = '0'+(lt->tm_mday % 10);
4866 tmp = lt->tm_year%100;
4867 *curpos++ = '0'+(tmp / 10);
4868 *curpos++ = '0'+(tmp % 10);
4871 len = 2; CHECK_SIZE();
4872 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4875 len = 10; CHECK_SIZE();
4876 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4877 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4880 total_done += 2; CHECK_SIZE();
4881 *curpos++ = '0'+(lt->tm_hour / 10);
4882 *curpos++ = '0'+(lt->tm_hour % 10);
4885 total_done += 2; CHECK_SIZE();
4891 *curpos++ = '0'+(tmp / 10);
4892 *curpos++ = '0'+(tmp % 10);
4895 len = 3; CHECK_SIZE();
4896 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4899 len = 2; CHECK_SIZE();
4900 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4903 len = 2; CHECK_SIZE();
4909 snprintf(curpos, buflen - total_done, "%2d", tmp);
4912 total_done += 2; CHECK_SIZE();
4913 tmp = lt->tm_mon + 1;
4914 *curpos++ = '0'+(tmp / 10);
4915 *curpos++ = '0'+(tmp % 10);
4918 total_done += 2; CHECK_SIZE();
4919 *curpos++ = '0'+(lt->tm_min / 10);
4920 *curpos++ = '0'+(lt->tm_min % 10);
4923 len = 1; CHECK_SIZE();
4927 if (lt->tm_hour >= 12) {
4928 len = s_pm_up_len; CHECK_SIZE();
4929 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4931 len = s_am_up_len; CHECK_SIZE();
4932 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4936 if (lt->tm_hour >= 12) {
4937 len = s_pm_low_len; CHECK_SIZE();
4938 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4940 len = s_am_low_len; CHECK_SIZE();
4941 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4945 strftime(subbuf, 64, "%r", lt);
4946 len = strlen(subbuf); CHECK_SIZE();
4947 strncpy2(curpos, subbuf, buflen - total_done);
4950 total_done += 5; CHECK_SIZE();
4951 *curpos++ = '0'+(lt->tm_hour / 10);
4952 *curpos++ = '0'+(lt->tm_hour % 10);
4954 *curpos++ = '0'+(lt->tm_min / 10);
4955 *curpos++ = '0'+(lt->tm_min % 10);
4958 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
4959 len = strlen(subbuf); CHECK_SIZE();
4960 strncpy2(curpos, subbuf, buflen - total_done);
4963 total_done += 2; CHECK_SIZE();
4964 *curpos++ = '0'+(lt->tm_sec / 10);
4965 *curpos++ = '0'+(lt->tm_sec % 10);
4968 len = 1; CHECK_SIZE();
4972 total_done += 8; CHECK_SIZE();
4973 *curpos++ = '0'+(lt->tm_hour / 10);
4974 *curpos++ = '0'+(lt->tm_hour % 10);
4976 *curpos++ = '0'+(lt->tm_min / 10);
4977 *curpos++ = '0'+(lt->tm_min % 10);
4979 *curpos++ = '0'+(lt->tm_sec / 10);
4980 *curpos++ = '0'+(lt->tm_sec % 10);
4983 len = 1; CHECK_SIZE();
4984 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
4987 len = 1; CHECK_SIZE();
4988 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
4991 strftime(subbuf, 64, "%x", lt);
4992 len = strlen(subbuf); CHECK_SIZE();
4993 strncpy2(curpos, subbuf, buflen - total_done);
4996 strftime(subbuf, 64, "%X", lt);
4997 len = strlen(subbuf); CHECK_SIZE();
4998 strncpy2(curpos, subbuf, buflen - total_done);
5001 total_done += 2; CHECK_SIZE();
5002 tmp = lt->tm_year%100;
5003 *curpos++ = '0'+(tmp / 10);
5004 *curpos++ = '0'+(tmp % 10);
5007 len = 4; CHECK_SIZE();
5008 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
5018 /* let these complicated ones be done with the libc */
5019 snprintf(subfmt, 64, "%%%c", *format);
5020 strftime(subbuf, 64, subfmt, lt);
5021 len = strlen(subbuf); CHECK_SIZE();
5022 strncpy2(curpos, subbuf, buflen - total_done);
5026 /* let these complicated modifiers be done with the libc */
5027 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
5028 strftime(subbuf, 64, subfmt, lt);
5029 len = strlen(subbuf); CHECK_SIZE();
5030 strncpy2(curpos, subbuf, buflen - total_done);
5034 g_warning("format error (%c)", *format);
5041 int len = 1; CHECK_SIZE();
5042 *curpos++ = *format++;
5049 gboolean prefs_common_get_use_shred(void);
5053 #define WEXITSTATUS(x) (x)
5056 int claws_unlink(const gchar *filename)
5059 static int found_shred = -1;
5060 static const gchar *args[4];
5062 if (filename == NULL)
5065 if (prefs_common_get_use_shred()) {
5066 if (found_shred == -1) {
5068 args[0] = g_find_program_in_path("shred");
5069 debug_print("found shred: %s\n", args[0]);
5070 found_shred = (args[0] != NULL) ? 1:0;
5074 if (found_shred == 1) {
5075 if (g_stat(filename, &s) == 0 && S_ISREG(s.st_mode)) {
5076 if (s.st_nlink == 1) {
5079 g_spawn_sync(NULL, (gchar **)args, NULL, 0,
5080 NULL, NULL, NULL, NULL, &status, NULL);
5081 debug_print("%s %s exited with status %d\n",
5082 args[0], filename, WEXITSTATUS(status));
5083 if (truncate(filename, 0) < 0)
5084 g_warning("couln't truncate: %s", filename);
5089 return g_unlink(filename);
5092 GMutex *cm_mutex_new(void) {
5093 #if GLIB_CHECK_VERSION(2,32,0)
5094 GMutex *m = g_new0(GMutex, 1);
5098 return g_mutex_new();
5102 void cm_mutex_free(GMutex *mutex) {
5103 #if GLIB_CHECK_VERSION(2,32,0)
5104 g_mutex_clear(mutex);
5107 g_mutex_free(mutex);
5111 static gchar *canonical_list_to_file(GSList *list)
5113 GString *result = g_string_new(NULL);
5114 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
5119 result = g_string_append(result, G_DIR_SEPARATOR_S);
5121 if (pathlist->data) {
5122 const gchar *root = (gchar *)pathlist->data;
5123 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
5125 /* drive - don't prepend dir separator */
5127 result = g_string_append(result, G_DIR_SEPARATOR_S);
5132 for (cur = pathlist; cur; cur = cur->next) {
5133 result = g_string_append(result, (gchar *)cur->data);
5135 result = g_string_append(result, G_DIR_SEPARATOR_S);
5137 g_slist_free(pathlist);
5140 g_string_free(result, FALSE);
5145 static GSList *cm_split_path(const gchar *filename, int depth)
5148 GSList *canonical_parts = NULL;
5152 gboolean follow_symlinks = TRUE;
5159 errno = EINVAL; /* can't happen, no symlink handling */
5164 if (!g_path_is_absolute(filename)) {
5169 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
5171 for (i = 0; path_parts[i] != NULL; i++) {
5172 if (!strcmp(path_parts[i], ""))
5174 if (!strcmp(path_parts[i], "."))
5176 else if (!strcmp(path_parts[i], "..")) {
5181 else /* Remove the last inserted element */
5183 g_slist_delete_link(canonical_parts,
5188 canonical_parts = g_slist_prepend(canonical_parts,
5189 g_strdup(path_parts[i]));
5191 tmp_path = canonical_list_to_file(canonical_parts);
5193 if(g_stat(tmp_path, &st) < 0) {
5194 if (errno == ENOENT) {
5197 follow_symlinks = FALSE;
5202 slist_free_strings_full(canonical_parts);
5203 g_strfreev(path_parts);
5209 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
5210 GError *error = NULL;
5211 gchar *target = g_file_read_link(tmp_path, &error);
5213 if (!g_path_is_absolute(target)) {
5214 /* remove the last inserted element */
5216 g_slist_delete_link(canonical_parts,
5218 /* add the target */
5219 canonical_parts = g_slist_prepend(canonical_parts,
5223 /* and get the new target */
5224 target = canonical_list_to_file(canonical_parts);
5227 /* restart from absolute target */
5228 slist_free_strings_full(canonical_parts);
5229 canonical_parts = NULL;
5231 canonical_parts = cm_split_path(target, depth + 1);
5233 g_error_free(error);
5234 if (canonical_parts == NULL) {
5236 g_strfreev(path_parts);
5245 g_strfreev(path_parts);
5246 return canonical_parts;
5250 * Canonicalize a filename, resolving symlinks along the way.
5251 * Returns a negative errno in case of error.
5253 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
5254 GSList *canonical_parts;
5255 gboolean is_absolute;
5257 if (filename == NULL)
5259 if (canonical_name == NULL)
5261 *canonical_name = NULL;
5263 is_absolute = g_path_is_absolute(filename);
5265 /* Always work on absolute filenames. */
5266 gchar *cur = g_get_current_dir();
5267 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
5270 canonical_parts = cm_split_path(absolute_filename, 0);
5271 g_free(absolute_filename);
5274 canonical_parts = cm_split_path(filename, 0);
5276 if (canonical_parts == NULL)
5279 *canonical_name = canonical_list_to_file(canonical_parts);
5280 slist_free_strings_full(canonical_parts);
5284 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
5285 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
5287 gchar *tmp = g_base64_decode(text, out_len);
5288 gchar *out = g_strndup(tmp, *out_len);
5292 if (strlen(out) != *out_len) {
5293 g_warning ("strlen(out) %zd != *out_len %" G_GSIZE_FORMAT, strlen(out), *out_len);
5299 #if !GLIB_CHECK_VERSION(2, 30, 0)
5302 * @str: a UTF-8 encoded string
5303 * @start_pos: a character offset within @str
5304 * @end_pos: another character offset within @str
5306 * Copies a substring out of a UTF-8 encoded string.
5307 * The substring will contain @end_pos - @start_pos
5310 * Returns: a newly allocated copy of the requested
5311 * substring. Free with g_free() when no longer needed.
5316 g_utf8_substring (const gchar *str,
5320 gchar *start, *end, *out;
5322 start = g_utf8_offset_to_pointer (str, start_pos);
5323 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
5325 out = g_malloc (end - start + 1);
5326 memcpy (out, start, end - start);
5327 out[end - start] = 0;
5333 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
5334 * It is up to the caller to make sure there is at least count bytes
5335 * available at buf. */
5337 get_random_bytes(void *buf, size_t count)
5339 /* Open our prng source. */
5340 #if defined G_OS_WIN32
5343 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
5344 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
5345 debug_print("Could not acquire a CSP handle.\n");
5352 rnd = open("/dev/urandom", O_RDONLY);
5354 FILE_OP_ERROR("/dev/urandom", "open");
5355 debug_print("Could not open /dev/urandom.\n");
5360 /* Read data from the source into buf. */
5361 #if defined G_OS_WIN32
5362 if (!CryptGenRandom(rnd, count, buf)) {
5363 debug_print("Could not read %zd random bytes.\n", count);
5364 CryptReleaseContext(rnd, 0);
5368 ret = read(rnd, buf, count);
5370 FILE_OP_ERROR("/dev/urandom", "read");
5371 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
5377 /* Close the prng source. */
5378 #if defined G_OS_WIN32
5379 CryptReleaseContext(rnd, 0);