2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2016 Hiroyuki Yamamoto & The Claws Mail Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 * The code of the g_utf8_substring function below is owned by
19 * Matthias Clasen <matthiasc@src.gnome.org>/<mclasen@redhat.com>
20 * and is got from GLIB 2.30: https://git.gnome.org/browse/glib/commit/
21 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
23 * GLib 2.30 is licensed under GPL v2 or later and:
24 * Copyright (C) 1999 Tom Tromey
25 * Copyright (C) 2000 Red Hat, Inc.
27 * https://git.gnome.org/browse/glib/tree/glib/gutf8.c
28 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
33 #include "claws-features.h"
41 #include <glib/gi18n.h>
51 #include <sys/param.h>
53 # include <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>
91 #include "file-utils.h"
95 static gboolean debug_mode = FALSE;
97 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
99 #if GLIB_CHECK_VERSION(2, 34, 0)
100 return g_slist_copy_deep(list, func, NULL);
102 GSList *res = g_slist_copy(list);
105 walk->data = func(walk->data, NULL);
112 void list_free_strings_full(GList *list)
114 g_list_free_full(list, (GDestroyNotify)g_free);
117 void slist_free_strings_full(GSList *list)
119 g_slist_free_full(list, (GDestroyNotify)g_free);
122 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
127 void hash_free_strings(GHashTable *table)
129 g_hash_table_foreach(table, hash_free_strings_func, NULL);
132 gint str_case_equal(gconstpointer v, gconstpointer v2)
134 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
137 guint str_case_hash(gconstpointer key)
139 const gchar *p = key;
143 h = g_ascii_tolower(h);
144 for (p += 1; *p != '\0'; p++)
145 h = (h << 5) - h + g_ascii_tolower(*p);
151 gint to_number(const gchar *nstr)
153 register const gchar *p;
155 if (*nstr == '\0') return -1;
157 for (p = nstr; *p != '\0'; p++)
158 if (!g_ascii_isdigit(*p)) return -1;
163 /* convert integer into string,
164 nstr must be not lower than 11 characters length */
165 gchar *itos_buf(gchar *nstr, gint n)
167 g_snprintf(nstr, 11, "%d", n);
171 /* convert integer into string */
174 static gchar nstr[11];
176 return itos_buf(nstr, n);
179 #define divide(num,divisor,i,d) \
181 i = num >> divisor; \
182 d = num & ((1<<divisor)-1); \
183 d = (d*100) >> divisor; \
188 * \brief Convert a given size in bytes in a human-readable string
190 * \param size The size expressed in bytes to convert in string
191 * \return The string that respresents the size in an human-readable way
193 gchar *to_human_readable(goffset size)
195 static gchar str[14];
196 static gchar *b_format = NULL, *kb_format = NULL,
197 *mb_format = NULL, *gb_format = NULL;
198 register int t = 0, r = 0;
199 if (b_format == NULL) {
201 kb_format = _("%d.%02dKB");
202 mb_format = _("%d.%02dMB");
203 gb_format = _("%.2fGB");
206 if (size < (goffset)1024) {
207 g_snprintf(str, sizeof(str), b_format, (gint)size);
209 } else if (size >> 10 < (goffset)1024) {
210 divide(size, 10, t, r);
211 g_snprintf(str, sizeof(str), kb_format, t, r);
213 } else if (size >> 20 < (goffset)1024) {
214 divide(size, 20, t, r);
215 g_snprintf(str, sizeof(str), mb_format, t, r);
218 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
224 gint path_cmp(const gchar *s1, const gchar *s2)
229 gchar *s1buf, *s2buf;
232 if (s1 == NULL || s2 == NULL) return -1;
233 if (*s1 == '\0' || *s2 == '\0') return -1;
236 s1buf = g_strdup (s1);
237 s2buf = g_strdup (s2);
238 subst_char (s1buf, '/', G_DIR_SEPARATOR);
239 subst_char (s2buf, '/', G_DIR_SEPARATOR);
242 #endif /* !G_OS_WIN32 */
247 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
248 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
250 rc = strncmp(s1, s2, MAX(len1, len2));
254 #endif /* !G_OS_WIN32 */
258 /* remove trailing return code */
259 gchar *strretchomp(gchar *str)
263 if (!*str) return str;
265 for (s = str + strlen(str) - 1;
266 s >= str && (*s == '\n' || *s == '\r');
273 /* remove trailing character */
274 gchar *strtailchomp(gchar *str, gchar tail_char)
278 if (!*str) return str;
279 if (tail_char == '\0') return str;
281 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
287 /* remove CR (carriage return) */
288 gchar *strcrchomp(gchar *str)
292 if (!*str) return str;
294 s = str + strlen(str) - 1;
295 if (*s == '\n' && s > str && *(s - 1) == '\r') {
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);
311 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
313 register size_t needle_len;
315 needle_len = strlen(needle);
317 if (haystack_len < needle_len || needle_len == 0)
320 while (haystack_len >= needle_len) {
321 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
322 return (gchar *)haystack;
332 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
333 gconstpointer needle, size_t needlelen)
335 const gchar *haystack_ = (const gchar *)haystack;
336 const gchar *needle_ = (const gchar *)needle;
337 const gchar *haystack_cur = (const gchar *)haystack;
338 size_t haystack_left = haystacklen;
341 return memchr(haystack_, *needle_, haystacklen);
343 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
345 if (haystacklen - (haystack_cur - haystack_) < needlelen)
347 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
348 return (gpointer)haystack_cur;
351 haystack_left = haystacklen - (haystack_cur - haystack_);
358 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
359 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
361 register const gchar *s = src;
362 register gchar *d = dest;
372 /* Examine if next block is non-ASCII string */
373 gboolean is_next_nonascii(const gchar *s)
377 /* skip head space */
378 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
380 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
381 if (*(guchar *)p > 127 || *(guchar *)p < 32)
388 gint get_next_word_len(const gchar *s)
392 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
398 static void trim_subject_for_compare(gchar *str)
402 eliminate_parenthesis(str, '[', ']');
403 eliminate_parenthesis(str, '(', ')');
406 srcp = str + subject_get_prefix_length(str);
408 memmove(str, srcp, strlen(srcp) + 1);
411 static void trim_subject_for_sort(gchar *str)
417 srcp = str + subject_get_prefix_length(str);
419 memmove(str, srcp, strlen(srcp) + 1);
422 /* compare subjects */
423 gint subject_compare(const gchar *s1, const gchar *s2)
427 if (!s1 || !s2) return -1;
428 if (!*s1 || !*s2) return -1;
430 Xstrdup_a(str1, s1, return -1);
431 Xstrdup_a(str2, s2, return -1);
433 trim_subject_for_compare(str1);
434 trim_subject_for_compare(str2);
436 if (!*str1 || !*str2) return -1;
438 return strcmp(str1, str2);
441 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
445 if (!s1 || !s2) return -1;
447 Xstrdup_a(str1, s1, return -1);
448 Xstrdup_a(str2, s2, return -1);
450 trim_subject_for_sort(str1);
451 trim_subject_for_sort(str2);
453 return g_utf8_collate(str1, str2);
456 void trim_subject(gchar *str)
458 register gchar *srcp;
464 srcp = str + subject_get_prefix_length(str);
469 } else if (*srcp == '(') {
481 else if (*srcp == cl)
488 while (g_ascii_isspace(*srcp)) srcp++;
489 memmove(str, srcp, strlen(srcp) + 1);
492 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
494 register gchar *srcp, *destp;
499 while ((destp = strchr(destp, op))) {
505 else if (*srcp == cl)
511 while (g_ascii_isspace(*srcp)) srcp++;
512 memmove(destp, srcp, strlen(srcp) + 1);
516 void extract_parenthesis(gchar *str, gchar op, gchar cl)
518 register gchar *srcp, *destp;
523 while ((srcp = strchr(destp, op))) {
526 memmove(destp, srcp + 1, strlen(srcp));
531 else if (*destp == cl)
543 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
546 register gchar *srcp, *destp;
548 gboolean in_quote = FALSE;
552 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
555 memmove(destp, srcp + 1, strlen(srcp));
558 if (*destp == op && !in_quote)
560 else if (*destp == cl && !in_quote)
562 else if (*destp == quote_chr)
574 void extract_quote(gchar *str, gchar quote_chr)
578 if ((str = strchr(str, quote_chr))) {
580 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
581 memmove(p - 1, p, strlen(p) + 1);
586 memmove(str, str + 1, p - str);
591 /* Returns a newly allocated string with all quote_chr not at the beginning
592 or the end of str escaped with '\' or the given str if not required. */
593 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
595 register gchar *p, *q;
599 if (str == NULL || *str == '\0')
602 /* search for unescaped quote_chr */
607 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
611 if (!k) /* nothing to escape */
614 /* unescaped quote_chr found */
615 qstr = g_malloc(l + k + 1);
618 if (*p == quote_chr) {
623 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
632 void eliminate_address_comment(gchar *str)
634 register gchar *srcp, *destp;
639 while ((destp = strchr(destp, '"'))) {
640 if ((srcp = strchr(destp + 1, '"'))) {
645 while (g_ascii_isspace(*srcp)) srcp++;
646 memmove(destp, srcp, strlen(srcp) + 1);
656 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
662 else if (*srcp == ')')
668 while (g_ascii_isspace(*srcp)) srcp++;
669 memmove(destp, srcp, strlen(srcp) + 1);
673 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
675 gboolean in_quote = FALSE;
678 if (*str == c && !in_quote)
680 if (*str == quote_chr)
688 void extract_address(gchar *str)
690 cm_return_if_fail(str != NULL);
691 eliminate_address_comment(str);
692 if (strchr_with_skip_quote(str, '"', '<'))
693 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
697 void extract_list_id_str(gchar *str)
699 if (strchr_with_skip_quote(str, '"', '<'))
700 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
704 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
709 if (!str) return addr_list;
711 Xstrdup_a(work, str, return addr_list);
714 eliminate_address_comment(work);
717 while (workp && *workp) {
720 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
726 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
727 extract_parenthesis_with_skip_quote
728 (workp, '"', '<', '>');
732 addr_list = g_slist_append(addr_list, g_strdup(workp));
740 GSList *address_list_append(GSList *addr_list, const gchar *str)
742 return address_list_append_real(addr_list, str, TRUE);
745 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
747 return address_list_append_real(addr_list, str, FALSE);
750 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
754 if (!str) return msgid_list;
757 while (strp && *strp) {
758 const gchar *start, *end;
761 if ((start = strchr(strp, '<')) != NULL) {
762 end = strchr(start + 1, '>');
767 msgid = g_strndup(start + 1, end - start - 1);
770 msgid_list = g_slist_prepend(msgid_list, msgid);
780 GSList *references_list_append(GSList *msgid_list, const gchar *str)
784 list = references_list_prepend(NULL, str);
785 list = g_slist_reverse(list);
786 msgid_list = g_slist_concat(msgid_list, list);
791 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
796 if (!str) return group_list;
798 Xstrdup_a(work, str, return group_list);
802 while (workp && *workp) {
805 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
813 group_list = g_slist_append(group_list,
822 GList *add_history(GList *list, const gchar *str)
827 cm_return_val_if_fail(str != NULL, list);
829 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)g_strcmp0);
832 list = g_list_remove(list, old->data);
834 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
837 last = g_list_last(list);
840 list = g_list_remove(list, last->data);
845 list = g_list_prepend(list, g_strdup(str));
850 void remove_return(gchar *str)
852 register gchar *p = str;
855 if (*p == '\n' || *p == '\r')
856 memmove(p, p + 1, strlen(p));
862 void remove_space(gchar *str)
864 register gchar *p = str;
869 while (g_ascii_isspace(*(p + spc)))
872 memmove(p, p + spc, strlen(p + spc) + 1);
878 void unfold_line(gchar *str)
884 ch = str; /* iterator for source string */
887 c = g_utf8_get_char_validated(ch, -1);
889 if (c == (gunichar)-1 || c == (gunichar)-2) {
890 /* non-unicode byte, move past it */
895 len = g_unichar_to_utf8(c, NULL);
897 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
898 g_unichar_isspace(c)) {
899 /* replace anything bad or whitespacey with a single space */
903 /* move rest of the string forwards, since we just replaced
904 * a multi-byte sequence with one byte */
905 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
908 /* A valid unicode character, copy it. */
914 void subst_char(gchar *str, gchar orig, gchar subst)
916 register gchar *p = str;
925 void subst_chars(gchar *str, gchar *orig, gchar subst)
927 register gchar *p = str;
930 if (strchr(orig, *p) != NULL)
936 void subst_for_filename(gchar *str)
941 subst_chars(str, "\t\r\n\\/*?:", '_');
943 subst_chars(str, "\t\r\n\\/*", '_');
947 void subst_for_shellsafe_filename(gchar *str)
951 subst_for_filename(str);
952 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
955 gboolean is_ascii_str(const gchar *str)
957 const guchar *p = (const guchar *)str;
960 if (*p != '\t' && *p != ' ' &&
961 *p != '\r' && *p != '\n' &&
962 (*p < 32 || *p >= 127))
970 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
972 gchar * position = NULL;
973 gchar * tmp_pos = NULL;
976 if (str == NULL || quote_chars == NULL)
979 for (i = 0; i < strlen(quote_chars); i++) {
980 tmp_pos = strrchr (str, quote_chars[i]);
982 || (tmp_pos != NULL && position <= tmp_pos) )
988 gint get_quote_level(const gchar *str, const gchar *quote_chars)
990 const gchar *first_pos;
991 const gchar *last_pos;
992 const gchar *p = str;
993 gint quote_level = -1;
995 /* speed up line processing by only searching to the last '>' */
996 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
997 /* skip a line if it contains a '<' before the initial '>' */
998 if (memchr(str, '<', first_pos - str) != NULL)
1000 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1004 while (p <= last_pos) {
1005 while (p < last_pos) {
1006 if (g_ascii_isspace(*p))
1012 if (strchr(quote_chars, *p))
1014 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1015 /* any characters are allowed except '-','<' and space */
1016 while (*p != '-' && *p != '<'
1017 && !strchr(quote_chars, *p)
1018 && !g_ascii_isspace(*p)
1021 if (strchr(quote_chars, *p))
1033 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1035 const gchar *p = str, *q;
1036 gint cur_line = 0, len;
1038 while ((q = strchr(p, '\n')) != NULL) {
1040 if (len > max_chars) {
1050 if (len > max_chars) {
1059 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1061 gchar * position = NULL;
1062 gchar * tmp_pos = NULL;
1065 if (str == NULL || quote_chars == NULL)
1068 for (i = 0; i < strlen(quote_chars); i++) {
1069 tmp_pos = strchr (str, quote_chars[i]);
1071 || (tmp_pos != NULL && position >= tmp_pos) )
1077 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1079 register guint haystack_len, needle_len;
1080 gboolean in_squote = FALSE, in_dquote = FALSE;
1082 haystack_len = strlen(haystack);
1083 needle_len = strlen(needle);
1085 if (haystack_len < needle_len || needle_len == 0)
1088 while (haystack_len >= needle_len) {
1089 if (!in_squote && !in_dquote &&
1090 !strncmp(haystack, needle, needle_len))
1091 return (gchar *)haystack;
1093 /* 'foo"bar"' -> foo"bar"
1094 "foo'bar'" -> foo'bar' */
1095 if (*haystack == '\'') {
1098 else if (!in_dquote)
1100 } else if (*haystack == '\"') {
1103 else if (!in_squote)
1105 } else if (*haystack == '\\') {
1117 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1120 GSList *string_list = NULL, *slist;
1121 gchar **str_array, *s, *new_str;
1122 guint i, n = 1, len;
1124 cm_return_val_if_fail(str != NULL, NULL);
1125 cm_return_val_if_fail(delim != NULL, NULL);
1128 max_tokens = G_MAXINT;
1130 s = strstr_with_skip_quote(str, delim);
1132 guint delimiter_len = strlen(delim);
1136 new_str = g_strndup(str, len);
1138 if (new_str[0] == '\'' || new_str[0] == '\"') {
1139 if (new_str[len - 1] == new_str[0]) {
1140 new_str[len - 1] = '\0';
1141 memmove(new_str, new_str + 1, len - 1);
1144 string_list = g_slist_prepend(string_list, new_str);
1146 str = s + delimiter_len;
1147 s = strstr_with_skip_quote(str, delim);
1148 } while (--max_tokens && s);
1152 new_str = g_strdup(str);
1153 if (new_str[0] == '\'' || new_str[0] == '\"') {
1155 if (new_str[len - 1] == new_str[0]) {
1156 new_str[len - 1] = '\0';
1157 memmove(new_str, new_str + 1, len - 1);
1160 string_list = g_slist_prepend(string_list, new_str);
1164 str_array = g_new(gchar*, n);
1168 str_array[i--] = NULL;
1169 for (slist = string_list; slist; slist = slist->next)
1170 str_array[i--] = slist->data;
1172 g_slist_free(string_list);
1177 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1179 gchar *abbrev_group;
1181 const gchar *p = group;
1184 cm_return_val_if_fail(group != NULL, NULL);
1186 last = group + strlen(group);
1187 abbrev_group = ap = g_malloc(strlen(group) + 1);
1192 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1194 while (*p != '.') p++;
1197 return abbrev_group;
1202 return abbrev_group;
1205 gchar *trim_string(const gchar *str, gint len)
1207 const gchar *p = str;
1212 if (!str) return NULL;
1213 if (strlen(str) <= len)
1214 return g_strdup(str);
1215 if (g_utf8_validate(str, -1, NULL) == FALSE)
1216 return g_strdup(str);
1218 while (*p != '\0') {
1219 mb_len = g_utf8_skip[*(guchar *)p];
1222 else if (new_len + mb_len > len)
1229 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1230 return g_strconcat(new_str, "...", NULL);
1233 GList *uri_list_extract_filenames(const gchar *uri_list)
1235 GList *result = NULL;
1237 gchar *escaped_utf8uri;
1243 while (g_ascii_isspace(*p)) p++;
1244 if (!strncmp(p, "file:", 5)) {
1247 while (*q && *q != '\n' && *q != '\r') q++;
1250 gchar *file, *locale_file = NULL;
1252 while (q > p && g_ascii_isspace(*q))
1254 Xalloca(escaped_utf8uri, q - p + 2,
1256 Xalloca(file, q - p + 2,
1259 strncpy(escaped_utf8uri, p, q - p + 1);
1260 escaped_utf8uri[q - p + 1] = '\0';
1261 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1263 * g_filename_from_uri() rejects escaped/locale encoded uri
1264 * string which come from Nautilus.
1267 if (g_utf8_validate(file, -1, NULL))
1269 = conv_codeset_strdup(
1272 conv_get_locale_charset_str());
1274 locale_file = g_strdup(file + 5);
1276 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1278 result = g_list_append(result, locale_file);
1282 p = strchr(p, '\n');
1289 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1292 static gint axtoi(const gchar *hexstr)
1294 gint hi, lo, result;
1297 if ('0' <= hi && hi <= '9') {
1300 if ('a' <= hi && hi <= 'f') {
1303 if ('A' <= hi && hi <= 'F') {
1308 if ('0' <= lo && lo <= '9') {
1311 if ('a' <= lo && lo <= 'f') {
1314 if ('A' <= lo && lo <= 'F') {
1317 result = lo + (16 * hi);
1321 gboolean is_uri_string(const gchar *str)
1323 while (str && *str && g_ascii_isspace(*str))
1325 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1326 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1327 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1328 g_ascii_strncasecmp(str, "www.", 4) == 0);
1331 gchar *get_uri_path(const gchar *uri)
1333 while (uri && *uri && g_ascii_isspace(*uri))
1335 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1336 return (gchar *)(uri + 7);
1337 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1338 return (gchar *)(uri + 8);
1339 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1340 return (gchar *)(uri + 6);
1342 return (gchar *)uri;
1345 gint get_uri_len(const gchar *str)
1349 if (is_uri_string(str)) {
1350 for (p = str; *p != '\0'; p++) {
1351 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1360 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1361 * plusses, and escape characters are used)
1363 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1365 gchar *dec = decoded_uri;
1366 const gchar *enc = encoded_uri;
1371 if (isxdigit((guchar)enc[0]) &&
1372 isxdigit((guchar)enc[1])) {
1378 if (with_plus && *enc == '+')
1390 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1392 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1395 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1397 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1398 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1402 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1403 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1407 const gchar *forbidden_uris[] = { ".gnupg/",
1413 gint num_attach = 0;
1415 cm_return_val_if_fail(mailto != NULL, -1);
1417 Xstrdup_a(tmp_mailto, mailto, return -1);
1419 if (!strncmp(tmp_mailto, "mailto:", 7))
1422 p = strchr(tmp_mailto, '?');
1429 *to = decode_uri_gdup(tmp_mailto);
1432 gchar *field, *value;
1449 if (*value == '\0') continue;
1451 if (from && !g_ascii_strcasecmp(field, "from")) {
1453 *from = decode_uri_gdup(value);
1455 gchar *tmp = decode_uri_gdup(value);
1456 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1461 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1463 *cc = decode_uri_gdup(value);
1465 gchar *tmp = decode_uri_gdup(value);
1466 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1471 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1473 *bcc = decode_uri_gdup(value);
1475 gchar *tmp = decode_uri_gdup(value);
1476 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1481 } else if (subject && !*subject &&
1482 !g_ascii_strcasecmp(field, "subject")) {
1483 *subject = decode_uri_gdup(value);
1484 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1485 *body = decode_uri_gdup(value);
1486 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1487 gchar *tmp = decode_uri_gdup(value);
1488 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1489 g_warning("couldn't set insert file '%s' in body", value);
1492 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1494 gchar *tmp = decode_uri_gdup(value);
1495 gchar **my_att = g_malloc(sizeof(char *));
1499 for (; forbidden_uris[i]; i++) {
1500 if (strstr(tmp, forbidden_uris[i])) {
1501 g_print("Refusing to attach '%s', potential private data leak\n",
1509 /* attach is correct */
1511 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1512 my_att[num_attach-1] = tmp;
1513 my_att[num_attach] = NULL;
1519 } else if (inreplyto && !*inreplyto &&
1520 !g_ascii_strcasecmp(field, "in-reply-to")) {
1521 *inreplyto = decode_uri_gdup(value);
1530 #include <windows.h>
1531 #ifndef CSIDL_APPDATA
1532 #define CSIDL_APPDATA 0x001a
1534 #ifndef CSIDL_LOCAL_APPDATA
1535 #define CSIDL_LOCAL_APPDATA 0x001c
1537 #ifndef CSIDL_FLAG_CREATE
1538 #define CSIDL_FLAG_CREATE 0x8000
1540 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1544 w32_strerror (int w32_errno)
1546 static char strerr[256];
1547 int ec = (int)GetLastError ();
1551 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1552 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1553 strerr, DIM (strerr)-1, NULL);
1557 static __inline__ void *
1558 dlopen (const char * name, int flag)
1560 void * hd = LoadLibrary (name);
1564 static __inline__ void *
1565 dlsym (void * hd, const char * sym)
1569 void * fnc = GetProcAddress (hd, sym);
1578 static __inline__ const char *
1581 return w32_strerror (0);
1585 static __inline__ int
1597 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1599 static int initialized;
1600 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1604 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1610 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1612 handle = dlopen (dllnames[i], RTLD_LAZY);
1615 func = dlsym (handle, "SHGetFolderPathW");
1626 return func (a,b,c,d,e);
1631 /* Returns a static string with the directroy from which the module
1632 has been loaded. Returns an empty string on error. */
1633 static char *w32_get_module_dir(void)
1635 static char *moddir;
1638 char name[MAX_PATH+10];
1641 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1644 p = strrchr (name, '\\');
1650 moddir = g_strdup (name);
1654 #endif /* G_OS_WIN32 */
1656 /* Return a static string with the locale dir. */
1657 const gchar *get_locale_dir(void)
1659 static gchar *loc_dir;
1663 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1664 "\\share\\locale", NULL);
1667 loc_dir = LOCALEDIR;
1673 const gchar *get_home_dir(void)
1676 static char home_dir_utf16[MAX_PATH] = "";
1677 static gchar *home_dir_utf8 = NULL;
1678 if (home_dir_utf16[0] == '\0') {
1679 if (w32_shgetfolderpath
1680 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1681 NULL, 0, home_dir_utf16) < 0)
1682 strcpy (home_dir_utf16, "C:\\Claws Mail");
1683 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1685 return home_dir_utf8;
1687 static const gchar *homeenv = NULL;
1692 if (!homeenv && g_getenv("HOME") != NULL)
1693 homeenv = g_strdup(g_getenv("HOME"));
1695 homeenv = g_get_home_dir();
1701 static gchar *claws_rc_dir = NULL;
1702 static gboolean rc_dir_alt = FALSE;
1703 const gchar *get_rc_dir(void)
1706 if (!claws_rc_dir) {
1707 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1709 debug_print("using default rc_dir %s\n", claws_rc_dir);
1711 return claws_rc_dir;
1714 void set_rc_dir(const gchar *dir)
1716 gchar *canonical_dir;
1717 if (claws_rc_dir != NULL) {
1718 g_print("Error: rc_dir already set\n");
1720 int err = cm_canonicalize_filename(dir, &canonical_dir);
1724 g_print("Error looking for %s: %d(%s)\n",
1725 dir, -err, g_strerror(-err));
1730 claws_rc_dir = canonical_dir;
1732 len = strlen(claws_rc_dir);
1733 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1734 claws_rc_dir[len - 1] = '\0';
1736 debug_print("set rc_dir to %s\n", claws_rc_dir);
1737 if (!is_dir_exist(claws_rc_dir)) {
1738 if (make_dir_hier(claws_rc_dir) != 0) {
1739 g_print("Error: can't create %s\n",
1747 gboolean rc_dir_is_alt(void) {
1751 const gchar *get_mail_base_dir(void)
1753 return get_home_dir();
1756 const gchar *get_news_cache_dir(void)
1758 static gchar *news_cache_dir = NULL;
1759 if (!news_cache_dir)
1760 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1761 NEWS_CACHE_DIR, NULL);
1763 return news_cache_dir;
1766 const gchar *get_imap_cache_dir(void)
1768 static gchar *imap_cache_dir = NULL;
1770 if (!imap_cache_dir)
1771 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1772 IMAP_CACHE_DIR, NULL);
1774 return imap_cache_dir;
1777 const gchar *get_mime_tmp_dir(void)
1779 static gchar *mime_tmp_dir = NULL;
1782 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1783 MIME_TMP_DIR, NULL);
1785 return mime_tmp_dir;
1788 const gchar *get_template_dir(void)
1790 static gchar *template_dir = NULL;
1793 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1794 TEMPLATE_DIR, NULL);
1796 return template_dir;
1800 const gchar *w32_get_cert_file(void)
1802 const gchar *cert_file = NULL;
1804 cert_file = g_strconcat(w32_get_module_dir(),
1805 "\\share\\claws-mail\\",
1806 "ca-certificates.crt",
1812 /* Return the filepath of the claws-mail.desktop file */
1813 const gchar *get_desktop_file(void)
1815 #ifdef DESKTOPFILEPATH
1816 return DESKTOPFILEPATH;
1822 /* Return the default directory for Plugins. */
1823 const gchar *get_plugin_dir(void)
1826 static gchar *plugin_dir = NULL;
1829 plugin_dir = g_strconcat(w32_get_module_dir(),
1830 "\\lib\\claws-mail\\plugins\\",
1834 if (is_dir_exist(PLUGINDIR))
1837 static gchar *plugin_dir = NULL;
1839 plugin_dir = g_strconcat(get_rc_dir(),
1840 G_DIR_SEPARATOR_S, "plugins",
1841 G_DIR_SEPARATOR_S, NULL);
1849 /* Return the default directory for Themes. */
1850 const gchar *w32_get_themes_dir(void)
1852 static gchar *themes_dir = NULL;
1855 themes_dir = g_strconcat(w32_get_module_dir(),
1856 "\\share\\claws-mail\\themes",
1862 const gchar *get_tmp_dir(void)
1864 static gchar *tmp_dir = NULL;
1867 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1873 gchar *get_tmp_file(void)
1876 static guint32 id = 0;
1878 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1879 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1884 const gchar *get_domain_name(void)
1887 static gchar *domain_name = NULL;
1888 struct addrinfo hints, *res;
1893 if (gethostname(hostname, sizeof(hostname)) != 0) {
1894 perror("gethostname");
1895 domain_name = "localhost";
1897 memset(&hints, 0, sizeof(struct addrinfo));
1898 hints.ai_family = AF_UNSPEC;
1899 hints.ai_socktype = 0;
1900 hints.ai_flags = AI_CANONNAME;
1901 hints.ai_protocol = 0;
1903 s = getaddrinfo(hostname, NULL, &hints, &res);
1905 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1906 domain_name = g_strdup(hostname);
1908 domain_name = g_strdup(res->ai_canonname);
1912 debug_print("domain name = %s\n", domain_name);
1921 /* Tells whether the given host address string is a valid representation of a
1922 * numerical IP (v4 or, if supported, v6) address.
1924 gboolean is_numeric_host_address(const gchar *hostaddress)
1926 struct addrinfo hints, *res;
1929 /* See what getaddrinfo makes of the string when told that it is a
1930 * numeric IP address representation. */
1931 memset(&hints, 0, sizeof(struct addrinfo));
1932 hints.ai_family = AF_UNSPEC;
1933 hints.ai_socktype = 0;
1934 hints.ai_flags = AI_NUMERICHOST;
1935 hints.ai_protocol = 0;
1937 err = getaddrinfo(hostaddress, NULL, &hints, &res);
1944 off_t get_file_size(const gchar *file)
1949 GError *error = NULL;
1952 f = g_file_new_for_path(file);
1953 fi = g_file_query_info(f, "standard::size",
1954 G_FILE_QUERY_INFO_NONE, NULL, &error);
1955 if (error != NULL) {
1956 debug_print("get_file_size error: %s\n", error->message);
1957 g_error_free(error);
1961 size = g_file_info_get_size(fi);
1969 if (g_stat(file, &s) < 0) {
1970 FILE_OP_ERROR(file, "stat");
1978 time_t get_file_mtime(const gchar *file)
1982 if (g_stat(file, &s) < 0) {
1983 FILE_OP_ERROR(file, "stat");
1990 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1997 if (g_stat(file, &s) < 0) {
1998 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2002 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2009 /* Test on whether FILE is a relative file name. This is
2010 * straightforward for Unix but more complex for Windows. */
2011 gboolean is_relative_filename(const gchar *file)
2016 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2017 return FALSE; /* Prefixed with a hostname - this can't
2018 * be a relative name. */
2020 if ( ((*file >= 'a' && *file <= 'z')
2021 || (*file >= 'A' && *file <= 'Z'))
2023 file += 2; /* Skip drive letter. */
2025 return !(*file == '\\' || *file == '/');
2027 return !(*file == G_DIR_SEPARATOR);
2032 gboolean is_dir_exist(const gchar *dir)
2037 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2040 gboolean is_file_entry_exist(const gchar *file)
2045 return g_file_test(file, G_FILE_TEST_EXISTS);
2048 gboolean dirent_is_regular_file(struct dirent *d)
2050 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2051 if (d->d_type == DT_REG)
2053 else if (d->d_type != DT_UNKNOWN)
2057 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2060 gint change_dir(const gchar *dir)
2062 gchar *prevdir = NULL;
2065 prevdir = g_get_current_dir();
2067 if (g_chdir(dir) < 0) {
2068 FILE_OP_ERROR(dir, "chdir");
2069 if (debug_mode) g_free(prevdir);
2071 } else if (debug_mode) {
2074 cwd = g_get_current_dir();
2075 if (strcmp(prevdir, cwd) != 0)
2076 g_print("current dir: %s\n", cwd);
2084 gint make_dir(const gchar *dir)
2086 if (g_mkdir(dir, S_IRWXU) < 0) {
2087 FILE_OP_ERROR(dir, "mkdir");
2090 if (g_chmod(dir, S_IRWXU) < 0)
2091 FILE_OP_ERROR(dir, "chmod");
2096 gint make_dir_hier(const gchar *dir)
2101 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2102 parent_dir = g_strndup(dir, p - dir);
2103 if (*parent_dir != '\0') {
2104 if (!is_dir_exist(parent_dir)) {
2105 if (make_dir(parent_dir) < 0) {
2114 if (!is_dir_exist(dir)) {
2115 if (make_dir(dir) < 0)
2122 gint remove_all_files(const gchar *dir)
2125 const gchar *file_name;
2128 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2129 g_warning("failed to open directory: %s", dir);
2133 while ((file_name = g_dir_read_name(dp)) != NULL) {
2134 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2135 if (claws_unlink(tmp) < 0)
2136 FILE_OP_ERROR(tmp, "unlink");
2145 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2148 const gchar *dir_name;
2152 if (first == last) {
2153 /* Skip all the dir reading part. */
2154 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2155 if (is_dir_exist(filename)) {
2156 /* a numbered directory with this name exists,
2157 * remove the dot-file instead */
2159 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2161 if (claws_unlink(filename) < 0) {
2162 FILE_OP_ERROR(filename, "unlink");
2170 prev_dir = g_get_current_dir();
2172 if (g_chdir(dir) < 0) {
2173 FILE_OP_ERROR(dir, "chdir");
2178 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2179 g_warning("failed to open directory: %s", dir);
2184 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2185 file_no = to_number(dir_name);
2186 if (file_no > 0 && first <= file_no && file_no <= last) {
2187 if (is_dir_exist(dir_name)) {
2188 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2189 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2190 FILE_OP_ERROR(dot_file, "unlink");
2195 if (claws_unlink(dir_name) < 0)
2196 FILE_OP_ERROR(dir_name, "unlink");
2202 if (g_chdir(prev_dir) < 0) {
2203 FILE_OP_ERROR(prev_dir, "chdir");
2213 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2216 const gchar *dir_name;
2219 GHashTable *wanted_files;
2221 GError *error = NULL;
2223 if (numberlist == NULL)
2226 prev_dir = g_get_current_dir();
2228 if (g_chdir(dir) < 0) {
2229 FILE_OP_ERROR(dir, "chdir");
2234 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2235 g_message("Couldn't open current directory: %s (%d).\n",
2236 error->message, error->code);
2237 g_error_free(error);
2242 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2243 for (cur = numberlist; cur != NULL; cur = cur->next) {
2244 /* numberlist->data is expected to be GINT_TO_POINTER */
2245 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2248 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2249 file_no = to_number(dir_name);
2250 if (is_dir_exist(dir_name))
2252 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2253 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2254 if (is_dir_exist(dir_name)) {
2255 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2256 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2257 FILE_OP_ERROR(dot_file, "unlink");
2262 if (claws_unlink(dir_name) < 0)
2263 FILE_OP_ERROR(dir_name, "unlink");
2268 g_hash_table_destroy(wanted_files);
2270 if (g_chdir(prev_dir) < 0) {
2271 FILE_OP_ERROR(prev_dir, "chdir");
2281 gint remove_all_numbered_files(const gchar *dir)
2283 return remove_numbered_files(dir, 0, UINT_MAX);
2286 gint remove_dir_recursive(const gchar *dir)
2290 const gchar *dir_name;
2293 if (g_stat(dir, &s) < 0) {
2294 FILE_OP_ERROR(dir, "stat");
2295 if (ENOENT == errno) return 0;
2299 if (!S_ISDIR(s.st_mode)) {
2300 if (claws_unlink(dir) < 0) {
2301 FILE_OP_ERROR(dir, "unlink");
2308 prev_dir = g_get_current_dir();
2309 /* g_print("prev_dir = %s\n", prev_dir); */
2311 if (!path_cmp(prev_dir, dir)) {
2313 if (g_chdir("..") < 0) {
2314 FILE_OP_ERROR(dir, "chdir");
2317 prev_dir = g_get_current_dir();
2320 if (g_chdir(dir) < 0) {
2321 FILE_OP_ERROR(dir, "chdir");
2326 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2327 g_warning("failed to open directory: %s", dir);
2333 /* remove all files in the directory */
2334 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2335 /* g_print("removing %s\n", dir_name); */
2337 if (is_dir_exist(dir_name)) {
2340 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2341 g_warning("can't remove directory: %s", dir_name);
2345 if (claws_unlink(dir_name) < 0)
2346 FILE_OP_ERROR(dir_name, "unlink");
2352 if (g_chdir(prev_dir) < 0) {
2353 FILE_OP_ERROR(prev_dir, "chdir");
2360 if (g_rmdir(dir) < 0) {
2361 FILE_OP_ERROR(dir, "rmdir");
2368 /* convert line endings into CRLF. If the last line doesn't end with
2369 * linebreak, add it.
2371 gchar *canonicalize_str(const gchar *str)
2377 for (p = str; *p != '\0'; ++p) {
2384 if (p == str || *(p - 1) != '\n')
2387 out = outp = g_malloc(new_len + 1);
2388 for (p = str; *p != '\0'; ++p) {
2395 if (p == str || *(p - 1) != '\n') {
2404 gchar *normalize_newlines(const gchar *str)
2409 out = outp = g_malloc(strlen(str) + 1);
2410 for (p = str; *p != '\0'; ++p) {
2412 if (*(p + 1) != '\n')
2423 gchar *get_outgoing_rfc2822_str(FILE *fp)
2425 gchar buf[BUFFSIZE];
2429 str = g_string_new(NULL);
2431 /* output header part */
2432 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2434 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2441 else if (next != ' ' && next != '\t') {
2445 if (claws_fgets(buf, sizeof(buf), fp) == NULL)
2449 g_string_append(str, buf);
2450 g_string_append(str, "\r\n");
2456 /* output body part */
2457 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2460 g_string_append_c(str, '.');
2461 g_string_append(str, buf);
2462 g_string_append(str, "\r\n");
2466 g_string_free(str, FALSE);
2472 * Create a new boundary in a way that it is very unlikely that this
2473 * will occur in the following text. It would be easy to ensure
2474 * uniqueness if everything is either quoted-printable or base64
2475 * encoded (note that conversion is allowed), but because MIME bodies
2476 * may be nested, it may happen that the same boundary has already
2479 * boundary := 0*69<bchars> bcharsnospace
2480 * bchars := bcharsnospace / " "
2481 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2482 * "+" / "_" / "," / "-" / "." /
2483 * "/" / ":" / "=" / "?"
2485 * some special characters removed because of buggy MTAs
2488 gchar *generate_mime_boundary(const gchar *prefix)
2490 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2491 "abcdefghijklmnopqrstuvwxyz"
2496 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2497 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2500 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2504 char *fgets_crlf(char *buf, int size, FILE *stream)
2506 gboolean is_cr = FALSE;
2507 gboolean last_was_cr = FALSE;
2512 while (--size > 0 && (c = getc(stream)) != EOF)
2515 is_cr = (c == '\r');
2525 last_was_cr = is_cr;
2527 if (c == EOF && cs == buf)
2535 static gint execute_async(gchar *const argv[], const gchar *working_directory)
2537 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2539 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2540 NULL, NULL, NULL, FALSE) == FALSE) {
2541 g_warning("couldn't execute command: %s", argv[0]);
2548 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
2552 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2555 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2556 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2557 g_warning("couldn't execute command: %s", argv[0]);
2561 if (WIFEXITED(status))
2562 return WEXITSTATUS(status);
2566 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
2567 G_SPAWN_SEARCH_PATH|
2568 G_SPAWN_CHILD_INHERITS_STDIN|
2569 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
2570 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2571 g_warning("couldn't execute command: %s", argv[0]);
2579 gint execute_command_line(const gchar *cmdline, gboolean async,
2580 const gchar *working_directory)
2585 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
2587 argv = strsplit_with_quote(cmdline, " ", 0);
2590 ret = execute_async(argv, working_directory);
2592 ret = execute_sync(argv, working_directory);
2599 gchar *get_command_output(const gchar *cmdline)
2601 gchar *child_stdout;
2604 cm_return_val_if_fail(cmdline != NULL, NULL);
2606 debug_print("get_command_output(): executing: %s\n", cmdline);
2608 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
2610 g_warning("couldn't execute command: %s", cmdline);
2614 return child_stdout;
2617 static gint is_unchanged_uri_char(char c)
2628 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2634 for(i = 0; i < strlen(uri) ; i++) {
2635 if (is_unchanged_uri_char(uri[i])) {
2636 if (k + 2 >= bufsize)
2638 encoded_uri[k++] = uri[i];
2641 char * hexa = "0123456789ABCDEF";
2643 if (k + 4 >= bufsize)
2645 encoded_uri[k++] = '%';
2646 encoded_uri[k++] = hexa[uri[i] / 16];
2647 encoded_uri[k++] = hexa[uri[i] % 16];
2653 gint open_uri(const gchar *uri, const gchar *cmdline)
2657 gchar buf[BUFFSIZE];
2659 gchar encoded_uri[BUFFSIZE];
2660 cm_return_val_if_fail(uri != NULL, -1);
2662 /* an option to choose whether to use encode_uri or not ? */
2663 encode_uri(encoded_uri, BUFFSIZE, uri);
2666 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2667 !strchr(p + 2, '%'))
2668 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
2671 g_warning("Open URI command-line is invalid "
2672 "(there must be only one '%%s'): %s",
2674 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
2677 execute_command_line(buf, TRUE, NULL);
2679 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
2684 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
2686 gchar buf[BUFFSIZE];
2689 cm_return_val_if_fail(filepath != NULL, -1);
2692 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2693 !strchr(p + 2, '%'))
2694 g_snprintf(buf, sizeof(buf), cmdline, filepath);
2697 g_warning("Open Text Editor command-line is invalid "
2698 "(there must be only one '%%s'): %s",
2700 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
2703 execute_command_line(buf, TRUE, NULL);
2708 time_t remote_tzoffset_sec(const gchar *zone)
2710 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
2716 time_t remoteoffset;
2718 strncpy(zone3, zone, 3);
2722 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
2723 (c == '+' || c == '-')) {
2724 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
2726 remoteoffset = -remoteoffset;
2727 } else if (!strncmp(zone, "UT" , 2) ||
2728 !strncmp(zone, "GMT", 3)) {
2730 } else if (strlen(zone3) == 3) {
2731 for (p = ustzstr; *p != '\0'; p += 3) {
2732 if (!g_ascii_strncasecmp(p, zone3, 3)) {
2733 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
2734 remoteoffset = iustz * 3600;
2740 } else if (strlen(zone3) == 1) {
2742 case 'Z': remoteoffset = 0; break;
2743 case 'A': remoteoffset = -1; break;
2744 case 'B': remoteoffset = -2; break;
2745 case 'C': remoteoffset = -3; break;
2746 case 'D': remoteoffset = -4; break;
2747 case 'E': remoteoffset = -5; break;
2748 case 'F': remoteoffset = -6; break;
2749 case 'G': remoteoffset = -7; break;
2750 case 'H': remoteoffset = -8; break;
2751 case 'I': remoteoffset = -9; break;
2752 case 'K': remoteoffset = -10; break; /* J is not used */
2753 case 'L': remoteoffset = -11; break;
2754 case 'M': remoteoffset = -12; break;
2755 case 'N': remoteoffset = 1; break;
2756 case 'O': remoteoffset = 2; break;
2757 case 'P': remoteoffset = 3; break;
2758 case 'Q': remoteoffset = 4; break;
2759 case 'R': remoteoffset = 5; break;
2760 case 'S': remoteoffset = 6; break;
2761 case 'T': remoteoffset = 7; break;
2762 case 'U': remoteoffset = 8; break;
2763 case 'V': remoteoffset = 9; break;
2764 case 'W': remoteoffset = 10; break;
2765 case 'X': remoteoffset = 11; break;
2766 case 'Y': remoteoffset = 12; break;
2767 default: remoteoffset = 0; break;
2769 remoteoffset = remoteoffset * 3600;
2773 return remoteoffset;
2776 time_t tzoffset_sec(time_t *now)
2780 struct tm buf1, buf2;
2782 if (now && *now < 0)
2785 gmt = *gmtime_r(now, &buf1);
2786 lt = localtime_r(now, &buf2);
2788 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2790 if (lt->tm_year < gmt.tm_year)
2792 else if (lt->tm_year > gmt.tm_year)
2794 else if (lt->tm_yday < gmt.tm_yday)
2796 else if (lt->tm_yday > gmt.tm_yday)
2799 if (off >= 24 * 60) /* should be impossible */
2800 off = 23 * 60 + 59; /* if not, insert silly value */
2801 if (off <= -24 * 60)
2802 off = -(23 * 60 + 59);
2807 /* calculate timezone offset */
2808 gchar *tzoffset(time_t *now)
2810 static gchar offset_string[6];
2814 struct tm buf1, buf2;
2816 if (now && *now < 0)
2819 gmt = *gmtime_r(now, &buf1);
2820 lt = localtime_r(now, &buf2);
2822 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2824 if (lt->tm_year < gmt.tm_year)
2826 else if (lt->tm_year > gmt.tm_year)
2828 else if (lt->tm_yday < gmt.tm_yday)
2830 else if (lt->tm_yday > gmt.tm_yday)
2838 if (off >= 24 * 60) /* should be impossible */
2839 off = 23 * 60 + 59; /* if not, insert silly value */
2841 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
2843 return offset_string;
2846 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
2850 gchar day[4], mon[4];
2851 gint dd, hh, mm, ss, yyyy;
2853 gchar buf2[RFC822_DATE_BUFFSIZE];
2857 lt = gmtime_r(&t, &buf1);
2859 lt = localtime_r(&t, &buf1);
2861 if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
2862 day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
2863 g_warning("failed reading date/time");
2865 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
2866 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
2869 void get_rfc822_date(gchar *buf, gint len)
2871 _get_rfc822_date(buf, len, FALSE);
2874 void get_rfc822_date_hide_tz(gchar *buf, gint len)
2876 _get_rfc822_date(buf, len, TRUE);
2879 void debug_set_mode(gboolean mode)
2884 gboolean debug_get_mode(void)
2889 void debug_print_real(const gchar *format, ...)
2892 gchar buf[BUFFSIZE];
2894 if (!debug_mode) return;
2896 va_start(args, format);
2897 g_vsnprintf(buf, sizeof(buf), format, args);
2904 const char * debug_srcname(const char *file)
2906 const char *s = strrchr (file, '/');
2911 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
2913 if (subject == NULL)
2916 subject += subject_get_prefix_length(subject);
2918 return g_hash_table_lookup(subject_table, subject);
2921 void subject_table_insert(GHashTable *subject_table, gchar * subject,
2924 if (subject == NULL || *subject == 0)
2926 subject += subject_get_prefix_length(subject);
2927 g_hash_table_insert(subject_table, subject, data);
2930 void subject_table_remove(GHashTable *subject_table, gchar * subject)
2932 if (subject == NULL)
2935 subject += subject_get_prefix_length(subject);
2936 g_hash_table_remove(subject_table, subject);
2939 static regex_t u_regex;
2940 static gboolean u_init_;
2942 void utils_free_regex(void)
2951 *\brief Check if a string is prefixed with known (combinations)
2952 * of prefixes. The function assumes that each prefix
2953 * is terminated by zero or exactly _one_ space.
2955 *\param str String to check for a prefixes
2957 *\return int Number of chars in the prefix that should be skipped
2958 * for a "clean" subject line. If no prefix was found, 0
2961 int subject_get_prefix_length(const gchar *subject)
2963 /*!< Array with allowable reply prefixes regexps. */
2964 static const gchar * const prefixes[] = {
2965 "Re\\:", /* "Re:" */
2966 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
2967 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
2968 "Aw\\:", /* "Aw:" (German) */
2969 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
2970 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
2971 "Fw\\:", /* "Fw:" Forward */
2972 "Fwd\\:", /* "Fwd:" Forward */
2973 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
2974 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
2975 "Rif\\:", /* "Rif:" (Italian Outlook) */
2976 "Sv\\:", /* "Sv" (Norwegian) */
2977 "Vs\\:", /* "Vs" (Norwegian) */
2978 "Ad\\:", /* "Ad" (Norwegian) */
2979 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
2980 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
2981 "Re \\:", /* "Re :" (French Yahoo Mail) */
2984 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
2988 if (!subject) return 0;
2989 if (!*subject) return 0;
2992 GString *s = g_string_new("");
2994 for (n = 0; n < PREFIXES; n++)
2995 /* Terminate each prefix regexpression by a
2996 * "\ ?" (zero or ONE space), and OR them */
2997 g_string_append_printf(s, "(%s\\ ?)%s",
3002 g_string_prepend(s, "(");
3003 g_string_append(s, ")+"); /* match at least once */
3004 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3007 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3008 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3009 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3010 debug_print("Error compiling regexp %s\n", s->str);
3011 g_string_free(s, TRUE);
3015 g_string_free(s, TRUE);
3019 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3025 static guint g_stricase_hash(gconstpointer gptr)
3027 guint hash_result = 0;
3030 for (str = gptr; str && *str; str++) {
3031 hash_result += toupper(*str);
3037 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3039 const char *str1 = gptr1;
3040 const char *str2 = gptr2;
3042 return !strcasecmp(str1, str2);
3045 gint g_int_compare(gconstpointer a, gconstpointer b)
3047 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3051 quote_cmd_argument()
3053 return a quoted string safely usable in argument of a command.
3055 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3058 gint quote_cmd_argument(gchar * result, guint size,
3068 for(p = path ; * p != '\0' ; p ++) {
3070 if (isalnum((guchar)*p) || (* p == '/')) {
3071 if (remaining > 0) {
3077 result[size - 1] = '\0';
3082 if (remaining >= 2) {
3090 result[size - 1] = '\0';
3095 if (remaining > 0) {
3099 result[size - 1] = '\0';
3113 static void g_node_map_recursive(GNode *node, gpointer data)
3115 GNodeMapData *mapdata = (GNodeMapData *) data;
3117 GNodeMapData newmapdata;
3120 newdata = mapdata->func(node->data, mapdata->data);
3121 if (newdata != NULL) {
3122 newnode = g_node_new(newdata);
3123 g_node_append(mapdata->parent, newnode);
3125 newmapdata.parent = newnode;
3126 newmapdata.func = mapdata->func;
3127 newmapdata.data = mapdata->data;
3129 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3133 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3136 GNodeMapData mapdata;
3138 cm_return_val_if_fail(node != NULL, NULL);
3139 cm_return_val_if_fail(func != NULL, NULL);
3141 root = g_node_new(func(node->data, data));
3143 mapdata.parent = root;
3144 mapdata.func = func;
3145 mapdata.data = data;
3147 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3152 #define HEX_TO_INT(val, hex) \
3156 if ('0' <= c && c <= '9') { \
3158 } else if ('a' <= c && c <= 'f') { \
3159 val = c - 'a' + 10; \
3160 } else if ('A' <= c && c <= 'F') { \
3161 val = c - 'A' + 10; \
3167 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3174 if (hi == -1 || lo == -1)
3177 *out = (hi << 4) + lo;
3181 #define INT_TO_HEX(hex, val) \
3184 hex = '0' + (val); \
3186 hex = 'A' + (val) - 10; \
3189 void get_hex_str(gchar *out, guchar ch)
3193 INT_TO_HEX(hex, ch >> 4);
3195 INT_TO_HEX(hex, ch & 0x0f);
3201 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3203 #define G_PRINT_REF g_print
3207 *\brief Register ref counted pointer. It is based on GBoxed, so should
3208 * work with anything that uses the GType system. The semantics
3209 * are similar to a C++ auto pointer, with the exception that
3210 * C doesn't have automatic closure (calling destructors) when
3211 * exiting a block scope.
3212 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3213 * function directly.
3215 *\return GType A GType type.
3217 GType g_auto_pointer_register(void)
3219 static GType auto_pointer_type;
3220 if (!auto_pointer_type)
3222 g_boxed_type_register_static
3223 ("G_TYPE_AUTO_POINTER",
3224 (GBoxedCopyFunc) g_auto_pointer_copy,
3225 (GBoxedFreeFunc) g_auto_pointer_free);
3226 return auto_pointer_type;
3230 *\brief Structure with g_new() allocated pointer guarded by the
3233 typedef struct AutoPointerRef {
3234 void (*free) (gpointer);
3240 *\brief The auto pointer opaque structure that references the
3241 * pointer guard block.
3243 typedef struct AutoPointer {
3244 AutoPointerRef *ref;
3245 gpointer ptr; /*!< access to protected pointer */
3249 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3253 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3254 * ... when assigning, copying and freeing storage elements
3256 * gtk_list_store_new(N_S_COLUMNS,
3257 * G_TYPE_AUTO_POINTER,
3261 * Template *precious_data = g_new0(Template, 1);
3262 * g_pointer protect = g_auto_pointer_new(precious_data);
3264 * gtk_list_store_set(container, &iter,
3268 * ... the gtk_list_store has copied the pointer and
3269 * ... incremented its reference count, we should free
3270 * ... the auto pointer (in C++ a destructor would do
3271 * ... this for us when leaving block scope)
3273 * g_auto_pointer_free(protect);
3275 * ... gtk_list_store_set() now manages the data. When
3276 * ... *explicitly* requesting a pointer from the list
3277 * ... store, don't forget you get a copy that should be
3278 * ... freed with g_auto_pointer_free() eventually.
3282 *\param pointer Pointer to be guarded.
3284 *\return GAuto * Pointer that should be used in containers with
3287 GAuto *g_auto_pointer_new(gpointer p)
3289 AutoPointerRef *ref;
3295 ref = g_new0(AutoPointerRef, 1);
3296 ptr = g_new0(AutoPointer, 1);
3306 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3312 *\brief Allocate an autopointer using the passed \a free function to
3313 * free the guarded pointer
3315 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3322 aptr = g_auto_pointer_new(p);
3323 aptr->ref->free = free_;
3327 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3329 if (auto_ptr == NULL)
3331 return ((AutoPointer *) auto_ptr)->ptr;
3335 *\brief Copies an auto pointer by. It's mostly not necessary
3336 * to call this function directly, unless you copy/assign
3337 * the guarded pointer.
3339 *\param auto_ptr Auto pointer returned by previous call to
3340 * g_auto_pointer_new_XXX()
3342 *\return gpointer An auto pointer
3344 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3347 AutoPointerRef *ref;
3350 if (auto_ptr == NULL)
3355 newp = g_new0(AutoPointer, 1);
3358 newp->ptr = ref->pointer;
3362 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3368 *\brief Free an auto pointer
3370 void g_auto_pointer_free(GAuto *auto_ptr)
3373 AutoPointerRef *ref;
3375 if (auto_ptr == NULL)
3381 if (--(ref->cnt) == 0) {
3383 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3385 ref->free(ref->pointer);
3390 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3395 void replace_returns(gchar *str)
3400 while (strstr(str, "\n")) {
3401 *strstr(str, "\n") = ' ';
3403 while (strstr(str, "\r")) {
3404 *strstr(str, "\r") = ' ';
3408 /* get_uri_part() - retrieves a URI starting from scanpos.
3409 Returns TRUE if successful */
3410 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
3411 const gchar **bp, const gchar **ep, gboolean hdr)
3414 gint parenthese_cnt = 0;
3416 cm_return_val_if_fail(start != NULL, FALSE);
3417 cm_return_val_if_fail(scanpos != NULL, FALSE);
3418 cm_return_val_if_fail(bp != NULL, FALSE);
3419 cm_return_val_if_fail(ep != NULL, FALSE);
3423 /* find end point of URI */
3424 for (ep_ = scanpos; *ep_ != '\0'; ep_ = g_utf8_next_char(ep_)) {
3425 gunichar u = g_utf8_get_char_validated(ep_, -1);
3426 if (!g_unichar_isgraph(u) ||
3427 u == (gunichar)-1 ||
3428 strchr("[]{}<>\"", *ep_)) {
3430 } else if (strchr("(", *ep_)) {
3432 } else if (strchr(")", *ep_)) {
3433 if (parenthese_cnt > 0)
3440 /* no punctuation at end of string */
3442 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
3443 * should pass some URI type to this function and decide on that whether
3444 * to perform punctuation stripping */
3446 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
3448 for (; ep_ - 1 > scanpos + 1 &&
3449 IS_REAL_PUNCT(*(ep_ - 1));
3453 #undef IS_REAL_PUNCT
3460 gchar *make_uri_string(const gchar *bp, const gchar *ep)
3462 while (bp && *bp && g_ascii_isspace(*bp))
3464 return g_strndup(bp, ep - bp);
3467 /* valid mail address characters */
3468 #define IS_RFC822_CHAR(ch) \
3472 !g_ascii_isspace(ch) && \
3473 !strchr("(),;<>\"", (ch)))
3475 /* alphabet and number within 7bit ASCII */
3476 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
3477 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
3479 static GHashTable *create_domain_tab(void)
3482 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
3484 cm_return_val_if_fail(htab, NULL);
3485 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
3486 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
3490 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
3492 const gint MAX_LVL_DOM_NAME_LEN = 6;
3493 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
3494 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
3497 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
3500 for (p = buf; p < m && first < last; *p++ = *first++)
3504 return g_hash_table_lookup(tab, buf) != NULL;
3507 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
3508 gboolean get_email_part(const gchar *start, const gchar *scanpos,
3509 const gchar **bp, const gchar **ep, gboolean hdr)
3511 /* more complex than the uri part because we need to scan back and forward starting from
3512 * the scan position. */
3513 gboolean result = FALSE;
3514 const gchar *bp_ = NULL;
3515 const gchar *ep_ = NULL;
3516 static GHashTable *dom_tab;
3517 const gchar *last_dot = NULL;
3518 const gchar *prelast_dot = NULL;
3519 const gchar *last_tld_char = NULL;
3521 /* the informative part of the email address (describing the name
3522 * of the email address owner) may contain quoted parts. the
3523 * closure stack stores the last encountered quotes. */
3524 gchar closure_stack[128];
3525 gchar *ptr = closure_stack;
3527 cm_return_val_if_fail(start != NULL, FALSE);
3528 cm_return_val_if_fail(scanpos != NULL, FALSE);
3529 cm_return_val_if_fail(bp != NULL, FALSE);
3530 cm_return_val_if_fail(ep != NULL, FALSE);
3533 const gchar *start_quote = NULL;
3534 const gchar *end_quote = NULL;
3536 /* go to the real start */
3537 if (start[0] == ',')
3539 if (start[0] == ';')
3541 while (start[0] == '\n' || start[0] == '\r')
3543 while (start[0] == ' ' || start[0] == '\t')
3548 /* check if there are quotes (to skip , in them) */
3549 if (*start == '"') {
3550 start_quote = start;
3552 end_quote = strstr(start, "\"");
3558 /* skip anything between quotes */
3559 if (start_quote && end_quote) {
3564 /* find end (either , or ; or end of line) */
3565 if (strstr(start, ",") && strstr(start, ";"))
3566 *ep = strstr(start,",") < strstr(start, ";")
3567 ? strstr(start, ",") : strstr(start, ";");
3568 else if (strstr(start, ","))
3569 *ep = strstr(start, ",");
3570 else if (strstr(start, ";"))
3571 *ep = strstr(start, ";");
3573 *ep = start+strlen(start);
3575 /* go back to real start */
3576 if (start_quote && end_quote) {
3577 start = start_quote;
3580 /* check there's still an @ in that, or search
3581 * further if possible */
3582 if (strstr(start, "@") && strstr(start, "@") < *ep)
3584 else if (*ep < start+strlen(start)) {
3587 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
3595 dom_tab = create_domain_tab();
3596 cm_return_val_if_fail(dom_tab, FALSE);
3598 /* scan start of address */
3599 for (bp_ = scanpos - 1;
3600 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
3603 /* TODO: should start with an alnum? */
3605 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
3608 if (bp_ != scanpos) {
3609 /* scan end of address */
3610 for (ep_ = scanpos + 1;
3611 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
3613 prelast_dot = last_dot;
3615 if (*(last_dot + 1) == '.') {
3616 if (prelast_dot == NULL)
3618 last_dot = prelast_dot;
3623 /* TODO: really should terminate with an alnum? */
3624 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
3629 if (last_dot == NULL)
3631 if (last_dot >= ep_)
3632 last_dot = prelast_dot;
3633 if (last_dot == NULL || (scanpos + 1 >= last_dot))
3637 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
3638 if (*last_tld_char == '?')
3641 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
3648 if (!result) return FALSE;
3650 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
3651 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
3652 && IS_RFC822_CHAR(*(ep_ + 3))) {
3653 /* this informative part with an @ in it is
3654 * followed by the email address */
3657 /* go to matching '>' (or next non-rfc822 char, like \n) */
3658 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
3661 /* include the bracket */
3662 if (*ep_ == '>') ep_++;
3664 /* include the leading quote */
3672 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
3673 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
3676 /* see if this is <bracketed>; in this case we also scan for the informative part. */
3677 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
3680 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
3681 #define IN_STACK() (ptr > closure_stack)
3682 /* has underrun check */
3683 #define POP_STACK() if(IN_STACK()) --ptr
3684 /* has overrun check */
3685 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
3686 /* has underrun check */
3687 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
3691 /* scan for the informative part. */
3692 for (bp_ -= 2; bp_ >= start; bp_--) {
3693 /* if closure on the stack keep scanning */
3694 if (PEEK_STACK() == *bp_) {
3698 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
3703 /* if nothing in the closure stack, do the special conditions
3704 * the following if..else expression simply checks whether
3705 * a token is acceptable. if not acceptable, the clause
3706 * should terminate the loop with a 'break' */
3707 if (!PEEK_STACK()) {
3709 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
3710 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
3711 /* hyphens are allowed, but only in
3713 } else if (strchr(" \"'", *bp_)) {
3714 /* but anything not being a punctiation
3717 break; /* anything else is rejected */
3724 /* scan forward (should start with an alnum) */
3725 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
3741 #undef IS_ASCII_ALNUM
3742 #undef IS_RFC822_CHAR
3744 gchar *make_email_string(const gchar *bp, const gchar *ep)
3746 /* returns a mailto: URI; mailto: is also used to detect the
3747 * uri type later on in the button_pressed signal handler */
3752 tmp = g_strndup(bp, ep - bp);
3754 /* If there is a colon in the username part of the address,
3755 * we're dealing with an URI for some other protocol - do
3756 * not prefix with mailto: in such case. */
3757 colon = strchr(tmp, ':');
3758 at = strchr(tmp, '@');
3759 if (colon != NULL && at != NULL && colon < at) {
3762 result = g_strconcat("mailto:", tmp, NULL);
3769 gchar *make_http_string(const gchar *bp, const gchar *ep)
3771 /* returns an http: URI; */
3775 while (bp && *bp && g_ascii_isspace(*bp))
3777 tmp = g_strndup(bp, ep - bp);
3778 result = g_strconcat("http://", tmp, NULL);
3784 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
3786 FILE *fp = claws_fopen(path, "rb");
3787 gchar buf[BUFFSIZE];
3788 gchar *result = NULL;
3791 while (claws_fgets(buf, sizeof (buf), fp) != NULL) {
3792 gchar **parts = g_strsplit(buf, ";", 3);
3793 gchar *trimmed = parts[0];
3794 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3796 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3797 trimmed[strlen(trimmed)-1] = '\0';
3799 if (!strcmp(trimmed, type)) {
3800 gboolean needsterminal = FALSE;
3801 if (parts[2] && strstr(parts[2], "needsterminal")) {
3802 needsterminal = TRUE;
3804 if (parts[2] && strstr(parts[2], "test=")) {
3805 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
3806 gchar *testcmd = orig_testcmd;
3807 if (strstr(testcmd,";"))
3808 *(strstr(testcmd,";")) = '\0';
3809 while (testcmd[0] == ' ' || testcmd[0] == '\t')
3811 while (testcmd[strlen(testcmd)-1] == '\n')
3812 testcmd[strlen(testcmd)-1] = '\0';
3813 while (testcmd[strlen(testcmd)-1] == '\r')
3814 testcmd[strlen(testcmd)-1] = '\0';
3815 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
3816 testcmd[strlen(testcmd)-1] = '\0';
3818 if (strstr(testcmd, "%s")) {
3819 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
3820 gint res = system(tmp);
3822 g_free(orig_testcmd);
3829 gint res = system(testcmd);
3830 g_free(orig_testcmd);
3840 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3842 while (trimmed[strlen(trimmed)-1] == '\n')
3843 trimmed[strlen(trimmed)-1] = '\0';
3844 while (trimmed[strlen(trimmed)-1] == '\r')
3845 trimmed[strlen(trimmed)-1] = '\0';
3846 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3847 trimmed[strlen(trimmed)-1] = '\0';
3848 result = g_strdup(trimmed);
3851 if (needsterminal) {
3852 gchar *tmp = g_strdup_printf("xterm -e %s", result);
3863 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
3865 gchar *result = NULL;
3869 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3870 result = mailcap_get_command_in_file(path, type, file_to_open);
3874 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
3878 void mailcap_update_default(const gchar *type, const gchar *command)
3880 gchar *path = NULL, *outpath = NULL;
3881 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3882 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
3883 FILE *fp = claws_fopen(path, "rb");
3885 gchar buf[BUFFSIZE];
3886 gboolean err = FALSE;
3889 fp = claws_fopen(path, "a");
3891 g_warning("failed to create file %s", path);
3896 fp = g_freopen(path, "rb", fp);
3898 g_warning("failed to reopen file %s", path);
3905 outfp = claws_fopen(outpath, "wb");
3907 g_warning("failed to create file %s", outpath);
3913 while (fp && claws_fgets(buf, sizeof (buf), fp) != NULL) {
3914 gchar **parts = g_strsplit(buf, ";", 3);
3915 gchar *trimmed = parts[0];
3916 while (trimmed[0] == ' ')
3918 while (trimmed[strlen(trimmed)-1] == ' ')
3919 trimmed[strlen(trimmed)-1] = '\0';
3921 if (!strcmp(trimmed, type)) {
3926 if(claws_fputs(buf, outfp) == EOF) {
3933 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
3939 if (claws_safe_fclose(outfp) == EOF)
3943 g_rename(outpath, path);
3949 /* crude test to see if a file is an email. */
3950 gboolean file_is_email (const gchar *filename)
3956 if (filename == NULL)
3958 if ((fp = claws_fopen(filename, "rb")) == NULL)
3960 while (i < 60 && score < 3
3961 && claws_fgets(buffer, sizeof (buffer), fp) != NULL) {
3962 if (!strncmp(buffer, "From:", strlen("From:")))
3964 else if (!strncmp(buffer, "Date:", strlen("Date:")))
3966 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
3968 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
3973 return (score >= 3);
3976 gboolean sc_g_list_bigger(GList *list, gint max)
3980 while (cur && i <= max+1) {
3987 gboolean sc_g_slist_bigger(GSList *list, gint max)
3991 while (cur && i <= max+1) {
3998 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
3999 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4000 NULL, NULL, NULL, NULL, NULL, NULL};
4001 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4002 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4003 NULL, NULL, NULL, NULL, NULL, NULL};
4005 gint daynames_len[] = {0,0,0,0,0,0,0};
4006 gint monthnames_len[] = {0,0,0,0,0,0,
4008 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4009 gint s_monthnames_len[] = {0,0,0,0,0,0,
4011 const gchar *s_am_up = NULL;
4012 const gchar *s_pm_up = NULL;
4013 const gchar *s_am_low = NULL;
4014 const gchar *s_pm_low = NULL;
4016 gint s_am_up_len = 0;
4017 gint s_pm_up_len = 0;
4018 gint s_am_low_len = 0;
4019 gint s_pm_low_len = 0;
4021 static gboolean time_names_init_done = FALSE;
4023 static void init_time_names(void)
4027 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4028 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4029 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4030 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4031 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4032 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4033 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4035 monthnames[0] = C_("Complete month name for use by strftime", "January");
4036 monthnames[1] = C_("Complete month name for use by strftime", "February");
4037 monthnames[2] = C_("Complete month name for use by strftime", "March");
4038 monthnames[3] = C_("Complete month name for use by strftime", "April");
4039 monthnames[4] = C_("Complete month name for use by strftime", "May");
4040 monthnames[5] = C_("Complete month name for use by strftime", "June");
4041 monthnames[6] = C_("Complete month name for use by strftime", "July");
4042 monthnames[7] = C_("Complete month name for use by strftime", "August");
4043 monthnames[8] = C_("Complete month name for use by strftime", "September");
4044 monthnames[9] = C_("Complete month name for use by strftime", "October");
4045 monthnames[10] = C_("Complete month name for use by strftime", "November");
4046 monthnames[11] = C_("Complete month name for use by strftime", "December");
4048 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4049 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4050 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4051 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4052 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4053 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4054 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4056 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4057 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4058 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4059 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4060 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4061 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4062 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4063 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4064 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4065 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4066 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4067 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4069 for (i = 0; i < 7; i++) {
4070 daynames_len[i] = strlen(daynames[i]);
4071 s_daynames_len[i] = strlen(s_daynames[i]);
4073 for (i = 0; i < 12; i++) {
4074 monthnames_len[i] = strlen(monthnames[i]);
4075 s_monthnames_len[i] = strlen(s_monthnames[i]);
4078 s_am_up = C_("For use by strftime (morning)", "AM");
4079 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4080 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4081 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4083 s_am_up_len = strlen(s_am_up);
4084 s_pm_up_len = strlen(s_pm_up);
4085 s_am_low_len = strlen(s_am_low);
4086 s_pm_low_len = strlen(s_pm_low);
4088 time_names_init_done = TRUE;
4091 #define CHECK_SIZE() { \
4092 total_done += len; \
4093 if (total_done >= buflen) { \
4094 buf[buflen-1] = '\0'; \
4099 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4101 gchar *curpos = buf;
4102 gint total_done = 0;
4103 gchar subbuf[64], subfmt[64];
4104 static time_t last_tzset = (time_t)0;
4106 if (!time_names_init_done)
4109 if (format == NULL || lt == NULL)
4112 if (last_tzset != time(NULL)) {
4114 last_tzset = time(NULL);
4117 if (*format == '%') {
4118 gint len = 0, tmp = 0;
4122 len = 1; CHECK_SIZE();
4126 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4127 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4130 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4131 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4135 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4136 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4139 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4140 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4143 strftime(subbuf, 64, "%c", lt);
4144 len = strlen(subbuf); CHECK_SIZE();
4145 strncpy2(curpos, subbuf, buflen - total_done);
4148 total_done += 2; CHECK_SIZE();
4149 tmp = (lt->tm_year + 1900)/100;
4150 *curpos++ = '0'+(tmp / 10);
4151 *curpos++ = '0'+(tmp % 10);
4154 total_done += 2; CHECK_SIZE();
4155 *curpos++ = '0'+(lt->tm_mday / 10);
4156 *curpos++ = '0'+(lt->tm_mday % 10);
4159 total_done += 8; CHECK_SIZE();
4160 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4161 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4163 *curpos++ = '0'+(lt->tm_mday / 10);
4164 *curpos++ = '0'+(lt->tm_mday % 10);
4166 tmp = lt->tm_year%100;
4167 *curpos++ = '0'+(tmp / 10);
4168 *curpos++ = '0'+(tmp % 10);
4171 len = 2; CHECK_SIZE();
4172 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4175 len = 10; CHECK_SIZE();
4176 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4177 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4180 total_done += 2; CHECK_SIZE();
4181 *curpos++ = '0'+(lt->tm_hour / 10);
4182 *curpos++ = '0'+(lt->tm_hour % 10);
4185 total_done += 2; CHECK_SIZE();
4191 *curpos++ = '0'+(tmp / 10);
4192 *curpos++ = '0'+(tmp % 10);
4195 len = 3; CHECK_SIZE();
4196 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4199 len = 2; CHECK_SIZE();
4200 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4203 len = 2; CHECK_SIZE();
4209 snprintf(curpos, buflen - total_done, "%2d", tmp);
4212 total_done += 2; CHECK_SIZE();
4213 tmp = lt->tm_mon + 1;
4214 *curpos++ = '0'+(tmp / 10);
4215 *curpos++ = '0'+(tmp % 10);
4218 total_done += 2; CHECK_SIZE();
4219 *curpos++ = '0'+(lt->tm_min / 10);
4220 *curpos++ = '0'+(lt->tm_min % 10);
4223 len = 1; CHECK_SIZE();
4227 if (lt->tm_hour >= 12) {
4228 len = s_pm_up_len; CHECK_SIZE();
4229 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4231 len = s_am_up_len; CHECK_SIZE();
4232 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4236 if (lt->tm_hour >= 12) {
4237 len = s_pm_low_len; CHECK_SIZE();
4238 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4240 len = s_am_low_len; CHECK_SIZE();
4241 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4246 strftime(subbuf, 64, "%I:%M:%S %p", lt);
4248 strftime(subbuf, 64, "%r", lt);
4250 len = strlen(subbuf); CHECK_SIZE();
4251 strncpy2(curpos, subbuf, buflen - total_done);
4254 total_done += 5; CHECK_SIZE();
4255 *curpos++ = '0'+(lt->tm_hour / 10);
4256 *curpos++ = '0'+(lt->tm_hour % 10);
4258 *curpos++ = '0'+(lt->tm_min / 10);
4259 *curpos++ = '0'+(lt->tm_min % 10);
4262 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
4263 len = strlen(subbuf); CHECK_SIZE();
4264 strncpy2(curpos, subbuf, buflen - total_done);
4267 total_done += 2; CHECK_SIZE();
4268 *curpos++ = '0'+(lt->tm_sec / 10);
4269 *curpos++ = '0'+(lt->tm_sec % 10);
4272 len = 1; CHECK_SIZE();
4276 total_done += 8; CHECK_SIZE();
4277 *curpos++ = '0'+(lt->tm_hour / 10);
4278 *curpos++ = '0'+(lt->tm_hour % 10);
4280 *curpos++ = '0'+(lt->tm_min / 10);
4281 *curpos++ = '0'+(lt->tm_min % 10);
4283 *curpos++ = '0'+(lt->tm_sec / 10);
4284 *curpos++ = '0'+(lt->tm_sec % 10);
4287 len = 1; CHECK_SIZE();
4288 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
4291 len = 1; CHECK_SIZE();
4292 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
4295 strftime(subbuf, 64, "%x", lt);
4296 len = strlen(subbuf); CHECK_SIZE();
4297 strncpy2(curpos, subbuf, buflen - total_done);
4300 strftime(subbuf, 64, "%X", lt);
4301 len = strlen(subbuf); CHECK_SIZE();
4302 strncpy2(curpos, subbuf, buflen - total_done);
4305 total_done += 2; CHECK_SIZE();
4306 tmp = lt->tm_year%100;
4307 *curpos++ = '0'+(tmp / 10);
4308 *curpos++ = '0'+(tmp % 10);
4311 len = 4; CHECK_SIZE();
4312 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
4322 /* let these complicated ones be done with the libc */
4323 snprintf(subfmt, 64, "%%%c", *format);
4324 strftime(subbuf, 64, subfmt, lt);
4325 len = strlen(subbuf); CHECK_SIZE();
4326 strncpy2(curpos, subbuf, buflen - total_done);
4330 /* let these complicated modifiers be done with the libc */
4331 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
4332 strftime(subbuf, 64, subfmt, lt);
4333 len = strlen(subbuf); CHECK_SIZE();
4334 strncpy2(curpos, subbuf, buflen - total_done);
4338 g_warning("format error (%c)", *format);
4345 int len = 1; CHECK_SIZE();
4346 *curpos++ = *format++;
4354 #define WEXITSTATUS(x) (x)
4357 GMutex *cm_mutex_new(void) {
4358 #if GLIB_CHECK_VERSION(2,32,0)
4359 GMutex *m = g_new0(GMutex, 1);
4363 return g_mutex_new();
4367 void cm_mutex_free(GMutex *mutex) {
4368 #if GLIB_CHECK_VERSION(2,32,0)
4369 g_mutex_clear(mutex);
4372 g_mutex_free(mutex);
4376 static gchar *canonical_list_to_file(GSList *list)
4378 GString *result = g_string_new(NULL);
4379 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
4384 result = g_string_append(result, G_DIR_SEPARATOR_S);
4386 if (pathlist->data) {
4387 const gchar *root = (gchar *)pathlist->data;
4388 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
4390 /* drive - don't prepend dir separator */
4392 result = g_string_append(result, G_DIR_SEPARATOR_S);
4397 for (cur = pathlist; cur; cur = cur->next) {
4398 result = g_string_append(result, (gchar *)cur->data);
4400 result = g_string_append(result, G_DIR_SEPARATOR_S);
4402 g_slist_free(pathlist);
4405 g_string_free(result, FALSE);
4410 static GSList *cm_split_path(const gchar *filename, int depth)
4413 GSList *canonical_parts = NULL;
4417 gboolean follow_symlinks = TRUE;
4424 errno = EINVAL; /* can't happen, no symlink handling */
4429 if (!g_path_is_absolute(filename)) {
4434 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
4436 for (i = 0; path_parts[i] != NULL; i++) {
4437 if (!strcmp(path_parts[i], ""))
4439 if (!strcmp(path_parts[i], "."))
4441 else if (!strcmp(path_parts[i], "..")) {
4446 else /* Remove the last inserted element */
4448 g_slist_delete_link(canonical_parts,
4453 canonical_parts = g_slist_prepend(canonical_parts,
4454 g_strdup(path_parts[i]));
4456 tmp_path = canonical_list_to_file(canonical_parts);
4458 if(g_stat(tmp_path, &st) < 0) {
4459 if (errno == ENOENT) {
4462 follow_symlinks = FALSE;
4467 slist_free_strings_full(canonical_parts);
4468 g_strfreev(path_parts);
4474 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
4475 GError *error = NULL;
4476 gchar *target = g_file_read_link(tmp_path, &error);
4478 if (!g_path_is_absolute(target)) {
4479 /* remove the last inserted element */
4481 g_slist_delete_link(canonical_parts,
4483 /* add the target */
4484 canonical_parts = g_slist_prepend(canonical_parts,
4488 /* and get the new target */
4489 target = canonical_list_to_file(canonical_parts);
4492 /* restart from absolute target */
4493 slist_free_strings_full(canonical_parts);
4494 canonical_parts = NULL;
4496 canonical_parts = cm_split_path(target, depth + 1);
4498 g_error_free(error);
4499 if (canonical_parts == NULL) {
4501 g_strfreev(path_parts);
4510 g_strfreev(path_parts);
4511 return canonical_parts;
4515 * Canonicalize a filename, resolving symlinks along the way.
4516 * Returns a negative errno in case of error.
4518 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
4519 GSList *canonical_parts;
4520 gboolean is_absolute;
4522 if (filename == NULL)
4524 if (canonical_name == NULL)
4526 *canonical_name = NULL;
4528 is_absolute = g_path_is_absolute(filename);
4530 /* Always work on absolute filenames. */
4531 gchar *cur = g_get_current_dir();
4532 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
4535 canonical_parts = cm_split_path(absolute_filename, 0);
4536 g_free(absolute_filename);
4539 canonical_parts = cm_split_path(filename, 0);
4541 if (canonical_parts == NULL)
4544 *canonical_name = canonical_list_to_file(canonical_parts);
4545 slist_free_strings_full(canonical_parts);
4549 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
4550 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
4552 gchar *tmp = g_base64_decode(text, out_len);
4553 gchar *out = g_strndup(tmp, *out_len);
4557 if (strlen(out) != *out_len) {
4558 g_warning ("strlen(out) %"G_GSIZE_FORMAT" != *out_len %"G_GSIZE_FORMAT, strlen(out), *out_len);
4564 #if !GLIB_CHECK_VERSION(2, 30, 0)
4567 * @str: a UTF-8 encoded string
4568 * @start_pos: a character offset within @str
4569 * @end_pos: another character offset within @str
4571 * Copies a substring out of a UTF-8 encoded string.
4572 * The substring will contain @end_pos - @start_pos
4575 * Returns: a newly allocated copy of the requested
4576 * substring. Free with g_free() when no longer needed.
4581 g_utf8_substring (const gchar *str,
4585 gchar *start, *end, *out;
4587 start = g_utf8_offset_to_pointer (str, start_pos);
4588 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
4590 out = g_malloc (end - start + 1);
4591 memcpy (out, start, end - start);
4592 out[end - start] = 0;
4598 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
4599 * It is up to the caller to make sure there is at least count bytes
4600 * available at buf. */
4602 get_random_bytes(void *buf, size_t count)
4604 /* Open our prng source. */
4605 #if defined G_OS_WIN32
4608 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
4609 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
4610 debug_print("Could not acquire a CSP handle.\n");
4617 rnd = open("/dev/urandom", O_RDONLY);
4619 FILE_OP_ERROR("/dev/urandom", "open");
4620 debug_print("Could not open /dev/urandom.\n");
4625 /* Read data from the source into buf. */
4626 #if defined G_OS_WIN32
4627 if (!CryptGenRandom(rnd, count, buf)) {
4628 debug_print("Could not read %"G_GSIZE_FORMAT" random bytes.\n", count);
4629 CryptReleaseContext(rnd, 0);
4633 ret = read(rnd, buf, count);
4635 FILE_OP_ERROR("/dev/urandom", "read");
4636 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
4642 /* Close the prng source. */
4643 #if defined G_OS_WIN32
4644 CryptReleaseContext(rnd, 0);
4652 /* returns FALSE if parsing failed, otherwise returns TRUE and sets *server, *port
4653 and eventually *fp from filename (if not NULL, they must be free'd by caller after
4655 filenames we expect: 'host.name.port.cert' or 'host.name.port.f:i:n:g:e:r:p:r:i:n:t.cert' */
4656 gboolean get_serverportfp_from_filename(const gchar *str, gchar **server, gchar **port, gchar **fp)
4658 const gchar *pos, *dotport_pos = NULL, *dotcert_pos = NULL, *dotfp_pos = NULL;
4660 g_return_val_if_fail(str != NULL, FALSE);
4662 pos = str + strlen(str) - 1;
4663 while ((pos > str) && !dotport_pos) {
4666 /* match the .cert suffix */
4667 if (strcmp(pos, ".cert") == 0) {
4672 /* match an eventual fingerprint */
4673 /* or the port number */
4674 if (strncmp(pos + 3, ":", 1) == 0) {
4680 /* match the port number */
4687 if (!dotport_pos || !dotcert_pos) {
4688 g_warning("could not parse filename %s", str);
4693 *server = g_strndup(str, dotport_pos - str);
4696 *port = g_strndup(dotport_pos + 1, dotfp_pos - dotport_pos - 1);
4698 *fp = g_strndup(dotfp_pos + 1, dotcert_pos - dotfp_pos - 1);
4701 *port = g_strndup(dotport_pos + 1, dotcert_pos - dotport_pos - 1);
4706 debug_print("filename='%s' => server='%s' port='%s' fp='%s'\n",
4708 (server ? *server : "(n/a)"),
4709 (port ? *port : "(n/a)"),
4710 (fp ? *fp : "(n/a)"));
4712 if (!(server && *server) || !(port && *port))
4719 gchar *win32_debug_log_path(void)
4721 return g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S,
4722 "claws-win32.log", NULL);