2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2015 Hiroyuki Yamamoto & The Claws Mail Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 * The code of the g_utf8_substring function below is owned by
19 * Matthias Clasen <matthiasc@src.gnome.org>/<mclasen@redhat.com>
20 * and is got from GLIB 2.30: https://git.gnome.org/browse/glib/commit/
21 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
23 * GLib 2.30 is licensed under GPL v2 or later and:
24 * Copyright (C) 1999 Tom Tromey
25 * Copyright (C) 2000 Red Hat, Inc.
27 * https://git.gnome.org/browse/glib/tree/glib/gutf8.c
28 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
33 #include "claws-features.h"
41 #include <glib/gi18n.h>
51 #include <sys/param.h>
53 #include <sys/socket.h>
56 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
64 #include <sys/types.h>
66 # include <sys/wait.h>
73 #include <sys/utsname.h>
86 #include "../codeconv.h"
91 static gboolean debug_mode = FALSE;
93 static GSList *tempfiles=NULL;
96 #if !GLIB_CHECK_VERSION(2, 26, 0)
97 guchar *g_base64_decode_wa(const gchar *text, gsize *out_len)
104 input_length = strlen(text);
106 ret = g_malloc0((input_length / 4) * 3 + 1);
108 *out_len = g_base64_decode_step(text, input_length, ret, &state, &save);
114 /* Return true if we are running as root. This function should beused
115 instead of getuid () == 0. */
116 gboolean superuser_p (void)
119 return w32_is_administrator ();
125 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
127 #if GLIB_CHECK_VERSION(2, 34, 0)
128 return g_slist_copy_deep(list, func, NULL);
130 GSList *res = g_slist_copy(list);
133 walk->data = func(walk->data, NULL);
140 void list_free_strings(GList *list)
142 list = g_list_first(list);
144 while (list != NULL) {
150 void slist_free_strings(GSList *list)
152 while (list != NULL) {
158 void slist_free_strings_full(GSList *list)
160 #if GLIB_CHECK_VERSION(2,28,0)
161 g_slist_free_full(list, (GDestroyNotify)g_free);
163 g_slist_foreach(list, (GFunc)g_free, NULL);
168 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
173 void hash_free_strings(GHashTable *table)
175 g_hash_table_foreach(table, hash_free_strings_func, NULL);
178 gint str_case_equal(gconstpointer v, gconstpointer v2)
180 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
183 guint str_case_hash(gconstpointer key)
185 const gchar *p = key;
189 h = g_ascii_tolower(h);
190 for (p += 1; *p != '\0'; p++)
191 h = (h << 5) - h + g_ascii_tolower(*p);
197 void ptr_array_free_strings(GPtrArray *array)
202 cm_return_if_fail(array != NULL);
204 for (i = 0; i < array->len; i++) {
205 str = g_ptr_array_index(array, i);
210 gint to_number(const gchar *nstr)
212 register const gchar *p;
214 if (*nstr == '\0') return -1;
216 for (p = nstr; *p != '\0'; p++)
217 if (!g_ascii_isdigit(*p)) return -1;
222 /* convert integer into string,
223 nstr must be not lower than 11 characters length */
224 gchar *itos_buf(gchar *nstr, gint n)
226 g_snprintf(nstr, 11, "%d", n);
230 /* convert integer into string */
233 static gchar nstr[11];
235 return itos_buf(nstr, n);
238 #define divide(num,divisor,i,d) \
240 i = num >> divisor; \
241 d = num & ((1<<divisor)-1); \
242 d = (d*100) >> divisor; \
247 * \brief Convert a given size in bytes in a human-readable string
249 * \param size The size expressed in bytes to convert in string
250 * \return The string that respresents the size in an human-readable way
252 gchar *to_human_readable(goffset size)
254 static gchar str[14];
255 static gchar *b_format = NULL, *kb_format = NULL,
256 *mb_format = NULL, *gb_format = NULL;
257 register int t = 0, r = 0;
258 if (b_format == NULL) {
260 kb_format = _("%d.%02dKB");
261 mb_format = _("%d.%02dMB");
262 gb_format = _("%.2fGB");
265 if (size < (goffset)1024) {
266 g_snprintf(str, sizeof(str), b_format, (gint)size);
268 } else if (size >> 10 < (goffset)1024) {
269 divide(size, 10, t, r);
270 g_snprintf(str, sizeof(str), kb_format, t, r);
272 } else if (size >> 20 < (goffset)1024) {
273 divide(size, 20, t, r);
274 g_snprintf(str, sizeof(str), mb_format, t, r);
277 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
282 /* strcmp with NULL-checking */
283 gint strcmp2(const gchar *s1, const gchar *s2)
285 if (s1 == NULL || s2 == NULL)
288 return strcmp(s1, s2);
290 /* strstr with NULL-checking */
291 gchar *strstr2(const gchar *s1, const gchar *s2)
293 if (s1 == NULL || s2 == NULL)
296 return strstr(s1, s2);
299 gint path_cmp(const gchar *s1, const gchar *s2)
304 gchar *s1buf, *s2buf;
307 if (s1 == NULL || s2 == NULL) return -1;
308 if (*s1 == '\0' || *s2 == '\0') return -1;
311 s1buf = g_strdup (s1);
312 s2buf = g_strdup (s2);
313 subst_char (s1buf, '/', G_DIR_SEPARATOR);
314 subst_char (s2buf, '/', G_DIR_SEPARATOR);
317 #endif /* !G_OS_WIN32 */
322 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
323 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
325 rc = strncmp(s1, s2, MAX(len1, len2));
329 #endif /* !G_OS_WIN32 */
333 /* remove trailing return code */
334 gchar *strretchomp(gchar *str)
338 if (!*str) return str;
340 for (s = str + strlen(str) - 1;
341 s >= str && (*s == '\n' || *s == '\r');
348 /* remove trailing character */
349 gchar *strtailchomp(gchar *str, gchar tail_char)
353 if (!*str) return str;
354 if (tail_char == '\0') return str;
356 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
362 /* remove CR (carriage return) */
363 gchar *strcrchomp(gchar *str)
367 if (!*str) return str;
369 s = str + strlen(str) - 1;
370 if (*s == '\n' && s > str && *(s - 1) == '\r') {
378 gint file_strip_crs(const gchar *file)
380 FILE *fp = NULL, *outfp = NULL;
382 gchar *out = get_tmp_file();
386 fp = g_fopen(file, "rb");
390 outfp = g_fopen(out, "wb");
396 while (fgets(buf, sizeof (buf), fp) != NULL) {
398 if (fputs(buf, outfp) == EOF) {
406 if (fclose(outfp) == EOF) {
410 if (move_file(out, file, TRUE) < 0)
422 /* Similar to `strstr' but this function ignores the case of both strings. */
423 gchar *strcasestr(const gchar *haystack, const gchar *needle)
425 size_t haystack_len = strlen(haystack);
427 return strncasestr(haystack, haystack_len, needle);
430 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
432 register size_t needle_len;
434 needle_len = strlen(needle);
436 if (haystack_len < needle_len || needle_len == 0)
439 while (haystack_len >= needle_len) {
440 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
441 return (gchar *)haystack;
451 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
452 gconstpointer needle, size_t needlelen)
454 const gchar *haystack_ = (const gchar *)haystack;
455 const gchar *needle_ = (const gchar *)needle;
456 const gchar *haystack_cur = (const gchar *)haystack;
457 size_t haystack_left = haystacklen;
460 return memchr(haystack_, *needle_, haystacklen);
462 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
464 if (haystacklen - (haystack_cur - haystack_) < needlelen)
466 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
467 return (gpointer)haystack_cur;
470 haystack_left = haystacklen - (haystack_cur - haystack_);
477 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
478 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
480 register const gchar *s = src;
481 register gchar *d = dest;
491 /* Examine if next block is non-ASCII string */
492 gboolean is_next_nonascii(const gchar *s)
496 /* skip head space */
497 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
499 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
500 if (*(guchar *)p > 127 || *(guchar *)p < 32)
507 gint get_next_word_len(const gchar *s)
511 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
517 static void trim_subject_for_compare(gchar *str)
521 eliminate_parenthesis(str, '[', ']');
522 eliminate_parenthesis(str, '(', ')');
525 srcp = str + subject_get_prefix_length(str);
527 memmove(str, srcp, strlen(srcp) + 1);
530 static void trim_subject_for_sort(gchar *str)
536 srcp = str + subject_get_prefix_length(str);
538 memmove(str, srcp, strlen(srcp) + 1);
541 /* compare subjects */
542 gint subject_compare(const gchar *s1, const gchar *s2)
546 if (!s1 || !s2) return -1;
547 if (!*s1 || !*s2) return -1;
549 Xstrdup_a(str1, s1, return -1);
550 Xstrdup_a(str2, s2, return -1);
552 trim_subject_for_compare(str1);
553 trim_subject_for_compare(str2);
555 if (!*str1 || !*str2) return -1;
557 return strcmp(str1, str2);
560 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
564 if (!s1 || !s2) return -1;
566 Xstrdup_a(str1, s1, return -1);
567 Xstrdup_a(str2, s2, return -1);
569 trim_subject_for_sort(str1);
570 trim_subject_for_sort(str2);
572 return g_utf8_collate(str1, str2);
575 void trim_subject(gchar *str)
577 register gchar *srcp;
583 srcp = str + subject_get_prefix_length(str);
588 } else if (*srcp == '(') {
600 else if (*srcp == cl)
607 while (g_ascii_isspace(*srcp)) srcp++;
608 memmove(str, srcp, strlen(srcp) + 1);
611 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
613 register gchar *srcp, *destp;
618 while ((destp = strchr(destp, op))) {
624 else if (*srcp == cl)
630 while (g_ascii_isspace(*srcp)) srcp++;
631 memmove(destp, srcp, strlen(srcp) + 1);
635 void extract_parenthesis(gchar *str, gchar op, gchar cl)
637 register gchar *srcp, *destp;
642 while ((srcp = strchr(destp, op))) {
645 memmove(destp, srcp + 1, strlen(srcp));
650 else if (*destp == cl)
662 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
665 register gchar *srcp, *destp;
667 gboolean in_quote = FALSE;
671 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
674 memmove(destp, srcp + 1, strlen(srcp));
677 if (*destp == op && !in_quote)
679 else if (*destp == cl && !in_quote)
681 else if (*destp == quote_chr)
693 void extract_quote(gchar *str, gchar quote_chr)
697 if ((str = strchr(str, quote_chr))) {
699 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
700 memmove(p - 1, p, strlen(p) + 1);
705 memmove(str, str + 1, p - str);
710 /* Returns a newly allocated string with all quote_chr not at the beginning
711 or the end of str escaped with '\' or the given str if not required. */
712 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
714 register gchar *p, *q;
718 if (str == NULL || *str == '\0')
721 /* search for unescaped quote_chr */
726 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
730 if (!k) /* nothing to escape */
733 /* unescaped quote_chr found */
734 qstr = g_malloc(l + k + 1);
737 if (*p == quote_chr) {
742 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
751 void eliminate_address_comment(gchar *str)
753 register gchar *srcp, *destp;
758 while ((destp = strchr(destp, '"'))) {
759 if ((srcp = strchr(destp + 1, '"'))) {
764 while (g_ascii_isspace(*srcp)) srcp++;
765 memmove(destp, srcp, strlen(srcp) + 1);
775 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
781 else if (*srcp == ')')
787 while (g_ascii_isspace(*srcp)) srcp++;
788 memmove(destp, srcp, strlen(srcp) + 1);
792 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
794 gboolean in_quote = FALSE;
797 if (*str == c && !in_quote)
799 if (*str == quote_chr)
807 void extract_address(gchar *str)
809 cm_return_if_fail(str != NULL);
810 eliminate_address_comment(str);
811 if (strchr_with_skip_quote(str, '"', '<'))
812 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
816 void extract_list_id_str(gchar *str)
818 if (strchr_with_skip_quote(str, '"', '<'))
819 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
823 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
828 if (!str) return addr_list;
830 Xstrdup_a(work, str, return addr_list);
833 eliminate_address_comment(work);
836 while (workp && *workp) {
839 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
845 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
846 extract_parenthesis_with_skip_quote
847 (workp, '"', '<', '>');
851 addr_list = g_slist_append(addr_list, g_strdup(workp));
859 GSList *address_list_append(GSList *addr_list, const gchar *str)
861 return address_list_append_real(addr_list, str, TRUE);
864 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
866 return address_list_append_real(addr_list, str, FALSE);
869 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
873 if (!str) return msgid_list;
876 while (strp && *strp) {
877 const gchar *start, *end;
880 if ((start = strchr(strp, '<')) != NULL) {
881 end = strchr(start + 1, '>');
886 msgid = g_strndup(start + 1, end - start - 1);
889 msgid_list = g_slist_prepend(msgid_list, msgid);
899 GSList *references_list_append(GSList *msgid_list, const gchar *str)
903 list = references_list_prepend(NULL, str);
904 list = g_slist_reverse(list);
905 msgid_list = g_slist_concat(msgid_list, list);
910 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
915 if (!str) return group_list;
917 Xstrdup_a(work, str, return group_list);
921 while (workp && *workp) {
924 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
932 group_list = g_slist_append(group_list,
941 GList *add_history(GList *list, const gchar *str)
946 cm_return_val_if_fail(str != NULL, list);
948 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
951 list = g_list_remove(list, old->data);
953 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
956 last = g_list_last(list);
959 list = g_list_remove(list, last->data);
964 list = g_list_prepend(list, g_strdup(str));
969 void remove_return(gchar *str)
971 register gchar *p = str;
974 if (*p == '\n' || *p == '\r')
975 memmove(p, p + 1, strlen(p));
981 void remove_space(gchar *str)
983 register gchar *p = str;
988 while (g_ascii_isspace(*(p + spc)))
991 memmove(p, p + spc, strlen(p + spc) + 1);
997 void unfold_line(gchar *str)
999 register gchar *p = str;
1003 if (*p == '\n' || *p == '\r') {
1006 while (g_ascii_isspace(*(p + spc)))
1009 memmove(p, p + spc, strlen(p + spc) + 1);
1015 void subst_char(gchar *str, gchar orig, gchar subst)
1017 register gchar *p = str;
1026 void subst_chars(gchar *str, gchar *orig, gchar subst)
1028 register gchar *p = str;
1031 if (strchr(orig, *p) != NULL)
1037 void subst_for_filename(gchar *str)
1042 subst_chars(str, "\t\r\n\\/*:", '_');
1044 subst_chars(str, "\t\r\n\\/*", '_');
1048 void subst_for_shellsafe_filename(gchar *str)
1052 subst_for_filename(str);
1053 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1056 gboolean is_ascii_str(const gchar *str)
1058 const guchar *p = (const guchar *)str;
1060 while (*p != '\0') {
1061 if (*p != '\t' && *p != ' ' &&
1062 *p != '\r' && *p != '\n' &&
1063 (*p < 32 || *p >= 127))
1071 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1073 gchar * position = NULL;
1074 gchar * tmp_pos = NULL;
1077 if (quote_chars == NULL)
1080 for (i = 0; i < strlen(quote_chars); i++) {
1081 tmp_pos = strrchr (str, quote_chars[i]);
1083 || (tmp_pos != NULL && position <= tmp_pos) )
1089 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1091 const gchar *first_pos;
1092 const gchar *last_pos;
1093 const gchar *p = str;
1094 gint quote_level = -1;
1096 /* speed up line processing by only searching to the last '>' */
1097 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1098 /* skip a line if it contains a '<' before the initial '>' */
1099 if (memchr(str, '<', first_pos - str) != NULL)
1101 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1105 while (p <= last_pos) {
1106 while (p < last_pos) {
1107 if (g_ascii_isspace(*p))
1113 if (strchr(quote_chars, *p))
1115 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1116 /* any characters are allowed except '-','<' and space */
1117 while (*p != '-' && *p != '<'
1118 && !strchr(quote_chars, *p)
1119 && !g_ascii_isspace(*p)
1122 if (strchr(quote_chars, *p))
1134 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1136 const gchar *p = str, *q;
1137 gint cur_line = 0, len;
1139 while ((q = strchr(p, '\n')) != NULL) {
1141 if (len > max_chars) {
1151 if (len > max_chars) {
1160 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1162 gchar * position = NULL;
1163 gchar * tmp_pos = NULL;
1166 if (quote_chars == NULL)
1169 for (i = 0; i < strlen(quote_chars); i++) {
1170 tmp_pos = strchr (str, quote_chars[i]);
1172 || (tmp_pos != NULL && position >= tmp_pos) )
1178 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1180 register guint haystack_len, needle_len;
1181 gboolean in_squote = FALSE, in_dquote = FALSE;
1183 haystack_len = strlen(haystack);
1184 needle_len = strlen(needle);
1186 if (haystack_len < needle_len || needle_len == 0)
1189 while (haystack_len >= needle_len) {
1190 if (!in_squote && !in_dquote &&
1191 !strncmp(haystack, needle, needle_len))
1192 return (gchar *)haystack;
1194 /* 'foo"bar"' -> foo"bar"
1195 "foo'bar'" -> foo'bar' */
1196 if (*haystack == '\'') {
1199 else if (!in_dquote)
1201 } else if (*haystack == '\"') {
1204 else if (!in_squote)
1206 } else if (*haystack == '\\') {
1218 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1221 GSList *string_list = NULL, *slist;
1222 gchar **str_array, *s, *new_str;
1223 guint i, n = 1, len;
1225 cm_return_val_if_fail(str != NULL, NULL);
1226 cm_return_val_if_fail(delim != NULL, NULL);
1229 max_tokens = G_MAXINT;
1231 s = strstr_with_skip_quote(str, delim);
1233 guint delimiter_len = strlen(delim);
1237 new_str = g_strndup(str, len);
1239 if (new_str[0] == '\'' || new_str[0] == '\"') {
1240 if (new_str[len - 1] == new_str[0]) {
1241 new_str[len - 1] = '\0';
1242 memmove(new_str, new_str + 1, len - 1);
1245 string_list = g_slist_prepend(string_list, new_str);
1247 str = s + delimiter_len;
1248 s = strstr_with_skip_quote(str, delim);
1249 } while (--max_tokens && s);
1253 new_str = g_strdup(str);
1254 if (new_str[0] == '\'' || new_str[0] == '\"') {
1256 if (new_str[len - 1] == new_str[0]) {
1257 new_str[len - 1] = '\0';
1258 memmove(new_str, new_str + 1, len - 1);
1261 string_list = g_slist_prepend(string_list, new_str);
1265 str_array = g_new(gchar*, n);
1269 str_array[i--] = NULL;
1270 for (slist = string_list; slist; slist = slist->next)
1271 str_array[i--] = slist->data;
1273 g_slist_free(string_list);
1278 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1280 gchar *abbrev_group;
1282 const gchar *p = group;
1285 cm_return_val_if_fail(group != NULL, NULL);
1287 last = group + strlen(group);
1288 abbrev_group = ap = g_malloc(strlen(group) + 1);
1293 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1295 while (*p != '.') p++;
1298 return abbrev_group;
1303 return abbrev_group;
1306 gchar *trim_string(const gchar *str, gint len)
1308 const gchar *p = str;
1313 if (!str) return NULL;
1314 if (strlen(str) <= len)
1315 return g_strdup(str);
1316 if (g_utf8_validate(str, -1, NULL) == FALSE)
1317 return g_strdup(str);
1319 while (*p != '\0') {
1320 mb_len = g_utf8_skip[*(guchar *)p];
1323 else if (new_len + mb_len > len)
1330 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1331 return g_strconcat(new_str, "...", NULL);
1334 GList *uri_list_extract_filenames(const gchar *uri_list)
1336 GList *result = NULL;
1338 gchar *escaped_utf8uri;
1344 while (g_ascii_isspace(*p)) p++;
1345 if (!strncmp(p, "file:", 5)) {
1348 while (*q && *q != '\n' && *q != '\r') q++;
1351 gchar *file, *locale_file = NULL;
1353 while (q > p && g_ascii_isspace(*q))
1355 Xalloca(escaped_utf8uri, q - p + 2,
1357 Xalloca(file, q - p + 2,
1360 strncpy(escaped_utf8uri, p, q - p + 1);
1361 escaped_utf8uri[q - p + 1] = '\0';
1362 decode_uri(file, escaped_utf8uri);
1364 * g_filename_from_uri() rejects escaped/locale encoded uri
1365 * string which come from Nautilus.
1368 if (g_utf8_validate(file, -1, NULL))
1370 = conv_codeset_strdup(
1373 conv_get_locale_charset_str());
1375 locale_file = g_strdup(file + 5);
1377 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1379 result = g_list_append(result, locale_file);
1383 p = strchr(p, '\n');
1390 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1393 static gint axtoi(const gchar *hexstr)
1395 gint hi, lo, result;
1398 if ('0' <= hi && hi <= '9') {
1401 if ('a' <= hi && hi <= 'f') {
1404 if ('A' <= hi && hi <= 'F') {
1409 if ('0' <= lo && lo <= '9') {
1412 if ('a' <= lo && lo <= 'f') {
1415 if ('A' <= lo && lo <= 'F') {
1418 result = lo + (16 * hi);
1422 gboolean is_uri_string(const gchar *str)
1424 while (str && *str && g_ascii_isspace(*str))
1426 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1427 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1428 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1429 g_ascii_strncasecmp(str, "www.", 4) == 0);
1432 gchar *get_uri_path(const gchar *uri)
1434 while (uri && *uri && g_ascii_isspace(*uri))
1436 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1437 return (gchar *)(uri + 7);
1438 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1439 return (gchar *)(uri + 8);
1440 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1441 return (gchar *)(uri + 6);
1443 return (gchar *)uri;
1446 gint get_uri_len(const gchar *str)
1450 if (is_uri_string(str)) {
1451 for (p = str; *p != '\0'; p++) {
1452 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1461 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1462 * plusses, and escape characters are used)
1464 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1466 gchar *dec = decoded_uri;
1467 const gchar *enc = encoded_uri;
1472 if (isxdigit((guchar)enc[0]) &&
1473 isxdigit((guchar)enc[1])) {
1479 if (with_plus && *enc == '+')
1491 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1493 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1496 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1498 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1499 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1503 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1504 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1508 const gchar *forbidden_uris[] = { ".gnupg/",
1514 gint num_attach = 0;
1515 gchar **my_att = NULL;
1517 Xstrdup_a(tmp_mailto, mailto, return -1);
1519 if (!strncmp(tmp_mailto, "mailto:", 7))
1522 p = strchr(tmp_mailto, '?');
1529 *to = decode_uri_gdup(tmp_mailto);
1531 my_att = g_malloc(sizeof(char *));
1535 gchar *field, *value;
1552 if (*value == '\0') continue;
1554 if (from && !g_ascii_strcasecmp(field, "from")) {
1556 *from = decode_uri_gdup(value);
1558 gchar *tmp = decode_uri_gdup(value);
1559 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1563 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1565 *cc = decode_uri_gdup(value);
1567 gchar *tmp = decode_uri_gdup(value);
1568 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1572 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1574 *bcc = decode_uri_gdup(value);
1576 gchar *tmp = decode_uri_gdup(value);
1577 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1581 } else if (subject && !*subject &&
1582 !g_ascii_strcasecmp(field, "subject")) {
1583 *subject = decode_uri_gdup(value);
1584 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1585 *body = decode_uri_gdup(value);
1586 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1587 gchar *tmp = decode_uri_gdup(value);
1588 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1589 g_warning("couldn't set insert file '%s' in body", value);
1593 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1595 gchar *tmp = decode_uri_gdup(value);
1596 for (; forbidden_uris[i]; i++) {
1597 if (strstr(tmp, forbidden_uris[i])) {
1598 g_print("Refusing to attach '%s', potential private data leak\n",
1606 /* attach is correct */
1608 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1609 my_att[num_attach-1] = tmp;
1610 my_att[num_attach] = NULL;
1612 } else if (inreplyto && !*inreplyto &&
1613 !g_ascii_strcasecmp(field, "in-reply-to")) {
1614 *inreplyto = decode_uri_gdup(value);
1625 #include <windows.h>
1626 #ifndef CSIDL_APPDATA
1627 #define CSIDL_APPDATA 0x001a
1629 #ifndef CSIDL_LOCAL_APPDATA
1630 #define CSIDL_LOCAL_APPDATA 0x001c
1632 #ifndef CSIDL_FLAG_CREATE
1633 #define CSIDL_FLAG_CREATE 0x8000
1635 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1639 w32_strerror (int w32_errno)
1641 static char strerr[256];
1642 int ec = (int)GetLastError ();
1646 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1647 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1648 strerr, DIM (strerr)-1, NULL);
1652 static __inline__ void *
1653 dlopen (const char * name, int flag)
1655 void * hd = LoadLibrary (name);
1659 static __inline__ void *
1660 dlsym (void * hd, const char * sym)
1664 void * fnc = GetProcAddress (hd, sym);
1673 static __inline__ const char *
1676 return w32_strerror (0);
1680 static __inline__ int
1692 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1694 static int initialized;
1695 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1699 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1705 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1707 handle = dlopen (dllnames[i], RTLD_LAZY);
1710 func = dlsym (handle, "SHGetFolderPathW");
1721 return func (a,b,c,d,e);
1726 /* Returns a static string with the directroy from which the module
1727 has been loaded. Returns an empty string on error. */
1728 static char *w32_get_module_dir(void)
1730 static char *moddir;
1733 char name[MAX_PATH+10];
1736 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1739 p = strrchr (name, '\\');
1745 moddir = g_strdup (name);
1749 #endif /* G_OS_WIN32 */
1751 /* Return a static string with the locale dir. */
1752 const gchar *get_locale_dir(void)
1754 static gchar *loc_dir;
1758 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1759 "\\share\\locale", NULL);
1762 loc_dir = LOCALEDIR;
1768 const gchar *get_home_dir(void)
1771 static char home_dir_utf16[MAX_PATH] = "";
1772 static gchar *home_dir_utf8 = NULL;
1773 if (home_dir_utf16[0] == '\0') {
1774 if (w32_shgetfolderpath
1775 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1776 NULL, 0, home_dir_utf16) < 0)
1777 strcpy (home_dir_utf16, "C:\\Sylpheed");
1778 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar *)home_dir_utf16, -1, NULL, NULL, NULL);
1780 return home_dir_utf8;
1782 static const gchar *homeenv = NULL;
1787 if (!homeenv && g_getenv("HOME") != NULL)
1788 homeenv = g_strdup(g_getenv("HOME"));
1790 homeenv = g_get_home_dir();
1796 static gchar *claws_rc_dir = NULL;
1797 static gboolean rc_dir_alt = FALSE;
1798 const gchar *get_rc_dir(void)
1801 if (!claws_rc_dir) {
1802 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1804 debug_print("using default rc_dir %s\n", claws_rc_dir);
1806 return claws_rc_dir;
1809 void set_rc_dir(const gchar *dir)
1811 gchar *canonical_dir;
1812 if (claws_rc_dir != NULL) {
1813 g_print("Error: rc_dir already set\n");
1815 int err = cm_canonicalize_filename(dir, &canonical_dir);
1819 g_print("Error looking for %s: %d(%s)\n",
1820 dir, -err, g_strerror(-err));
1825 claws_rc_dir = canonical_dir;
1827 len = strlen(claws_rc_dir);
1828 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1829 claws_rc_dir[len - 1] = '\0';
1831 debug_print("set rc_dir to %s\n", claws_rc_dir);
1832 if (!is_dir_exist(claws_rc_dir)) {
1833 if (make_dir_hier(claws_rc_dir) != 0) {
1834 g_print("Error: can't create %s\n",
1842 gboolean rc_dir_is_alt(void) {
1846 const gchar *get_mail_base_dir(void)
1848 return get_home_dir();
1851 const gchar *get_news_cache_dir(void)
1853 static gchar *news_cache_dir = NULL;
1854 if (!news_cache_dir)
1855 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1856 NEWS_CACHE_DIR, NULL);
1858 return news_cache_dir;
1861 const gchar *get_imap_cache_dir(void)
1863 static gchar *imap_cache_dir = NULL;
1865 if (!imap_cache_dir)
1866 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1867 IMAP_CACHE_DIR, NULL);
1869 return imap_cache_dir;
1872 const gchar *get_mime_tmp_dir(void)
1874 static gchar *mime_tmp_dir = NULL;
1877 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1878 MIME_TMP_DIR, NULL);
1880 return mime_tmp_dir;
1883 const gchar *get_template_dir(void)
1885 static gchar *template_dir = NULL;
1888 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1889 TEMPLATE_DIR, NULL);
1891 return template_dir;
1895 const gchar *w32_get_cert_file(void)
1897 const gchar *cert_file = NULL;
1899 cert_file = g_strconcat(w32_get_module_dir(),
1900 "\\share\\claws-mail\\",
1901 "ca-certificates.crt",
1907 /* Return the filepath of the claws-mail.desktop file */
1908 const gchar *get_desktop_file(void)
1910 #ifdef DESKTOPFILEPATH
1911 return DESKTOPFILEPATH;
1917 /* Return the default directory for Plugins. */
1918 const gchar *get_plugin_dir(void)
1921 static gchar *plugin_dir = NULL;
1924 plugin_dir = g_strconcat(w32_get_module_dir(),
1925 "\\lib\\claws-mail\\plugins\\",
1929 if (is_dir_exist(PLUGINDIR))
1932 static gchar *plugin_dir = NULL;
1934 plugin_dir = g_strconcat(get_rc_dir(),
1935 G_DIR_SEPARATOR_S, "plugins",
1936 G_DIR_SEPARATOR_S, NULL);
1944 /* Return the default directory for Themes. */
1945 const gchar *w32_get_themes_dir(void)
1947 static gchar *themes_dir = NULL;
1950 themes_dir = g_strconcat(w32_get_module_dir(),
1951 "\\share\\claws-mail\\themes",
1957 const gchar *get_tmp_dir(void)
1959 static gchar *tmp_dir = NULL;
1962 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1968 gchar *get_tmp_file(void)
1971 static guint32 id = 0;
1973 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1974 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1979 const gchar *get_domain_name(void)
1982 static gchar *domain_name = NULL;
1983 struct addrinfo hints, *res;
1988 if (gethostname(hostname, sizeof(hostname)) != 0) {
1989 perror("gethostname");
1990 domain_name = "localhost";
1992 memset(&hints, 0, sizeof(struct addrinfo));
1993 hints.ai_family = AF_UNSPEC;
1994 hints.ai_socktype = 0;
1995 hints.ai_flags = AI_CANONNAME;
1996 hints.ai_protocol = 0;
1998 s = getaddrinfo(hostname, NULL, &hints, &res);
2000 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
2001 domain_name = g_strdup(hostname);
2003 domain_name = g_strdup(res->ai_canonname);
2007 debug_print("domain name = %s\n", domain_name);
2016 off_t get_file_size(const gchar *file)
2020 if (g_stat(file, &s) < 0) {
2021 FILE_OP_ERROR(file, "stat");
2028 time_t get_file_mtime(const gchar *file)
2032 if (g_stat(file, &s) < 0) {
2033 FILE_OP_ERROR(file, "stat");
2040 off_t get_file_size_as_crlf(const gchar *file)
2044 gchar buf[BUFFSIZE];
2046 if ((fp = g_fopen(file, "rb")) == NULL) {
2047 FILE_OP_ERROR(file, "g_fopen");
2051 while (fgets(buf, sizeof(buf), fp) != NULL) {
2053 size += strlen(buf) + 2;
2057 FILE_OP_ERROR(file, "fgets");
2066 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2073 if (g_stat(file, &s) < 0) {
2074 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2078 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2085 /* Test on whether FILE is a relative file name. This is
2086 * straightforward for Unix but more complex for Windows. */
2087 gboolean is_relative_filename(const gchar *file)
2092 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2093 return FALSE; /* Prefixed with a hostname - this can't
2094 * be a relative name. */
2096 if ( ((*file >= 'a' && *file <= 'z')
2097 || (*file >= 'A' && *file <= 'Z'))
2099 file += 2; /* Skip drive letter. */
2101 return !(*file == '\\' || *file == '/');
2103 return !(*file == G_DIR_SEPARATOR);
2108 gboolean is_dir_exist(const gchar *dir)
2113 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2116 gboolean is_file_entry_exist(const gchar *file)
2121 return g_file_test(file, G_FILE_TEST_EXISTS);
2124 gboolean dirent_is_regular_file(struct dirent *d)
2126 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2127 if (d->d_type == DT_REG)
2129 else if (d->d_type != DT_UNKNOWN)
2133 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2136 gint change_dir(const gchar *dir)
2138 gchar *prevdir = NULL;
2141 prevdir = g_get_current_dir();
2143 if (g_chdir(dir) < 0) {
2144 FILE_OP_ERROR(dir, "chdir");
2145 if (debug_mode) g_free(prevdir);
2147 } else if (debug_mode) {
2150 cwd = g_get_current_dir();
2151 if (strcmp(prevdir, cwd) != 0)
2152 g_print("current dir: %s\n", cwd);
2160 gint make_dir(const gchar *dir)
2162 if (g_mkdir(dir, S_IRWXU) < 0) {
2163 FILE_OP_ERROR(dir, "mkdir");
2166 if (g_chmod(dir, S_IRWXU) < 0)
2167 FILE_OP_ERROR(dir, "chmod");
2172 gint make_dir_hier(const gchar *dir)
2177 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2178 parent_dir = g_strndup(dir, p - dir);
2179 if (*parent_dir != '\0') {
2180 if (!is_dir_exist(parent_dir)) {
2181 if (make_dir(parent_dir) < 0) {
2190 if (!is_dir_exist(dir)) {
2191 if (make_dir(dir) < 0)
2198 gint remove_all_files(const gchar *dir)
2201 const gchar *file_name;
2204 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2205 g_warning("failed to open directory: %s", dir);
2209 while ((file_name = g_dir_read_name(dp)) != NULL) {
2210 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2211 if (claws_unlink(tmp) < 0)
2212 FILE_OP_ERROR(tmp, "unlink");
2221 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2224 const gchar *dir_name;
2228 if (first == last) {
2229 /* Skip all the dir reading part. */
2230 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2231 if (is_dir_exist(filename)) {
2232 /* a numbered directory with this name exists,
2233 * remove the dot-file instead */
2235 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2237 if (claws_unlink(filename) < 0) {
2238 FILE_OP_ERROR(filename, "unlink");
2246 prev_dir = g_get_current_dir();
2248 if (g_chdir(dir) < 0) {
2249 FILE_OP_ERROR(dir, "chdir");
2254 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2255 g_warning("failed to open directory: %s", dir);
2260 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2261 file_no = to_number(dir_name);
2262 if (file_no > 0 && first <= file_no && file_no <= last) {
2263 if (is_dir_exist(dir_name)) {
2264 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2265 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2266 FILE_OP_ERROR(dot_file, "unlink");
2271 if (claws_unlink(dir_name) < 0)
2272 FILE_OP_ERROR(dir_name, "unlink");
2278 if (g_chdir(prev_dir) < 0) {
2279 FILE_OP_ERROR(prev_dir, "chdir");
2289 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2292 const gchar *dir_name;
2295 GHashTable *wanted_files;
2297 GError *error = NULL;
2299 if (numberlist == NULL)
2302 prev_dir = g_get_current_dir();
2304 if (g_chdir(dir) < 0) {
2305 FILE_OP_ERROR(dir, "chdir");
2310 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2311 g_message("Couldn't open current directory: %s (%d).\n",
2312 error->message, error->code);
2313 g_error_free(error);
2318 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2319 for (cur = numberlist; cur != NULL; cur = cur->next) {
2320 /* numberlist->data is expected to be GINT_TO_POINTER */
2321 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2324 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2325 file_no = to_number(dir_name);
2326 if (is_dir_exist(dir_name))
2328 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2329 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2330 if (is_dir_exist(dir_name)) {
2331 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2332 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2333 FILE_OP_ERROR(dot_file, "unlink");
2338 if (claws_unlink(dir_name) < 0)
2339 FILE_OP_ERROR(dir_name, "unlink");
2344 g_hash_table_destroy(wanted_files);
2346 if (g_chdir(prev_dir) < 0) {
2347 FILE_OP_ERROR(prev_dir, "chdir");
2357 gint remove_all_numbered_files(const gchar *dir)
2359 return remove_numbered_files(dir, 0, UINT_MAX);
2362 gint remove_dir_recursive(const gchar *dir)
2366 const gchar *dir_name;
2369 if (g_stat(dir, &s) < 0) {
2370 FILE_OP_ERROR(dir, "stat");
2371 if (ENOENT == errno) return 0;
2375 if (!S_ISDIR(s.st_mode)) {
2376 if (claws_unlink(dir) < 0) {
2377 FILE_OP_ERROR(dir, "unlink");
2384 prev_dir = g_get_current_dir();
2385 /* g_print("prev_dir = %s\n", prev_dir); */
2387 if (!path_cmp(prev_dir, dir)) {
2389 if (g_chdir("..") < 0) {
2390 FILE_OP_ERROR(dir, "chdir");
2393 prev_dir = g_get_current_dir();
2396 if (g_chdir(dir) < 0) {
2397 FILE_OP_ERROR(dir, "chdir");
2402 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2403 g_warning("failed to open directory: %s", dir);
2409 /* remove all files in the directory */
2410 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2411 /* g_print("removing %s\n", dir_name); */
2413 if (is_dir_exist(dir_name)) {
2416 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2417 g_warning("can't remove directory: %s", dir_name);
2421 if (claws_unlink(dir_name) < 0)
2422 FILE_OP_ERROR(dir_name, "unlink");
2428 if (g_chdir(prev_dir) < 0) {
2429 FILE_OP_ERROR(prev_dir, "chdir");
2436 if (g_rmdir(dir) < 0) {
2437 FILE_OP_ERROR(dir, "rmdir");
2444 gint rename_force(const gchar *oldpath, const gchar *newpath)
2447 if (!is_file_entry_exist(oldpath)) {
2451 if (is_file_exist(newpath)) {
2452 if (claws_unlink(newpath) < 0)
2453 FILE_OP_ERROR(newpath, "unlink");
2456 return g_rename(oldpath, newpath);
2460 * Append src file body to the tail of dest file.
2461 * Now keep_backup has no effects.
2463 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2465 FILE *src_fp, *dest_fp;
2469 gboolean err = FALSE;
2471 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2472 FILE_OP_ERROR(src, "g_fopen");
2476 if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2477 FILE_OP_ERROR(dest, "g_fopen");
2482 if (change_file_mode_rw(dest_fp, dest) < 0) {
2483 FILE_OP_ERROR(dest, "chmod");
2484 g_warning("can't change file mode: %s", dest);
2487 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2488 if (n_read < sizeof(buf) && ferror(src_fp))
2490 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2491 g_warning("writing to %s failed.", dest);
2499 if (ferror(src_fp)) {
2500 FILE_OP_ERROR(src, "fread");
2504 if (fclose(dest_fp) == EOF) {
2505 FILE_OP_ERROR(dest, "fclose");
2517 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2519 FILE *src_fp, *dest_fp;
2522 gchar *dest_bak = NULL;
2523 gboolean err = FALSE;
2525 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2526 FILE_OP_ERROR(src, "g_fopen");
2529 if (is_file_exist(dest)) {
2530 dest_bak = g_strconcat(dest, ".bak", NULL);
2531 if (rename_force(dest, dest_bak) < 0) {
2532 FILE_OP_ERROR(dest, "rename");
2539 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2540 FILE_OP_ERROR(dest, "g_fopen");
2543 if (rename_force(dest_bak, dest) < 0)
2544 FILE_OP_ERROR(dest_bak, "rename");
2550 if (change_file_mode_rw(dest_fp, dest) < 0) {
2551 FILE_OP_ERROR(dest, "chmod");
2552 g_warning("can't change file mode: %s", dest);
2555 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2556 if (n_read < sizeof(buf) && ferror(src_fp))
2558 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2559 g_warning("writing to %s failed.", dest);
2564 if (rename_force(dest_bak, dest) < 0)
2565 FILE_OP_ERROR(dest_bak, "rename");
2572 if (ferror(src_fp)) {
2573 FILE_OP_ERROR(src, "fread");
2577 if (fclose(dest_fp) == EOF) {
2578 FILE_OP_ERROR(dest, "fclose");
2585 if (rename_force(dest_bak, dest) < 0)
2586 FILE_OP_ERROR(dest_bak, "rename");
2592 if (keep_backup == FALSE && dest_bak)
2593 claws_unlink(dest_bak);
2600 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2602 if (overwrite == FALSE && is_file_exist(dest)) {
2603 g_warning("move_file(): file %s already exists.", dest);
2607 if (rename_force(src, dest) == 0) return 0;
2609 if (EXDEV != errno) {
2610 FILE_OP_ERROR(src, "rename");
2614 if (copy_file(src, dest, FALSE) < 0) return -1;
2621 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2624 gint bytes_left, to_read;
2627 if (fseek(fp, offset, SEEK_SET) < 0) {
2632 bytes_left = length;
2633 to_read = MIN(bytes_left, sizeof(buf));
2635 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2636 if (n_read < to_read && ferror(fp))
2638 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2641 bytes_left -= n_read;
2642 if (bytes_left == 0)
2644 to_read = MIN(bytes_left, sizeof(buf));
2655 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2658 gboolean err = FALSE;
2660 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2661 FILE_OP_ERROR(dest, "g_fopen");
2665 if (change_file_mode_rw(dest_fp, dest) < 0) {
2666 FILE_OP_ERROR(dest, "chmod");
2667 g_warning("can't change file mode: %s", dest);
2670 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2673 if (!err && fclose(dest_fp) == EOF) {
2674 FILE_OP_ERROR(dest, "fclose");
2679 g_warning("writing to %s failed.", dest);
2687 /* convert line endings into CRLF. If the last line doesn't end with
2688 * linebreak, add it.
2690 gchar *canonicalize_str(const gchar *str)
2696 for (p = str; *p != '\0'; ++p) {
2703 if (p == str || *(p - 1) != '\n')
2706 out = outp = g_malloc(new_len + 1);
2707 for (p = str; *p != '\0'; ++p) {
2714 if (p == str || *(p - 1) != '\n') {
2723 gint canonicalize_file(const gchar *src, const gchar *dest)
2725 FILE *src_fp, *dest_fp;
2726 gchar buf[BUFFSIZE];
2728 gboolean err = FALSE;
2729 gboolean last_linebreak = FALSE;
2731 if (src == NULL || dest == NULL)
2734 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2735 FILE_OP_ERROR(src, "g_fopen");
2739 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2740 FILE_OP_ERROR(dest, "g_fopen");
2745 if (change_file_mode_rw(dest_fp, dest) < 0) {
2746 FILE_OP_ERROR(dest, "chmod");
2747 g_warning("can't change file mode: %s", dest);
2750 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2754 if (len == 0) break;
2755 last_linebreak = FALSE;
2757 if (buf[len - 1] != '\n') {
2758 last_linebreak = TRUE;
2759 r = fputs(buf, dest_fp);
2760 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2761 r = fputs(buf, dest_fp);
2764 r = fwrite(buf, 1, len - 1, dest_fp);
2769 r = fputs("\r\n", dest_fp);
2773 g_warning("writing to %s failed.", dest);
2781 if (last_linebreak == TRUE) {
2782 if (fputs("\r\n", dest_fp) == EOF)
2786 if (ferror(src_fp)) {
2787 FILE_OP_ERROR(src, "fgets");
2791 if (fclose(dest_fp) == EOF) {
2792 FILE_OP_ERROR(dest, "fclose");
2804 gint canonicalize_file_replace(const gchar *file)
2808 tmp_file = get_tmp_file();
2810 if (canonicalize_file(file, tmp_file) < 0) {
2815 if (move_file(tmp_file, file, TRUE) < 0) {
2816 g_warning("can't replace file: %s", file);
2817 claws_unlink(tmp_file);
2826 gchar *normalize_newlines(const gchar *str)
2831 out = outp = g_malloc(strlen(str) + 1);
2832 for (p = str; *p != '\0'; ++p) {
2834 if (*(p + 1) != '\n')
2845 gchar *get_outgoing_rfc2822_str(FILE *fp)
2847 gchar buf[BUFFSIZE];
2851 str = g_string_new(NULL);
2853 /* output header part */
2854 while (fgets(buf, sizeof(buf), fp) != NULL) {
2856 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2863 else if (next != ' ' && next != '\t') {
2867 if (fgets(buf, sizeof(buf), fp) == NULL)
2871 g_string_append(str, buf);
2872 g_string_append(str, "\r\n");
2878 /* output body part */
2879 while (fgets(buf, sizeof(buf), fp) != NULL) {
2882 g_string_append_c(str, '.');
2883 g_string_append(str, buf);
2884 g_string_append(str, "\r\n");
2888 g_string_free(str, FALSE);
2894 * Create a new boundary in a way that it is very unlikely that this
2895 * will occur in the following text. It would be easy to ensure
2896 * uniqueness if everything is either quoted-printable or base64
2897 * encoded (note that conversion is allowed), but because MIME bodies
2898 * may be nested, it may happen that the same boundary has already
2901 * boundary := 0*69<bchars> bcharsnospace
2902 * bchars := bcharsnospace / " "
2903 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2904 * "+" / "_" / "," / "-" / "." /
2905 * "/" / ":" / "=" / "?"
2907 * some special characters removed because of buggy MTAs
2910 gchar *generate_mime_boundary(const gchar *prefix)
2912 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2913 "abcdefghijklmnopqrstuvwxyz"
2918 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2919 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2922 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2926 gint change_file_mode_rw(FILE *fp, const gchar *file)
2929 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2931 return g_chmod(file, S_IRUSR|S_IWUSR);
2935 FILE *my_tmpfile(void)
2937 const gchar suffix[] = ".XXXXXX";
2938 const gchar *tmpdir;
2940 const gchar *progname;
2949 tmpdir = get_tmp_dir();
2950 tmplen = strlen(tmpdir);
2951 progname = g_get_prgname();
2952 if (progname == NULL)
2953 progname = "claws-mail";
2954 proglen = strlen(progname);
2955 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2958 memcpy(fname, tmpdir, tmplen);
2959 fname[tmplen] = G_DIR_SEPARATOR;
2960 memcpy(fname + tmplen + 1, progname, proglen);
2961 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2963 fd = g_mkstemp(fname);
2968 claws_unlink(fname);
2970 /* verify that we can write in the file after unlinking */
2971 if (write(fd, buf, 1) < 0) {
2978 fp = fdopen(fd, "w+b");
2989 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2992 *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
2993 fd = g_mkstemp(*filename);
2996 return fdopen(fd, "w+");
2999 FILE *str_open_as_stream(const gchar *str)
3004 cm_return_val_if_fail(str != NULL, NULL);
3008 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3013 if (len == 0) return fp;
3015 if (fwrite(str, 1, len, fp) != len) {
3016 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3025 gint str_write_to_file(const gchar *str, const gchar *file)
3030 cm_return_val_if_fail(str != NULL, -1);
3031 cm_return_val_if_fail(file != NULL, -1);
3033 if ((fp = g_fopen(file, "wb")) == NULL) {
3034 FILE_OP_ERROR(file, "g_fopen");
3044 if (fwrite(str, 1, len, fp) != len) {
3045 FILE_OP_ERROR(file, "fwrite");
3051 if (fclose(fp) == EOF) {
3052 FILE_OP_ERROR(file, "fclose");
3060 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3067 cm_return_val_if_fail(fp != NULL, NULL);
3069 array = g_byte_array_new();
3071 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3072 if (n_read < sizeof(buf) && ferror(fp))
3074 g_byte_array_append(array, buf, n_read);
3078 FILE_OP_ERROR("file stream", "fread");
3079 g_byte_array_free(array, TRUE);
3084 g_byte_array_append(array, buf, 1);
3085 str = (gchar *)array->data;
3086 g_byte_array_free(array, FALSE);
3088 if (recode && !g_utf8_validate(str, -1, NULL)) {
3089 const gchar *src_codeset, *dest_codeset;
3091 src_codeset = conv_get_locale_charset_str();
3092 dest_codeset = CS_UTF_8;
3093 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3101 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3108 struct timeval timeout = {1, 0};
3113 cm_return_val_if_fail(file != NULL, NULL);
3115 if (g_stat(file, &s) != 0) {
3116 FILE_OP_ERROR(file, "stat");
3119 if (S_ISDIR(s.st_mode)) {
3120 g_warning("%s: is a directory", file);
3125 fp = g_fopen (file, "rb");
3127 FILE_OP_ERROR(file, "open");
3131 /* test whether the file is readable without blocking */
3132 fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3134 FILE_OP_ERROR(file, "open");
3141 /* allow for one second */
3142 err = select(fd+1, &fds, NULL, NULL, &timeout);
3143 if (err <= 0 || !FD_ISSET(fd, &fds)) {
3145 FILE_OP_ERROR(file, "select");
3147 g_warning("%s: doesn't seem readable", file);
3153 /* Now clear O_NONBLOCK */
3154 if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3155 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3159 if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3160 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3165 /* get the FILE pointer */
3166 fp = fdopen(fd, "rb");
3169 FILE_OP_ERROR(file, "fdopen");
3170 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3175 str = file_read_stream_to_str_full(fp, recode);
3182 gchar *file_read_to_str(const gchar *file)
3184 return file_read_to_str_full(file, TRUE);
3186 gchar *file_read_stream_to_str(FILE *fp)
3188 return file_read_stream_to_str_full(fp, TRUE);
3191 gchar *file_read_to_str_no_recode(const gchar *file)
3193 return file_read_to_str_full(file, FALSE);
3195 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3197 return file_read_stream_to_str_full(fp, FALSE);
3200 char *fgets_crlf(char *buf, int size, FILE *stream)
3202 gboolean is_cr = FALSE;
3203 gboolean last_was_cr = FALSE;
3208 while (--size > 0 && (c = getc(stream)) != EOF)
3211 is_cr = (c == '\r');
3221 last_was_cr = is_cr;
3223 if (c == EOF && cs == buf)
3231 static gint execute_async(gchar *const argv[])
3233 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3235 if (g_spawn_async(NULL, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3236 NULL, NULL, NULL, FALSE) == FALSE) {
3237 g_warning("couldn't execute command: %s", argv[0]);
3244 static gint execute_sync(gchar *const argv[])
3248 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3251 if (g_spawn_sync(NULL, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3252 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3253 g_warning("couldn't execute command: %s", argv[0]);
3257 if (WIFEXITED(status))
3258 return WEXITSTATUS(status);
3262 if (g_spawn_sync(NULL, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH|
3263 G_SPAWN_CHILD_INHERITS_STDIN|G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3264 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3265 g_warning("couldn't execute command: %s", argv[0]);
3273 gint execute_command_line(const gchar *cmdline, gboolean async)
3278 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3280 argv = strsplit_with_quote(cmdline, " ", 0);
3283 ret = execute_async(argv);
3285 ret = execute_sync(argv);
3292 gchar *get_command_output(const gchar *cmdline)
3294 gchar *child_stdout;
3297 cm_return_val_if_fail(cmdline != NULL, NULL);
3299 debug_print("get_command_output(): executing: %s\n", cmdline);
3301 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3303 g_warning("couldn't execute command: %s", cmdline);
3307 return child_stdout;
3310 static gint is_unchanged_uri_char(char c)
3321 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3327 for(i = 0; i < strlen(uri) ; i++) {
3328 if (is_unchanged_uri_char(uri[i])) {
3329 if (k + 2 >= bufsize)
3331 encoded_uri[k++] = uri[i];
3334 char * hexa = "0123456789ABCDEF";
3336 if (k + 4 >= bufsize)
3338 encoded_uri[k++] = '%';
3339 encoded_uri[k++] = hexa[uri[i] / 16];
3340 encoded_uri[k++] = hexa[uri[i] % 16];
3346 gint open_uri(const gchar *uri, const gchar *cmdline)
3350 gchar buf[BUFFSIZE];
3352 gchar encoded_uri[BUFFSIZE];
3353 cm_return_val_if_fail(uri != NULL, -1);
3355 /* an option to choose whether to use encode_uri or not ? */
3356 encode_uri(encoded_uri, BUFFSIZE, uri);
3359 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3360 !strchr(p + 2, '%'))
3361 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3364 g_warning("Open URI command-line is invalid "
3365 "(there must be only one '%%s'): %s",
3367 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3370 execute_command_line(buf, TRUE);
3372 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3377 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3379 gchar buf[BUFFSIZE];
3382 cm_return_val_if_fail(filepath != NULL, -1);
3385 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3386 !strchr(p + 2, '%'))
3387 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3390 g_warning("Open Text Editor command-line is invalid "
3391 "(there must be only one '%%s'): %s",
3393 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3396 execute_command_line(buf, TRUE);
3401 time_t remote_tzoffset_sec(const gchar *zone)
3403 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3409 time_t remoteoffset;
3411 strncpy(zone3, zone, 3);
3415 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3416 (c == '+' || c == '-')) {
3417 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3419 remoteoffset = -remoteoffset;
3420 } else if (!strncmp(zone, "UT" , 2) ||
3421 !strncmp(zone, "GMT", 3)) {
3423 } else if (strlen(zone3) == 3) {
3424 for (p = ustzstr; *p != '\0'; p += 3) {
3425 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3426 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3427 remoteoffset = iustz * 3600;
3433 } else if (strlen(zone3) == 1) {
3435 case 'Z': remoteoffset = 0; break;
3436 case 'A': remoteoffset = -1; break;
3437 case 'B': remoteoffset = -2; break;
3438 case 'C': remoteoffset = -3; break;
3439 case 'D': remoteoffset = -4; break;
3440 case 'E': remoteoffset = -5; break;
3441 case 'F': remoteoffset = -6; break;
3442 case 'G': remoteoffset = -7; break;
3443 case 'H': remoteoffset = -8; break;
3444 case 'I': remoteoffset = -9; break;
3445 case 'K': remoteoffset = -10; break; /* J is not used */
3446 case 'L': remoteoffset = -11; break;
3447 case 'M': remoteoffset = -12; break;
3448 case 'N': remoteoffset = 1; break;
3449 case 'O': remoteoffset = 2; break;
3450 case 'P': remoteoffset = 3; break;
3451 case 'Q': remoteoffset = 4; break;
3452 case 'R': remoteoffset = 5; break;
3453 case 'S': remoteoffset = 6; break;
3454 case 'T': remoteoffset = 7; break;
3455 case 'U': remoteoffset = 8; break;
3456 case 'V': remoteoffset = 9; break;
3457 case 'W': remoteoffset = 10; break;
3458 case 'X': remoteoffset = 11; break;
3459 case 'Y': remoteoffset = 12; break;
3460 default: remoteoffset = 0; break;
3462 remoteoffset = remoteoffset * 3600;
3466 return remoteoffset;
3469 time_t tzoffset_sec(time_t *now)
3473 struct tm buf1, buf2;
3475 if (now && *now < 0)
3478 gmt = *gmtime_r(now, &buf1);
3479 lt = localtime_r(now, &buf2);
3481 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3483 if (lt->tm_year < gmt.tm_year)
3485 else if (lt->tm_year > gmt.tm_year)
3487 else if (lt->tm_yday < gmt.tm_yday)
3489 else if (lt->tm_yday > gmt.tm_yday)
3492 if (off >= 24 * 60) /* should be impossible */
3493 off = 23 * 60 + 59; /* if not, insert silly value */
3494 if (off <= -24 * 60)
3495 off = -(23 * 60 + 59);
3500 /* calculate timezone offset */
3501 gchar *tzoffset(time_t *now)
3503 static gchar offset_string[6];
3507 struct tm buf1, buf2;
3509 if (now && *now < 0)
3512 gmt = *gmtime_r(now, &buf1);
3513 lt = localtime_r(now, &buf2);
3515 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3517 if (lt->tm_year < gmt.tm_year)
3519 else if (lt->tm_year > gmt.tm_year)
3521 else if (lt->tm_yday < gmt.tm_yday)
3523 else if (lt->tm_yday > gmt.tm_yday)
3531 if (off >= 24 * 60) /* should be impossible */
3532 off = 23 * 60 + 59; /* if not, insert silly value */
3534 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3536 return offset_string;
3539 void get_rfc822_date(gchar *buf, gint len)
3543 gchar day[4], mon[4];
3544 gint dd, hh, mm, ss, yyyy;
3546 gchar buf2[BUFFSIZE];
3549 lt = localtime_r(&t, &buf1);
3551 sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
3552 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3554 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3555 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3558 void debug_set_mode(gboolean mode)
3563 gboolean debug_get_mode(void)
3568 void debug_print_real(const gchar *format, ...)
3571 gchar buf[BUFFSIZE];
3573 if (!debug_mode) return;
3575 va_start(args, format);
3576 g_vsnprintf(buf, sizeof(buf), format, args);
3583 const char * debug_srcname(const char *file)
3585 const char *s = strrchr (file, '/');
3590 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3592 if (subject == NULL)
3595 subject += subject_get_prefix_length(subject);
3597 return g_hash_table_lookup(subject_table, subject);
3600 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3603 if (subject == NULL || *subject == 0)
3605 subject += subject_get_prefix_length(subject);
3606 g_hash_table_insert(subject_table, subject, data);
3609 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3611 if (subject == NULL)
3614 subject += subject_get_prefix_length(subject);
3615 g_hash_table_remove(subject_table, subject);
3618 static regex_t u_regex;
3619 static gboolean u_init_;
3621 void utils_free_regex(void)
3630 *\brief Check if a string is prefixed with known (combinations)
3631 * of prefixes. The function assumes that each prefix
3632 * is terminated by zero or exactly _one_ space.
3634 *\param str String to check for a prefixes
3636 *\return int Number of chars in the prefix that should be skipped
3637 * for a "clean" subject line. If no prefix was found, 0
3640 int subject_get_prefix_length(const gchar *subject)
3642 /*!< Array with allowable reply prefixes regexps. */
3643 static const gchar * const prefixes[] = {
3644 "Re\\:", /* "Re:" */
3645 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3646 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3647 "Aw\\:", /* "Aw:" (German) */
3648 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3649 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3650 "Fw\\:", /* "Fw:" Forward */
3651 "Fwd\\:", /* "Fwd:" Forward */
3652 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3653 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3654 "Rif\\:", /* "Rif:" (Italian Outlook) */
3655 "Sv\\:", /* "Sv" (Norwegian) */
3656 "Vs\\:", /* "Vs" (Norwegian) */
3657 "Ad\\:", /* "Ad" (Norwegian) */
3658 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3659 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3660 "Re \\:", /* "Re :" (French Yahoo Mail) */
3663 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3667 if (!subject) return 0;
3668 if (!*subject) return 0;
3671 GString *s = g_string_new("");
3673 for (n = 0; n < PREFIXES; n++)
3674 /* Terminate each prefix regexpression by a
3675 * "\ ?" (zero or ONE space), and OR them */
3676 g_string_append_printf(s, "(%s\\ ?)%s",
3681 g_string_prepend(s, "(");
3682 g_string_append(s, ")+"); /* match at least once */
3683 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3686 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3687 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3688 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3689 debug_print("Error compiling regexp %s\n", s->str);
3690 g_string_free(s, TRUE);
3694 g_string_free(s, TRUE);
3698 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3704 static guint g_stricase_hash(gconstpointer gptr)
3706 guint hash_result = 0;
3709 for (str = gptr; str && *str; str++) {
3710 hash_result += toupper(*str);
3716 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3718 const char *str1 = gptr1;
3719 const char *str2 = gptr2;
3721 return !strcasecmp(str1, str2);
3724 gint g_int_compare(gconstpointer a, gconstpointer b)
3726 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3729 gchar *generate_msgid(gchar *buf, gint len, gchar *user_addr)
3737 lt = localtime_r(&t, &buft);
3739 if (user_addr != NULL)
3740 addr = g_strdup_printf(".%s", user_addr);
3741 else if (strlen(buf) != 0)
3742 addr = g_strdup_printf("@%s", buf);
3744 addr = g_strdup_printf("@%s", get_domain_name());
3746 /* Replace all @ but the last one in addr, with underscores.
3747 * RFC 2822 States that msg-id syntax only allows one @.
3749 while (strchr(addr, '@') != NULL && strchr(addr, '@') != strrchr(addr, '@'))
3750 *(strchr(addr, '@')) = '_';
3752 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x%s",
3753 lt->tm_year + 1900, lt->tm_mon + 1,
3754 lt->tm_mday, lt->tm_hour,
3755 lt->tm_min, lt->tm_sec,
3756 (guint) rand(), addr);
3763 quote_cmd_argument()
3765 return a quoted string safely usable in argument of a command.
3767 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3770 gint quote_cmd_argument(gchar * result, guint size,
3780 for(p = path ; * p != '\0' ; p ++) {
3782 if (isalnum((guchar)*p) || (* p == '/')) {
3783 if (remaining > 0) {
3789 result[size - 1] = '\0';
3794 if (remaining >= 2) {
3802 result[size - 1] = '\0';
3807 if (remaining > 0) {
3811 result[size - 1] = '\0';
3825 static void g_node_map_recursive(GNode *node, gpointer data)
3827 GNodeMapData *mapdata = (GNodeMapData *) data;
3829 GNodeMapData newmapdata;
3832 newdata = mapdata->func(node->data, mapdata->data);
3833 if (newdata != NULL) {
3834 newnode = g_node_new(newdata);
3835 g_node_append(mapdata->parent, newnode);
3837 newmapdata.parent = newnode;
3838 newmapdata.func = mapdata->func;
3839 newmapdata.data = mapdata->data;
3841 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3845 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3848 GNodeMapData mapdata;
3850 cm_return_val_if_fail(node != NULL, NULL);
3851 cm_return_val_if_fail(func != NULL, NULL);
3853 root = g_node_new(func(node->data, data));
3855 mapdata.parent = root;
3856 mapdata.func = func;
3857 mapdata.data = data;
3859 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3864 #define HEX_TO_INT(val, hex) \
3868 if ('0' <= c && c <= '9') { \
3870 } else if ('a' <= c && c <= 'f') { \
3871 val = c - 'a' + 10; \
3872 } else if ('A' <= c && c <= 'F') { \
3873 val = c - 'A' + 10; \
3879 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3886 if (hi == -1 || lo == -1)
3889 *out = (hi << 4) + lo;
3893 #define INT_TO_HEX(hex, val) \
3896 hex = '0' + (val); \
3898 hex = 'A' + (val) - 10; \
3901 void get_hex_str(gchar *out, guchar ch)
3905 INT_TO_HEX(hex, ch >> 4);
3907 INT_TO_HEX(hex, ch & 0x0f);
3913 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3915 #define G_PRINT_REF g_print
3919 *\brief Register ref counted pointer. It is based on GBoxed, so should
3920 * work with anything that uses the GType system. The semantics
3921 * are similar to a C++ auto pointer, with the exception that
3922 * C doesn't have automatic closure (calling destructors) when
3923 * exiting a block scope.
3924 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3925 * function directly.
3927 *\return GType A GType type.
3929 GType g_auto_pointer_register(void)
3931 static GType auto_pointer_type;
3932 if (!auto_pointer_type)
3934 g_boxed_type_register_static
3935 ("G_TYPE_AUTO_POINTER",
3936 (GBoxedCopyFunc) g_auto_pointer_copy,
3937 (GBoxedFreeFunc) g_auto_pointer_free);
3938 return auto_pointer_type;
3942 *\brief Structure with g_new() allocated pointer guarded by the
3945 typedef struct AutoPointerRef {
3946 void (*free) (gpointer);
3952 *\brief The auto pointer opaque structure that references the
3953 * pointer guard block.
3955 typedef struct AutoPointer {
3956 AutoPointerRef *ref;
3957 gpointer ptr; /*!< access to protected pointer */
3961 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3965 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3966 * ... when assigning, copying and freeing storage elements
3968 * gtk_list_store_new(N_S_COLUMNS,
3969 * G_TYPE_AUTO_POINTER,
3973 * Template *precious_data = g_new0(Template, 1);
3974 * g_pointer protect = g_auto_pointer_new(precious_data);
3976 * gtk_list_store_set(container, &iter,
3980 * ... the gtk_list_store has copied the pointer and
3981 * ... incremented its reference count, we should free
3982 * ... the auto pointer (in C++ a destructor would do
3983 * ... this for us when leaving block scope)
3985 * g_auto_pointer_free(protect);
3987 * ... gtk_list_store_set() now manages the data. When
3988 * ... *explicitly* requesting a pointer from the list
3989 * ... store, don't forget you get a copy that should be
3990 * ... freed with g_auto_pointer_free() eventually.
3994 *\param pointer Pointer to be guarded.
3996 *\return GAuto * Pointer that should be used in containers with
3999 GAuto *g_auto_pointer_new(gpointer p)
4001 AutoPointerRef *ref;
4007 ref = g_new0(AutoPointerRef, 1);
4008 ptr = g_new0(AutoPointer, 1);
4018 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
4024 *\brief Allocate an autopointer using the passed \a free function to
4025 * free the guarded pointer
4027 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
4034 aptr = g_auto_pointer_new(p);
4035 aptr->ref->free = free_;
4039 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
4041 if (auto_ptr == NULL)
4043 return ((AutoPointer *) auto_ptr)->ptr;
4047 *\brief Copies an auto pointer by. It's mostly not necessary
4048 * to call this function directly, unless you copy/assign
4049 * the guarded pointer.
4051 *\param auto_ptr Auto pointer returned by previous call to
4052 * g_auto_pointer_new_XXX()
4054 *\return gpointer An auto pointer
4056 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
4059 AutoPointerRef *ref;
4062 if (auto_ptr == NULL)
4067 newp = g_new0(AutoPointer, 1);
4070 newp->ptr = ref->pointer;
4074 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4080 *\brief Free an auto pointer
4082 void g_auto_pointer_free(GAuto *auto_ptr)
4085 AutoPointerRef *ref;
4087 if (auto_ptr == NULL)
4093 if (--(ref->cnt) == 0) {
4095 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4097 ref->free(ref->pointer);
4102 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4107 void replace_returns(gchar *str)
4112 while (strstr(str, "\n")) {
4113 *strstr(str, "\n") = ' ';
4115 while (strstr(str, "\r")) {
4116 *strstr(str, "\r") = ' ';
4120 /* get_uri_part() - retrieves a URI starting from scanpos.
4121 Returns TRUE if succesful */
4122 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
4123 const gchar **bp, const gchar **ep, gboolean hdr)
4126 gint parenthese_cnt = 0;
4128 cm_return_val_if_fail(start != NULL, FALSE);
4129 cm_return_val_if_fail(scanpos != NULL, FALSE);
4130 cm_return_val_if_fail(bp != NULL, FALSE);
4131 cm_return_val_if_fail(ep != NULL, FALSE);
4135 /* find end point of URI */
4136 for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
4137 if (!g_ascii_isgraph(*(const guchar *)ep_) ||
4138 !IS_ASCII(*(const guchar *)ep_) ||
4139 strchr("[]{}<>\"", *ep_)) {
4141 } else if (strchr("(", *ep_)) {
4143 } else if (strchr(")", *ep_)) {
4144 if (parenthese_cnt > 0)
4151 /* no punctuation at end of string */
4153 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
4154 * should pass some URI type to this function and decide on that whether
4155 * to perform punctuation stripping */
4157 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_)", ch))
4159 for (; ep_ - 1 > scanpos + 1 &&
4160 IS_REAL_PUNCT(*(ep_ - 1));
4164 #undef IS_REAL_PUNCT
4171 gchar *make_uri_string(const gchar *bp, const gchar *ep)
4173 while (bp && *bp && g_ascii_isspace(*bp))
4175 return g_strndup(bp, ep - bp);
4178 /* valid mail address characters */
4179 #define IS_RFC822_CHAR(ch) \
4183 !g_ascii_isspace(ch) && \
4184 !strchr("(),;<>\"", (ch)))
4186 /* alphabet and number within 7bit ASCII */
4187 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
4188 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
4190 static GHashTable *create_domain_tab(void)
4193 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
4195 cm_return_val_if_fail(htab, NULL);
4196 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
4197 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
4201 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
4203 const gint MAX_LVL_DOM_NAME_LEN = 6;
4204 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
4205 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
4208 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
4211 for (p = buf; p < m && first < last; *p++ = *first++)
4215 return g_hash_table_lookup(tab, buf) != NULL;
4218 /* get_email_part() - retrieves an email address. Returns TRUE if succesful */
4219 gboolean get_email_part(const gchar *start, const gchar *scanpos,
4220 const gchar **bp, const gchar **ep, gboolean hdr)
4222 /* more complex than the uri part because we need to scan back and forward starting from
4223 * the scan position. */
4224 gboolean result = FALSE;
4225 const gchar *bp_ = NULL;
4226 const gchar *ep_ = NULL;
4227 static GHashTable *dom_tab;
4228 const gchar *last_dot = NULL;
4229 const gchar *prelast_dot = NULL;
4230 const gchar *last_tld_char = NULL;
4232 /* the informative part of the email address (describing the name
4233 * of the email address owner) may contain quoted parts. the
4234 * closure stack stores the last encountered quotes. */
4235 gchar closure_stack[128];
4236 gchar *ptr = closure_stack;
4238 cm_return_val_if_fail(start != NULL, FALSE);
4239 cm_return_val_if_fail(scanpos != NULL, FALSE);
4240 cm_return_val_if_fail(bp != NULL, FALSE);
4241 cm_return_val_if_fail(ep != NULL, FALSE);
4244 const gchar *start_quote = NULL;
4245 const gchar *end_quote = NULL;
4247 /* go to the real start */