2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2021 The Claws Mail Team and Hiroyuki Yamamoto
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 <ws2tcpip.h>
55 # include <sys/socket.h>
58 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
66 #include <sys/types.h>
68 # include <sys/wait.h>
75 #include <sys/utsname.h>
90 #include "file-utils.h"
94 static gboolean debug_mode = FALSE;
96 void list_free_strings_full(GList *list)
98 g_list_free_full(list, (GDestroyNotify)g_free);
101 void slist_free_strings_full(GSList *list)
103 g_slist_free_full(list, (GDestroyNotify)g_free);
106 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
111 void hash_free_strings(GHashTable *table)
113 g_hash_table_foreach(table, hash_free_strings_func, NULL);
116 gint str_case_equal(gconstpointer v, gconstpointer v2)
118 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
121 guint str_case_hash(gconstpointer key)
123 const gchar *p = key;
127 h = g_ascii_tolower(h);
128 for (p += 1; *p != '\0'; p++)
129 h = (h << 5) - h + g_ascii_tolower(*p);
135 gint to_number(const gchar *nstr)
137 register const gchar *p;
139 if (*nstr == '\0') return -1;
141 for (p = nstr; *p != '\0'; p++)
142 if (!g_ascii_isdigit(*p)) return -1;
147 /* convert integer into string,
148 nstr must be not lower than 11 characters length */
149 gchar *itos_buf(gchar *nstr, gint n)
151 g_snprintf(nstr, 11, "%d", n);
155 /* convert integer into string */
158 static gchar nstr[11];
160 return itos_buf(nstr, n);
163 #define divide(num,divisor,i,d) \
165 i = num >> divisor; \
166 d = num & ((1<<divisor)-1); \
167 d = (d*100) >> divisor; \
172 * \brief Convert a given size in bytes in a human-readable string
174 * \param size The size expressed in bytes to convert in string
175 * \return The string that respresents the size in an human-readable way
177 gchar *to_human_readable(goffset size)
179 static gchar str[14];
180 static gchar *b_format = NULL, *kb_format = NULL,
181 *mb_format = NULL, *gb_format = NULL;
182 register int t = 0, r = 0;
183 if (b_format == NULL) {
185 kb_format = _("%d.%02dKiB");
186 mb_format = _("%d.%02dMiB");
187 gb_format = _("%.2fGiB");
190 if (size < (goffset)1024) {
191 g_snprintf(str, sizeof(str), b_format, (gint)size);
193 } else if (size >> 10 < (goffset)1024) {
194 divide(size, 10, t, r);
195 g_snprintf(str, sizeof(str), kb_format, t, r);
197 } else if (size >> 20 < (goffset)1024) {
198 divide(size, 20, t, r);
199 g_snprintf(str, sizeof(str), mb_format, t, r);
202 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
208 gint path_cmp(const gchar *s1, const gchar *s2)
213 gchar *s1buf, *s2buf;
216 if (s1 == NULL || s2 == NULL) return -1;
217 if (*s1 == '\0' || *s2 == '\0') return -1;
220 s1buf = g_strdup (s1);
221 s2buf = g_strdup (s2);
222 subst_char (s1buf, '/', G_DIR_SEPARATOR);
223 subst_char (s2buf, '/', G_DIR_SEPARATOR);
226 #endif /* !G_OS_WIN32 */
231 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
232 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
234 rc = strncmp(s1, s2, MAX(len1, len2));
238 #endif /* !G_OS_WIN32 */
242 /* remove trailing return code */
243 gchar *strretchomp(gchar *str)
247 if (!*str) return str;
249 for (s = str + strlen(str) - 1;
250 s >= str && (*s == '\n' || *s == '\r');
257 /* remove trailing character */
258 gchar *strtailchomp(gchar *str, gchar tail_char)
262 if (!*str) return str;
263 if (tail_char == '\0') return str;
265 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
271 /* remove CR (carriage return) */
272 gchar *strcrchomp(gchar *str)
276 if (!*str) return str;
278 s = str + strlen(str) - 1;
279 if (*s == '\n' && s > str && *(s - 1) == '\r') {
287 /* truncates string at first CR (carriage return) or LF (line feed) */
288 gchar *strcrlftrunc(gchar *str)
292 if ((str == NULL) || (!*str)) return str;
294 if ((p = strstr(str, "\r")) != NULL)
296 if ((p = strstr(str, "\n")) != NULL)
302 #ifndef HAVE_STRCASESTR
303 /* Similar to `strstr' but this function ignores the case of both strings. */
304 gchar *strcasestr(const gchar *haystack, const gchar *needle)
306 size_t haystack_len = strlen(haystack);
308 return strncasestr(haystack, haystack_len, needle);
310 #endif /* HAVE_STRCASESTR */
312 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
314 register size_t needle_len;
316 needle_len = strlen(needle);
318 if (haystack_len < needle_len || needle_len == 0)
321 while (haystack_len >= needle_len) {
322 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
323 return (gchar *)haystack;
333 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
334 gconstpointer needle, size_t needlelen)
336 const gchar *haystack_ = (const gchar *)haystack;
337 const gchar *needle_ = (const gchar *)needle;
338 const gchar *haystack_cur = (const gchar *)haystack;
339 size_t haystack_left = haystacklen;
342 return memchr(haystack_, *needle_, haystacklen);
344 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
346 if (haystacklen - (haystack_cur - haystack_) < needlelen)
348 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
349 return (gpointer)haystack_cur;
352 haystack_left = haystacklen - (haystack_cur - haystack_);
359 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
360 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
362 register const gchar *s = src;
363 register gchar *d = dest;
373 /* Examine if next block is non-ASCII string */
374 gboolean is_next_nonascii(const gchar *s)
378 /* skip head space */
379 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
381 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
382 if (*(guchar *)p > 127 || *(guchar *)p < 32)
389 gint get_next_word_len(const gchar *s)
393 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
399 static void trim_subject_for_compare(gchar *str)
403 eliminate_parenthesis(str, '[', ']');
404 eliminate_parenthesis(str, '(', ')');
407 srcp = str + subject_get_prefix_length(str);
409 memmove(str, srcp, strlen(srcp) + 1);
412 static void trim_subject_for_sort(gchar *str)
418 srcp = str + subject_get_prefix_length(str);
420 memmove(str, srcp, strlen(srcp) + 1);
423 /* compare subjects */
424 gint subject_compare(const gchar *s1, const gchar *s2)
428 if (!s1 || !s2) return -1;
429 if (!*s1 || !*s2) return -1;
431 Xstrdup_a(str1, s1, return -1);
432 Xstrdup_a(str2, s2, return -1);
434 trim_subject_for_compare(str1);
435 trim_subject_for_compare(str2);
437 if (!*str1 || !*str2) return -1;
439 return strcmp(str1, str2);
442 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
446 if (!s1 || !s2) return -1;
448 Xstrdup_a(str1, s1, return -1);
449 Xstrdup_a(str2, s2, return -1);
451 trim_subject_for_sort(str1);
452 trim_subject_for_sort(str2);
454 if (!g_utf8_validate(str1, -1, NULL)) {
455 g_warning("message subject \"%s\" failed UTF-8 validation", str1);
457 } else if (!g_utf8_validate(str2, -1, NULL)) {
458 g_warning("message subject \"%s\" failed UTF-8 validation", str2);
462 return g_utf8_collate(str1, str2);
465 void trim_subject(gchar *str)
467 register gchar *srcp;
473 srcp = str + subject_get_prefix_length(str);
478 } else if (*srcp == '(') {
490 else if (*srcp == cl)
497 while (g_ascii_isspace(*srcp)) srcp++;
498 memmove(str, srcp, strlen(srcp) + 1);
501 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
503 register gchar *srcp, *destp;
508 while ((destp = strchr(destp, op))) {
514 else if (*srcp == cl)
520 while (g_ascii_isspace(*srcp)) srcp++;
521 memmove(destp, srcp, strlen(srcp) + 1);
525 void extract_parenthesis(gchar *str, gchar op, gchar cl)
527 register gchar *srcp, *destp;
532 while ((srcp = strchr(destp, op))) {
535 memmove(destp, srcp + 1, strlen(srcp));
540 else if (*destp == cl)
552 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
555 register gchar *srcp, *destp;
557 gboolean in_quote = FALSE;
561 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
564 memmove(destp, srcp + 1, strlen(srcp));
567 if (*destp == op && !in_quote)
569 else if (*destp == cl && !in_quote)
571 else if (*destp == quote_chr)
583 void extract_quote(gchar *str, gchar quote_chr)
587 if ((str = strchr(str, quote_chr))) {
589 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
590 memmove(p - 1, p, strlen(p) + 1);
595 memmove(str, str + 1, p - str);
600 /* Returns a newly allocated string with all quote_chr not at the beginning
601 or the end of str escaped with '\' or the given str if not required. */
602 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
604 register gchar *p, *q;
608 if (str == NULL || *str == '\0')
611 /* search for unescaped quote_chr */
616 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
620 if (!k) /* nothing to escape */
623 /* unescaped quote_chr found */
624 qstr = g_malloc(l + k + 1);
627 if (*p == quote_chr) {
632 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
641 void eliminate_address_comment(gchar *str)
643 register gchar *srcp, *destp;
648 while ((destp = strchr(destp, '"'))) {
649 if ((srcp = strchr(destp + 1, '"'))) {
654 while (g_ascii_isspace(*srcp)) srcp++;
655 memmove(destp, srcp, strlen(srcp) + 1);
665 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
671 else if (*srcp == ')')
677 while (g_ascii_isspace(*srcp)) srcp++;
678 memmove(destp, srcp, strlen(srcp) + 1);
682 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
684 gboolean in_quote = FALSE;
687 if (*str == c && !in_quote)
689 if (*str == quote_chr)
697 void extract_address(gchar *str)
699 cm_return_if_fail(str != NULL);
700 eliminate_address_comment(str);
701 if (strchr_with_skip_quote(str, '"', '<'))
702 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
706 void extract_list_id_str(gchar *str)
708 if (strchr_with_skip_quote(str, '"', '<'))
709 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
713 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
718 if (!str) return addr_list;
720 Xstrdup_a(work, str, return addr_list);
723 eliminate_address_comment(work);
726 while (workp && *workp) {
729 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
735 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
736 extract_parenthesis_with_skip_quote
737 (workp, '"', '<', '>');
741 addr_list = g_slist_append(addr_list, g_strdup(workp));
749 GSList *address_list_append(GSList *addr_list, const gchar *str)
751 return address_list_append_real(addr_list, str, TRUE);
754 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
756 return address_list_append_real(addr_list, str, FALSE);
759 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
763 if (!str) return msgid_list;
766 while (strp && *strp) {
767 const gchar *start, *end;
770 if ((start = strchr(strp, '<')) != NULL) {
771 end = strchr(start + 1, '>');
776 msgid = g_strndup(start + 1, end - start - 1);
779 msgid_list = g_slist_prepend(msgid_list, msgid);
789 GSList *references_list_append(GSList *msgid_list, const gchar *str)
793 list = references_list_prepend(NULL, str);
794 list = g_slist_reverse(list);
795 msgid_list = g_slist_concat(msgid_list, list);
800 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
805 if (!str) return group_list;
807 Xstrdup_a(work, str, return group_list);
811 while (workp && *workp) {
814 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
822 group_list = g_slist_append(group_list,
831 GList *add_history(GList *list, const gchar *str)
836 cm_return_val_if_fail(str != NULL, list);
838 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)g_strcmp0);
841 list = g_list_remove(list, old->data);
843 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
846 last = g_list_last(list);
849 list = g_list_remove(list, last->data);
854 list = g_list_prepend(list, g_strdup(str));
859 void remove_return(gchar *str)
861 register gchar *p = str;
864 if (*p == '\n' || *p == '\r')
865 memmove(p, p + 1, strlen(p));
871 void remove_space(gchar *str)
873 register gchar *p = str;
878 while (g_ascii_isspace(*(p + spc)))
881 memmove(p, p + spc, strlen(p + spc) + 1);
887 void unfold_line(gchar *str)
893 ch = str; /* iterator for source string */
896 c = g_utf8_get_char_validated(ch, -1);
898 if (c == (gunichar)-1 || c == (gunichar)-2) {
899 /* non-unicode byte, move past it */
904 len = g_unichar_to_utf8(c, NULL);
906 if ((!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
907 g_unichar_isspace(c)) && c != 173) {
908 /* replace anything bad or whitespacey with a single space */
912 /* move rest of the string forwards, since we just replaced
913 * a multi-byte sequence with one byte */
914 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
917 /* A valid unicode character, copy it. */
923 void subst_char(gchar *str, gchar orig, gchar subst)
925 register gchar *p = str;
934 void subst_chars(gchar *str, gchar *orig, gchar subst)
936 register gchar *p = str;
939 if (strchr(orig, *p) != NULL)
945 void subst_for_filename(gchar *str)
950 subst_chars(str, "\t\r\n\\/*?:", '_');
952 subst_chars(str, "\t\r\n\\/*", '_');
956 void subst_for_shellsafe_filename(gchar *str)
960 subst_for_filename(str);
961 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
964 gboolean is_ascii_str(const gchar *str)
966 const guchar *p = (const guchar *)str;
969 if (*p != '\t' && *p != ' ' &&
970 *p != '\r' && *p != '\n' &&
971 (*p < 32 || *p >= 127))
979 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
981 gchar * position = NULL;
982 gchar * tmp_pos = NULL;
985 if (str == NULL || quote_chars == NULL)
988 for (i = 0; i < strlen(quote_chars); i++) {
989 tmp_pos = strrchr (str, quote_chars[i]);
991 || (tmp_pos != NULL && position <= tmp_pos) )
997 gint get_quote_level(const gchar *str, const gchar *quote_chars)
999 const gchar *first_pos;
1000 const gchar *last_pos;
1001 const gchar *p = str;
1002 gint quote_level = -1;
1004 /* speed up line processing by only searching to the last '>' */
1005 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1006 /* skip a line if it contains a '<' before the initial '>' */
1007 if (memchr(str, '<', first_pos - str) != NULL)
1009 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1013 while (p <= last_pos) {
1014 while (p < last_pos) {
1015 if (g_ascii_isspace(*p))
1021 if (strchr(quote_chars, *p))
1023 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1024 /* any characters are allowed except '-','<' and space */
1025 while (*p != '-' && *p != '<'
1026 && !strchr(quote_chars, *p)
1027 && !g_ascii_isspace(*p)
1030 if (strchr(quote_chars, *p))
1042 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1044 const gchar *p = str, *q;
1045 gint cur_line = 0, len;
1047 while ((q = strchr(p, '\n')) != NULL) {
1049 if (len > max_chars) {
1059 if (len > max_chars) {
1068 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1070 gchar * position = NULL;
1071 gchar * tmp_pos = NULL;
1074 if (str == NULL || quote_chars == NULL)
1077 for (i = 0; i < strlen(quote_chars); i++) {
1078 tmp_pos = strchr (str, quote_chars[i]);
1080 || (tmp_pos != NULL && position >= tmp_pos) )
1086 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1088 register guint haystack_len, needle_len;
1089 gboolean in_squote = FALSE, in_dquote = FALSE;
1091 haystack_len = strlen(haystack);
1092 needle_len = strlen(needle);
1094 if (haystack_len < needle_len || needle_len == 0)
1097 while (haystack_len >= needle_len) {
1098 if (!in_squote && !in_dquote &&
1099 !strncmp(haystack, needle, needle_len))
1100 return (gchar *)haystack;
1102 /* 'foo"bar"' -> foo"bar"
1103 "foo'bar'" -> foo'bar' */
1104 if (*haystack == '\'') {
1107 else if (!in_dquote)
1109 } else if (*haystack == '\"') {
1112 else if (!in_squote)
1114 } else if (*haystack == '\\') {
1126 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1129 GSList *string_list = NULL, *slist;
1130 gchar **str_array, *s, *new_str;
1131 guint i, n = 1, len;
1133 cm_return_val_if_fail(str != NULL, NULL);
1134 cm_return_val_if_fail(delim != NULL, NULL);
1137 max_tokens = G_MAXINT;
1139 s = strstr_with_skip_quote(str, delim);
1141 guint delimiter_len = strlen(delim);
1145 new_str = g_strndup(str, len);
1147 if (new_str[0] == '\'' || new_str[0] == '\"') {
1148 if (new_str[len - 1] == new_str[0]) {
1149 new_str[len - 1] = '\0';
1150 memmove(new_str, new_str + 1, len - 1);
1153 string_list = g_slist_prepend(string_list, new_str);
1155 str = s + delimiter_len;
1156 s = strstr_with_skip_quote(str, delim);
1157 } while (--max_tokens && s);
1161 new_str = g_strdup(str);
1162 if (new_str[0] == '\'' || new_str[0] == '\"') {
1164 if (new_str[len - 1] == new_str[0]) {
1165 new_str[len - 1] = '\0';
1166 memmove(new_str, new_str + 1, len - 1);
1169 string_list = g_slist_prepend(string_list, new_str);
1173 str_array = g_new(gchar*, n);
1177 str_array[i--] = NULL;
1178 for (slist = string_list; slist; slist = slist->next)
1179 str_array[i--] = slist->data;
1181 g_slist_free(string_list);
1186 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1188 gchar *abbrev_group;
1190 const gchar *p = group;
1193 cm_return_val_if_fail(group != NULL, NULL);
1195 last = group + strlen(group);
1196 abbrev_group = ap = g_malloc(strlen(group) + 1);
1201 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1203 while (*p != '.') p++;
1206 return abbrev_group;
1211 return abbrev_group;
1214 gchar *trim_string(const gchar *str, gint len)
1216 const gchar *p = str;
1221 if (!str) return NULL;
1222 if (strlen(str) <= len)
1223 return g_strdup(str);
1224 if (g_utf8_validate(str, -1, NULL) == FALSE)
1225 return g_strdup(str);
1227 while (*p != '\0') {
1228 mb_len = g_utf8_skip[*(guchar *)p];
1231 else if (new_len + mb_len > len)
1238 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1239 return g_strconcat(new_str, "...", NULL);
1242 GList *uri_list_extract_filenames(const gchar *uri_list)
1244 GList *result = NULL;
1246 gchar *escaped_utf8uri;
1252 while (g_ascii_isspace(*p)) p++;
1253 if (!strncmp(p, "file:", 5)) {
1256 while (*q && *q != '\n' && *q != '\r') q++;
1259 gchar *file, *locale_file = NULL;
1261 while (q > p && g_ascii_isspace(*q))
1263 Xalloca(escaped_utf8uri, q - p + 2,
1265 Xalloca(file, q - p + 2,
1268 strncpy(escaped_utf8uri, p, q - p + 1);
1269 escaped_utf8uri[q - p + 1] = '\0';
1270 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1272 * g_filename_from_uri() rejects escaped/locale encoded uri
1273 * string which come from Nautilus.
1276 if (g_utf8_validate(file, -1, NULL))
1278 = conv_codeset_strdup(
1281 conv_get_locale_charset_str());
1283 locale_file = g_strdup(file + 5);
1285 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1287 result = g_list_append(result, locale_file);
1291 p = strchr(p, '\n');
1298 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1301 static gint axtoi(const gchar *hexstr)
1303 gint hi, lo, result;
1306 if ('0' <= hi && hi <= '9') {
1309 if ('a' <= hi && hi <= 'f') {
1312 if ('A' <= hi && hi <= 'F') {
1317 if ('0' <= lo && lo <= '9') {
1320 if ('a' <= lo && lo <= 'f') {
1323 if ('A' <= lo && lo <= 'F') {
1326 result = lo + (16 * hi);
1330 gboolean is_uri_string(const gchar *str)
1332 while (str && *str && g_ascii_isspace(*str))
1334 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1335 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1336 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1337 g_ascii_strncasecmp(str, "ftps://", 7) == 0 ||
1338 g_ascii_strncasecmp(str, "sftp://", 7) == 0 ||
1339 g_ascii_strncasecmp(str, "ftp.", 4) == 0 ||
1340 g_ascii_strncasecmp(str, "webcal://", 9) == 0 ||
1341 g_ascii_strncasecmp(str, "webcals://", 10) == 0 ||
1342 g_ascii_strncasecmp(str, "www.", 4) == 0);
1345 gchar *get_uri_path(const gchar *uri)
1347 while (uri && *uri && g_ascii_isspace(*uri))
1349 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1350 return (gchar *)(uri + 7);
1351 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1352 return (gchar *)(uri + 8);
1353 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1354 return (gchar *)(uri + 6);
1355 else if (g_ascii_strncasecmp(uri, "ftps://", 7) == 0)
1356 return (gchar *)(uri + 7);
1357 else if (g_ascii_strncasecmp(uri, "sftp://", 7) == 0)
1358 return (gchar *)(uri + 7);
1359 else if (g_ascii_strncasecmp(uri, "webcal://", 9) == 0)
1360 return (gchar *)(uri + 7);
1361 else if (g_ascii_strncasecmp(uri, "webcals://", 10) == 0)
1362 return (gchar *)(uri + 7);
1364 return (gchar *)uri;
1367 gint get_uri_len(const gchar *str)
1371 if (is_uri_string(str)) {
1372 for (p = str; *p != '\0'; p++) {
1373 if (!g_ascii_isgraph(*p) || strchr("<>\"", *p))
1382 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1383 * plusses, and escape characters are used)
1385 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1387 gchar *dec = decoded_uri;
1388 const gchar *enc = encoded_uri;
1393 if (isxdigit((guchar)enc[0]) &&
1394 isxdigit((guchar)enc[1])) {
1400 if (with_plus && *enc == '+')
1412 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1414 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1417 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1419 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1420 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1424 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1425 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1429 const gchar *forbidden_uris[] = { ".gnupg/",
1435 gint num_attach = 0;
1437 cm_return_val_if_fail(mailto != NULL, -1);
1439 Xstrdup_a(tmp_mailto, mailto, return -1);
1441 if (!strncmp(tmp_mailto, "mailto:", 7))
1444 p = strchr(tmp_mailto, '?');
1451 *to = decode_uri_gdup(tmp_mailto);
1454 gchar *field, *value;
1471 if (*value == '\0') continue;
1473 if (from && !g_ascii_strcasecmp(field, "from")) {
1475 *from = decode_uri_gdup(value);
1477 gchar *tmp = decode_uri_gdup(value);
1478 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1483 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1485 *cc = decode_uri_gdup(value);
1487 gchar *tmp = decode_uri_gdup(value);
1488 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1493 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1495 *bcc = decode_uri_gdup(value);
1497 gchar *tmp = decode_uri_gdup(value);
1498 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1503 } else if (subject && !*subject &&
1504 !g_ascii_strcasecmp(field, "subject")) {
1505 *subject = decode_uri_gdup(value);
1506 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1507 *body = decode_uri_gdup(value);
1508 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1510 gchar *tmp = decode_uri_gdup(value);
1512 for (; forbidden_uris[i]; i++) {
1513 if (strstr(tmp, forbidden_uris[i])) {
1514 g_print("Refusing to insert '%s', potential private data leak\n",
1523 if (!is_file_entry_regular(tmp)) {
1524 g_warning("refusing to insert '%s', not a regular file", tmp);
1525 } else if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1526 g_warning("couldn't set insert file '%s' in body", value);
1531 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1533 gchar *tmp = decode_uri_gdup(value);
1534 gchar **my_att = g_malloc(sizeof(char *));
1538 for (; forbidden_uris[i]; i++) {
1539 if (strstr(tmp, forbidden_uris[i])) {
1540 g_print("Refusing to attach '%s', potential private data leak\n",
1548 /* attach is correct */
1550 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1551 my_att[num_attach-1] = tmp;
1552 my_att[num_attach] = NULL;
1557 } else if (inreplyto && !*inreplyto &&
1558 !g_ascii_strcasecmp(field, "in-reply-to")) {
1559 *inreplyto = decode_uri_gdup(value);
1568 #include <windows.h>
1569 #ifndef CSIDL_APPDATA
1570 #define CSIDL_APPDATA 0x001a
1572 #ifndef CSIDL_LOCAL_APPDATA
1573 #define CSIDL_LOCAL_APPDATA 0x001c
1575 #ifndef CSIDL_FLAG_CREATE
1576 #define CSIDL_FLAG_CREATE 0x8000
1578 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1582 w32_strerror (int w32_errno)
1584 static char strerr[256];
1585 int ec = (int)GetLastError ();
1589 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1590 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1591 strerr, DIM (strerr)-1, NULL);
1595 static __inline__ void *
1596 dlopen (const char * name, int flag)
1598 void * hd = LoadLibrary (name);
1602 static __inline__ void *
1603 dlsym (void * hd, const char * sym)
1607 void * fnc = GetProcAddress (hd, sym);
1616 static __inline__ const char *
1619 return w32_strerror (0);
1623 static __inline__ int
1635 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1637 static int initialized;
1638 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1642 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1648 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1650 handle = dlopen (dllnames[i], RTLD_LAZY);
1653 func = dlsym (handle, "SHGetFolderPathW");
1664 return func (a,b,c,d,e);
1669 /* Returns a static string with the directroy from which the module
1670 has been loaded. Returns an empty string on error. */
1671 static char *w32_get_module_dir(void)
1673 static char *moddir;
1676 char name[MAX_PATH+10];
1679 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1682 p = strrchr (name, '\\');
1688 moddir = g_strdup (name);
1692 #endif /* G_OS_WIN32 */
1694 /* Return a static string with the locale dir. */
1695 const gchar *get_locale_dir(void)
1697 static gchar *loc_dir;
1701 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1702 "\\share\\locale", NULL);
1705 loc_dir = LOCALEDIR;
1711 const gchar *get_home_dir(void)
1714 static char home_dir_utf16[MAX_PATH] = "";
1715 static gchar *home_dir_utf8 = NULL;
1716 if (home_dir_utf16[0] == '\0') {
1717 if (w32_shgetfolderpath
1718 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1719 NULL, 0, home_dir_utf16) < 0)
1720 strcpy (home_dir_utf16, "C:\\Claws Mail");
1721 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1723 return home_dir_utf8;
1725 static const gchar *homeenv = NULL;
1730 if (!homeenv && g_getenv("HOME") != NULL)
1731 homeenv = g_strdup(g_getenv("HOME"));
1733 homeenv = g_get_home_dir();
1739 static gchar *claws_rc_dir = NULL;
1740 static gboolean rc_dir_alt = FALSE;
1741 const gchar *get_rc_dir(void)
1744 if (!claws_rc_dir) {
1745 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1747 debug_print("using default rc_dir %s\n", claws_rc_dir);
1749 return claws_rc_dir;
1752 void set_rc_dir(const gchar *dir)
1754 gchar *canonical_dir;
1755 if (claws_rc_dir != NULL) {
1756 g_print("Error: rc_dir already set\n");
1758 int err = cm_canonicalize_filename(dir, &canonical_dir);
1762 g_print("Error looking for %s: %d(%s)\n",
1763 dir, -err, g_strerror(-err));
1768 claws_rc_dir = canonical_dir;
1770 len = strlen(claws_rc_dir);
1771 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1772 claws_rc_dir[len - 1] = '\0';
1774 debug_print("set rc_dir to %s\n", claws_rc_dir);
1775 if (!is_dir_exist(claws_rc_dir)) {
1776 if (make_dir_hier(claws_rc_dir) != 0) {
1777 g_print("Error: can't create %s\n",
1785 gboolean rc_dir_is_alt(void) {
1789 const gchar *get_mail_base_dir(void)
1791 return get_home_dir();
1794 const gchar *get_news_cache_dir(void)
1796 static gchar *news_cache_dir = NULL;
1797 if (!news_cache_dir)
1798 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1799 NEWS_CACHE_DIR, NULL);
1801 return news_cache_dir;
1804 const gchar *get_imap_cache_dir(void)
1806 static gchar *imap_cache_dir = NULL;
1808 if (!imap_cache_dir)
1809 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1810 IMAP_CACHE_DIR, NULL);
1812 return imap_cache_dir;
1815 const gchar *get_mime_tmp_dir(void)
1817 static gchar *mime_tmp_dir = NULL;
1820 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1821 MIME_TMP_DIR, NULL);
1823 return mime_tmp_dir;
1826 const gchar *get_template_dir(void)
1828 static gchar *template_dir = NULL;
1831 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1832 TEMPLATE_DIR, NULL);
1834 return template_dir;
1838 const gchar *w32_get_cert_file(void)
1840 const gchar *cert_file = NULL;
1842 cert_file = g_strconcat(w32_get_module_dir(),
1843 "\\share\\claws-mail\\",
1844 "ca-certificates.crt",
1850 /* Return the filepath of the claws-mail.desktop file */
1851 const gchar *get_desktop_file(void)
1853 #ifdef DESKTOPFILEPATH
1854 return DESKTOPFILEPATH;
1860 /* Return the default directory for Plugins. */
1861 const gchar *get_plugin_dir(void)
1864 static gchar *plugin_dir = NULL;
1867 plugin_dir = g_strconcat(w32_get_module_dir(),
1868 "\\lib\\claws-mail\\plugins\\",
1872 if (is_dir_exist(PLUGINDIR))
1875 static gchar *plugin_dir = NULL;
1877 plugin_dir = g_strconcat(get_rc_dir(),
1878 G_DIR_SEPARATOR_S, "plugins",
1879 G_DIR_SEPARATOR_S, NULL);
1887 /* Return the default directory for Themes. */
1888 const gchar *w32_get_themes_dir(void)
1890 static gchar *themes_dir = NULL;
1893 themes_dir = g_strconcat(w32_get_module_dir(),
1894 "\\share\\claws-mail\\themes",
1900 const gchar *get_tmp_dir(void)
1902 static gchar *tmp_dir = NULL;
1905 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1911 gchar *get_tmp_file(void)
1914 static guint32 id = 0;
1916 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1917 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1922 const gchar *get_domain_name(void)
1925 static gchar *domain_name = NULL;
1926 struct addrinfo hints, *res;
1931 if (gethostname(hostname, sizeof(hostname)) != 0) {
1932 perror("gethostname");
1933 domain_name = "localhost";
1935 memset(&hints, 0, sizeof(struct addrinfo));
1936 hints.ai_family = AF_UNSPEC;
1937 hints.ai_socktype = 0;
1938 hints.ai_flags = AI_CANONNAME;
1939 hints.ai_protocol = 0;
1941 s = getaddrinfo(hostname, NULL, &hints, &res);
1943 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1944 domain_name = g_strdup(hostname);
1946 domain_name = g_strdup(res->ai_canonname);
1950 debug_print("domain name = %s\n", domain_name);
1959 /* Tells whether the given host address string is a valid representation of a
1960 * numerical IP (v4 or, if supported, v6) address.
1962 gboolean is_numeric_host_address(const gchar *hostaddress)
1964 struct addrinfo hints, *res;
1967 /* See what getaddrinfo makes of the string when told that it is a
1968 * numeric IP address representation. */
1969 memset(&hints, 0, sizeof(struct addrinfo));
1970 hints.ai_family = AF_UNSPEC;
1971 hints.ai_socktype = 0;
1972 hints.ai_flags = AI_NUMERICHOST;
1973 hints.ai_protocol = 0;
1975 err = getaddrinfo(hostaddress, NULL, &hints, &res);
1982 off_t get_file_size(const gchar *file)
1987 GError *error = NULL;
1990 f = g_file_new_for_path(file);
1991 fi = g_file_query_info(f, "standard::size",
1992 G_FILE_QUERY_INFO_NONE, NULL, &error);
1993 if (error != NULL) {
1994 debug_print("get_file_size error: %s\n", error->message);
1995 g_error_free(error);
1999 size = g_file_info_get_size(fi);
2007 if (g_stat(file, &s) < 0) {
2008 FILE_OP_ERROR(file, "stat");
2016 time_t get_file_mtime(const gchar *file)
2020 if (g_stat(file, &s) < 0) {
2021 FILE_OP_ERROR(file, "stat");
2028 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2035 if (g_stat(file, &s) < 0) {
2036 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2040 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2047 /* Test on whether FILE is a relative file name. This is
2048 * straightforward for Unix but more complex for Windows. */
2049 gboolean is_relative_filename(const gchar *file)
2054 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2055 return FALSE; /* Prefixed with a hostname - this can't
2056 * be a relative name. */
2058 if ( ((*file >= 'a' && *file <= 'z')
2059 || (*file >= 'A' && *file <= 'Z'))
2061 file += 2; /* Skip drive letter. */
2063 return !(*file == '\\' || *file == '/');
2065 return !(*file == G_DIR_SEPARATOR);
2070 gboolean is_dir_exist(const gchar *dir)
2075 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2078 gboolean is_file_entry_exist(const gchar *file)
2083 return g_file_test(file, G_FILE_TEST_EXISTS);
2086 gboolean is_file_entry_regular(const gchar *file)
2091 return g_file_test(file, G_FILE_TEST_IS_REGULAR);
2094 gboolean dirent_is_regular_file(struct dirent *d)
2096 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2097 if (d->d_type == DT_REG)
2099 else if (d->d_type != DT_UNKNOWN)
2103 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2106 gint change_dir(const gchar *dir)
2108 gchar *prevdir = NULL;
2111 prevdir = g_get_current_dir();
2113 if (g_chdir(dir) < 0) {
2114 FILE_OP_ERROR(dir, "chdir");
2115 if (debug_mode) g_free(prevdir);
2117 } else if (debug_mode) {
2120 cwd = g_get_current_dir();
2121 if (strcmp(prevdir, cwd) != 0)
2122 g_print("current dir: %s\n", cwd);
2130 gint make_dir(const gchar *dir)
2132 if (g_mkdir(dir, S_IRWXU) < 0) {
2133 FILE_OP_ERROR(dir, "mkdir");
2136 if (g_chmod(dir, S_IRWXU) < 0)
2137 FILE_OP_ERROR(dir, "chmod");
2142 gint make_dir_hier(const gchar *dir)
2147 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2148 parent_dir = g_strndup(dir, p - dir);
2149 if (*parent_dir != '\0') {
2150 if (!is_dir_exist(parent_dir)) {
2151 if (make_dir(parent_dir) < 0) {
2160 if (!is_dir_exist(dir)) {
2161 if (make_dir(dir) < 0)
2168 gint remove_all_files(const gchar *dir)
2171 const gchar *file_name;
2174 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2175 g_warning("failed to open directory: %s", dir);
2179 while ((file_name = g_dir_read_name(dp)) != NULL) {
2180 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2181 if (claws_unlink(tmp) < 0)
2182 FILE_OP_ERROR(tmp, "unlink");
2191 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2194 const gchar *dir_name;
2198 if (first == last) {
2199 /* Skip all the dir reading part. */
2200 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2201 if (is_dir_exist(filename)) {
2202 /* a numbered directory with this name exists,
2203 * remove the dot-file instead */
2205 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2207 if (claws_unlink(filename) < 0) {
2208 FILE_OP_ERROR(filename, "unlink");
2216 prev_dir = g_get_current_dir();
2218 if (g_chdir(dir) < 0) {
2219 FILE_OP_ERROR(dir, "chdir");
2224 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2225 g_warning("failed to open directory: %s", dir);
2230 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2231 file_no = to_number(dir_name);
2232 if (file_no > 0 && first <= file_no && file_no <= last) {
2233 if (is_dir_exist(dir_name)) {
2234 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2235 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2236 FILE_OP_ERROR(dot_file, "unlink");
2241 if (claws_unlink(dir_name) < 0)
2242 FILE_OP_ERROR(dir_name, "unlink");
2248 if (g_chdir(prev_dir) < 0) {
2249 FILE_OP_ERROR(prev_dir, "chdir");
2259 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2262 const gchar *dir_name;
2265 GHashTable *wanted_files;
2267 GError *error = NULL;
2269 if (numberlist == NULL)
2272 prev_dir = g_get_current_dir();
2274 if (g_chdir(dir) < 0) {
2275 FILE_OP_ERROR(dir, "chdir");
2280 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2281 g_message("Couldn't open current directory: %s (%d).\n",
2282 error->message, error->code);
2283 g_error_free(error);
2288 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2289 for (cur = numberlist; cur != NULL; cur = cur->next) {
2290 /* numberlist->data is expected to be GINT_TO_POINTER */
2291 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2294 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2295 file_no = to_number(dir_name);
2296 if (is_dir_exist(dir_name))
2298 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2299 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2300 if (is_dir_exist(dir_name)) {
2301 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2302 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2303 FILE_OP_ERROR(dot_file, "unlink");
2308 if (claws_unlink(dir_name) < 0)
2309 FILE_OP_ERROR(dir_name, "unlink");
2314 g_hash_table_destroy(wanted_files);
2316 if (g_chdir(prev_dir) < 0) {
2317 FILE_OP_ERROR(prev_dir, "chdir");
2327 gint remove_all_numbered_files(const gchar *dir)
2329 return remove_numbered_files(dir, 0, UINT_MAX);
2332 gint remove_dir_recursive(const gchar *dir)
2336 const gchar *dir_name;
2339 if (g_stat(dir, &s) < 0) {
2340 FILE_OP_ERROR(dir, "stat");
2341 if (ENOENT == errno) return 0;
2345 if (!S_ISDIR(s.st_mode)) {
2346 if (claws_unlink(dir) < 0) {
2347 FILE_OP_ERROR(dir, "unlink");
2354 prev_dir = g_get_current_dir();
2355 /* g_print("prev_dir = %s\n", prev_dir); */
2357 if (!path_cmp(prev_dir, dir)) {
2359 if (g_chdir("..") < 0) {
2360 FILE_OP_ERROR(dir, "chdir");
2363 prev_dir = g_get_current_dir();
2366 if (g_chdir(dir) < 0) {
2367 FILE_OP_ERROR(dir, "chdir");
2372 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2373 g_warning("failed to open directory: %s", dir);
2379 /* remove all files in the directory */
2380 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2381 /* g_print("removing %s\n", dir_name); */
2383 if (is_dir_exist(dir_name)) {
2386 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2387 g_warning("can't remove directory: %s", dir_name);
2392 if (claws_unlink(dir_name) < 0)
2393 FILE_OP_ERROR(dir_name, "unlink");
2399 if (g_chdir(prev_dir) < 0) {
2400 FILE_OP_ERROR(prev_dir, "chdir");
2407 if (g_rmdir(dir) < 0) {
2408 FILE_OP_ERROR(dir, "rmdir");
2415 /* convert line endings into CRLF. If the last line doesn't end with
2416 * linebreak, add it.
2418 gchar *canonicalize_str(const gchar *str)
2424 for (p = str; *p != '\0'; ++p) {
2431 if (p == str || *(p - 1) != '\n')
2434 out = outp = g_malloc(new_len + 1);
2435 for (p = str; *p != '\0'; ++p) {
2442 if (p == str || *(p - 1) != '\n') {
2451 gchar *normalize_newlines(const gchar *str)
2456 out = outp = g_malloc(strlen(str) + 1);
2457 for (p = str; *p != '\0'; ++p) {
2459 if (*(p + 1) != '\n')
2470 gchar *get_outgoing_rfc2822_str(FILE *fp)
2472 gchar buf[BUFFSIZE];
2476 str = g_string_new(NULL);
2478 /* output header part */
2479 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2481 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2488 else if (next != ' ' && next != '\t') {
2492 if (claws_fgets(buf, sizeof(buf), fp) == NULL)
2496 g_string_append(str, buf);
2497 g_string_append(str, "\r\n");
2503 /* output body part */
2504 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2507 g_string_append_c(str, '.');
2508 g_string_append(str, buf);
2509 g_string_append(str, "\r\n");
2513 g_string_free(str, FALSE);
2519 * Create a new boundary in a way that it is very unlikely that this
2520 * will occur in the following text. It would be easy to ensure
2521 * uniqueness if everything is either quoted-printable or base64
2522 * encoded (note that conversion is allowed), but because MIME bodies
2523 * may be nested, it may happen that the same boundary has already
2526 * boundary := 0*69<bchars> bcharsnospace
2527 * bchars := bcharsnospace / " "
2528 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2529 * "+" / "_" / "," / "-" / "." /
2530 * "/" / ":" / "=" / "?"
2532 * some special characters removed because of buggy MTAs
2535 gchar *generate_mime_boundary(const gchar *prefix)
2537 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2538 "abcdefghijklmnopqrstuvwxyz"
2543 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2544 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2547 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2551 char *fgets_crlf(char *buf, int size, FILE *stream)
2553 gboolean is_cr = FALSE;
2554 gboolean last_was_cr = FALSE;
2559 while (--size > 0 && (c = getc(stream)) != EOF)
2562 is_cr = (c == '\r');
2572 last_was_cr = is_cr;
2574 if (c == EOF && cs == buf)
2582 static gint execute_async(gchar *const argv[], const gchar *working_directory)
2584 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2586 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2587 NULL, NULL, NULL, FALSE) == FALSE) {
2588 g_warning("couldn't execute command: %s", argv[0]);
2595 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
2599 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2602 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2603 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2604 g_warning("couldn't execute command: %s", argv[0]);
2608 if (WIFEXITED(status))
2609 return WEXITSTATUS(status);
2613 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
2614 G_SPAWN_SEARCH_PATH|
2615 G_SPAWN_CHILD_INHERITS_STDIN|
2616 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
2617 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2618 g_warning("couldn't execute command: %s", argv[0]);
2626 gint execute_command_line(const gchar *cmdline, gboolean async,
2627 const gchar *working_directory)
2632 cm_return_val_if_fail(cmdline != NULL, -1);
2634 debug_print("execute_command_line(): executing: %s\n", cmdline);
2636 argv = strsplit_with_quote(cmdline, " ", 0);
2639 ret = execute_async(argv, working_directory);
2641 ret = execute_sync(argv, working_directory);
2648 gchar *get_command_output(const gchar *cmdline)
2650 gchar *child_stdout;
2653 cm_return_val_if_fail(cmdline != NULL, NULL);
2655 debug_print("get_command_output(): executing: %s\n", cmdline);
2657 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
2659 g_warning("couldn't execute command: %s", cmdline);
2663 return child_stdout;
2666 FILE *get_command_output_stream(const char* cmdline)
2670 gchar **argv = NULL;
2673 cm_return_val_if_fail(cmdline != NULL, NULL);
2675 debug_print("get_command_output_stream(): executing: %s\n", cmdline);
2677 /* turn the command-line string into an array */
2678 if (!g_shell_parse_argv(cmdline, NULL, &argv, &err)) {
2679 g_warning("could not parse command line from '%s': %s", cmdline, err->message);
2684 if (!g_spawn_async_with_pipes(NULL, argv, NULL, G_SPAWN_SEARCH_PATH,
2685 NULL, NULL, &pid, NULL, &fd, NULL, &err)
2688 g_warning("could not spawn '%s': %s", cmdline, err->message);
2695 return fdopen(fd, "r");
2699 static gint is_unchanged_uri_char(char c)
2710 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2716 for(i = 0; i < strlen(uri) ; i++) {
2717 if (is_unchanged_uri_char(uri[i])) {
2718 if (k + 2 >= bufsize)
2720 encoded_uri[k++] = uri[i];
2723 char * hexa = "0123456789ABCDEF";
2725 if (k + 4 >= bufsize)
2727 encoded_uri[k++] = '%';
2728 encoded_uri[k++] = hexa[uri[i] / 16];
2729 encoded_uri[k++] = hexa[uri[i] % 16];
2736 gint open_uri(const gchar *uri, const gchar *cmdline)
2740 gchar buf[BUFFSIZE];
2742 gchar encoded_uri[BUFFSIZE];
2743 cm_return_val_if_fail(uri != NULL, -1);
2745 /* an option to choose whether to use encode_uri or not ? */
2746 encode_uri(encoded_uri, BUFFSIZE, uri);
2749 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2750 !strchr(p + 2, '%'))
2751 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
2754 g_warning("Open URI command-line is invalid "
2755 "(there must be only one '%%s'): %s",
2757 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
2760 execute_command_line(buf, TRUE, NULL);
2762 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
2767 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
2769 gchar buf[BUFFSIZE];
2772 cm_return_val_if_fail(filepath != NULL, -1);
2775 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2776 !strchr(p + 2, '%'))
2777 g_snprintf(buf, sizeof(buf), cmdline, filepath);
2780 g_warning("Open Text Editor command-line is invalid "
2781 "(there must be only one '%%s'): %s",
2783 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
2786 execute_command_line(buf, TRUE, NULL);
2791 time_t remote_tzoffset_sec(const gchar *zone)
2793 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
2799 time_t remoteoffset;
2801 strncpy(zone3, zone, 3);
2805 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
2806 (c == '+' || c == '-')) {
2807 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
2809 remoteoffset = -remoteoffset;
2810 } else if (!strncmp(zone, "UT" , 2) ||
2811 !strncmp(zone, "GMT", 3)) {
2813 } else if (strlen(zone3) == 3) {
2814 for (p = ustzstr; *p != '\0'; p += 3) {
2815 if (!g_ascii_strncasecmp(p, zone3, 3)) {
2816 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
2817 remoteoffset = iustz * 3600;
2823 } else if (strlen(zone3) == 1) {
2825 case 'Z': remoteoffset = 0; break;
2826 case 'A': remoteoffset = -1; break;
2827 case 'B': remoteoffset = -2; break;
2828 case 'C': remoteoffset = -3; break;
2829 case 'D': remoteoffset = -4; break;
2830 case 'E': remoteoffset = -5; break;
2831 case 'F': remoteoffset = -6; break;
2832 case 'G': remoteoffset = -7; break;
2833 case 'H': remoteoffset = -8; break;
2834 case 'I': remoteoffset = -9; break;
2835 case 'K': remoteoffset = -10; break; /* J is not used */
2836 case 'L': remoteoffset = -11; break;
2837 case 'M': remoteoffset = -12; break;
2838 case 'N': remoteoffset = 1; break;
2839 case 'O': remoteoffset = 2; break;
2840 case 'P': remoteoffset = 3; break;
2841 case 'Q': remoteoffset = 4; break;
2842 case 'R': remoteoffset = 5; break;
2843 case 'S': remoteoffset = 6; break;
2844 case 'T': remoteoffset = 7; break;
2845 case 'U': remoteoffset = 8; break;
2846 case 'V': remoteoffset = 9; break;
2847 case 'W': remoteoffset = 10; break;
2848 case 'X': remoteoffset = 11; break;
2849 case 'Y': remoteoffset = 12; break;
2850 default: remoteoffset = 0; break;
2852 remoteoffset = remoteoffset * 3600;
2856 return remoteoffset;
2859 time_t tzoffset_sec(time_t *now)
2863 struct tm buf1, buf2;
2865 if (now && *now < 0)
2868 gmt = *gmtime_r(now, &buf1);
2869 lt = localtime_r(now, &buf2);
2871 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2873 if (lt->tm_year < gmt.tm_year)
2875 else if (lt->tm_year > gmt.tm_year)
2877 else if (lt->tm_yday < gmt.tm_yday)
2879 else if (lt->tm_yday > gmt.tm_yday)
2882 if (off >= 24 * 60) /* should be impossible */
2883 off = 23 * 60 + 59; /* if not, insert silly value */
2884 if (off <= -24 * 60)
2885 off = -(23 * 60 + 59);
2890 /* calculate timezone offset */
2891 gchar *tzoffset(time_t *now)
2893 static gchar offset_string[6];
2897 struct tm buf1, buf2;
2899 if (now && *now < 0)
2902 gmt = *gmtime_r(now, &buf1);
2903 lt = localtime_r(now, &buf2);
2905 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2907 if (lt->tm_year < gmt.tm_year)
2909 else if (lt->tm_year > gmt.tm_year)
2911 else if (lt->tm_yday < gmt.tm_yday)
2913 else if (lt->tm_yday > gmt.tm_yday)
2921 if (off >= 24 * 60) /* should be impossible */
2922 off = 23 * 60 + 59; /* if not, insert silly value */
2924 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
2926 return offset_string;
2929 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
2933 gchar day[4], mon[4];
2934 gint dd, hh, mm, ss, yyyy;
2936 gchar buf2[RFC822_DATE_BUFFSIZE];
2940 lt = gmtime_r(&t, &buf1);
2942 lt = localtime_r(&t, &buf1);
2944 if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
2945 day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
2946 g_warning("failed reading date/time");
2948 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
2949 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
2952 void get_rfc822_date(gchar *buf, gint len)
2954 _get_rfc822_date(buf, len, FALSE);
2957 void get_rfc822_date_hide_tz(gchar *buf, gint len)
2959 _get_rfc822_date(buf, len, TRUE);
2962 void debug_set_mode(gboolean mode)
2967 gboolean debug_get_mode(void)
2973 void debug_print_real(const char *file, int line, const gchar *format, ...)
2976 gchar buf[BUFFSIZE];
2979 if (!debug_mode) return;
2981 prefix_len = g_snprintf(buf, sizeof(buf), "%s:%d:", debug_srcname(file), line);
2983 va_start(args, format);
2984 g_vsnprintf(buf + prefix_len, sizeof(buf) - prefix_len, format, args);
2990 void debug_print_real(const gchar *format, ...)
2993 gchar buf[BUFFSIZE];
2995 if (!debug_mode) return;
2997 va_start(args, format);
2998 g_vsnprintf(buf, sizeof(buf), format, args);
3006 const char * debug_srcname(const char *file)
3008 const char *s = strrchr (file, '/');
3013 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3015 if (subject == NULL)
3018 subject += subject_get_prefix_length(subject);
3020 return g_hash_table_lookup(subject_table, subject);
3023 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3026 if (subject == NULL || *subject == 0)
3028 subject += subject_get_prefix_length(subject);
3029 g_hash_table_insert(subject_table, subject, data);
3032 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3034 if (subject == NULL)
3037 subject += subject_get_prefix_length(subject);
3038 g_hash_table_remove(subject_table, subject);
3041 static regex_t u_regex;
3042 static gboolean u_init_;
3044 void utils_free_regex(void)
3053 *\brief Check if a string is prefixed with known (combinations)
3054 * of prefixes. The function assumes that each prefix
3055 * is terminated by zero or exactly _one_ space.
3057 *\param str String to check for a prefixes
3059 *\return int Number of chars in the prefix that should be skipped
3060 * for a "clean" subject line. If no prefix was found, 0
3063 int subject_get_prefix_length(const gchar *subject)
3065 /*!< Array with allowable reply prefixes regexps. */
3066 static const gchar * const prefixes[] = {
3067 "Re\\:", /* "Re:" */
3068 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3069 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3070 "Aw\\:", /* "Aw:" (German) */
3071 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3072 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3073 "Fw\\:", /* "Fw:" Forward */
3074 "Fwd\\:", /* "Fwd:" Forward */
3075 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3076 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3077 "Rif\\:", /* "Rif:" (Italian Outlook) */
3078 "Sv\\:", /* "Sv" (Norwegian) */
3079 "Vs\\:", /* "Vs" (Norwegian) */
3080 "Ad\\:", /* "Ad" (Norwegian) */
3081 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3082 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3083 "Re \\:", /* "Re :" (French Yahoo Mail) */
3086 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3090 if (!subject) return 0;
3091 if (!*subject) return 0;
3094 GString *s = g_string_new("");
3096 for (n = 0; n < PREFIXES; n++)
3097 /* Terminate each prefix regexpression by a
3098 * "\ ?" (zero or ONE space), and OR them */
3099 g_string_append_printf(s, "(%s\\ ?)%s",
3104 g_string_prepend(s, "(");
3105 g_string_append(s, ")+"); /* match at least once */
3106 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3109 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3110 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3111 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3112 debug_print("Error compiling regexp %s\n", s->str);
3113 g_string_free(s, TRUE);
3117 g_string_free(s, TRUE);
3121 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3127 static guint g_stricase_hash(gconstpointer gptr)
3129 guint hash_result = 0;
3132 for (str = gptr; str && *str; str++) {
3133 hash_result += toupper(*str);
3139 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3141 const char *str1 = gptr1;
3142 const char *str2 = gptr2;
3144 return !strcasecmp(str1, str2);
3147 gint g_int_compare(gconstpointer a, gconstpointer b)
3149 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3153 quote_cmd_argument()
3155 return a quoted string safely usable in argument of a command.
3157 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3160 gint quote_cmd_argument(gchar * result, guint size,
3170 for(p = path ; * p != '\0' ; p ++) {
3172 if (isalnum((guchar)*p) || (* p == '/')) {
3173 if (remaining > 0) {
3179 result[size - 1] = '\0';
3184 if (remaining >= 2) {
3192 result[size - 1] = '\0';
3197 if (remaining > 0) {
3201 result[size - 1] = '\0';
3215 static void g_node_map_recursive(GNode *node, gpointer data)
3217 GNodeMapData *mapdata = (GNodeMapData *) data;
3219 GNodeMapData newmapdata;
3222 newdata = mapdata->func(node->data, mapdata->data);
3223 if (newdata != NULL) {
3224 newnode = g_node_new(newdata);
3225 g_node_append(mapdata->parent, newnode);
3227 newmapdata.parent = newnode;
3228 newmapdata.func = mapdata->func;
3229 newmapdata.data = mapdata->data;
3231 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3235 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3238 GNodeMapData mapdata;
3240 cm_return_val_if_fail(node != NULL, NULL);
3241 cm_return_val_if_fail(func != NULL, NULL);
3243 root = g_node_new(func(node->data, data));
3245 mapdata.parent = root;
3246 mapdata.func = func;
3247 mapdata.data = data;
3249 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3254 #define HEX_TO_INT(val, hex) \
3258 if ('0' <= c && c <= '9') { \
3260 } else if ('a' <= c && c <= 'f') { \
3261 val = c - 'a' + 10; \
3262 } else if ('A' <= c && c <= 'F') { \
3263 val = c - 'A' + 10; \
3269 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3276 if (hi == -1 || lo == -1)
3279 *out = (hi << 4) + lo;
3283 #define INT_TO_HEX(hex, val) \
3286 hex = '0' + (val); \
3288 hex = 'A' + (val) - 10; \
3291 void get_hex_str(gchar *out, guchar ch)
3295 INT_TO_HEX(hex, ch >> 4);
3297 INT_TO_HEX(hex, ch & 0x0f);
3303 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3305 #define G_PRINT_REF g_print
3309 *\brief Register ref counted pointer. It is based on GBoxed, so should
3310 * work with anything that uses the GType system. The semantics
3311 * are similar to a C++ auto pointer, with the exception that
3312 * C doesn't have automatic closure (calling destructors) when
3313 * exiting a block scope.
3314 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3315 * function directly.
3317 *\return GType A GType type.
3319 GType g_auto_pointer_register(void)
3321 static GType auto_pointer_type;
3322 if (!auto_pointer_type)
3324 g_boxed_type_register_static
3325 ("G_TYPE_AUTO_POINTER",
3326 (GBoxedCopyFunc) g_auto_pointer_copy,
3327 (GBoxedFreeFunc) g_auto_pointer_free);
3328 return auto_pointer_type;
3332 *\brief Structure with g_new() allocated pointer guarded by the
3335 typedef struct AutoPointerRef {
3336 void (*free) (gpointer);
3342 *\brief The auto pointer opaque structure that references the
3343 * pointer guard block.
3345 typedef struct AutoPointer {
3346 AutoPointerRef *ref;
3347 gpointer ptr; /*!< access to protected pointer */
3351 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3355 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3356 * ... when assigning, copying and freeing storage elements
3358 * gtk_list_store_new(N_S_COLUMNS,
3359 * G_TYPE_AUTO_POINTER,
3363 * Template *precious_data = g_new0(Template, 1);
3364 * g_pointer protect = g_auto_pointer_new(precious_data);
3366 * gtk_list_store_set(container, &iter,
3370 * ... the gtk_list_store has copied the pointer and
3371 * ... incremented its reference count, we should free
3372 * ... the auto pointer (in C++ a destructor would do
3373 * ... this for us when leaving block scope)
3375 * g_auto_pointer_free(protect);
3377 * ... gtk_list_store_set() now manages the data. When
3378 * ... *explicitly* requesting a pointer from the list
3379 * ... store, don't forget you get a copy that should be
3380 * ... freed with g_auto_pointer_free() eventually.
3384 *\param pointer Pointer to be guarded.
3386 *\return GAuto * Pointer that should be used in containers with
3389 GAuto *g_auto_pointer_new(gpointer p)
3391 AutoPointerRef *ref;
3397 ref = g_new0(AutoPointerRef, 1);
3398 ptr = g_new0(AutoPointer, 1);
3408 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3414 *\brief Allocate an autopointer using the passed \a free function to
3415 * free the guarded pointer
3417 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3424 aptr = g_auto_pointer_new(p);
3425 aptr->ref->free = free_;
3429 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3431 if (auto_ptr == NULL)
3433 return ((AutoPointer *) auto_ptr)->ptr;
3437 *\brief Copies an auto pointer by. It's mostly not necessary
3438 * to call this function directly, unless you copy/assign
3439 * the guarded pointer.
3441 *\param auto_ptr Auto pointer returned by previous call to
3442 * g_auto_pointer_new_XXX()
3444 *\return gpointer An auto pointer
3446 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3449 AutoPointerRef *ref;
3452 if (auto_ptr == NULL)
3457 newp = g_new0(AutoPointer, 1);
3460 newp->ptr = ref->pointer;
3464 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3470 *\brief Free an auto pointer
3472 void g_auto_pointer_free(GAuto *auto_ptr)
3475 AutoPointerRef *ref;
3477 if (auto_ptr == NULL)
3483 if (--(ref->cnt) == 0) {
3485 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3487 ref->free(ref->pointer);
3492 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3497 /* get_uri_part() - retrieves a URI starting from scanpos.
3498 Returns TRUE if successful */
3499 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
3500 const gchar **bp, const gchar **ep, gboolean hdr)
3503 gint parenthese_cnt = 0;
3505 cm_return_val_if_fail(start != NULL, FALSE);
3506 cm_return_val_if_fail(scanpos != NULL, FALSE);
3507 cm_return_val_if_fail(bp != NULL, FALSE);
3508 cm_return_val_if_fail(ep != NULL, FALSE);
3512 /* find end point of URI */
3513 for (ep_ = scanpos; *ep_ != '\0'; ep_ = g_utf8_next_char(ep_)) {
3514 gunichar u = g_utf8_get_char_validated(ep_, -1);
3515 if (!g_unichar_isgraph(u) ||
3516 u == (gunichar)-1 ||
3517 strchr("[]{}<>\"", *ep_)) {
3519 } else if (strchr("(", *ep_)) {
3521 } else if (strchr(")", *ep_)) {
3522 if (parenthese_cnt > 0)
3529 /* no punctuation at end of string */
3531 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
3532 * should pass some URI type to this function and decide on that whether
3533 * to perform punctuation stripping */
3535 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
3537 for (; ep_ - 1 > scanpos + 1 &&
3538 IS_REAL_PUNCT(*(ep_ - 1));
3542 #undef IS_REAL_PUNCT
3549 gchar *make_uri_string(const gchar *bp, const gchar *ep)
3551 while (bp && *bp && g_ascii_isspace(*bp))
3553 return g_strndup(bp, ep - bp);
3556 /* valid mail address characters */
3557 #define IS_RFC822_CHAR(ch) \
3561 !g_ascii_isspace(ch) && \
3562 !strchr("(),;<>\"", (ch)))
3564 /* alphabet and number within 7bit ASCII */
3565 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
3566 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
3568 static GHashTable *create_domain_tab(void)
3571 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
3573 cm_return_val_if_fail(htab, NULL);
3574 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
3575 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
3579 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
3581 gchar buf[BUFFSIZE + 1];
3582 const gchar *m = buf + BUFFSIZE + 1;
3585 if (last - first > BUFFSIZE || first > last)
3588 for (p = buf; p < m && first < last; *p++ = *first++)
3592 return g_hash_table_lookup(tab, buf) != NULL;
3595 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
3596 gboolean get_email_part(const gchar *start, const gchar *scanpos,
3597 const gchar **bp, const gchar **ep, gboolean hdr)
3599 /* more complex than the uri part because we need to scan back and forward starting from
3600 * the scan position. */
3601 gboolean result = FALSE;
3602 const gchar *bp_ = NULL;
3603 const gchar *ep_ = NULL;
3604 static GHashTable *dom_tab;
3605 const gchar *last_dot = NULL;
3606 const gchar *prelast_dot = NULL;
3607 const gchar *last_tld_char = NULL;
3609 /* the informative part of the email address (describing the name
3610 * of the email address owner) may contain quoted parts. the
3611 * closure stack stores the last encountered quotes. */
3612 gchar closure_stack[128];
3613 gchar *ptr = closure_stack;
3615 cm_return_val_if_fail(start != NULL, FALSE);
3616 cm_return_val_if_fail(scanpos != NULL, FALSE);
3617 cm_return_val_if_fail(bp != NULL, FALSE);
3618 cm_return_val_if_fail(ep != NULL, FALSE);
3621 const gchar *start_quote = NULL;
3622 const gchar *end_quote = NULL;
3624 /* go to the real start */
3625 if (start[0] == ',')
3627 if (start[0] == ';')
3629 while (start[0] == '\n' || start[0] == '\r')
3631 while (start[0] == ' ' || start[0] == '\t')
3636 /* check if there are quotes (to skip , in them) */
3637 if (*start == '"') {
3638 start_quote = start;
3640 end_quote = strstr(start, "\"");
3646 /* skip anything between quotes */
3647 if (start_quote && end_quote) {
3652 /* find end (either , or ; or end of line) */
3653 if (strstr(start, ",") && strstr(start, ";"))
3654 *ep = strstr(start,",") < strstr(start, ";")
3655 ? strstr(start, ",") : strstr(start, ";");
3656 else if (strstr(start, ","))
3657 *ep = strstr(start, ",");
3658 else if (strstr(start, ";"))
3659 *ep = strstr(start, ";");
3661 *ep = start+strlen(start);
3663 /* go back to real start */
3664 if (start_quote && end_quote) {
3665 start = start_quote;
3668 /* check there's still an @ in that, or search
3669 * further if possible */
3670 if (strstr(start, "@") && strstr(start, "@") < *ep)
3672 else if (*ep < start+strlen(start)) {
3675 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
3683 dom_tab = create_domain_tab();
3684 cm_return_val_if_fail(dom_tab, FALSE);
3686 /* scan start of address */
3687 for (bp_ = scanpos - 1;
3688 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
3691 /* TODO: should start with an alnum? */
3693 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
3696 if (bp_ != scanpos) {
3697 /* scan end of address */
3698 for (ep_ = scanpos + 1;
3699 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
3701 prelast_dot = last_dot;
3703 if (*(last_dot + 1) == '.') {
3704 if (prelast_dot == NULL)
3706 last_dot = prelast_dot;
3711 /* TODO: really should terminate with an alnum? */
3712 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
3717 if (last_dot == NULL)
3719 if (last_dot >= ep_)
3720 last_dot = prelast_dot;
3721 if (last_dot == NULL || (scanpos + 1 >= last_dot))
3725 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
3726 if (*last_tld_char == '?')
3729 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
3736 if (!result) return FALSE;
3738 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
3739 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
3740 && IS_RFC822_CHAR(*(ep_ + 3))) {
3741 /* this informative part with an @ in it is
3742 * followed by the email address */
3745 /* go to matching '>' (or next non-rfc822 char, like \n) */
3746 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
3749 /* include the bracket */
3750 if (*ep_ == '>') ep_++;
3752 /* include the leading quote */
3760 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
3761 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
3764 /* see if this is <bracketed>; in this case we also scan for the informative part. */
3765 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
3768 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
3769 #define IN_STACK() (ptr > closure_stack)
3770 /* has underrun check */
3771 #define POP_STACK() if(IN_STACK()) --ptr
3772 /* has overrun check */
3773 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
3774 /* has underrun check */
3775 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
3779 /* scan for the informative part. */
3780 for (bp_ -= 2; bp_ >= start; bp_--) {
3781 /* if closure on the stack keep scanning */
3782 if (PEEK_STACK() == *bp_) {
3786 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
3791 /* if nothing in the closure stack, do the special conditions
3792 * the following if..else expression simply checks whether
3793 * a token is acceptable. if not acceptable, the clause
3794 * should terminate the loop with a 'break' */
3795 if (!PEEK_STACK()) {
3797 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
3798 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
3799 /* hyphens are allowed, but only in
3801 } else if (strchr(" \"'", *bp_)) {
3802 /* but anything not being a punctiation
3805 break; /* anything else is rejected */
3812 /* scan forward (should start with an alnum) */
3813 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
3829 #undef IS_ASCII_ALNUM
3830 #undef IS_RFC822_CHAR
3832 gchar *make_email_string(const gchar *bp, const gchar *ep)
3834 /* returns a mailto: URI; mailto: is also used to detect the
3835 * uri type later on in the button_pressed signal handler */
3840 tmp = g_strndup(bp, ep - bp);
3842 /* If there is a colon in the username part of the address,
3843 * we're dealing with an URI for some other protocol - do
3844 * not prefix with mailto: in such case. */
3845 colon = strchr(tmp, ':');
3846 at = strchr(tmp, '@');
3847 if (colon != NULL && at != NULL && colon < at) {
3850 result = g_strconcat("mailto:", tmp, NULL);
3857 gchar *make_http_string(const gchar *bp, const gchar *ep)
3859 /* returns an http: URI; */
3863 while (bp && *bp && g_ascii_isspace(*bp))
3865 tmp = g_strndup(bp, ep - bp);
3866 result = g_strconcat("http://", tmp, NULL);
3872 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
3874 FILE *fp = claws_fopen(path, "rb");
3875 gchar buf[BUFFSIZE];
3876 gchar *result = NULL;
3879 while (claws_fgets(buf, sizeof (buf), fp) != NULL) {
3880 gchar **parts = g_strsplit(buf, ";", 3);
3881 gchar *trimmed = parts[0];
3882 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3884 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3885 trimmed[strlen(trimmed)-1] = '\0';
3887 if (!strcmp(trimmed, type)) {
3888 gboolean needsterminal = FALSE;
3889 if (parts[2] && strstr(parts[2], "needsterminal")) {
3890 needsterminal = TRUE;
3892 if (parts[2] && strstr(parts[2], "test=")) {
3893 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
3894 gchar *testcmd = orig_testcmd;
3895 if (strstr(testcmd,";"))
3896 *(strstr(testcmd,";")) = '\0';
3897 while (testcmd[0] == ' ' || testcmd[0] == '\t')
3899 while (testcmd[strlen(testcmd)-1] == '\n')
3900 testcmd[strlen(testcmd)-1] = '\0';
3901 while (testcmd[strlen(testcmd)-1] == '\r')
3902 testcmd[strlen(testcmd)-1] = '\0';
3903 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
3904 testcmd[strlen(testcmd)-1] = '\0';
3906 if (strstr(testcmd, "%s")) {
3907 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
3908 gint res = system(tmp);
3910 g_free(orig_testcmd);
3917 gint res = system(testcmd);
3918 g_free(orig_testcmd);
3928 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3930 while (trimmed[strlen(trimmed)-1] == '\n')
3931 trimmed[strlen(trimmed)-1] = '\0';
3932 while (trimmed[strlen(trimmed)-1] == '\r')
3933 trimmed[strlen(trimmed)-1] = '\0';
3934 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3935 trimmed[strlen(trimmed)-1] = '\0';
3936 result = g_strdup(trimmed);
3939 if (needsterminal) {
3940 gchar *tmp = g_strdup_printf("xterm -e %s", result);
3951 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
3953 gchar *result = NULL;
3957 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3958 result = mailcap_get_command_in_file(path, type, file_to_open);
3962 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
3966 void mailcap_update_default(const gchar *type, const gchar *command)
3968 gchar *path = NULL, *outpath = NULL;
3969 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3970 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
3971 FILE *fp = claws_fopen(path, "rb");
3973 gchar buf[BUFFSIZE];
3974 gboolean err = FALSE;
3977 fp = claws_fopen(path, "a");
3979 g_warning("failed to create file %s", path);
3984 fp = g_freopen(path, "rb", fp);
3986 g_warning("failed to reopen file %s", path);
3993 outfp = claws_fopen(outpath, "wb");
3995 g_warning("failed to create file %s", outpath);
4001 while (fp && claws_fgets(buf, sizeof (buf), fp) != NULL) {
4002 gchar **parts = g_strsplit(buf, ";", 3);
4003 gchar *trimmed = parts[0];
4004 while (trimmed[0] == ' ')
4006 while (trimmed[strlen(trimmed)-1] == ' ')
4007 trimmed[strlen(trimmed)-1] = '\0';
4009 if (!strcmp(trimmed, type)) {
4014 if(claws_fputs(buf, outfp) == EOF) {
4022 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4028 if (claws_safe_fclose(outfp) == EOF)
4032 g_rename(outpath, path);
4038 /* crude test to see if a file is an email. */
4039 gboolean file_is_email (const gchar *filename)
4044 if (filename == NULL)
4046 if ((fp = claws_fopen(filename, "rb")) == NULL)
4049 && claws_fgets(buffer, sizeof (buffer), fp) != NULL) {
4050 if (!strncmp(buffer, "From:", strlen("From:")))
4052 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4054 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4056 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4058 else if (!strcmp(buffer, "\r\n")) {
4059 debug_print("End of headers\n");
4064 return (score >= 3);
4067 gboolean sc_g_list_bigger(GList *list, gint max)
4071 while (cur && i <= max+1) {
4078 gboolean sc_g_slist_bigger(GSList *list, gint max)
4082 while (cur && i <= max+1) {
4089 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4090 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4091 NULL, NULL, NULL, NULL, NULL, NULL};
4092 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4093 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4094 NULL, NULL, NULL, NULL, NULL, NULL};
4096 gint daynames_len[] = {0,0,0,0,0,0,0};
4097 gint monthnames_len[] = {0,0,0,0,0,0,
4099 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4100 gint s_monthnames_len[] = {0,0,0,0,0,0,
4102 const gchar *s_am_up = NULL;
4103 const gchar *s_pm_up = NULL;
4104 const gchar *s_am_low = NULL;
4105 const gchar *s_pm_low = NULL;
4107 gint s_am_up_len = 0;
4108 gint s_pm_up_len = 0;
4109 gint s_am_low_len = 0;
4110 gint s_pm_low_len = 0;
4112 static gboolean time_names_init_done = FALSE;
4114 static void init_time_names(void)
4118 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4119 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4120 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4121 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4122 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4123 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4124 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4126 monthnames[0] = C_("Complete month name for use by strftime", "January");
4127 monthnames[1] = C_("Complete month name for use by strftime", "February");
4128 monthnames[2] = C_("Complete month name for use by strftime", "March");
4129 monthnames[3] = C_("Complete month name for use by strftime", "April");
4130 monthnames[4] = C_("Complete month name for use by strftime", "May");
4131 monthnames[5] = C_("Complete month name for use by strftime", "June");
4132 monthnames[6] = C_("Complete month name for use by strftime", "July");
4133 monthnames[7] = C_("Complete month name for use by strftime", "August");
4134 monthnames[8] = C_("Complete month name for use by strftime", "September");
4135 monthnames[9] = C_("Complete month name for use by strftime", "October");
4136 monthnames[10] = C_("Complete month name for use by strftime", "November");
4137 monthnames[11] = C_("Complete month name for use by strftime", "December");
4139 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4140 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4141 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4142 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4143 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4144 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4145 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4147 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4148 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4149 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4150 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4151 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4152 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4153 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4154 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4155 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4156 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4157 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4158 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4160 for (i = 0; i < 7; i++) {
4161 daynames_len[i] = strlen(daynames[i]);
4162 s_daynames_len[i] = strlen(s_daynames[i]);
4164 for (i = 0; i < 12; i++) {
4165 monthnames_len[i] = strlen(monthnames[i]);
4166 s_monthnames_len[i] = strlen(s_monthnames[i]);
4169 s_am_up = C_("For use by strftime (morning)", "AM");
4170 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4171 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4172 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4174 s_am_up_len = strlen(s_am_up);
4175 s_pm_up_len = strlen(s_pm_up);
4176 s_am_low_len = strlen(s_am_low);
4177 s_pm_low_len = strlen(s_pm_low);
4179 time_names_init_done = TRUE;
4182 #define CHECK_SIZE() { \
4183 total_done += len; \
4184 if (total_done >= buflen) { \
4185 buf[buflen-1] = '\0'; \
4190 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4192 gchar *curpos = buf;
4193 gint total_done = 0;
4194 gchar subbuf[64], subfmt[64];
4195 static time_t last_tzset = (time_t)0;
4197 if (!time_names_init_done)
4200 if (format == NULL || lt == NULL)
4203 if (last_tzset != time(NULL)) {
4205 last_tzset = time(NULL);
4208 if (*format == '%') {
4209 gint len = 0, tmp = 0;
4213 len = 1; CHECK_SIZE();
4217 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4218 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4221 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4222 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4226 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4227 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4230 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4231 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4234 strftime(subbuf, 64, "%c", lt);
4235 len = strlen(subbuf); CHECK_SIZE();
4236 strncpy2(curpos, subbuf, buflen - total_done);
4239 total_done += 2; CHECK_SIZE();
4240 tmp = (lt->tm_year + 1900)/100;
4241 *curpos++ = '0'+(tmp / 10);
4242 *curpos++ = '0'+(tmp % 10);
4245 total_done += 2; CHECK_SIZE();
4246 *curpos++ = '0'+(lt->tm_mday / 10);
4247 *curpos++ = '0'+(lt->tm_mday % 10);
4250 total_done += 8; CHECK_SIZE();
4251 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4252 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4254 *curpos++ = '0'+(lt->tm_mday / 10);
4255 *curpos++ = '0'+(lt->tm_mday % 10);
4257 tmp = lt->tm_year%100;
4258 *curpos++ = '0'+(tmp / 10);
4259 *curpos++ = '0'+(tmp % 10);
4262 len = 2; CHECK_SIZE();
4263 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4266 len = 10; CHECK_SIZE();
4267 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4268 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4271 total_done += 2; CHECK_SIZE();
4272 *curpos++ = '0'+(lt->tm_hour / 10);
4273 *curpos++ = '0'+(lt->tm_hour % 10);
4276 total_done += 2; CHECK_SIZE();
4282 *curpos++ = '0'+(tmp / 10);
4283 *curpos++ = '0'+(tmp % 10);
4286 len = 3; CHECK_SIZE();
4287 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4290 len = 2; CHECK_SIZE();
4291 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4294 len = 2; CHECK_SIZE();
4300 snprintf(curpos, buflen - total_done, "%2d", tmp);
4303 total_done += 2; CHECK_SIZE();
4304 tmp = lt->tm_mon + 1;
4305 *curpos++ = '0'+(tmp / 10);
4306 *curpos++ = '0'+(tmp % 10);
4309 total_done += 2; CHECK_SIZE();
4310 *curpos++ = '0'+(lt->tm_min / 10);
4311 *curpos++ = '0'+(lt->tm_min % 10);
4314 len = 1; CHECK_SIZE();
4318 if (lt->tm_hour >= 12) {
4319 len = s_pm_up_len; CHECK_SIZE();
4320 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4322 len = s_am_up_len; CHECK_SIZE();
4323 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4327 if (lt->tm_hour >= 12) {
4328 len = s_pm_low_len; CHECK_SIZE();
4329 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4331 len = s_am_low_len; CHECK_SIZE();
4332 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4337 strftime(subbuf, 64, "%I:%M:%S %p", lt);
4339 strftime(subbuf, 64, "%r", lt);
4341 len = strlen(subbuf); CHECK_SIZE();
4342 strncpy2(curpos, subbuf, buflen - total_done);
4345 total_done += 5; CHECK_SIZE();
4346 *curpos++ = '0'+(lt->tm_hour / 10);
4347 *curpos++ = '0'+(lt->tm_hour % 10);
4349 *curpos++ = '0'+(lt->tm_min / 10);
4350 *curpos++ = '0'+(lt->tm_min % 10);
4353 snprintf(subbuf, 64, "%" CM_TIME_FORMAT, mktime(lt));
4354 len = strlen(subbuf); CHECK_SIZE();
4355 strncpy2(curpos, subbuf, buflen - total_done);
4358 total_done += 2; CHECK_SIZE();
4359 *curpos++ = '0'+(lt->tm_sec / 10);
4360 *curpos++ = '0'+(lt->tm_sec % 10);
4363 len = 1; CHECK_SIZE();
4367 total_done += 8; CHECK_SIZE();
4368 *curpos++ = '0'+(lt->tm_hour / 10);
4369 *curpos++ = '0'+(lt->tm_hour % 10);
4371 *curpos++ = '0'+(lt->tm_min / 10);
4372 *curpos++ = '0'+(lt->tm_min % 10);
4374 *curpos++ = '0'+(lt->tm_sec / 10);
4375 *curpos++ = '0'+(lt->tm_sec % 10);
4378 len = 1; CHECK_SIZE();
4379 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
4382 len = 1; CHECK_SIZE();
4383 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
4386 strftime(subbuf, 64, "%x", lt);
4387 len = strlen(subbuf); CHECK_SIZE();
4388 strncpy2(curpos, subbuf, buflen - total_done);
4391 strftime(subbuf, 64, "%X", lt);
4392 len = strlen(subbuf); CHECK_SIZE();
4393 strncpy2(curpos, subbuf, buflen - total_done);
4396 total_done += 2; CHECK_SIZE();
4397 tmp = lt->tm_year%100;
4398 *curpos++ = '0'+(tmp / 10);
4399 *curpos++ = '0'+(tmp % 10);
4402 len = 4; CHECK_SIZE();
4403 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
4413 /* let these complicated ones be done with the libc */
4414 snprintf(subfmt, 64, "%%%c", *format);
4415 strftime(subbuf, 64, subfmt, lt);
4416 len = strlen(subbuf); CHECK_SIZE();
4417 strncpy2(curpos, subbuf, buflen - total_done);
4421 /* let these complicated modifiers be done with the libc */
4422 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
4423 strftime(subbuf, 64, subfmt, lt);
4424 len = strlen(subbuf); CHECK_SIZE();
4425 strncpy2(curpos, subbuf, buflen - total_done);
4429 g_warning("format error (%c)", *format);
4436 int len = 1; CHECK_SIZE();
4437 *curpos++ = *format++;
4445 #define WEXITSTATUS(x) (x)
4448 static gchar *canonical_list_to_file(GSList *list)
4450 GString *result = g_string_new(NULL);
4451 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
4456 result = g_string_append(result, G_DIR_SEPARATOR_S);
4458 if (pathlist->data) {
4459 const gchar *root = (gchar *)pathlist->data;
4460 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
4462 /* drive - don't prepend dir separator */
4464 result = g_string_append(result, G_DIR_SEPARATOR_S);
4469 for (cur = pathlist; cur; cur = cur->next) {
4470 result = g_string_append(result, (gchar *)cur->data);
4472 result = g_string_append(result, G_DIR_SEPARATOR_S);
4474 g_slist_free(pathlist);
4477 g_string_free(result, FALSE);
4482 static GSList *cm_split_path(const gchar *filename, int depth)
4485 GSList *canonical_parts = NULL;
4489 gboolean follow_symlinks = TRUE;
4496 errno = EINVAL; /* can't happen, no symlink handling */
4501 if (!g_path_is_absolute(filename)) {
4506 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
4508 for (i = 0; path_parts[i] != NULL; i++) {
4509 if (!strcmp(path_parts[i], ""))
4511 if (!strcmp(path_parts[i], "."))
4513 else if (!strcmp(path_parts[i], "..")) {
4516 g_strfreev(path_parts);
4519 else /* Remove the last inserted element */
4521 g_slist_delete_link(canonical_parts,
4526 canonical_parts = g_slist_prepend(canonical_parts,
4527 g_strdup(path_parts[i]));
4529 tmp_path = canonical_list_to_file(canonical_parts);
4531 if(g_stat(tmp_path, &st) < 0) {
4532 if (errno == ENOENT) {
4535 follow_symlinks = FALSE;
4540 slist_free_strings_full(canonical_parts);
4541 g_strfreev(path_parts);
4547 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
4548 GError *error = NULL;
4549 gchar *target = g_file_read_link(tmp_path, &error);
4551 if (!g_path_is_absolute(target)) {
4552 /* remove the last inserted element */
4554 g_slist_delete_link(canonical_parts,
4556 /* add the target */
4557 canonical_parts = g_slist_prepend(canonical_parts,
4561 /* and get the new target */
4562 target = canonical_list_to_file(canonical_parts);
4565 /* restart from absolute target */
4566 slist_free_strings_full(canonical_parts);
4567 canonical_parts = NULL;
4569 canonical_parts = cm_split_path(target, depth + 1);
4571 g_error_free(error);
4572 if (canonical_parts == NULL) {
4574 g_strfreev(path_parts);
4583 g_strfreev(path_parts);
4584 return canonical_parts;
4588 * Canonicalize a filename, resolving symlinks along the way.
4589 * Returns a negative errno in case of error.
4591 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
4592 GSList *canonical_parts;
4593 gboolean is_absolute;
4595 if (filename == NULL)
4597 if (canonical_name == NULL)
4599 *canonical_name = NULL;
4601 is_absolute = g_path_is_absolute(filename);
4603 /* Always work on absolute filenames. */
4604 gchar *cur = g_get_current_dir();
4605 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
4608 canonical_parts = cm_split_path(absolute_filename, 0);
4609 g_free(absolute_filename);
4612 canonical_parts = cm_split_path(filename, 0);
4614 if (canonical_parts == NULL)
4617 *canonical_name = canonical_list_to_file(canonical_parts);
4618 slist_free_strings_full(canonical_parts);
4622 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
4623 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
4625 gchar *tmp = g_base64_decode(text, out_len);
4626 gchar *out = g_strndup(tmp, *out_len);
4630 if (strlen(out) != *out_len) {
4631 g_warning("strlen(out) %"G_GSIZE_FORMAT" != *out_len %"G_GSIZE_FORMAT, strlen(out), *out_len);
4637 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
4638 * It is up to the caller to make sure there is at least count bytes
4639 * available at buf. */
4641 get_random_bytes(void *buf, size_t count)
4643 /* Open our prng source. */
4644 #if defined G_OS_WIN32
4647 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
4648 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
4649 debug_print("Could not acquire a CSP handle.\n");
4656 rnd = open("/dev/urandom", O_RDONLY);
4658 FILE_OP_ERROR("/dev/urandom", "open");
4659 debug_print("Could not open /dev/urandom.\n");
4664 /* Read data from the source into buf. */
4665 #if defined G_OS_WIN32
4666 if (!CryptGenRandom(rnd, count, buf)) {
4667 debug_print("Could not read %"G_GSIZE_FORMAT" random bytes.\n", count);
4668 CryptReleaseContext(rnd, 0);
4672 ret = read(rnd, buf, count);
4674 FILE_OP_ERROR("/dev/urandom", "read");
4675 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
4681 /* Close the prng source. */
4682 #if defined G_OS_WIN32
4683 CryptReleaseContext(rnd, 0);
4691 /* returns FALSE if parsing failed, otherwise returns TRUE and sets *server, *port
4692 and eventually *fp from filename (if not NULL, they must be free'd by caller after
4694 filenames we expect: 'host.name.port.cert' or 'host.name.port.f:i:n:g:e:r:p:r:i:n:t.cert' */
4695 gboolean get_serverportfp_from_filename(const gchar *str, gchar **server, gchar **port, gchar **fp)
4697 const gchar *pos, *dotport_pos = NULL, *dotcert_pos = NULL, *dotfp_pos = NULL;
4699 g_return_val_if_fail(str != NULL, FALSE);
4701 pos = str + strlen(str) - 1;
4702 while ((pos > str) && !dotport_pos) {
4705 /* match the .cert suffix */
4706 if (strcmp(pos, ".cert") == 0) {
4711 /* match an eventual fingerprint */
4712 /* or the port number */
4713 if (strncmp(pos + 3, ":", 1) == 0) {
4719 /* match the port number */
4726 if (!dotport_pos || !dotcert_pos) {
4727 g_warning("could not parse filename %s", str);
4732 *server = g_strndup(str, dotport_pos - str);
4735 *port = g_strndup(dotport_pos + 1, dotfp_pos - dotport_pos - 1);
4737 *fp = g_strndup(dotfp_pos + 1, dotcert_pos - dotfp_pos - 1);
4740 *port = g_strndup(dotport_pos + 1, dotcert_pos - dotport_pos - 1);
4745 debug_print("filename='%s' => server='%s' port='%s' fp='%s'\n",
4747 (server ? *server : "(n/a)"),
4748 (port ? *port : "(n/a)"),
4749 (fp ? *fp : "(n/a)"));
4751 if (!(server && *server) || !(port && *port))
4758 gchar *win32_debug_log_path(void)
4760 return g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S,
4761 "claws-win32.log", NULL);