2 * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2016 Hiroyuki Yamamoto & The Claws Mail Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 * The code of the g_utf8_substring function below is owned by
19 * Matthias Clasen <matthiasc@src.gnome.org>/<mclasen@redhat.com>
20 * and is got from GLIB 2.30: https://git.gnome.org/browse/glib/commit/
21 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
23 * GLib 2.30 is licensed under GPL v2 or later and:
24 * Copyright (C) 1999 Tom Tromey
25 * Copyright (C) 2000 Red Hat, Inc.
27 * https://git.gnome.org/browse/glib/tree/glib/gutf8.c
28 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
33 #include "claws-features.h"
41 #include <glib/gi18n.h>
51 #include <sys/param.h>
53 #include <sys/socket.h>
56 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
64 #include <sys/types.h>
66 # include <sys/wait.h>
73 #include <sys/utsname.h>
89 #include "file-utils.h"
93 static gboolean debug_mode = FALSE;
95 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
97 #if GLIB_CHECK_VERSION(2, 34, 0)
98 return g_slist_copy_deep(list, func, NULL);
100 GSList *res = g_slist_copy(list);
103 walk->data = func(walk->data, NULL);
110 void list_free_strings_full(GList *list)
112 g_list_free_full(list, (GDestroyNotify)g_free);
115 void slist_free_strings_full(GSList *list)
117 g_slist_free_full(list, (GDestroyNotify)g_free);
120 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
125 void hash_free_strings(GHashTable *table)
127 g_hash_table_foreach(table, hash_free_strings_func, NULL);
130 gint str_case_equal(gconstpointer v, gconstpointer v2)
132 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
135 guint str_case_hash(gconstpointer key)
137 const gchar *p = key;
141 h = g_ascii_tolower(h);
142 for (p += 1; *p != '\0'; p++)
143 h = (h << 5) - h + g_ascii_tolower(*p);
149 gint to_number(const gchar *nstr)
151 register const gchar *p;
153 if (*nstr == '\0') return -1;
155 for (p = nstr; *p != '\0'; p++)
156 if (!g_ascii_isdigit(*p)) return -1;
161 /* convert integer into string,
162 nstr must be not lower than 11 characters length */
163 gchar *itos_buf(gchar *nstr, gint n)
165 g_snprintf(nstr, 11, "%d", n);
169 /* convert integer into string */
172 static gchar nstr[11];
174 return itos_buf(nstr, n);
177 #define divide(num,divisor,i,d) \
179 i = num >> divisor; \
180 d = num & ((1<<divisor)-1); \
181 d = (d*100) >> divisor; \
186 * \brief Convert a given size in bytes in a human-readable string
188 * \param size The size expressed in bytes to convert in string
189 * \return The string that respresents the size in an human-readable way
191 gchar *to_human_readable(goffset size)
193 static gchar str[14];
194 static gchar *b_format = NULL, *kb_format = NULL,
195 *mb_format = NULL, *gb_format = NULL;
196 register int t = 0, r = 0;
197 if (b_format == NULL) {
199 kb_format = _("%d.%02dKB");
200 mb_format = _("%d.%02dMB");
201 gb_format = _("%.2fGB");
204 if (size < (goffset)1024) {
205 g_snprintf(str, sizeof(str), b_format, (gint)size);
207 } else if (size >> 10 < (goffset)1024) {
208 divide(size, 10, t, r);
209 g_snprintf(str, sizeof(str), kb_format, t, r);
211 } else if (size >> 20 < (goffset)1024) {
212 divide(size, 20, t, r);
213 g_snprintf(str, sizeof(str), mb_format, t, r);
216 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
222 gint path_cmp(const gchar *s1, const gchar *s2)
227 gchar *s1buf, *s2buf;
230 if (s1 == NULL || s2 == NULL) return -1;
231 if (*s1 == '\0' || *s2 == '\0') return -1;
234 s1buf = g_strdup (s1);
235 s2buf = g_strdup (s2);
236 subst_char (s1buf, '/', G_DIR_SEPARATOR);
237 subst_char (s2buf, '/', G_DIR_SEPARATOR);
240 #endif /* !G_OS_WIN32 */
245 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
246 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
248 rc = strncmp(s1, s2, MAX(len1, len2));
252 #endif /* !G_OS_WIN32 */
256 /* remove trailing return code */
257 gchar *strretchomp(gchar *str)
261 if (!*str) return str;
263 for (s = str + strlen(str) - 1;
264 s >= str && (*s == '\n' || *s == '\r');
271 /* remove trailing character */
272 gchar *strtailchomp(gchar *str, gchar tail_char)
276 if (!*str) return str;
277 if (tail_char == '\0') return str;
279 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
285 /* remove CR (carriage return) */
286 gchar *strcrchomp(gchar *str)
290 if (!*str) return str;
292 s = str + strlen(str) - 1;
293 if (*s == '\n' && s > str && *(s - 1) == '\r') {
301 /* Similar to `strstr' but this function ignores the case of both strings. */
302 gchar *strcasestr(const gchar *haystack, const gchar *needle)
304 size_t haystack_len = strlen(haystack);
306 return strncasestr(haystack, haystack_len, needle);
309 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
311 register size_t needle_len;
313 needle_len = strlen(needle);
315 if (haystack_len < needle_len || needle_len == 0)
318 while (haystack_len >= needle_len) {
319 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
320 return (gchar *)haystack;
330 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
331 gconstpointer needle, size_t needlelen)
333 const gchar *haystack_ = (const gchar *)haystack;
334 const gchar *needle_ = (const gchar *)needle;
335 const gchar *haystack_cur = (const gchar *)haystack;
336 size_t haystack_left = haystacklen;
339 return memchr(haystack_, *needle_, haystacklen);
341 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
343 if (haystacklen - (haystack_cur - haystack_) < needlelen)
345 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
346 return (gpointer)haystack_cur;
349 haystack_left = haystacklen - (haystack_cur - haystack_);
356 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
357 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
359 register const gchar *s = src;
360 register gchar *d = dest;
370 /* Examine if next block is non-ASCII string */
371 gboolean is_next_nonascii(const gchar *s)
375 /* skip head space */
376 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
378 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
379 if (*(guchar *)p > 127 || *(guchar *)p < 32)
386 gint get_next_word_len(const gchar *s)
390 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
396 static void trim_subject_for_compare(gchar *str)
400 eliminate_parenthesis(str, '[', ']');
401 eliminate_parenthesis(str, '(', ')');
404 srcp = str + subject_get_prefix_length(str);
406 memmove(str, srcp, strlen(srcp) + 1);
409 static void trim_subject_for_sort(gchar *str)
415 srcp = str + subject_get_prefix_length(str);
417 memmove(str, srcp, strlen(srcp) + 1);
420 /* compare subjects */
421 gint subject_compare(const gchar *s1, const gchar *s2)
425 if (!s1 || !s2) return -1;
426 if (!*s1 || !*s2) return -1;
428 Xstrdup_a(str1, s1, return -1);
429 Xstrdup_a(str2, s2, return -1);
431 trim_subject_for_compare(str1);
432 trim_subject_for_compare(str2);
434 if (!*str1 || !*str2) return -1;
436 return strcmp(str1, str2);
439 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
443 if (!s1 || !s2) return -1;
445 Xstrdup_a(str1, s1, return -1);
446 Xstrdup_a(str2, s2, return -1);
448 trim_subject_for_sort(str1);
449 trim_subject_for_sort(str2);
451 return g_utf8_collate(str1, str2);
454 void trim_subject(gchar *str)
456 register gchar *srcp;
462 srcp = str + subject_get_prefix_length(str);
467 } else if (*srcp == '(') {
479 else if (*srcp == cl)
486 while (g_ascii_isspace(*srcp)) srcp++;
487 memmove(str, srcp, strlen(srcp) + 1);
490 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
492 register gchar *srcp, *destp;
497 while ((destp = strchr(destp, op))) {
503 else if (*srcp == cl)
509 while (g_ascii_isspace(*srcp)) srcp++;
510 memmove(destp, srcp, strlen(srcp) + 1);
514 void extract_parenthesis(gchar *str, gchar op, gchar cl)
516 register gchar *srcp, *destp;
521 while ((srcp = strchr(destp, op))) {
524 memmove(destp, srcp + 1, strlen(srcp));
529 else if (*destp == cl)
541 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
544 register gchar *srcp, *destp;
546 gboolean in_quote = FALSE;
550 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
553 memmove(destp, srcp + 1, strlen(srcp));
556 if (*destp == op && !in_quote)
558 else if (*destp == cl && !in_quote)
560 else if (*destp == quote_chr)
572 void extract_quote(gchar *str, gchar quote_chr)
576 if ((str = strchr(str, quote_chr))) {
578 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
579 memmove(p - 1, p, strlen(p) + 1);
584 memmove(str, str + 1, p - str);
589 /* Returns a newly allocated string with all quote_chr not at the beginning
590 or the end of str escaped with '\' or the given str if not required. */
591 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
593 register gchar *p, *q;
597 if (str == NULL || *str == '\0')
600 /* search for unescaped quote_chr */
605 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
609 if (!k) /* nothing to escape */
612 /* unescaped quote_chr found */
613 qstr = g_malloc(l + k + 1);
616 if (*p == quote_chr) {
621 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
630 void eliminate_address_comment(gchar *str)
632 register gchar *srcp, *destp;
637 while ((destp = strchr(destp, '"'))) {
638 if ((srcp = strchr(destp + 1, '"'))) {
643 while (g_ascii_isspace(*srcp)) srcp++;
644 memmove(destp, srcp, strlen(srcp) + 1);
654 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
660 else if (*srcp == ')')
666 while (g_ascii_isspace(*srcp)) srcp++;
667 memmove(destp, srcp, strlen(srcp) + 1);
671 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
673 gboolean in_quote = FALSE;
676 if (*str == c && !in_quote)
678 if (*str == quote_chr)
686 void extract_address(gchar *str)
688 cm_return_if_fail(str != NULL);
689 eliminate_address_comment(str);
690 if (strchr_with_skip_quote(str, '"', '<'))
691 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
695 void extract_list_id_str(gchar *str)
697 if (strchr_with_skip_quote(str, '"', '<'))
698 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
702 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
707 if (!str) return addr_list;
709 Xstrdup_a(work, str, return addr_list);
712 eliminate_address_comment(work);
715 while (workp && *workp) {
718 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
724 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
725 extract_parenthesis_with_skip_quote
726 (workp, '"', '<', '>');
730 addr_list = g_slist_append(addr_list, g_strdup(workp));
738 GSList *address_list_append(GSList *addr_list, const gchar *str)
740 return address_list_append_real(addr_list, str, TRUE);
743 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
745 return address_list_append_real(addr_list, str, FALSE);
748 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
752 if (!str) return msgid_list;
755 while (strp && *strp) {
756 const gchar *start, *end;
759 if ((start = strchr(strp, '<')) != NULL) {
760 end = strchr(start + 1, '>');
765 msgid = g_strndup(start + 1, end - start - 1);
768 msgid_list = g_slist_prepend(msgid_list, msgid);
778 GSList *references_list_append(GSList *msgid_list, const gchar *str)
782 list = references_list_prepend(NULL, str);
783 list = g_slist_reverse(list);
784 msgid_list = g_slist_concat(msgid_list, list);
789 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
794 if (!str) return group_list;
796 Xstrdup_a(work, str, return group_list);
800 while (workp && *workp) {
803 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
811 group_list = g_slist_append(group_list,
820 GList *add_history(GList *list, const gchar *str)
825 cm_return_val_if_fail(str != NULL, list);
827 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)g_strcmp0);
830 list = g_list_remove(list, old->data);
832 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
835 last = g_list_last(list);
838 list = g_list_remove(list, last->data);
843 list = g_list_prepend(list, g_strdup(str));
848 void remove_return(gchar *str)
850 register gchar *p = str;
853 if (*p == '\n' || *p == '\r')
854 memmove(p, p + 1, strlen(p));
860 void remove_space(gchar *str)
862 register gchar *p = str;
867 while (g_ascii_isspace(*(p + spc)))
870 memmove(p, p + spc, strlen(p + spc) + 1);
876 void unfold_line(gchar *str)
882 ch = str; /* iterator for source string */
885 c = g_utf8_get_char_validated(ch, -1);
887 if (c == (gunichar)-1 || c == (gunichar)-2) {
888 /* non-unicode byte, move past it */
893 len = g_unichar_to_utf8(c, NULL);
895 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
896 g_unichar_isspace(c)) {
897 /* replace anything bad or whitespacey with a single space */
901 /* move rest of the string forwards, since we just replaced
902 * a multi-byte sequence with one byte */
903 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
906 /* A valid unicode character, copy it. */
912 void subst_char(gchar *str, gchar orig, gchar subst)
914 register gchar *p = str;
923 void subst_chars(gchar *str, gchar *orig, gchar subst)
925 register gchar *p = str;
928 if (strchr(orig, *p) != NULL)
934 void subst_for_filename(gchar *str)
939 subst_chars(str, "\t\r\n\\/*?:", '_');
941 subst_chars(str, "\t\r\n\\/*", '_');
945 void subst_for_shellsafe_filename(gchar *str)
949 subst_for_filename(str);
950 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
953 gboolean is_ascii_str(const gchar *str)
955 const guchar *p = (const guchar *)str;
958 if (*p != '\t' && *p != ' ' &&
959 *p != '\r' && *p != '\n' &&
960 (*p < 32 || *p >= 127))
968 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
970 gchar * position = NULL;
971 gchar * tmp_pos = NULL;
974 if (str == NULL || quote_chars == NULL)
977 for (i = 0; i < strlen(quote_chars); i++) {
978 tmp_pos = strrchr (str, quote_chars[i]);
980 || (tmp_pos != NULL && position <= tmp_pos) )
986 gint get_quote_level(const gchar *str, const gchar *quote_chars)
988 const gchar *first_pos;
989 const gchar *last_pos;
990 const gchar *p = str;
991 gint quote_level = -1;
993 /* speed up line processing by only searching to the last '>' */
994 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
995 /* skip a line if it contains a '<' before the initial '>' */
996 if (memchr(str, '<', first_pos - str) != NULL)
998 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1002 while (p <= last_pos) {
1003 while (p < last_pos) {
1004 if (g_ascii_isspace(*p))
1010 if (strchr(quote_chars, *p))
1012 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1013 /* any characters are allowed except '-','<' and space */
1014 while (*p != '-' && *p != '<'
1015 && !strchr(quote_chars, *p)
1016 && !g_ascii_isspace(*p)
1019 if (strchr(quote_chars, *p))
1031 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1033 const gchar *p = str, *q;
1034 gint cur_line = 0, len;
1036 while ((q = strchr(p, '\n')) != NULL) {
1038 if (len > max_chars) {
1048 if (len > max_chars) {
1057 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1059 gchar * position = NULL;
1060 gchar * tmp_pos = NULL;
1063 if (str == NULL || quote_chars == NULL)
1066 for (i = 0; i < strlen(quote_chars); i++) {
1067 tmp_pos = strchr (str, quote_chars[i]);
1069 || (tmp_pos != NULL && position >= tmp_pos) )
1075 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1077 register guint haystack_len, needle_len;
1078 gboolean in_squote = FALSE, in_dquote = FALSE;
1080 haystack_len = strlen(haystack);
1081 needle_len = strlen(needle);
1083 if (haystack_len < needle_len || needle_len == 0)
1086 while (haystack_len >= needle_len) {
1087 if (!in_squote && !in_dquote &&
1088 !strncmp(haystack, needle, needle_len))
1089 return (gchar *)haystack;
1091 /* 'foo"bar"' -> foo"bar"
1092 "foo'bar'" -> foo'bar' */
1093 if (*haystack == '\'') {
1096 else if (!in_dquote)
1098 } else if (*haystack == '\"') {
1101 else if (!in_squote)
1103 } else if (*haystack == '\\') {
1115 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1118 GSList *string_list = NULL, *slist;
1119 gchar **str_array, *s, *new_str;
1120 guint i, n = 1, len;
1122 cm_return_val_if_fail(str != NULL, NULL);
1123 cm_return_val_if_fail(delim != NULL, NULL);
1126 max_tokens = G_MAXINT;
1128 s = strstr_with_skip_quote(str, delim);
1130 guint delimiter_len = strlen(delim);
1134 new_str = g_strndup(str, len);
1136 if (new_str[0] == '\'' || new_str[0] == '\"') {
1137 if (new_str[len - 1] == new_str[0]) {
1138 new_str[len - 1] = '\0';
1139 memmove(new_str, new_str + 1, len - 1);
1142 string_list = g_slist_prepend(string_list, new_str);
1144 str = s + delimiter_len;
1145 s = strstr_with_skip_quote(str, delim);
1146 } while (--max_tokens && s);
1150 new_str = g_strdup(str);
1151 if (new_str[0] == '\'' || new_str[0] == '\"') {
1153 if (new_str[len - 1] == new_str[0]) {
1154 new_str[len - 1] = '\0';
1155 memmove(new_str, new_str + 1, len - 1);
1158 string_list = g_slist_prepend(string_list, new_str);
1162 str_array = g_new(gchar*, n);
1166 str_array[i--] = NULL;
1167 for (slist = string_list; slist; slist = slist->next)
1168 str_array[i--] = slist->data;
1170 g_slist_free(string_list);
1175 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1177 gchar *abbrev_group;
1179 const gchar *p = group;
1182 cm_return_val_if_fail(group != NULL, NULL);
1184 last = group + strlen(group);
1185 abbrev_group = ap = g_malloc(strlen(group) + 1);
1190 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1192 while (*p != '.') p++;
1195 return abbrev_group;
1200 return abbrev_group;
1203 gchar *trim_string(const gchar *str, gint len)
1205 const gchar *p = str;
1210 if (!str) return NULL;
1211 if (strlen(str) <= len)
1212 return g_strdup(str);
1213 if (g_utf8_validate(str, -1, NULL) == FALSE)
1214 return g_strdup(str);
1216 while (*p != '\0') {
1217 mb_len = g_utf8_skip[*(guchar *)p];
1220 else if (new_len + mb_len > len)
1227 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1228 return g_strconcat(new_str, "...", NULL);
1231 GList *uri_list_extract_filenames(const gchar *uri_list)
1233 GList *result = NULL;
1235 gchar *escaped_utf8uri;
1241 while (g_ascii_isspace(*p)) p++;
1242 if (!strncmp(p, "file:", 5)) {
1245 while (*q && *q != '\n' && *q != '\r') q++;
1248 gchar *file, *locale_file = NULL;
1250 while (q > p && g_ascii_isspace(*q))
1252 Xalloca(escaped_utf8uri, q - p + 2,
1254 Xalloca(file, q - p + 2,
1257 strncpy(escaped_utf8uri, p, q - p + 1);
1258 escaped_utf8uri[q - p + 1] = '\0';
1259 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1261 * g_filename_from_uri() rejects escaped/locale encoded uri
1262 * string which come from Nautilus.
1265 if (g_utf8_validate(file, -1, NULL))
1267 = conv_codeset_strdup(
1270 conv_get_locale_charset_str());
1272 locale_file = g_strdup(file + 5);
1274 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1276 result = g_list_append(result, locale_file);
1280 p = strchr(p, '\n');
1287 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1290 static gint axtoi(const gchar *hexstr)
1292 gint hi, lo, result;
1295 if ('0' <= hi && hi <= '9') {
1298 if ('a' <= hi && hi <= 'f') {
1301 if ('A' <= hi && hi <= 'F') {
1306 if ('0' <= lo && lo <= '9') {
1309 if ('a' <= lo && lo <= 'f') {
1312 if ('A' <= lo && lo <= 'F') {
1315 result = lo + (16 * hi);
1319 gboolean is_uri_string(const gchar *str)
1321 while (str && *str && g_ascii_isspace(*str))
1323 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1324 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1325 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1326 g_ascii_strncasecmp(str, "www.", 4) == 0);
1329 gchar *get_uri_path(const gchar *uri)
1331 while (uri && *uri && g_ascii_isspace(*uri))
1333 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1334 return (gchar *)(uri + 7);
1335 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1336 return (gchar *)(uri + 8);
1337 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1338 return (gchar *)(uri + 6);
1340 return (gchar *)uri;
1343 gint get_uri_len(const gchar *str)
1347 if (is_uri_string(str)) {
1348 for (p = str; *p != '\0'; p++) {
1349 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1358 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1359 * plusses, and escape characters are used)
1361 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1363 gchar *dec = decoded_uri;
1364 const gchar *enc = encoded_uri;
1369 if (isxdigit((guchar)enc[0]) &&
1370 isxdigit((guchar)enc[1])) {
1376 if (with_plus && *enc == '+')
1388 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1390 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1393 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1395 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1396 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1400 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1401 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1405 const gchar *forbidden_uris[] = { ".gnupg/",
1411 gint num_attach = 0;
1412 gchar **my_att = NULL;
1414 Xstrdup_a(tmp_mailto, mailto, return -1);
1416 if (!strncmp(tmp_mailto, "mailto:", 7))
1419 p = strchr(tmp_mailto, '?');
1426 *to = decode_uri_gdup(tmp_mailto);
1428 my_att = g_malloc(sizeof(char *));
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);
1460 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1462 *cc = decode_uri_gdup(value);
1464 gchar *tmp = decode_uri_gdup(value);
1465 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1469 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1471 *bcc = decode_uri_gdup(value);
1473 gchar *tmp = decode_uri_gdup(value);
1474 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1478 } else if (subject && !*subject &&
1479 !g_ascii_strcasecmp(field, "subject")) {
1480 *subject = decode_uri_gdup(value);
1481 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1482 *body = decode_uri_gdup(value);
1483 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1484 gchar *tmp = decode_uri_gdup(value);
1485 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1486 g_warning("couldn't set insert file '%s' in body", value);
1489 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1491 gchar *tmp = decode_uri_gdup(value);
1492 for (; forbidden_uris[i]; i++) {
1493 if (strstr(tmp, forbidden_uris[i])) {
1494 g_print("Refusing to attach '%s', potential private data leak\n",
1501 /* attach is correct */
1503 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1504 my_att[num_attach-1] = tmp;
1505 my_att[num_attach] = NULL;
1507 } else if (inreplyto && !*inreplyto &&
1508 !g_ascii_strcasecmp(field, "in-reply-to")) {
1509 *inreplyto = decode_uri_gdup(value);
1520 #include <windows.h>
1521 #ifndef CSIDL_APPDATA
1522 #define CSIDL_APPDATA 0x001a
1524 #ifndef CSIDL_LOCAL_APPDATA
1525 #define CSIDL_LOCAL_APPDATA 0x001c
1527 #ifndef CSIDL_FLAG_CREATE
1528 #define CSIDL_FLAG_CREATE 0x8000
1530 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1534 w32_strerror (int w32_errno)
1536 static char strerr[256];
1537 int ec = (int)GetLastError ();
1541 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1542 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1543 strerr, DIM (strerr)-1, NULL);
1547 static __inline__ void *
1548 dlopen (const char * name, int flag)
1550 void * hd = LoadLibrary (name);
1554 static __inline__ void *
1555 dlsym (void * hd, const char * sym)
1559 void * fnc = GetProcAddress (hd, sym);
1568 static __inline__ const char *
1571 return w32_strerror (0);
1575 static __inline__ int
1587 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1589 static int initialized;
1590 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1594 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1600 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1602 handle = dlopen (dllnames[i], RTLD_LAZY);
1605 func = dlsym (handle, "SHGetFolderPathW");
1616 return func (a,b,c,d,e);
1621 /* Returns a static string with the directroy from which the module
1622 has been loaded. Returns an empty string on error. */
1623 static char *w32_get_module_dir(void)
1625 static char *moddir;
1628 char name[MAX_PATH+10];
1631 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1634 p = strrchr (name, '\\');
1640 moddir = g_strdup (name);
1644 #endif /* G_OS_WIN32 */
1646 /* Return a static string with the locale dir. */
1647 const gchar *get_locale_dir(void)
1649 static gchar *loc_dir;
1653 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1654 "\\share\\locale", NULL);
1657 loc_dir = LOCALEDIR;
1663 const gchar *get_home_dir(void)
1666 static char home_dir_utf16[MAX_PATH] = "";
1667 static gchar *home_dir_utf8 = NULL;
1668 if (home_dir_utf16[0] == '\0') {
1669 if (w32_shgetfolderpath
1670 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1671 NULL, 0, home_dir_utf16) < 0)
1672 strcpy (home_dir_utf16, "C:\\Claws Mail");
1673 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1675 return home_dir_utf8;
1677 static const gchar *homeenv = NULL;
1682 if (!homeenv && g_getenv("HOME") != NULL)
1683 homeenv = g_strdup(g_getenv("HOME"));
1685 homeenv = g_get_home_dir();
1691 static gchar *claws_rc_dir = NULL;
1692 static gboolean rc_dir_alt = FALSE;
1693 const gchar *get_rc_dir(void)
1696 if (!claws_rc_dir) {
1697 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1699 debug_print("using default rc_dir %s\n", claws_rc_dir);
1701 return claws_rc_dir;
1704 void set_rc_dir(const gchar *dir)
1706 gchar *canonical_dir;
1707 if (claws_rc_dir != NULL) {
1708 g_print("Error: rc_dir already set\n");
1710 int err = cm_canonicalize_filename(dir, &canonical_dir);
1714 g_print("Error looking for %s: %d(%s)\n",
1715 dir, -err, g_strerror(-err));
1720 claws_rc_dir = canonical_dir;
1722 len = strlen(claws_rc_dir);
1723 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1724 claws_rc_dir[len - 1] = '\0';
1726 debug_print("set rc_dir to %s\n", claws_rc_dir);
1727 if (!is_dir_exist(claws_rc_dir)) {
1728 if (make_dir_hier(claws_rc_dir) != 0) {
1729 g_print("Error: can't create %s\n",
1737 gboolean rc_dir_is_alt(void) {
1741 const gchar *get_mail_base_dir(void)
1743 return get_home_dir();
1746 const gchar *get_news_cache_dir(void)
1748 static gchar *news_cache_dir = NULL;
1749 if (!news_cache_dir)
1750 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1751 NEWS_CACHE_DIR, NULL);
1753 return news_cache_dir;
1756 const gchar *get_imap_cache_dir(void)
1758 static gchar *imap_cache_dir = NULL;
1760 if (!imap_cache_dir)
1761 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1762 IMAP_CACHE_DIR, NULL);
1764 return imap_cache_dir;
1767 const gchar *get_mime_tmp_dir(void)
1769 static gchar *mime_tmp_dir = NULL;
1772 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1773 MIME_TMP_DIR, NULL);
1775 return mime_tmp_dir;
1778 const gchar *get_template_dir(void)
1780 static gchar *template_dir = NULL;
1783 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1784 TEMPLATE_DIR, NULL);
1786 return template_dir;
1790 const gchar *w32_get_cert_file(void)
1792 const gchar *cert_file = NULL;
1794 cert_file = g_strconcat(w32_get_module_dir(),
1795 "\\share\\claws-mail\\",
1796 "ca-certificates.crt",
1802 /* Return the filepath of the claws-mail.desktop file */
1803 const gchar *get_desktop_file(void)
1805 #ifdef DESKTOPFILEPATH
1806 return DESKTOPFILEPATH;
1812 /* Return the default directory for Plugins. */
1813 const gchar *get_plugin_dir(void)
1816 static gchar *plugin_dir = NULL;
1819 plugin_dir = g_strconcat(w32_get_module_dir(),
1820 "\\lib\\claws-mail\\plugins\\",
1824 if (is_dir_exist(PLUGINDIR))
1827 static gchar *plugin_dir = NULL;
1829 plugin_dir = g_strconcat(get_rc_dir(),
1830 G_DIR_SEPARATOR_S, "plugins",
1831 G_DIR_SEPARATOR_S, NULL);
1839 /* Return the default directory for Themes. */
1840 const gchar *w32_get_themes_dir(void)
1842 static gchar *themes_dir = NULL;
1845 themes_dir = g_strconcat(w32_get_module_dir(),
1846 "\\share\\claws-mail\\themes",
1852 const gchar *get_tmp_dir(void)
1854 static gchar *tmp_dir = NULL;
1857 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1863 gchar *get_tmp_file(void)
1866 static guint32 id = 0;
1868 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1869 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1874 const gchar *get_domain_name(void)
1877 static gchar *domain_name = NULL;
1878 struct addrinfo hints, *res;
1883 if (gethostname(hostname, sizeof(hostname)) != 0) {
1884 perror("gethostname");
1885 domain_name = "localhost";
1887 memset(&hints, 0, sizeof(struct addrinfo));
1888 hints.ai_family = AF_UNSPEC;
1889 hints.ai_socktype = 0;
1890 hints.ai_flags = AI_CANONNAME;
1891 hints.ai_protocol = 0;
1893 s = getaddrinfo(hostname, NULL, &hints, &res);
1895 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1896 domain_name = g_strdup(hostname);
1898 domain_name = g_strdup(res->ai_canonname);
1902 debug_print("domain name = %s\n", domain_name);
1911 /* Tells whether the given host address string is a valid representation of a
1912 * numerical IP (v4 or, if supported, v6) address.
1914 gboolean is_numeric_host_address(const gchar *hostaddress)
1916 struct addrinfo hints, *res;
1919 /* See what getaddrinfo makes of the string when told that it is a
1920 * numeric IP address representation. */
1921 memset(&hints, 0, sizeof(struct addrinfo));
1922 hints.ai_family = AF_UNSPEC;
1923 hints.ai_socktype = 0;
1924 hints.ai_flags = AI_NUMERICHOST;
1925 hints.ai_protocol = 0;
1927 err = getaddrinfo(hostaddress, NULL, &hints, &res);
1934 off_t get_file_size(const gchar *file)
1939 GError *error = NULL;
1942 f = g_file_new_for_path(file);
1943 fi = g_file_query_info(f, "standard::size",
1944 G_FILE_QUERY_INFO_NONE, NULL, &error);
1945 if (error != NULL) {
1946 debug_print("get_file_size error: %s\n", error->message);
1947 g_error_free(error);
1951 size = g_file_info_get_size(fi);
1959 if (g_stat(file, &s) < 0) {
1960 FILE_OP_ERROR(file, "stat");
1968 time_t get_file_mtime(const gchar *file)
1972 if (g_stat(file, &s) < 0) {
1973 FILE_OP_ERROR(file, "stat");
1980 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1987 if (g_stat(file, &s) < 0) {
1988 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1992 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1999 /* Test on whether FILE is a relative file name. This is
2000 * straightforward for Unix but more complex for Windows. */
2001 gboolean is_relative_filename(const gchar *file)
2006 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2007 return FALSE; /* Prefixed with a hostname - this can't
2008 * be a relative name. */
2010 if ( ((*file >= 'a' && *file <= 'z')
2011 || (*file >= 'A' && *file <= 'Z'))
2013 file += 2; /* Skip drive letter. */
2015 return !(*file == '\\' || *file == '/');
2017 return !(*file == G_DIR_SEPARATOR);
2022 gboolean is_dir_exist(const gchar *dir)
2027 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2030 gboolean is_file_entry_exist(const gchar *file)
2035 return g_file_test(file, G_FILE_TEST_EXISTS);
2038 gboolean dirent_is_regular_file(struct dirent *d)
2040 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2041 if (d->d_type == DT_REG)
2043 else if (d->d_type != DT_UNKNOWN)
2047 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2050 gint change_dir(const gchar *dir)
2052 gchar *prevdir = NULL;
2055 prevdir = g_get_current_dir();
2057 if (g_chdir(dir) < 0) {
2058 FILE_OP_ERROR(dir, "chdir");
2059 if (debug_mode) g_free(prevdir);
2061 } else if (debug_mode) {
2064 cwd = g_get_current_dir();
2065 if (strcmp(prevdir, cwd) != 0)
2066 g_print("current dir: %s\n", cwd);
2074 gint make_dir(const gchar *dir)
2076 if (g_mkdir(dir, S_IRWXU) < 0) {
2077 FILE_OP_ERROR(dir, "mkdir");
2080 if (g_chmod(dir, S_IRWXU) < 0)
2081 FILE_OP_ERROR(dir, "chmod");
2086 gint make_dir_hier(const gchar *dir)
2091 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2092 parent_dir = g_strndup(dir, p - dir);
2093 if (*parent_dir != '\0') {
2094 if (!is_dir_exist(parent_dir)) {
2095 if (make_dir(parent_dir) < 0) {
2104 if (!is_dir_exist(dir)) {
2105 if (make_dir(dir) < 0)
2112 gint remove_all_files(const gchar *dir)
2115 const gchar *file_name;
2118 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2119 g_warning("failed to open directory: %s", dir);
2123 while ((file_name = g_dir_read_name(dp)) != NULL) {
2124 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2125 if (claws_unlink(tmp) < 0)
2126 FILE_OP_ERROR(tmp, "unlink");
2135 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2138 const gchar *dir_name;
2142 if (first == last) {
2143 /* Skip all the dir reading part. */
2144 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2145 if (is_dir_exist(filename)) {
2146 /* a numbered directory with this name exists,
2147 * remove the dot-file instead */
2149 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2151 if (claws_unlink(filename) < 0) {
2152 FILE_OP_ERROR(filename, "unlink");
2160 prev_dir = g_get_current_dir();
2162 if (g_chdir(dir) < 0) {
2163 FILE_OP_ERROR(dir, "chdir");
2168 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2169 g_warning("failed to open directory: %s", dir);
2174 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2175 file_no = to_number(dir_name);
2176 if (file_no > 0 && first <= file_no && file_no <= last) {
2177 if (is_dir_exist(dir_name)) {
2178 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2179 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2180 FILE_OP_ERROR(dot_file, "unlink");
2185 if (claws_unlink(dir_name) < 0)
2186 FILE_OP_ERROR(dir_name, "unlink");
2192 if (g_chdir(prev_dir) < 0) {
2193 FILE_OP_ERROR(prev_dir, "chdir");
2203 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2206 const gchar *dir_name;
2209 GHashTable *wanted_files;
2211 GError *error = NULL;
2213 if (numberlist == NULL)
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, &error)) == NULL) {
2225 g_message("Couldn't open current directory: %s (%d).\n",
2226 error->message, error->code);
2227 g_error_free(error);
2232 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2233 for (cur = numberlist; cur != NULL; cur = cur->next) {
2234 /* numberlist->data is expected to be GINT_TO_POINTER */
2235 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2238 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2239 file_no = to_number(dir_name);
2240 if (is_dir_exist(dir_name))
2242 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2243 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2244 if (is_dir_exist(dir_name)) {
2245 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2246 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2247 FILE_OP_ERROR(dot_file, "unlink");
2252 if (claws_unlink(dir_name) < 0)
2253 FILE_OP_ERROR(dir_name, "unlink");
2258 g_hash_table_destroy(wanted_files);
2260 if (g_chdir(prev_dir) < 0) {
2261 FILE_OP_ERROR(prev_dir, "chdir");
2271 gint remove_all_numbered_files(const gchar *dir)
2273 return remove_numbered_files(dir, 0, UINT_MAX);
2276 gint remove_dir_recursive(const gchar *dir)
2280 const gchar *dir_name;
2283 if (g_stat(dir, &s) < 0) {
2284 FILE_OP_ERROR(dir, "stat");
2285 if (ENOENT == errno) return 0;
2289 if (!S_ISDIR(s.st_mode)) {
2290 if (claws_unlink(dir) < 0) {
2291 FILE_OP_ERROR(dir, "unlink");
2298 prev_dir = g_get_current_dir();
2299 /* g_print("prev_dir = %s\n", prev_dir); */
2301 if (!path_cmp(prev_dir, dir)) {
2303 if (g_chdir("..") < 0) {
2304 FILE_OP_ERROR(dir, "chdir");
2307 prev_dir = g_get_current_dir();
2310 if (g_chdir(dir) < 0) {
2311 FILE_OP_ERROR(dir, "chdir");
2316 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2317 g_warning("failed to open directory: %s", dir);
2323 /* remove all files in the directory */
2324 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2325 /* g_print("removing %s\n", dir_name); */
2327 if (is_dir_exist(dir_name)) {
2330 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2331 g_warning("can't remove directory: %s", dir_name);
2335 if (claws_unlink(dir_name) < 0)
2336 FILE_OP_ERROR(dir_name, "unlink");
2342 if (g_chdir(prev_dir) < 0) {
2343 FILE_OP_ERROR(prev_dir, "chdir");
2350 if (g_rmdir(dir) < 0) {
2351 FILE_OP_ERROR(dir, "rmdir");
2358 /* convert line endings into CRLF. If the last line doesn't end with
2359 * linebreak, add it.
2361 gchar *canonicalize_str(const gchar *str)
2367 for (p = str; *p != '\0'; ++p) {
2374 if (p == str || *(p - 1) != '\n')
2377 out = outp = g_malloc(new_len + 1);
2378 for (p = str; *p != '\0'; ++p) {
2385 if (p == str || *(p - 1) != '\n') {
2394 gchar *normalize_newlines(const gchar *str)
2399 out = outp = g_malloc(strlen(str) + 1);
2400 for (p = str; *p != '\0'; ++p) {
2402 if (*(p + 1) != '\n')
2413 gchar *get_outgoing_rfc2822_str(FILE *fp)
2415 gchar buf[BUFFSIZE];
2419 str = g_string_new(NULL);
2421 /* output header part */
2422 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2424 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2431 else if (next != ' ' && next != '\t') {
2435 if (claws_fgets(buf, sizeof(buf), fp) == NULL)
2439 g_string_append(str, buf);
2440 g_string_append(str, "\r\n");
2446 /* output body part */
2447 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2450 g_string_append_c(str, '.');
2451 g_string_append(str, buf);
2452 g_string_append(str, "\r\n");
2456 g_string_free(str, FALSE);
2462 * Create a new boundary in a way that it is very unlikely that this
2463 * will occur in the following text. It would be easy to ensure
2464 * uniqueness if everything is either quoted-printable or base64
2465 * encoded (note that conversion is allowed), but because MIME bodies
2466 * may be nested, it may happen that the same boundary has already
2469 * boundary := 0*69<bchars> bcharsnospace
2470 * bchars := bcharsnospace / " "
2471 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2472 * "+" / "_" / "," / "-" / "." /
2473 * "/" / ":" / "=" / "?"
2475 * some special characters removed because of buggy MTAs
2478 gchar *generate_mime_boundary(const gchar *prefix)
2480 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2481 "abcdefghijklmnopqrstuvwxyz"
2486 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2487 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2490 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2494 char *fgets_crlf(char *buf, int size, FILE *stream)
2496 gboolean is_cr = FALSE;
2497 gboolean last_was_cr = FALSE;
2502 while (--size > 0 && (c = getc(stream)) != EOF)
2505 is_cr = (c == '\r');
2515 last_was_cr = is_cr;
2517 if (c == EOF && cs == buf)
2525 static gint execute_async(gchar *const argv[], const gchar *working_directory)
2527 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2529 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2530 NULL, NULL, NULL, FALSE) == FALSE) {
2531 g_warning("couldn't execute command: %s", argv[0]);
2538 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
2542 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2545 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2546 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2547 g_warning("couldn't execute command: %s", argv[0]);
2551 if (WIFEXITED(status))
2552 return WEXITSTATUS(status);
2556 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
2557 G_SPAWN_SEARCH_PATH|
2558 G_SPAWN_CHILD_INHERITS_STDIN|
2559 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
2560 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2561 g_warning("couldn't execute command: %s", argv[0]);
2569 gint execute_command_line(const gchar *cmdline, gboolean async,
2570 const gchar *working_directory)
2575 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
2577 argv = strsplit_with_quote(cmdline, " ", 0);
2580 ret = execute_async(argv, working_directory);
2582 ret = execute_sync(argv, working_directory);
2589 gchar *get_command_output(const gchar *cmdline)
2591 gchar *child_stdout;
2594 cm_return_val_if_fail(cmdline != NULL, NULL);
2596 debug_print("get_command_output(): executing: %s\n", cmdline);
2598 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
2600 g_warning("couldn't execute command: %s", cmdline);
2604 return child_stdout;
2607 static gint is_unchanged_uri_char(char c)
2618 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2624 for(i = 0; i < strlen(uri) ; i++) {
2625 if (is_unchanged_uri_char(uri[i])) {
2626 if (k + 2 >= bufsize)
2628 encoded_uri[k++] = uri[i];
2631 char * hexa = "0123456789ABCDEF";
2633 if (k + 4 >= bufsize)
2635 encoded_uri[k++] = '%';
2636 encoded_uri[k++] = hexa[uri[i] / 16];
2637 encoded_uri[k++] = hexa[uri[i] % 16];
2643 gint open_uri(const gchar *uri, const gchar *cmdline)
2647 gchar buf[BUFFSIZE];
2649 gchar encoded_uri[BUFFSIZE];
2650 cm_return_val_if_fail(uri != NULL, -1);
2652 /* an option to choose whether to use encode_uri or not ? */
2653 encode_uri(encoded_uri, BUFFSIZE, uri);
2656 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2657 !strchr(p + 2, '%'))
2658 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
2661 g_warning("Open URI command-line is invalid "
2662 "(there must be only one '%%s'): %s",
2664 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
2667 execute_command_line(buf, TRUE, NULL);
2669 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
2674 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
2676 gchar buf[BUFFSIZE];
2679 cm_return_val_if_fail(filepath != NULL, -1);
2682 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2683 !strchr(p + 2, '%'))
2684 g_snprintf(buf, sizeof(buf), cmdline, filepath);
2687 g_warning("Open Text Editor command-line is invalid "
2688 "(there must be only one '%%s'): %s",
2690 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
2693 execute_command_line(buf, TRUE, NULL);
2698 time_t remote_tzoffset_sec(const gchar *zone)
2700 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
2706 time_t remoteoffset;
2708 strncpy(zone3, zone, 3);
2712 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
2713 (c == '+' || c == '-')) {
2714 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
2716 remoteoffset = -remoteoffset;
2717 } else if (!strncmp(zone, "UT" , 2) ||
2718 !strncmp(zone, "GMT", 3)) {
2720 } else if (strlen(zone3) == 3) {
2721 for (p = ustzstr; *p != '\0'; p += 3) {
2722 if (!g_ascii_strncasecmp(p, zone3, 3)) {
2723 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
2724 remoteoffset = iustz * 3600;
2730 } else if (strlen(zone3) == 1) {
2732 case 'Z': remoteoffset = 0; break;
2733 case 'A': remoteoffset = -1; break;
2734 case 'B': remoteoffset = -2; break;
2735 case 'C': remoteoffset = -3; break;
2736 case 'D': remoteoffset = -4; break;
2737 case 'E': remoteoffset = -5; break;
2738 case 'F': remoteoffset = -6; break;
2739 case 'G': remoteoffset = -7; break;
2740 case 'H': remoteoffset = -8; break;
2741 case 'I': remoteoffset = -9; break;
2742 case 'K': remoteoffset = -10; break; /* J is not used */
2743 case 'L': remoteoffset = -11; break;
2744 case 'M': remoteoffset = -12; break;
2745 case 'N': remoteoffset = 1; break;
2746 case 'O': remoteoffset = 2; break;
2747 case 'P': remoteoffset = 3; break;
2748 case 'Q': remoteoffset = 4; break;
2749 case 'R': remoteoffset = 5; break;
2750 case 'S': remoteoffset = 6; break;
2751 case 'T': remoteoffset = 7; break;
2752 case 'U': remoteoffset = 8; break;
2753 case 'V': remoteoffset = 9; break;
2754 case 'W': remoteoffset = 10; break;
2755 case 'X': remoteoffset = 11; break;
2756 case 'Y': remoteoffset = 12; break;
2757 default: remoteoffset = 0; break;
2759 remoteoffset = remoteoffset * 3600;
2763 return remoteoffset;
2766 time_t tzoffset_sec(time_t *now)
2770 struct tm buf1, buf2;
2772 if (now && *now < 0)
2775 gmt = *gmtime_r(now, &buf1);
2776 lt = localtime_r(now, &buf2);
2778 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2780 if (lt->tm_year < gmt.tm_year)
2782 else if (lt->tm_year > gmt.tm_year)
2784 else if (lt->tm_yday < gmt.tm_yday)
2786 else if (lt->tm_yday > gmt.tm_yday)
2789 if (off >= 24 * 60) /* should be impossible */
2790 off = 23 * 60 + 59; /* if not, insert silly value */
2791 if (off <= -24 * 60)
2792 off = -(23 * 60 + 59);
2797 /* calculate timezone offset */
2798 gchar *tzoffset(time_t *now)
2800 static gchar offset_string[6];
2804 struct tm buf1, buf2;
2806 if (now && *now < 0)
2809 gmt = *gmtime_r(now, &buf1);
2810 lt = localtime_r(now, &buf2);
2812 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2814 if (lt->tm_year < gmt.tm_year)
2816 else if (lt->tm_year > gmt.tm_year)
2818 else if (lt->tm_yday < gmt.tm_yday)
2820 else if (lt->tm_yday > gmt.tm_yday)
2828 if (off >= 24 * 60) /* should be impossible */
2829 off = 23 * 60 + 59; /* if not, insert silly value */
2831 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
2833 return offset_string;
2836 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
2840 gchar day[4], mon[4];
2841 gint dd, hh, mm, ss, yyyy;
2843 gchar buf2[RFC822_DATE_BUFFSIZE];
2847 lt = gmtime_r(&t, &buf1);
2849 lt = localtime_r(&t, &buf1);
2851 if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
2852 day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
2853 g_warning("failed reading date/time");
2855 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
2856 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
2859 void get_rfc822_date(gchar *buf, gint len)
2861 _get_rfc822_date(buf, len, FALSE);
2864 void get_rfc822_date_hide_tz(gchar *buf, gint len)
2866 _get_rfc822_date(buf, len, TRUE);
2869 void debug_set_mode(gboolean mode)
2874 gboolean debug_get_mode(void)
2879 void debug_print_real(const gchar *format, ...)
2882 gchar buf[BUFFSIZE];
2884 if (!debug_mode) return;
2886 va_start(args, format);
2887 g_vsnprintf(buf, sizeof(buf), format, args);
2894 const char * debug_srcname(const char *file)
2896 const char *s = strrchr (file, '/');
2901 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
2903 if (subject == NULL)
2906 subject += subject_get_prefix_length(subject);
2908 return g_hash_table_lookup(subject_table, subject);
2911 void subject_table_insert(GHashTable *subject_table, gchar * subject,
2914 if (subject == NULL || *subject == 0)
2916 subject += subject_get_prefix_length(subject);
2917 g_hash_table_insert(subject_table, subject, data);
2920 void subject_table_remove(GHashTable *subject_table, gchar * subject)
2922 if (subject == NULL)
2925 subject += subject_get_prefix_length(subject);
2926 g_hash_table_remove(subject_table, subject);
2929 static regex_t u_regex;
2930 static gboolean u_init_;
2932 void utils_free_regex(void)
2941 *\brief Check if a string is prefixed with known (combinations)
2942 * of prefixes. The function assumes that each prefix
2943 * is terminated by zero or exactly _one_ space.
2945 *\param str String to check for a prefixes
2947 *\return int Number of chars in the prefix that should be skipped
2948 * for a "clean" subject line. If no prefix was found, 0
2951 int subject_get_prefix_length(const gchar *subject)
2953 /*!< Array with allowable reply prefixes regexps. */
2954 static const gchar * const prefixes[] = {
2955 "Re\\:", /* "Re:" */
2956 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
2957 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
2958 "Aw\\:", /* "Aw:" (German) */
2959 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
2960 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
2961 "Fw\\:", /* "Fw:" Forward */
2962 "Fwd\\:", /* "Fwd:" Forward */
2963 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
2964 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
2965 "Rif\\:", /* "Rif:" (Italian Outlook) */
2966 "Sv\\:", /* "Sv" (Norwegian) */
2967 "Vs\\:", /* "Vs" (Norwegian) */
2968 "Ad\\:", /* "Ad" (Norwegian) */
2969 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
2970 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
2971 "Re \\:", /* "Re :" (French Yahoo Mail) */
2974 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
2978 if (!subject) return 0;
2979 if (!*subject) return 0;
2982 GString *s = g_string_new("");
2984 for (n = 0; n < PREFIXES; n++)
2985 /* Terminate each prefix regexpression by a
2986 * "\ ?" (zero or ONE space), and OR them */
2987 g_string_append_printf(s, "(%s\\ ?)%s",
2992 g_string_prepend(s, "(");
2993 g_string_append(s, ")+"); /* match at least once */
2994 g_string_prepend(s, "^\\ *"); /* from beginning of line */
2997 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
2998 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
2999 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3000 debug_print("Error compiling regexp %s\n", s->str);
3001 g_string_free(s, TRUE);
3005 g_string_free(s, TRUE);
3009 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3015 static guint g_stricase_hash(gconstpointer gptr)
3017 guint hash_result = 0;
3020 for (str = gptr; str && *str; str++) {
3021 hash_result += toupper(*str);
3027 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3029 const char *str1 = gptr1;
3030 const char *str2 = gptr2;
3032 return !strcasecmp(str1, str2);
3035 gint g_int_compare(gconstpointer a, gconstpointer b)
3037 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3041 quote_cmd_argument()
3043 return a quoted string safely usable in argument of a command.
3045 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3048 gint quote_cmd_argument(gchar * result, guint size,
3058 for(p = path ; * p != '\0' ; p ++) {
3060 if (isalnum((guchar)*p) || (* p == '/')) {
3061 if (remaining > 0) {
3067 result[size - 1] = '\0';
3072 if (remaining >= 2) {
3080 result[size - 1] = '\0';
3085 if (remaining > 0) {
3089 result[size - 1] = '\0';
3103 static void g_node_map_recursive(GNode *node, gpointer data)
3105 GNodeMapData *mapdata = (GNodeMapData *) data;
3107 GNodeMapData newmapdata;
3110 newdata = mapdata->func(node->data, mapdata->data);
3111 if (newdata != NULL) {
3112 newnode = g_node_new(newdata);
3113 g_node_append(mapdata->parent, newnode);
3115 newmapdata.parent = newnode;
3116 newmapdata.func = mapdata->func;
3117 newmapdata.data = mapdata->data;
3119 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3123 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3126 GNodeMapData mapdata;
3128 cm_return_val_if_fail(node != NULL, NULL);
3129 cm_return_val_if_fail(func != NULL, NULL);
3131 root = g_node_new(func(node->data, data));
3133 mapdata.parent = root;
3134 mapdata.func = func;
3135 mapdata.data = data;
3137 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3142 #define HEX_TO_INT(val, hex) \
3146 if ('0' <= c && c <= '9') { \
3148 } else if ('a' <= c && c <= 'f') { \
3149 val = c - 'a' + 10; \
3150 } else if ('A' <= c && c <= 'F') { \
3151 val = c - 'A' + 10; \
3157 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3164 if (hi == -1 || lo == -1)
3167 *out = (hi << 4) + lo;
3171 #define INT_TO_HEX(hex, val) \
3174 hex = '0' + (val); \
3176 hex = 'A' + (val) - 10; \
3179 void get_hex_str(gchar *out, guchar ch)
3183 INT_TO_HEX(hex, ch >> 4);
3185 INT_TO_HEX(hex, ch & 0x0f);
3191 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3193 #define G_PRINT_REF g_print
3197 *\brief Register ref counted pointer. It is based on GBoxed, so should
3198 * work with anything that uses the GType system. The semantics
3199 * are similar to a C++ auto pointer, with the exception that
3200 * C doesn't have automatic closure (calling destructors) when
3201 * exiting a block scope.
3202 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3203 * function directly.
3205 *\return GType A GType type.
3207 GType g_auto_pointer_register(void)
3209 static GType auto_pointer_type;
3210 if (!auto_pointer_type)
3212 g_boxed_type_register_static
3213 ("G_TYPE_AUTO_POINTER",
3214 (GBoxedCopyFunc) g_auto_pointer_copy,
3215 (GBoxedFreeFunc) g_auto_pointer_free);
3216 return auto_pointer_type;
3220 *\brief Structure with g_new() allocated pointer guarded by the
3223 typedef struct AutoPointerRef {
3224 void (*free) (gpointer);
3230 *\brief The auto pointer opaque structure that references the
3231 * pointer guard block.
3233 typedef struct AutoPointer {
3234 AutoPointerRef *ref;
3235 gpointer ptr; /*!< access to protected pointer */
3239 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3243 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3244 * ... when assigning, copying and freeing storage elements
3246 * gtk_list_store_new(N_S_COLUMNS,
3247 * G_TYPE_AUTO_POINTER,
3251 * Template *precious_data = g_new0(Template, 1);
3252 * g_pointer protect = g_auto_pointer_new(precious_data);
3254 * gtk_list_store_set(container, &iter,
3258 * ... the gtk_list_store has copied the pointer and
3259 * ... incremented its reference count, we should free
3260 * ... the auto pointer (in C++ a destructor would do
3261 * ... this for us when leaving block scope)
3263 * g_auto_pointer_free(protect);
3265 * ... gtk_list_store_set() now manages the data. When
3266 * ... *explicitly* requesting a pointer from the list
3267 * ... store, don't forget you get a copy that should be
3268 * ... freed with g_auto_pointer_free() eventually.
3272 *\param pointer Pointer to be guarded.
3274 *\return GAuto * Pointer that should be used in containers with
3277 GAuto *g_auto_pointer_new(gpointer p)
3279 AutoPointerRef *ref;
3285 ref = g_new0(AutoPointerRef, 1);
3286 ptr = g_new0(AutoPointer, 1);
3296 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3302 *\brief Allocate an autopointer using the passed \a free function to
3303 * free the guarded pointer
3305 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3312 aptr = g_auto_pointer_new(p);
3313 aptr->ref->free = free_;
3317 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3319 if (auto_ptr == NULL)
3321 return ((AutoPointer *) auto_ptr)->ptr;
3325 *\brief Copies an auto pointer by. It's mostly not necessary
3326 * to call this function directly, unless you copy/assign
3327 * the guarded pointer.
3329 *\param auto_ptr Auto pointer returned by previous call to
3330 * g_auto_pointer_new_XXX()
3332 *\return gpointer An auto pointer
3334 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3337 AutoPointerRef *ref;
3340 if (auto_ptr == NULL)
3345 newp = g_new0(AutoPointer, 1);
3348 newp->ptr = ref->pointer;
3352 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3358 *\brief Free an auto pointer
3360 void g_auto_pointer_free(GAuto *auto_ptr)
3363 AutoPointerRef *ref;
3365 if (auto_ptr == NULL)
3371 if (--(ref->cnt) == 0) {
3373 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3375 ref->free(ref->pointer);
3380 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3385 void replace_returns(gchar *str)
3390 while (strstr(str, "\n")) {
3391 *strstr(str, "\n") = ' ';
3393 while (strstr(str, "\r")) {
3394 *strstr(str, "\r") = ' ';
3398 /* get_uri_part() - retrieves a URI starting from scanpos.
3399 Returns TRUE if successful */
3400 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
3401 const gchar **bp, const gchar **ep, gboolean hdr)
3404 gint parenthese_cnt = 0;
3406 cm_return_val_if_fail(start != NULL, FALSE);
3407 cm_return_val_if_fail(scanpos != NULL, FALSE);
3408 cm_return_val_if_fail(bp != NULL, FALSE);
3409 cm_return_val_if_fail(ep != NULL, FALSE);
3413 /* find end point of URI */
3414 for (ep_ = scanpos; *ep_ != '\0'; ep_ = g_utf8_next_char(ep_)) {
3415 gunichar u = g_utf8_get_char_validated(ep_, -1);
3416 if (!g_unichar_isgraph(u) ||
3417 u == (gunichar)-1 ||
3418 strchr("[]{}<>\"", *ep_)) {
3420 } else if (strchr("(", *ep_)) {
3422 } else if (strchr(")", *ep_)) {
3423 if (parenthese_cnt > 0)
3430 /* no punctuation at end of string */
3432 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
3433 * should pass some URI type to this function and decide on that whether
3434 * to perform punctuation stripping */
3436 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
3438 for (; ep_ - 1 > scanpos + 1 &&
3439 IS_REAL_PUNCT(*(ep_ - 1));
3443 #undef IS_REAL_PUNCT
3450 gchar *make_uri_string(const gchar *bp, const gchar *ep)
3452 while (bp && *bp && g_ascii_isspace(*bp))
3454 return g_strndup(bp, ep - bp);
3457 /* valid mail address characters */
3458 #define IS_RFC822_CHAR(ch) \
3462 !g_ascii_isspace(ch) && \
3463 !strchr("(),;<>\"", (ch)))
3465 /* alphabet and number within 7bit ASCII */
3466 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
3467 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
3469 static GHashTable *create_domain_tab(void)
3472 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
3474 cm_return_val_if_fail(htab, NULL);
3475 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
3476 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
3480 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
3482 const gint MAX_LVL_DOM_NAME_LEN = 6;
3483 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
3484 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
3487 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
3490 for (p = buf; p < m && first < last; *p++ = *first++)
3494 return g_hash_table_lookup(tab, buf) != NULL;
3497 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
3498 gboolean get_email_part(const gchar *start, const gchar *scanpos,
3499 const gchar **bp, const gchar **ep, gboolean hdr)
3501 /* more complex than the uri part because we need to scan back and forward starting from
3502 * the scan position. */
3503 gboolean result = FALSE;
3504 const gchar *bp_ = NULL;
3505 const gchar *ep_ = NULL;
3506 static GHashTable *dom_tab;
3507 const gchar *last_dot = NULL;
3508 const gchar *prelast_dot = NULL;
3509 const gchar *last_tld_char = NULL;
3511 /* the informative part of the email address (describing the name
3512 * of the email address owner) may contain quoted parts. the
3513 * closure stack stores the last encountered quotes. */
3514 gchar closure_stack[128];
3515 gchar *ptr = closure_stack;
3517 cm_return_val_if_fail(start != NULL, FALSE);
3518 cm_return_val_if_fail(scanpos != NULL, FALSE);
3519 cm_return_val_if_fail(bp != NULL, FALSE);
3520 cm_return_val_if_fail(ep != NULL, FALSE);
3523 const gchar *start_quote = NULL;
3524 const gchar *end_quote = NULL;
3526 /* go to the real start */
3527 if (start[0] == ',')
3529 if (start[0] == ';')
3531 while (start[0] == '\n' || start[0] == '\r')
3533 while (start[0] == ' ' || start[0] == '\t')
3538 /* check if there are quotes (to skip , in them) */
3539 if (*start == '"') {
3540 start_quote = start;
3542 end_quote = strstr(start, "\"");
3548 /* skip anything between quotes */
3549 if (start_quote && end_quote) {
3554 /* find end (either , or ; or end of line) */
3555 if (strstr(start, ",") && strstr(start, ";"))
3556 *ep = strstr(start,",") < strstr(start, ";")
3557 ? strstr(start, ",") : strstr(start, ";");
3558 else if (strstr(start, ","))
3559 *ep = strstr(start, ",");
3560 else if (strstr(start, ";"))
3561 *ep = strstr(start, ";");
3563 *ep = start+strlen(start);
3565 /* go back to real start */
3566 if (start_quote && end_quote) {
3567 start = start_quote;
3570 /* check there's still an @ in that, or search
3571 * further if possible */
3572 if (strstr(start, "@") && strstr(start, "@") < *ep)
3574 else if (*ep < start+strlen(start)) {
3577 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
3585 dom_tab = create_domain_tab();
3586 cm_return_val_if_fail(dom_tab, FALSE);
3588 /* scan start of address */
3589 for (bp_ = scanpos - 1;
3590 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
3593 /* TODO: should start with an alnum? */
3595 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
3598 if (bp_ != scanpos) {
3599 /* scan end of address */
3600 for (ep_ = scanpos + 1;
3601 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
3603 prelast_dot = last_dot;
3605 if (*(last_dot + 1) == '.') {
3606 if (prelast_dot == NULL)
3608 last_dot = prelast_dot;
3613 /* TODO: really should terminate with an alnum? */
3614 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
3619 if (last_dot == NULL)
3621 if (last_dot >= ep_)
3622 last_dot = prelast_dot;
3623 if (last_dot == NULL || (scanpos + 1 >= last_dot))
3627 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
3628 if (*last_tld_char == '?')
3631 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
3638 if (!result) return FALSE;
3640 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
3641 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
3642 && IS_RFC822_CHAR(*(ep_ + 3))) {
3643 /* this informative part with an @ in it is
3644 * followed by the email address */
3647 /* go to matching '>' (or next non-rfc822 char, like \n) */
3648 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
3651 /* include the bracket */
3652 if (*ep_ == '>') ep_++;
3654 /* include the leading quote */
3662 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
3663 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
3666 /* see if this is <bracketed>; in this case we also scan for the informative part. */
3667 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
3670 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
3671 #define IN_STACK() (ptr > closure_stack)
3672 /* has underrun check */
3673 #define POP_STACK() if(IN_STACK()) --ptr
3674 /* has overrun check */
3675 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
3676 /* has underrun check */
3677 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
3681 /* scan for the informative part. */
3682 for (bp_ -= 2; bp_ >= start; bp_--) {
3683 /* if closure on the stack keep scanning */
3684 if (PEEK_STACK() == *bp_) {
3688 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
3693 /* if nothing in the closure stack, do the special conditions
3694 * the following if..else expression simply checks whether
3695 * a token is acceptable. if not acceptable, the clause
3696 * should terminate the loop with a 'break' */
3697 if (!PEEK_STACK()) {
3699 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
3700 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
3701 /* hyphens are allowed, but only in
3703 } else if (strchr(" \"'", *bp_)) {
3704 /* but anything not being a punctiation
3707 break; /* anything else is rejected */
3714 /* scan forward (should start with an alnum) */
3715 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
3731 #undef IS_ASCII_ALNUM
3732 #undef IS_RFC822_CHAR
3734 gchar *make_email_string(const gchar *bp, const gchar *ep)
3736 /* returns a mailto: URI; mailto: is also used to detect the
3737 * uri type later on in the button_pressed signal handler */
3742 tmp = g_strndup(bp, ep - bp);
3744 /* If there is a colon in the username part of the address,
3745 * we're dealing with an URI for some other protocol - do
3746 * not prefix with mailto: in such case. */
3747 colon = strchr(tmp, ':');
3748 at = strchr(tmp, '@');
3749 if (colon != NULL && at != NULL && colon < at) {
3752 result = g_strconcat("mailto:", tmp, NULL);
3759 gchar *make_http_string(const gchar *bp, const gchar *ep)
3761 /* returns an http: URI; */
3765 while (bp && *bp && g_ascii_isspace(*bp))
3767 tmp = g_strndup(bp, ep - bp);
3768 result = g_strconcat("http://", tmp, NULL);
3774 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
3776 FILE *fp = claws_fopen(path, "rb");
3777 gchar buf[BUFFSIZE];
3778 gchar *result = NULL;
3781 while (claws_fgets(buf, sizeof (buf), fp) != NULL) {
3782 gchar **parts = g_strsplit(buf, ";", 3);
3783 gchar *trimmed = parts[0];
3784 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3786 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3787 trimmed[strlen(trimmed)-1] = '\0';
3789 if (!strcmp(trimmed, type)) {
3790 gboolean needsterminal = FALSE;
3791 if (parts[2] && strstr(parts[2], "needsterminal")) {
3792 needsterminal = TRUE;
3794 if (parts[2] && strstr(parts[2], "test=")) {
3795 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
3796 gchar *testcmd = orig_testcmd;
3797 if (strstr(testcmd,";"))
3798 *(strstr(testcmd,";")) = '\0';
3799 while (testcmd[0] == ' ' || testcmd[0] == '\t')
3801 while (testcmd[strlen(testcmd)-1] == '\n')
3802 testcmd[strlen(testcmd)-1] = '\0';
3803 while (testcmd[strlen(testcmd)-1] == '\r')
3804 testcmd[strlen(testcmd)-1] = '\0';
3805 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
3806 testcmd[strlen(testcmd)-1] = '\0';
3808 if (strstr(testcmd, "%s")) {
3809 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
3810 gint res = system(tmp);
3812 g_free(orig_testcmd);
3819 gint res = system(testcmd);
3820 g_free(orig_testcmd);
3830 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3832 while (trimmed[strlen(trimmed)-1] == '\n')
3833 trimmed[strlen(trimmed)-1] = '\0';
3834 while (trimmed[strlen(trimmed)-1] == '\r')
3835 trimmed[strlen(trimmed)-1] = '\0';
3836 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3837 trimmed[strlen(trimmed)-1] = '\0';
3838 result = g_strdup(trimmed);
3841 if (needsterminal) {
3842 gchar *tmp = g_strdup_printf("xterm -e %s", result);
3853 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
3855 gchar *result = NULL;
3859 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3860 result = mailcap_get_command_in_file(path, type, file_to_open);
3864 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
3868 void mailcap_update_default(const gchar *type, const gchar *command)
3870 gchar *path = NULL, *outpath = NULL;
3871 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3872 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
3873 FILE *fp = claws_fopen(path, "rb");
3875 gchar buf[BUFFSIZE];
3876 gboolean err = FALSE;
3879 fp = claws_fopen(path, "a");
3881 g_warning("failed to create file %s", path);
3886 fp = g_freopen(path, "rb", fp);
3888 g_warning("failed to reopen file %s", path);
3895 outfp = claws_fopen(outpath, "wb");
3897 g_warning("failed to create file %s", outpath);
3903 while (fp && claws_fgets(buf, sizeof (buf), fp) != NULL) {
3904 gchar **parts = g_strsplit(buf, ";", 3);
3905 gchar *trimmed = parts[0];
3906 while (trimmed[0] == ' ')
3908 while (trimmed[strlen(trimmed)-1] == ' ')
3909 trimmed[strlen(trimmed)-1] = '\0';
3911 if (!strcmp(trimmed, type)) {
3916 if(claws_fputs(buf, outfp) == EOF) {
3923 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
3929 if (claws_safe_fclose(outfp) == EOF)
3933 g_rename(outpath, path);
3939 /* crude test to see if a file is an email. */
3940 gboolean file_is_email (const gchar *filename)
3946 if (filename == NULL)
3948 if ((fp = claws_fopen(filename, "rb")) == NULL)
3950 while (i < 60 && score < 3
3951 && claws_fgets(buffer, sizeof (buffer), fp) != NULL) {
3952 if (!strncmp(buffer, "From:", strlen("From:")))
3954 else if (!strncmp(buffer, "Date:", strlen("Date:")))
3956 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
3958 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
3963 return (score >= 3);
3966 gboolean sc_g_list_bigger(GList *list, gint max)
3970 while (cur && i <= max+1) {
3977 gboolean sc_g_slist_bigger(GSList *list, gint max)
3981 while (cur && i <= max+1) {
3988 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
3989 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
3990 NULL, NULL, NULL, NULL, NULL, NULL};
3991 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
3992 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
3993 NULL, NULL, NULL, NULL, NULL, NULL};
3995 gint daynames_len[] = {0,0,0,0,0,0,0};
3996 gint monthnames_len[] = {0,0,0,0,0,0,
3998 gint s_daynames_len[] = {0,0,0,0,0,0,0};
3999 gint s_monthnames_len[] = {0,0,0,0,0,0,
4001 const gchar *s_am_up = NULL;
4002 const gchar *s_pm_up = NULL;
4003 const gchar *s_am_low = NULL;
4004 const gchar *s_pm_low = NULL;
4006 gint s_am_up_len = 0;
4007 gint s_pm_up_len = 0;
4008 gint s_am_low_len = 0;
4009 gint s_pm_low_len = 0;
4011 static gboolean time_names_init_done = FALSE;
4013 static void init_time_names(void)
4017 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4018 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4019 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4020 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4021 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4022 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4023 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4025 monthnames[0] = C_("Complete month name for use by strftime", "January");
4026 monthnames[1] = C_("Complete month name for use by strftime", "February");
4027 monthnames[2] = C_("Complete month name for use by strftime", "March");
4028 monthnames[3] = C_("Complete month name for use by strftime", "April");
4029 monthnames[4] = C_("Complete month name for use by strftime", "May");
4030 monthnames[5] = C_("Complete month name for use by strftime", "June");
4031 monthnames[6] = C_("Complete month name for use by strftime", "July");
4032 monthnames[7] = C_("Complete month name for use by strftime", "August");
4033 monthnames[8] = C_("Complete month name for use by strftime", "September");
4034 monthnames[9] = C_("Complete month name for use by strftime", "October");
4035 monthnames[10] = C_("Complete month name for use by strftime", "November");
4036 monthnames[11] = C_("Complete month name for use by strftime", "December");
4038 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4039 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4040 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4041 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4042 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4043 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4044 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4046 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4047 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4048 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4049 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4050 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4051 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4052 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4053 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4054 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4055 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4056 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4057 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4059 for (i = 0; i < 7; i++) {
4060 daynames_len[i] = strlen(daynames[i]);
4061 s_daynames_len[i] = strlen(s_daynames[i]);
4063 for (i = 0; i < 12; i++) {
4064 monthnames_len[i] = strlen(monthnames[i]);
4065 s_monthnames_len[i] = strlen(s_monthnames[i]);
4068 s_am_up = C_("For use by strftime (morning)", "AM");
4069 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4070 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4071 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4073 s_am_up_len = strlen(s_am_up);
4074 s_pm_up_len = strlen(s_pm_up);
4075 s_am_low_len = strlen(s_am_low);
4076 s_pm_low_len = strlen(s_pm_low);
4078 time_names_init_done = TRUE;
4081 #define CHECK_SIZE() { \
4082 total_done += len; \
4083 if (total_done >= buflen) { \
4084 buf[buflen-1] = '\0'; \
4089 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4091 gchar *curpos = buf;
4092 gint total_done = 0;
4093 gchar subbuf[64], subfmt[64];
4094 static time_t last_tzset = (time_t)0;
4096 if (!time_names_init_done)
4099 if (format == NULL || lt == NULL)
4102 if (last_tzset != time(NULL)) {
4104 last_tzset = time(NULL);
4107 if (*format == '%') {
4108 gint len = 0, tmp = 0;
4112 len = 1; CHECK_SIZE();
4116 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4117 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4120 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4121 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4125 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4126 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4129 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4130 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4133 strftime(subbuf, 64, "%c", lt);
4134 len = strlen(subbuf); CHECK_SIZE();
4135 strncpy2(curpos, subbuf, buflen - total_done);
4138 total_done += 2; CHECK_SIZE();
4139 tmp = (lt->tm_year + 1900)/100;
4140 *curpos++ = '0'+(tmp / 10);
4141 *curpos++ = '0'+(tmp % 10);
4144 total_done += 2; CHECK_SIZE();
4145 *curpos++ = '0'+(lt->tm_mday / 10);
4146 *curpos++ = '0'+(lt->tm_mday % 10);
4149 total_done += 8; CHECK_SIZE();
4150 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4151 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4153 *curpos++ = '0'+(lt->tm_mday / 10);
4154 *curpos++ = '0'+(lt->tm_mday % 10);
4156 tmp = lt->tm_year%100;
4157 *curpos++ = '0'+(tmp / 10);
4158 *curpos++ = '0'+(tmp % 10);
4161 len = 2; CHECK_SIZE();
4162 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4165 len = 10; CHECK_SIZE();
4166 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4167 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4170 total_done += 2; CHECK_SIZE();
4171 *curpos++ = '0'+(lt->tm_hour / 10);
4172 *curpos++ = '0'+(lt->tm_hour % 10);
4175 total_done += 2; CHECK_SIZE();
4181 *curpos++ = '0'+(tmp / 10);
4182 *curpos++ = '0'+(tmp % 10);
4185 len = 3; CHECK_SIZE();
4186 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4189 len = 2; CHECK_SIZE();
4190 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4193 len = 2; CHECK_SIZE();
4199 snprintf(curpos, buflen - total_done, "%2d", tmp);
4202 total_done += 2; CHECK_SIZE();
4203 tmp = lt->tm_mon + 1;
4204 *curpos++ = '0'+(tmp / 10);
4205 *curpos++ = '0'+(tmp % 10);
4208 total_done += 2; CHECK_SIZE();
4209 *curpos++ = '0'+(lt->tm_min / 10);
4210 *curpos++ = '0'+(lt->tm_min % 10);
4213 len = 1; CHECK_SIZE();
4217 if (lt->tm_hour >= 12) {
4218 len = s_pm_up_len; CHECK_SIZE();
4219 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4221 len = s_am_up_len; CHECK_SIZE();
4222 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4226 if (lt->tm_hour >= 12) {
4227 len = s_pm_low_len; CHECK_SIZE();
4228 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4230 len = s_am_low_len; CHECK_SIZE();
4231 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4235 strftime(subbuf, 64, "%r", lt);
4236 len = strlen(subbuf); CHECK_SIZE();
4237 strncpy2(curpos, subbuf, buflen - total_done);
4240 total_done += 5; CHECK_SIZE();
4241 *curpos++ = '0'+(lt->tm_hour / 10);
4242 *curpos++ = '0'+(lt->tm_hour % 10);
4244 *curpos++ = '0'+(lt->tm_min / 10);
4245 *curpos++ = '0'+(lt->tm_min % 10);
4248 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
4249 len = strlen(subbuf); CHECK_SIZE();
4250 strncpy2(curpos, subbuf, buflen - total_done);
4253 total_done += 2; CHECK_SIZE();
4254 *curpos++ = '0'+(lt->tm_sec / 10);
4255 *curpos++ = '0'+(lt->tm_sec % 10);
4258 len = 1; CHECK_SIZE();
4262 total_done += 8; CHECK_SIZE();
4263 *curpos++ = '0'+(lt->tm_hour / 10);
4264 *curpos++ = '0'+(lt->tm_hour % 10);
4266 *curpos++ = '0'+(lt->tm_min / 10);
4267 *curpos++ = '0'+(lt->tm_min % 10);
4269 *curpos++ = '0'+(lt->tm_sec / 10);
4270 *curpos++ = '0'+(lt->tm_sec % 10);
4273 len = 1; CHECK_SIZE();
4274 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
4277 len = 1; CHECK_SIZE();
4278 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
4281 strftime(subbuf, 64, "%x", lt);
4282 len = strlen(subbuf); CHECK_SIZE();
4283 strncpy2(curpos, subbuf, buflen - total_done);
4286 strftime(subbuf, 64, "%X", lt);
4287 len = strlen(subbuf); CHECK_SIZE();
4288 strncpy2(curpos, subbuf, buflen - total_done);
4291 total_done += 2; CHECK_SIZE();
4292 tmp = lt->tm_year%100;
4293 *curpos++ = '0'+(tmp / 10);
4294 *curpos++ = '0'+(tmp % 10);
4297 len = 4; CHECK_SIZE();
4298 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
4308 /* let these complicated ones be done with the libc */
4309 snprintf(subfmt, 64, "%%%c", *format);
4310 strftime(subbuf, 64, subfmt, lt);
4311 len = strlen(subbuf); CHECK_SIZE();
4312 strncpy2(curpos, subbuf, buflen - total_done);
4316 /* let these complicated modifiers be done with the libc */
4317 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
4318 strftime(subbuf, 64, subfmt, lt);
4319 len = strlen(subbuf); CHECK_SIZE();
4320 strncpy2(curpos, subbuf, buflen - total_done);
4324 g_warning("format error (%c)", *format);
4331 int len = 1; CHECK_SIZE();
4332 *curpos++ = *format++;
4340 #define WEXITSTATUS(x) (x)
4343 GMutex *cm_mutex_new(void) {
4344 #if GLIB_CHECK_VERSION(2,32,0)
4345 GMutex *m = g_new0(GMutex, 1);
4349 return g_mutex_new();
4353 void cm_mutex_free(GMutex *mutex) {
4354 #if GLIB_CHECK_VERSION(2,32,0)
4355 g_mutex_clear(mutex);
4358 g_mutex_free(mutex);
4362 static gchar *canonical_list_to_file(GSList *list)
4364 GString *result = g_string_new(NULL);
4365 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
4370 result = g_string_append(result, G_DIR_SEPARATOR_S);
4372 if (pathlist->data) {
4373 const gchar *root = (gchar *)pathlist->data;
4374 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
4376 /* drive - don't prepend dir separator */
4378 result = g_string_append(result, G_DIR_SEPARATOR_S);
4383 for (cur = pathlist; cur; cur = cur->next) {
4384 result = g_string_append(result, (gchar *)cur->data);
4386 result = g_string_append(result, G_DIR_SEPARATOR_S);
4388 g_slist_free(pathlist);
4391 g_string_free(result, FALSE);
4396 static GSList *cm_split_path(const gchar *filename, int depth)
4399 GSList *canonical_parts = NULL;
4403 gboolean follow_symlinks = TRUE;
4410 errno = EINVAL; /* can't happen, no symlink handling */
4415 if (!g_path_is_absolute(filename)) {
4420 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
4422 for (i = 0; path_parts[i] != NULL; i++) {
4423 if (!strcmp(path_parts[i], ""))
4425 if (!strcmp(path_parts[i], "."))
4427 else if (!strcmp(path_parts[i], "..")) {
4432 else /* Remove the last inserted element */
4434 g_slist_delete_link(canonical_parts,
4439 canonical_parts = g_slist_prepend(canonical_parts,
4440 g_strdup(path_parts[i]));
4442 tmp_path = canonical_list_to_file(canonical_parts);
4444 if(g_stat(tmp_path, &st) < 0) {
4445 if (errno == ENOENT) {
4448 follow_symlinks = FALSE;
4453 slist_free_strings_full(canonical_parts);
4454 g_strfreev(path_parts);
4460 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
4461 GError *error = NULL;
4462 gchar *target = g_file_read_link(tmp_path, &error);
4464 if (!g_path_is_absolute(target)) {
4465 /* remove the last inserted element */
4467 g_slist_delete_link(canonical_parts,
4469 /* add the target */
4470 canonical_parts = g_slist_prepend(canonical_parts,
4474 /* and get the new target */
4475 target = canonical_list_to_file(canonical_parts);
4478 /* restart from absolute target */
4479 slist_free_strings_full(canonical_parts);
4480 canonical_parts = NULL;
4482 canonical_parts = cm_split_path(target, depth + 1);
4484 g_error_free(error);
4485 if (canonical_parts == NULL) {
4487 g_strfreev(path_parts);
4496 g_strfreev(path_parts);
4497 return canonical_parts;
4501 * Canonicalize a filename, resolving symlinks along the way.
4502 * Returns a negative errno in case of error.
4504 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
4505 GSList *canonical_parts;
4506 gboolean is_absolute;
4508 if (filename == NULL)
4510 if (canonical_name == NULL)
4512 *canonical_name = NULL;
4514 is_absolute = g_path_is_absolute(filename);
4516 /* Always work on absolute filenames. */
4517 gchar *cur = g_get_current_dir();
4518 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
4521 canonical_parts = cm_split_path(absolute_filename, 0);
4522 g_free(absolute_filename);
4525 canonical_parts = cm_split_path(filename, 0);
4527 if (canonical_parts == NULL)
4530 *canonical_name = canonical_list_to_file(canonical_parts);
4531 slist_free_strings_full(canonical_parts);
4535 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
4536 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
4538 gchar *tmp = g_base64_decode(text, out_len);
4539 gchar *out = g_strndup(tmp, *out_len);
4543 if (strlen(out) != *out_len) {
4544 g_warning ("strlen(out) %zd != *out_len %" G_GSIZE_FORMAT, strlen(out), *out_len);
4550 #if !GLIB_CHECK_VERSION(2, 30, 0)
4553 * @str: a UTF-8 encoded string
4554 * @start_pos: a character offset within @str
4555 * @end_pos: another character offset within @str
4557 * Copies a substring out of a UTF-8 encoded string.
4558 * The substring will contain @end_pos - @start_pos
4561 * Returns: a newly allocated copy of the requested
4562 * substring. Free with g_free() when no longer needed.
4567 g_utf8_substring (const gchar *str,
4571 gchar *start, *end, *out;
4573 start = g_utf8_offset_to_pointer (str, start_pos);
4574 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
4576 out = g_malloc (end - start + 1);
4577 memcpy (out, start, end - start);
4578 out[end - start] = 0;
4584 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
4585 * It is up to the caller to make sure there is at least count bytes
4586 * available at buf. */
4588 get_random_bytes(void *buf, size_t count)
4590 /* Open our prng source. */
4591 #if defined G_OS_WIN32
4594 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
4595 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
4596 debug_print("Could not acquire a CSP handle.\n");
4603 rnd = open("/dev/urandom", O_RDONLY);
4605 FILE_OP_ERROR("/dev/urandom", "open");
4606 debug_print("Could not open /dev/urandom.\n");
4611 /* Read data from the source into buf. */
4612 #if defined G_OS_WIN32
4613 if (!CryptGenRandom(rnd, count, buf)) {
4614 debug_print("Could not read %zd random bytes.\n", count);
4615 CryptReleaseContext(rnd, 0);
4619 ret = read(rnd, buf, count);
4621 FILE_OP_ERROR("/dev/urandom", "read");
4622 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
4628 /* Close the prng source. */
4629 #if defined G_OS_WIN32
4630 CryptReleaseContext(rnd, 0);
4638 /* returns FALSE if parsing failed, otherwise returns TRUE and sets *server, *port
4639 and eventually *fp from filename (if not NULL, they must be free'd by caller after
4641 filenames we expect: 'host.name.port.cert' or 'host.name.port.f:i:n:g:e:r:p:r:i:n:t.cert' */
4642 gboolean get_serverportfp_from_filename(const gchar *str, gchar **server, gchar **port, gchar **fp)
4644 const gchar *pos, *dotport_pos = NULL, *dotcert_pos = NULL, *dotfp_pos = NULL;
4646 g_return_val_if_fail(str != NULL, FALSE);
4648 pos = str + strlen(str) - 1;
4649 while ((pos > str) && !dotport_pos) {
4652 /* match the .cert suffix */
4653 if (strcmp(pos, ".cert") == 0) {
4658 /* match an eventual fingerprint */
4659 /* or the port number */
4660 if (strncmp(pos + 3, ":", 1) == 0) {
4666 /* match the port number */
4673 if (!dotport_pos || !dotcert_pos) {
4674 g_warning("could not parse filename %s", str);
4679 *server = g_strndup(str, dotport_pos - str);
4682 *port = g_strndup(dotport_pos + 1, dotfp_pos - dotport_pos - 1);
4684 *fp = g_strndup(dotfp_pos + 1, dotcert_pos - dotfp_pos - 1);
4687 *port = g_strndup(dotport_pos + 1, dotcert_pos - dotport_pos - 1);
4692 debug_print("filename='%s' => server='%s' port='%s' fp='%s'\n",
4694 (server ? *server : "(n/a)"),
4695 (port ? *port : "(n/a)"),
4696 (fp ? *fp : "(n/a)"));
4698 if (!(server && *server) || !(port && *port))