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>
86 #include "../codeconv.h"
91 static gboolean debug_mode = FALSE;
93 static GSList *tempfiles=NULL;
96 #if !GLIB_CHECK_VERSION(2, 26, 0)
97 guchar *g_base64_decode_wa(const gchar *text, gsize *out_len)
104 input_length = strlen(text);
106 ret = g_malloc0((input_length / 4) * 3 + 1);
108 *out_len = g_base64_decode_step(text, input_length, ret, &state, &save);
114 /* Return true if we are running as root. This function should beused
115 instead of getuid () == 0. */
116 gboolean superuser_p (void)
119 return w32_is_administrator ();
125 GSList *slist_copy_deep(GSList *list, GCopyFunc func)
127 #if GLIB_CHECK_VERSION(2, 34, 0)
128 return g_slist_copy_deep(list, func, NULL);
130 GSList *res = g_slist_copy(list);
133 walk->data = func(walk->data, NULL);
140 void list_free_strings(GList *list)
142 list = g_list_first(list);
144 while (list != NULL) {
150 void slist_free_strings(GSList *list)
152 while (list != NULL) {
158 void slist_free_strings_full(GSList *list)
160 #if GLIB_CHECK_VERSION(2,28,0)
161 g_slist_free_full(list, (GDestroyNotify)g_free);
163 g_slist_foreach(list, (GFunc)g_free, NULL);
168 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
173 void hash_free_strings(GHashTable *table)
175 g_hash_table_foreach(table, hash_free_strings_func, NULL);
178 gint str_case_equal(gconstpointer v, gconstpointer v2)
180 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
183 guint str_case_hash(gconstpointer key)
185 const gchar *p = key;
189 h = g_ascii_tolower(h);
190 for (p += 1; *p != '\0'; p++)
191 h = (h << 5) - h + g_ascii_tolower(*p);
197 void ptr_array_free_strings(GPtrArray *array)
202 cm_return_if_fail(array != NULL);
204 for (i = 0; i < array->len; i++) {
205 str = g_ptr_array_index(array, i);
210 gint to_number(const gchar *nstr)
212 register const gchar *p;
214 if (*nstr == '\0') return -1;
216 for (p = nstr; *p != '\0'; p++)
217 if (!g_ascii_isdigit(*p)) return -1;
222 /* convert integer into string,
223 nstr must be not lower than 11 characters length */
224 gchar *itos_buf(gchar *nstr, gint n)
226 g_snprintf(nstr, 11, "%d", n);
230 /* convert integer into string */
233 static gchar nstr[11];
235 return itos_buf(nstr, n);
238 #define divide(num,divisor,i,d) \
240 i = num >> divisor; \
241 d = num & ((1<<divisor)-1); \
242 d = (d*100) >> divisor; \
247 * \brief Convert a given size in bytes in a human-readable string
249 * \param size The size expressed in bytes to convert in string
250 * \return The string that respresents the size in an human-readable way
252 gchar *to_human_readable(goffset size)
254 static gchar str[14];
255 static gchar *b_format = NULL, *kb_format = NULL,
256 *mb_format = NULL, *gb_format = NULL;
257 register int t = 0, r = 0;
258 if (b_format == NULL) {
260 kb_format = _("%d.%02dKB");
261 mb_format = _("%d.%02dMB");
262 gb_format = _("%.2fGB");
265 if (size < (goffset)1024) {
266 g_snprintf(str, sizeof(str), b_format, (gint)size);
268 } else if (size >> 10 < (goffset)1024) {
269 divide(size, 10, t, r);
270 g_snprintf(str, sizeof(str), kb_format, t, r);
272 } else if (size >> 20 < (goffset)1024) {
273 divide(size, 20, t, r);
274 g_snprintf(str, sizeof(str), mb_format, t, r);
277 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
282 /* strcmp with NULL-checking */
283 gint strcmp2(const gchar *s1, const gchar *s2)
285 if (s1 == NULL || s2 == NULL)
288 return strcmp(s1, s2);
290 /* strstr with NULL-checking */
291 gchar *strstr2(const gchar *s1, const gchar *s2)
293 if (s1 == NULL || s2 == NULL)
296 return strstr(s1, s2);
299 gint path_cmp(const gchar *s1, const gchar *s2)
304 gchar *s1buf, *s2buf;
307 if (s1 == NULL || s2 == NULL) return -1;
308 if (*s1 == '\0' || *s2 == '\0') return -1;
311 s1buf = g_strdup (s1);
312 s2buf = g_strdup (s2);
313 subst_char (s1buf, '/', G_DIR_SEPARATOR);
314 subst_char (s2buf, '/', G_DIR_SEPARATOR);
317 #endif /* !G_OS_WIN32 */
322 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
323 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
325 rc = strncmp(s1, s2, MAX(len1, len2));
329 #endif /* !G_OS_WIN32 */
333 /* remove trailing return code */
334 gchar *strretchomp(gchar *str)
338 if (!*str) return str;
340 for (s = str + strlen(str) - 1;
341 s >= str && (*s == '\n' || *s == '\r');
348 /* remove trailing character */
349 gchar *strtailchomp(gchar *str, gchar tail_char)
353 if (!*str) return str;
354 if (tail_char == '\0') return str;
356 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
362 /* remove CR (carriage return) */
363 gchar *strcrchomp(gchar *str)
367 if (!*str) return str;
369 s = str + strlen(str) - 1;
370 if (*s == '\n' && s > str && *(s - 1) == '\r') {
378 gint file_strip_crs(const gchar *file)
380 FILE *fp = NULL, *outfp = NULL;
382 gchar *out = get_tmp_file();
386 fp = g_fopen(file, "rb");
390 outfp = g_fopen(out, "wb");
396 while (fgets(buf, sizeof (buf), fp) != NULL) {
398 if (fputs(buf, outfp) == EOF) {
406 if (fclose(outfp) == EOF) {
410 if (move_file(out, file, TRUE) < 0)
422 /* Similar to `strstr' but this function ignores the case of both strings. */
423 gchar *strcasestr(const gchar *haystack, const gchar *needle)
425 size_t haystack_len = strlen(haystack);
427 return strncasestr(haystack, haystack_len, needle);
430 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
432 register size_t needle_len;
434 needle_len = strlen(needle);
436 if (haystack_len < needle_len || needle_len == 0)
439 while (haystack_len >= needle_len) {
440 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
441 return (gchar *)haystack;
451 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
452 gconstpointer needle, size_t needlelen)
454 const gchar *haystack_ = (const gchar *)haystack;
455 const gchar *needle_ = (const gchar *)needle;
456 const gchar *haystack_cur = (const gchar *)haystack;
457 size_t haystack_left = haystacklen;
460 return memchr(haystack_, *needle_, haystacklen);
462 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
464 if (haystacklen - (haystack_cur - haystack_) < needlelen)
466 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
467 return (gpointer)haystack_cur;
470 haystack_left = haystacklen - (haystack_cur - haystack_);
477 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
478 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
480 register const gchar *s = src;
481 register gchar *d = dest;
491 /* Examine if next block is non-ASCII string */
492 gboolean is_next_nonascii(const gchar *s)
496 /* skip head space */
497 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
499 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
500 if (*(guchar *)p > 127 || *(guchar *)p < 32)
507 gint get_next_word_len(const gchar *s)
511 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
517 static void trim_subject_for_compare(gchar *str)
521 eliminate_parenthesis(str, '[', ']');
522 eliminate_parenthesis(str, '(', ')');
525 srcp = str + subject_get_prefix_length(str);
527 memmove(str, srcp, strlen(srcp) + 1);
530 static void trim_subject_for_sort(gchar *str)
536 srcp = str + subject_get_prefix_length(str);
538 memmove(str, srcp, strlen(srcp) + 1);
541 /* compare subjects */
542 gint subject_compare(const gchar *s1, const gchar *s2)
546 if (!s1 || !s2) return -1;
547 if (!*s1 || !*s2) return -1;
549 Xstrdup_a(str1, s1, return -1);
550 Xstrdup_a(str2, s2, return -1);
552 trim_subject_for_compare(str1);
553 trim_subject_for_compare(str2);
555 if (!*str1 || !*str2) return -1;
557 return strcmp(str1, str2);
560 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
564 if (!s1 || !s2) return -1;
566 Xstrdup_a(str1, s1, return -1);
567 Xstrdup_a(str2, s2, return -1);
569 trim_subject_for_sort(str1);
570 trim_subject_for_sort(str2);
572 return g_utf8_collate(str1, str2);
575 void trim_subject(gchar *str)
577 register gchar *srcp;
583 srcp = str + subject_get_prefix_length(str);
588 } else if (*srcp == '(') {
600 else if (*srcp == cl)
607 while (g_ascii_isspace(*srcp)) srcp++;
608 memmove(str, srcp, strlen(srcp) + 1);
611 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
613 register gchar *srcp, *destp;
618 while ((destp = strchr(destp, op))) {
624 else if (*srcp == cl)
630 while (g_ascii_isspace(*srcp)) srcp++;
631 memmove(destp, srcp, strlen(srcp) + 1);
635 void extract_parenthesis(gchar *str, gchar op, gchar cl)
637 register gchar *srcp, *destp;
642 while ((srcp = strchr(destp, op))) {
645 memmove(destp, srcp + 1, strlen(srcp));
650 else if (*destp == cl)
662 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
665 register gchar *srcp, *destp;
667 gboolean in_quote = FALSE;
671 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
674 memmove(destp, srcp + 1, strlen(srcp));
677 if (*destp == op && !in_quote)
679 else if (*destp == cl && !in_quote)
681 else if (*destp == quote_chr)
693 void extract_quote(gchar *str, gchar quote_chr)
697 if ((str = strchr(str, quote_chr))) {
699 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
700 memmove(p - 1, p, strlen(p) + 1);
705 memmove(str, str + 1, p - str);
710 /* Returns a newly allocated string with all quote_chr not at the beginning
711 or the end of str escaped with '\' or the given str if not required. */
712 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
714 register gchar *p, *q;
718 if (str == NULL || *str == '\0')
721 /* search for unescaped quote_chr */
726 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
730 if (!k) /* nothing to escape */
733 /* unescaped quote_chr found */
734 qstr = g_malloc(l + k + 1);
737 if (*p == quote_chr) {
742 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
751 void eliminate_address_comment(gchar *str)
753 register gchar *srcp, *destp;
758 while ((destp = strchr(destp, '"'))) {
759 if ((srcp = strchr(destp + 1, '"'))) {
764 while (g_ascii_isspace(*srcp)) srcp++;
765 memmove(destp, srcp, strlen(srcp) + 1);
775 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
781 else if (*srcp == ')')
787 while (g_ascii_isspace(*srcp)) srcp++;
788 memmove(destp, srcp, strlen(srcp) + 1);
792 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
794 gboolean in_quote = FALSE;
797 if (*str == c && !in_quote)
799 if (*str == quote_chr)
807 void extract_address(gchar *str)
809 cm_return_if_fail(str != NULL);
810 eliminate_address_comment(str);
811 if (strchr_with_skip_quote(str, '"', '<'))
812 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
816 void extract_list_id_str(gchar *str)
818 if (strchr_with_skip_quote(str, '"', '<'))
819 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
823 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
828 if (!str) return addr_list;
830 Xstrdup_a(work, str, return addr_list);
833 eliminate_address_comment(work);
836 while (workp && *workp) {
839 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
845 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
846 extract_parenthesis_with_skip_quote
847 (workp, '"', '<', '>');
851 addr_list = g_slist_append(addr_list, g_strdup(workp));
859 GSList *address_list_append(GSList *addr_list, const gchar *str)
861 return address_list_append_real(addr_list, str, TRUE);
864 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
866 return address_list_append_real(addr_list, str, FALSE);
869 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
873 if (!str) return msgid_list;
876 while (strp && *strp) {
877 const gchar *start, *end;
880 if ((start = strchr(strp, '<')) != NULL) {
881 end = strchr(start + 1, '>');
886 msgid = g_strndup(start + 1, end - start - 1);
889 msgid_list = g_slist_prepend(msgid_list, msgid);
899 GSList *references_list_append(GSList *msgid_list, const gchar *str)
903 list = references_list_prepend(NULL, str);
904 list = g_slist_reverse(list);
905 msgid_list = g_slist_concat(msgid_list, list);
910 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
915 if (!str) return group_list;
917 Xstrdup_a(work, str, return group_list);
921 while (workp && *workp) {
924 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
932 group_list = g_slist_append(group_list,
941 GList *add_history(GList *list, const gchar *str)
946 cm_return_val_if_fail(str != NULL, list);
948 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
951 list = g_list_remove(list, old->data);
953 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
956 last = g_list_last(list);
959 list = g_list_remove(list, last->data);
964 list = g_list_prepend(list, g_strdup(str));
969 void remove_return(gchar *str)
971 register gchar *p = str;
974 if (*p == '\n' || *p == '\r')
975 memmove(p, p + 1, strlen(p));
981 void remove_space(gchar *str)
983 register gchar *p = str;
988 while (g_ascii_isspace(*(p + spc)))
991 memmove(p, p + spc, strlen(p + spc) + 1);
997 void unfold_line(gchar *str)
1000 register gunichar c;
1003 ch = str; /* iterator for source string */
1006 c = g_utf8_get_char_validated(ch, -1);
1008 if (c == (gunichar)-1 || c == (gunichar)-2) {
1009 /* non-unicode byte, move past it */
1014 len = g_unichar_to_utf8(c, NULL);
1016 if (!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
1017 g_unichar_isspace(c)) {
1018 /* replace anything bad or whitespacey with a single space */
1022 /* move rest of the string forwards, since we just replaced
1023 * a multi-byte sequence with one byte */
1024 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
1027 /* A valid unicode character, copy it. */
1033 void subst_char(gchar *str, gchar orig, gchar subst)
1035 register gchar *p = str;
1044 void subst_chars(gchar *str, gchar *orig, gchar subst)
1046 register gchar *p = str;
1049 if (strchr(orig, *p) != NULL)
1055 void subst_for_filename(gchar *str)
1060 subst_chars(str, "\t\r\n\\/*:", '_');
1062 subst_chars(str, "\t\r\n\\/*", '_');
1066 void subst_for_shellsafe_filename(gchar *str)
1070 subst_for_filename(str);
1071 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1074 gboolean is_ascii_str(const gchar *str)
1076 const guchar *p = (const guchar *)str;
1078 while (*p != '\0') {
1079 if (*p != '\t' && *p != ' ' &&
1080 *p != '\r' && *p != '\n' &&
1081 (*p < 32 || *p >= 127))
1089 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1091 gchar * position = NULL;
1092 gchar * tmp_pos = NULL;
1095 if (quote_chars == NULL)
1098 for (i = 0; i < strlen(quote_chars); i++) {
1099 tmp_pos = strrchr (str, quote_chars[i]);
1101 || (tmp_pos != NULL && position <= tmp_pos) )
1107 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1109 const gchar *first_pos;
1110 const gchar *last_pos;
1111 const gchar *p = str;
1112 gint quote_level = -1;
1114 /* speed up line processing by only searching to the last '>' */
1115 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1116 /* skip a line if it contains a '<' before the initial '>' */
1117 if (memchr(str, '<', first_pos - str) != NULL)
1119 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1123 while (p <= last_pos) {
1124 while (p < last_pos) {
1125 if (g_ascii_isspace(*p))
1131 if (strchr(quote_chars, *p))
1133 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1134 /* any characters are allowed except '-','<' and space */
1135 while (*p != '-' && *p != '<'
1136 && !strchr(quote_chars, *p)
1137 && !g_ascii_isspace(*p)
1140 if (strchr(quote_chars, *p))
1152 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1154 const gchar *p = str, *q;
1155 gint cur_line = 0, len;
1157 while ((q = strchr(p, '\n')) != NULL) {
1159 if (len > max_chars) {
1169 if (len > max_chars) {
1178 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1180 gchar * position = NULL;
1181 gchar * tmp_pos = NULL;
1184 if (quote_chars == NULL)
1187 for (i = 0; i < strlen(quote_chars); i++) {
1188 tmp_pos = strchr (str, quote_chars[i]);
1190 || (tmp_pos != NULL && position >= tmp_pos) )
1196 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1198 register guint haystack_len, needle_len;
1199 gboolean in_squote = FALSE, in_dquote = FALSE;
1201 haystack_len = strlen(haystack);
1202 needle_len = strlen(needle);
1204 if (haystack_len < needle_len || needle_len == 0)
1207 while (haystack_len >= needle_len) {
1208 if (!in_squote && !in_dquote &&
1209 !strncmp(haystack, needle, needle_len))
1210 return (gchar *)haystack;
1212 /* 'foo"bar"' -> foo"bar"
1213 "foo'bar'" -> foo'bar' */
1214 if (*haystack == '\'') {
1217 else if (!in_dquote)
1219 } else if (*haystack == '\"') {
1222 else if (!in_squote)
1224 } else if (*haystack == '\\') {
1236 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1239 GSList *string_list = NULL, *slist;
1240 gchar **str_array, *s, *new_str;
1241 guint i, n = 1, len;
1243 cm_return_val_if_fail(str != NULL, NULL);
1244 cm_return_val_if_fail(delim != NULL, NULL);
1247 max_tokens = G_MAXINT;
1249 s = strstr_with_skip_quote(str, delim);
1251 guint delimiter_len = strlen(delim);
1255 new_str = g_strndup(str, len);
1257 if (new_str[0] == '\'' || new_str[0] == '\"') {
1258 if (new_str[len - 1] == new_str[0]) {
1259 new_str[len - 1] = '\0';
1260 memmove(new_str, new_str + 1, len - 1);
1263 string_list = g_slist_prepend(string_list, new_str);
1265 str = s + delimiter_len;
1266 s = strstr_with_skip_quote(str, delim);
1267 } while (--max_tokens && s);
1271 new_str = g_strdup(str);
1272 if (new_str[0] == '\'' || new_str[0] == '\"') {
1274 if (new_str[len - 1] == new_str[0]) {
1275 new_str[len - 1] = '\0';
1276 memmove(new_str, new_str + 1, len - 1);
1279 string_list = g_slist_prepend(string_list, new_str);
1283 str_array = g_new(gchar*, n);
1287 str_array[i--] = NULL;
1288 for (slist = string_list; slist; slist = slist->next)
1289 str_array[i--] = slist->data;
1291 g_slist_free(string_list);
1296 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1298 gchar *abbrev_group;
1300 const gchar *p = group;
1303 cm_return_val_if_fail(group != NULL, NULL);
1305 last = group + strlen(group);
1306 abbrev_group = ap = g_malloc(strlen(group) + 1);
1311 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1313 while (*p != '.') p++;
1316 return abbrev_group;
1321 return abbrev_group;
1324 gchar *trim_string(const gchar *str, gint len)
1326 const gchar *p = str;
1331 if (!str) return NULL;
1332 if (strlen(str) <= len)
1333 return g_strdup(str);
1334 if (g_utf8_validate(str, -1, NULL) == FALSE)
1335 return g_strdup(str);
1337 while (*p != '\0') {
1338 mb_len = g_utf8_skip[*(guchar *)p];
1341 else if (new_len + mb_len > len)
1348 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1349 return g_strconcat(new_str, "...", NULL);
1352 GList *uri_list_extract_filenames(const gchar *uri_list)
1354 GList *result = NULL;
1356 gchar *escaped_utf8uri;
1362 while (g_ascii_isspace(*p)) p++;
1363 if (!strncmp(p, "file:", 5)) {
1366 while (*q && *q != '\n' && *q != '\r') q++;
1369 gchar *file, *locale_file = NULL;
1371 while (q > p && g_ascii_isspace(*q))
1373 Xalloca(escaped_utf8uri, q - p + 2,
1375 Xalloca(file, q - p + 2,
1378 strncpy(escaped_utf8uri, p, q - p + 1);
1379 escaped_utf8uri[q - p + 1] = '\0';
1380 decode_uri(file, escaped_utf8uri);
1382 * g_filename_from_uri() rejects escaped/locale encoded uri
1383 * string which come from Nautilus.
1386 if (g_utf8_validate(file, -1, NULL))
1388 = conv_codeset_strdup(
1391 conv_get_locale_charset_str());
1393 locale_file = g_strdup(file + 5);
1395 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1397 result = g_list_append(result, locale_file);
1401 p = strchr(p, '\n');
1408 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1411 static gint axtoi(const gchar *hexstr)
1413 gint hi, lo, result;
1416 if ('0' <= hi && hi <= '9') {
1419 if ('a' <= hi && hi <= 'f') {
1422 if ('A' <= hi && hi <= 'F') {
1427 if ('0' <= lo && lo <= '9') {
1430 if ('a' <= lo && lo <= 'f') {
1433 if ('A' <= lo && lo <= 'F') {
1436 result = lo + (16 * hi);
1440 gboolean is_uri_string(const gchar *str)
1442 while (str && *str && g_ascii_isspace(*str))
1444 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1445 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1446 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1447 g_ascii_strncasecmp(str, "www.", 4) == 0);
1450 gchar *get_uri_path(const gchar *uri)
1452 while (uri && *uri && g_ascii_isspace(*uri))
1454 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1455 return (gchar *)(uri + 7);
1456 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1457 return (gchar *)(uri + 8);
1458 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1459 return (gchar *)(uri + 6);
1461 return (gchar *)uri;
1464 gint get_uri_len(const gchar *str)
1468 if (is_uri_string(str)) {
1469 for (p = str; *p != '\0'; p++) {
1470 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1479 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1480 * plusses, and escape characters are used)
1482 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1484 gchar *dec = decoded_uri;
1485 const gchar *enc = encoded_uri;
1490 if (isxdigit((guchar)enc[0]) &&
1491 isxdigit((guchar)enc[1])) {
1497 if (with_plus && *enc == '+')
1509 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1511 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1514 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1516 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1517 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1521 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1522 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1526 const gchar *forbidden_uris[] = { ".gnupg/",
1532 gint num_attach = 0;
1533 gchar **my_att = NULL;
1535 Xstrdup_a(tmp_mailto, mailto, return -1);
1537 if (!strncmp(tmp_mailto, "mailto:", 7))
1540 p = strchr(tmp_mailto, '?');
1547 *to = decode_uri_gdup(tmp_mailto);
1549 my_att = g_malloc(sizeof(char *));
1553 gchar *field, *value;
1570 if (*value == '\0') continue;
1572 if (from && !g_ascii_strcasecmp(field, "from")) {
1574 *from = decode_uri_gdup(value);
1576 gchar *tmp = decode_uri_gdup(value);
1577 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1581 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1583 *cc = decode_uri_gdup(value);
1585 gchar *tmp = decode_uri_gdup(value);
1586 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1590 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1592 *bcc = decode_uri_gdup(value);
1594 gchar *tmp = decode_uri_gdup(value);
1595 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1599 } else if (subject && !*subject &&
1600 !g_ascii_strcasecmp(field, "subject")) {
1601 *subject = decode_uri_gdup(value);
1602 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1603 *body = decode_uri_gdup(value);
1604 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1605 gchar *tmp = decode_uri_gdup(value);
1606 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1607 g_warning("couldn't set insert file '%s' in body", value);
1611 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1613 gchar *tmp = decode_uri_gdup(value);
1614 for (; forbidden_uris[i]; i++) {
1615 if (strstr(tmp, forbidden_uris[i])) {
1616 g_print("Refusing to attach '%s', potential private data leak\n",
1624 /* attach is correct */
1626 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1627 my_att[num_attach-1] = tmp;
1628 my_att[num_attach] = NULL;
1630 } else if (inreplyto && !*inreplyto &&
1631 !g_ascii_strcasecmp(field, "in-reply-to")) {
1632 *inreplyto = decode_uri_gdup(value);
1643 #include <windows.h>
1644 #ifndef CSIDL_APPDATA
1645 #define CSIDL_APPDATA 0x001a
1647 #ifndef CSIDL_LOCAL_APPDATA
1648 #define CSIDL_LOCAL_APPDATA 0x001c
1650 #ifndef CSIDL_FLAG_CREATE
1651 #define CSIDL_FLAG_CREATE 0x8000
1653 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1657 w32_strerror (int w32_errno)
1659 static char strerr[256];
1660 int ec = (int)GetLastError ();
1664 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1665 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1666 strerr, DIM (strerr)-1, NULL);
1670 static __inline__ void *
1671 dlopen (const char * name, int flag)
1673 void * hd = LoadLibrary (name);
1677 static __inline__ void *
1678 dlsym (void * hd, const char * sym)
1682 void * fnc = GetProcAddress (hd, sym);
1691 static __inline__ const char *
1694 return w32_strerror (0);
1698 static __inline__ int
1710 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1712 static int initialized;
1713 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1717 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1723 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1725 handle = dlopen (dllnames[i], RTLD_LAZY);
1728 func = dlsym (handle, "SHGetFolderPathW");
1739 return func (a,b,c,d,e);
1744 /* Returns a static string with the directroy from which the module
1745 has been loaded. Returns an empty string on error. */
1746 static char *w32_get_module_dir(void)
1748 static char *moddir;
1751 char name[MAX_PATH+10];
1754 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1757 p = strrchr (name, '\\');
1763 moddir = g_strdup (name);
1767 #endif /* G_OS_WIN32 */
1769 /* Return a static string with the locale dir. */
1770 const gchar *get_locale_dir(void)
1772 static gchar *loc_dir;
1776 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1777 "\\share\\locale", NULL);
1780 loc_dir = LOCALEDIR;
1786 const gchar *get_home_dir(void)
1789 static char home_dir_utf16[MAX_PATH] = "";
1790 static gchar *home_dir_utf8 = NULL;
1791 if (home_dir_utf16[0] == '\0') {
1792 if (w32_shgetfolderpath
1793 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1794 NULL, 0, home_dir_utf16) < 0)
1795 strcpy (home_dir_utf16, "C:\\Sylpheed");
1796 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar *)home_dir_utf16, -1, NULL, NULL, NULL);
1798 return home_dir_utf8;
1800 static const gchar *homeenv = NULL;
1805 if (!homeenv && g_getenv("HOME") != NULL)
1806 homeenv = g_strdup(g_getenv("HOME"));
1808 homeenv = g_get_home_dir();
1814 static gchar *claws_rc_dir = NULL;
1815 static gboolean rc_dir_alt = FALSE;
1816 const gchar *get_rc_dir(void)
1819 if (!claws_rc_dir) {
1820 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1822 debug_print("using default rc_dir %s\n", claws_rc_dir);
1824 return claws_rc_dir;
1827 void set_rc_dir(const gchar *dir)
1829 gchar *canonical_dir;
1830 if (claws_rc_dir != NULL) {
1831 g_print("Error: rc_dir already set\n");
1833 int err = cm_canonicalize_filename(dir, &canonical_dir);
1837 g_print("Error looking for %s: %d(%s)\n",
1838 dir, -err, g_strerror(-err));
1843 claws_rc_dir = canonical_dir;
1845 len = strlen(claws_rc_dir);
1846 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1847 claws_rc_dir[len - 1] = '\0';
1849 debug_print("set rc_dir to %s\n", claws_rc_dir);
1850 if (!is_dir_exist(claws_rc_dir)) {
1851 if (make_dir_hier(claws_rc_dir) != 0) {
1852 g_print("Error: can't create %s\n",
1860 gboolean rc_dir_is_alt(void) {
1864 const gchar *get_mail_base_dir(void)
1866 return get_home_dir();
1869 const gchar *get_news_cache_dir(void)
1871 static gchar *news_cache_dir = NULL;
1872 if (!news_cache_dir)
1873 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1874 NEWS_CACHE_DIR, NULL);
1876 return news_cache_dir;
1879 const gchar *get_imap_cache_dir(void)
1881 static gchar *imap_cache_dir = NULL;
1883 if (!imap_cache_dir)
1884 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1885 IMAP_CACHE_DIR, NULL);
1887 return imap_cache_dir;
1890 const gchar *get_mime_tmp_dir(void)
1892 static gchar *mime_tmp_dir = NULL;
1895 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1896 MIME_TMP_DIR, NULL);
1898 return mime_tmp_dir;
1901 const gchar *get_template_dir(void)
1903 static gchar *template_dir = NULL;
1906 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1907 TEMPLATE_DIR, NULL);
1909 return template_dir;
1913 const gchar *w32_get_cert_file(void)
1915 const gchar *cert_file = NULL;
1917 cert_file = g_strconcat(w32_get_module_dir(),
1918 "\\share\\claws-mail\\",
1919 "ca-certificates.crt",
1925 /* Return the filepath of the claws-mail.desktop file */
1926 const gchar *get_desktop_file(void)
1928 #ifdef DESKTOPFILEPATH
1929 return DESKTOPFILEPATH;
1935 /* Return the default directory for Plugins. */
1936 const gchar *get_plugin_dir(void)
1939 static gchar *plugin_dir = NULL;
1942 plugin_dir = g_strconcat(w32_get_module_dir(),
1943 "\\lib\\claws-mail\\plugins\\",
1947 if (is_dir_exist(PLUGINDIR))
1950 static gchar *plugin_dir = NULL;
1952 plugin_dir = g_strconcat(get_rc_dir(),
1953 G_DIR_SEPARATOR_S, "plugins",
1954 G_DIR_SEPARATOR_S, NULL);
1962 /* Return the default directory for Themes. */
1963 const gchar *w32_get_themes_dir(void)
1965 static gchar *themes_dir = NULL;
1968 themes_dir = g_strconcat(w32_get_module_dir(),
1969 "\\share\\claws-mail\\themes",
1975 const gchar *get_tmp_dir(void)
1977 static gchar *tmp_dir = NULL;
1980 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1986 gchar *get_tmp_file(void)
1989 static guint32 id = 0;
1991 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1992 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1997 const gchar *get_domain_name(void)
2000 static gchar *domain_name = NULL;
2001 struct addrinfo hints, *res;
2006 if (gethostname(hostname, sizeof(hostname)) != 0) {
2007 perror("gethostname");
2008 domain_name = "localhost";
2010 memset(&hints, 0, sizeof(struct addrinfo));
2011 hints.ai_family = AF_UNSPEC;
2012 hints.ai_socktype = 0;
2013 hints.ai_flags = AI_CANONNAME;
2014 hints.ai_protocol = 0;
2016 s = getaddrinfo(hostname, NULL, &hints, &res);
2018 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
2019 domain_name = g_strdup(hostname);
2021 domain_name = g_strdup(res->ai_canonname);
2025 debug_print("domain name = %s\n", domain_name);
2034 off_t get_file_size(const gchar *file)
2038 if (g_stat(file, &s) < 0) {
2039 FILE_OP_ERROR(file, "stat");
2046 time_t get_file_mtime(const gchar *file)
2050 if (g_stat(file, &s) < 0) {
2051 FILE_OP_ERROR(file, "stat");
2058 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2065 if (g_stat(file, &s) < 0) {
2066 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2070 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2077 /* Test on whether FILE is a relative file name. This is
2078 * straightforward for Unix but more complex for Windows. */
2079 gboolean is_relative_filename(const gchar *file)
2084 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2085 return FALSE; /* Prefixed with a hostname - this can't
2086 * be a relative name. */
2088 if ( ((*file >= 'a' && *file <= 'z')
2089 || (*file >= 'A' && *file <= 'Z'))
2091 file += 2; /* Skip drive letter. */
2093 return !(*file == '\\' || *file == '/');
2095 return !(*file == G_DIR_SEPARATOR);
2100 gboolean is_dir_exist(const gchar *dir)
2105 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2108 gboolean is_file_entry_exist(const gchar *file)
2113 return g_file_test(file, G_FILE_TEST_EXISTS);
2116 gboolean dirent_is_regular_file(struct dirent *d)
2118 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2119 if (d->d_type == DT_REG)
2121 else if (d->d_type != DT_UNKNOWN)
2125 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2128 gint change_dir(const gchar *dir)
2130 gchar *prevdir = NULL;
2133 prevdir = g_get_current_dir();
2135 if (g_chdir(dir) < 0) {
2136 FILE_OP_ERROR(dir, "chdir");
2137 if (debug_mode) g_free(prevdir);
2139 } else if (debug_mode) {
2142 cwd = g_get_current_dir();
2143 if (strcmp(prevdir, cwd) != 0)
2144 g_print("current dir: %s\n", cwd);
2152 gint make_dir(const gchar *dir)
2154 if (g_mkdir(dir, S_IRWXU) < 0) {
2155 FILE_OP_ERROR(dir, "mkdir");
2158 if (g_chmod(dir, S_IRWXU) < 0)
2159 FILE_OP_ERROR(dir, "chmod");
2164 gint make_dir_hier(const gchar *dir)
2169 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2170 parent_dir = g_strndup(dir, p - dir);
2171 if (*parent_dir != '\0') {
2172 if (!is_dir_exist(parent_dir)) {
2173 if (make_dir(parent_dir) < 0) {
2182 if (!is_dir_exist(dir)) {
2183 if (make_dir(dir) < 0)
2190 gint remove_all_files(const gchar *dir)
2193 const gchar *file_name;
2196 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2197 g_warning("failed to open directory: %s", dir);
2201 while ((file_name = g_dir_read_name(dp)) != NULL) {
2202 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2203 if (claws_unlink(tmp) < 0)
2204 FILE_OP_ERROR(tmp, "unlink");
2213 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2216 const gchar *dir_name;
2220 if (first == last) {
2221 /* Skip all the dir reading part. */
2222 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2223 if (is_dir_exist(filename)) {
2224 /* a numbered directory with this name exists,
2225 * remove the dot-file instead */
2227 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2229 if (claws_unlink(filename) < 0) {
2230 FILE_OP_ERROR(filename, "unlink");
2238 prev_dir = g_get_current_dir();
2240 if (g_chdir(dir) < 0) {
2241 FILE_OP_ERROR(dir, "chdir");
2246 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2247 g_warning("failed to open directory: %s", dir);
2252 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2253 file_no = to_number(dir_name);
2254 if (file_no > 0 && first <= file_no && file_no <= last) {
2255 if (is_dir_exist(dir_name)) {
2256 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2257 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2258 FILE_OP_ERROR(dot_file, "unlink");
2263 if (claws_unlink(dir_name) < 0)
2264 FILE_OP_ERROR(dir_name, "unlink");
2270 if (g_chdir(prev_dir) < 0) {
2271 FILE_OP_ERROR(prev_dir, "chdir");
2281 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2284 const gchar *dir_name;
2287 GHashTable *wanted_files;
2289 GError *error = NULL;
2291 if (numberlist == NULL)
2294 prev_dir = g_get_current_dir();
2296 if (g_chdir(dir) < 0) {
2297 FILE_OP_ERROR(dir, "chdir");
2302 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2303 g_message("Couldn't open current directory: %s (%d).\n",
2304 error->message, error->code);
2305 g_error_free(error);
2310 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2311 for (cur = numberlist; cur != NULL; cur = cur->next) {
2312 /* numberlist->data is expected to be GINT_TO_POINTER */
2313 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2316 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2317 file_no = to_number(dir_name);
2318 if (is_dir_exist(dir_name))
2320 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2321 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2322 if (is_dir_exist(dir_name)) {
2323 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2324 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2325 FILE_OP_ERROR(dot_file, "unlink");
2330 if (claws_unlink(dir_name) < 0)
2331 FILE_OP_ERROR(dir_name, "unlink");
2336 g_hash_table_destroy(wanted_files);
2338 if (g_chdir(prev_dir) < 0) {
2339 FILE_OP_ERROR(prev_dir, "chdir");
2349 gint remove_all_numbered_files(const gchar *dir)
2351 return remove_numbered_files(dir, 0, UINT_MAX);
2354 gint remove_dir_recursive(const gchar *dir)
2358 const gchar *dir_name;
2361 if (g_stat(dir, &s) < 0) {
2362 FILE_OP_ERROR(dir, "stat");
2363 if (ENOENT == errno) return 0;
2367 if (!S_ISDIR(s.st_mode)) {
2368 if (claws_unlink(dir) < 0) {
2369 FILE_OP_ERROR(dir, "unlink");
2376 prev_dir = g_get_current_dir();
2377 /* g_print("prev_dir = %s\n", prev_dir); */
2379 if (!path_cmp(prev_dir, dir)) {
2381 if (g_chdir("..") < 0) {
2382 FILE_OP_ERROR(dir, "chdir");
2385 prev_dir = g_get_current_dir();
2388 if (g_chdir(dir) < 0) {
2389 FILE_OP_ERROR(dir, "chdir");
2394 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2395 g_warning("failed to open directory: %s", dir);
2401 /* remove all files in the directory */
2402 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2403 /* g_print("removing %s\n", dir_name); */
2405 if (is_dir_exist(dir_name)) {
2408 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2409 g_warning("can't remove directory: %s", dir_name);
2413 if (claws_unlink(dir_name) < 0)
2414 FILE_OP_ERROR(dir_name, "unlink");
2420 if (g_chdir(prev_dir) < 0) {
2421 FILE_OP_ERROR(prev_dir, "chdir");
2428 if (g_rmdir(dir) < 0) {
2429 FILE_OP_ERROR(dir, "rmdir");
2436 gint rename_force(const gchar *oldpath, const gchar *newpath)
2439 if (!is_file_entry_exist(oldpath)) {
2443 if (is_file_exist(newpath)) {
2444 if (claws_unlink(newpath) < 0)
2445 FILE_OP_ERROR(newpath, "unlink");
2448 return g_rename(oldpath, newpath);
2452 * Append src file body to the tail of dest file.
2453 * Now keep_backup has no effects.
2455 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2457 FILE *src_fp, *dest_fp;
2461 gboolean err = FALSE;
2463 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2464 FILE_OP_ERROR(src, "g_fopen");
2468 if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2469 FILE_OP_ERROR(dest, "g_fopen");
2474 if (change_file_mode_rw(dest_fp, dest) < 0) {
2475 FILE_OP_ERROR(dest, "chmod");
2476 g_warning("can't change file mode: %s", dest);
2479 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2480 if (n_read < sizeof(buf) && ferror(src_fp))
2482 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2483 g_warning("writing to %s failed.", dest);
2491 if (ferror(src_fp)) {
2492 FILE_OP_ERROR(src, "fread");
2496 if (fclose(dest_fp) == EOF) {
2497 FILE_OP_ERROR(dest, "fclose");
2509 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2511 FILE *src_fp, *dest_fp;
2514 gchar *dest_bak = NULL;
2515 gboolean err = FALSE;
2517 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2518 FILE_OP_ERROR(src, "g_fopen");
2521 if (is_file_exist(dest)) {
2522 dest_bak = g_strconcat(dest, ".bak", NULL);
2523 if (rename_force(dest, dest_bak) < 0) {
2524 FILE_OP_ERROR(dest, "rename");
2531 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2532 FILE_OP_ERROR(dest, "g_fopen");
2535 if (rename_force(dest_bak, dest) < 0)
2536 FILE_OP_ERROR(dest_bak, "rename");
2542 if (change_file_mode_rw(dest_fp, dest) < 0) {
2543 FILE_OP_ERROR(dest, "chmod");
2544 g_warning("can't change file mode: %s", dest);
2547 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2548 if (n_read < sizeof(buf) && ferror(src_fp))
2550 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2551 g_warning("writing to %s failed.", dest);
2556 if (rename_force(dest_bak, dest) < 0)
2557 FILE_OP_ERROR(dest_bak, "rename");
2564 if (ferror(src_fp)) {
2565 FILE_OP_ERROR(src, "fread");
2569 if (fclose(dest_fp) == EOF) {
2570 FILE_OP_ERROR(dest, "fclose");
2577 if (rename_force(dest_bak, dest) < 0)
2578 FILE_OP_ERROR(dest_bak, "rename");
2584 if (keep_backup == FALSE && dest_bak)
2585 claws_unlink(dest_bak);
2592 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2594 if (overwrite == FALSE && is_file_exist(dest)) {
2595 g_warning("move_file(): file %s already exists.", dest);
2599 if (rename_force(src, dest) == 0) return 0;
2601 if (EXDEV != errno) {
2602 FILE_OP_ERROR(src, "rename");
2606 if (copy_file(src, dest, FALSE) < 0) return -1;
2613 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2616 gint bytes_left, to_read;
2619 if (fseek(fp, offset, SEEK_SET) < 0) {
2624 bytes_left = length;
2625 to_read = MIN(bytes_left, sizeof(buf));
2627 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2628 if (n_read < to_read && ferror(fp))
2630 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2633 bytes_left -= n_read;
2634 if (bytes_left == 0)
2636 to_read = MIN(bytes_left, sizeof(buf));
2647 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2650 gboolean err = FALSE;
2652 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2653 FILE_OP_ERROR(dest, "g_fopen");
2657 if (change_file_mode_rw(dest_fp, dest) < 0) {
2658 FILE_OP_ERROR(dest, "chmod");
2659 g_warning("can't change file mode: %s", dest);
2662 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2665 if (!err && fclose(dest_fp) == EOF) {
2666 FILE_OP_ERROR(dest, "fclose");
2671 g_warning("writing to %s failed.", dest);
2679 /* convert line endings into CRLF. If the last line doesn't end with
2680 * linebreak, add it.
2682 gchar *canonicalize_str(const gchar *str)
2688 for (p = str; *p != '\0'; ++p) {
2695 if (p == str || *(p - 1) != '\n')
2698 out = outp = g_malloc(new_len + 1);
2699 for (p = str; *p != '\0'; ++p) {
2706 if (p == str || *(p - 1) != '\n') {
2715 gint canonicalize_file(const gchar *src, const gchar *dest)
2717 FILE *src_fp, *dest_fp;
2718 gchar buf[BUFFSIZE];
2720 gboolean err = FALSE;
2721 gboolean last_linebreak = FALSE;
2723 if (src == NULL || dest == NULL)
2726 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2727 FILE_OP_ERROR(src, "g_fopen");
2731 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2732 FILE_OP_ERROR(dest, "g_fopen");
2737 if (change_file_mode_rw(dest_fp, dest) < 0) {
2738 FILE_OP_ERROR(dest, "chmod");
2739 g_warning("can't change file mode: %s", dest);
2742 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2746 if (len == 0) break;
2747 last_linebreak = FALSE;
2749 if (buf[len - 1] != '\n') {
2750 last_linebreak = TRUE;
2751 r = fputs(buf, dest_fp);
2752 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2753 r = fputs(buf, dest_fp);
2756 r = fwrite(buf, 1, len - 1, dest_fp);
2761 r = fputs("\r\n", dest_fp);
2765 g_warning("writing to %s failed.", dest);
2773 if (last_linebreak == TRUE) {
2774 if (fputs("\r\n", dest_fp) == EOF)
2778 if (ferror(src_fp)) {
2779 FILE_OP_ERROR(src, "fgets");
2783 if (fclose(dest_fp) == EOF) {
2784 FILE_OP_ERROR(dest, "fclose");
2796 gint canonicalize_file_replace(const gchar *file)
2800 tmp_file = get_tmp_file();
2802 if (canonicalize_file(file, tmp_file) < 0) {
2807 if (move_file(tmp_file, file, TRUE) < 0) {
2808 g_warning("can't replace file: %s", file);
2809 claws_unlink(tmp_file);
2818 gchar *normalize_newlines(const gchar *str)
2823 out = outp = g_malloc(strlen(str) + 1);
2824 for (p = str; *p != '\0'; ++p) {
2826 if (*(p + 1) != '\n')
2837 gchar *get_outgoing_rfc2822_str(FILE *fp)
2839 gchar buf[BUFFSIZE];
2843 str = g_string_new(NULL);
2845 /* output header part */
2846 while (fgets(buf, sizeof(buf), fp) != NULL) {
2848 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2855 else if (next != ' ' && next != '\t') {
2859 if (fgets(buf, sizeof(buf), fp) == NULL)
2863 g_string_append(str, buf);
2864 g_string_append(str, "\r\n");
2870 /* output body part */
2871 while (fgets(buf, sizeof(buf), fp) != NULL) {
2874 g_string_append_c(str, '.');
2875 g_string_append(str, buf);
2876 g_string_append(str, "\r\n");
2880 g_string_free(str, FALSE);
2886 * Create a new boundary in a way that it is very unlikely that this
2887 * will occur in the following text. It would be easy to ensure
2888 * uniqueness if everything is either quoted-printable or base64
2889 * encoded (note that conversion is allowed), but because MIME bodies
2890 * may be nested, it may happen that the same boundary has already
2893 * boundary := 0*69<bchars> bcharsnospace
2894 * bchars := bcharsnospace / " "
2895 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2896 * "+" / "_" / "," / "-" / "." /
2897 * "/" / ":" / "=" / "?"
2899 * some special characters removed because of buggy MTAs
2902 gchar *generate_mime_boundary(const gchar *prefix)
2904 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2905 "abcdefghijklmnopqrstuvwxyz"
2910 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2911 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2914 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2918 gint change_file_mode_rw(FILE *fp, const gchar *file)
2921 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2923 return g_chmod(file, S_IRUSR|S_IWUSR);
2927 FILE *my_tmpfile(void)
2929 const gchar suffix[] = ".XXXXXX";
2930 const gchar *tmpdir;
2932 const gchar *progname;
2941 tmpdir = get_tmp_dir();
2942 tmplen = strlen(tmpdir);
2943 progname = g_get_prgname();
2944 if (progname == NULL)
2945 progname = "claws-mail";
2946 proglen = strlen(progname);
2947 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2950 memcpy(fname, tmpdir, tmplen);
2951 fname[tmplen] = G_DIR_SEPARATOR;
2952 memcpy(fname + tmplen + 1, progname, proglen);
2953 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2955 fd = g_mkstemp(fname);
2960 claws_unlink(fname);
2962 /* verify that we can write in the file after unlinking */
2963 if (write(fd, buf, 1) < 0) {
2970 fp = fdopen(fd, "w+b");
2981 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2984 *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
2985 fd = g_mkstemp(*filename);
2988 return fdopen(fd, "w+");
2991 FILE *str_open_as_stream(const gchar *str)
2996 cm_return_val_if_fail(str != NULL, NULL);
3000 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3005 if (len == 0) return fp;
3007 if (fwrite(str, 1, len, fp) != len) {
3008 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3017 gint str_write_to_file(const gchar *str, const gchar *file)
3022 cm_return_val_if_fail(str != NULL, -1);
3023 cm_return_val_if_fail(file != NULL, -1);
3025 if ((fp = g_fopen(file, "wb")) == NULL) {
3026 FILE_OP_ERROR(file, "g_fopen");
3036 if (fwrite(str, 1, len, fp) != len) {
3037 FILE_OP_ERROR(file, "fwrite");
3043 if (fclose(fp) == EOF) {
3044 FILE_OP_ERROR(file, "fclose");
3052 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3059 cm_return_val_if_fail(fp != NULL, NULL);
3061 array = g_byte_array_new();
3063 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3064 if (n_read < sizeof(buf) && ferror(fp))
3066 g_byte_array_append(array, buf, n_read);
3070 FILE_OP_ERROR("file stream", "fread");
3071 g_byte_array_free(array, TRUE);
3076 g_byte_array_append(array, buf, 1);
3077 str = (gchar *)array->data;
3078 g_byte_array_free(array, FALSE);
3080 if (recode && !g_utf8_validate(str, -1, NULL)) {
3081 const gchar *src_codeset, *dest_codeset;
3083 src_codeset = conv_get_locale_charset_str();
3084 dest_codeset = CS_UTF_8;
3085 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3093 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3100 struct timeval timeout = {1, 0};
3105 cm_return_val_if_fail(file != NULL, NULL);
3107 if (g_stat(file, &s) != 0) {
3108 FILE_OP_ERROR(file, "stat");
3111 if (S_ISDIR(s.st_mode)) {
3112 g_warning("%s: is a directory", file);
3117 fp = g_fopen (file, "rb");
3119 FILE_OP_ERROR(file, "open");
3123 /* test whether the file is readable without blocking */
3124 fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3126 FILE_OP_ERROR(file, "open");
3133 /* allow for one second */
3134 err = select(fd+1, &fds, NULL, NULL, &timeout);
3135 if (err <= 0 || !FD_ISSET(fd, &fds)) {
3137 FILE_OP_ERROR(file, "select");
3139 g_warning("%s: doesn't seem readable", file);
3145 /* Now clear O_NONBLOCK */
3146 if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3147 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3151 if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3152 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3157 /* get the FILE pointer */
3158 fp = fdopen(fd, "rb");
3161 FILE_OP_ERROR(file, "fdopen");
3162 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3167 str = file_read_stream_to_str_full(fp, recode);
3174 gchar *file_read_to_str(const gchar *file)
3176 return file_read_to_str_full(file, TRUE);
3178 gchar *file_read_stream_to_str(FILE *fp)
3180 return file_read_stream_to_str_full(fp, TRUE);
3183 gchar *file_read_to_str_no_recode(const gchar *file)
3185 return file_read_to_str_full(file, FALSE);
3187 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3189 return file_read_stream_to_str_full(fp, FALSE);
3192 char *fgets_crlf(char *buf, int size, FILE *stream)
3194 gboolean is_cr = FALSE;
3195 gboolean last_was_cr = FALSE;
3200 while (--size > 0 && (c = getc(stream)) != EOF)
3203 is_cr = (c == '\r');
3213 last_was_cr = is_cr;
3215 if (c == EOF && cs == buf)
3223 static gint execute_async(gchar *const argv[], const gchar *working_directory)
3225 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3227 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3228 NULL, NULL, NULL, FALSE) == FALSE) {
3229 g_warning("couldn't execute command: %s", argv[0]);
3236 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
3240 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3243 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3244 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3245 g_warning("couldn't execute command: %s", argv[0]);
3249 if (WIFEXITED(status))
3250 return WEXITSTATUS(status);
3254 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
3255 G_SPAWN_SEARCH_PATH|
3256 G_SPAWN_CHILD_INHERITS_STDIN|
3257 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3258 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3259 g_warning("couldn't execute command: %s", argv[0]);
3267 gint execute_command_line(const gchar *cmdline, gboolean async,
3268 const gchar *working_directory)
3273 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3275 argv = strsplit_with_quote(cmdline, " ", 0);
3278 ret = execute_async(argv, working_directory);
3280 ret = execute_sync(argv, working_directory);
3287 gchar *get_command_output(const gchar *cmdline)
3289 gchar *child_stdout;
3292 cm_return_val_if_fail(cmdline != NULL, NULL);
3294 debug_print("get_command_output(): executing: %s\n", cmdline);
3296 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3298 g_warning("couldn't execute command: %s", cmdline);
3302 return child_stdout;
3305 static gint is_unchanged_uri_char(char c)
3316 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3322 for(i = 0; i < strlen(uri) ; i++) {
3323 if (is_unchanged_uri_char(uri[i])) {
3324 if (k + 2 >= bufsize)
3326 encoded_uri[k++] = uri[i];
3329 char * hexa = "0123456789ABCDEF";
3331 if (k + 4 >= bufsize)
3333 encoded_uri[k++] = '%';
3334 encoded_uri[k++] = hexa[uri[i] / 16];
3335 encoded_uri[k++] = hexa[uri[i] % 16];
3341 gint open_uri(const gchar *uri, const gchar *cmdline)
3345 gchar buf[BUFFSIZE];
3347 gchar encoded_uri[BUFFSIZE];
3348 cm_return_val_if_fail(uri != NULL, -1);
3350 /* an option to choose whether to use encode_uri or not ? */
3351 encode_uri(encoded_uri, BUFFSIZE, uri);
3354 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3355 !strchr(p + 2, '%'))
3356 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3359 g_warning("Open URI command-line is invalid "
3360 "(there must be only one '%%s'): %s",
3362 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3365 execute_command_line(buf, TRUE, NULL);
3367 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3372 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3374 gchar buf[BUFFSIZE];
3377 cm_return_val_if_fail(filepath != NULL, -1);
3380 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3381 !strchr(p + 2, '%'))
3382 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3385 g_warning("Open Text Editor command-line is invalid "
3386 "(there must be only one '%%s'): %s",
3388 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3391 execute_command_line(buf, TRUE, NULL);
3396 time_t remote_tzoffset_sec(const gchar *zone)
3398 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3404 time_t remoteoffset;
3406 strncpy(zone3, zone, 3);
3410 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3411 (c == '+' || c == '-')) {
3412 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3414 remoteoffset = -remoteoffset;
3415 } else if (!strncmp(zone, "UT" , 2) ||
3416 !strncmp(zone, "GMT", 3)) {
3418 } else if (strlen(zone3) == 3) {
3419 for (p = ustzstr; *p != '\0'; p += 3) {
3420 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3421 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3422 remoteoffset = iustz * 3600;
3428 } else if (strlen(zone3) == 1) {
3430 case 'Z': remoteoffset = 0; break;
3431 case 'A': remoteoffset = -1; break;
3432 case 'B': remoteoffset = -2; break;
3433 case 'C': remoteoffset = -3; break;
3434 case 'D': remoteoffset = -4; break;
3435 case 'E': remoteoffset = -5; break;
3436 case 'F': remoteoffset = -6; break;
3437 case 'G': remoteoffset = -7; break;
3438 case 'H': remoteoffset = -8; break;
3439 case 'I': remoteoffset = -9; break;
3440 case 'K': remoteoffset = -10; break; /* J is not used */
3441 case 'L': remoteoffset = -11; break;
3442 case 'M': remoteoffset = -12; break;
3443 case 'N': remoteoffset = 1; break;
3444 case 'O': remoteoffset = 2; break;
3445 case 'P': remoteoffset = 3; break;
3446 case 'Q': remoteoffset = 4; break;
3447 case 'R': remoteoffset = 5; break;
3448 case 'S': remoteoffset = 6; break;
3449 case 'T': remoteoffset = 7; break;
3450 case 'U': remoteoffset = 8; break;
3451 case 'V': remoteoffset = 9; break;
3452 case 'W': remoteoffset = 10; break;
3453 case 'X': remoteoffset = 11; break;
3454 case 'Y': remoteoffset = 12; break;
3455 default: remoteoffset = 0; break;
3457 remoteoffset = remoteoffset * 3600;
3461 return remoteoffset;
3464 time_t tzoffset_sec(time_t *now)
3468 struct tm buf1, buf2;
3470 if (now && *now < 0)
3473 gmt = *gmtime_r(now, &buf1);
3474 lt = localtime_r(now, &buf2);
3476 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3478 if (lt->tm_year < gmt.tm_year)
3480 else if (lt->tm_year > gmt.tm_year)
3482 else if (lt->tm_yday < gmt.tm_yday)
3484 else if (lt->tm_yday > gmt.tm_yday)
3487 if (off >= 24 * 60) /* should be impossible */
3488 off = 23 * 60 + 59; /* if not, insert silly value */
3489 if (off <= -24 * 60)
3490 off = -(23 * 60 + 59);
3495 /* calculate timezone offset */
3496 gchar *tzoffset(time_t *now)
3498 static gchar offset_string[6];
3502 struct tm buf1, buf2;
3504 if (now && *now < 0)
3507 gmt = *gmtime_r(now, &buf1);
3508 lt = localtime_r(now, &buf2);
3510 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3512 if (lt->tm_year < gmt.tm_year)
3514 else if (lt->tm_year > gmt.tm_year)
3516 else if (lt->tm_yday < gmt.tm_yday)
3518 else if (lt->tm_yday > gmt.tm_yday)
3526 if (off >= 24 * 60) /* should be impossible */
3527 off = 23 * 60 + 59; /* if not, insert silly value */
3529 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3531 return offset_string;
3534 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
3538 gchar day[4], mon[4];
3539 gint dd, hh, mm, ss, yyyy;
3541 gchar buf2[BUFFSIZE];
3544 lt = localtime_r(&t, &buf1);
3546 sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
3547 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3549 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3550 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
3553 void get_rfc822_date(gchar *buf, gint len)
3555 _get_rfc822_date(buf, len, FALSE);
3558 void get_rfc822_date_hide_tz(gchar *buf, gint len)
3560 _get_rfc822_date(buf, len, TRUE);
3563 void debug_set_mode(gboolean mode)
3568 gboolean debug_get_mode(void)
3573 void debug_print_real(const gchar *format, ...)
3576 gchar buf[BUFFSIZE];
3578 if (!debug_mode) return;
3580 va_start(args, format);
3581 g_vsnprintf(buf, sizeof(buf), format, args);
3588 const char * debug_srcname(const char *file)
3590 const char *s = strrchr (file, '/');
3595 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3597 if (subject == NULL)
3600 subject += subject_get_prefix_length(subject);
3602 return g_hash_table_lookup(subject_table, subject);
3605 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3608 if (subject == NULL || *subject == 0)
3610 subject += subject_get_prefix_length(subject);
3611 g_hash_table_insert(subject_table, subject, data);
3614 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3616 if (subject == NULL)
3619 subject += subject_get_prefix_length(subject);
3620 g_hash_table_remove(subject_table, subject);
3623 static regex_t u_regex;
3624 static gboolean u_init_;
3626 void utils_free_regex(void)
3635 *\brief Check if a string is prefixed with known (combinations)
3636 * of prefixes. The function assumes that each prefix
3637 * is terminated by zero or exactly _one_ space.
3639 *\param str String to check for a prefixes
3641 *\return int Number of chars in the prefix that should be skipped
3642 * for a "clean" subject line. If no prefix was found, 0
3645 int subject_get_prefix_length(const gchar *subject)
3647 /*!< Array with allowable reply prefixes regexps. */
3648 static const gchar * const prefixes[] = {
3649 "Re\\:", /* "Re:" */
3650 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3651 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3652 "Aw\\:", /* "Aw:" (German) */
3653 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3654 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3655 "Fw\\:", /* "Fw:" Forward */
3656 "Fwd\\:", /* "Fwd:" Forward */
3657 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3658 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3659 "Rif\\:", /* "Rif:" (Italian Outlook) */
3660 "Sv\\:", /* "Sv" (Norwegian) */
3661 "Vs\\:", /* "Vs" (Norwegian) */
3662 "Ad\\:", /* "Ad" (Norwegian) */
3663 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3664 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3665 "Re \\:", /* "Re :" (French Yahoo Mail) */
3668 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3672 if (!subject) return 0;
3673 if (!*subject) return 0;
3676 GString *s = g_string_new("");
3678 for (n = 0; n < PREFIXES; n++)
3679 /* Terminate each prefix regexpression by a
3680 * "\ ?" (zero or ONE space), and OR them */
3681 g_string_append_printf(s, "(%s\\ ?)%s",
3686 g_string_prepend(s, "(");
3687 g_string_append(s, ")+"); /* match at least once */
3688 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3691 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3692 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3693 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3694 debug_print("Error compiling regexp %s\n", s->str);
3695 g_string_free(s, TRUE);
3699 g_string_free(s, TRUE);
3703 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3709 static guint g_stricase_hash(gconstpointer gptr)
3711 guint hash_result = 0;
3714 for (str = gptr; str && *str; str++) {
3715 hash_result += toupper(*str);
3721 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3723 const char *str1 = gptr1;
3724 const char *str2 = gptr2;
3726 return !strcasecmp(str1, str2);
3729 gint g_int_compare(gconstpointer a, gconstpointer b)
3731 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3734 gchar *generate_msgid(gchar *buf, gint len, gchar *user_addr)
3742 lt = localtime_r(&t, &buft);
3744 if (user_addr != NULL)
3745 addr = g_strdup_printf(".%s", user_addr);
3746 else if (strlen(buf) != 0)
3747 addr = g_strdup_printf("@%s", buf);
3749 addr = g_strdup_printf("@%s", get_domain_name());
3751 /* Replace all @ but the last one in addr, with underscores.
3752 * RFC 2822 States that msg-id syntax only allows one @.
3754 while (strchr(addr, '@') != NULL && strchr(addr, '@') != strrchr(addr, '@'))
3755 *(strchr(addr, '@')) = '_';
3757 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x%s",
3758 lt->tm_year + 1900, lt->tm_mon + 1,
3759 lt->tm_mday, lt->tm_hour,
3760 lt->tm_min, lt->tm_sec,
3761 (guint) rand(), addr);
3768 quote_cmd_argument()
3770 return a quoted string safely usable in argument of a command.
3772 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3775 gint quote_cmd_argument(gchar * result, guint size,
3785 for(p = path ; * p != '\0' ; p ++) {
3787 if (isalnum((guchar)*p) || (* p == '/')) {
3788 if (remaining > 0) {
3794 result[size - 1] = '\0';
3799 if (remaining >= 2) {
3807 result[size - 1] = '\0';
3812 if (remaining > 0) {
3816 result[size - 1] = '\0';
3830 static void g_node_map_recursive(GNode *node, gpointer data)
3832 GNodeMapData *mapdata = (GNodeMapData *) data;
3834 GNodeMapData newmapdata;
3837 newdata = mapdata->func(node->data, mapdata->data);
3838 if (newdata != NULL) {
3839 newnode = g_node_new(newdata);
3840 g_node_append(mapdata->parent, newnode);
3842 newmapdata.parent = newnode;
3843 newmapdata.func = mapdata->func;
3844 newmapdata.data = mapdata->data;
3846 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3850 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3853 GNodeMapData mapdata;
3855 cm_return_val_if_fail(node != NULL, NULL);
3856 cm_return_val_if_fail(func != NULL, NULL);
3858 root = g_node_new(func(node->data, data));
3860 mapdata.parent = root;
3861 mapdata.func = func;
3862 mapdata.data = data;
3864 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3869 #define HEX_TO_INT(val, hex) \
3873 if ('0' <= c && c <= '9') { \
3875 } else if ('a' <= c && c <= 'f') { \
3876 val = c - 'a' + 10; \
3877 } else if ('A' <= c && c <= 'F') { \
3878 val = c - 'A' + 10; \
3884 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3891 if (hi == -1 || lo == -1)
3894 *out = (hi << 4) + lo;
3898 #define INT_TO_HEX(hex, val) \
3901 hex = '0' + (val); \
3903 hex = 'A' + (val) - 10; \
3906 void get_hex_str(gchar *out, guchar ch)
3910 INT_TO_HEX(hex, ch >> 4);
3912 INT_TO_HEX(hex, ch & 0x0f);
3918 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3920 #define G_PRINT_REF g_print
3924 *\brief Register ref counted pointer. It is based on GBoxed, so should
3925 * work with anything that uses the GType system. The semantics
3926 * are similar to a C++ auto pointer, with the exception that
3927 * C doesn't have automatic closure (calling destructors) when
3928 * exiting a block scope.
3929 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3930 * function directly.
3932 *\return GType A GType type.
3934 GType g_auto_pointer_register(void)
3936 static GType auto_pointer_type;
3937 if (!auto_pointer_type)
3939 g_boxed_type_register_static
3940 ("G_TYPE_AUTO_POINTER",
3941 (GBoxedCopyFunc) g_auto_pointer_copy,
3942 (GBoxedFreeFunc) g_auto_pointer_free);
3943 return auto_pointer_type;
3947 *\brief Structure with g_new() allocated pointer guarded by the
3950 typedef struct AutoPointerRef {
3951 void (*free) (gpointer);
3957 *\brief The auto pointer opaque structure that references the
3958 * pointer guard block.
3960 typedef struct AutoPointer {
3961 AutoPointerRef *ref;
3962 gpointer ptr; /*!< access to protected pointer */
3966 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3970 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3971 * ... when assigning, copying and freeing storage elements
3973 * gtk_list_store_new(N_S_COLUMNS,
3974 * G_TYPE_AUTO_POINTER,
3978 * Template *precious_data = g_new0(Template, 1);
3979 * g_pointer protect = g_auto_pointer_new(precious_data);
3981 * gtk_list_store_set(container, &iter,
3985 * ... the gtk_list_store has copied the pointer and
3986 * ... incremented its reference count, we should free
3987 * ... the auto pointer (in C++ a destructor would do
3988 * ... this for us when leaving block scope)
3990 * g_auto_pointer_free(protect);
3992 * ... gtk_list_store_set() now manages the data. When
3993 * ... *explicitly* requesting a pointer from the list
3994 * ... store, don't forget you get a copy that should be
3995 * ... freed with g_auto_pointer_free() eventually.
3999 *\param pointer Pointer to be guarded.
4001 *\return GAuto * Pointer that should be used in containers with
4004 GAuto *g_auto_pointer_new(gpointer p)
4006 AutoPointerRef *ref;
4012 ref = g_new0(AutoPointerRef, 1);
4013 ptr = g_new0(AutoPointer, 1);
4023 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
4029 *\brief Allocate an autopointer using the passed \a free function to
4030 * free the guarded pointer
4032 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
4039 aptr = g_auto_pointer_new(p);
4040 aptr->ref->free = free_;
4044 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
4046 if (auto_ptr == NULL)
4048 return ((AutoPointer *) auto_ptr)->ptr;
4052 *\brief Copies an auto pointer by. It's mostly not necessary
4053 * to call this function directly, unless you copy/assign
4054 * the guarded pointer.
4056 *\param auto_ptr Auto pointer returned by previous call to
4057 * g_auto_pointer_new_XXX()
4059 *\return gpointer An auto pointer
4061 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
4064 AutoPointerRef *ref;
4067 if (auto_ptr == NULL)
4072 newp = g_new0(AutoPointer, 1);
4075 newp->ptr = ref->pointer;
4079 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4085 *\brief Free an auto pointer
4087 void g_auto_pointer_free(GAuto *auto_ptr)
4090 AutoPointerRef *ref;
4092 if (auto_ptr == NULL)
4098 if (--(ref->cnt) == 0) {
4100 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4102 ref->free(ref->pointer);
4107 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
4112 void replace_returns(gchar *str)
4117 while (strstr(str, "\n")) {
4118 *strstr(str, "\n") = ' ';
4120 while (strstr(str, "\r")) {
4121 *strstr(str, "\r") = ' ';
4125 /* get_uri_part() - retrieves a URI starting from scanpos.
4126 Returns TRUE if succesful */
4127 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
4128 const gchar **bp, const gchar **ep, gboolean hdr)
4131 gint parenthese_cnt = 0;
4133 cm_return_val_if_fail(start != NULL, FALSE);
4134 cm_return_val_if_fail(scanpos != NULL, FALSE);
4135 cm_return_val_if_fail(bp != NULL, FALSE);
4136 cm_return_val_if_fail(ep != NULL, FALSE);
4140 /* find end point of URI */
4141 for (ep_ = scanpos; *ep_ != '\0'; ep_++) {
4142 if (!g_ascii_isgraph(*(const guchar *)ep_) ||
4143 !IS_ASCII(*(const guchar *)ep_) ||
4144 strchr("[]{}<>\"", *ep_)) {
4146 } else if (strchr("(", *ep_)) {
4148 } else if (strchr(")", *ep_)) {
4149 if (parenthese_cnt > 0)
4156 /* no punctuation at end of string */
4158 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
4159 * should pass some URI type to this function and decide on that whether
4160 * to perform punctuation stripping */
4162 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_)", ch))
4164 for (; ep_ - 1 > scanpos + 1 &&
4165 IS_REAL_PUNCT(*(ep_ - 1));
4169 #undef IS_REAL_PUNCT
4176 gchar *make_uri_string(const gchar *bp, const gchar *ep)
4178 while (bp && *bp && g_ascii_isspace(*bp))
4180 return g_strndup(bp, ep - bp);
4183 /* valid mail address characters */
4184 #define IS_RFC822_CHAR(ch) \
4188 !g_ascii_isspace(ch) && \
4189 !strchr("(),;<>\"", (ch)))
4191 /* alphabet and number within 7bit ASCII */
4192 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
4193 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
4195 static GHashTable *create_domain_tab(void)
4198 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
4200 cm_return_val_if_fail(htab, NULL);
4201 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
4202 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
4206 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
4208 const gint MAX_LVL_DOM_NAME_LEN = 6;
4209 gchar buf[MAX_LVL_DOM_NAME_LEN + 1];
4210 const gchar *m = buf + MAX_LVL_DOM_NAME_LEN + 1;
4213 if (last - first > MAX_LVL_DOM_NAME_LEN || first > last)
4216 for (p = buf; p < m && first < last; *p++ = *first++)
4220 return g_hash_table_lookup(tab, buf) != NULL;
4223 /* get_email_part() - retrieves an email address. Returns TRUE if succesful */
4224 gboolean get_email_part(const gchar *start, const gchar *scanpos,
4225 const gchar **bp, const gchar **ep, gboolean hdr)
4227 /* more complex than the uri part because we need to scan back and forward starting from
4228 * the scan position. */
4229 gboolean result = FALSE;
4230 const gchar *bp_ = NULL;
4231 const gchar *ep_ = NULL;
4232 static GHashTable *dom_tab;
4233 const gchar *last_dot = NULL;
4234 const gchar *prelast_dot = NULL;
4235 const gchar *last_tld_char = NULL;
4237 /* the informative part of the email address (describing the name
4238 * of the email address owner) may contain quoted parts. the
4239 * closure stack stores the last encountered quotes. */
4240 gchar closure_stack[128];
4241 gchar *ptr = closure_stack;
4243 cm_return_val_if_fail(start != NULL, FALSE);
4244 cm_return_val_if_fail(scanpos != NULL, FALSE);
4245 cm_return_val_if_fail(bp != NULL, FALSE);
4246 cm_return_val_if_fail(ep != NULL, FALSE);
4249 const gchar *start_quote = NULL;
4250 const gchar *end_quote = NULL;
4252 /* go to the real start */
4253 if (start[0] == ',')
4255 if (start[0] == ';')
4257 while (start[0] == '\n' || start[0] == '\r')
4259 while (start[0] == ' ' || start[0] == '\t')
4264 /* check if there are quotes (to skip , in them) */
4265 if (*start == '"') {
4266 start_quote = start;
4268 end_quote = strstr(start, "\"");
4274 /* skip anything between quotes */
4275 if (start_quote && end_quote) {
4280 /* find end (either , or ; or end of line) */
4281 if (strstr(start, ",") && strstr(start, ";"))
4282 *ep = strstr(start,",") < strstr(start, ";")
4283 ? strstr(start, ",") : strstr(start, ";");
4284 else if (strstr(start, ","))
4285 *ep = strstr(start, ",");
4286 else if (strstr(start, ";"))
4287 *ep = strstr(start, ";");
4289 *ep = start+strlen(start);
4291 /* go back to real start */
4292 if (start_quote && end_quote) {
4293 start = start_quote;
4296 /* check there's still an @ in that, or search
4297 * further if possible */
4298 if (strstr(start, "@") && strstr(start, "@") < *ep)
4300 else if (*ep < start+strlen(start)) {
4303 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
4311 dom_tab = create_domain_tab();
4312 cm_return_val_if_fail(dom_tab, FALSE);
4314 /* scan start of address */
4315 for (bp_ = scanpos - 1;
4316 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
4319 /* TODO: should start with an alnum? */
4321 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
4324 if (bp_ != scanpos) {
4325 /* scan end of address */
4326 for (ep_ = scanpos + 1;
4327 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
4329 prelast_dot = last_dot;
4331 if (*(last_dot + 1) == '.') {
4332 if (prelast_dot == NULL)
4334 last_dot = prelast_dot;
4339 /* TODO: really should terminate with an alnum? */
4340 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
4345 if (last_dot == NULL)
4347 if (last_dot >= ep_)
4348 last_dot = prelast_dot;
4349 if (last_dot == NULL || (scanpos + 1 >= last_dot))
4353 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
4354 if (*last_tld_char == '?')
4357 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
4364 if (!result) return FALSE;
4366 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
4367 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
4368 && IS_RFC822_CHAR(*(ep_ + 3))) {
4369 /* this informative part with an @ in it is
4370 * followed by the email address */
4373 /* go to matching '>' (or next non-rfc822 char, like \n) */
4374 for (; *ep_ != '>' && *ep != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
4377 /* include the bracket */
4378 if (*ep_ == '>') ep_++;
4380 /* include the leading quote */
4388 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
4389 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
4392 /* see if this is <bracketed>; in this case we also scan for the informative part. */
4393 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
4396 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
4397 #define IN_STACK() (ptr > closure_stack)
4398 /* has underrun check */
4399 #define POP_STACK() if(IN_STACK()) --ptr
4400 /* has overrun check */
4401 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
4402 /* has underrun check */
4403 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
4407 /* scan for the informative part. */
4408 for (bp_ -= 2; bp_ >= start; bp_--) {
4409 /* if closure on the stack keep scanning */
4410 if (PEEK_STACK() == *bp_) {
4414 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
4419 /* if nothing in the closure stack, do the special conditions
4420 * the following if..else expression simply checks whether
4421 * a token is acceptable. if not acceptable, the clause
4422 * should terminate the loop with a 'break' */
4423 if (!PEEK_STACK()) {
4425 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
4426 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
4427 /* hyphens are allowed, but only in
4429 } else if (strchr(" \"'", *bp_)) {
4430 /* but anything not being a punctiation
4433 break; /* anything else is rejected */
4440 /* scan forward (should start with an alnum) */
4441 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
4457 #undef IS_ASCII_ALNUM
4458 #undef IS_RFC822_CHAR
4460 gchar *make_email_string(const gchar *bp, const gchar *ep)
4462 /* returns a mailto: URI; mailto: is also used to detect the
4463 * uri type later on in the button_pressed signal handler */
4468 tmp = g_strndup(bp, ep - bp);
4470 /* If there is a colon in the username part of the address,
4471 * we're dealing with an URI for some other protocol - do
4472 * not prefix with mailto: in such case. */
4473 colon = strchr(tmp, ':');
4474 at = strchr(tmp, '@');
4475 if (colon != NULL && at != NULL && colon < at) {
4478 result = g_strconcat("mailto:", tmp, NULL);
4485 gchar *make_http_string(const gchar *bp, const gchar *ep)
4487 /* returns an http: URI; */
4491 while (bp && *bp && g_ascii_isspace(*bp))
4493 tmp = g_strndup(bp, ep - bp);
4494 result = g_strconcat("http://", tmp, NULL);
4500 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
4502 FILE *fp = g_fopen(path, "rb");
4503 gchar buf[BUFFSIZE];
4504 gchar *result = NULL;
4507 while (fgets(buf, sizeof (buf), fp) != NULL) {
4508 gchar **parts = g_strsplit(buf, ";", 3);
4509 gchar *trimmed = parts[0];
4510 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4512 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4513 trimmed[strlen(trimmed)-1] = '\0';
4515 if (!strcmp(trimmed, type)) {
4516 gboolean needsterminal = FALSE;
4517 if (parts[2] && strstr(parts[2], "needsterminal")) {
4518 needsterminal = TRUE;
4520 if (parts[2] && strstr(parts[2], "test=")) {
4521 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
4522 gchar *testcmd = orig_testcmd;
4523 if (strstr(testcmd,";"))
4524 *(strstr(testcmd,";")) = '\0';
4525 while (testcmd[0] == ' ' || testcmd[0] == '\t')
4527 while (testcmd[strlen(testcmd)-1] == '\n')
4528 testcmd[strlen(testcmd)-1] = '\0';
4529 while (testcmd[strlen(testcmd)-1] == '\r')
4530 testcmd[strlen(testcmd)-1] = '\0';
4531 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
4532 testcmd[strlen(testcmd)-1] = '\0';
4534 if (strstr(testcmd, "%s")) {
4535 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
4536 gint res = system(tmp);
4538 g_free(orig_testcmd);
4545 gint res = system(testcmd);
4546 g_free(orig_testcmd);
4556 while (trimmed[0] == ' ' || trimmed[0] == '\t')
4558 while (trimmed[strlen(trimmed)-1] == '\n')
4559 trimmed[strlen(trimmed)-1] = '\0';
4560 while (trimmed[strlen(trimmed)-1] == '\r')
4561 trimmed[strlen(trimmed)-1] = '\0';
4562 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
4563 trimmed[strlen(trimmed)-1] = '\0';
4564 result = g_strdup(trimmed);
4567 if (needsterminal) {
4568 gchar *tmp = g_strdup_printf("xterm -e %s", result);
4579 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
4581 gchar *result = NULL;
4585 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4586 result = mailcap_get_command_in_file(path, type, file_to_open);
4590 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
4594 void mailcap_update_default(const gchar *type, const gchar *command)
4596 gchar *path = NULL, *outpath = NULL;
4597 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
4598 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
4599 FILE *fp = g_fopen(path, "rb");
4601 gchar buf[BUFFSIZE];
4602 gboolean err = FALSE;
4605 fp = g_fopen(path, "a");
4607 g_warning("failed to create file %s", path);
4612 fp = g_freopen(path, "rb", fp);
4614 g_warning("failed to reopen file %s", path);
4621 outfp = g_fopen(outpath, "wb");
4623 g_warning("failed to create file %s", outpath);
4629 while (fp && fgets(buf, sizeof (buf), fp) != NULL) {
4630 gchar **parts = g_strsplit(buf, ";", 3);
4631 gchar *trimmed = parts[0];
4632 while (trimmed[0] == ' ')
4634 while (trimmed[strlen(trimmed)-1] == ' ')
4635 trimmed[strlen(trimmed)-1] = '\0';
4637 if (!strcmp(trimmed, type)) {
4642 if(fputs(buf, outfp) == EOF) {
4649 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4655 if (fclose(outfp) == EOF)
4659 g_rename(outpath, path);
4665 gint copy_dir(const gchar *src, const gchar *dst)
4670 if ((dir = g_dir_open(src, 0, NULL)) == NULL) {
4671 g_warning("failed to open directory: %s", src);
4675 if (make_dir(dst) < 0)
4678 while ((name = g_dir_read_name(dir)) != NULL) {
4679 gchar *old_file, *new_file;
4680 old_file = g_strconcat(src, G_DIR_SEPARATOR_S, name, NULL);
4681 new_file = g_strconcat(dst, G_DIR_SEPARATOR_S, name, NULL);
4682 debug_print("copying: %s -> %s\n", old_file, new_file);
4683 if (g_file_test(old_file, G_FILE_TEST_IS_REGULAR)) {
4684 gint r = copy_file(old_file, new_file, TRUE);
4691 /* Windows has no symlinks. Or well, Vista seems to
4692 have something like this but the semantics might be
4693 different. Thus we don't use it under Windows. */
4694 else if (g_file_test(old_file, G_FILE_TEST_IS_SYMLINK)) {
4695 GError *error = NULL;
4697 gchar *target = g_file_read_link(old_file, &error);
4699 r = symlink(target, new_file);
4706 #endif /*G_OS_WIN32*/
4707 else if (g_file_test(old_file, G_FILE_TEST_IS_DIR)) {
4708 gint r = copy_dir(old_file, new_file);
4719 /* crude test to see if a file is an email. */
4720 gboolean file_is_email (const gchar *filename)
4726 if (filename == NULL)
4728 if ((fp = g_fopen(filename, "rb")) == NULL)
4730 while (i < 60 && score < 3
4731 && fgets(buffer, sizeof (buffer), fp) != NULL) {
4732 if (!strncmp(buffer, "From:", strlen("From:")))
4734 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4736 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4738 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4743 return (score >= 3);
4746 gboolean sc_g_list_bigger(GList *list, gint max)
4750 while (cur && i <= max+1) {
4757 gboolean sc_g_slist_bigger(GSList *list, gint max)
4761 while (cur && i <= max+1) {
4768 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4769 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4770 NULL, NULL, NULL, NULL, NULL, NULL};
4771 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4772 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4773 NULL, NULL, NULL, NULL, NULL, NULL};
4775 gint daynames_len[] = {0,0,0,0,0,0,0};
4776 gint monthnames_len[] = {0,0,0,0,0,0,
4778 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4779 gint s_monthnames_len[] = {0,0,0,0,0,0,
4781 const gchar *s_am_up = NULL;
4782 const gchar *s_pm_up = NULL;
4783 const gchar *s_am_low = NULL;
4784 const gchar *s_pm_low = NULL;
4786 gint s_am_up_len = 0;
4787 gint s_pm_up_len = 0;
4788 gint s_am_low_len = 0;
4789 gint s_pm_low_len = 0;
4791 static gboolean time_names_init_done = FALSE;
4793 static void init_time_names(void)
4797 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4798 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4799 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4800 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4801 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4802 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4803 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4805 monthnames[0] = C_("Complete month name for use by strftime", "January");
4806 monthnames[1] = C_("Complete month name for use by strftime", "February");
4807 monthnames[2] = C_("Complete month name for use by strftime", "March");
4808 monthnames[3] = C_("Complete month name for use by strftime", "April");
4809 monthnames[4] = C_("Complete month name for use by strftime", "May");
4810 monthnames[5] = C_("Complete month name for use by strftime", "June");
4811 monthnames[6] = C_("Complete month name for use by strftime", "July");
4812 monthnames[7] = C_("Complete month name for use by strftime", "August");
4813 monthnames[8] = C_("Complete month name for use by strftime", "September");
4814 monthnames[9] = C_("Complete month name for use by strftime", "October");
4815 monthnames[10] = C_("Complete month name for use by strftime", "November");
4816 monthnames[11] = C_("Complete month name for use by strftime", "December");
4818 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4819 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4820 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4821 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4822 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4823 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4824 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4826 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4827 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4828 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4829 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4830 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4831 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4832 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4833 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4834 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4835 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4836 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4837 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4839 for (i = 0; i < 7; i++) {
4840 daynames_len[i] = strlen(daynames[i]);
4841 s_daynames_len[i] = strlen(s_daynames[i]);
4843 for (i = 0; i < 12; i++) {
4844 monthnames_len[i] = strlen(monthnames[i]);
4845 s_monthnames_len[i] = strlen(s_monthnames[i]);
4848 s_am_up = C_("For use by strftime (morning)", "AM");
4849 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4850 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4851 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4853 s_am_up_len = strlen(s_am_up);
4854 s_pm_up_len = strlen(s_pm_up);
4855 s_am_low_len = strlen(s_am_low);
4856 s_pm_low_len = strlen(s_pm_low);
4858 time_names_init_done = TRUE;
4861 #define CHECK_SIZE() { \
4862 total_done += len; \
4863 if (total_done >= buflen) { \
4864 buf[buflen-1] = '\0'; \
4869 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4871 gchar *curpos = buf;
4872 gint total_done = 0;
4873 gchar subbuf[64], subfmt[64];
4874 static time_t last_tzset = (time_t)0;
4876 if (!time_names_init_done)
4879 if (format == NULL || lt == NULL)
4882 if (last_tzset != time(NULL)) {
4884 last_tzset = time(NULL);
4887 if (*format == '%') {
4888 gint len = 0, tmp = 0;
4892 len = 1; CHECK_SIZE();
4896 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4897 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4900 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4901 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4905 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4906 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4909 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4910 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4913 strftime(subbuf, 64, "%c", lt);
4914 len = strlen(subbuf); CHECK_SIZE();
4915 strncpy2(curpos, subbuf, buflen - total_done);
4918 total_done += 2; CHECK_SIZE();
4919 tmp = (lt->tm_year + 1900)/100;
4920 *curpos++ = '0'+(tmp / 10);
4921 *curpos++ = '0'+(tmp % 10);
4924 total_done += 2; CHECK_SIZE();
4925 *curpos++ = '0'+(lt->tm_mday / 10);
4926 *curpos++ = '0'+(lt->tm_mday % 10);
4929 total_done += 8; CHECK_SIZE();
4930 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4931 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4933 *curpos++ = '0'+(lt->tm_mday / 10);
4934 *curpos++ = '0'+(lt->tm_mday % 10);
4936 tmp = lt->tm_year%100;
4937 *curpos++ = '0'+(tmp / 10);
4938 *curpos++ = '0'+(tmp % 10);
4941 len = 2; CHECK_SIZE();
4942 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4945 len = 10; CHECK_SIZE();
4946 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4947 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4950 total_done += 2; CHECK_SIZE();
4951 *curpos++ = '0'+(lt->tm_hour / 10);
4952 *curpos++ = '0'+(lt->tm_hour % 10);
4955 total_done += 2; CHECK_SIZE();
4961 *curpos++ = '0'+(tmp / 10);
4962 *curpos++ = '0'+(tmp % 10);
4965 len = 3; CHECK_SIZE();
4966 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4969 len = 2; CHECK_SIZE();
4970 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4973 len = 2; CHECK_SIZE();
4979 snprintf(curpos, buflen - total_done, "%2d", tmp);
4982 total_done += 2; CHECK_SIZE();
4983 tmp = lt->tm_mon + 1;
4984 *curpos++ = '0'+(tmp / 10);
4985 *curpos++ = '0'+(tmp % 10);
4988 total_done += 2; CHECK_SIZE();
4989 *curpos++ = '0'+(lt->tm_min / 10);
4990 *curpos++ = '0'+(lt->tm_min % 10);
4993 len = 1; CHECK_SIZE();
4997 if (lt->tm_hour >= 12) {
4998 len = s_pm_up_len; CHECK_SIZE();
4999 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
5001 len = s_am_up_len; CHECK_SIZE();
5002 snprintf(curpos, buflen-total_done, "%s", s_am_up);
5006 if (lt->tm_hour >= 12) {
5007 len = s_pm_low_len; CHECK_SIZE();
5008 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
5010 len = s_am_low_len; CHECK_SIZE();
5011 snprintf(curpos, buflen-total_done, "%s", s_am_low);
5015 strftime(subbuf, 64, "%r", lt);
5016 len = strlen(subbuf); CHECK_SIZE();
5017 strncpy2(curpos, subbuf, buflen - total_done);
5020 total_done += 5; CHECK_SIZE();
5021 *curpos++ = '0'+(lt->tm_hour / 10);
5022 *curpos++ = '0'+(lt->tm_hour % 10);
5024 *curpos++ = '0'+(lt->tm_min / 10);
5025 *curpos++ = '0'+(lt->tm_min % 10);
5028 snprintf(subbuf, 64, "%lld", (long long)mktime(lt));
5029 len = strlen(subbuf); CHECK_SIZE();
5030 strncpy2(curpos, subbuf, buflen - total_done);
5033 total_done += 2; CHECK_SIZE();
5034 *curpos++ = '0'+(lt->tm_sec / 10);
5035 *curpos++ = '0'+(lt->tm_sec % 10);
5038 len = 1; CHECK_SIZE();
5042 total_done += 8; CHECK_SIZE();
5043 *curpos++ = '0'+(lt->tm_hour / 10);
5044 *curpos++ = '0'+(lt->tm_hour % 10);
5046 *curpos++ = '0'+(lt->tm_min / 10);
5047 *curpos++ = '0'+(lt->tm_min % 10);
5049 *curpos++ = '0'+(lt->tm_sec / 10);
5050 *curpos++ = '0'+(lt->tm_sec % 10);
5053 len = 1; CHECK_SIZE();
5054 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
5057 len = 1; CHECK_SIZE();
5058 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
5061 strftime(subbuf, 64, "%x", lt);
5062 len = strlen(subbuf); CHECK_SIZE();
5063 strncpy2(curpos, subbuf, buflen - total_done);
5066 strftime(subbuf, 64, "%X", lt);
5067 len = strlen(subbuf); CHECK_SIZE();
5068 strncpy2(curpos, subbuf, buflen - total_done);
5071 total_done += 2; CHECK_SIZE();
5072 tmp = lt->tm_year%100;
5073 *curpos++ = '0'+(tmp / 10);
5074 *curpos++ = '0'+(tmp % 10);
5077 len = 4; CHECK_SIZE();
5078 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
5088 /* let these complicated ones be done with the libc */
5089 snprintf(subfmt, 64, "%%%c", *format);
5090 strftime(subbuf, 64, subfmt, lt);
5091 len = strlen(subbuf); CHECK_SIZE();
5092 strncpy2(curpos, subbuf, buflen - total_done);
5096 /* let these complicated modifiers be done with the libc */
5097 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
5098 strftime(subbuf, 64, subfmt, lt);
5099 len = strlen(subbuf); CHECK_SIZE();
5100 strncpy2(curpos, subbuf, buflen - total_done);
5104 g_warning("format error (%c)", *format);
5111 int len = 1; CHECK_SIZE();
5112 *curpos++ = *format++;
5119 gboolean prefs_common_get_use_shred(void);
5123 #define WEXITSTATUS(x) (x)
5126 int claws_unlink(const gchar *filename)
5129 static int found_shred = -1;
5130 static const gchar *args[4];
5132 if (filename == NULL)
5135 if (prefs_common_get_use_shred()) {
5136 if (found_shred == -1) {
5138 args[0] = g_find_program_in_path("shred");
5139 debug_print("found shred: %s\n", args[0]);
5140 found_shred = (args[0] != NULL) ? 1:0;
5144 if (found_shred == 1) {
5145 if (g_stat(filename, &s) == 0 && S_ISREG(s.st_mode)) {
5146 if (s.st_nlink == 1) {
5149 g_spawn_sync(NULL, (gchar **)args, NULL, 0,
5150 NULL, NULL, NULL, NULL, &status, NULL);
5151 debug_print("%s %s exited with status %d\n",
5152 args[0], filename, WEXITSTATUS(status));
5153 if (truncate(filename, 0) < 0)
5154 g_warning("couln't truncate: %s", filename);
5159 return g_unlink(filename);
5162 GMutex *cm_mutex_new(void) {
5163 #if GLIB_CHECK_VERSION(2,32,0)
5164 GMutex *m = g_new0(GMutex, 1);
5168 return g_mutex_new();
5172 void cm_mutex_free(GMutex *mutex) {
5173 #if GLIB_CHECK_VERSION(2,32,0)
5174 g_mutex_clear(mutex);
5177 g_mutex_free(mutex);
5181 static gchar *canonical_list_to_file(GSList *list)
5183 GString *result = g_string_new(NULL);
5184 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
5189 result = g_string_append(result, G_DIR_SEPARATOR_S);
5191 if (pathlist->data) {
5192 const gchar *root = (gchar *)pathlist->data;
5193 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
5195 /* drive - don't prepend dir separator */
5197 result = g_string_append(result, G_DIR_SEPARATOR_S);
5202 for (cur = pathlist; cur; cur = cur->next) {
5203 result = g_string_append(result, (gchar *)cur->data);
5205 result = g_string_append(result, G_DIR_SEPARATOR_S);
5207 g_slist_free(pathlist);
5210 g_string_free(result, FALSE);
5215 static GSList *cm_split_path(const gchar *filename, int depth)
5218 GSList *canonical_parts = NULL;
5221 gboolean follow_symlinks = TRUE;
5227 errno = EINVAL; /* can't happen, no symlink handling */
5232 if (!g_path_is_absolute(filename)) {
5237 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
5239 for (i = 0; path_parts[i] != NULL; i++) {
5240 if (!strcmp(path_parts[i], ""))
5242 if (!strcmp(path_parts[i], "."))
5244 else if (!strcmp(path_parts[i], "..")) {
5249 else /* Remove the last inserted element */
5251 g_slist_delete_link(canonical_parts,
5256 canonical_parts = g_slist_prepend(canonical_parts,
5257 g_strdup(path_parts[i]));
5259 tmp_path = canonical_list_to_file(canonical_parts);
5261 if(g_stat(tmp_path, &st) < 0) {
5262 if (errno == ENOENT) {
5264 follow_symlinks = FALSE;
5268 slist_free_strings_full(canonical_parts);
5269 g_strfreev(path_parts);
5275 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
5276 GError *error = NULL;
5277 gchar *target = g_file_read_link(tmp_path, &error);
5279 if (!g_path_is_absolute(target)) {
5280 /* remove the last inserted element */
5282 g_slist_delete_link(canonical_parts,
5284 /* add the target */
5285 canonical_parts = g_slist_prepend(canonical_parts,
5289 /* and get the new target */
5290 target = canonical_list_to_file(canonical_parts);
5293 /* restart from absolute target */
5294 slist_free_strings_full(canonical_parts);
5295 canonical_parts = NULL;
5297 canonical_parts = cm_split_path(target, depth + 1);
5299 g_error_free(error);
5300 if (canonical_parts == NULL) {
5302 g_strfreev(path_parts);
5311 g_strfreev(path_parts);
5312 return canonical_parts;
5316 * Canonicalize a filename, resolving symlinks along the way.
5317 * Returns a negative errno in case of error.
5319 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
5320 GSList *canonical_parts;
5321 gboolean is_absolute;
5323 if (filename == NULL)
5325 if (canonical_name == NULL)
5327 *canonical_name = NULL;
5329 is_absolute = g_path_is_absolute(filename);
5331 /* Always work on absolute filenames. */
5332 gchar *cur = g_get_current_dir();
5333 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
5336 canonical_parts = cm_split_path(absolute_filename, 0);
5337 g_free(absolute_filename);
5340 canonical_parts = cm_split_path(filename, 0);
5342 if (canonical_parts == NULL)
5345 *canonical_name = canonical_list_to_file(canonical_parts);
5346 slist_free_strings_full(canonical_parts);
5350 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
5351 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
5353 gchar *tmp = g_base64_decode(text, out_len);
5354 gchar *out = g_strndup(tmp, *out_len);
5358 if (strlen(out) != *out_len) {
5359 g_warning ("strlen(out) %zd != *out_len %" G_GSIZE_FORMAT, strlen(out), *out_len);
5365 #if !GLIB_CHECK_VERSION(2, 30, 0)
5368 * @str: a UTF-8 encoded string
5369 * @start_pos: a character offset within @str
5370 * @end_pos: another character offset within @str
5372 * Copies a substring out of a UTF-8 encoded string.
5373 * The substring will contain @end_pos - @start_pos
5376 * Returns: a newly allocated copy of the requested
5377 * substring. Free with g_free() when no longer needed.
5382 g_utf8_substring (const gchar *str,
5386 gchar *start, *end, *out;
5388 start = g_utf8_offset_to_pointer (str, start_pos);
5389 end = g_utf8_offset_to_pointer (start, end_pos - start_pos);
5391 out = g_malloc (end - start + 1);
5392 memcpy (out, start, end - start);
5393 out[end - start] = 0;
5399 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
5400 * It is up to the caller to make sure there is at least count bytes
5401 * available at buf. */
5403 get_random_bytes(void *buf, size_t count)
5405 /* Open our prng source. */
5406 #if defined G_OS_WIN32
5409 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
5410 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
5411 debug_print("Could not acquire a CSP handle.\n");
5418 rnd = open("/dev/urandom", O_RDONLY);
5420 perror("open on /dev/urandom");
5421 debug_print("Could not open /dev/urandom.\n");
5426 /* Read data from the source into buf. */
5427 #if defined G_OS_WIN32
5428 if (!CryptGenRandom(rnd, count, buf)) {
5429 debug_print("Could not read %d random bytes.\n", count);
5430 CryptReleaseContext(rnd, 0);
5434 ret = read(rnd, buf, count);
5436 perror("read from /dev/urandom");
5437 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
5443 /* Close the prng source. */
5444 #if defined G_OS_WIN32
5445 CryptReleaseContext(rnd, 0);