2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2012 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/>.
22 #include "claws-features.h"
29 #include <glib/gi18n.h>
39 #include <sys/param.h>
41 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
49 #include <sys/types.h>
51 # include <sys/wait.h>
58 #include <sys/utsname.h>
72 # include <tablet-browser-interface.h>
74 # include <osso-browser-interface.h>
80 #include "../codeconv.h"
84 static gboolean debug_mode = FALSE;
86 static GSList *tempfiles=NULL;
89 /* Return true if we are running as root. This function should beused
90 instead of getuid () == 0. */
91 gboolean superuser_p (void)
94 return w32_is_administrator ();
102 #if !GLIB_CHECK_VERSION(2, 7, 0) && !defined(G_OS_UNIX)
103 gint g_chdir(const gchar *path)
106 if (G_WIN32_HAVE_WIDECHAR_API()) {
111 wpath = g_utf8_to_utf16(path, -1, NULL, NULL, NULL);
117 retval = _wchdir(wpath);
129 cp_path = g_locale_from_utf8(path, -1, NULL, NULL, NULL);
130 if (cp_path == NULL) {
135 retval = chdir(cp_path);
148 gint g_chmod(const gchar *path, gint mode)
151 if (G_WIN32_HAVE_WIDECHAR_API()) {
156 wpath = g_utf8_to_utf16(path, -1, NULL, NULL, NULL);
162 retval = _wchmod(wpath, mode);
174 cp_path = g_locale_from_utf8(path, -1, NULL, NULL, NULL);
175 if (cp_path == NULL) {
180 retval = chmod(cp_path, mode);
189 return chmod(path, mode);
193 FILE* g_fopen(const gchar *filename, const gchar *mode)
196 char *name = g_win32_locale_filename_from_utf8(filename);
197 FILE* fp = fopen(name, mode);
201 return fopen(filename, mode);
204 int g_open(const gchar *filename, int flags, int mode)
207 char *name = g_win32_locale_filename_from_utf8(filename);
208 int fd = open(name, flags, mode);
212 return open(filename, flags, mode);
215 #endif /* GLIB_CHECK_VERSION && G_OS_UNIX */
219 gint mkstemp_name(gchar *template, gchar **name_used)
221 static gulong count=0; /* W32-_mktemp only supports up to 27
225 *name_used = g_strdup_printf("%s.%ld",_mktemp(template),count++);
226 tmpfd = g_open (*name_used, (O_CREAT | O_RDWR | O_BINARY),
227 (S_IRUSR | S_IWUSR));
229 tempfiles=g_slist_append(tempfiles, g_strdup(*name_used));
231 perror(g_strdup_printf("cant create %s",*name_used));
237 #endif /* G_OS_WIN32 */
240 gint mkstemp(gchar *template)
243 gint res = mkstemp_name(template, &dummyname);
247 #endif /* G_OS_WIN32 */
249 void list_free_strings(GList *list)
251 list = g_list_first(list);
253 while (list != NULL) {
259 void slist_free_strings(GSList *list)
261 while (list != NULL) {
267 void slist_free_strings_full(GSList *list)
269 #if GLIB_CHECK_VERSION(2,28,0)
270 g_slist_free_full(list, (GDestroyNotify)g_free);
272 while (list != NULL) {
280 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
285 void hash_free_strings(GHashTable *table)
287 g_hash_table_foreach(table, hash_free_strings_func, NULL);
290 gint str_case_equal(gconstpointer v, gconstpointer v2)
292 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
295 guint str_case_hash(gconstpointer key)
297 const gchar *p = key;
301 h = g_ascii_tolower(h);
302 for (p += 1; *p != '\0'; p++)
303 h = (h << 5) - h + g_ascii_tolower(*p);
309 void ptr_array_free_strings(GPtrArray *array)
314 cm_return_if_fail(array != NULL);
316 for (i = 0; i < array->len; i++) {
317 str = g_ptr_array_index(array, i);
322 gint to_number(const gchar *nstr)
324 register const gchar *p;
326 if (*nstr == '\0') return -1;
328 for (p = nstr; *p != '\0'; p++)
329 if (!g_ascii_isdigit(*p)) return -1;
334 /* convert integer into string,
335 nstr must be not lower than 11 characters length */
336 gchar *itos_buf(gchar *nstr, gint n)
338 g_snprintf(nstr, 11, "%d", n);
342 /* convert integer into string */
345 static gchar nstr[11];
347 return itos_buf(nstr, n);
350 #define divide(num,divisor,i,d) \
352 i = num >> divisor; \
353 d = num & ((1<<divisor)-1); \
354 d = (d*100) >> divisor; \
359 * \brief Convert a given size in bytes in a human-readable string
361 * \param size The size expressed in bytes to convert in string
362 * \return The string that respresents the size in an human-readable way
364 gchar *to_human_readable(goffset size)
366 static gchar str[14];
367 static gchar *b_format = NULL, *kb_format = NULL,
368 *mb_format = NULL, *gb_format = NULL;
369 register int t = 0, r = 0;
370 if (b_format == NULL) {
372 kb_format = _("%d.%02dKB");
373 mb_format = _("%d.%02dMB");
374 gb_format = _("%.2fGB");
377 if (size < (goffset)1024) {
378 g_snprintf(str, sizeof(str), b_format, (gint)size);
380 } else if (size >> 10 < (goffset)1024) {
381 divide(size, 10, t, r);
382 g_snprintf(str, sizeof(str), kb_format, t, r);
384 } else if (size >> 20 < (goffset)1024) {
385 divide(size, 20, t, r);
386 g_snprintf(str, sizeof(str), mb_format, t, r);
389 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
394 /* strcmp with NULL-checking */
395 gint strcmp2(const gchar *s1, const gchar *s2)
397 if (s1 == NULL || s2 == NULL)
400 return strcmp(s1, s2);
402 /* strstr with NULL-checking */
403 gchar *strstr2(const gchar *s1, const gchar *s2)
405 if (s1 == NULL || s2 == NULL)
408 return strstr(s1, s2);
411 gint path_cmp(const gchar *s1, const gchar *s2)
416 gchar *s1buf, *s2buf;
419 if (s1 == NULL || s2 == NULL) return -1;
420 if (*s1 == '\0' || *s2 == '\0') return -1;
423 s1buf = g_strdup (s1);
424 s2buf = g_strdup (s2);
425 subst_char (s1buf, '/', G_DIR_SEPARATOR);
426 subst_char (s2buf, '/', G_DIR_SEPARATOR);
429 #endif /* !G_OS_WIN32 */
434 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
435 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
437 rc = strncmp(s1, s2, MAX(len1, len2));
441 #endif /* !G_OS_WIN32 */
445 /* remove trailing return code */
446 gchar *strretchomp(gchar *str)
450 if (!*str) return str;
452 for (s = str + strlen(str) - 1;
453 s >= str && (*s == '\n' || *s == '\r');
460 /* remove trailing character */
461 gchar *strtailchomp(gchar *str, gchar tail_char)
465 if (!*str) return str;
466 if (tail_char == '\0') return str;
468 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
474 /* remove CR (carriage return) */
475 gchar *strcrchomp(gchar *str)
479 if (!*str) return str;
481 s = str + strlen(str) - 1;
482 if (*s == '\n' && s > str && *(s - 1) == '\r') {
490 gint file_strip_crs(const gchar *file)
492 FILE *fp = NULL, *outfp = NULL;
494 gchar *out = get_tmp_file();
498 fp = g_fopen(file, "rb");
502 outfp = g_fopen(out, "wb");
508 while (fgets(buf, sizeof (buf), fp) != NULL) {
510 if (fputs(buf, outfp) == EOF) {
518 if (fclose(outfp) == EOF) {
522 if (move_file(out, file, TRUE) < 0)
534 /* Similar to `strstr' but this function ignores the case of both strings. */
535 gchar *strcasestr(const gchar *haystack, const gchar *needle)
537 size_t haystack_len = strlen(haystack);
539 return strncasestr(haystack, haystack_len, needle);
542 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
544 register size_t needle_len;
546 needle_len = strlen(needle);
548 if (haystack_len < needle_len || needle_len == 0)
551 while (haystack_len >= needle_len) {
552 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
553 return (gchar *)haystack;
563 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
564 gconstpointer needle, size_t needlelen)
566 const gchar *haystack_ = (const gchar *)haystack;
567 const gchar *needle_ = (const gchar *)needle;
568 const gchar *haystack_cur = (const gchar *)haystack;
569 size_t haystack_left = haystacklen;
572 return memchr(haystack_, *needle_, haystacklen);
574 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
576 if (haystacklen - (haystack_cur - haystack_) < needlelen)
578 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
579 return (gpointer)haystack_cur;
582 haystack_left = haystacklen - (haystack_cur - haystack_);
589 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
590 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
592 register const gchar *s = src;
593 register gchar *d = dest;
603 /* Examine if next block is non-ASCII string */
604 gboolean is_next_nonascii(const gchar *s)
608 /* skip head space */
609 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
611 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
612 if (*(guchar *)p > 127 || *(guchar *)p < 32)
619 gint get_next_word_len(const gchar *s)
623 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
629 static void trim_subject_for_compare(gchar *str)
633 eliminate_parenthesis(str, '[', ']');
634 eliminate_parenthesis(str, '(', ')');
637 srcp = str + subject_get_prefix_length(str);
639 memmove(str, srcp, strlen(srcp) + 1);
642 static void trim_subject_for_sort(gchar *str)
648 srcp = str + subject_get_prefix_length(str);
650 memmove(str, srcp, strlen(srcp) + 1);
653 /* compare subjects */
654 gint subject_compare(const gchar *s1, const gchar *s2)
658 if (!s1 || !s2) return -1;
659 if (!*s1 || !*s2) return -1;
661 Xstrdup_a(str1, s1, return -1);
662 Xstrdup_a(str2, s2, return -1);
664 trim_subject_for_compare(str1);
665 trim_subject_for_compare(str2);
667 if (!*str1 || !*str2) return -1;
669 return strcmp(str1, str2);
672 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
676 if (!s1 || !s2) return -1;
678 Xstrdup_a(str1, s1, return -1);
679 Xstrdup_a(str2, s2, return -1);
681 trim_subject_for_sort(str1);
682 trim_subject_for_sort(str2);
684 return g_utf8_collate(str1, str2);
687 void trim_subject(gchar *str)
689 register gchar *srcp;
695 srcp = str + subject_get_prefix_length(str);
700 } else if (*srcp == '(') {
712 else if (*srcp == cl)
719 while (g_ascii_isspace(*srcp)) srcp++;
720 memmove(str, srcp, strlen(srcp) + 1);
723 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
725 register gchar *srcp, *destp;
730 while ((destp = strchr(destp, op))) {
736 else if (*srcp == cl)
742 while (g_ascii_isspace(*srcp)) srcp++;
743 memmove(destp, srcp, strlen(srcp) + 1);
747 void extract_parenthesis(gchar *str, gchar op, gchar cl)
749 register gchar *srcp, *destp;
754 while ((srcp = strchr(destp, op))) {
757 memmove(destp, srcp + 1, strlen(srcp));
762 else if (*destp == cl)
774 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
777 register gchar *srcp, *destp;
779 gboolean in_quote = FALSE;
783 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
786 memmove(destp, srcp + 1, strlen(srcp));
789 if (*destp == op && !in_quote)
791 else if (*destp == cl && !in_quote)
793 else if (*destp == quote_chr)
805 void extract_quote(gchar *str, gchar quote_chr)
809 if ((str = strchr(str, quote_chr))) {
811 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
812 memmove(p - 1, p, strlen(p) + 1);
817 memmove(str, str + 1, p - str);
822 void eliminate_address_comment(gchar *str)
824 register gchar *srcp, *destp;
829 while ((destp = strchr(destp, '"'))) {
830 if ((srcp = strchr(destp + 1, '"'))) {
835 while (g_ascii_isspace(*srcp)) srcp++;
836 memmove(destp, srcp, strlen(srcp) + 1);
846 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
852 else if (*srcp == ')')
858 while (g_ascii_isspace(*srcp)) srcp++;
859 memmove(destp, srcp, strlen(srcp) + 1);
863 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
865 gboolean in_quote = FALSE;
868 if (*str == c && !in_quote)
870 if (*str == quote_chr)
878 void extract_address(gchar *str)
880 eliminate_address_comment(str);
881 if (strchr_with_skip_quote(str, '"', '<'))
882 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
886 void extract_list_id_str(gchar *str)
888 if (strchr_with_skip_quote(str, '"', '<'))
889 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
893 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
898 if (!str) return addr_list;
900 Xstrdup_a(work, str, return addr_list);
903 eliminate_address_comment(work);
906 while (workp && *workp) {
909 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
915 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
916 extract_parenthesis_with_skip_quote
917 (workp, '"', '<', '>');
921 addr_list = g_slist_append(addr_list, g_strdup(workp));
929 GSList *address_list_append(GSList *addr_list, const gchar *str)
931 return address_list_append_real(addr_list, str, TRUE);
934 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
936 return address_list_append_real(addr_list, str, FALSE);
939 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
943 if (!str) return msgid_list;
946 while (strp && *strp) {
947 const gchar *start, *end;
950 if ((start = strchr(strp, '<')) != NULL) {
951 end = strchr(start + 1, '>');
956 msgid = g_strndup(start + 1, end - start - 1);
959 msgid_list = g_slist_prepend(msgid_list, msgid);
969 GSList *references_list_append(GSList *msgid_list, const gchar *str)
973 list = references_list_prepend(NULL, str);
974 list = g_slist_reverse(list);
975 msgid_list = g_slist_concat(msgid_list, list);
980 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
985 if (!str) return group_list;
987 Xstrdup_a(work, str, return group_list);
991 while (workp && *workp) {
994 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
1002 group_list = g_slist_append(group_list,
1011 GList *add_history(GList *list, const gchar *str)
1016 cm_return_val_if_fail(str != NULL, list);
1018 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
1021 list = g_list_remove(list, old->data);
1023 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
1026 last = g_list_last(list);
1028 oldstr = last->data;
1029 list = g_list_remove(list, last->data);
1034 list = g_list_prepend(list, g_strdup(str));
1039 void remove_return(gchar *str)
1041 register gchar *p = str;
1044 if (*p == '\n' || *p == '\r')
1045 memmove(p, p + 1, strlen(p));
1051 void remove_space(gchar *str)
1053 register gchar *p = str;
1058 while (g_ascii_isspace(*(p + spc)))
1061 memmove(p, p + spc, strlen(p + spc) + 1);
1067 void unfold_line(gchar *str)
1069 register gchar *p = str;
1073 if (*p == '\n' || *p == '\r') {
1076 while (g_ascii_isspace(*(p + spc)))
1079 memmove(p, p + spc, strlen(p + spc) + 1);
1085 void subst_char(gchar *str, gchar orig, gchar subst)
1087 register gchar *p = str;
1096 void subst_chars(gchar *str, gchar *orig, gchar subst)
1098 register gchar *p = str;
1101 if (strchr(orig, *p) != NULL)
1107 void subst_for_filename(gchar *str)
1112 subst_chars(str, "\t\r\n\\/*:", '_');
1114 subst_chars(str, "\t\r\n\\/*", '_');
1118 void subst_for_shellsafe_filename(gchar *str)
1122 subst_for_filename(str);
1123 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1126 gboolean is_ascii_str(const gchar *str)
1128 const guchar *p = (const guchar *)str;
1130 while (*p != '\0') {
1131 if (*p != '\t' && *p != ' ' &&
1132 *p != '\r' && *p != '\n' &&
1133 (*p < 32 || *p >= 127))
1141 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1143 gchar * position = NULL;
1144 gchar * tmp_pos = NULL;
1147 if (quote_chars == NULL)
1150 for (i = 0; i < strlen(quote_chars); i++) {
1151 tmp_pos = strrchr (str, quote_chars[i]);
1153 || (tmp_pos != NULL && position <= tmp_pos) )
1159 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1161 const gchar *first_pos;
1162 const gchar *last_pos;
1163 const gchar *p = str;
1164 gint quote_level = -1;
1166 /* speed up line processing by only searching to the last '>' */
1167 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1168 /* skip a line if it contains a '<' before the initial '>' */
1169 if (memchr(str, '<', first_pos - str) != NULL)
1171 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1175 while (p <= last_pos) {
1176 while (p < last_pos) {
1177 if (g_ascii_isspace(*p))
1183 if (strchr(quote_chars, *p))
1185 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1186 /* any characters are allowed except '-','<' and space */
1187 while (*p != '-' && *p != '<'
1188 && !strchr(quote_chars, *p)
1189 && !g_ascii_isspace(*p)
1192 if (strchr(quote_chars, *p))
1204 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1206 const gchar *p = str, *q;
1207 gint cur_line = 0, len;
1209 while ((q = strchr(p, '\n')) != NULL) {
1211 if (len > max_chars) {
1221 if (len > max_chars) {
1230 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1232 gchar * position = NULL;
1233 gchar * tmp_pos = NULL;
1236 if (quote_chars == NULL)
1239 for (i = 0; i < strlen(quote_chars); i++) {
1240 tmp_pos = strchr (str, quote_chars[i]);
1242 || (tmp_pos != NULL && position >= tmp_pos) )
1248 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1250 register guint haystack_len, needle_len;
1251 gboolean in_squote = FALSE, in_dquote = FALSE;
1253 haystack_len = strlen(haystack);
1254 needle_len = strlen(needle);
1256 if (haystack_len < needle_len || needle_len == 0)
1259 while (haystack_len >= needle_len) {
1260 if (!in_squote && !in_dquote &&
1261 !strncmp(haystack, needle, needle_len))
1262 return (gchar *)haystack;
1264 /* 'foo"bar"' -> foo"bar"
1265 "foo'bar'" -> foo'bar' */
1266 if (*haystack == '\'') {
1269 else if (!in_dquote)
1271 } else if (*haystack == '\"') {
1274 else if (!in_squote)
1276 } else if (*haystack == '\\') {
1288 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1291 GSList *string_list = NULL, *slist;
1292 gchar **str_array, *s, *new_str;
1293 guint i, n = 1, len;
1295 cm_return_val_if_fail(str != NULL, NULL);
1296 cm_return_val_if_fail(delim != NULL, NULL);
1299 max_tokens = G_MAXINT;
1301 s = strstr_with_skip_quote(str, delim);
1303 guint delimiter_len = strlen(delim);
1307 new_str = g_strndup(str, len);
1309 if (new_str[0] == '\'' || new_str[0] == '\"') {
1310 if (new_str[len - 1] == new_str[0]) {
1311 new_str[len - 1] = '\0';
1312 memmove(new_str, new_str + 1, len - 1);
1315 string_list = g_slist_prepend(string_list, new_str);
1317 str = s + delimiter_len;
1318 s = strstr_with_skip_quote(str, delim);
1319 } while (--max_tokens && s);
1323 new_str = g_strdup(str);
1324 if (new_str[0] == '\'' || new_str[0] == '\"') {
1326 if (new_str[len - 1] == new_str[0]) {
1327 new_str[len - 1] = '\0';
1328 memmove(new_str, new_str + 1, len - 1);
1331 string_list = g_slist_prepend(string_list, new_str);
1335 str_array = g_new(gchar*, n);
1339 str_array[i--] = NULL;
1340 for (slist = string_list; slist; slist = slist->next)
1341 str_array[i--] = slist->data;
1343 g_slist_free(string_list);
1348 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1350 gchar *abbrev_group;
1352 const gchar *p = group;
1355 cm_return_val_if_fail(group != NULL, NULL);
1357 last = group + strlen(group);
1358 abbrev_group = ap = g_malloc(strlen(group) + 1);
1363 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1365 while (*p != '.') p++;
1368 return abbrev_group;
1373 return abbrev_group;
1376 gchar *trim_string(const gchar *str, gint len)
1378 const gchar *p = str;
1383 if (!str) return NULL;
1384 if (strlen(str) <= len)
1385 return g_strdup(str);
1386 if (g_utf8_validate(str, -1, NULL) == FALSE)
1387 return g_strdup(str);
1389 while (*p != '\0') {
1390 mb_len = g_utf8_skip[*(guchar *)p];
1393 else if (new_len + mb_len > len)
1400 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1401 return g_strconcat(new_str, "...", NULL);
1404 GList *uri_list_extract_filenames(const gchar *uri_list)
1406 GList *result = NULL;
1408 gchar *escaped_utf8uri;
1414 while (g_ascii_isspace(*p)) p++;
1415 if (!strncmp(p, "file:", 5)) {
1418 while (*q && *q != '\n' && *q != '\r') q++;
1421 gchar *file, *locale_file = NULL;
1423 while (q > p && g_ascii_isspace(*q))
1425 Xalloca(escaped_utf8uri, q - p + 2,
1427 Xalloca(file, q - p + 2,
1430 strncpy(escaped_utf8uri, p, q - p + 1);
1431 escaped_utf8uri[q - p + 1] = '\0';
1432 decode_uri(file, escaped_utf8uri);
1434 * g_filename_from_uri() rejects escaped/locale encoded uri
1435 * string which come from Nautilus.
1438 if (g_utf8_validate(file, -1, NULL))
1440 = conv_codeset_strdup(
1443 conv_get_locale_charset_str());
1445 locale_file = g_strdup(file + 5);
1447 locale_file = g_filename_from_uri(file, NULL, NULL);
1449 result = g_list_append(result, locale_file);
1453 p = strchr(p, '\n');
1460 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1463 static gint axtoi(const gchar *hexstr)
1465 gint hi, lo, result;
1468 if ('0' <= hi && hi <= '9') {
1471 if ('a' <= hi && hi <= 'f') {
1474 if ('A' <= hi && hi <= 'F') {
1479 if ('0' <= lo && lo <= '9') {
1482 if ('a' <= lo && lo <= 'f') {
1485 if ('A' <= lo && lo <= 'F') {
1488 result = lo + (16 * hi);
1492 gboolean is_uri_string(const gchar *str)
1494 while (str && *str && g_ascii_isspace(*str))
1496 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1497 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1498 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1499 g_ascii_strncasecmp(str, "www.", 4) == 0);
1502 gchar *get_uri_path(const gchar *uri)
1504 while (uri && *uri && g_ascii_isspace(*uri))
1506 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1507 return (gchar *)(uri + 7);
1508 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1509 return (gchar *)(uri + 8);
1510 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1511 return (gchar *)(uri + 6);
1513 return (gchar *)uri;
1516 gint get_uri_len(const gchar *str)
1520 if (is_uri_string(str)) {
1521 for (p = str; *p != '\0'; p++) {
1522 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1531 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1532 * plusses, and escape characters are used)
1534 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1536 gchar *dec = decoded_uri;
1537 const gchar *enc = encoded_uri;
1542 if (isxdigit((guchar)enc[0]) &&
1543 isxdigit((guchar)enc[1])) {
1549 if (with_plus && *enc == '+')
1561 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1563 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1566 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1568 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1569 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1573 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1574 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1578 const gchar *forbidden_uris[] = { ".gnupg/",
1584 gint num_attach = 0;
1585 gchar **my_att = NULL;
1587 Xstrdup_a(tmp_mailto, mailto, return -1);
1589 if (!strncmp(tmp_mailto, "mailto:", 7))
1592 p = strchr(tmp_mailto, '?');
1599 *to = decode_uri_gdup(tmp_mailto);
1601 my_att = g_malloc(sizeof(char *));
1605 gchar *field, *value;
1622 if (*value == '\0') continue;
1624 if (from && !g_ascii_strcasecmp(field, "from")) {
1626 *from = decode_uri_gdup(value);
1628 gchar *tmp = decode_uri_gdup(value);
1629 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1633 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1635 *cc = decode_uri_gdup(value);
1637 gchar *tmp = decode_uri_gdup(value);
1638 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1642 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1644 *bcc = decode_uri_gdup(value);
1646 gchar *tmp = decode_uri_gdup(value);
1647 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1651 } else if (subject && !*subject &&
1652 !g_ascii_strcasecmp(field, "subject")) {
1653 *subject = decode_uri_gdup(value);
1654 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1655 *body = decode_uri_gdup(value);
1656 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1657 gchar *tmp = decode_uri_gdup(value);
1658 if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1659 g_warning("Error: couldn't set insert file '%s' in body\n", value);
1663 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1665 gchar *tmp = decode_uri_gdup(value);
1666 for (; forbidden_uris[i]; i++) {
1667 if (strstr(tmp, forbidden_uris[i])) {
1668 g_print("Refusing to attach '%s', potential private data leak\n",
1676 /* attach is correct */
1678 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1679 my_att[num_attach-1] = tmp;
1680 my_att[num_attach] = NULL;
1682 } else if (inreplyto && !*inreplyto &&
1683 !g_ascii_strcasecmp(field, "in-reply-to")) {
1684 *inreplyto = decode_uri_gdup(value);
1695 #include <windows.h>
1696 #ifndef CSIDL_APPDATA
1697 #define CSIDL_APPDATA 0x001a
1699 #ifndef CSIDL_LOCAL_APPDATA
1700 #define CSIDL_LOCAL_APPDATA 0x001c
1702 #ifndef CSIDL_FLAG_CREATE
1703 #define CSIDL_FLAG_CREATE 0x8000
1705 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1709 w32_strerror (int w32_errno)
1711 static char strerr[256];
1712 int ec = (int)GetLastError ();
1716 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1717 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1718 strerr, DIM (strerr)-1, NULL);
1722 static __inline__ void *
1723 dlopen (const char * name, int flag)
1725 void * hd = LoadLibrary (name);
1729 static __inline__ void *
1730 dlsym (void * hd, const char * sym)
1734 void * fnc = GetProcAddress (hd, sym);
1743 static __inline__ const char *
1746 return w32_strerror (0);
1750 static __inline__ int
1762 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1764 static int initialized;
1765 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1769 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1775 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1777 handle = dlopen (dllnames[i], RTLD_LAZY);
1780 func = dlsym (handle, "SHGetFolderPathW");
1791 return func (a,b,c,d,e);
1796 /* Returns a static string with the directroy from which the module
1797 has been loaded. Returns an empty string on error. */
1798 static char *w32_get_module_dir(void)
1800 static char *moddir;
1803 char name[MAX_PATH+10];
1806 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1809 p = strrchr (name, '\\');
1815 moddir = g_strdup (name);
1819 #endif /* G_OS_WIN32 */
1821 /* Return a static string with the locale dir. */
1822 const gchar *get_locale_dir(void)
1824 static gchar *loc_dir;
1828 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1829 "\\share\\locale", NULL);
1832 loc_dir = LOCALEDIR;
1838 const gchar *get_home_dir(void)
1841 static char home_dir_utf16[MAX_PATH] = "";
1842 static gchar *home_dir_utf8 = NULL;
1843 if (home_dir_utf16[0] == '\0') {
1844 if (w32_shgetfolderpath
1845 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1846 NULL, 0, home_dir_utf16) < 0)
1847 strcpy (home_dir_utf16, "C:\\Sylpheed");
1848 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar *)home_dir_utf16, -1, NULL, NULL, NULL);
1850 return home_dir_utf8;
1852 static const gchar *homeenv = NULL;
1857 if (!homeenv && g_getenv("HOME") != NULL)
1858 homeenv = g_strdup(g_getenv("HOME"));
1860 homeenv = g_get_home_dir();
1866 static gchar *claws_rc_dir = NULL;
1867 static gboolean rc_dir_alt = FALSE;
1868 const gchar *get_rc_dir(void)
1871 if (!claws_rc_dir) {
1872 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1874 debug_print("using default rc_dir %s\n", claws_rc_dir);
1876 return claws_rc_dir;
1879 void set_rc_dir(const gchar *dir)
1881 gchar *canonical_dir;
1882 if (claws_rc_dir != NULL) {
1883 g_print("Error: rc_dir already set\n");
1885 int err = cm_canonicalize_filename(dir, &canonical_dir);
1889 g_print("Error looking for %s: %d(%s)\n",
1890 dir, -err, strerror(-err));
1895 claws_rc_dir = canonical_dir;
1897 len = strlen(claws_rc_dir);
1898 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1899 claws_rc_dir[len - 1] = '\0';
1901 debug_print("set rc_dir to %s\n", claws_rc_dir);
1902 if (!is_dir_exist(claws_rc_dir)) {
1903 if (make_dir_hier(claws_rc_dir) != 0) {
1904 g_print("Error: can't create %s\n",
1912 gboolean rc_dir_is_alt(void) {
1916 const gchar *get_mail_base_dir(void)
1918 return get_home_dir();
1922 const gchar *prefs_common_get_data_root(void);
1923 gchar *last_data_root = NULL;
1926 const gchar *get_news_cache_dir(void)
1928 static gchar *news_cache_dir = NULL;
1930 const gchar *data_root = prefs_common_get_data_root();
1931 if (strcmp2(data_root, last_data_root)) {
1932 g_free(news_cache_dir);
1933 news_cache_dir = NULL;
1936 if (!news_cache_dir)
1938 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1939 NEWS_CACHE_DIR, NULL);
1943 news_cache_dir = g_strconcat(data_root, G_DIR_SEPARATOR_S,
1944 "Claws", G_DIR_SEPARATOR_S,
1945 g_get_user_name(), G_DIR_SEPARATOR_S,
1946 NEWS_CACHE_DIR, NULL);
1947 g_free(last_data_root);
1948 last_data_root = g_strdup(last_data_root);
1950 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1951 NEWS_CACHE_DIR, NULL);
1952 g_free(last_data_root);
1953 last_data_root = NULL;
1957 return news_cache_dir;
1960 const gchar *get_imap_cache_dir(void)
1962 static gchar *imap_cache_dir = NULL;
1964 const gchar *data_root = prefs_common_get_data_root();
1965 if (strcmp2(data_root, last_data_root)) {
1966 g_free(imap_cache_dir);
1967 imap_cache_dir = NULL;
1971 if (!imap_cache_dir)
1973 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1974 IMAP_CACHE_DIR, NULL);
1978 imap_cache_dir = g_strconcat(data_root, G_DIR_SEPARATOR_S,
1979 "Claws", G_DIR_SEPARATOR_S,
1980 g_get_user_name(), G_DIR_SEPARATOR_S,
1981 IMAP_CACHE_DIR, NULL);
1982 g_free(last_data_root);
1983 last_data_root = g_strdup(last_data_root);
1985 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1986 IMAP_CACHE_DIR, NULL);
1987 g_free(last_data_root);
1988 last_data_root = NULL;
1993 return imap_cache_dir;
1996 const gchar *get_mime_tmp_dir(void)
1998 static gchar *mime_tmp_dir = NULL;
2001 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2002 MIME_TMP_DIR, NULL);
2004 return mime_tmp_dir;
2007 const gchar *get_template_dir(void)
2009 static gchar *template_dir = NULL;
2012 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2013 TEMPLATE_DIR, NULL);
2015 return template_dir;
2019 const gchar *get_cert_file(void)
2021 const gchar *cert_file = NULL;
2023 cert_file = g_strconcat(w32_get_module_dir(),
2024 "\\share\\claws-mail\\",
2025 "ca-certificates.crt",
2031 /* Return the filepath of the claws-mail.desktop file */
2032 const gchar *get_desktop_file(void)
2034 #ifdef DESKTOPFILEPATH
2035 return DESKTOPFILEPATH;
2041 /* Return the default directory for Plugins. */
2042 const gchar *get_plugin_dir(void)
2045 static gchar *plugin_dir = NULL;
2048 plugin_dir = g_strconcat(w32_get_module_dir(),
2049 "\\lib\\claws-mail\\plugins\\",
2053 if (is_dir_exist(PLUGINDIR))
2056 static gchar *plugin_dir = NULL;
2058 plugin_dir = g_strconcat(get_rc_dir(),
2059 G_DIR_SEPARATOR_S, "plugins",
2060 G_DIR_SEPARATOR_S, NULL);
2068 /* Return the default directory for Themes. */
2069 const gchar *get_themes_dir(void)
2071 static gchar *themes_dir = NULL;
2074 themes_dir = g_strconcat(w32_get_module_dir(),
2075 "\\share\\claws-mail\\themes",
2081 const gchar *get_tmp_dir(void)
2083 static gchar *tmp_dir = NULL;
2086 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
2092 gchar *get_tmp_file(void)
2095 static guint32 id = 0;
2097 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
2098 get_tmp_dir(), G_DIR_SEPARATOR, id++);
2103 const gchar *get_domain_name(void)
2106 static gchar *domain_name = NULL;
2112 if (gethostname(hostname, sizeof(hostname)) != 0) {
2113 perror("gethostname");
2114 domain_name = "unknown";
2116 hostname[sizeof(hostname) - 1] = '\0';
2117 if ((hp = my_gethostbyname(hostname)) == NULL) {
2118 perror("gethostbyname");
2119 domain_name = g_strdup(hostname);
2121 domain_name = g_strdup(hp->h_name);
2124 debug_print("domain name = %s\n", domain_name);
2133 off_t get_file_size(const gchar *file)
2137 if (g_stat(file, &s) < 0) {
2138 FILE_OP_ERROR(file, "stat");
2145 time_t get_file_mtime(const gchar *file)
2149 if (g_stat(file, &s) < 0) {
2150 FILE_OP_ERROR(file, "stat");
2157 off_t get_file_size_as_crlf(const gchar *file)
2161 gchar buf[BUFFSIZE];
2163 if ((fp = g_fopen(file, "rb")) == NULL) {
2164 FILE_OP_ERROR(file, "g_fopen");
2168 while (fgets(buf, sizeof(buf), fp) != NULL) {
2170 size += strlen(buf) + 2;
2174 FILE_OP_ERROR(file, "fgets");
2183 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2190 if (g_stat(file, &s) < 0) {
2191 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2195 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2202 /* Test on whether FILE is a relative file name. This is
2203 * straightforward for Unix but more complex for Windows. */
2204 gboolean is_relative_filename(const gchar *file)
2209 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2210 return FALSE; /* Prefixed with a hostname - this can't
2211 * be a relative name. */
2213 if ( ((*file >= 'a' && *file <= 'z')
2214 || (*file >= 'A' && *file <= 'Z'))
2216 file += 2; /* Skip drive letter. */
2218 return !(*file == '\\' || *file == '/');
2220 return !(*file == G_DIR_SEPARATOR);
2225 gboolean is_dir_exist(const gchar *dir)
2230 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2233 gboolean is_file_entry_exist(const gchar *file)
2238 return g_file_test(file, G_FILE_TEST_EXISTS);
2241 gboolean dirent_is_regular_file(struct dirent *d)
2243 #if !defined(G_OS_WIN32) && !defined(MAEMO) && defined(HAVE_DIRENT_D_TYPE)
2244 if (d->d_type == DT_REG)
2246 else if (d->d_type != DT_UNKNOWN)
2250 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2253 gint change_dir(const gchar *dir)
2255 gchar *prevdir = NULL;
2258 prevdir = g_get_current_dir();
2260 if (g_chdir(dir) < 0) {
2261 FILE_OP_ERROR(dir, "chdir");
2262 if (debug_mode) g_free(prevdir);
2264 } else if (debug_mode) {
2267 cwd = g_get_current_dir();
2268 if (strcmp(prevdir, cwd) != 0)
2269 g_print("current dir: %s\n", cwd);
2277 gint make_dir(const gchar *dir)
2279 if (g_mkdir(dir, S_IRWXU) < 0) {
2280 FILE_OP_ERROR(dir, "mkdir");
2283 if (g_chmod(dir, S_IRWXU) < 0)
2284 FILE_OP_ERROR(dir, "chmod");
2289 gint make_dir_hier(const gchar *dir)
2294 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2295 parent_dir = g_strndup(dir, p - dir);
2296 if (*parent_dir != '\0') {
2297 if (!is_dir_exist(parent_dir)) {
2298 if (make_dir(parent_dir) < 0) {
2307 if (!is_dir_exist(dir)) {
2308 if (make_dir(dir) < 0)
2315 gint remove_all_files(const gchar *dir)
2318 const gchar *dir_name;
2321 prev_dir = g_get_current_dir();
2323 if (g_chdir(dir) < 0) {
2324 FILE_OP_ERROR(dir, "chdir");
2329 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2330 g_warning("failed to open directory: %s\n", dir);
2335 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2336 if (claws_unlink(dir_name) < 0)
2337 FILE_OP_ERROR(dir_name, "unlink");
2342 if (g_chdir(prev_dir) < 0) {
2343 FILE_OP_ERROR(prev_dir, "chdir");
2353 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2356 const gchar *dir_name;
2360 if (first == last) {
2361 /* Skip all the dir reading part. */
2362 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2363 if (claws_unlink(filename) < 0) {
2364 FILE_OP_ERROR(filename, "unlink");
2372 prev_dir = g_get_current_dir();
2374 if (g_chdir(dir) < 0) {
2375 FILE_OP_ERROR(dir, "chdir");
2380 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2381 g_warning("failed to open directory: %s\n", dir);
2386 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2387 file_no = to_number(dir_name);
2388 if (file_no > 0 && first <= file_no && file_no <= last) {
2389 if (is_dir_exist(dir_name))
2391 if (claws_unlink(dir_name) < 0)
2392 FILE_OP_ERROR(dir_name, "unlink");
2398 if (g_chdir(prev_dir) < 0) {
2399 FILE_OP_ERROR(prev_dir, "chdir");
2409 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2412 const gchar *dir_name;
2415 GHashTable *file_no_tbl;
2417 if (numberlist == NULL)
2420 prev_dir = g_get_current_dir();
2422 if (g_chdir(dir) < 0) {
2423 FILE_OP_ERROR(dir, "chdir");
2428 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2429 FILE_OP_ERROR(dir, "opendir");
2434 file_no_tbl = g_hash_table_new(g_direct_hash, g_direct_equal);
2435 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2436 file_no = to_number(dir_name);
2437 if (is_dir_exist(dir_name))
2440 g_hash_table_insert(file_no_tbl, GINT_TO_POINTER(file_no), GINT_TO_POINTER(1));
2444 if (g_hash_table_lookup(file_no_tbl, numberlist->data) == NULL) {
2445 debug_print("removing unwanted file %d from %s\n",
2446 GPOINTER_TO_INT(numberlist->data), dir);
2447 if (claws_unlink(dir_name) < 0)
2448 FILE_OP_ERROR(dir_name, "unlink");
2450 } while ((numberlist = g_slist_next(numberlist)));
2453 g_hash_table_destroy(file_no_tbl);
2455 if (g_chdir(prev_dir) < 0) {
2456 FILE_OP_ERROR(prev_dir, "chdir");
2466 gint remove_all_numbered_files(const gchar *dir)
2468 return remove_numbered_files(dir, 0, UINT_MAX);
2471 gint remove_dir_recursive(const gchar *dir)
2475 const gchar *dir_name;
2478 if (g_stat(dir, &s) < 0) {
2479 FILE_OP_ERROR(dir, "stat");
2480 if (ENOENT == errno) return 0;
2484 if (!S_ISDIR(s.st_mode)) {
2485 if (claws_unlink(dir) < 0) {
2486 FILE_OP_ERROR(dir, "unlink");
2493 prev_dir = g_get_current_dir();
2494 /* g_print("prev_dir = %s\n", prev_dir); */
2496 if (!path_cmp(prev_dir, dir)) {
2498 if (g_chdir("..") < 0) {
2499 FILE_OP_ERROR(dir, "chdir");
2502 prev_dir = g_get_current_dir();
2505 if (g_chdir(dir) < 0) {
2506 FILE_OP_ERROR(dir, "chdir");
2511 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2512 g_warning("failed to open directory: %s\n", dir);
2518 /* remove all files in the directory */
2519 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2520 /* g_print("removing %s\n", dir_name); */
2522 if (is_dir_exist(dir_name)) {
2523 if (remove_dir_recursive(dir_name) < 0) {
2524 g_warning("can't remove directory\n");
2528 if (claws_unlink(dir_name) < 0)
2529 FILE_OP_ERROR(dir_name, "unlink");
2535 if (g_chdir(prev_dir) < 0) {
2536 FILE_OP_ERROR(prev_dir, "chdir");
2543 if (g_rmdir(dir) < 0) {
2544 FILE_OP_ERROR(dir, "rmdir");
2551 gint rename_force(const gchar *oldpath, const gchar *newpath)
2554 if (!is_file_entry_exist(oldpath)) {
2558 if (is_file_exist(newpath)) {
2559 if (claws_unlink(newpath) < 0)
2560 FILE_OP_ERROR(newpath, "unlink");
2563 return g_rename(oldpath, newpath);
2567 * Append src file body to the tail of dest file.
2568 * Now keep_backup has no effects.
2570 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2572 FILE *src_fp, *dest_fp;
2576 gboolean err = FALSE;
2578 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2579 FILE_OP_ERROR(src, "g_fopen");
2583 if ((dest_fp = g_fopen(dest, "ab")) == NULL) {
2584 FILE_OP_ERROR(dest, "g_fopen");
2589 if (change_file_mode_rw(dest_fp, dest) < 0) {
2590 FILE_OP_ERROR(dest, "chmod");
2591 g_warning("can't change file mode\n");
2594 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2595 if (n_read < sizeof(buf) && ferror(src_fp))
2597 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2598 g_warning("writing to %s failed.\n", dest);
2606 if (ferror(src_fp)) {
2607 FILE_OP_ERROR(src, "fread");
2611 if (fclose(dest_fp) == EOF) {
2612 FILE_OP_ERROR(dest, "fclose");
2624 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2626 FILE *src_fp, *dest_fp;
2629 gchar *dest_bak = NULL;
2630 gboolean err = FALSE;
2632 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2633 FILE_OP_ERROR(src, "g_fopen");
2636 if (is_file_exist(dest)) {
2637 dest_bak = g_strconcat(dest, ".bak", NULL);
2638 if (rename_force(dest, dest_bak) < 0) {
2639 FILE_OP_ERROR(dest, "rename");
2646 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2647 FILE_OP_ERROR(dest, "g_fopen");
2650 if (rename_force(dest_bak, dest) < 0)
2651 FILE_OP_ERROR(dest_bak, "rename");
2657 if (change_file_mode_rw(dest_fp, dest) < 0) {
2658 FILE_OP_ERROR(dest, "chmod");
2659 g_warning("can't change file mode\n");
2662 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2663 if (n_read < sizeof(buf) && ferror(src_fp))
2665 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2666 g_warning("writing to %s failed.\n", dest);
2671 if (rename_force(dest_bak, dest) < 0)
2672 FILE_OP_ERROR(dest_bak, "rename");
2679 if (ferror(src_fp)) {
2680 FILE_OP_ERROR(src, "fread");
2684 if (fclose(dest_fp) == EOF) {
2685 FILE_OP_ERROR(dest, "fclose");
2692 if (rename_force(dest_bak, dest) < 0)
2693 FILE_OP_ERROR(dest_bak, "rename");
2699 if (keep_backup == FALSE && dest_bak)
2700 claws_unlink(dest_bak);
2707 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2709 if (overwrite == FALSE && is_file_exist(dest)) {
2710 g_warning("move_file(): file %s already exists.", dest);
2714 if (rename_force(src, dest) == 0) return 0;
2716 if (EXDEV != errno) {
2717 FILE_OP_ERROR(src, "rename");
2721 if (copy_file(src, dest, FALSE) < 0) return -1;
2728 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2731 gint bytes_left, to_read;
2734 if (fseek(fp, offset, SEEK_SET) < 0) {
2739 bytes_left = length;
2740 to_read = MIN(bytes_left, sizeof(buf));
2742 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2743 if (n_read < to_read && ferror(fp))
2745 if (fwrite(buf, 1, n_read, dest_fp) < n_read) {
2748 bytes_left -= n_read;
2749 if (bytes_left == 0)
2751 to_read = MIN(bytes_left, sizeof(buf));
2762 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2765 gboolean err = FALSE;
2767 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2768 FILE_OP_ERROR(dest, "g_fopen");
2772 if (change_file_mode_rw(dest_fp, dest) < 0) {
2773 FILE_OP_ERROR(dest, "chmod");
2774 g_warning("can't change file mode\n");
2777 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2780 if (!err && fclose(dest_fp) == EOF) {
2781 FILE_OP_ERROR(dest, "fclose");
2786 g_warning("writing to %s failed.\n", dest);
2794 /* convert line endings into CRLF. If the last line doesn't end with
2795 * linebreak, add it.
2797 gchar *canonicalize_str(const gchar *str)
2803 for (p = str; *p != '\0'; ++p) {
2810 if (p == str || *(p - 1) != '\n')
2813 out = outp = g_malloc(new_len + 1);
2814 for (p = str; *p != '\0'; ++p) {
2821 if (p == str || *(p - 1) != '\n') {
2830 gint canonicalize_file(const gchar *src, const gchar *dest)
2832 FILE *src_fp, *dest_fp;
2833 gchar buf[BUFFSIZE];
2835 gboolean err = FALSE;
2836 gboolean last_linebreak = FALSE;
2838 if (src == NULL || dest == NULL)
2841 if ((src_fp = g_fopen(src, "rb")) == NULL) {
2842 FILE_OP_ERROR(src, "g_fopen");
2846 if ((dest_fp = g_fopen(dest, "wb")) == NULL) {
2847 FILE_OP_ERROR(dest, "g_fopen");
2852 if (change_file_mode_rw(dest_fp, dest) < 0) {
2853 FILE_OP_ERROR(dest, "chmod");
2854 g_warning("can't change file mode\n");
2857 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2861 if (len == 0) break;
2862 last_linebreak = FALSE;
2864 if (buf[len - 1] != '\n') {
2865 last_linebreak = TRUE;
2866 r = fputs(buf, dest_fp);
2867 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2868 r = fputs(buf, dest_fp);
2871 r = fwrite(buf, 1, len - 1, dest_fp);
2876 r = fputs("\r\n", dest_fp);
2880 g_warning("writing to %s failed.\n", dest);
2888 if (last_linebreak == TRUE) {
2889 if (fputs("\r\n", dest_fp) == EOF)
2893 if (ferror(src_fp)) {
2894 FILE_OP_ERROR(src, "fgets");
2898 if (fclose(dest_fp) == EOF) {
2899 FILE_OP_ERROR(dest, "fclose");
2911 gint canonicalize_file_replace(const gchar *file)
2915 tmp_file = get_tmp_file();
2917 if (canonicalize_file(file, tmp_file) < 0) {
2922 if (move_file(tmp_file, file, TRUE) < 0) {
2923 g_warning("can't replace %s .\n", file);
2924 claws_unlink(tmp_file);
2933 gchar *normalize_newlines(const gchar *str)
2938 out = outp = g_malloc(strlen(str) + 1);
2939 for (p = str; *p != '\0'; ++p) {
2941 if (*(p + 1) != '\n')
2952 gchar *get_outgoing_rfc2822_str(FILE *fp)
2954 gchar buf[BUFFSIZE];
2958 str = g_string_new(NULL);
2960 /* output header part */
2961 while (fgets(buf, sizeof(buf), fp) != NULL) {
2963 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2970 else if (next != ' ' && next != '\t') {
2974 if (fgets(buf, sizeof(buf), fp) == NULL)
2978 g_string_append(str, buf);
2979 g_string_append(str, "\r\n");
2985 /* output body part */
2986 while (fgets(buf, sizeof(buf), fp) != NULL) {
2989 g_string_append_c(str, '.');
2990 g_string_append(str, buf);
2991 g_string_append(str, "\r\n");
2995 g_string_free(str, FALSE);
3001 * Create a new boundary in a way that it is very unlikely that this
3002 * will occur in the following text. It would be easy to ensure
3003 * uniqueness if everything is either quoted-printable or base64
3004 * encoded (note that conversion is allowed), but because MIME bodies
3005 * may be nested, it may happen that the same boundary has already
3008 * boundary := 0*69<bchars> bcharsnospace
3009 * bchars := bcharsnospace / " "
3010 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
3011 * "+" / "_" / "," / "-" / "." /
3012 * "/" / ":" / "=" / "?"
3014 * some special characters removed because of buggy MTAs
3017 gchar *generate_mime_boundary(const gchar *prefix)
3019 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
3020 "abcdefghijklmnopqrstuvwxyz"
3025 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
3026 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
3029 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
3033 gint change_file_mode_rw(FILE *fp, const gchar *file)
3036 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
3038 return g_chmod(file, S_IRUSR|S_IWUSR);
3042 FILE *my_tmpfile(void)
3044 #if HAVE_MKSTEMP || defined(G_OS_WIN32)
3045 const gchar suffix[] = ".XXXXXX";
3046 const gchar *tmpdir;
3048 const gchar *progname;
3057 tmpdir = get_tmp_dir();
3058 tmplen = strlen(tmpdir);
3059 progname = g_get_prgname();
3060 if (progname == NULL)
3061 progname = "claws-mail";
3062 proglen = strlen(progname);
3063 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
3066 memcpy(fname, tmpdir, tmplen);
3067 fname[tmplen] = G_DIR_SEPARATOR;
3068 memcpy(fname + tmplen + 1, progname, proglen);
3069 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
3071 fd = mkstemp(fname);
3076 claws_unlink(fname);
3078 /* verify that we can write in the file after unlinking */
3079 if (write(fd, buf, 1) < 0) {
3086 fp = fdopen(fd, "w+b");
3094 #endif /* HAVE_MKSTEMP || G_OS_WIN32 */
3099 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
3103 char *template = g_strdup_printf ("%s%cclaws.XXXXXX",
3104 dir, G_DIR_SEPARATOR);
3105 fd = mkstemp_name(template, filename);
3108 *filename = g_strdup_printf("%s%cclaws.XXXXXX", dir, G_DIR_SEPARATOR);
3109 fd = mkstemp(*filename);
3111 return fdopen(fd, "w+");
3114 FILE *str_open_as_stream(const gchar *str)
3119 cm_return_val_if_fail(str != NULL, NULL);
3123 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3128 if (len == 0) return fp;
3130 if (fwrite(str, 1, len, fp) != len) {
3131 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3140 gint str_write_to_file(const gchar *str, const gchar *file)
3145 cm_return_val_if_fail(str != NULL, -1);
3146 cm_return_val_if_fail(file != NULL, -1);
3148 if ((fp = g_fopen(file, "wb")) == NULL) {
3149 FILE_OP_ERROR(file, "g_fopen");
3159 if (fwrite(str, 1, len, fp) != len) {
3160 FILE_OP_ERROR(file, "fwrite");
3166 if (fclose(fp) == EOF) {
3167 FILE_OP_ERROR(file, "fclose");
3175 static gchar *file_read_stream_to_str_full(FILE *fp, gboolean recode)
3182 cm_return_val_if_fail(fp != NULL, NULL);
3184 array = g_byte_array_new();
3186 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3187 if (n_read < sizeof(buf) && ferror(fp))
3189 g_byte_array_append(array, buf, n_read);
3193 FILE_OP_ERROR("file stream", "fread");
3194 g_byte_array_free(array, TRUE);
3199 g_byte_array_append(array, buf, 1);
3200 str = (gchar *)array->data;
3201 g_byte_array_free(array, FALSE);
3203 if (recode && !g_utf8_validate(str, -1, NULL)) {
3204 const gchar *src_codeset, *dest_codeset;
3206 src_codeset = conv_get_locale_charset_str();
3207 dest_codeset = CS_UTF_8;
3208 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3216 static gchar *file_read_to_str_full(const gchar *file, gboolean recode)
3223 struct timeval timeout = {1, 0};
3228 cm_return_val_if_fail(file != NULL, NULL);
3230 if (g_stat(file, &s) != 0) {
3231 FILE_OP_ERROR(file, "stat");
3234 if (S_ISDIR(s.st_mode)) {
3235 g_warning("%s: is a directory\n", file);
3240 fp = g_fopen (file, "rb");
3242 FILE_OP_ERROR(file, "open");
3246 /* test whether the file is readable without blocking */
3247 fd = g_open(file, O_RDONLY | O_NONBLOCK, 0);
3249 FILE_OP_ERROR(file, "open");
3256 /* allow for one second */
3257 err = select(fd+1, &fds, NULL, NULL, &timeout);
3258 if (err <= 0 || !FD_ISSET(fd, &fds)) {
3260 FILE_OP_ERROR(file, "select");
3262 g_warning("%s: doesn't seem readable\n", file);
3268 /* Now clear O_NONBLOCK */
3269 if ((fflags = fcntl(fd, F_GETFL)) < 0) {
3270 FILE_OP_ERROR(file, "fcntl (F_GETFL)");
3274 if (fcntl(fd, F_SETFL, (fflags & ~O_NONBLOCK)) < 0) {
3275 FILE_OP_ERROR(file, "fcntl (F_SETFL)");
3280 /* get the FILE pointer */
3281 fp = fdopen(fd, "rb");
3284 FILE_OP_ERROR(file, "fdopen");
3285 close(fd); /* if fp isn't NULL, we'll use fclose instead! */
3290 str = file_read_stream_to_str_full(fp, recode);
3297 gchar *file_read_to_str(const gchar *file)
3299 return file_read_to_str_full(file, TRUE);
3301 gchar *file_read_stream_to_str(FILE *fp)
3303 return file_read_stream_to_str_full(fp, TRUE);
3306 gchar *file_read_to_str_no_recode(const gchar *file)
3308 return file_read_to_str_full(file, FALSE);
3310 gchar *file_read_stream_to_str_no_recode(FILE *fp)
3312 return file_read_stream_to_str_full(fp, FALSE);
3315 char *fgets_crlf(char *buf, int size, FILE *stream)
3317 gboolean is_cr = FALSE;
3318 gboolean last_was_cr = FALSE;
3323 while (--size > 0 && (c = getc(stream)) != EOF)
3326 is_cr = (c == '\r');
3336 last_was_cr = is_cr;
3338 if (c == EOF && cs == buf)
3346 static gint execute_async(gchar *const argv[])
3348 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3350 if (g_spawn_async(NULL, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3351 NULL, NULL, NULL, FALSE) == FALSE) {
3352 g_warning("Couldn't execute command: %s\n", argv[0]);
3359 static gint execute_sync(gchar *const argv[])
3363 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
3366 if (g_spawn_sync(NULL, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
3367 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3368 g_warning("Couldn't execute command: %s\n", argv[0]);
3372 if (WIFEXITED(status))
3373 return WEXITSTATUS(status);
3377 if (g_spawn_sync(NULL, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH|
3378 G_SPAWN_CHILD_INHERITS_STDIN|G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
3379 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
3380 g_warning("Couldn't execute command: %s\n", argv[0]);
3388 gint execute_command_line(const gchar *cmdline, gboolean async)
3393 debug_print("execute_command_line(): executing: %s\n", cmdline?cmdline:"(null)");
3395 argv = strsplit_with_quote(cmdline, " ", 0);
3398 ret = execute_async(argv);
3400 ret = execute_sync(argv);
3407 gchar *get_command_output(const gchar *cmdline)
3409 gchar *child_stdout;
3412 cm_return_val_if_fail(cmdline != NULL, NULL);
3414 debug_print("get_command_output(): executing: %s\n", cmdline);
3416 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3418 g_warning("Couldn't execute command: %s\n", cmdline);
3422 return child_stdout;
3425 static gint is_unchanged_uri_char(char c)
3436 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3442 for(i = 0; i < strlen(uri) ; i++) {
3443 if (is_unchanged_uri_char(uri[i])) {
3444 if (k + 2 >= bufsize)
3446 encoded_uri[k++] = uri[i];
3449 char * hexa = "0123456789ABCDEF";
3451 if (k + 4 >= bufsize)
3453 encoded_uri[k++] = '%';
3454 encoded_uri[k++] = hexa[uri[i] / 16];
3455 encoded_uri[k++] = hexa[uri[i] % 16];
3461 gint open_uri(const gchar *uri, const gchar *cmdline)
3465 gchar buf[BUFFSIZE];
3467 gchar encoded_uri[BUFFSIZE];
3468 cm_return_val_if_fail(uri != NULL, -1);
3470 /* an option to choose whether to use encode_uri or not ? */
3471 encode_uri(encoded_uri, BUFFSIZE, uri);
3474 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3475 !strchr(p + 2, '%'))
3476 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3479 g_warning("Open URI command-line is invalid "
3480 "(there must be only one '%%s'): %s",
3482 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3485 execute_command_line(buf, TRUE);
3487 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
3490 extern osso_context_t *get_osso_context(void);
3491 osso_rpc_run_with_defaults(get_osso_context(), "osso_browser",
3492 OSSO_BROWSER_OPEN_NEW_WINDOW_REQ, NULL,
3493 DBUS_TYPE_STRING, uri, DBUS_TYPE_INVALID);
3498 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
3500 gchar buf[BUFFSIZE];
3503 cm_return_val_if_fail(filepath != NULL, -1);
3506 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3507 !strchr(p + 2, '%'))
3508 g_snprintf(buf, sizeof(buf), cmdline, filepath);
3511 g_warning("Open Text Editor command-line is invalid "
3512 "(there must be only one '%%s'): %s",
3514 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
3517 execute_command_line(buf, TRUE);
3522 time_t remote_tzoffset_sec(const gchar *zone)
3524 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3530 time_t remoteoffset;
3532 strncpy(zone3, zone, 3);
3536 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3537 (c == '+' || c == '-')) {
3538 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3540 remoteoffset = -remoteoffset;
3541 } else if (!strncmp(zone, "UT" , 2) ||
3542 !strncmp(zone, "GMT", 2)) {
3544 } else if (strlen(zone3) == 3) {
3545 for (p = ustzstr; *p != '\0'; p += 3) {
3546 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3547 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3548 remoteoffset = iustz * 3600;
3554 } else if (strlen(zone3) == 1) {
3556 case 'Z': remoteoffset = 0; break;
3557 case 'A': remoteoffset = -1; break;
3558 case 'B': remoteoffset = -2; break;
3559 case 'C': remoteoffset = -3; break;
3560 case 'D': remoteoffset = -4; break;
3561 case 'E': remoteoffset = -5; break;
3562 case 'F': remoteoffset = -6; break;
3563 case 'G': remoteoffset = -7; break;
3564 case 'H': remoteoffset = -8; break;
3565 case 'I': remoteoffset = -9; break;
3566 case 'K': remoteoffset = -10; break; /* J is not used */
3567 case 'L': remoteoffset = -11; break;
3568 case 'M': remoteoffset = -12; break;
3569 case 'N': remoteoffset = 1; break;
3570 case 'O': remoteoffset = 2; break;
3571 case 'P': remoteoffset = 3; break;
3572 case 'Q': remoteoffset = 4; break;
3573 case 'R': remoteoffset = 5; break;
3574 case 'S': remoteoffset = 6; break;
3575 case 'T': remoteoffset = 7; break;
3576 case 'U': remoteoffset = 8; break;
3577 case 'V': remoteoffset = 9; break;
3578 case 'W': remoteoffset = 10; break;
3579 case 'X': remoteoffset = 11; break;
3580 case 'Y': remoteoffset = 12; break;
3581 default: remoteoffset = 0; break;
3583 remoteoffset = remoteoffset * 3600;
3587 return remoteoffset;
3590 time_t tzoffset_sec(time_t *now)
3594 struct tm buf1, buf2;
3596 if (now && *now < 0)
3599 gmt = *gmtime_r(now, &buf1);
3600 lt = localtime_r(now, &buf2);
3602 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3604 if (lt->tm_year < gmt.tm_year)
3606 else if (lt->tm_year > gmt.tm_year)
3608 else if (lt->tm_yday < gmt.tm_yday)