correctly set modified flag after auto-save
[claws.git] / src / common / utils.c
blob497bedfcadee5715bfa8c3e70df41fe5c8cd7ef6
1 /*
2 * Claws Mail -- a GTK based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2021 The Claws Mail Team and Hiroyuki Yamamoto
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 * The code of the g_utf8_substring function below is owned by
19 * Matthias Clasen <matthiasc@src.gnome.org>/<mclasen@redhat.com>
20 * and is got from GLIB 2.30: https://git.gnome.org/browse/glib/commit/
21 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
23 * GLib 2.30 is licensed under GPL v2 or later and:
24 * Copyright (C) 1999 Tom Tromey
25 * Copyright (C) 2000 Red Hat, Inc.
27 * https://git.gnome.org/browse/glib/tree/glib/gutf8.c
28 * ?h=glib-2-30&id=9eb65dd3ed5e1a9638595cbe10699c7606376511
31 #ifdef HAVE_CONFIG_H
32 # include "config.h"
33 #include "claws-features.h"
34 #endif
36 #include "defs.h"
38 #include <glib.h>
39 #include <gio/gio.h>
41 #include <glib/gi18n.h>
43 #ifdef USE_PTHREAD
44 #include <pthread.h>
45 #endif
47 #include <stdio.h>
48 #include <string.h>
49 #include <ctype.h>
50 #include <errno.h>
51 #include <sys/param.h>
52 #ifdef G_OS_WIN32
53 # include <ws2tcpip.h>
54 #else
55 # include <sys/socket.h>
56 #endif
58 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
59 # include <wchar.h>
60 # include <wctype.h>
61 #endif
62 #include <stdlib.h>
63 #include <sys/stat.h>
64 #include <unistd.h>
65 #include <stdarg.h>
66 #include <sys/types.h>
67 #if HAVE_SYS_WAIT_H
68 # include <sys/wait.h>
69 #endif
70 #include <dirent.h>
71 #include <time.h>
72 #include <regex.h>
74 #ifdef G_OS_UNIX
75 #include <sys/utsname.h>
76 #endif
78 #include <fcntl.h>
80 #ifdef G_OS_WIN32
81 # include <direct.h>
82 # include <io.h>
83 #endif
85 #include "utils.h"
86 #include "socket.h"
87 #include "codeconv.h"
88 #include "tlds.h"
89 #include "timing.h"
90 #include "file-utils.h"
92 #define BUFFSIZE 8192
94 static gboolean debug_mode = FALSE;
96 void list_free_strings_full(GList *list)
98 g_list_free_full(list, (GDestroyNotify)g_free);
101 void slist_free_strings_full(GSList *list)
103 g_slist_free_full(list, (GDestroyNotify)g_free);
106 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
108 g_free(key);
111 void hash_free_strings(GHashTable *table)
113 g_hash_table_foreach(table, hash_free_strings_func, NULL);
116 gint str_case_equal(gconstpointer v, gconstpointer v2)
118 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
121 guint str_case_hash(gconstpointer key)
123 const gchar *p = key;
124 guint h = *p;
126 if (h) {
127 h = g_ascii_tolower(h);
128 for (p += 1; *p != '\0'; p++)
129 h = (h << 5) - h + g_ascii_tolower(*p);
132 return h;
135 gint to_number(const gchar *nstr)
137 register const gchar *p;
139 if (*nstr == '\0') return -1;
141 for (p = nstr; *p != '\0'; p++)
142 if (!g_ascii_isdigit(*p)) return -1;
144 return atoi(nstr);
147 /* convert integer into string,
148 nstr must be not lower than 11 characters length */
149 gchar *itos_buf(gchar *nstr, gint n)
151 g_snprintf(nstr, 11, "%d", n);
152 return nstr;
155 /* convert integer into string */
156 gchar *itos(gint n)
158 static gchar nstr[11];
160 return itos_buf(nstr, n);
163 #define divide(num,divisor,i,d) \
165 i = num >> divisor; \
166 d = num & ((1<<divisor)-1); \
167 d = (d*100) >> divisor; \
172 * \brief Convert a given size in bytes in a human-readable string
174 * \param size The size expressed in bytes to convert in string
175 * \return The string that respresents the size in an human-readable way
177 gchar *to_human_readable(goffset size)
179 static gchar str[14];
180 static gchar *b_format = NULL, *kb_format = NULL,
181 *mb_format = NULL, *gb_format = NULL;
182 register int t = 0, r = 0;
183 if (b_format == NULL) {
184 b_format = _("%dB");
185 kb_format = _("%d.%02dKiB");
186 mb_format = _("%d.%02dMiB");
187 gb_format = _("%.2fGiB");
190 if (size < (goffset)1024) {
191 g_snprintf(str, sizeof(str), b_format, (gint)size);
192 return str;
193 } else if (size >> 10 < (goffset)1024) {
194 divide(size, 10, t, r);
195 g_snprintf(str, sizeof(str), kb_format, t, r);
196 return str;
197 } else if (size >> 20 < (goffset)1024) {
198 divide(size, 20, t, r);
199 g_snprintf(str, sizeof(str), mb_format, t, r);
200 return str;
201 } else {
202 g_snprintf(str, sizeof(str), gb_format, (gfloat)(size >> 30));
203 return str;
207 /* compare paths */
208 gint path_cmp(const gchar *s1, const gchar *s2)
210 gint len1, len2;
211 int rc;
212 #ifdef G_OS_WIN32
213 gchar *s1buf, *s2buf;
214 #endif
216 if (s1 == NULL || s2 == NULL) return -1;
217 if (*s1 == '\0' || *s2 == '\0') return -1;
219 #ifdef G_OS_WIN32
220 s1buf = g_strdup (s1);
221 s2buf = g_strdup (s2);
222 subst_char (s1buf, '/', G_DIR_SEPARATOR);
223 subst_char (s2buf, '/', G_DIR_SEPARATOR);
224 s1 = s1buf;
225 s2 = s2buf;
226 #endif /* !G_OS_WIN32 */
228 len1 = strlen(s1);
229 len2 = strlen(s2);
231 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
232 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
234 rc = strncmp(s1, s2, MAX(len1, len2));
235 #ifdef G_OS_WIN32
236 g_free (s1buf);
237 g_free (s2buf);
238 #endif /* !G_OS_WIN32 */
239 return rc;
242 /* remove trailing return code */
243 gchar *strretchomp(gchar *str)
245 register gchar *s;
247 if (!*str) return str;
249 for (s = str + strlen(str) - 1;
250 s >= str && (*s == '\n' || *s == '\r');
251 s--)
252 *s = '\0';
254 return str;
257 /* remove trailing character */
258 gchar *strtailchomp(gchar *str, gchar tail_char)
260 register gchar *s;
262 if (!*str) return str;
263 if (tail_char == '\0') return str;
265 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
266 *s = '\0';
268 return str;
271 /* remove CR (carriage return) */
272 gchar *strcrchomp(gchar *str)
274 register gchar *s;
276 if (!*str) return str;
278 s = str + strlen(str) - 1;
279 if (*s == '\n' && s > str && *(s - 1) == '\r') {
280 *(s - 1) = '\n';
281 *s = '\0';
284 return str;
287 /* truncates string at first CR (carriage return) or LF (line feed) */
288 gchar *strcrlftrunc(gchar *str)
290 gchar *p = NULL;
292 if ((str == NULL) || (!*str)) return str;
294 if ((p = strstr(str, "\r")) != NULL)
295 *p = '\0';
296 if ((p = strstr(str, "\n")) != NULL)
297 *p = '\0';
299 return str;
302 #ifndef HAVE_STRCASESTR
303 /* Similar to `strstr' but this function ignores the case of both strings. */
304 gchar *strcasestr(const gchar *haystack, const gchar *needle)
306 size_t haystack_len = strlen(haystack);
308 return strncasestr(haystack, haystack_len, needle);
310 #endif /* HAVE_STRCASESTR */
312 gchar *strncasestr(const gchar *haystack, gint haystack_len, const gchar *needle)
314 register size_t needle_len;
316 needle_len = strlen(needle);
318 if (haystack_len < needle_len || needle_len == 0)
319 return NULL;
321 while (haystack_len >= needle_len) {
322 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
323 return (gchar *)haystack;
324 else {
325 haystack++;
326 haystack_len--;
330 return NULL;
333 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
334 gconstpointer needle, size_t needlelen)
336 const gchar *haystack_ = (const gchar *)haystack;
337 const gchar *needle_ = (const gchar *)needle;
338 const gchar *haystack_cur = (const gchar *)haystack;
339 size_t haystack_left = haystacklen;
341 if (needlelen == 1)
342 return memchr(haystack_, *needle_, haystacklen);
344 while ((haystack_cur = memchr(haystack_cur, *needle_, haystack_left))
345 != NULL) {
346 if (haystacklen - (haystack_cur - haystack_) < needlelen)
347 break;
348 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
349 return (gpointer)haystack_cur;
350 else{
351 haystack_cur++;
352 haystack_left = haystacklen - (haystack_cur - haystack_);
356 return NULL;
359 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
360 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
362 register const gchar *s = src;
363 register gchar *d = dest;
365 while (--n && *s)
366 *d++ = *s++;
367 *d = '\0';
369 return dest;
373 /* Examine if next block is non-ASCII string */
374 gboolean is_next_nonascii(const gchar *s)
376 const gchar *p;
378 /* skip head space */
379 for (p = s; *p != '\0' && g_ascii_isspace(*p); p++)
381 for (; *p != '\0' && !g_ascii_isspace(*p); p++) {
382 if (*(guchar *)p > 127 || *(guchar *)p < 32)
383 return TRUE;
386 return FALSE;
389 gint get_next_word_len(const gchar *s)
391 gint len = 0;
393 for (; *s != '\0' && !g_ascii_isspace(*s); s++, len++)
396 return len;
399 static void trim_subject_for_compare(gchar *str)
401 gchar *srcp;
403 eliminate_parenthesis(str, '[', ']');
404 eliminate_parenthesis(str, '(', ')');
405 g_strstrip(str);
407 srcp = str + subject_get_prefix_length(str);
408 if (srcp != str)
409 memmove(str, srcp, strlen(srcp) + 1);
412 static void trim_subject_for_sort(gchar *str)
414 gchar *srcp;
416 g_strstrip(str);
418 srcp = str + subject_get_prefix_length(str);
419 if (srcp != str)
420 memmove(str, srcp, strlen(srcp) + 1);
423 /* compare subjects */
424 gint subject_compare(const gchar *s1, const gchar *s2)
426 gchar *str1, *str2;
428 if (!s1 || !s2) return -1;
429 if (!*s1 || !*s2) return -1;
431 Xstrdup_a(str1, s1, return -1);
432 Xstrdup_a(str2, s2, return -1);
434 trim_subject_for_compare(str1);
435 trim_subject_for_compare(str2);
437 if (!*str1 || !*str2) return -1;
439 return strcmp(str1, str2);
442 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
444 gchar *str1, *str2;
446 if (!s1 || !s2) return -1;
448 Xstrdup_a(str1, s1, return -1);
449 Xstrdup_a(str2, s2, return -1);
451 trim_subject_for_sort(str1);
452 trim_subject_for_sort(str2);
454 if (!g_utf8_validate(str1, -1, NULL)) {
455 g_warning("message subject \"%s\" failed UTF-8 validation", str1);
456 return 0;
457 } else if (!g_utf8_validate(str2, -1, NULL)) {
458 g_warning("message subject \"%s\" failed UTF-8 validation", str2);
459 return 0;
462 return g_utf8_collate(str1, str2);
465 void trim_subject(gchar *str)
467 register gchar *srcp;
468 gchar op, cl;
469 gint in_brace;
471 g_strstrip(str);
473 srcp = str + subject_get_prefix_length(str);
475 if (*srcp == '[') {
476 op = '[';
477 cl = ']';
478 } else if (*srcp == '(') {
479 op = '(';
480 cl = ')';
481 } else
482 op = 0;
484 if (op) {
485 ++srcp;
486 in_brace = 1;
487 while (*srcp) {
488 if (*srcp == op)
489 in_brace++;
490 else if (*srcp == cl)
491 in_brace--;
492 srcp++;
493 if (in_brace == 0)
494 break;
497 while (g_ascii_isspace(*srcp)) srcp++;
498 memmove(str, srcp, strlen(srcp) + 1);
501 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
503 register gchar *srcp, *destp;
504 gint in_brace;
506 destp = str;
508 while ((destp = strchr(destp, op))) {
509 in_brace = 1;
510 srcp = destp + 1;
511 while (*srcp) {
512 if (*srcp == op)
513 in_brace++;
514 else if (*srcp == cl)
515 in_brace--;
516 srcp++;
517 if (in_brace == 0)
518 break;
520 while (g_ascii_isspace(*srcp)) srcp++;
521 memmove(destp, srcp, strlen(srcp) + 1);
525 void extract_parenthesis(gchar *str, gchar op, gchar cl)
527 register gchar *srcp, *destp;
528 gint in_brace;
530 destp = str;
532 while ((srcp = strchr(destp, op))) {
533 if (destp > str)
534 *destp++ = ' ';
535 memmove(destp, srcp + 1, strlen(srcp));
536 in_brace = 1;
537 while(*destp) {
538 if (*destp == op)
539 in_brace++;
540 else if (*destp == cl)
541 in_brace--;
543 if (in_brace == 0)
544 break;
546 destp++;
549 *destp = '\0';
552 static void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
553 gchar op, gchar cl)
555 register gchar *srcp, *destp;
556 gint in_brace;
557 gboolean in_quote = FALSE;
559 destp = str;
561 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
562 if (destp > str)
563 *destp++ = ' ';
564 memmove(destp, srcp + 1, strlen(srcp));
565 in_brace = 1;
566 while(*destp) {
567 if (*destp == op && !in_quote)
568 in_brace++;
569 else if (*destp == cl && !in_quote)
570 in_brace--;
571 else if (*destp == quote_chr)
572 in_quote ^= TRUE;
574 if (in_brace == 0)
575 break;
577 destp++;
580 *destp = '\0';
583 void extract_quote(gchar *str, gchar quote_chr)
585 register gchar *p;
587 if ((str = strchr(str, quote_chr))) {
588 p = str;
589 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
590 memmove(p - 1, p, strlen(p) + 1);
591 p--;
593 if(p) {
594 *p = '\0';
595 memmove(str, str + 1, p - str);
600 /* Returns a newly allocated string with all quote_chr not at the beginning
601 or the end of str escaped with '\' or the given str if not required. */
602 gchar *escape_internal_quotes(gchar *str, gchar quote_chr)
604 register gchar *p, *q;
605 gchar *qstr;
606 int k = 0, l = 0;
608 if (str == NULL || *str == '\0')
609 return str;
611 /* search for unescaped quote_chr */
612 p = str;
613 if (*p == quote_chr)
614 ++p, ++l;
615 while (*p) {
616 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
617 ++k;
618 ++p, ++l;
620 if (!k) /* nothing to escape */
621 return str;
623 /* unescaped quote_chr found */
624 qstr = g_malloc(l + k + 1);
625 p = str;
626 q = qstr;
627 if (*p == quote_chr) {
628 *q = quote_chr;
629 ++p, ++q;
631 while (*p) {
632 if (*p == quote_chr && *(p - 1) != '\\' && *(p + 1) != '\0')
633 *q++ = '\\';
634 *q++ = *p++;
636 *q = '\0';
638 return qstr;
641 void eliminate_address_comment(gchar *str)
643 register gchar *srcp, *destp;
644 gint in_brace;
646 destp = str;
648 while ((destp = strchr(destp, '"'))) {
649 if ((srcp = strchr(destp + 1, '"'))) {
650 srcp++;
651 if (*srcp == '@') {
652 destp = srcp + 1;
653 } else {
654 while (g_ascii_isspace(*srcp)) srcp++;
655 memmove(destp, srcp, strlen(srcp) + 1);
657 } else {
658 *destp = '\0';
659 break;
663 destp = str;
665 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
666 in_brace = 1;
667 srcp = destp + 1;
668 while (*srcp) {
669 if (*srcp == '(')
670 in_brace++;
671 else if (*srcp == ')')
672 in_brace--;
673 srcp++;
674 if (in_brace == 0)
675 break;
677 while (g_ascii_isspace(*srcp)) srcp++;
678 memmove(destp, srcp, strlen(srcp) + 1);
682 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
684 gboolean in_quote = FALSE;
686 while (*str) {
687 if (*str == c && !in_quote)
688 return (gchar *)str;
689 if (*str == quote_chr)
690 in_quote ^= TRUE;
691 str++;
694 return NULL;
697 void extract_address(gchar *str)
699 cm_return_if_fail(str != NULL);
700 eliminate_address_comment(str);
701 if (strchr_with_skip_quote(str, '"', '<'))
702 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
703 g_strstrip(str);
706 void extract_list_id_str(gchar *str)
708 if (strchr_with_skip_quote(str, '"', '<'))
709 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
710 g_strstrip(str);
713 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
715 gchar *work;
716 gchar *workp;
718 if (!str) return addr_list;
720 Xstrdup_a(work, str, return addr_list);
722 if (removecomments)
723 eliminate_address_comment(work);
724 workp = work;
726 while (workp && *workp) {
727 gchar *p, *next;
729 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
730 *p = '\0';
731 next = p + 1;
732 } else
733 next = NULL;
735 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
736 extract_parenthesis_with_skip_quote
737 (workp, '"', '<', '>');
739 g_strstrip(workp);
740 if (*workp)
741 addr_list = g_slist_append(addr_list, g_strdup(workp));
743 workp = next;
746 return addr_list;
749 GSList *address_list_append(GSList *addr_list, const gchar *str)
751 return address_list_append_real(addr_list, str, TRUE);
754 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
756 return address_list_append_real(addr_list, str, FALSE);
759 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
761 const gchar *strp;
763 if (!str) return msgid_list;
764 strp = str;
766 while (strp && *strp) {
767 const gchar *start, *end;
768 gchar *msgid;
770 if ((start = strchr(strp, '<')) != NULL) {
771 end = strchr(start + 1, '>');
772 if (!end) break;
773 } else
774 break;
776 msgid = g_strndup(start + 1, end - start - 1);
777 g_strstrip(msgid);
778 if (*msgid)
779 msgid_list = g_slist_prepend(msgid_list, msgid);
780 else
781 g_free(msgid);
783 strp = end + 1;
786 return msgid_list;
789 GSList *references_list_append(GSList *msgid_list, const gchar *str)
791 GSList *list;
793 list = references_list_prepend(NULL, str);
794 list = g_slist_reverse(list);
795 msgid_list = g_slist_concat(msgid_list, list);
797 return msgid_list;
800 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
802 gchar *work;
803 gchar *workp;
805 if (!str) return group_list;
807 Xstrdup_a(work, str, return group_list);
809 workp = work;
811 while (workp && *workp) {
812 gchar *p, *next;
814 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
815 *p = '\0';
816 next = p + 1;
817 } else
818 next = NULL;
820 g_strstrip(workp);
821 if (*workp)
822 group_list = g_slist_append(group_list,
823 g_strdup(workp));
825 workp = next;
828 return group_list;
831 GList *add_history(GList *list, const gchar *str)
833 GList *old;
834 gchar *oldstr;
836 cm_return_val_if_fail(str != NULL, list);
838 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)g_strcmp0);
839 if (old) {
840 oldstr = old->data;
841 list = g_list_remove(list, old->data);
842 g_free(oldstr);
843 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
844 GList *last;
846 last = g_list_last(list);
847 if (last) {
848 oldstr = last->data;
849 list = g_list_remove(list, last->data);
850 g_free(oldstr);
854 list = g_list_prepend(list, g_strdup(str));
856 return list;
859 void remove_return(gchar *str)
861 register gchar *p = str;
863 while (*p) {
864 if (*p == '\n' || *p == '\r')
865 memmove(p, p + 1, strlen(p));
866 else
867 p++;
871 void remove_space(gchar *str)
873 register gchar *p = str;
874 register gint spc;
876 while (*p) {
877 spc = 0;
878 while (g_ascii_isspace(*(p + spc)))
879 spc++;
880 if (spc)
881 memmove(p, p + spc, strlen(p + spc) + 1);
882 else
883 p++;
887 void unfold_line(gchar *str)
889 register gchar *ch;
890 register gunichar c;
891 register gint len;
893 ch = str; /* iterator for source string */
895 while (*ch != 0) {
896 c = g_utf8_get_char_validated(ch, -1);
898 if (c == (gunichar)-1 || c == (gunichar)-2) {
899 /* non-unicode byte, move past it */
900 ch++;
901 continue;
904 len = g_unichar_to_utf8(c, NULL);
906 if ((!g_unichar_isdefined(c) || !g_unichar_isprint(c) ||
907 g_unichar_isspace(c)) && c != 173) {
908 /* replace anything bad or whitespacey with a single space */
909 *ch = ' ';
910 ch++;
911 if (len > 1) {
912 /* move rest of the string forwards, since we just replaced
913 * a multi-byte sequence with one byte */
914 memmove(ch, ch + len-1, strlen(ch + len-1) + 1);
916 } else {
917 /* A valid unicode character, copy it. */
918 ch += len;
923 void subst_char(gchar *str, gchar orig, gchar subst)
925 register gchar *p = str;
927 while (*p) {
928 if (*p == orig)
929 *p = subst;
930 p++;
934 void subst_chars(gchar *str, gchar *orig, gchar subst)
936 register gchar *p = str;
938 while (*p) {
939 if (strchr(orig, *p) != NULL)
940 *p = subst;
941 p++;
945 void subst_for_filename(gchar *str)
947 if (!str)
948 return;
949 #ifdef G_OS_WIN32
950 subst_chars(str, "\t\r\n\\/*?:", '_');
951 #else
952 subst_chars(str, "\t\r\n\\/*", '_');
953 #endif
956 void subst_for_shellsafe_filename(gchar *str)
958 if (!str)
959 return;
960 subst_for_filename(str);
961 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
964 gboolean is_ascii_str(const gchar *str)
966 const guchar *p = (const guchar *)str;
968 while (*p != '\0') {
969 if (*p != '\t' && *p != ' ' &&
970 *p != '\r' && *p != '\n' &&
971 (*p < 32 || *p >= 127))
972 return FALSE;
973 p++;
976 return TRUE;
979 static const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
981 gchar * position = NULL;
982 gchar * tmp_pos = NULL;
983 int i;
985 if (str == NULL || quote_chars == NULL)
986 return NULL;
988 for (i = 0; i < strlen(quote_chars); i++) {
989 tmp_pos = strrchr (str, quote_chars[i]);
990 if(position == NULL
991 || (tmp_pos != NULL && position <= tmp_pos) )
992 position = tmp_pos;
994 return position;
997 gint get_quote_level(const gchar *str, const gchar *quote_chars)
999 const gchar *first_pos;
1000 const gchar *last_pos;
1001 const gchar *p = str;
1002 gint quote_level = -1;
1004 /* speed up line processing by only searching to the last '>' */
1005 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1006 /* skip a line if it contains a '<' before the initial '>' */
1007 if (memchr(str, '<', first_pos - str) != NULL)
1008 return -1;
1009 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1010 } else
1011 return -1;
1013 while (p <= last_pos) {
1014 while (p < last_pos) {
1015 if (g_ascii_isspace(*p))
1016 p++;
1017 else
1018 break;
1021 if (strchr(quote_chars, *p))
1022 quote_level++;
1023 else if (*p != '-' && !g_ascii_isspace(*p) && p <= last_pos) {
1024 /* any characters are allowed except '-','<' and space */
1025 while (*p != '-' && *p != '<'
1026 && !strchr(quote_chars, *p)
1027 && !g_ascii_isspace(*p)
1028 && p < last_pos)
1029 p++;
1030 if (strchr(quote_chars, *p))
1031 quote_level++;
1032 else
1033 break;
1036 p++;
1039 return quote_level;
1042 gint check_line_length(const gchar *str, gint max_chars, gint *line)
1044 const gchar *p = str, *q;
1045 gint cur_line = 0, len;
1047 while ((q = strchr(p, '\n')) != NULL) {
1048 len = q - p + 1;
1049 if (len > max_chars) {
1050 if (line)
1051 *line = cur_line;
1052 return -1;
1054 p = q + 1;
1055 ++cur_line;
1058 len = strlen(p);
1059 if (len > max_chars) {
1060 if (line)
1061 *line = cur_line;
1062 return -1;
1065 return 0;
1068 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1070 gchar * position = NULL;
1071 gchar * tmp_pos = NULL;
1072 int i;
1074 if (str == NULL || quote_chars == NULL)
1075 return NULL;
1077 for (i = 0; i < strlen(quote_chars); i++) {
1078 tmp_pos = strchr (str, quote_chars[i]);
1079 if(position == NULL
1080 || (tmp_pos != NULL && position >= tmp_pos) )
1081 position = tmp_pos;
1083 return position;
1086 static gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1088 register guint haystack_len, needle_len;
1089 gboolean in_squote = FALSE, in_dquote = FALSE;
1091 haystack_len = strlen(haystack);
1092 needle_len = strlen(needle);
1094 if (haystack_len < needle_len || needle_len == 0)
1095 return NULL;
1097 while (haystack_len >= needle_len) {
1098 if (!in_squote && !in_dquote &&
1099 !strncmp(haystack, needle, needle_len))
1100 return (gchar *)haystack;
1102 /* 'foo"bar"' -> foo"bar"
1103 "foo'bar'" -> foo'bar' */
1104 if (*haystack == '\'') {
1105 if (in_squote)
1106 in_squote = FALSE;
1107 else if (!in_dquote)
1108 in_squote = TRUE;
1109 } else if (*haystack == '\"') {
1110 if (in_dquote)
1111 in_dquote = FALSE;
1112 else if (!in_squote)
1113 in_dquote = TRUE;
1114 } else if (*haystack == '\\') {
1115 haystack++;
1116 haystack_len--;
1119 haystack++;
1120 haystack_len--;
1123 return NULL;
1126 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1127 gint max_tokens)
1129 GSList *string_list = NULL, *slist;
1130 gchar **str_array, *s, *new_str;
1131 guint i, n = 1, len;
1133 cm_return_val_if_fail(str != NULL, NULL);
1134 cm_return_val_if_fail(delim != NULL, NULL);
1136 if (max_tokens < 1)
1137 max_tokens = G_MAXINT;
1139 s = strstr_with_skip_quote(str, delim);
1140 if (s) {
1141 guint delimiter_len = strlen(delim);
1143 do {
1144 len = s - str;
1145 new_str = g_strndup(str, len);
1147 if (new_str[0] == '\'' || new_str[0] == '\"') {
1148 if (new_str[len - 1] == new_str[0]) {
1149 new_str[len - 1] = '\0';
1150 memmove(new_str, new_str + 1, len - 1);
1153 string_list = g_slist_prepend(string_list, new_str);
1154 n++;
1155 str = s + delimiter_len;
1156 s = strstr_with_skip_quote(str, delim);
1157 } while (--max_tokens && s);
1160 if (*str) {
1161 new_str = g_strdup(str);
1162 if (new_str[0] == '\'' || new_str[0] == '\"') {
1163 len = strlen(str);
1164 if (new_str[len - 1] == new_str[0]) {
1165 new_str[len - 1] = '\0';
1166 memmove(new_str, new_str + 1, len - 1);
1169 string_list = g_slist_prepend(string_list, new_str);
1170 n++;
1173 str_array = g_new(gchar*, n);
1175 i = n - 1;
1177 str_array[i--] = NULL;
1178 for (slist = string_list; slist; slist = slist->next)
1179 str_array[i--] = slist->data;
1181 g_slist_free(string_list);
1183 return str_array;
1186 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1188 gchar *abbrev_group;
1189 gchar *ap;
1190 const gchar *p = group;
1191 const gchar *last;
1193 cm_return_val_if_fail(group != NULL, NULL);
1195 last = group + strlen(group);
1196 abbrev_group = ap = g_malloc(strlen(group) + 1);
1198 while (*p) {
1199 while (*p == '.')
1200 *ap++ = *p++;
1201 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1202 *ap++ = *p++;
1203 while (*p != '.') p++;
1204 } else {
1205 strcpy(ap, p);
1206 return abbrev_group;
1210 *ap = '\0';
1211 return abbrev_group;
1214 gchar *trim_string(const gchar *str, gint len)
1216 const gchar *p = str;
1217 gint mb_len;
1218 gchar *new_str;
1219 gint new_len = 0;
1221 if (!str) return NULL;
1222 if (strlen(str) <= len)
1223 return g_strdup(str);
1224 if (g_utf8_validate(str, -1, NULL) == FALSE)
1225 return g_strdup(str);
1227 while (*p != '\0') {
1228 mb_len = g_utf8_skip[*(guchar *)p];
1229 if (mb_len == 0)
1230 break;
1231 else if (new_len + mb_len > len)
1232 break;
1234 new_len += mb_len;
1235 p += mb_len;
1238 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1239 return g_strconcat(new_str, "...", NULL);
1242 GList *uri_list_extract_filenames(const gchar *uri_list)
1244 GList *result = NULL;
1245 const gchar *p, *q;
1246 gchar *escaped_utf8uri;
1248 p = uri_list;
1250 while (p) {
1251 if (*p != '#') {
1252 while (g_ascii_isspace(*p)) p++;
1253 if (!strncmp(p, "file:", 5)) {
1254 q = p;
1255 q += 5;
1256 while (*q && *q != '\n' && *q != '\r') q++;
1258 if (q > p) {
1259 gchar *file, *locale_file = NULL;
1260 q--;
1261 while (q > p && g_ascii_isspace(*q))
1262 q--;
1263 Xalloca(escaped_utf8uri, q - p + 2,
1264 return result);
1265 Xalloca(file, q - p + 2,
1266 return result);
1267 *file = '\0';
1268 strncpy(escaped_utf8uri, p, q - p + 1);
1269 escaped_utf8uri[q - p + 1] = '\0';
1270 decode_uri_with_plus(file, escaped_utf8uri, FALSE);
1272 * g_filename_from_uri() rejects escaped/locale encoded uri
1273 * string which come from Nautilus.
1275 #ifndef G_OS_WIN32
1276 if (g_utf8_validate(file, -1, NULL))
1277 locale_file
1278 = conv_codeset_strdup(
1279 file + 5,
1280 CS_UTF_8,
1281 conv_get_locale_charset_str());
1282 if (!locale_file)
1283 locale_file = g_strdup(file + 5);
1284 #else
1285 locale_file = g_filename_from_uri(escaped_utf8uri, NULL, NULL);
1286 #endif
1287 result = g_list_append(result, locale_file);
1291 p = strchr(p, '\n');
1292 if (p) p++;
1295 return result;
1298 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1299 * characters
1301 static gint axtoi(const gchar *hexstr)
1303 gint hi, lo, result;
1305 hi = hexstr[0];
1306 if ('0' <= hi && hi <= '9') {
1307 hi -= '0';
1308 } else
1309 if ('a' <= hi && hi <= 'f') {
1310 hi -= ('a' - 10);
1311 } else
1312 if ('A' <= hi && hi <= 'F') {
1313 hi -= ('A' - 10);
1316 lo = hexstr[1];
1317 if ('0' <= lo && lo <= '9') {
1318 lo -= '0';
1319 } else
1320 if ('a' <= lo && lo <= 'f') {
1321 lo -= ('a'-10);
1322 } else
1323 if ('A' <= lo && lo <= 'F') {
1324 lo -= ('A' - 10);
1326 result = lo + (16 * hi);
1327 return result;
1330 gboolean is_uri_string(const gchar *str)
1332 while (str && *str && g_ascii_isspace(*str))
1333 str++;
1334 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1335 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1336 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1337 g_ascii_strncasecmp(str, "ftps://", 7) == 0 ||
1338 g_ascii_strncasecmp(str, "sftp://", 7) == 0 ||
1339 g_ascii_strncasecmp(str, "ftp.", 4) == 0 ||
1340 g_ascii_strncasecmp(str, "webcal://", 9) == 0 ||
1341 g_ascii_strncasecmp(str, "webcals://", 10) == 0 ||
1342 g_ascii_strncasecmp(str, "www.", 4) == 0);
1345 gchar *get_uri_path(const gchar *uri)
1347 while (uri && *uri && g_ascii_isspace(*uri))
1348 uri++;
1349 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1350 return (gchar *)(uri + 7);
1351 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1352 return (gchar *)(uri + 8);
1353 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1354 return (gchar *)(uri + 6);
1355 else if (g_ascii_strncasecmp(uri, "ftps://", 7) == 0)
1356 return (gchar *)(uri + 7);
1357 else if (g_ascii_strncasecmp(uri, "sftp://", 7) == 0)
1358 return (gchar *)(uri + 7);
1359 else if (g_ascii_strncasecmp(uri, "webcal://", 9) == 0)
1360 return (gchar *)(uri + 7);
1361 else if (g_ascii_strncasecmp(uri, "webcals://", 10) == 0)
1362 return (gchar *)(uri + 7);
1363 else
1364 return (gchar *)uri;
1367 gint get_uri_len(const gchar *str)
1369 const gchar *p;
1371 if (is_uri_string(str)) {
1372 for (p = str; *p != '\0'; p++) {
1373 if (!g_ascii_isgraph(*p) || strchr("<>\"", *p))
1374 break;
1376 return p - str;
1379 return 0;
1382 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1383 * plusses, and escape characters are used)
1385 void decode_uri_with_plus(gchar *decoded_uri, const gchar *encoded_uri, gboolean with_plus)
1387 gchar *dec = decoded_uri;
1388 const gchar *enc = encoded_uri;
1390 while (*enc) {
1391 if (*enc == '%') {
1392 enc++;
1393 if (isxdigit((guchar)enc[0]) &&
1394 isxdigit((guchar)enc[1])) {
1395 *dec = axtoi(enc);
1396 dec++;
1397 enc += 2;
1399 } else {
1400 if (with_plus && *enc == '+')
1401 *dec = ' ';
1402 else
1403 *dec = *enc;
1404 dec++;
1405 enc++;
1409 *dec = '\0';
1412 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1414 decode_uri_with_plus(decoded_uri, encoded_uri, TRUE);
1417 static gchar *decode_uri_gdup(const gchar *encoded_uri)
1419 gchar *buffer = g_malloc(strlen(encoded_uri)+1);
1420 decode_uri_with_plus(buffer, encoded_uri, FALSE);
1421 return buffer;
1424 gint scan_mailto_url(const gchar *mailto, gchar **from, gchar **to, gchar **cc, gchar **bcc,
1425 gchar **subject, gchar **body, gchar ***attach, gchar **inreplyto)
1427 gchar *tmp_mailto;
1428 gchar *p;
1429 const gchar *forbidden_uris[] = { ".gnupg/",
1430 "/etc/passwd",
1431 "/etc/shadow",
1432 ".ssh/",
1433 "../",
1434 NULL };
1435 gint num_attach = 0;
1437 cm_return_val_if_fail(mailto != NULL, -1);
1439 Xstrdup_a(tmp_mailto, mailto, return -1);
1441 if (!strncmp(tmp_mailto, "mailto:", 7))
1442 tmp_mailto += 7;
1444 p = strchr(tmp_mailto, '?');
1445 if (p) {
1446 *p = '\0';
1447 p++;
1450 if (to && !*to)
1451 *to = decode_uri_gdup(tmp_mailto);
1453 while (p) {
1454 gchar *field, *value;
1456 field = p;
1458 p = strchr(p, '=');
1459 if (!p) break;
1460 *p = '\0';
1461 p++;
1463 value = p;
1465 p = strchr(p, '&');
1466 if (p) {
1467 *p = '\0';
1468 p++;
1471 if (*value == '\0') continue;
1473 if (from && !g_ascii_strcasecmp(field, "from")) {
1474 if (!*from) {
1475 *from = decode_uri_gdup(value);
1476 } else {
1477 gchar *tmp = decode_uri_gdup(value);
1478 gchar *new_from = g_strdup_printf("%s, %s", *from, tmp);
1479 g_free(tmp);
1480 g_free(*from);
1481 *from = new_from;
1483 } else if (cc && !g_ascii_strcasecmp(field, "cc")) {
1484 if (!*cc) {
1485 *cc = decode_uri_gdup(value);
1486 } else {
1487 gchar *tmp = decode_uri_gdup(value);
1488 gchar *new_cc = g_strdup_printf("%s, %s", *cc, tmp);
1489 g_free(tmp);
1490 g_free(*cc);
1491 *cc = new_cc;
1493 } else if (bcc && !g_ascii_strcasecmp(field, "bcc")) {
1494 if (!*bcc) {
1495 *bcc = decode_uri_gdup(value);
1496 } else {
1497 gchar *tmp = decode_uri_gdup(value);
1498 gchar *new_bcc = g_strdup_printf("%s, %s", *bcc, tmp);
1499 g_free(tmp);
1500 g_free(*bcc);
1501 *bcc = new_bcc;
1503 } else if (subject && !*subject &&
1504 !g_ascii_strcasecmp(field, "subject")) {
1505 *subject = decode_uri_gdup(value);
1506 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1507 *body = decode_uri_gdup(value);
1508 } else if (body && !*body && !g_ascii_strcasecmp(field, "insert")) {
1509 int i = 0;
1510 gchar *tmp = decode_uri_gdup(value);
1512 for (; forbidden_uris[i]; i++) {
1513 if (strstr(tmp, forbidden_uris[i])) {
1514 g_print("Refusing to insert '%s', potential private data leak\n",
1515 tmp);
1516 g_free(tmp);
1517 tmp = NULL;
1518 break;
1522 if (tmp) {
1523 if (!is_file_entry_regular(tmp)) {
1524 g_warning("refusing to insert '%s', not a regular file", tmp);
1525 } else if (!g_file_get_contents(tmp, body, NULL, NULL)) {
1526 g_warning("couldn't set insert file '%s' in body", value);
1529 g_free(tmp);
1531 } else if (attach && !g_ascii_strcasecmp(field, "attach")) {
1532 int i = 0;
1533 gchar *tmp = decode_uri_gdup(value);
1534 gchar **my_att = g_malloc(sizeof(char *));
1536 my_att[0] = NULL;
1538 for (; forbidden_uris[i]; i++) {
1539 if (strstr(tmp, forbidden_uris[i])) {
1540 g_print("Refusing to attach '%s', potential private data leak\n",
1541 tmp);
1542 g_free(tmp);
1543 tmp = NULL;
1544 break;
1547 if (tmp) {
1548 /* attach is correct */
1549 num_attach++;
1550 my_att = g_realloc(my_att, (sizeof(char *))*(num_attach+1));
1551 my_att[num_attach-1] = tmp;
1552 my_att[num_attach] = NULL;
1553 *attach = my_att;
1555 else
1556 g_free(my_att);
1557 } else if (inreplyto && !*inreplyto &&
1558 !g_ascii_strcasecmp(field, "in-reply-to")) {
1559 *inreplyto = decode_uri_gdup(value);
1563 return 0;
1567 #ifdef G_OS_WIN32
1568 #include <windows.h>
1569 #ifndef CSIDL_APPDATA
1570 #define CSIDL_APPDATA 0x001a
1571 #endif
1572 #ifndef CSIDL_LOCAL_APPDATA
1573 #define CSIDL_LOCAL_APPDATA 0x001c
1574 #endif
1575 #ifndef CSIDL_FLAG_CREATE
1576 #define CSIDL_FLAG_CREATE 0x8000
1577 #endif
1578 #define DIM(v) (sizeof(v)/sizeof((v)[0]))
1580 #define RTLD_LAZY 0
1581 const char *
1582 w32_strerror (int w32_errno)
1584 static char strerr[256];
1585 int ec = (int)GetLastError ();
1587 if (w32_errno == 0)
1588 w32_errno = ec;
1589 FormatMessage (FORMAT_MESSAGE_FROM_SYSTEM, NULL, w32_errno,
1590 MAKELANGID (LANG_NEUTRAL, SUBLANG_DEFAULT),
1591 strerr, DIM (strerr)-1, NULL);
1592 return strerr;
1595 static __inline__ void *
1596 dlopen (const char * name, int flag)
1598 void * hd = LoadLibrary (name);
1599 return hd;
1602 static __inline__ void *
1603 dlsym (void * hd, const char * sym)
1605 if (hd && sym)
1607 void * fnc = GetProcAddress (hd, sym);
1608 if (!fnc)
1609 return NULL;
1610 return fnc;
1612 return NULL;
1616 static __inline__ const char *
1617 dlerror (void)
1619 return w32_strerror (0);
1623 static __inline__ int
1624 dlclose (void * hd)
1626 if (hd)
1628 FreeLibrary (hd);
1629 return 0;
1631 return -1;
1634 static HRESULT
1635 w32_shgetfolderpath (HWND a, int b, HANDLE c, DWORD d, LPSTR e)
1637 static int initialized;
1638 static HRESULT (WINAPI * func)(HWND,int,HANDLE,DWORD,LPSTR);
1640 if (!initialized)
1642 static char *dllnames[] = { "shell32.dll", "shfolder.dll", NULL };
1643 void *handle;
1644 int i;
1646 initialized = 1;
1648 for (i=0, handle = NULL; !handle && dllnames[i]; i++)
1650 handle = dlopen (dllnames[i], RTLD_LAZY);
1651 if (handle)
1653 func = dlsym (handle, "SHGetFolderPathW");
1654 if (!func)
1656 dlclose (handle);
1657 handle = NULL;
1663 if (func)
1664 return func (a,b,c,d,e);
1665 else
1666 return -1;
1669 /* Returns a static string with the directroy from which the module
1670 has been loaded. Returns an empty string on error. */
1671 static char *w32_get_module_dir(void)
1673 static char *moddir;
1675 if (!moddir) {
1676 char name[MAX_PATH+10];
1677 char *p;
1679 if ( !GetModuleFileNameA (0, name, sizeof (name)-10) )
1680 *name = 0;
1681 else {
1682 p = strrchr (name, '\\');
1683 if (p)
1684 *p = 0;
1685 else
1686 *name = 0;
1688 moddir = g_strdup (name);
1690 return moddir;
1692 #endif /* G_OS_WIN32 */
1694 /* Return a static string with the locale dir. */
1695 const gchar *get_locale_dir(void)
1697 static gchar *loc_dir;
1699 #ifdef G_OS_WIN32
1700 if (!loc_dir)
1701 loc_dir = g_strconcat(w32_get_module_dir(), G_DIR_SEPARATOR_S,
1702 "\\share\\locale", NULL);
1703 #endif
1704 if (!loc_dir)
1705 loc_dir = LOCALEDIR;
1707 return loc_dir;
1711 const gchar *get_home_dir(void)
1713 #ifdef G_OS_WIN32
1714 static char home_dir_utf16[MAX_PATH] = "";
1715 static gchar *home_dir_utf8 = NULL;
1716 if (home_dir_utf16[0] == '\0') {
1717 if (w32_shgetfolderpath
1718 (NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE,
1719 NULL, 0, home_dir_utf16) < 0)
1720 strcpy (home_dir_utf16, "C:\\Claws Mail");
1721 home_dir_utf8 = g_utf16_to_utf8 ((const gunichar2 *)home_dir_utf16, -1, NULL, NULL, NULL);
1723 return home_dir_utf8;
1724 #else
1725 static const gchar *homeenv = NULL;
1727 if (homeenv)
1728 return homeenv;
1730 if (!homeenv && g_getenv("HOME") != NULL)
1731 homeenv = g_strdup(g_getenv("HOME"));
1732 if (!homeenv)
1733 homeenv = g_get_home_dir();
1735 return homeenv;
1736 #endif
1739 static gchar *claws_rc_dir = NULL;
1740 static gboolean rc_dir_alt = FALSE;
1741 const gchar *get_rc_dir(void)
1744 if (!claws_rc_dir) {
1745 claws_rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1746 RC_DIR, NULL);
1747 debug_print("using default rc_dir %s\n", claws_rc_dir);
1749 return claws_rc_dir;
1752 void set_rc_dir(const gchar *dir)
1754 gchar *canonical_dir;
1755 if (claws_rc_dir != NULL) {
1756 g_print("Error: rc_dir already set\n");
1757 } else {
1758 int err = cm_canonicalize_filename(dir, &canonical_dir);
1759 int len;
1761 if (err) {
1762 g_print("Error looking for %s: %d(%s)\n",
1763 dir, -err, g_strerror(-err));
1764 exit(0);
1766 rc_dir_alt = TRUE;
1768 claws_rc_dir = canonical_dir;
1770 len = strlen(claws_rc_dir);
1771 if (claws_rc_dir[len - 1] == G_DIR_SEPARATOR)
1772 claws_rc_dir[len - 1] = '\0';
1774 debug_print("set rc_dir to %s\n", claws_rc_dir);
1775 if (!is_dir_exist(claws_rc_dir)) {
1776 if (make_dir_hier(claws_rc_dir) != 0) {
1777 g_print("Error: can't create %s\n",
1778 claws_rc_dir);
1779 exit(0);
1785 gboolean rc_dir_is_alt(void) {
1786 return rc_dir_alt;
1789 const gchar *get_mail_base_dir(void)
1791 return get_home_dir();
1794 const gchar *get_news_cache_dir(void)
1796 static gchar *news_cache_dir = NULL;
1797 if (!news_cache_dir)
1798 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1799 NEWS_CACHE_DIR, NULL);
1801 return news_cache_dir;
1804 const gchar *get_imap_cache_dir(void)
1806 static gchar *imap_cache_dir = NULL;
1808 if (!imap_cache_dir)
1809 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1810 IMAP_CACHE_DIR, NULL);
1812 return imap_cache_dir;
1815 const gchar *get_mime_tmp_dir(void)
1817 static gchar *mime_tmp_dir = NULL;
1819 if (!mime_tmp_dir)
1820 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1821 MIME_TMP_DIR, NULL);
1823 return mime_tmp_dir;
1826 const gchar *get_template_dir(void)
1828 static gchar *template_dir = NULL;
1830 if (!template_dir)
1831 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1832 TEMPLATE_DIR, NULL);
1834 return template_dir;
1837 #ifdef G_OS_WIN32
1838 const gchar *w32_get_cert_file(void)
1840 const gchar *cert_file = NULL;
1841 if (!cert_file)
1842 cert_file = g_strconcat(w32_get_module_dir(),
1843 "\\share\\claws-mail\\",
1844 "ca-certificates.crt",
1845 NULL);
1846 return cert_file;
1848 #endif
1850 /* Return the filepath of the claws-mail.desktop file */
1851 const gchar *get_desktop_file(void)
1853 #ifdef DESKTOPFILEPATH
1854 return DESKTOPFILEPATH;
1855 #else
1856 return NULL;
1857 #endif
1860 /* Return the default directory for Plugins. */
1861 const gchar *get_plugin_dir(void)
1863 #ifdef G_OS_WIN32
1864 static gchar *plugin_dir = NULL;
1866 if (!plugin_dir)
1867 plugin_dir = g_strconcat(w32_get_module_dir(),
1868 "\\lib\\claws-mail\\plugins\\",
1869 NULL);
1870 return plugin_dir;
1871 #else
1872 if (is_dir_exist(PLUGINDIR))
1873 return PLUGINDIR;
1874 else {
1875 static gchar *plugin_dir = NULL;
1876 if (!plugin_dir)
1877 plugin_dir = g_strconcat(get_rc_dir(),
1878 G_DIR_SEPARATOR_S, "plugins",
1879 G_DIR_SEPARATOR_S, NULL);
1880 return plugin_dir;
1882 #endif
1886 #ifdef G_OS_WIN32
1887 /* Return the default directory for Themes. */
1888 const gchar *w32_get_themes_dir(void)
1890 static gchar *themes_dir = NULL;
1892 if (!themes_dir)
1893 themes_dir = g_strconcat(w32_get_module_dir(),
1894 "\\share\\claws-mail\\themes",
1895 NULL);
1896 return themes_dir;
1898 #endif
1900 const gchar *get_tmp_dir(void)
1902 static gchar *tmp_dir = NULL;
1904 if (!tmp_dir)
1905 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1906 TMP_DIR, NULL);
1908 return tmp_dir;
1911 gchar *get_tmp_file(void)
1913 gchar *tmp_file;
1914 static guint32 id = 0;
1916 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1917 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1919 return tmp_file;
1922 const gchar *get_domain_name(void)
1924 #ifdef G_OS_UNIX
1925 static gchar *domain_name = NULL;
1926 struct addrinfo hints, *res;
1927 char hostname[256];
1928 int s;
1930 if (!domain_name) {
1931 if (gethostname(hostname, sizeof(hostname)) != 0) {
1932 perror("gethostname");
1933 domain_name = "localhost";
1934 } else {
1935 memset(&hints, 0, sizeof(struct addrinfo));
1936 hints.ai_family = AF_UNSPEC;
1937 hints.ai_socktype = 0;
1938 hints.ai_flags = AI_CANONNAME;
1939 hints.ai_protocol = 0;
1941 s = getaddrinfo(hostname, NULL, &hints, &res);
1942 if (s != 0) {
1943 fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
1944 domain_name = g_strdup(hostname);
1945 } else {
1946 domain_name = g_strdup(res->ai_canonname);
1947 freeaddrinfo(res);
1950 debug_print("domain name = %s\n", domain_name);
1953 return domain_name;
1954 #else
1955 return "localhost";
1956 #endif
1959 /* Tells whether the given host address string is a valid representation of a
1960 * numerical IP (v4 or, if supported, v6) address.
1962 gboolean is_numeric_host_address(const gchar *hostaddress)
1964 struct addrinfo hints, *res;
1965 int err;
1967 /* See what getaddrinfo makes of the string when told that it is a
1968 * numeric IP address representation. */
1969 memset(&hints, 0, sizeof(struct addrinfo));
1970 hints.ai_family = AF_UNSPEC;
1971 hints.ai_socktype = 0;
1972 hints.ai_flags = AI_NUMERICHOST;
1973 hints.ai_protocol = 0;
1975 err = getaddrinfo(hostaddress, NULL, &hints, &res);
1976 if (err == 0)
1977 freeaddrinfo(res);
1979 return (err == 0);
1982 off_t get_file_size(const gchar *file)
1984 #ifdef G_OS_WIN32
1985 GFile *f;
1986 GFileInfo *fi;
1987 GError *error = NULL;
1988 goffset size;
1990 f = g_file_new_for_path(file);
1991 fi = g_file_query_info(f, "standard::size",
1992 G_FILE_QUERY_INFO_NONE, NULL, &error);
1993 if (error != NULL) {
1994 debug_print("get_file_size error: %s\n", error->message);
1995 g_error_free(error);
1996 g_object_unref(f);
1997 return -1;
1999 size = g_file_info_get_size(fi);
2000 g_object_unref(fi);
2001 g_object_unref(f);
2002 return size;
2004 #else
2005 GStatBuf s;
2007 if (g_stat(file, &s) < 0) {
2008 FILE_OP_ERROR(file, "stat");
2009 return -1;
2012 return s.st_size;
2013 #endif
2016 time_t get_file_mtime(const gchar *file)
2018 GStatBuf s;
2020 if (g_stat(file, &s) < 0) {
2021 FILE_OP_ERROR(file, "stat");
2022 return -1;
2025 return s.st_mtime;
2028 gboolean file_exist(const gchar *file, gboolean allow_fifo)
2030 GStatBuf s;
2032 if (file == NULL)
2033 return FALSE;
2035 if (g_stat(file, &s) < 0) {
2036 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
2037 return FALSE;
2040 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
2041 return TRUE;
2043 return FALSE;
2047 /* Test on whether FILE is a relative file name. This is
2048 * straightforward for Unix but more complex for Windows. */
2049 gboolean is_relative_filename(const gchar *file)
2051 if (!file)
2052 return TRUE;
2053 #ifdef G_OS_WIN32
2054 if ( *file == '\\' && file[1] == '\\' && strchr (file+2, '\\') )
2055 return FALSE; /* Prefixed with a hostname - this can't
2056 * be a relative name. */
2058 if ( ((*file >= 'a' && *file <= 'z')
2059 || (*file >= 'A' && *file <= 'Z'))
2060 && file[1] == ':')
2061 file += 2; /* Skip drive letter. */
2063 return !(*file == '\\' || *file == '/');
2064 #else
2065 return !(*file == G_DIR_SEPARATOR);
2066 #endif
2070 gboolean is_dir_exist(const gchar *dir)
2072 if (dir == NULL)
2073 return FALSE;
2075 return g_file_test(dir, G_FILE_TEST_IS_DIR);
2078 gboolean is_file_entry_exist(const gchar *file)
2080 if (file == NULL)
2081 return FALSE;
2083 return g_file_test(file, G_FILE_TEST_EXISTS);
2086 gboolean is_file_entry_regular(const gchar *file)
2088 if (file == NULL)
2089 return FALSE;
2091 return g_file_test(file, G_FILE_TEST_IS_REGULAR);
2094 gboolean dirent_is_regular_file(struct dirent *d)
2096 #if !defined(G_OS_WIN32) && defined(HAVE_DIRENT_D_TYPE)
2097 if (d->d_type == DT_REG)
2098 return TRUE;
2099 else if (d->d_type != DT_UNKNOWN)
2100 return FALSE;
2101 #endif
2103 return g_file_test(d->d_name, G_FILE_TEST_IS_REGULAR);
2106 gint change_dir(const gchar *dir)
2108 gchar *prevdir = NULL;
2110 if (debug_mode)
2111 prevdir = g_get_current_dir();
2113 if (g_chdir(dir) < 0) {
2114 FILE_OP_ERROR(dir, "chdir");
2115 if (debug_mode) g_free(prevdir);
2116 return -1;
2117 } else if (debug_mode) {
2118 gchar *cwd;
2120 cwd = g_get_current_dir();
2121 if (strcmp(prevdir, cwd) != 0)
2122 g_print("current dir: %s\n", cwd);
2123 g_free(cwd);
2124 g_free(prevdir);
2127 return 0;
2130 gint make_dir(const gchar *dir)
2132 if (g_mkdir(dir, S_IRWXU) < 0) {
2133 FILE_OP_ERROR(dir, "mkdir");
2134 return -1;
2136 if (g_chmod(dir, S_IRWXU) < 0)
2137 FILE_OP_ERROR(dir, "chmod");
2139 return 0;
2142 gint make_dir_hier(const gchar *dir)
2144 gchar *parent_dir;
2145 const gchar *p;
2147 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2148 parent_dir = g_strndup(dir, p - dir);
2149 if (*parent_dir != '\0') {
2150 if (!is_dir_exist(parent_dir)) {
2151 if (make_dir(parent_dir) < 0) {
2152 g_free(parent_dir);
2153 return -1;
2157 g_free(parent_dir);
2160 if (!is_dir_exist(dir)) {
2161 if (make_dir(dir) < 0)
2162 return -1;
2165 return 0;
2168 gint remove_all_files(const gchar *dir)
2170 GDir *dp;
2171 const gchar *file_name;
2172 gchar *tmp;
2174 if ((dp = g_dir_open(dir, 0, NULL)) == NULL) {
2175 g_warning("failed to open directory: %s", dir);
2176 return -1;
2179 while ((file_name = g_dir_read_name(dp)) != NULL) {
2180 tmp = g_strconcat(dir, G_DIR_SEPARATOR_S, file_name, NULL);
2181 if (claws_unlink(tmp) < 0)
2182 FILE_OP_ERROR(tmp, "unlink");
2183 g_free(tmp);
2186 g_dir_close(dp);
2188 return 0;
2191 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2193 GDir *dp;
2194 const gchar *dir_name;
2195 gchar *prev_dir;
2196 gint file_no;
2198 if (first == last) {
2199 /* Skip all the dir reading part. */
2200 gchar *filename = g_strdup_printf("%s%s%u", dir, G_DIR_SEPARATOR_S, first);
2201 if (is_dir_exist(filename)) {
2202 /* a numbered directory with this name exists,
2203 * remove the dot-file instead */
2204 g_free(filename);
2205 filename = g_strdup_printf("%s%s.%u", dir, G_DIR_SEPARATOR_S, first);
2207 if (claws_unlink(filename) < 0) {
2208 FILE_OP_ERROR(filename, "unlink");
2209 g_free(filename);
2210 return -1;
2212 g_free(filename);
2213 return 0;
2216 prev_dir = g_get_current_dir();
2218 if (g_chdir(dir) < 0) {
2219 FILE_OP_ERROR(dir, "chdir");
2220 g_free(prev_dir);
2221 return -1;
2224 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2225 g_warning("failed to open directory: %s", dir);
2226 g_free(prev_dir);
2227 return -1;
2230 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2231 file_no = to_number(dir_name);
2232 if (file_no > 0 && first <= file_no && file_no <= last) {
2233 if (is_dir_exist(dir_name)) {
2234 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2235 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2236 FILE_OP_ERROR(dot_file, "unlink");
2238 g_free(dot_file);
2239 continue;
2241 if (claws_unlink(dir_name) < 0)
2242 FILE_OP_ERROR(dir_name, "unlink");
2246 g_dir_close(dp);
2248 if (g_chdir(prev_dir) < 0) {
2249 FILE_OP_ERROR(prev_dir, "chdir");
2250 g_free(prev_dir);
2251 return -1;
2254 g_free(prev_dir);
2256 return 0;
2259 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2261 GDir *dp;
2262 const gchar *dir_name;
2263 gchar *prev_dir;
2264 gint file_no;
2265 GHashTable *wanted_files;
2266 GSList *cur;
2267 GError *error = NULL;
2269 if (numberlist == NULL)
2270 return 0;
2272 prev_dir = g_get_current_dir();
2274 if (g_chdir(dir) < 0) {
2275 FILE_OP_ERROR(dir, "chdir");
2276 g_free(prev_dir);
2277 return -1;
2280 if ((dp = g_dir_open(".", 0, &error)) == NULL) {
2281 g_message("Couldn't open current directory: %s (%d).\n",
2282 error->message, error->code);
2283 g_error_free(error);
2284 g_free(prev_dir);
2285 return -1;
2288 wanted_files = g_hash_table_new(g_direct_hash, g_direct_equal);
2289 for (cur = numberlist; cur != NULL; cur = cur->next) {
2290 /* numberlist->data is expected to be GINT_TO_POINTER */
2291 g_hash_table_insert(wanted_files, cur->data, GINT_TO_POINTER(1));
2294 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2295 file_no = to_number(dir_name);
2296 if (is_dir_exist(dir_name))
2297 continue;
2298 if (file_no > 0 && g_hash_table_lookup(wanted_files, GINT_TO_POINTER(file_no)) == NULL) {
2299 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2300 if (is_dir_exist(dir_name)) {
2301 gchar *dot_file = g_strdup_printf(".%s", dir_name);
2302 if (is_file_exist(dot_file) && claws_unlink(dot_file) < 0) {
2303 FILE_OP_ERROR(dot_file, "unlink");
2305 g_free(dot_file);
2306 continue;
2308 if (claws_unlink(dir_name) < 0)
2309 FILE_OP_ERROR(dir_name, "unlink");
2313 g_dir_close(dp);
2314 g_hash_table_destroy(wanted_files);
2316 if (g_chdir(prev_dir) < 0) {
2317 FILE_OP_ERROR(prev_dir, "chdir");
2318 g_free(prev_dir);
2319 return -1;
2322 g_free(prev_dir);
2324 return 0;
2327 gint remove_all_numbered_files(const gchar *dir)
2329 return remove_numbered_files(dir, 0, UINT_MAX);
2332 gint remove_dir_recursive(const gchar *dir)
2334 GStatBuf s;
2335 GDir *dp;
2336 const gchar *dir_name;
2337 gchar *prev_dir;
2339 if (g_stat(dir, &s) < 0) {
2340 FILE_OP_ERROR(dir, "stat");
2341 if (ENOENT == errno) return 0;
2342 return -(errno);
2345 if (!S_ISDIR(s.st_mode)) {
2346 if (claws_unlink(dir) < 0) {
2347 FILE_OP_ERROR(dir, "unlink");
2348 return -(errno);
2351 return 0;
2354 prev_dir = g_get_current_dir();
2355 /* g_print("prev_dir = %s\n", prev_dir); */
2357 if (!path_cmp(prev_dir, dir)) {
2358 g_free(prev_dir);
2359 if (g_chdir("..") < 0) {
2360 FILE_OP_ERROR(dir, "chdir");
2361 return -(errno);
2363 prev_dir = g_get_current_dir();
2366 if (g_chdir(dir) < 0) {
2367 FILE_OP_ERROR(dir, "chdir");
2368 g_free(prev_dir);
2369 return -(errno);
2372 if ((dp = g_dir_open(".", 0, NULL)) == NULL) {
2373 g_warning("failed to open directory: %s", dir);
2374 g_chdir(prev_dir);
2375 g_free(prev_dir);
2376 return -(errno);
2379 /* remove all files in the directory */
2380 while ((dir_name = g_dir_read_name(dp)) != NULL) {
2381 /* g_print("removing %s\n", dir_name); */
2383 if (is_dir_exist(dir_name)) {
2384 gint ret;
2386 if ((ret = remove_dir_recursive(dir_name)) < 0) {
2387 g_warning("can't remove directory: %s", dir_name);
2388 g_dir_close(dp);
2389 return ret;
2391 } else {
2392 if (claws_unlink(dir_name) < 0)
2393 FILE_OP_ERROR(dir_name, "unlink");
2397 g_dir_close(dp);
2399 if (g_chdir(prev_dir) < 0) {
2400 FILE_OP_ERROR(prev_dir, "chdir");
2401 g_free(prev_dir);
2402 return -(errno);
2405 g_free(prev_dir);
2407 if (g_rmdir(dir) < 0) {
2408 FILE_OP_ERROR(dir, "rmdir");
2409 return -(errno);
2412 return 0;
2415 /* convert line endings into CRLF. If the last line doesn't end with
2416 * linebreak, add it.
2418 gchar *canonicalize_str(const gchar *str)
2420 const gchar *p;
2421 guint new_len = 0;
2422 gchar *out, *outp;
2424 for (p = str; *p != '\0'; ++p) {
2425 if (*p != '\r') {
2426 ++new_len;
2427 if (*p == '\n')
2428 ++new_len;
2431 if (p == str || *(p - 1) != '\n')
2432 new_len += 2;
2434 out = outp = g_malloc(new_len + 1);
2435 for (p = str; *p != '\0'; ++p) {
2436 if (*p != '\r') {
2437 if (*p == '\n')
2438 *outp++ = '\r';
2439 *outp++ = *p;
2442 if (p == str || *(p - 1) != '\n') {
2443 *outp++ = '\r';
2444 *outp++ = '\n';
2446 *outp = '\0';
2448 return out;
2451 gchar *normalize_newlines(const gchar *str)
2453 const gchar *p;
2454 gchar *out, *outp;
2456 out = outp = g_malloc(strlen(str) + 1);
2457 for (p = str; *p != '\0'; ++p) {
2458 if (*p == '\r') {
2459 if (*(p + 1) != '\n')
2460 *outp++ = '\n';
2461 } else
2462 *outp++ = *p;
2465 *outp = '\0';
2467 return out;
2470 gchar *get_outgoing_rfc2822_str(FILE *fp)
2472 gchar buf[BUFFSIZE];
2473 GString *str;
2474 gchar *ret;
2476 str = g_string_new(NULL);
2478 /* output header part */
2479 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2480 strretchomp(buf);
2481 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2482 gint next;
2484 for (;;) {
2485 next = fgetc(fp);
2486 if (next == EOF)
2487 break;
2488 else if (next != ' ' && next != '\t') {
2489 ungetc(next, fp);
2490 break;
2492 if (claws_fgets(buf, sizeof(buf), fp) == NULL)
2493 break;
2495 } else {
2496 g_string_append(str, buf);
2497 g_string_append(str, "\r\n");
2498 if (buf[0] == '\0')
2499 break;
2503 /* output body part */
2504 while (claws_fgets(buf, sizeof(buf), fp) != NULL) {
2505 strretchomp(buf);
2506 if (buf[0] == '.')
2507 g_string_append_c(str, '.');
2508 g_string_append(str, buf);
2509 g_string_append(str, "\r\n");
2512 ret = str->str;
2513 g_string_free(str, FALSE);
2515 return ret;
2519 * Create a new boundary in a way that it is very unlikely that this
2520 * will occur in the following text. It would be easy to ensure
2521 * uniqueness if everything is either quoted-printable or base64
2522 * encoded (note that conversion is allowed), but because MIME bodies
2523 * may be nested, it may happen that the same boundary has already
2524 * been used.
2526 * boundary := 0*69<bchars> bcharsnospace
2527 * bchars := bcharsnospace / " "
2528 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2529 * "+" / "_" / "," / "-" / "." /
2530 * "/" / ":" / "=" / "?"
2532 * some special characters removed because of buggy MTAs
2535 gchar *generate_mime_boundary(const gchar *prefix)
2537 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2538 "abcdefghijklmnopqrstuvwxyz"
2539 "1234567890+_./=";
2540 gchar buf_uniq[24];
2541 gint i;
2543 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2544 buf_uniq[i] = tbl[g_random_int_range(0, sizeof(tbl) - 1)];
2545 buf_uniq[i] = '\0';
2547 return g_strdup_printf("%s_/%s", prefix ? prefix : "MP",
2548 buf_uniq);
2551 char *fgets_crlf(char *buf, int size, FILE *stream)
2553 gboolean is_cr = FALSE;
2554 gboolean last_was_cr = FALSE;
2555 int c = 0;
2556 char *cs;
2558 cs = buf;
2559 while (--size > 0 && (c = getc(stream)) != EOF)
2561 *cs++ = c;
2562 is_cr = (c == '\r');
2563 if (c == '\n') {
2564 break;
2566 if (last_was_cr) {
2567 *(--cs) = '\n';
2568 cs++;
2569 ungetc(c, stream);
2570 break;
2572 last_was_cr = is_cr;
2574 if (c == EOF && cs == buf)
2575 return NULL;
2577 *cs = '\0';
2579 return buf;
2582 static gint execute_async(gchar *const argv[], const gchar *working_directory)
2584 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2586 if (g_spawn_async(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2587 NULL, NULL, NULL, FALSE) == FALSE) {
2588 g_warning("couldn't execute command: %s", argv[0]);
2589 return -1;
2592 return 0;
2595 static gint execute_sync(gchar *const argv[], const gchar *working_directory)
2597 gint status;
2599 cm_return_val_if_fail(argv != NULL && argv[0] != NULL, -1);
2601 #ifdef G_OS_UNIX
2602 if (g_spawn_sync(working_directory, (gchar **)argv, NULL, G_SPAWN_SEARCH_PATH,
2603 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2604 g_warning("couldn't execute command: %s", argv[0]);
2605 return -1;
2608 if (WIFEXITED(status))
2609 return WEXITSTATUS(status);
2610 else
2611 return -1;
2612 #else
2613 if (g_spawn_sync(working_directory, (gchar **)argv, NULL,
2614 G_SPAWN_SEARCH_PATH|
2615 G_SPAWN_CHILD_INHERITS_STDIN|
2616 G_SPAWN_LEAVE_DESCRIPTORS_OPEN,
2617 NULL, NULL, NULL, NULL, &status, NULL) == FALSE) {
2618 g_warning("couldn't execute command: %s", argv[0]);
2619 return -1;
2622 return status;
2623 #endif
2626 gint execute_command_line(const gchar *cmdline, gboolean async,
2627 const gchar *working_directory)
2629 gchar **argv;
2630 gint ret;
2632 cm_return_val_if_fail(cmdline != NULL, -1);
2634 debug_print("execute_command_line(): executing: %s\n", cmdline);
2636 argv = strsplit_with_quote(cmdline, " ", 0);
2638 if (async)
2639 ret = execute_async(argv, working_directory);
2640 else
2641 ret = execute_sync(argv, working_directory);
2643 g_strfreev(argv);
2645 return ret;
2648 gchar *get_command_output(const gchar *cmdline)
2650 gchar *child_stdout;
2651 gint status;
2653 cm_return_val_if_fail(cmdline != NULL, NULL);
2655 debug_print("get_command_output(): executing: %s\n", cmdline);
2657 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
2658 NULL) == FALSE) {
2659 g_warning("couldn't execute command: %s", cmdline);
2660 return NULL;
2663 return child_stdout;
2666 FILE *get_command_output_stream(const char* cmdline)
2668 GPid pid;
2669 GError *err = NULL;
2670 gchar **argv = NULL;
2671 int fd;
2673 cm_return_val_if_fail(cmdline != NULL, NULL);
2675 debug_print("get_command_output_stream(): executing: %s\n", cmdline);
2677 /* turn the command-line string into an array */
2678 if (!g_shell_parse_argv(cmdline, NULL, &argv, &err)) {
2679 g_warning("could not parse command line from '%s': %s", cmdline, err->message);
2680 g_error_free(err);
2681 return NULL;
2684 if (!g_spawn_async_with_pipes(NULL, argv, NULL, G_SPAWN_SEARCH_PATH,
2685 NULL, NULL, &pid, NULL, &fd, NULL, &err)
2686 && err)
2688 g_warning("could not spawn '%s': %s", cmdline, err->message);
2689 g_error_free(err);
2690 g_strfreev(argv);
2691 return NULL;
2694 g_strfreev(argv);
2695 return fdopen(fd, "r");
2698 #ifndef G_OS_WIN32
2699 static gint is_unchanged_uri_char(char c)
2701 switch (c) {
2702 case '(':
2703 case ')':
2704 return 0;
2705 default:
2706 return 1;
2710 static void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2712 int i;
2713 int k;
2715 k = 0;
2716 for(i = 0; i < strlen(uri) ; i++) {
2717 if (is_unchanged_uri_char(uri[i])) {
2718 if (k + 2 >= bufsize)
2719 break;
2720 encoded_uri[k++] = uri[i];
2722 else {
2723 char * hexa = "0123456789ABCDEF";
2725 if (k + 4 >= bufsize)
2726 break;
2727 encoded_uri[k++] = '%';
2728 encoded_uri[k++] = hexa[uri[i] / 16];
2729 encoded_uri[k++] = hexa[uri[i] % 16];
2732 encoded_uri[k] = 0;
2734 #endif
2736 gint open_uri(const gchar *uri, const gchar *cmdline)
2739 #ifndef G_OS_WIN32
2740 gchar buf[BUFFSIZE];
2741 gchar *p;
2742 gchar encoded_uri[BUFFSIZE];
2743 cm_return_val_if_fail(uri != NULL, -1);
2745 /* an option to choose whether to use encode_uri or not ? */
2746 encode_uri(encoded_uri, BUFFSIZE, uri);
2748 if (cmdline &&
2749 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2750 !strchr(p + 2, '%'))
2751 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
2752 else {
2753 if (cmdline)
2754 g_warning("Open URI command-line is invalid "
2755 "(there must be only one '%%s'): %s",
2756 cmdline);
2757 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
2760 execute_command_line(buf, TRUE, NULL);
2761 #else
2762 ShellExecute(NULL, "open", uri, NULL, NULL, SW_SHOW);
2763 #endif
2764 return 0;
2767 gint open_txt_editor(const gchar *filepath, const gchar *cmdline)
2769 gchar buf[BUFFSIZE];
2770 gchar *p;
2772 cm_return_val_if_fail(filepath != NULL, -1);
2774 if (cmdline &&
2775 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2776 !strchr(p + 2, '%'))
2777 g_snprintf(buf, sizeof(buf), cmdline, filepath);
2778 else {
2779 if (cmdline)
2780 g_warning("Open Text Editor command-line is invalid "
2781 "(there must be only one '%%s'): %s",
2782 cmdline);
2783 g_snprintf(buf, sizeof(buf), DEFAULT_EDITOR_CMD, filepath);
2786 execute_command_line(buf, TRUE, NULL);
2788 return 0;
2791 time_t remote_tzoffset_sec(const gchar *zone)
2793 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
2794 gchar zone3[4];
2795 gchar *p;
2796 gchar c;
2797 gint iustz;
2798 gint offset;
2799 time_t remoteoffset;
2801 strncpy(zone3, zone, 3);
2802 zone3[3] = '\0';
2803 remoteoffset = 0;
2805 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
2806 (c == '+' || c == '-')) {
2807 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
2808 if (c == '-')
2809 remoteoffset = -remoteoffset;
2810 } else if (!strncmp(zone, "UT" , 2) ||
2811 !strncmp(zone, "GMT", 3)) {
2812 remoteoffset = 0;
2813 } else if (strlen(zone3) == 3) {
2814 for (p = ustzstr; *p != '\0'; p += 3) {
2815 if (!g_ascii_strncasecmp(p, zone3, 3)) {
2816 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
2817 remoteoffset = iustz * 3600;
2818 break;
2821 if (*p == '\0')
2822 return -1;
2823 } else if (strlen(zone3) == 1) {
2824 switch (zone[0]) {
2825 case 'Z': remoteoffset = 0; break;
2826 case 'A': remoteoffset = -1; break;
2827 case 'B': remoteoffset = -2; break;
2828 case 'C': remoteoffset = -3; break;
2829 case 'D': remoteoffset = -4; break;
2830 case 'E': remoteoffset = -5; break;
2831 case 'F': remoteoffset = -6; break;
2832 case 'G': remoteoffset = -7; break;
2833 case 'H': remoteoffset = -8; break;
2834 case 'I': remoteoffset = -9; break;
2835 case 'K': remoteoffset = -10; break; /* J is not used */
2836 case 'L': remoteoffset = -11; break;
2837 case 'M': remoteoffset = -12; break;
2838 case 'N': remoteoffset = 1; break;
2839 case 'O': remoteoffset = 2; break;
2840 case 'P': remoteoffset = 3; break;
2841 case 'Q': remoteoffset = 4; break;
2842 case 'R': remoteoffset = 5; break;
2843 case 'S': remoteoffset = 6; break;
2844 case 'T': remoteoffset = 7; break;
2845 case 'U': remoteoffset = 8; break;
2846 case 'V': remoteoffset = 9; break;
2847 case 'W': remoteoffset = 10; break;
2848 case 'X': remoteoffset = 11; break;
2849 case 'Y': remoteoffset = 12; break;
2850 default: remoteoffset = 0; break;
2852 remoteoffset = remoteoffset * 3600;
2853 } else
2854 return -1;
2856 return remoteoffset;
2859 time_t tzoffset_sec(time_t *now)
2861 struct tm gmt, *lt;
2862 gint off;
2863 struct tm buf1, buf2;
2864 #ifdef G_OS_WIN32
2865 if (now && *now < 0)
2866 return 0;
2867 #endif
2868 gmt = *gmtime_r(now, &buf1);
2869 lt = localtime_r(now, &buf2);
2871 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2873 if (lt->tm_year < gmt.tm_year)
2874 off -= 24 * 60;
2875 else if (lt->tm_year > gmt.tm_year)
2876 off += 24 * 60;
2877 else if (lt->tm_yday < gmt.tm_yday)
2878 off -= 24 * 60;
2879 else if (lt->tm_yday > gmt.tm_yday)
2880 off += 24 * 60;
2882 if (off >= 24 * 60) /* should be impossible */
2883 off = 23 * 60 + 59; /* if not, insert silly value */
2884 if (off <= -24 * 60)
2885 off = -(23 * 60 + 59);
2887 return off * 60;
2890 /* calculate timezone offset */
2891 gchar *tzoffset(time_t *now)
2893 static gchar offset_string[6];
2894 struct tm gmt, *lt;
2895 gint off;
2896 gchar sign = '+';
2897 struct tm buf1, buf2;
2898 #ifdef G_OS_WIN32
2899 if (now && *now < 0)
2900 return 0;
2901 #endif
2902 gmt = *gmtime_r(now, &buf1);
2903 lt = localtime_r(now, &buf2);
2905 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2907 if (lt->tm_year < gmt.tm_year)
2908 off -= 24 * 60;
2909 else if (lt->tm_year > gmt.tm_year)
2910 off += 24 * 60;
2911 else if (lt->tm_yday < gmt.tm_yday)
2912 off -= 24 * 60;
2913 else if (lt->tm_yday > gmt.tm_yday)
2914 off += 24 * 60;
2916 if (off < 0) {
2917 sign = '-';
2918 off = -off;
2921 if (off >= 24 * 60) /* should be impossible */
2922 off = 23 * 60 + 59; /* if not, insert silly value */
2924 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
2926 return offset_string;
2929 static void _get_rfc822_date(gchar *buf, gint len, gboolean hidetz)
2931 struct tm *lt;
2932 time_t t;
2933 gchar day[4], mon[4];
2934 gint dd, hh, mm, ss, yyyy;
2935 struct tm buf1;
2936 gchar buf2[RFC822_DATE_BUFFSIZE];
2938 t = time(NULL);
2939 if (hidetz)
2940 lt = gmtime_r(&t, &buf1);
2941 else
2942 lt = localtime_r(&t, &buf1);
2944 if (sscanf(asctime_r(lt, buf2), "%3s %3s %d %d:%d:%d %d\n",
2945 day, mon, &dd, &hh, &mm, &ss, &yyyy) != 7)
2946 g_warning("failed reading date/time");
2948 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
2949 day, dd, mon, yyyy, hh, mm, ss, (hidetz? "-0000": tzoffset(&t)));
2952 void get_rfc822_date(gchar *buf, gint len)
2954 _get_rfc822_date(buf, len, FALSE);
2957 void get_rfc822_date_hide_tz(gchar *buf, gint len)
2959 _get_rfc822_date(buf, len, TRUE);
2962 void debug_set_mode(gboolean mode)
2964 debug_mode = mode;
2967 gboolean debug_get_mode(void)
2969 return debug_mode;
2972 #ifdef HAVE_VA_OPT
2973 void debug_print_real(const char *file, int line, const gchar *format, ...)
2975 va_list args;
2976 gchar buf[BUFFSIZE];
2977 gint prefix_len;
2979 if (!debug_mode) return;
2981 prefix_len = g_snprintf(buf, sizeof(buf), "%s:%d:", debug_srcname(file), line);
2983 va_start(args, format);
2984 g_vsnprintf(buf + prefix_len, sizeof(buf) - prefix_len, format, args);
2985 va_end(args);
2987 g_print("%s", buf);
2989 #else
2990 void debug_print_real(const gchar *format, ...)
2992 va_list args;
2993 gchar buf[BUFFSIZE];
2995 if (!debug_mode) return;
2997 va_start(args, format);
2998 g_vsnprintf(buf, sizeof(buf), format, args);
2999 va_end(args);
3001 g_print("%s", buf);
3003 #endif
3006 const char * debug_srcname(const char *file)
3008 const char *s = strrchr (file, '/');
3009 return s? s+1:file;
3013 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3015 if (subject == NULL)
3016 subject = "";
3017 else
3018 subject += subject_get_prefix_length(subject);
3020 return g_hash_table_lookup(subject_table, subject);
3023 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3024 void * data)
3026 if (subject == NULL || *subject == 0)
3027 return;
3028 subject += subject_get_prefix_length(subject);
3029 g_hash_table_insert(subject_table, subject, data);
3032 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3034 if (subject == NULL)
3035 return;
3037 subject += subject_get_prefix_length(subject);
3038 g_hash_table_remove(subject_table, subject);
3041 static regex_t u_regex;
3042 static gboolean u_init_;
3044 void utils_free_regex(void)
3046 if (u_init_) {
3047 regfree(&u_regex);
3048 u_init_ = FALSE;
3053 *\brief Check if a string is prefixed with known (combinations)
3054 * of prefixes. The function assumes that each prefix
3055 * is terminated by zero or exactly _one_ space.
3057 *\param str String to check for a prefixes
3059 *\return int Number of chars in the prefix that should be skipped
3060 * for a "clean" subject line. If no prefix was found, 0
3061 * is returned.
3063 int subject_get_prefix_length(const gchar *subject)
3065 /*!< Array with allowable reply prefixes regexps. */
3066 static const gchar * const prefixes[] = {
3067 "Re\\:", /* "Re:" */
3068 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3069 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3070 "Aw\\:", /* "Aw:" (German) */
3071 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3072 "Res\\:", /* "Res:" (Spanish/Brazilian Outlook) */
3073 "Fw\\:", /* "Fw:" Forward */
3074 "Fwd\\:", /* "Fwd:" Forward */
3075 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3076 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3077 "Rif\\:", /* "Rif:" (Italian Outlook) */
3078 "Sv\\:", /* "Sv" (Norwegian) */
3079 "Vs\\:", /* "Vs" (Norwegian) */
3080 "Ad\\:", /* "Ad" (Norwegian) */
3081 "\347\255\224\345\244\215\\:", /* "Re" (Chinese, UTF-8) */
3082 "R\303\251f\\. \\:", /* "R�f. :" (French Lotus Notes) */
3083 "Re \\:", /* "Re :" (French Yahoo Mail) */
3084 /* add more */
3086 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3087 int n;
3088 regmatch_t pos;
3090 if (!subject) return 0;
3091 if (!*subject) return 0;
3093 if (!u_init_) {
3094 GString *s = g_string_new("");
3096 for (n = 0; n < PREFIXES; n++)
3097 /* Terminate each prefix regexpression by a
3098 * "\ ?" (zero or ONE space), and OR them */
3099 g_string_append_printf(s, "(%s\\ ?)%s",
3100 prefixes[n],
3101 n < PREFIXES - 1 ?
3102 "|" : "");
3104 g_string_prepend(s, "(");
3105 g_string_append(s, ")+"); /* match at least once */
3106 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3109 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3110 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3111 if (regcomp(&u_regex, s->str, REG_EXTENDED | REG_ICASE)) {
3112 debug_print("Error compiling regexp %s\n", s->str);
3113 g_string_free(s, TRUE);
3114 return 0;
3115 } else {
3116 u_init_ = TRUE;
3117 g_string_free(s, TRUE);
3121 if (!regexec(&u_regex, subject, 1, &pos, 0) && pos.rm_so != -1)
3122 return pos.rm_eo;
3123 else
3124 return 0;
3127 static guint g_stricase_hash(gconstpointer gptr)
3129 guint hash_result = 0;
3130 const char *str;
3132 for (str = gptr; str && *str; str++) {
3133 hash_result += toupper(*str);
3136 return hash_result;
3139 static gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3141 const char *str1 = gptr1;
3142 const char *str2 = gptr2;
3144 return !strcasecmp(str1, str2);
3147 gint g_int_compare(gconstpointer a, gconstpointer b)
3149 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3153 quote_cmd_argument()
3155 return a quoted string safely usable in argument of a command.
3157 code is extracted and adapted from etPan! project -- DINH V. Ho�.
3160 gint quote_cmd_argument(gchar * result, guint size,
3161 const gchar * path)
3163 const gchar * p;
3164 gchar * result_p;
3165 guint remaining;
3167 result_p = result;
3168 remaining = size;
3170 for(p = path ; * p != '\0' ; p ++) {
3172 if (isalnum((guchar)*p) || (* p == '/')) {
3173 if (remaining > 0) {
3174 * result_p = * p;
3175 result_p ++;
3176 remaining --;
3178 else {
3179 result[size - 1] = '\0';
3180 return -1;
3183 else {
3184 if (remaining >= 2) {
3185 * result_p = '\\';
3186 result_p ++;
3187 * result_p = * p;
3188 result_p ++;
3189 remaining -= 2;
3191 else {
3192 result[size - 1] = '\0';
3193 return -1;
3197 if (remaining > 0) {
3198 * result_p = '\0';
3200 else {
3201 result[size - 1] = '\0';
3202 return -1;
3205 return 0;
3208 typedef struct
3210 GNode *parent;
3211 GNodeMapFunc func;
3212 gpointer data;
3213 } GNodeMapData;
3215 static void g_node_map_recursive(GNode *node, gpointer data)
3217 GNodeMapData *mapdata = (GNodeMapData *) data;
3218 GNode *newnode;
3219 GNodeMapData newmapdata;
3220 gpointer newdata;
3222 newdata = mapdata->func(node->data, mapdata->data);
3223 if (newdata != NULL) {
3224 newnode = g_node_new(newdata);
3225 g_node_append(mapdata->parent, newnode);
3227 newmapdata.parent = newnode;
3228 newmapdata.func = mapdata->func;
3229 newmapdata.data = mapdata->data;
3231 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3235 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3237 GNode *root;
3238 GNodeMapData mapdata;
3240 cm_return_val_if_fail(node != NULL, NULL);
3241 cm_return_val_if_fail(func != NULL, NULL);
3243 root = g_node_new(func(node->data, data));
3245 mapdata.parent = root;
3246 mapdata.func = func;
3247 mapdata.data = data;
3249 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3251 return root;
3254 #define HEX_TO_INT(val, hex) \
3256 gchar c = hex; \
3258 if ('0' <= c && c <= '9') { \
3259 val = c - '0'; \
3260 } else if ('a' <= c && c <= 'f') { \
3261 val = c - 'a' + 10; \
3262 } else if ('A' <= c && c <= 'F') { \
3263 val = c - 'A' + 10; \
3264 } else { \
3265 val = -1; \
3269 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3271 gint hi, lo;
3273 HEX_TO_INT(hi, c1);
3274 HEX_TO_INT(lo, c2);
3276 if (hi == -1 || lo == -1)
3277 return FALSE;
3279 *out = (hi << 4) + lo;
3280 return TRUE;
3283 #define INT_TO_HEX(hex, val) \
3285 if ((val) < 10) \
3286 hex = '0' + (val); \
3287 else \
3288 hex = 'A' + (val) - 10; \
3291 void get_hex_str(gchar *out, guchar ch)
3293 gchar hex;
3295 INT_TO_HEX(hex, ch >> 4);
3296 *out++ = hex;
3297 INT_TO_HEX(hex, ch & 0x0f);
3298 *out = hex;
3301 #undef REF_DEBUG
3302 #ifndef REF_DEBUG
3303 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3304 #else
3305 #define G_PRINT_REF g_print
3306 #endif
3309 *\brief Register ref counted pointer. It is based on GBoxed, so should
3310 * work with anything that uses the GType system. The semantics
3311 * are similar to a C++ auto pointer, with the exception that
3312 * C doesn't have automatic closure (calling destructors) when
3313 * exiting a block scope.
3314 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3315 * function directly.
3317 *\return GType A GType type.
3319 GType g_auto_pointer_register(void)
3321 static GType auto_pointer_type;
3322 if (!auto_pointer_type)
3323 auto_pointer_type =
3324 g_boxed_type_register_static
3325 ("G_TYPE_AUTO_POINTER",
3326 (GBoxedCopyFunc) g_auto_pointer_copy,
3327 (GBoxedFreeFunc) g_auto_pointer_free);
3328 return auto_pointer_type;
3332 *\brief Structure with g_new() allocated pointer guarded by the
3333 * auto pointer
3335 typedef struct AutoPointerRef {
3336 void (*free) (gpointer);
3337 gpointer pointer;
3338 glong cnt;
3339 } AutoPointerRef;
3342 *\brief The auto pointer opaque structure that references the
3343 * pointer guard block.
3345 typedef struct AutoPointer {
3346 AutoPointerRef *ref;
3347 gpointer ptr; /*!< access to protected pointer */
3348 } AutoPointer;
3351 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3353 *\code
3355 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3356 * ... when assigning, copying and freeing storage elements
3358 * gtk_list_store_new(N_S_COLUMNS,
3359 * G_TYPE_AUTO_POINTER,
3360 * -1);
3363 * Template *precious_data = g_new0(Template, 1);
3364 * g_pointer protect = g_auto_pointer_new(precious_data);
3366 * gtk_list_store_set(container, &iter,
3367 * S_DATA, protect,
3368 * -1);
3370 * ... the gtk_list_store has copied the pointer and
3371 * ... incremented its reference count, we should free
3372 * ... the auto pointer (in C++ a destructor would do
3373 * ... this for us when leaving block scope)
3375 * g_auto_pointer_free(protect);
3377 * ... gtk_list_store_set() now manages the data. When
3378 * ... *explicitly* requesting a pointer from the list
3379 * ... store, don't forget you get a copy that should be
3380 * ... freed with g_auto_pointer_free() eventually.
3382 *\endcode
3384 *\param pointer Pointer to be guarded.
3386 *\return GAuto * Pointer that should be used in containers with
3387 * GType support.
3389 GAuto *g_auto_pointer_new(gpointer p)
3391 AutoPointerRef *ref;
3392 AutoPointer *ptr;
3394 if (p == NULL)
3395 return NULL;
3397 ref = g_new0(AutoPointerRef, 1);
3398 ptr = g_new0(AutoPointer, 1);
3400 ref->pointer = p;
3401 ref->free = g_free;
3402 ref->cnt = 1;
3404 ptr->ref = ref;
3405 ptr->ptr = p;
3407 #ifdef REF_DEBUG
3408 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3409 #endif
3410 return ptr;
3414 *\brief Allocate an autopointer using the passed \a free function to
3415 * free the guarded pointer
3417 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3419 AutoPointer *aptr;
3421 if (p == NULL)
3422 return NULL;
3424 aptr = g_auto_pointer_new(p);
3425 aptr->ref->free = free_;
3426 return aptr;
3429 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3431 if (auto_ptr == NULL)
3432 return NULL;
3433 return ((AutoPointer *) auto_ptr)->ptr;
3437 *\brief Copies an auto pointer by. It's mostly not necessary
3438 * to call this function directly, unless you copy/assign
3439 * the guarded pointer.
3441 *\param auto_ptr Auto pointer returned by previous call to
3442 * g_auto_pointer_new_XXX()
3444 *\return gpointer An auto pointer
3446 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3448 AutoPointer *ptr;
3449 AutoPointerRef *ref;
3450 AutoPointer *newp;
3452 if (auto_ptr == NULL)
3453 return NULL;
3455 ptr = auto_ptr;
3456 ref = ptr->ref;
3457 newp = g_new0(AutoPointer, 1);
3459 newp->ref = ref;
3460 newp->ptr = ref->pointer;
3461 ++(ref->cnt);
3463 #ifdef REF_DEBUG
3464 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3465 #endif
3466 return newp;
3470 *\brief Free an auto pointer
3472 void g_auto_pointer_free(GAuto *auto_ptr)
3474 AutoPointer *ptr;
3475 AutoPointerRef *ref;
3477 if (auto_ptr == NULL)
3478 return;
3480 ptr = auto_ptr;
3481 ref = ptr->ref;
3483 if (--(ref->cnt) == 0) {
3484 #ifdef REF_DEBUG
3485 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3486 #endif
3487 ref->free(ref->pointer);
3488 g_free(ref);
3490 #ifdef REF_DEBUG
3491 else
3492 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3493 #endif
3494 g_free(ptr);
3497 /* get_uri_part() - retrieves a URI starting from scanpos.
3498 Returns TRUE if successful */
3499 gboolean get_uri_part(const gchar *start, const gchar *scanpos,
3500 const gchar **bp, const gchar **ep, gboolean hdr)
3502 const gchar *ep_;
3503 gint parenthese_cnt = 0;
3505 cm_return_val_if_fail(start != NULL, FALSE);
3506 cm_return_val_if_fail(scanpos != NULL, FALSE);
3507 cm_return_val_if_fail(bp != NULL, FALSE);
3508 cm_return_val_if_fail(ep != NULL, FALSE);
3510 *bp = scanpos;
3512 /* find end point of URI */
3513 for (ep_ = scanpos; *ep_ != '\0'; ep_ = g_utf8_next_char(ep_)) {
3514 gunichar u = g_utf8_get_char_validated(ep_, -1);
3515 if (!g_unichar_isgraph(u) ||
3516 u == (gunichar)-1 ||
3517 strchr("[]{}<>\"", *ep_)) {
3518 break;
3519 } else if (strchr("(", *ep_)) {
3520 parenthese_cnt++;
3521 } else if (strchr(")", *ep_)) {
3522 if (parenthese_cnt > 0)
3523 parenthese_cnt--;
3524 else
3525 break;
3529 /* no punctuation at end of string */
3531 /* FIXME: this stripping of trailing punctuations may bite with other URIs.
3532 * should pass some URI type to this function and decide on that whether
3533 * to perform punctuation stripping */
3535 #define IS_REAL_PUNCT(ch) (g_ascii_ispunct(ch) && !strchr("/?=-_~)", ch))
3537 for (; ep_ - 1 > scanpos + 1 &&
3538 IS_REAL_PUNCT(*(ep_ - 1));
3539 ep_--)
3542 #undef IS_REAL_PUNCT
3544 *ep = ep_;
3546 return TRUE;
3549 gchar *make_uri_string(const gchar *bp, const gchar *ep)
3551 while (bp && *bp && g_ascii_isspace(*bp))
3552 bp++;
3553 return g_strndup(bp, ep - bp);
3556 /* valid mail address characters */
3557 #define IS_RFC822_CHAR(ch) \
3558 (IS_ASCII(ch) && \
3559 (ch) > 32 && \
3560 (ch) != 127 && \
3561 !g_ascii_isspace(ch) && \
3562 !strchr("(),;<>\"", (ch)))
3564 /* alphabet and number within 7bit ASCII */
3565 #define IS_ASCII_ALNUM(ch) (IS_ASCII(ch) && g_ascii_isalnum(ch))
3566 #define IS_QUOTE(ch) ((ch) == '\'' || (ch) == '"')
3568 static GHashTable *create_domain_tab(void)
3570 gint n;
3571 GHashTable *htab = g_hash_table_new(g_stricase_hash, g_stricase_equal);
3573 cm_return_val_if_fail(htab, NULL);
3574 for (n = 0; n < sizeof toplvl_domains / sizeof toplvl_domains[0]; n++)
3575 g_hash_table_insert(htab, (gpointer) toplvl_domains[n], (gpointer) toplvl_domains[n]);
3576 return htab;
3579 static gboolean is_toplvl_domain(GHashTable *tab, const gchar *first, const gchar *last)
3581 gchar buf[BUFFSIZE + 1];
3582 const gchar *m = buf + BUFFSIZE + 1;
3583 register gchar *p;
3585 if (last - first > BUFFSIZE || first > last)
3586 return FALSE;
3588 for (p = buf; p < m && first < last; *p++ = *first++)
3590 *p = 0;
3592 return g_hash_table_lookup(tab, buf) != NULL;
3595 /* get_email_part() - retrieves an email address. Returns TRUE if successful */
3596 gboolean get_email_part(const gchar *start, const gchar *scanpos,
3597 const gchar **bp, const gchar **ep, gboolean hdr)
3599 /* more complex than the uri part because we need to scan back and forward starting from
3600 * the scan position. */
3601 gboolean result = FALSE;
3602 const gchar *bp_ = NULL;
3603 const gchar *ep_ = NULL;
3604 static GHashTable *dom_tab;
3605 const gchar *last_dot = NULL;
3606 const gchar *prelast_dot = NULL;
3607 const gchar *last_tld_char = NULL;
3609 /* the informative part of the email address (describing the name
3610 * of the email address owner) may contain quoted parts. the
3611 * closure stack stores the last encountered quotes. */
3612 gchar closure_stack[128];
3613 gchar *ptr = closure_stack;
3615 cm_return_val_if_fail(start != NULL, FALSE);
3616 cm_return_val_if_fail(scanpos != NULL, FALSE);
3617 cm_return_val_if_fail(bp != NULL, FALSE);
3618 cm_return_val_if_fail(ep != NULL, FALSE);
3620 if (hdr) {
3621 const gchar *start_quote = NULL;
3622 const gchar *end_quote = NULL;
3623 search_again:
3624 /* go to the real start */
3625 if (start[0] == ',')
3626 start++;
3627 if (start[0] == ';')
3628 start++;
3629 while (start[0] == '\n' || start[0] == '\r')
3630 start++;
3631 while (start[0] == ' ' || start[0] == '\t')
3632 start++;
3634 *bp = start;
3636 /* check if there are quotes (to skip , in them) */
3637 if (*start == '"') {
3638 start_quote = start;
3639 start++;
3640 end_quote = strstr(start, "\"");
3641 } else {
3642 start_quote = NULL;
3643 end_quote = NULL;
3646 /* skip anything between quotes */
3647 if (start_quote && end_quote) {
3648 start = end_quote;
3652 /* find end (either , or ; or end of line) */
3653 if (strstr(start, ",") && strstr(start, ";"))
3654 *ep = strstr(start,",") < strstr(start, ";")
3655 ? strstr(start, ",") : strstr(start, ";");
3656 else if (strstr(start, ","))
3657 *ep = strstr(start, ",");
3658 else if (strstr(start, ";"))
3659 *ep = strstr(start, ";");
3660 else
3661 *ep = start+strlen(start);
3663 /* go back to real start */
3664 if (start_quote && end_quote) {
3665 start = start_quote;
3668 /* check there's still an @ in that, or search
3669 * further if possible */
3670 if (strstr(start, "@") && strstr(start, "@") < *ep)
3671 return TRUE;
3672 else if (*ep < start+strlen(start)) {
3673 start = *ep;
3674 goto search_again;
3675 } else if (start_quote && strstr(start, "\"") && strstr(start, "\"") < *ep) {
3676 *bp = start_quote;
3677 return TRUE;
3678 } else
3679 return FALSE;
3682 if (!dom_tab)
3683 dom_tab = create_domain_tab();
3684 cm_return_val_if_fail(dom_tab, FALSE);
3686 /* scan start of address */
3687 for (bp_ = scanpos - 1;
3688 bp_ >= start && IS_RFC822_CHAR(*(const guchar *)bp_); bp_--)
3691 /* TODO: should start with an alnum? */
3692 bp_++;
3693 for (; bp_ < scanpos && !IS_ASCII_ALNUM(*(const guchar *)bp_); bp_++)
3696 if (bp_ != scanpos) {
3697 /* scan end of address */
3698 for (ep_ = scanpos + 1;
3699 *ep_ && IS_RFC822_CHAR(*(const guchar *)ep_); ep_++)
3700 if (*ep_ == '.') {
3701 prelast_dot = last_dot;
3702 last_dot = ep_;
3703 if (*(last_dot + 1) == '.') {
3704 if (prelast_dot == NULL)
3705 return FALSE;
3706 last_dot = prelast_dot;
3707 break;
3711 /* TODO: really should terminate with an alnum? */
3712 for (; ep_ > scanpos && !IS_ASCII_ALNUM(*(const guchar *)ep_);
3713 --ep_)
3715 ep_++;
3717 if (last_dot == NULL)
3718 return FALSE;
3719 if (last_dot >= ep_)
3720 last_dot = prelast_dot;
3721 if (last_dot == NULL || (scanpos + 1 >= last_dot))
3722 return FALSE;
3723 last_dot++;
3725 for (last_tld_char = last_dot; last_tld_char < ep_; last_tld_char++)
3726 if (*last_tld_char == '?')
3727 break;
3729 if (is_toplvl_domain(dom_tab, last_dot, last_tld_char))
3730 result = TRUE;
3732 *ep = ep_;
3733 *bp = bp_;
3736 if (!result) return FALSE;
3738 if (*ep_ && bp_ != start && *(bp_ - 1) == '"' && *(ep_) == '"'
3739 && *(ep_ + 1) == ' ' && *(ep_ + 2) == '<'
3740 && IS_RFC822_CHAR(*(ep_ + 3))) {
3741 /* this informative part with an @ in it is
3742 * followed by the email address */
3743 ep_ += 3;
3745 /* go to matching '>' (or next non-rfc822 char, like \n) */
3746 for (; *ep_ != '>' && *ep_ != '\0' && IS_RFC822_CHAR(*ep_); ep_++)
3749 /* include the bracket */
3750 if (*ep_ == '>') ep_++;
3752 /* include the leading quote */
3753 bp_--;
3755 *ep = ep_;
3756 *bp = bp_;
3757 return TRUE;
3760 /* skip if it's between quotes "'alfons@proteus.demon.nl'" <alfons@proteus.demon.nl> */
3761 if (bp_ - 1 > start && IS_QUOTE(*(bp_ - 1)) && IS_QUOTE(*ep_))
3762 return FALSE;
3764 /* see if this is <bracketed>; in this case we also scan for the informative part. */
3765 if (bp_ - 1 <= start || *(bp_ - 1) != '<' || *ep_ != '>')
3766 return TRUE;
3768 #define FULL_STACK() ((size_t) (ptr - closure_stack) >= sizeof closure_stack)
3769 #define IN_STACK() (ptr > closure_stack)
3770 /* has underrun check */
3771 #define POP_STACK() if(IN_STACK()) --ptr
3772 /* has overrun check */
3773 #define PUSH_STACK(c) if(!FULL_STACK()) *ptr++ = (c); else return TRUE
3774 /* has underrun check */
3775 #define PEEK_STACK() (IN_STACK() ? *(ptr - 1) : 0)
3777 ep_++;
3779 /* scan for the informative part. */
3780 for (bp_ -= 2; bp_ >= start; bp_--) {
3781 /* if closure on the stack keep scanning */
3782 if (PEEK_STACK() == *bp_) {
3783 POP_STACK();
3784 continue;
3786 if (!IN_STACK() && (*bp_ == '\'' || *bp_ == '"')) {
3787 PUSH_STACK(*bp_);
3788 continue;
3791 /* if nothing in the closure stack, do the special conditions
3792 * the following if..else expression simply checks whether
3793 * a token is acceptable. if not acceptable, the clause
3794 * should terminate the loop with a 'break' */
3795 if (!PEEK_STACK()) {
3796 if (*bp_ == '-'
3797 && (((bp_ - 1) >= start) && isalnum(*(bp_ - 1)))
3798 && (((bp_ + 1) < ep_) && isalnum(*(bp_ + 1)))) {
3799 /* hyphens are allowed, but only in
3800 between alnums */
3801 } else if (strchr(" \"'", *bp_)) {
3802 /* but anything not being a punctiation
3803 is ok */
3804 } else {
3805 break; /* anything else is rejected */
3810 bp_++;
3812 /* scan forward (should start with an alnum) */
3813 for (; *bp_ != '<' && isspace(*bp_) && *bp_ != '"'; bp_++)
3815 #undef PEEK_STACK
3816 #undef PUSH_STACK
3817 #undef POP_STACK
3818 #undef IN_STACK
3819 #undef FULL_STACK
3822 *bp = bp_;
3823 *ep = ep_;
3825 return result;
3828 #undef IS_QUOTE
3829 #undef IS_ASCII_ALNUM
3830 #undef IS_RFC822_CHAR
3832 gchar *make_email_string(const gchar *bp, const gchar *ep)
3834 /* returns a mailto: URI; mailto: is also used to detect the
3835 * uri type later on in the button_pressed signal handler */
3836 gchar *tmp;
3837 gchar *result;
3838 gchar *colon, *at;
3840 tmp = g_strndup(bp, ep - bp);
3842 /* If there is a colon in the username part of the address,
3843 * we're dealing with an URI for some other protocol - do
3844 * not prefix with mailto: in such case. */
3845 colon = strchr(tmp, ':');
3846 at = strchr(tmp, '@');
3847 if (colon != NULL && at != NULL && colon < at) {
3848 result = tmp;
3849 } else {
3850 result = g_strconcat("mailto:", tmp, NULL);
3851 g_free(tmp);
3854 return result;
3857 gchar *make_http_string(const gchar *bp, const gchar *ep)
3859 /* returns an http: URI; */
3860 gchar *tmp;
3861 gchar *result;
3863 while (bp && *bp && g_ascii_isspace(*bp))
3864 bp++;
3865 tmp = g_strndup(bp, ep - bp);
3866 result = g_strconcat("http://", tmp, NULL);
3867 g_free(tmp);
3869 return result;
3872 static gchar *mailcap_get_command_in_file(const gchar *path, const gchar *type, const gchar *file_to_open)
3874 FILE *fp = claws_fopen(path, "rb");
3875 gchar buf[BUFFSIZE];
3876 gchar *result = NULL;
3877 if (!fp)
3878 return NULL;
3879 while (claws_fgets(buf, sizeof (buf), fp) != NULL) {
3880 gchar **parts = g_strsplit(buf, ";", 3);
3881 gchar *trimmed = parts[0];
3882 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3883 trimmed++;
3884 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3885 trimmed[strlen(trimmed)-1] = '\0';
3887 if (!strcmp(trimmed, type)) {
3888 gboolean needsterminal = FALSE;
3889 if (parts[2] && strstr(parts[2], "needsterminal")) {
3890 needsterminal = TRUE;
3892 if (parts[2] && strstr(parts[2], "test=")) {
3893 gchar *orig_testcmd = g_strdup(strstr(parts[2], "test=")+5);
3894 gchar *testcmd = orig_testcmd;
3895 if (strstr(testcmd,";"))
3896 *(strstr(testcmd,";")) = '\0';
3897 while (testcmd[0] == ' ' || testcmd[0] == '\t')
3898 testcmd++;
3899 while (testcmd[strlen(testcmd)-1] == '\n')
3900 testcmd[strlen(testcmd)-1] = '\0';
3901 while (testcmd[strlen(testcmd)-1] == '\r')
3902 testcmd[strlen(testcmd)-1] = '\0';
3903 while (testcmd[strlen(testcmd)-1] == ' ' || testcmd[strlen(testcmd)-1] == '\t')
3904 testcmd[strlen(testcmd)-1] = '\0';
3906 if (strstr(testcmd, "%s")) {
3907 gchar *tmp = g_strdup_printf(testcmd, file_to_open);
3908 gint res = system(tmp);
3909 g_free(tmp);
3910 g_free(orig_testcmd);
3912 if (res != 0) {
3913 g_strfreev(parts);
3914 continue;
3916 } else {
3917 gint res = system(testcmd);
3918 g_free(orig_testcmd);
3920 if (res != 0) {
3921 g_strfreev(parts);
3922 continue;
3927 trimmed = parts[1];
3928 while (trimmed[0] == ' ' || trimmed[0] == '\t')
3929 trimmed++;
3930 while (trimmed[strlen(trimmed)-1] == '\n')
3931 trimmed[strlen(trimmed)-1] = '\0';
3932 while (trimmed[strlen(trimmed)-1] == '\r')
3933 trimmed[strlen(trimmed)-1] = '\0';
3934 while (trimmed[strlen(trimmed)-1] == ' ' || trimmed[strlen(trimmed)-1] == '\t')
3935 trimmed[strlen(trimmed)-1] = '\0';
3936 result = g_strdup(trimmed);
3937 g_strfreev(parts);
3938 claws_fclose(fp);
3939 if (needsterminal) {
3940 gchar *tmp = g_strdup_printf("xterm -e %s", result);
3941 g_free(result);
3942 result = tmp;
3944 return result;
3946 g_strfreev(parts);
3948 claws_fclose(fp);
3949 return NULL;
3951 gchar *mailcap_get_command_for_type(const gchar *type, const gchar *file_to_open)
3953 gchar *result = NULL;
3954 gchar *path = NULL;
3955 if (type == NULL)
3956 return NULL;
3957 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3958 result = mailcap_get_command_in_file(path, type, file_to_open);
3959 g_free(path);
3960 if (result)
3961 return result;
3962 result = mailcap_get_command_in_file("/etc/mailcap", type, file_to_open);
3963 return result;
3966 void mailcap_update_default(const gchar *type, const gchar *command)
3968 gchar *path = NULL, *outpath = NULL;
3969 path = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap", NULL);
3970 outpath = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S, ".mailcap.new", NULL);
3971 FILE *fp = claws_fopen(path, "rb");
3972 FILE *outfp = NULL;
3973 gchar buf[BUFFSIZE];
3974 gboolean err = FALSE;
3976 if (!fp) {
3977 fp = claws_fopen(path, "a");
3978 if (!fp) {
3979 g_warning("failed to create file %s", path);
3980 g_free(path);
3981 g_free(outpath);
3982 return;
3984 fp = g_freopen(path, "rb", fp);
3985 if (!fp) {
3986 g_warning("failed to reopen file %s", path);
3987 g_free(path);
3988 g_free(outpath);
3989 return;
3993 outfp = claws_fopen(outpath, "wb");
3994 if (!outfp) {
3995 g_warning("failed to create file %s", outpath);
3996 g_free(path);
3997 g_free(outpath);
3998 claws_fclose(fp);
3999 return;
4001 while (fp && claws_fgets(buf, sizeof (buf), fp) != NULL) {
4002 gchar **parts = g_strsplit(buf, ";", 3);
4003 gchar *trimmed = parts[0];
4004 while (trimmed[0] == ' ')
4005 trimmed++;
4006 while (trimmed[strlen(trimmed)-1] == ' ')
4007 trimmed[strlen(trimmed)-1] = '\0';
4009 if (!strcmp(trimmed, type)) {
4010 g_strfreev(parts);
4011 continue;
4013 else {
4014 if(claws_fputs(buf, outfp) == EOF) {
4015 err = TRUE;
4016 g_strfreev(parts);
4017 break;
4020 g_strfreev(parts);
4022 if (fprintf(outfp, "%s; %s\n", type, command) < 0)
4023 err = TRUE;
4025 if (fp)
4026 claws_fclose(fp);
4028 if (claws_safe_fclose(outfp) == EOF)
4029 err = TRUE;
4031 if (!err)
4032 g_rename(outpath, path);
4034 g_free(path);
4035 g_free(outpath);
4038 /* crude test to see if a file is an email. */
4039 gboolean file_is_email (const gchar *filename)
4041 FILE *fp = NULL;
4042 gchar buffer[2048];
4043 gint score = 0;
4044 if (filename == NULL)
4045 return FALSE;
4046 if ((fp = claws_fopen(filename, "rb")) == NULL)
4047 return FALSE;
4048 while (score < 3
4049 && claws_fgets(buffer, sizeof (buffer), fp) != NULL) {
4050 if (!strncmp(buffer, "From:", strlen("From:")))
4051 score++;
4052 else if (!strncmp(buffer, "Date:", strlen("Date:")))
4053 score++;
4054 else if (!strncmp(buffer, "Message-ID:", strlen("Message-ID:")))
4055 score++;
4056 else if (!strncmp(buffer, "Subject:", strlen("Subject:")))
4057 score++;
4058 else if (!strcmp(buffer, "\r\n")) {
4059 debug_print("End of headers\n");
4060 break;
4063 claws_fclose(fp);
4064 return (score >= 3);
4067 gboolean sc_g_list_bigger(GList *list, gint max)
4069 GList *cur = list;
4070 int i = 0;
4071 while (cur && i <= max+1) {
4072 i++;
4073 cur = cur->next;
4075 return (i > max);
4078 gboolean sc_g_slist_bigger(GSList *list, gint max)
4080 GSList *cur = list;
4081 int i = 0;
4082 while (cur && i <= max+1) {
4083 i++;
4084 cur = cur->next;
4086 return (i > max);
4089 const gchar *daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4090 const gchar *monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4091 NULL, NULL, NULL, NULL, NULL, NULL};
4092 const gchar *s_daynames[] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
4093 const gchar *s_monthnames[] = {NULL, NULL, NULL, NULL, NULL, NULL,
4094 NULL, NULL, NULL, NULL, NULL, NULL};
4096 gint daynames_len[] = {0,0,0,0,0,0,0};
4097 gint monthnames_len[] = {0,0,0,0,0,0,
4098 0,0,0,0,0,0};
4099 gint s_daynames_len[] = {0,0,0,0,0,0,0};
4100 gint s_monthnames_len[] = {0,0,0,0,0,0,
4101 0,0,0,0,0,0};
4102 const gchar *s_am_up = NULL;
4103 const gchar *s_pm_up = NULL;
4104 const gchar *s_am_low = NULL;
4105 const gchar *s_pm_low = NULL;
4107 gint s_am_up_len = 0;
4108 gint s_pm_up_len = 0;
4109 gint s_am_low_len = 0;
4110 gint s_pm_low_len = 0;
4112 static gboolean time_names_init_done = FALSE;
4114 static void init_time_names(void)
4116 int i = 0;
4118 daynames[0] = C_("Complete day name for use by strftime", "Sunday");
4119 daynames[1] = C_("Complete day name for use by strftime", "Monday");
4120 daynames[2] = C_("Complete day name for use by strftime", "Tuesday");
4121 daynames[3] = C_("Complete day name for use by strftime", "Wednesday");
4122 daynames[4] = C_("Complete day name for use by strftime", "Thursday");
4123 daynames[5] = C_("Complete day name for use by strftime", "Friday");
4124 daynames[6] = C_("Complete day name for use by strftime", "Saturday");
4126 monthnames[0] = C_("Complete month name for use by strftime", "January");
4127 monthnames[1] = C_("Complete month name for use by strftime", "February");
4128 monthnames[2] = C_("Complete month name for use by strftime", "March");
4129 monthnames[3] = C_("Complete month name for use by strftime", "April");
4130 monthnames[4] = C_("Complete month name for use by strftime", "May");
4131 monthnames[5] = C_("Complete month name for use by strftime", "June");
4132 monthnames[6] = C_("Complete month name for use by strftime", "July");
4133 monthnames[7] = C_("Complete month name for use by strftime", "August");
4134 monthnames[8] = C_("Complete month name for use by strftime", "September");
4135 monthnames[9] = C_("Complete month name for use by strftime", "October");
4136 monthnames[10] = C_("Complete month name for use by strftime", "November");
4137 monthnames[11] = C_("Complete month name for use by strftime", "December");
4139 s_daynames[0] = C_("Abbr. day name for use by strftime", "Sun");
4140 s_daynames[1] = C_("Abbr. day name for use by strftime", "Mon");
4141 s_daynames[2] = C_("Abbr. day name for use by strftime", "Tue");
4142 s_daynames[3] = C_("Abbr. day name for use by strftime", "Wed");
4143 s_daynames[4] = C_("Abbr. day name for use by strftime", "Thu");
4144 s_daynames[5] = C_("Abbr. day name for use by strftime", "Fri");
4145 s_daynames[6] = C_("Abbr. day name for use by strftime", "Sat");
4147 s_monthnames[0] = C_("Abbr. month name for use by strftime", "Jan");
4148 s_monthnames[1] = C_("Abbr. month name for use by strftime", "Feb");
4149 s_monthnames[2] = C_("Abbr. month name for use by strftime", "Mar");
4150 s_monthnames[3] = C_("Abbr. month name for use by strftime", "Apr");
4151 s_monthnames[4] = C_("Abbr. month name for use by strftime", "May");
4152 s_monthnames[5] = C_("Abbr. month name for use by strftime", "Jun");
4153 s_monthnames[6] = C_("Abbr. month name for use by strftime", "Jul");
4154 s_monthnames[7] = C_("Abbr. month name for use by strftime", "Aug");
4155 s_monthnames[8] = C_("Abbr. month name for use by strftime", "Sep");
4156 s_monthnames[9] = C_("Abbr. month name for use by strftime", "Oct");
4157 s_monthnames[10] = C_("Abbr. month name for use by strftime", "Nov");
4158 s_monthnames[11] = C_("Abbr. month name for use by strftime", "Dec");
4160 for (i = 0; i < 7; i++) {
4161 daynames_len[i] = strlen(daynames[i]);
4162 s_daynames_len[i] = strlen(s_daynames[i]);
4164 for (i = 0; i < 12; i++) {
4165 monthnames_len[i] = strlen(monthnames[i]);
4166 s_monthnames_len[i] = strlen(s_monthnames[i]);
4169 s_am_up = C_("For use by strftime (morning)", "AM");
4170 s_pm_up = C_("For use by strftime (afternoon)", "PM");
4171 s_am_low = C_("For use by strftime (morning, lowercase)", "am");
4172 s_pm_low = C_("For use by strftime (afternoon, lowercase)", "pm");
4174 s_am_up_len = strlen(s_am_up);
4175 s_pm_up_len = strlen(s_pm_up);
4176 s_am_low_len = strlen(s_am_low);
4177 s_pm_low_len = strlen(s_pm_low);
4179 time_names_init_done = TRUE;
4182 #define CHECK_SIZE() { \
4183 total_done += len; \
4184 if (total_done >= buflen) { \
4185 buf[buflen-1] = '\0'; \
4186 return 0; \
4190 size_t fast_strftime(gchar *buf, gint buflen, const gchar *format, struct tm *lt)
4192 gchar *curpos = buf;
4193 gint total_done = 0;
4194 gchar subbuf[64], subfmt[64];
4195 static time_t last_tzset = (time_t)0;
4197 if (!time_names_init_done)
4198 init_time_names();
4200 if (format == NULL || lt == NULL)
4201 return 0;
4203 if (last_tzset != time(NULL)) {
4204 tzset();
4205 last_tzset = time(NULL);
4207 while(*format) {
4208 if (*format == '%') {
4209 gint len = 0, tmp = 0;
4210 format++;
4211 switch(*format) {
4212 case '%':
4213 len = 1; CHECK_SIZE();
4214 *curpos = '%';
4215 break;
4216 case 'a':
4217 len = s_daynames_len[lt->tm_wday]; CHECK_SIZE();
4218 strncpy2(curpos, s_daynames[lt->tm_wday], buflen - total_done);
4219 break;
4220 case 'A':
4221 len = daynames_len[lt->tm_wday]; CHECK_SIZE();
4222 strncpy2(curpos, daynames[lt->tm_wday], buflen - total_done);
4223 break;
4224 case 'b':
4225 case 'h':
4226 len = s_monthnames_len[lt->tm_mon]; CHECK_SIZE();
4227 strncpy2(curpos, s_monthnames[lt->tm_mon], buflen - total_done);
4228 break;
4229 case 'B':
4230 len = monthnames_len[lt->tm_mon]; CHECK_SIZE();
4231 strncpy2(curpos, monthnames[lt->tm_mon], buflen - total_done);
4232 break;
4233 case 'c':
4234 strftime(subbuf, 64, "%c", lt);
4235 len = strlen(subbuf); CHECK_SIZE();
4236 strncpy2(curpos, subbuf, buflen - total_done);
4237 break;
4238 case 'C':
4239 total_done += 2; CHECK_SIZE();
4240 tmp = (lt->tm_year + 1900)/100;
4241 *curpos++ = '0'+(tmp / 10);
4242 *curpos++ = '0'+(tmp % 10);
4243 break;
4244 case 'd':
4245 total_done += 2; CHECK_SIZE();
4246 *curpos++ = '0'+(lt->tm_mday / 10);
4247 *curpos++ = '0'+(lt->tm_mday % 10);
4248 break;
4249 case 'D':
4250 total_done += 8; CHECK_SIZE();
4251 *curpos++ = '0'+((lt->tm_mon+1) / 10);
4252 *curpos++ = '0'+((lt->tm_mon+1) % 10);
4253 *curpos++ = '/';
4254 *curpos++ = '0'+(lt->tm_mday / 10);
4255 *curpos++ = '0'+(lt->tm_mday % 10);
4256 *curpos++ = '/';
4257 tmp = lt->tm_year%100;
4258 *curpos++ = '0'+(tmp / 10);
4259 *curpos++ = '0'+(tmp % 10);
4260 break;
4261 case 'e':
4262 len = 2; CHECK_SIZE();
4263 snprintf(curpos, buflen - total_done, "%2d", lt->tm_mday);
4264 break;
4265 case 'F':
4266 len = 10; CHECK_SIZE();
4267 snprintf(curpos, buflen - total_done, "%4d-%02d-%02d",
4268 lt->tm_year + 1900, lt->tm_mon +1, lt->tm_mday);
4269 break;
4270 case 'H':
4271 total_done += 2; CHECK_SIZE();
4272 *curpos++ = '0'+(lt->tm_hour / 10);
4273 *curpos++ = '0'+(lt->tm_hour % 10);
4274 break;
4275 case 'I':
4276 total_done += 2; CHECK_SIZE();
4277 tmp = lt->tm_hour;
4278 if (tmp > 12)
4279 tmp -= 12;
4280 else if (tmp == 0)
4281 tmp = 12;
4282 *curpos++ = '0'+(tmp / 10);
4283 *curpos++ = '0'+(tmp % 10);
4284 break;
4285 case 'j':
4286 len = 3; CHECK_SIZE();
4287 snprintf(curpos, buflen - total_done, "%03d", lt->tm_yday+1);
4288 break;
4289 case 'k':
4290 len = 2; CHECK_SIZE();
4291 snprintf(curpos, buflen - total_done, "%2d", lt->tm_hour);
4292 break;
4293 case 'l':
4294 len = 2; CHECK_SIZE();
4295 tmp = lt->tm_hour;
4296 if (tmp > 12)
4297 tmp -= 12;
4298 else if (tmp == 0)
4299 tmp = 12;
4300 snprintf(curpos, buflen - total_done, "%2d", tmp);
4301 break;
4302 case 'm':
4303 total_done += 2; CHECK_SIZE();
4304 tmp = lt->tm_mon + 1;
4305 *curpos++ = '0'+(tmp / 10);
4306 *curpos++ = '0'+(tmp % 10);
4307 break;
4308 case 'M':
4309 total_done += 2; CHECK_SIZE();
4310 *curpos++ = '0'+(lt->tm_min / 10);
4311 *curpos++ = '0'+(lt->tm_min % 10);
4312 break;
4313 case 'n':
4314 len = 1; CHECK_SIZE();
4315 *curpos = '\n';
4316 break;
4317 case 'p':
4318 if (lt->tm_hour >= 12) {
4319 len = s_pm_up_len; CHECK_SIZE();
4320 snprintf(curpos, buflen-total_done, "%s", s_pm_up);
4321 } else {
4322 len = s_am_up_len; CHECK_SIZE();
4323 snprintf(curpos, buflen-total_done, "%s", s_am_up);
4325 break;
4326 case 'P':
4327 if (lt->tm_hour >= 12) {
4328 len = s_pm_low_len; CHECK_SIZE();
4329 snprintf(curpos, buflen-total_done, "%s", s_pm_low);
4330 } else {
4331 len = s_am_low_len; CHECK_SIZE();
4332 snprintf(curpos, buflen-total_done, "%s", s_am_low);
4334 break;
4335 case 'r':
4336 #ifdef G_OS_WIN32
4337 strftime(subbuf, 64, "%I:%M:%S %p", lt);
4338 #else
4339 strftime(subbuf, 64, "%r", lt);
4340 #endif
4341 len = strlen(subbuf); CHECK_SIZE();
4342 strncpy2(curpos, subbuf, buflen - total_done);
4343 break;
4344 case 'R':
4345 total_done += 5; CHECK_SIZE();
4346 *curpos++ = '0'+(lt->tm_hour / 10);
4347 *curpos++ = '0'+(lt->tm_hour % 10);
4348 *curpos++ = ':';
4349 *curpos++ = '0'+(lt->tm_min / 10);
4350 *curpos++ = '0'+(lt->tm_min % 10);
4351 break;
4352 case 's':
4353 snprintf(subbuf, 64, "%" CM_TIME_FORMAT, mktime(lt));
4354 len = strlen(subbuf); CHECK_SIZE();
4355 strncpy2(curpos, subbuf, buflen - total_done);
4356 break;
4357 case 'S':
4358 total_done += 2; CHECK_SIZE();
4359 *curpos++ = '0'+(lt->tm_sec / 10);
4360 *curpos++ = '0'+(lt->tm_sec % 10);
4361 break;
4362 case 't':
4363 len = 1; CHECK_SIZE();
4364 *curpos = '\t';
4365 break;
4366 case 'T':
4367 total_done += 8; CHECK_SIZE();
4368 *curpos++ = '0'+(lt->tm_hour / 10);
4369 *curpos++ = '0'+(lt->tm_hour % 10);
4370 *curpos++ = ':';
4371 *curpos++ = '0'+(lt->tm_min / 10);
4372 *curpos++ = '0'+(lt->tm_min % 10);
4373 *curpos++ = ':';
4374 *curpos++ = '0'+(lt->tm_sec / 10);
4375 *curpos++ = '0'+(lt->tm_sec % 10);
4376 break;
4377 case 'u':
4378 len = 1; CHECK_SIZE();
4379 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday == 0 ? 7: lt->tm_wday);
4380 break;
4381 case 'w':
4382 len = 1; CHECK_SIZE();
4383 snprintf(curpos, buflen - total_done, "%d", lt->tm_wday);
4384 break;
4385 case 'x':
4386 strftime(subbuf, 64, "%x", lt);
4387 len = strlen(subbuf); CHECK_SIZE();
4388 strncpy2(curpos, subbuf, buflen - total_done);
4389 break;
4390 case 'X':
4391 strftime(subbuf, 64, "%X", lt);
4392 len = strlen(subbuf); CHECK_SIZE();
4393 strncpy2(curpos, subbuf, buflen - total_done);
4394 break;
4395 case 'y':
4396 total_done += 2; CHECK_SIZE();
4397 tmp = lt->tm_year%100;
4398 *curpos++ = '0'+(tmp / 10);
4399 *curpos++ = '0'+(tmp % 10);
4400 break;
4401 case 'Y':
4402 len = 4; CHECK_SIZE();
4403 snprintf(curpos, buflen - total_done, "%4d", lt->tm_year + 1900);
4404 break;
4405 case 'G':
4406 case 'g':
4407 case 'U':
4408 case 'V':
4409 case 'W':
4410 case 'z':
4411 case 'Z':
4412 case '+':
4413 /* let these complicated ones be done with the libc */
4414 snprintf(subfmt, 64, "%%%c", *format);
4415 strftime(subbuf, 64, subfmt, lt);
4416 len = strlen(subbuf); CHECK_SIZE();
4417 strncpy2(curpos, subbuf, buflen - total_done);
4418 break;
4419 case 'E':
4420 case 'O':
4421 /* let these complicated modifiers be done with the libc */
4422 snprintf(subfmt, 64, "%%%c%c", *format, *(format+1));
4423 strftime(subbuf, 64, subfmt, lt);
4424 len = strlen(subbuf); CHECK_SIZE();
4425 strncpy2(curpos, subbuf, buflen - total_done);
4426 format++;
4427 break;
4428 default:
4429 g_warning("format error (%c)", *format);
4430 *curpos = '\0';
4431 return total_done;
4433 curpos += len;
4434 format++;
4435 } else {
4436 int len = 1; CHECK_SIZE();
4437 *curpos++ = *format++;
4440 *curpos = '\0';
4441 return total_done;
4444 #ifdef G_OS_WIN32
4445 #define WEXITSTATUS(x) (x)
4446 #endif
4448 static gchar *canonical_list_to_file(GSList *list)
4450 GString *result = g_string_new(NULL);
4451 GSList *pathlist = g_slist_reverse(g_slist_copy(list));
4452 GSList *cur;
4453 gchar *str;
4455 #ifndef G_OS_WIN32
4456 result = g_string_append(result, G_DIR_SEPARATOR_S);
4457 #else
4458 if (pathlist->data) {
4459 const gchar *root = (gchar *)pathlist->data;
4460 if (root[0] != '\0' && g_ascii_isalpha(root[0]) &&
4461 root[1] == ':') {
4462 /* drive - don't prepend dir separator */
4463 } else {
4464 result = g_string_append(result, G_DIR_SEPARATOR_S);
4467 #endif
4469 for (cur = pathlist; cur; cur = cur->next) {
4470 result = g_string_append(result, (gchar *)cur->data);
4471 if (cur->next)
4472 result = g_string_append(result, G_DIR_SEPARATOR_S);
4474 g_slist_free(pathlist);
4476 str = result->str;
4477 g_string_free(result, FALSE);
4479 return str;
4482 static GSList *cm_split_path(const gchar *filename, int depth)
4484 gchar **path_parts;
4485 GSList *canonical_parts = NULL;
4486 GStatBuf st;
4487 int i;
4488 #ifndef G_OS_WIN32
4489 gboolean follow_symlinks = TRUE;
4490 #endif
4492 if (depth > 32) {
4493 #ifndef G_OS_WIN32
4494 errno = ELOOP;
4495 #else
4496 errno = EINVAL; /* can't happen, no symlink handling */
4497 #endif
4498 return NULL;
4501 if (!g_path_is_absolute(filename)) {
4502 errno =EINVAL;
4503 return NULL;
4506 path_parts = g_strsplit(filename, G_DIR_SEPARATOR_S, -1);
4508 for (i = 0; path_parts[i] != NULL; i++) {
4509 if (!strcmp(path_parts[i], ""))
4510 continue;
4511 if (!strcmp(path_parts[i], "."))
4512 continue;
4513 else if (!strcmp(path_parts[i], "..")) {
4514 if (i == 0) {
4515 errno =ENOTDIR;
4516 g_strfreev(path_parts);
4517 return NULL;
4519 else /* Remove the last inserted element */
4520 canonical_parts =
4521 g_slist_delete_link(canonical_parts,
4522 canonical_parts);
4523 } else {
4524 gchar *tmp_path;
4526 canonical_parts = g_slist_prepend(canonical_parts,
4527 g_strdup(path_parts[i]));
4529 tmp_path = canonical_list_to_file(canonical_parts);
4531 if(g_stat(tmp_path, &st) < 0) {
4532 if (errno == ENOENT) {
4533 errno = 0;
4534 #ifndef G_OS_WIN32
4535 follow_symlinks = FALSE;
4536 #endif
4538 if (errno != 0) {
4539 g_free(tmp_path);
4540 slist_free_strings_full(canonical_parts);
4541 g_strfreev(path_parts);
4543 return NULL;
4546 #ifndef G_OS_WIN32
4547 if (follow_symlinks && g_file_test(tmp_path, G_FILE_TEST_IS_SYMLINK)) {
4548 GError *error = NULL;
4549 gchar *target = g_file_read_link(tmp_path, &error);
4551 if (!g_path_is_absolute(target)) {
4552 /* remove the last inserted element */
4553 canonical_parts =
4554 g_slist_delete_link(canonical_parts,
4555 canonical_parts);
4556 /* add the target */
4557 canonical_parts = g_slist_prepend(canonical_parts,
4558 g_strdup(target));
4559 g_free(target);
4561 /* and get the new target */
4562 target = canonical_list_to_file(canonical_parts);
4565 /* restart from absolute target */
4566 slist_free_strings_full(canonical_parts);
4567 canonical_parts = NULL;
4568 if (!error)
4569 canonical_parts = cm_split_path(target, depth + 1);
4570 else
4571 g_error_free(error);
4572 if (canonical_parts == NULL) {
4573 g_free(tmp_path);
4574 g_strfreev(path_parts);
4575 return NULL;
4577 g_free(target);
4579 #endif
4580 g_free(tmp_path);
4583 g_strfreev(path_parts);
4584 return canonical_parts;
4588 * Canonicalize a filename, resolving symlinks along the way.
4589 * Returns a negative errno in case of error.
4591 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name) {
4592 GSList *canonical_parts;
4593 gboolean is_absolute;
4595 if (filename == NULL)
4596 return -EINVAL;
4597 if (canonical_name == NULL)
4598 return -EINVAL;
4599 *canonical_name = NULL;
4601 is_absolute = g_path_is_absolute(filename);
4602 if (!is_absolute) {
4603 /* Always work on absolute filenames. */
4604 gchar *cur = g_get_current_dir();
4605 gchar *absolute_filename = g_strconcat(cur, G_DIR_SEPARATOR_S,
4606 filename, NULL);
4608 canonical_parts = cm_split_path(absolute_filename, 0);
4609 g_free(absolute_filename);
4610 g_free(cur);
4611 } else
4612 canonical_parts = cm_split_path(filename, 0);
4614 if (canonical_parts == NULL)
4615 return -errno;
4617 *canonical_name = canonical_list_to_file(canonical_parts);
4618 slist_free_strings_full(canonical_parts);
4619 return 0;
4622 /* Returns a decoded base64 string, guaranteed to be null-terminated. */
4623 guchar *g_base64_decode_zero(const gchar *text, gsize *out_len)
4625 gchar *tmp = g_base64_decode(text, out_len);
4626 gchar *out = g_strndup(tmp, *out_len);
4628 g_free(tmp);
4630 if (strlen(out) != *out_len) {
4631 g_warning("strlen(out) %"G_GSIZE_FORMAT" != *out_len %"G_GSIZE_FORMAT, strlen(out), *out_len);
4634 return out;
4637 /* Attempts to read count bytes from a PRNG into memory area starting at buf.
4638 * It is up to the caller to make sure there is at least count bytes
4639 * available at buf. */
4640 gboolean
4641 get_random_bytes(void *buf, size_t count)
4643 /* Open our prng source. */
4644 #if defined G_OS_WIN32
4645 HCRYPTPROV rnd;
4647 if (!CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, 0) &&
4648 !CryptAcquireContext(&rnd, NULL, NULL, PROV_RSA_FULL, CRYPT_NEWKEYSET)) {
4649 debug_print("Could not acquire a CSP handle.\n");
4650 return FALSE;
4652 #else
4653 int rnd;
4654 ssize_t ret;
4656 rnd = open("/dev/urandom", O_RDONLY);
4657 if (rnd == -1) {
4658 FILE_OP_ERROR("/dev/urandom", "open");
4659 debug_print("Could not open /dev/urandom.\n");
4660 return FALSE;
4662 #endif
4664 /* Read data from the source into buf. */
4665 #if defined G_OS_WIN32
4666 if (!CryptGenRandom(rnd, count, buf)) {
4667 debug_print("Could not read %"G_GSIZE_FORMAT" random bytes.\n", count);
4668 CryptReleaseContext(rnd, 0);
4669 return FALSE;
4671 #else
4672 ret = read(rnd, buf, count);
4673 if (ret != count) {
4674 FILE_OP_ERROR("/dev/urandom", "read");
4675 debug_print("Could not read enough data from /dev/urandom, read only %ld of %lu bytes.\n", ret, count);
4676 close(rnd);
4677 return FALSE;
4679 #endif
4681 /* Close the prng source. */
4682 #if defined G_OS_WIN32
4683 CryptReleaseContext(rnd, 0);
4684 #else
4685 close(rnd);
4686 #endif
4688 return TRUE;
4691 /* returns FALSE if parsing failed, otherwise returns TRUE and sets *server, *port
4692 and eventually *fp from filename (if not NULL, they must be free'd by caller after
4693 user.
4694 filenames we expect: 'host.name.port.cert' or 'host.name.port.f:i:n:g:e:r:p:r:i:n:t.cert' */
4695 gboolean get_serverportfp_from_filename(const gchar *str, gchar **server, gchar **port, gchar **fp)
4697 const gchar *pos, *dotport_pos = NULL, *dotcert_pos = NULL, *dotfp_pos = NULL;
4699 g_return_val_if_fail(str != NULL, FALSE);
4701 pos = str + strlen(str) - 1;
4702 while ((pos > str) && !dotport_pos) {
4703 if (*pos == '.') {
4704 if (!dotcert_pos) {
4705 /* match the .cert suffix */
4706 if (strcmp(pos, ".cert") == 0) {
4707 dotcert_pos = pos;
4709 } else {
4710 if (!dotfp_pos) {
4711 /* match an eventual fingerprint */
4712 /* or the port number */
4713 if (strncmp(pos + 3, ":", 1) == 0) {
4714 dotfp_pos = pos;
4715 } else {
4716 dotport_pos = pos;
4718 } else {
4719 /* match the port number */
4720 dotport_pos = pos;
4724 pos--;
4726 if (!dotport_pos || !dotcert_pos) {
4727 g_warning("could not parse filename %s", str);
4728 return FALSE;
4731 if (server != NULL)
4732 *server = g_strndup(str, dotport_pos - str);
4733 if (dotfp_pos) {
4734 if (port != NULL)
4735 *port = g_strndup(dotport_pos + 1, dotfp_pos - dotport_pos - 1);
4736 if (fp != NULL)
4737 *fp = g_strndup(dotfp_pos + 1, dotcert_pos - dotfp_pos - 1);
4738 } else {
4739 if (port != NULL)
4740 *port = g_strndup(dotport_pos + 1, dotcert_pos - dotport_pos - 1);
4741 if (fp != NULL)
4742 *fp = NULL;
4745 debug_print("filename='%s' => server='%s' port='%s' fp='%s'\n",
4746 str,
4747 (server ? *server : "(n/a)"),
4748 (port ? *port : "(n/a)"),
4749 (fp ? *fp : "(n/a)"));
4751 if (!(server && *server) || !(port && *port))
4752 return FALSE;
4753 else
4754 return TRUE;
4757 #ifdef G_OS_WIN32
4758 gchar *win32_debug_log_path(void)
4760 return g_strconcat(g_get_tmp_dir(), G_DIR_SEPARATOR_S,
4761 "claws-win32.log", NULL);
4763 #endif