2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2003 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 2 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, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
32 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
40 #include <sys/types.h>
51 static gboolean debug_mode = FALSE;
53 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
55 void list_free_strings(GList *list)
57 list = g_list_first(list);
59 while (list != NULL) {
65 void slist_free_strings(GSList *list)
67 while (list != NULL) {
73 GSList *slist_concat_unique (GSList *first, GSList *second)
81 } else if (second == NULL)
84 for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
85 if (g_slist_find(ret, tmp->data) == NULL)
86 ret = g_slist_prepend(ret, tmp->data);
91 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
96 void hash_free_strings(GHashTable *table)
98 g_hash_table_foreach(table, hash_free_strings_func, NULL);
101 static void hash_free_value_mem_func(gpointer key, gpointer value,
107 void hash_free_value_mem(GHashTable *table)
109 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
112 void ptr_array_free_strings(GPtrArray *array)
117 g_return_if_fail(array != NULL);
119 for (i = 0; i < array->len; i++) {
120 str = g_ptr_array_index(array, i);
125 gint to_number(const gchar *nstr)
127 register const gchar *p;
129 if (*nstr == '\0') return -1;
131 for (p = nstr; *p != '\0'; p++)
132 if (!isdigit(*p)) return -1;
137 /* convert integer into string,
138 nstr must be not lower than 11 characters length */
139 gchar *itos_buf(gchar *nstr, gint n)
141 g_snprintf(nstr, 11, "%d", n);
145 /* convert integer into string */
148 static gchar nstr[11];
150 return itos_buf(nstr, n);
153 gchar *to_human_readable(off_t size)
155 static gchar str[10];
158 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
159 else if (size >> 10 < 1024)
160 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
161 else if (size >> 20 < 1024)
162 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
164 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
169 /* strcmp with NULL-checking */
170 gint strcmp2(const gchar *s1, const gchar *s2)
172 if (s1 == NULL || s2 == NULL)
175 return strcmp(s1, s2);
177 /* strstr with NULL-checking */
178 gchar *strstr2(const gchar *s1, const gchar *s2)
180 if (s1 == NULL || s2 == NULL)
183 return strstr(s1, s2);
186 gint path_cmp(const gchar *s1, const gchar *s2)
190 if (s1 == NULL || s2 == NULL) return -1;
191 if (*s1 == '\0' || *s2 == '\0') return -1;
196 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
197 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
199 return strncmp(s1, s2, MAX(len1, len2));
202 /* remove trailing return code */
203 gchar *strretchomp(gchar *str)
207 if (!*str) return str;
209 for (s = str + strlen(str) - 1;
210 s >= str && (*s == '\n' || *s == '\r');
217 /* remove trailing character */
218 gchar *strtailchomp(gchar *str, gchar tail_char)
222 if (!*str) return str;
223 if (tail_char == '\0') return str;
225 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
231 /* remove CR (carriage return) */
232 gchar *strcrchomp(gchar *str)
236 if (!*str) return str;
238 s = str + strlen(str) - 1;
239 if (*s == '\n' && s > str && *(s - 1) == '\r') {
247 /* Similar to `strstr' but this function ignores the case of both strings. */
248 gchar *strcasestr(const gchar *haystack, const gchar *needle)
250 register size_t haystack_len, needle_len;
252 haystack_len = strlen(haystack);
253 needle_len = strlen(needle);
255 if (haystack_len < needle_len || needle_len == 0)
258 while (haystack_len >= needle_len) {
259 if (!strncasecmp(haystack, needle, needle_len))
260 return (gchar *)haystack;
270 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
271 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
285 /* don't do zero fill */
290 int iswalnum(wint_t wc)
292 return isalnum((int)wc);
297 int iswspace(wint_t wc)
299 return isspace((int)wc);
304 wint_t towlower(wint_t wc)
306 if (wc >= L'A' && wc <= L'Z')
307 return wc + L'a' - L'A';
314 size_t wcslen(const wchar_t *s)
326 /* Copy SRC to DEST. */
327 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
335 } while (c != L'\0');
342 /* Copy no more than N wide-characters of SRC to DEST. */
343 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
353 } while (c != L'\0');
364 /* Duplicate S, returning an identical malloc'd string. */
365 wchar_t *wcsdup(const wchar_t *s)
370 new_str = g_new(wchar_t, wcslen(s) + 1);
378 /* Duplicate no more than N wide-characters of S,
379 returning an identical malloc'd string. */
380 wchar_t *wcsndup(const wchar_t *s, size_t n)
385 new_str = g_new(wchar_t, n + 1);
386 wcsncpy(new_str, s, n);
387 new_str[n] = (wchar_t)0;
394 wchar_t *strdup_mbstowcs(const gchar *s)
399 new_str = g_new(wchar_t, strlen(s) + 1);
400 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
404 new_str = g_realloc(new_str,
405 sizeof(wchar_t) * (wcslen(new_str) + 1));
412 gchar *strdup_wcstombs(const wchar_t *s)
418 len = wcslen(s) * MB_CUR_MAX + 1;
419 new_str = g_new(gchar, len);
420 if (wcstombs(new_str, s, len) < 0) {
424 new_str = g_realloc(new_str, strlen(new_str) + 1);
431 /* Compare S1 and S2, ignoring case. */
432 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
438 c1 = towlower(*s1++);
439 c2 = towlower(*s2++);
442 else if (c1 == 0 && c2 == 0)
449 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
450 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
452 register size_t haystack_len, needle_len;
454 haystack_len = wcslen(haystack);
455 needle_len = wcslen(needle);
457 if (haystack_len < needle_len || needle_len == 0)
460 while (haystack_len >= needle_len) {
461 if (!wcsncasecmp(haystack, needle, needle_len))
462 return (wchar_t *)haystack;
472 /* Examine if next block is non-ASCII string */
473 gboolean is_next_nonascii(const guchar *s)
477 /* skip head space */
478 for (p = s; *p != '\0' && isspace(*p); p++)
480 for (; *p != '\0' && !isspace(*p); p++) {
481 if (*p > 127 || *p < 32)
488 gint get_next_word_len(const gchar *s)
492 for (; *s != '\0' && !isspace(*s); s++, len++)
498 /* compare subjects */
499 gint subject_compare(const gchar *s1, const gchar *s2)
503 if (!s1 || !s2) return -1;
504 if (!*s1 || !*s2) return -1;
506 Xstrdup_a(str1, s1, return -1);
507 Xstrdup_a(str2, s2, return -1);
512 if (!*str1 || !*str2) return -1;
514 return strcmp(str1, str2);
517 void trim_subject(gchar *str)
521 eliminate_parenthesis(str, '[', ']');
522 eliminate_parenthesis(str, '(', ')');
525 while (!strncasecmp(str, "Re:", 3)) {
527 while (isspace(*srcp)) srcp++;
528 memmove(str, srcp, strlen(srcp) + 1);
532 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
534 register gchar *srcp, *destp;
539 while ((destp = strchr(destp, op))) {
545 else if (*srcp == cl)
551 while (isspace(*srcp)) srcp++;
552 memmove(destp, srcp, strlen(srcp) + 1);
556 void extract_parenthesis(gchar *str, gchar op, gchar cl)
558 register gchar *srcp, *destp;
563 while ((srcp = strchr(destp, op))) {
566 memmove(destp, srcp + 1, strlen(srcp));
571 else if (*destp == cl)
583 void extract_one_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
586 register gchar *srcp, *destp;
588 gboolean in_quote = FALSE;
592 if ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
593 memmove(destp, srcp + 1, strlen(srcp));
596 if (*destp == op && !in_quote)
598 else if (*destp == cl && !in_quote)
600 else if (*destp == quote_chr)
612 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
615 register gchar *srcp, *destp;
617 gboolean in_quote = FALSE;
621 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
624 memmove(destp, srcp + 1, strlen(srcp));
627 if (*destp == op && !in_quote)
629 else if (*destp == cl && !in_quote)
631 else if (*destp == quote_chr)
643 void eliminate_quote(gchar *str, gchar quote_chr)
645 register gchar *srcp, *destp;
649 while ((destp = strchr(destp, quote_chr))) {
650 if ((srcp = strchr(destp + 1, quote_chr))) {
652 while (isspace(*srcp)) srcp++;
653 memmove(destp, srcp, strlen(srcp) + 1);
661 void extract_quote(gchar *str, gchar quote_chr)
665 if ((str = strchr(str, quote_chr))) {
667 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
668 memmove(p - 1, p, strlen(p) + 1);
673 memmove(str, str + 1, p - str);
678 void eliminate_address_comment(gchar *str)
680 register gchar *srcp, *destp;
685 while ((destp = strchr(destp, '"'))) {
686 if ((srcp = strchr(destp + 1, '"'))) {
691 while (isspace(*srcp)) srcp++;
692 memmove(destp, srcp, strlen(srcp) + 1);
702 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
708 else if (*srcp == ')')
714 while (isspace(*srcp)) srcp++;
715 memmove(destp, srcp, strlen(srcp) + 1);
719 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
721 gboolean in_quote = FALSE;
724 if (*str == c && !in_quote)
726 if (*str == quote_chr)
734 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
736 gboolean in_quote = FALSE;
739 p = str + strlen(str) - 1;
741 if (*p == c && !in_quote)
751 void extract_address(gchar *str)
753 eliminate_address_comment(str);
754 if (strchr_with_skip_quote(str, '"', '<'))
755 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
759 GSList *address_list_append(GSList *addr_list, const gchar *str)
764 if (!str) return addr_list;
766 Xstrdup_a(work, str, return addr_list);
768 eliminate_address_comment(work);
771 while (workp && *workp) {
774 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
780 if (strchr_with_skip_quote(workp, '"', '<'))
781 extract_parenthesis_with_skip_quote
782 (workp, '"', '<', '>');
786 addr_list = g_slist_append(addr_list, g_strdup(workp));
794 GSList *references_list_append(GSList *msgid_list, const gchar *str)
798 if (!str) return msgid_list;
801 while (strp && *strp) {
802 const gchar *start, *end;
805 if ((start = strchr(strp, '<')) != NULL) {
806 end = strchr(start + 1, '>');
811 msgid = g_strndup(start + 1, end - start - 1);
814 msgid_list = g_slist_append(msgid_list, msgid);
824 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
829 if (!str) return group_list;
831 Xstrdup_a(work, str, return group_list);
835 while (workp && *workp) {
838 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
846 group_list = g_slist_append(group_list,
855 GList *add_history(GList *list, const gchar *str)
859 g_return_val_if_fail(str != NULL, list);
861 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
864 list = g_list_remove(list, old->data);
865 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
868 last = g_list_last(list);
871 g_list_remove(list, last->data);
875 list = g_list_prepend(list, g_strdup(str));
880 void remove_return(gchar *str)
882 register gchar *p = str;
885 if (*p == '\n' || *p == '\r')
886 memmove(p, p + 1, strlen(p));
892 void remove_space(gchar *str)
894 register gchar *p = str;
899 while (isspace(*(p + spc)))
902 memmove(p, p + spc, strlen(p + spc) + 1);
908 void unfold_line(gchar *str)
910 register gchar *p = str;
914 if (*p == '\n' || *p == '\r') {
917 while (isspace(*(p + spc)))
920 memmove(p, p + spc, strlen(p + spc) + 1);
926 void subst_char(gchar *str, gchar orig, gchar subst)
928 register gchar *p = str;
937 void subst_chars(gchar *str, gchar *orig, gchar subst)
939 register gchar *p = str;
942 if (strchr(orig, *p) != NULL)
948 void subst_for_filename(gchar *str)
950 subst_chars(str, " \t\r\n\"/\\", '_');
953 gboolean is_header_line(const gchar *str)
955 if (str[0] == ':') return FALSE;
957 while (*str != '\0' && *str != ' ') {
966 gboolean is_ascii_str(const guchar *str)
968 while (*str != '\0') {
969 if (*str != '\t' && *str != ' ' &&
970 *str != '\r' && *str != '\n' &&
971 (*str < 32 || *str >= 127))
979 gint get_quote_level(const gchar *str, const gchar *quote_chars)
981 const gchar *first_pos;
982 const gchar *last_pos;
983 const gchar *p = str;
984 gint quote_level = -1;
986 /* speed up line processing by only searching to the last '>' */
987 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
988 /* skip a line if it contains a '<' before the initial '>' */
989 if (memchr(str, '<', first_pos - str) != NULL)
991 last_pos = line_has_quote_char_last(first_pos, quote_chars);
995 while (p <= last_pos) {
996 while (p < last_pos) {
1003 if (strchr(quote_chars, *p))
1005 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1006 /* any characters are allowed except '-' and space */
1008 && !strchr(quote_chars, *p)
1012 if (strchr(quote_chars, *p))
1024 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1026 gchar * position = NULL;
1027 gchar * tmp_pos = NULL;
1030 if (quote_chars == NULL)
1033 for (i = 0; i < strlen(quote_chars); i++) {
1034 tmp_pos = strchr (str, quote_chars[i]);
1036 || (tmp_pos != NULL && position >= tmp_pos) )
1042 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1044 gchar * position = NULL;
1045 gchar * tmp_pos = NULL;
1048 if (quote_chars == NULL)
1051 for (i = 0; i < strlen(quote_chars); i++) {
1052 tmp_pos = strrchr (str, quote_chars[i]);
1054 || (tmp_pos != NULL && position <= tmp_pos) )
1060 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1062 register guint haystack_len, needle_len;
1063 gboolean in_squote = FALSE, in_dquote = FALSE;
1065 haystack_len = strlen(haystack);
1066 needle_len = strlen(needle);
1068 if (haystack_len < needle_len || needle_len == 0)
1071 while (haystack_len >= needle_len) {
1072 if (!in_squote && !in_dquote &&
1073 !strncmp(haystack, needle, needle_len))
1074 return (gchar *)haystack;
1076 /* 'foo"bar"' -> foo"bar"
1077 "foo'bar'" -> foo'bar' */
1078 if (*haystack == '\'') {
1081 else if (!in_dquote)
1083 } else if (*haystack == '\"') {
1086 else if (!in_squote)
1097 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1100 gchar quote_chr = '"';
1102 gboolean in_quote = FALSE;
1106 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1110 if (*p == op && !in_quote)
1112 else if (*p == cl && !in_quote)
1114 else if (*p == quote_chr)
1127 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1130 GSList *string_list = NULL, *slist;
1132 const gchar *s_op, *s_cl;
1135 g_return_val_if_fail(str != NULL, NULL);
1138 max_tokens = G_MAXINT;
1140 s_op = strchr_with_skip_quote(str, '"', op);
1141 if (!s_op) return NULL;
1143 s_cl = strchr_parenthesis_close(str, op, cl);
1151 new_string = g_new(gchar, len + 1);
1152 strncpy(new_string, str, len);
1153 new_string[len] = 0;
1154 string_list = g_slist_prepend(string_list, new_string);
1158 while (*str && isspace(*str)) str++;
1160 string_list = g_slist_prepend(string_list,
1163 s_op = strchr_with_skip_quote(str, '"', op);
1164 if (!--max_tokens || !s_op) break;
1168 s_cl = strchr_parenthesis_close(str, op, cl);
1169 } while (--max_tokens && s_cl);
1172 str_array = g_new(gchar*, n);
1176 str_array[i--] = NULL;
1177 for (slist = string_list; slist; slist = slist->next)
1178 str_array[i--] = slist->data;
1180 g_slist_free(string_list);
1185 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1188 GSList *string_list = NULL, *slist;
1189 gchar **str_array, *s, *new_str;
1190 guint i, n = 1, len;
1192 g_return_val_if_fail(str != NULL, NULL);
1193 g_return_val_if_fail(delim != NULL, NULL);
1196 max_tokens = G_MAXINT;
1198 s = strstr_with_skip_quote(str, delim);
1200 guint delimiter_len = strlen(delim);
1204 new_str = g_strndup(str, len);
1206 if (new_str[0] == '\'' || new_str[0] == '\"') {
1207 if (new_str[len - 1] == new_str[0]) {
1208 new_str[len - 1] = '\0';
1209 memmove(new_str, new_str + 1, len - 1);
1212 string_list = g_slist_prepend(string_list, new_str);
1214 str = s + delimiter_len;
1215 s = strstr_with_skip_quote(str, delim);
1216 } while (--max_tokens && s);
1220 new_str = g_strdup(str);
1221 if (new_str[0] == '\'' || new_str[0] == '\"') {
1223 if (new_str[len - 1] == new_str[0]) {
1224 new_str[len - 1] = '\0';
1225 memmove(new_str, new_str + 1, len - 1);
1228 string_list = g_slist_prepend(string_list, new_str);
1232 str_array = g_new(gchar*, n);
1236 str_array[i--] = NULL;
1237 for (slist = string_list; slist; slist = slist->next)
1238 str_array[i--] = slist->data;
1240 g_slist_free(string_list);
1245 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1247 gchar *abbrev_group;
1249 const gchar *p = group;
1252 g_return_val_if_fail(group != NULL, NULL);
1254 last = group + strlen(group);
1255 abbrev_group = ap = g_malloc(strlen(group) + 1);
1260 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1262 while (*p != '.') p++;
1265 return abbrev_group;
1270 return abbrev_group;
1273 gchar *trim_string(const gchar *str, gint len)
1275 const gchar *p = str;
1280 if (!str) return NULL;
1281 if (strlen(str) <= len)
1282 return g_strdup(str);
1284 while (*p != '\0') {
1285 mb_len = mblen(p, MB_LEN_MAX);
1288 else if (mb_len < 0)
1289 return g_strdup(str);
1290 else if (new_len + mb_len > len)
1297 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1298 return g_strconcat(new_str, "...", NULL);
1301 GList *uri_list_extract_filenames(const gchar *uri_list)
1303 GList *result = NULL;
1311 while (isspace(*p)) p++;
1312 if (!strncmp(p, "file:", 5)) {
1315 while (*q && *q != '\n' && *q != '\r') q++;
1319 while (q > p && isspace(*q)) q--;
1320 file = g_malloc(q - p + 2);
1321 strncpy(file, p, q - p + 1);
1322 file[q - p + 1] = '\0';
1323 result = g_list_append(result,file);
1327 p = strchr(p, '\n');
1334 #define HEX_TO_INT(val, hex) \
1338 if ('0' <= c && c <= '9') { \
1340 } else if ('a' <= c && c <= 'f') { \
1341 val = c - 'a' + 10; \
1342 } else if ('A' <= c && c <= 'F') { \
1343 val = c - 'A' + 10; \
1349 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1350 gchar **subject, gchar **body)
1355 Xstrdup_a(tmp_mailto, mailto, return -1);
1357 if (!strncmp(tmp_mailto, "mailto:", 7))
1360 p = strchr(tmp_mailto, '?');
1367 *to = g_strdup(tmp_mailto);
1370 gchar *field, *value;
1387 if (*value == '\0') continue;
1389 if (cc && !*cc && !g_strcasecmp(field, "cc")) {
1390 *cc = g_strdup(value);
1391 } else if (bcc && !*bcc && !g_strcasecmp(field, "bcc")) {
1392 *bcc = g_strdup(value);
1393 } else if (subject && !*subject &&
1394 !g_strcasecmp(field, "subject")) {
1395 *subject = g_malloc(strlen(value) + 1);
1396 decode_uri(*subject, value);
1397 } else if (body && !*body && !g_strcasecmp(field, "body")) {
1398 *body = g_malloc(strlen(value) + 1);
1399 decode_uri(*body, value);
1407 * We need this wrapper around g_get_home_dir(), so that
1408 * we can fix some Windoze things here. Should be done in glibc of course
1409 * but as long as we are not able to do our own extensions to glibc, we do
1412 gchar *get_home_dir(void)
1414 #if HAVE_DOSISH_SYSTEM
1415 static gchar *home_dir;
1418 home_dir = read_w32_registry_string(NULL,
1419 "Software\\Sylpheed", "HomeDir" );
1420 if (!home_dir || !*home_dir) {
1421 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1422 const char *s = g_get_home_dir();
1424 home_dir = g_strdup (s);
1426 if (!home_dir || !*home_dir)
1427 home_dir = g_strdup ("c:\\sylpheed");
1429 debug_print("initialized home_dir to `%s'\n", home_dir);
1432 #else /* standard glib */
1433 return g_get_home_dir();
1437 gchar *get_rc_dir(void)
1439 static gchar *rc_dir = NULL;
1442 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1448 gchar *get_news_cache_dir(void)
1450 static gchar *news_cache_dir = NULL;
1452 if (!news_cache_dir)
1453 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1454 NEWS_CACHE_DIR, NULL);
1456 return news_cache_dir;
1459 gchar *get_imap_cache_dir(void)
1461 static gchar *imap_cache_dir = NULL;
1463 if (!imap_cache_dir)
1464 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1465 IMAP_CACHE_DIR, NULL);
1467 return imap_cache_dir;
1470 gchar *get_mbox_cache_dir(void)
1472 static gchar *mbox_cache_dir = NULL;
1474 if (!mbox_cache_dir)
1475 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1476 MBOX_CACHE_DIR, NULL);
1478 return mbox_cache_dir;
1481 gchar *get_mime_tmp_dir(void)
1483 static gchar *mime_tmp_dir = NULL;
1486 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1487 MIME_TMP_DIR, NULL);
1489 return mime_tmp_dir;
1492 gchar *get_template_dir(void)
1494 static gchar *template_dir = NULL;
1497 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1498 TEMPLATE_DIR, NULL);
1500 return template_dir;
1503 gchar *get_header_cache_dir(void)
1505 static gchar *header_dir = NULL;
1508 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1509 HEADER_CACHE_DIR, NULL);
1514 gchar *get_tmp_dir(void)
1516 static gchar *tmp_dir = NULL;
1519 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1525 gchar *get_tmp_file(void)
1528 static guint32 id = 0;
1530 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1531 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1536 gchar *get_domain_name(void)
1538 static gchar *domain_name = NULL;
1541 gchar buf[128] = "";
1544 if (gethostname(buf, sizeof(buf)) < 0) {
1545 perror("gethostname");
1546 domain_name = "unknown";
1548 buf[sizeof(buf) - 1] = '\0';
1549 if ((hp = my_gethostbyname(buf)) == NULL) {
1550 perror("gethostbyname");
1551 domain_name = g_strdup(buf);
1553 domain_name = g_strdup(hp->h_name);
1557 debug_print("domain name = %s\n", domain_name);
1563 off_t get_file_size(const gchar *file)
1567 if (stat(file, &s) < 0) {
1568 FILE_OP_ERROR(file, "stat");
1575 off_t get_file_size_as_crlf(const gchar *file)
1579 gchar buf[BUFFSIZE];
1581 if ((fp = fopen(file, "rb")) == NULL) {
1582 FILE_OP_ERROR(file, "fopen");
1586 while (fgets(buf, sizeof(buf), fp) != NULL) {
1588 size += strlen(buf) + 2;
1592 FILE_OP_ERROR(file, "fgets");
1601 off_t get_left_file_size(FILE *fp)
1607 if ((pos = ftell(fp)) < 0) {
1611 if (fseek(fp, 0L, SEEK_END) < 0) {
1615 if ((end = ftell(fp)) < 0) {
1620 if (fseek(fp, pos, SEEK_SET) < 0) {
1628 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1635 if (stat(file, &s) < 0) {
1636 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1640 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1646 gboolean is_dir_exist(const gchar *dir)
1653 if (stat(dir, &s) < 0) {
1654 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1658 if (S_ISDIR(s.st_mode))
1664 gboolean is_file_entry_exist(const gchar *file)
1671 if (stat(file, &s) < 0) {
1672 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1679 gint change_dir(const gchar *dir)
1681 gchar *prevdir = NULL;
1684 prevdir = g_get_current_dir();
1686 if (chdir(dir) < 0) {
1687 FILE_OP_ERROR(dir, "chdir");
1688 if (debug_mode) g_free(prevdir);
1690 } else if (debug_mode) {
1693 cwd = g_get_current_dir();
1694 if (strcmp(prevdir, cwd) != 0)
1695 g_print("current dir: %s\n", cwd);
1703 gint make_dir(const gchar *dir)
1705 if (mkdir(dir, S_IRWXU) < 0) {
1706 FILE_OP_ERROR(dir, "mkdir");
1709 if (chmod(dir, S_IRWXU) < 0)
1710 FILE_OP_ERROR(dir, "chmod");
1715 gint make_dir_hier(const gchar *dir)
1720 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
1721 parent_dir = g_strndup(dir, p - dir);
1722 if (*parent_dir != '\0') {
1723 if (!is_dir_exist(parent_dir)) {
1724 if (make_dir(parent_dir) < 0) {
1733 if (!is_dir_exist(dir)) {
1734 if (make_dir(dir) < 0)
1741 gint remove_all_files(const gchar *dir)
1747 prev_dir = g_get_current_dir();
1749 if (chdir(dir) < 0) {
1750 FILE_OP_ERROR(dir, "chdir");
1755 if ((dp = opendir(".")) == NULL) {
1756 FILE_OP_ERROR(dir, "opendir");
1761 while ((d = readdir(dp)) != NULL) {
1762 if (!strcmp(d->d_name, ".") ||
1763 !strcmp(d->d_name, ".."))
1766 if (unlink(d->d_name) < 0)
1767 FILE_OP_ERROR(d->d_name, "unlink");
1772 if (chdir(prev_dir) < 0) {
1773 FILE_OP_ERROR(prev_dir, "chdir");
1783 gint remove_numbered_files(const gchar *dir, guint first, guint last)
1790 prev_dir = g_get_current_dir();
1792 if (chdir(dir) < 0) {
1793 FILE_OP_ERROR(dir, "chdir");
1798 if ((dp = opendir(".")) == NULL) {
1799 FILE_OP_ERROR(dir, "opendir");
1804 while ((d = readdir(dp)) != NULL) {
1805 fileno = to_number(d->d_name);
1806 if (fileno >= 0 && first <= fileno && fileno <= last) {
1807 if (is_dir_exist(d->d_name))
1809 if (unlink(d->d_name) < 0)
1810 FILE_OP_ERROR(d->d_name, "unlink");
1816 if (chdir(prev_dir) < 0) {
1817 FILE_OP_ERROR(prev_dir, "chdir");
1827 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
1834 prev_dir = g_get_current_dir();
1836 if (chdir(dir) < 0) {
1837 FILE_OP_ERROR(dir, "chdir");
1842 if ((dp = opendir(".")) == NULL) {
1843 FILE_OP_ERROR(dir, "opendir");
1848 while ((d = readdir(dp)) != NULL) {
1849 fileno = to_number(d->d_name);
1850 if (fileno >= 0 && (g_slist_find(numberlist, GINT_TO_POINTER(fileno)) == NULL)) {
1851 debug_print("removing unwanted file %d from %s\n", fileno, dir);
1852 if (is_dir_exist(d->d_name))
1854 if (unlink(d->d_name) < 0)
1855 FILE_OP_ERROR(d->d_name, "unlink");
1861 if (chdir(prev_dir) < 0) {
1862 FILE_OP_ERROR(prev_dir, "chdir");
1872 gint remove_all_numbered_files(const gchar *dir)
1874 return remove_numbered_files(dir, 0, UINT_MAX);
1877 gint remove_expired_files(const gchar *dir, guint hours)
1884 time_t mtime, now, expire_time;
1886 prev_dir = g_get_current_dir();
1888 if (chdir(dir) < 0) {
1889 FILE_OP_ERROR(dir, "chdir");
1894 if ((dp = opendir(".")) == NULL) {
1895 FILE_OP_ERROR(dir, "opendir");
1901 expire_time = hours * 60 * 60;
1903 while ((d = readdir(dp)) != NULL) {
1904 fileno = to_number(d->d_name);
1906 if (stat(d->d_name, &s) < 0) {
1907 FILE_OP_ERROR(d->d_name, "stat");
1910 if (S_ISDIR(s.st_mode))
1912 mtime = MAX(s.st_mtime, s.st_atime);
1913 if (now - mtime > expire_time) {
1914 if (unlink(d->d_name) < 0)
1915 FILE_OP_ERROR(d->d_name, "unlink");
1922 if (chdir(prev_dir) < 0) {
1923 FILE_OP_ERROR(prev_dir, "chdir");
1933 gint remove_dir_recursive(const gchar *dir)
1940 /* g_print("dir = %s\n", dir); */
1942 if (stat(dir, &s) < 0) {
1943 FILE_OP_ERROR(dir, "stat");
1944 if (ENOENT == errno) return 0;
1948 if (!S_ISDIR(s.st_mode)) {
1949 if (unlink(dir) < 0) {
1950 FILE_OP_ERROR(dir, "unlink");
1957 prev_dir = g_get_current_dir();
1958 /* g_print("prev_dir = %s\n", prev_dir); */
1960 if (!path_cmp(prev_dir, dir)) {
1962 if (chdir("..") < 0) {
1963 FILE_OP_ERROR(dir, "chdir");
1966 prev_dir = g_get_current_dir();
1969 if (chdir(dir) < 0) {
1970 FILE_OP_ERROR(dir, "chdir");
1975 if ((dp = opendir(".")) == NULL) {
1976 FILE_OP_ERROR(dir, "opendir");
1982 /* remove all files in the directory */
1983 while ((d = readdir(dp)) != NULL) {
1984 if (!strcmp(d->d_name, ".") ||
1985 !strcmp(d->d_name, ".."))
1988 if (stat(d->d_name, &s) < 0) {
1989 FILE_OP_ERROR(d->d_name, "stat");
1993 /* g_print("removing %s\n", d->d_name); */
1995 if (S_ISDIR(s.st_mode)) {
1996 if (remove_dir_recursive(d->d_name) < 0) {
1997 g_warning("can't remove directory\n");
2001 if (unlink(d->d_name) < 0)
2002 FILE_OP_ERROR(d->d_name, "unlink");
2008 if (chdir(prev_dir) < 0) {
2009 FILE_OP_ERROR(prev_dir, "chdir");
2016 if (rmdir(dir) < 0) {
2017 FILE_OP_ERROR(dir, "rmdir");
2025 /* this seems to be slower than the stdio version... */
2026 gint copy_file(const gchar *src, const gchar *dest)
2028 gint src_fd, dest_fd;
2032 gchar *dest_bak = NULL;
2034 if ((src_fd = open(src, O_RDONLY)) < 0) {
2035 FILE_OP_ERROR(src, "open");
2039 if (is_file_exist(dest)) {
2040 dest_bak = g_strconcat(dest, ".bak", NULL);
2041 if (rename(dest, dest_bak) < 0) {
2042 FILE_OP_ERROR(dest, "rename");
2049 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2050 FILE_OP_ERROR(dest, "open");
2053 if (rename(dest_bak, dest) < 0)
2054 FILE_OP_ERROR(dest_bak, "rename");
2060 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2065 n_write = write(dest_fd, bufp, len);
2067 g_warning("writing to %s failed.\n", dest);
2072 if (rename(dest_bak, dest) < 0)
2073 FILE_OP_ERROR(dest_bak, "rename");
2086 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2087 g_warning("File copy from %s to %s failed.\n", src, dest);
2090 if (rename(dest_bak, dest) < 0)
2091 FILE_OP_ERROR(dest_bak, "rename");
2104 * Append src file body to the tail of dest file.
2105 * Now keep_backup has no effects.
2107 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2109 FILE *src_fp, *dest_fp;
2113 gboolean err = FALSE;
2115 if ((src_fp = fopen(src, "rb")) == NULL) {
2116 FILE_OP_ERROR(src, "fopen");
2120 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2121 FILE_OP_ERROR(dest, "fopen");
2126 if (change_file_mode_rw(dest_fp, dest) < 0) {
2127 FILE_OP_ERROR(dest, "chmod");
2128 g_warning("can't change file mode\n");
2131 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2132 if (n_read < sizeof(buf) && ferror(src_fp))
2134 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2135 g_warning("writing to %s failed.\n", dest);
2143 if (ferror(src_fp)) {
2144 FILE_OP_ERROR(src, "fread");
2148 if (fclose(dest_fp) == EOF) {
2149 FILE_OP_ERROR(dest, "fclose");
2161 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2163 FILE *src_fp, *dest_fp;
2166 gchar *dest_bak = NULL;
2167 gboolean err = FALSE;
2169 if ((src_fp = fopen(src, "rb")) == NULL) {
2170 FILE_OP_ERROR(src, "fopen");
2173 if (is_file_exist(dest)) {
2174 dest_bak = g_strconcat(dest, ".bak", NULL);
2175 if (rename(dest, dest_bak) < 0) {
2176 FILE_OP_ERROR(dest, "rename");
2183 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2184 FILE_OP_ERROR(dest, "fopen");
2187 if (rename(dest_bak, dest) < 0)
2188 FILE_OP_ERROR(dest_bak, "rename");
2194 if (change_file_mode_rw(dest_fp, dest) < 0) {
2195 FILE_OP_ERROR(dest, "chmod");
2196 g_warning("can't change file mode\n");
2199 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2200 if (n_read < sizeof(buf) && ferror(src_fp))
2202 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2203 g_warning("writing to %s failed.\n", dest);
2208 if (rename(dest_bak, dest) < 0)
2209 FILE_OP_ERROR(dest_bak, "rename");
2216 if (ferror(src_fp)) {
2217 FILE_OP_ERROR(src, "fread");
2221 if (fclose(dest_fp) == EOF) {
2222 FILE_OP_ERROR(dest, "fclose");
2229 if (rename(dest_bak, dest) < 0)
2230 FILE_OP_ERROR(dest_bak, "rename");
2236 if (keep_backup == FALSE && dest_bak)
2244 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2246 if (overwrite == FALSE && is_file_exist(dest)) {
2247 g_warning("move_file(): file %s already exists.", dest);
2251 if (rename(src, dest) == 0) return 0;
2253 if (EXDEV != errno) {
2254 FILE_OP_ERROR(src, "rename");
2258 if (copy_file(src, dest, FALSE) < 0) return -1;
2265 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2269 gint bytes_left, to_read;
2271 gboolean err = FALSE;
2273 if (fseek(fp, offset, SEEK_SET) < 0) {
2278 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2279 FILE_OP_ERROR(dest, "fopen");
2283 if (change_file_mode_rw(dest_fp, dest) < 0) {
2284 FILE_OP_ERROR(dest, "chmod");
2285 g_warning("can't change file mode\n");
2288 bytes_left = length;
2289 to_read = MIN(bytes_left, sizeof(buf));
2291 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2292 if (n_read < to_read && ferror(fp))
2294 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2295 g_warning("writing to %s failed.\n", dest);
2300 bytes_left -= n_read;
2301 if (bytes_left == 0)
2303 to_read = MIN(bytes_left, sizeof(buf));
2310 if (fclose(dest_fp) == EOF) {
2311 FILE_OP_ERROR(dest, "fclose");
2323 /* convert line endings into CRLF. If the last line doesn't end with
2324 * linebreak, add it.
2326 gchar *canonicalize_str(const gchar *str)
2332 for (p = str; *p != '\0'; ++p) {
2339 if (p == str || *(p - 1) != '\n')
2342 out = outp = g_malloc(new_len + 1);
2343 for (p = str; *p != '\0'; ++p) {
2350 if (p == str || *(p - 1) != '\n') {
2359 gint canonicalize_file(const gchar *src, const gchar *dest)
2361 FILE *src_fp, *dest_fp;
2362 gchar buf[BUFFSIZE];
2364 gboolean err = FALSE;
2365 gboolean last_linebreak = FALSE;
2367 if ((src_fp = fopen(src, "rb")) == NULL) {
2368 FILE_OP_ERROR(src, "fopen");
2372 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2373 FILE_OP_ERROR(dest, "fopen");
2378 if (change_file_mode_rw(dest_fp, dest) < 0) {
2379 FILE_OP_ERROR(dest, "chmod");
2380 g_warning("can't change file mode\n");
2383 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2387 if (len == 0) break;
2388 last_linebreak = FALSE;
2390 if (buf[len - 1] != '\n') {
2391 last_linebreak = TRUE;
2392 r = fputs(buf, dest_fp);
2393 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2394 r = fputs(buf, dest_fp);
2397 r = fwrite(buf, len - 1, 1, dest_fp);
2402 r = fputs("\r\n", dest_fp);
2406 g_warning("writing to %s failed.\n", dest);
2414 if (last_linebreak == TRUE) {
2415 if (fputs("\r\n", dest_fp) == EOF)
2419 if (ferror(src_fp)) {
2420 FILE_OP_ERROR(src, "fgets");
2424 if (fclose(dest_fp) == EOF) {
2425 FILE_OP_ERROR(dest, "fclose");
2437 gint canonicalize_file_replace(const gchar *file)
2441 tmp_file = get_tmp_file();
2443 if (canonicalize_file(file, tmp_file) < 0) {
2448 if (move_file(tmp_file, file, TRUE) < 0) {
2449 g_warning("can't replace %s .\n", file);
2459 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2461 FILE *src_fp, *dest_fp;
2462 gchar buf[BUFFSIZE];
2463 gboolean err = FALSE;
2465 if ((src_fp = fopen(src, "rb")) == NULL) {
2466 FILE_OP_ERROR(src, "fopen");
2470 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2471 FILE_OP_ERROR(dest, "fopen");
2476 if (change_file_mode_rw(dest_fp, dest) < 0) {
2477 FILE_OP_ERROR(dest, "chmod");
2478 g_warning("can't change file mode\n");
2481 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2483 if (fputs(buf, dest_fp) == EOF) {
2484 g_warning("writing to %s failed.\n", dest);
2492 if (ferror(src_fp)) {
2493 FILE_OP_ERROR(src, "fgets");
2497 if (fclose(dest_fp) == EOF) {
2498 FILE_OP_ERROR(dest, "fclose");
2510 gint uncanonicalize_file_replace(const gchar *file)
2514 tmp_file = get_tmp_file();
2516 if (uncanonicalize_file(file, tmp_file) < 0) {
2521 if (move_file(tmp_file, file, TRUE) < 0) {
2522 g_warning("can't replace %s .\n", file);
2532 gint change_file_mode_rw(FILE *fp, const gchar *file)
2535 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2537 return chmod(file, S_IRUSR|S_IWUSR);
2541 FILE *my_tmpfile(void)
2544 const gchar suffix[] = ".XXXXXX";
2545 const gchar *tmpdir;
2547 const gchar *progname;
2553 tmpdir = get_tmp_dir();
2554 tmplen = strlen(tmpdir);
2555 progname = g_get_prgname();
2556 proglen = strlen(progname);
2557 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2560 memcpy(fname, tmpdir, tmplen);
2561 fname[tmplen] = G_DIR_SEPARATOR;
2562 memcpy(fname + tmplen + 1, progname, proglen);
2563 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2565 fd = mkstemp(fname);
2571 fp = fdopen(fd, "w+b");
2576 #endif /* HAVE_MKSTEMP */
2581 FILE *str_open_as_stream(const gchar *str)
2586 g_return_val_if_fail(str != NULL, NULL);
2590 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
2595 if (len == 0) return fp;
2597 if (fwrite(str, len, 1, fp) != 1) {
2598 FILE_OP_ERROR("str_open_as_stream", "fwrite");
2607 gint str_write_to_file(const gchar *str, const gchar *file)
2612 g_return_val_if_fail(str != NULL, -1);
2613 g_return_val_if_fail(file != NULL, -1);
2615 if ((fp = fopen(file, "wb")) == NULL) {
2616 FILE_OP_ERROR(file, "fopen");
2626 if (fwrite(str, len, 1, fp) != 1) {
2627 FILE_OP_ERROR(file, "fwrite");
2633 if (fclose(fp) == EOF) {
2634 FILE_OP_ERROR(file, "fclose");
2642 gchar *file_read_to_str(const gchar *file)
2650 g_return_val_if_fail(file != NULL, NULL);
2652 if ((fp = fopen(file, "rb")) == NULL) {
2653 FILE_OP_ERROR(file, "fopen");
2657 array = g_byte_array_new();
2659 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
2660 if (n_read < sizeof(buf) && ferror(fp))
2662 g_byte_array_append(array, buf, n_read);
2666 FILE_OP_ERROR(file, "fread");
2668 g_byte_array_free(array, TRUE);
2675 g_byte_array_append(array, buf, 1);
2676 str = (gchar *)array->data;
2677 g_byte_array_free(array, FALSE);
2682 gint execute_async(gchar *const argv[])
2686 if ((pid = fork()) < 0) {
2691 if (pid == 0) { /* child process */
2694 if ((gch_pid = fork()) < 0) {
2699 if (gch_pid == 0) { /* grandchild process */
2700 execvp(argv[0], argv);
2709 waitpid(pid, NULL, 0);
2714 gint execute_sync(gchar *const argv[])
2718 if ((pid = fork()) < 0) {
2723 if (pid == 0) { /* child process */
2724 execvp(argv[0], argv);
2730 waitpid(pid, NULL, 0);
2735 gint execute_command_line(const gchar *cmdline, gboolean async)
2740 argv = strsplit_with_quote(cmdline, " ", 0);
2743 ret = execute_async(argv);
2745 ret = execute_sync(argv);
2751 static gint is_unchanged_uri_char(char c)
2763 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
2769 for(i = 0; i < strlen(uri) ; i++) {
2770 if (is_unchanged_uri_char(uri[i])) {
2771 if (k + 2 >= bufsize)
2773 encoded_uri[k++] = uri[i];
2776 char * hexa = "0123456789ABCDEF";
2778 if (k + 4 >= bufsize)
2780 encoded_uri[k++] = '%';
2781 encoded_uri[k++] = hexa[uri[i] / 16];
2782 encoded_uri[k++] = hexa[uri[i] % 16];
2788 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
2791 static gint axtoi(const gchar *hexstr)
2793 gint hi, lo, result;
2796 if ('0' <= hi && hi <= '9') {
2799 if ('a' <= hi && hi <= 'f') {
2802 if ('A' <= hi && hi <= 'F') {
2807 if ('0' <= lo && lo <= '9') {
2810 if ('a' <= lo && lo <= 'f') {
2813 if ('A' <= lo && lo <= 'F') {
2816 result = lo + (16 * hi);
2821 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
2822 * plusses, and escape characters are used)
2825 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
2827 const gchar *encoded;
2830 encoded = encoded_uri;
2831 decoded = decoded_uri;
2834 if (*encoded == '%') {
2836 if (isxdigit(encoded[0])
2837 && isxdigit(encoded[1])) {
2838 *decoded = (gchar) axtoi(encoded);
2843 else if (*encoded == '+') {
2849 *decoded = *encoded;
2859 gint open_uri(const gchar *uri, const gchar *cmdline)
2861 gchar buf[BUFFSIZE];
2863 gchar encoded_uri[BUFFSIZE];
2865 g_return_val_if_fail(uri != NULL, -1);
2867 /* an option to choose whether to use encode_uri or not ? */
2868 encode_uri(encoded_uri, BUFFSIZE, uri);
2871 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
2872 !strchr(p + 2, '%'))
2873 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
2876 g_warning("Open URI command line is invalid: `%s'",
2878 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
2881 execute_command_line(buf, TRUE);
2886 time_t remote_tzoffset_sec(const gchar *zone)
2888 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
2894 time_t remoteoffset;
2896 strncpy(zone3, zone, 3);
2900 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
2901 (c == '+' || c == '-')) {
2902 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
2904 remoteoffset = -remoteoffset;
2905 } else if (!strncmp(zone, "UT" , 2) ||
2906 !strncmp(zone, "GMT", 2)) {
2908 } else if (strlen(zone3) == 3 &&
2909 (p = strstr(ustzstr, zone3)) != NULL &&
2910 (p - ustzstr) % 3 == 0) {
2911 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
2912 remoteoffset = iustz * 3600;
2913 } else if (strlen(zone3) == 1) {
2915 case 'Z': remoteoffset = 0; break;
2916 case 'A': remoteoffset = -1; break;
2917 case 'B': remoteoffset = -2; break;
2918 case 'C': remoteoffset = -3; break;
2919 case 'D': remoteoffset = -4; break;
2920 case 'E': remoteoffset = -5; break;
2921 case 'F': remoteoffset = -6; break;
2922 case 'G': remoteoffset = -7; break;
2923 case 'H': remoteoffset = -8; break;
2924 case 'I': remoteoffset = -9; break;
2925 case 'K': remoteoffset = -10; break; /* J is not used */
2926 case 'L': remoteoffset = -11; break;
2927 case 'M': remoteoffset = -12; break;
2928 case 'N': remoteoffset = 1; break;
2929 case 'O': remoteoffset = 2; break;
2930 case 'P': remoteoffset = 3; break;
2931 case 'Q': remoteoffset = 4; break;
2932 case 'R': remoteoffset = 5; break;
2933 case 'S': remoteoffset = 6; break;
2934 case 'T': remoteoffset = 7; break;
2935 case 'U': remoteoffset = 8; break;
2936 case 'V': remoteoffset = 9; break;
2937 case 'W': remoteoffset = 10; break;
2938 case 'X': remoteoffset = 11; break;
2939 case 'Y': remoteoffset = 12; break;
2940 default: remoteoffset = 0; break;
2942 remoteoffset = remoteoffset * 3600;
2945 return remoteoffset;
2948 time_t tzoffset_sec(time_t *now)
2954 lt = localtime(now);
2956 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2958 if (lt->tm_year < gmt.tm_year)
2960 else if (lt->tm_year > gmt.tm_year)
2962 else if (lt->tm_yday < gmt.tm_yday)
2964 else if (lt->tm_yday > gmt.tm_yday)
2967 if (off >= 24 * 60) /* should be impossible */
2968 off = 23 * 60 + 59; /* if not, insert silly value */
2969 if (off <= -24 * 60)
2970 off = -(23 * 60 + 59);
2975 /* calculate timezone offset */
2976 gchar *tzoffset(time_t *now)
2978 static gchar offset_string[6];
2984 lt = localtime(now);
2986 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
2988 if (lt->tm_year < gmt.tm_year)
2990 else if (lt->tm_year > gmt.tm_year)
2992 else if (lt->tm_yday < gmt.tm_yday)
2994 else if (lt->tm_yday > gmt.tm_yday)
3002 if (off >= 24 * 60) /* should be impossible */
3003 off = 23 * 60 + 59; /* if not, insert silly value */
3005 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3007 return offset_string;
3010 void get_rfc822_date(gchar *buf, gint len)
3014 gchar day[4], mon[4];
3015 gint dd, hh, mm, ss, yyyy;
3020 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3021 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3022 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3023 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3026 void debug_set_mode(gboolean mode)
3031 gboolean debug_get_mode()
3036 void debug_print_real(const gchar *format, ...)
3039 gchar buf[BUFFSIZE];
3041 if (!debug_mode) return;
3043 va_start(args, format);
3044 g_vsnprintf(buf, sizeof(buf), format, args);
3050 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3052 if (subject == NULL)
3055 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3056 return g_hash_table_lookup(subject_table, subject + 4);
3058 return g_hash_table_lookup(subject_table, subject);
3061 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3064 if (subject == NULL)
3068 if (g_strcasecmp(subject, "Re:") == 0)
3070 if (g_strcasecmp(subject, "Re: ") == 0)
3073 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3074 g_hash_table_insert(subject_table, subject + 4, data);
3076 g_hash_table_insert(subject_table, subject, data);
3079 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3081 if (subject == NULL)
3084 if (g_strncasecmp(subject, "Re: ", 4) == 0)
3085 g_hash_table_remove(subject_table, subject + 4);
3087 g_hash_table_remove(subject_table, subject);
3090 gboolean subject_is_reply(const gchar *subject)
3092 /* XXX: just simply here so someone can handle really
3093 * advanced Re: detection like "Re[4]", "ANTW:" or
3094 * Re: Re: Re: Re: Re: Re: Re: Re:" stuff. */
3095 if (subject == NULL) return FALSE;
3096 else return 0 == g_strncasecmp(subject, "Re: ", 4);
3099 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
3103 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
3104 fd = mkstemp(*filename);
3106 return fdopen(fd, "w+");
3109 /* allow Mutt-like patterns in quick search */
3110 gchar *expand_search_string(const gchar *search_string)
3113 gchar term_char, save_char;
3114 gchar *cmd_start, *cmd_end;
3115 GString *matcherstr;
3116 gchar *returnstr = NULL;
3118 gboolean casesens, dontmatch;
3119 /* list of allowed pattern abbreviations */
3121 gchar *abbreviated; /* abbreviation */
3122 gchar *command; /* actual matcher command */
3123 gint numparams; /* number of params for cmd */
3124 gboolean qualifier; /* do we append regexpcase */
3125 gboolean quotes; /* do we need quotes */
3128 { "a", "all", 0, FALSE, FALSE },
3129 { "ag", "age_greater", 1, FALSE, FALSE },
3130 { "al", "age_lower", 1, FALSE, FALSE },
3131 { "b", "body_part", 1, TRUE, TRUE },
3132 { "B", "message", 1, TRUE, TRUE },
3133 { "c", "cc", 1, TRUE, TRUE },
3134 { "C", "to_or_cc", 1, TRUE, TRUE },
3135 { "D", "deleted", 0, FALSE, FALSE },
3136 { "e", "header \"Sender\"", 1, TRUE, TRUE },
3137 { "E", "execute", 1, FALSE, TRUE },
3138 { "f", "from", 1, TRUE, TRUE },
3139 { "F", "forwarded", 0, FALSE, FALSE },
3140 { "h", "headers_part", 1, TRUE, TRUE },
3141 { "i", "header \"Message-Id\"", 1, TRUE, TRUE },
3142 { "I", "inreplyto", 1, TRUE, TRUE },
3143 { "L", "locked", 0, FALSE, FALSE },
3144 { "n", "newsgroups", 1, TRUE, TRUE },
3145 { "N", "new", 0, FALSE, FALSE },
3146 { "O", "~new", 0, FALSE, FALSE },
3147 { "r", "replied", 0, FALSE, FALSE },
3148 { "R", "~unread", 0, FALSE, FALSE },
3149 { "s", "subject", 1, TRUE, TRUE },
3150 { "se", "score_equal", 1, FALSE, FALSE },
3151 { "sg", "score_greater", 1, FALSE, FALSE },
3152 { "sl", "score_lower", 1, FALSE, FALSE },
3153 { "Se", "size_equal", 1, FALSE, FALSE },
3154 { "Sg", "size_greater", 1, FALSE, FALSE },
3155 { "Ss", "size_smaller", 1, FALSE, FALSE },
3156 { "t", "to", 1, TRUE, TRUE },
3157 { "T", "marked", 0, FALSE, FALSE },
3158 { "U", "unread", 0, FALSE, FALSE },
3159 { "x", "header \"References\"", 1, TRUE, TRUE },
3160 { "y", "header \"X-Label\"", 1, TRUE, TRUE },
3161 { "&", "&", 0, FALSE, FALSE },
3162 { "|", "|", 0, FALSE, FALSE },
3163 { NULL, NULL, 0, FALSE, FALSE }
3166 if (search_string == NULL)
3169 copy_str = g_strdup(search_string);
3171 /* if it's a full command don't process it so users
3172 can still do something like from regexpcase "foo" */
3173 for (i = 0; cmds[i].command; i++) {
3174 const gchar *tmp_search_string = search_string;
3175 cmd_start = cmds[i].command;
3176 /* allow logical NOT */
3177 if (*tmp_search_string == '~')
3178 tmp_search_string++;
3179 if (!strncmp(tmp_search_string, cmd_start, strlen(cmd_start)))
3182 if (cmds[i].command)
3185 matcherstr = g_string_sized_new(16);
3186 cmd_start = cmd_end = copy_str;
3187 while (cmd_end && *cmd_end) {
3188 /* skip all white spaces */
3189 while (*cmd_end && isspace(*cmd_end))
3192 /* extract a command */
3193 while (*cmd_end && !isspace(*cmd_end))
3196 /* save character */
3197 save_char = *cmd_end;
3203 /* ~ and ! mean logical NOT */
3204 if (*cmd_start == '~' || *cmd_start == '!')
3209 /* % means case sensitive match */
3210 if (*cmd_start == '%')
3216 /* find matching abbreviation */
3217 for (i = 0; cmds[i].command; i++) {
3218 if (!strcmp(cmd_start, cmds[i].abbreviated)) {
3219 /* restore character */
3220 *cmd_end = save_char;
3223 if (matcherstr->len > 0) {
3224 g_string_append(matcherstr, " ");
3227 g_string_append(matcherstr, "~");
3228 g_string_append(matcherstr, cmds[i].command);
3229 g_string_append(matcherstr, " ");
3231 /* stop if no params required */
3232 if (cmds[i].numparams == 0)
3235 /* extract a parameter, allow quotes */
3237 cmd_start = cmd_end;
3238 if (*cmd_start == '"') {
3245 /* extract actual parameter */
3246 while ((*cmd_end) && (*cmd_end != term_char))
3249 if (*cmd_end && (*cmd_end != term_char))
3252 if (*cmd_end == '"')
3255 save_char = *cmd_end;
3258 if (cmds[i].qualifier) {
3260 g_string_append(matcherstr, "regexp ");
3262 g_string_append(matcherstr, "regexpcase ");
3265 /* do we need to add quotes ? */
3266 if (cmds[i].quotes && term_char != '"')
3267 g_string_append(matcherstr, "\"");
3269 /* copy actual parameter */
3270 g_string_append(matcherstr, cmd_start);
3272 /* do we need to add quotes ? */
3273 if (cmds[i].quotes && term_char != '"')
3274 g_string_append(matcherstr, "\"");
3276 /* restore original character */
3277 *cmd_end = save_char;
3285 cmd_start = cmd_end;
3290 returnstr = matcherstr->str;
3291 g_string_free(matcherstr, FALSE);
3295 guint g_stricase_hash(gconstpointer gptr)
3297 guint hash_result = 0;
3300 for (str = gptr; str && *str; str++) {
3301 if (isupper(*str)) hash_result += (*str + ' ');
3302 else hash_result += *str;
3308 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3310 const char *str1 = gptr1;
3311 const char *str2 = gptr2;
3313 return !strcasecmp(str1, str2);