2 * Sylpheed -- a GTK+ based, lightweight, and fast e-mail client
3 * Copyright (C) 1999-2005 Hiroyuki Yamamoto & The Sylpheed-Claws Team
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 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.
27 #include <glib/gi18n.h>
33 #if (HAVE_WCTYPE_H && HAVE_WCHAR_H)
41 #include <sys/types.h>
46 #include <sys/utsname.h>
50 #include "../codeconv.h"
54 static gboolean debug_mode = FALSE;
56 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data);
58 void list_free_strings(GList *list)
60 list = g_list_first(list);
62 while (list != NULL) {
68 void slist_free_strings(GSList *list)
70 while (list != NULL) {
76 GSList *slist_concat_unique (GSList *first, GSList *second)
84 } else if (second == NULL)
87 for (tmp = second; tmp != NULL; tmp = g_slist_next(tmp)) {
88 if (g_slist_find(ret, tmp->data) == NULL)
89 ret = g_slist_prepend(ret, tmp->data);
94 static void hash_free_strings_func(gpointer key, gpointer value, gpointer data)
99 void hash_free_strings(GHashTable *table)
101 g_hash_table_foreach(table, hash_free_strings_func, NULL);
104 static void hash_free_value_mem_func(gpointer key, gpointer value,
110 void hash_free_value_mem(GHashTable *table)
112 g_hash_table_foreach(table, hash_free_value_mem_func, NULL);
115 gint str_case_equal(gconstpointer v, gconstpointer v2)
117 return g_ascii_strcasecmp((const gchar *)v, (const gchar *)v2) == 0;
120 guint str_case_hash(gconstpointer key)
122 const gchar *p = key;
127 for (p += 1; *p != '\0'; p++)
128 h = (h << 5) - h + tolower(*p);
134 void ptr_array_free_strings(GPtrArray *array)
139 g_return_if_fail(array != NULL);
141 for (i = 0; i < array->len; i++) {
142 str = g_ptr_array_index(array, i);
147 gboolean str_find(const gchar *haystack, const gchar *needle)
149 return strstr(haystack, needle) != NULL ? TRUE : FALSE;
152 gboolean str_case_find(const gchar *haystack, const gchar *needle)
154 return strcasestr(haystack, needle) != NULL ? TRUE : FALSE;
157 gboolean str_find_equal(const gchar *haystack, const gchar *needle)
159 return strcmp(haystack, needle) == 0;
162 gboolean str_case_find_equal(const gchar *haystack, const gchar *needle)
164 return strcasecmp(haystack, needle) == 0;
167 gint to_number(const gchar *nstr)
169 register const guchar *p;
171 if (*nstr == '\0') return -1;
173 for (p = nstr; *p != '\0'; p++)
174 if (!isdigit(*p)) return -1;
179 /* convert integer into string,
180 nstr must be not lower than 11 characters length */
181 gchar *itos_buf(gchar *nstr, gint n)
183 g_snprintf(nstr, 11, "%d", n);
187 /* convert integer into string */
190 static gchar nstr[11];
192 return itos_buf(nstr, n);
195 gchar *to_human_readable(off_t size)
197 static gchar str[10];
200 g_snprintf(str, sizeof(str), _("%dB"), (gint)size);
201 else if (size >> 10 < 1024)
202 g_snprintf(str, sizeof(str), _("%.1fKB"), (gfloat)size / (1 << 10));
203 else if (size >> 20 < 1024)
204 g_snprintf(str, sizeof(str), _("%.2fMB"), (gfloat)size / (1 << 20));
206 g_snprintf(str, sizeof(str), _("%.2fGB"), (gfloat)size / (1 << 30));
211 /* strcmp with NULL-checking */
212 gint strcmp2(const gchar *s1, const gchar *s2)
214 if (s1 == NULL || s2 == NULL)
217 return strcmp(s1, s2);
219 /* strstr with NULL-checking */
220 gchar *strstr2(const gchar *s1, const gchar *s2)
222 if (s1 == NULL || s2 == NULL)
225 return strstr(s1, s2);
228 gint path_cmp(const gchar *s1, const gchar *s2)
232 if (s1 == NULL || s2 == NULL) return -1;
233 if (*s1 == '\0' || *s2 == '\0') return -1;
238 if (s1[len1 - 1] == G_DIR_SEPARATOR) len1--;
239 if (s2[len2 - 1] == G_DIR_SEPARATOR) len2--;
241 return strncmp(s1, s2, MAX(len1, len2));
244 /* remove trailing return code */
245 gchar *strretchomp(gchar *str)
249 if (!*str) return str;
251 for (s = str + strlen(str) - 1;
252 s >= str && (*s == '\n' || *s == '\r');
259 /* remove trailing character */
260 gchar *strtailchomp(gchar *str, gchar tail_char)
264 if (!*str) return str;
265 if (tail_char == '\0') return str;
267 for (s = str + strlen(str) - 1; s >= str && *s == tail_char; s--)
273 /* remove CR (carriage return) */
274 gchar *strcrchomp(gchar *str)
278 if (!*str) return str;
280 s = str + strlen(str) - 1;
281 if (*s == '\n' && s > str && *(s - 1) == '\r') {
289 /* Similar to `strstr' but this function ignores the case of both strings. */
290 gchar *strcasestr(const gchar *haystack, const gchar *needle)
292 register size_t haystack_len, needle_len;
294 haystack_len = strlen(haystack);
295 needle_len = strlen(needle);
297 if (haystack_len < needle_len || needle_len == 0)
300 while (haystack_len >= needle_len) {
301 if (!g_ascii_strncasecmp(haystack, needle, needle_len))
302 return (gchar *)haystack;
312 gpointer my_memmem(gconstpointer haystack, size_t haystacklen,
313 gconstpointer needle, size_t needlelen)
315 const gchar *haystack_ = (const gchar *)haystack;
316 const gchar *needle_ = (const gchar *)needle;
317 const gchar *haystack_cur = (const gchar *)haystack;
320 return memchr(haystack_, *needle_, haystacklen);
322 while ((haystack_cur = memchr(haystack_cur, *needle_, haystacklen))
324 if (haystacklen - (haystack_cur - haystack_) < needlelen)
326 if (memcmp(haystack_cur + 1, needle_ + 1, needlelen - 1) == 0)
327 return (gpointer)haystack_cur;
335 /* Copy no more than N characters of SRC to DEST, with NULL terminating. */
336 gchar *strncpy2(gchar *dest, const gchar *src, size_t n)
338 register const gchar *s = src;
339 register gchar *d = dest;
349 int iswalnum(wint_t wc)
351 return isalnum((int)wc);
356 int iswspace(wint_t wc)
358 return isspace((int)wc);
363 wint_t towlower(wint_t wc)
365 if (wc >= L'A' && wc <= L'Z')
366 return wc + L'a' - L'A';
373 size_t wcslen(const wchar_t *s)
385 /* Copy SRC to DEST. */
386 wchar_t *wcscpy(wchar_t *dest, const wchar_t *src)
394 } while (c != L'\0');
401 /* Copy no more than N wide-characters of SRC to DEST. */
402 wchar_t *wcsncpy (wchar_t *dest, const wchar_t *src, size_t n)
412 } while (c != L'\0');
423 /* Duplicate S, returning an identical malloc'd string. */
424 wchar_t *wcsdup(const wchar_t *s)
429 new_str = g_new(wchar_t, wcslen(s) + 1);
437 /* Duplicate no more than N wide-characters of S,
438 returning an identical malloc'd string. */
439 wchar_t *wcsndup(const wchar_t *s, size_t n)
444 new_str = g_new(wchar_t, n + 1);
445 wcsncpy(new_str, s, n);
446 new_str[n] = (wchar_t)0;
453 wchar_t *strdup_mbstowcs(const gchar *s)
458 new_str = g_new(wchar_t, strlen(s) + 1);
459 if (mbstowcs(new_str, s, strlen(s) + 1) < 0) {
463 new_str = g_realloc(new_str,
464 sizeof(wchar_t) * (wcslen(new_str) + 1));
471 gchar *strdup_wcstombs(const wchar_t *s)
477 len = wcslen(s) * MB_CUR_MAX + 1;
478 new_str = g_new(gchar, len);
479 if (wcstombs(new_str, s, len) < 0) {
483 new_str = g_realloc(new_str, strlen(new_str) + 1);
490 /* Compare S1 and S2, ignoring case. */
491 gint wcsncasecmp(const wchar_t *s1, const wchar_t *s2, size_t n)
497 c1 = towlower(*s1++);
498 c2 = towlower(*s2++);
501 else if (c1 == 0 && c2 == 0)
508 /* Find the first occurrence of NEEDLE in HAYSTACK, ignoring case. */
509 wchar_t *wcscasestr(const wchar_t *haystack, const wchar_t *needle)
511 register size_t haystack_len, needle_len;
513 haystack_len = wcslen(haystack);
514 needle_len = wcslen(needle);
516 if (haystack_len < needle_len || needle_len == 0)
519 while (haystack_len >= needle_len) {
520 if (!wcsncasecmp(haystack, needle, needle_len))
521 return (wchar_t *)haystack;
531 gint get_mbs_len(const gchar *s)
541 mb_len = g_utf8_skip[*(guchar *)p];
553 /* Examine if next block is non-ASCII string */
554 gboolean is_next_nonascii(const guchar *s)
558 /* skip head space */
559 for (p = s; *p != '\0' && isspace(*p); p++)
561 for (; *p != '\0' && !isspace(*p); p++) {
562 if (*p > 127 || *p < 32)
569 gint get_next_word_len(const guchar *s)
573 for (; *s != '\0' && !isspace(*s); s++, len++)
579 /* compare subjects */
580 gint subject_compare(const gchar *s1, const gchar *s2)
584 if (!s1 || !s2) return -1;
585 if (!*s1 || !*s2) return -1;
587 Xstrdup_a(str1, s1, return -1);
588 Xstrdup_a(str2, s2, return -1);
590 trim_subject_for_compare(str1);
591 trim_subject_for_compare(str2);
593 if (!*str1 || !*str2) return -1;
595 return strcmp(str1, str2);
598 gint subject_compare_for_sort(const gchar *s1, const gchar *s2)
602 if (!s1 || !s2) return -1;
604 Xstrdup_a(str1, s1, return -1);
605 Xstrdup_a(str2, s2, return -1);
607 trim_subject_for_sort(str1);
608 trim_subject_for_sort(str2);
610 return g_utf8_collate(str1, str2);
613 void trim_subject_for_compare(gchar *str)
617 eliminate_parenthesis(str, '[', ']');
618 eliminate_parenthesis(str, '(', ')');
621 srcp = str + subject_get_prefix_length(str);
623 memmove(str, srcp, strlen(srcp) + 1);
626 void trim_subject_for_sort(gchar *str)
632 srcp = str + subject_get_prefix_length(str);
634 memmove(str, srcp, strlen(srcp) + 1);
637 void trim_subject(gchar *str)
639 register guchar *srcp;
645 srcp = str + subject_get_prefix_length(str);
650 } else if (*srcp == '(') {
662 else if (*srcp == cl)
669 while (isspace(*srcp)) srcp++;
670 memmove(str, srcp, strlen(srcp) + 1);
673 void eliminate_parenthesis(gchar *str, gchar op, gchar cl)
675 register guchar *srcp, *destp;
680 while ((destp = strchr(destp, op))) {
686 else if (*srcp == cl)
692 while (isspace(*srcp)) srcp++;
693 memmove(destp, srcp, strlen(srcp) + 1);
697 void extract_parenthesis(gchar *str, gchar op, gchar cl)
699 register gchar *srcp, *destp;
704 while ((srcp = strchr(destp, op))) {
707 memmove(destp, srcp + 1, strlen(srcp));
712 else if (*destp == cl)
724 void extract_parenthesis_with_skip_quote(gchar *str, gchar quote_chr,
727 register gchar *srcp, *destp;
729 gboolean in_quote = FALSE;
733 while ((srcp = strchr_with_skip_quote(destp, quote_chr, op))) {
736 memmove(destp, srcp + 1, strlen(srcp));
739 if (*destp == op && !in_quote)
741 else if (*destp == cl && !in_quote)
743 else if (*destp == quote_chr)
755 void eliminate_quote(gchar *str, gchar quote_chr)
757 register guchar *srcp, *destp;
761 while ((destp = strchr(destp, quote_chr))) {
762 if ((srcp = strchr(destp + 1, quote_chr))) {
764 while (isspace(*srcp)) srcp++;
765 memmove(destp, srcp, strlen(srcp) + 1);
773 void extract_quote(gchar *str, gchar quote_chr)
777 if ((str = strchr(str, quote_chr))) {
779 while ((p = strchr(p + 1, quote_chr)) && (p[-1] == '\\')) {
780 memmove(p - 1, p, strlen(p) + 1);
785 memmove(str, str + 1, p - str);
790 void eliminate_address_comment(gchar *str)
792 register guchar *srcp, *destp;
797 while ((destp = strchr(destp, '"'))) {
798 if ((srcp = strchr(destp + 1, '"'))) {
803 while (isspace(*srcp)) srcp++;
804 memmove(destp, srcp, strlen(srcp) + 1);
814 while ((destp = strchr_with_skip_quote(destp, '"', '('))) {
820 else if (*srcp == ')')
826 while (isspace(*srcp)) srcp++;
827 memmove(destp, srcp, strlen(srcp) + 1);
831 gchar *strchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
833 gboolean in_quote = FALSE;
836 if (*str == c && !in_quote)
838 if (*str == quote_chr)
846 gchar *strrchr_with_skip_quote(const gchar *str, gint quote_chr, gint c)
848 gboolean in_quote = FALSE;
851 p = str + strlen(str) - 1;
853 if (*p == c && !in_quote)
863 void extract_address(gchar *str)
865 eliminate_address_comment(str);
866 if (strchr_with_skip_quote(str, '"', '<'))
867 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
871 void extract_list_id_str(gchar *str)
873 if (strchr_with_skip_quote(str, '"', '<'))
874 extract_parenthesis_with_skip_quote(str, '"', '<', '>');
878 static GSList *address_list_append_real(GSList *addr_list, const gchar *str, gboolean removecomments)
883 if (!str) return addr_list;
885 Xstrdup_a(work, str, return addr_list);
888 eliminate_address_comment(work);
891 while (workp && *workp) {
894 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
900 if (removecomments && strchr_with_skip_quote(workp, '"', '<'))
901 extract_parenthesis_with_skip_quote
902 (workp, '"', '<', '>');
906 addr_list = g_slist_append(addr_list, g_strdup(workp));
914 GSList *address_list_append(GSList *addr_list, const gchar *str)
916 return address_list_append_real(addr_list, str, TRUE);
919 GSList *address_list_append_with_comments(GSList *addr_list, const gchar *str)
921 return address_list_append_real(addr_list, str, FALSE);
924 GSList *references_list_prepend(GSList *msgid_list, const gchar *str)
928 if (!str) return msgid_list;
931 while (strp && *strp) {
932 const gchar *start, *end;
935 if ((start = strchr(strp, '<')) != NULL) {
936 end = strchr(start + 1, '>');
941 msgid = g_strndup(start + 1, end - start - 1);
944 msgid_list = g_slist_prepend(msgid_list, msgid);
954 GSList *references_list_append(GSList *msgid_list, const gchar *str)
958 list = references_list_prepend(NULL, str);
959 list = g_slist_reverse(list);
960 msgid_list = g_slist_concat(msgid_list, list);
965 GSList *newsgroup_list_append(GSList *group_list, const gchar *str)
970 if (!str) return group_list;
972 Xstrdup_a(work, str, return group_list);
976 while (workp && *workp) {
979 if ((p = strchr_with_skip_quote(workp, '"', ','))) {
987 group_list = g_slist_append(group_list,
996 GList *add_history(GList *list, const gchar *str)
1000 g_return_val_if_fail(str != NULL, list);
1002 old = g_list_find_custom(list, (gpointer)str, (GCompareFunc)strcmp2);
1005 list = g_list_remove(list, old->data);
1006 } else if (g_list_length(list) >= MAX_HISTORY_SIZE) {
1009 last = g_list_last(list);
1012 g_list_remove(list, last->data);
1016 list = g_list_prepend(list, g_strdup(str));
1021 void remove_return(gchar *str)
1023 register gchar *p = str;
1026 if (*p == '\n' || *p == '\r')
1027 memmove(p, p + 1, strlen(p));
1033 void remove_space(gchar *str)
1035 register guchar *p = str;
1040 while (isspace(*(p + spc)))
1043 memmove(p, p + spc, strlen(p + spc) + 1);
1049 void unfold_line(gchar *str)
1051 register guchar *p = str;
1055 if (*p == '\n' || *p == '\r') {
1058 while (isspace(*(p + spc)))
1061 memmove(p, p + spc, strlen(p + spc) + 1);
1067 void subst_char(gchar *str, gchar orig, gchar subst)
1069 register gchar *p = str;
1078 void subst_chars(gchar *str, gchar *orig, gchar subst)
1080 register gchar *p = str;
1083 if (strchr(orig, *p) != NULL)
1089 void subst_for_filename(gchar *str)
1093 subst_chars(str, "\t\r\n\\/*", '_');
1096 void subst_for_shellsafe_filename(gchar *str)
1100 subst_for_filename(str);
1101 subst_chars(str, " \"'|&;()<>'!{}[]",'_');
1104 gboolean is_header_line(const gchar *str)
1106 if (str[0] == ':') return FALSE;
1108 while (*str != '\0' && *str != ' ') {
1117 gboolean is_ascii_str(const guchar *str)
1119 g_return_val_if_fail(str, FALSE);
1121 while (*str != '\0') {
1122 if (*str != '\t' && *str != ' ' &&
1123 *str != '\r' && *str != '\n' &&
1124 (*str < 32 || *str >= 127))
1132 gint get_quote_level(const gchar *str, const gchar *quote_chars)
1134 const guchar *first_pos;
1135 const guchar *last_pos;
1136 const guchar *p = str;
1137 gint quote_level = -1;
1139 /* speed up line processing by only searching to the last '>' */
1140 if ((first_pos = line_has_quote_char(str, quote_chars)) != NULL) {
1141 /* skip a line if it contains a '<' before the initial '>' */
1142 if (memchr(str, '<', first_pos - (const guchar *)str) != NULL)
1144 last_pos = line_has_quote_char_last(first_pos, quote_chars);
1148 while (p <= last_pos) {
1149 while (p < last_pos) {
1156 if (strchr(quote_chars, *p))
1158 else if (*p != '-' && !isspace(*p) && p <= last_pos) {
1159 /* any characters are allowed except '-' and space */
1161 && !strchr(quote_chars, *p)
1165 if (strchr(quote_chars, *p))
1177 const gchar * line_has_quote_char(const gchar * str, const gchar *quote_chars)
1179 gchar * position = NULL;
1180 gchar * tmp_pos = NULL;
1183 if (quote_chars == NULL)
1186 for (i = 0; i < strlen(quote_chars); i++) {
1187 tmp_pos = strchr (str, quote_chars[i]);
1189 || (tmp_pos != NULL && position >= tmp_pos) )
1195 const gchar * line_has_quote_char_last(const gchar * str, const gchar *quote_chars)
1197 gchar * position = NULL;
1198 gchar * tmp_pos = NULL;
1201 if (quote_chars == NULL)
1204 for (i = 0; i < strlen(quote_chars); i++) {
1205 tmp_pos = strrchr (str, quote_chars[i]);
1207 || (tmp_pos != NULL && position <= tmp_pos) )
1213 gchar *strstr_with_skip_quote(const gchar *haystack, const gchar *needle)
1215 register guint haystack_len, needle_len;
1216 gboolean in_squote = FALSE, in_dquote = FALSE;
1218 haystack_len = strlen(haystack);
1219 needle_len = strlen(needle);
1221 if (haystack_len < needle_len || needle_len == 0)
1224 while (haystack_len >= needle_len) {
1225 if (!in_squote && !in_dquote &&
1226 !strncmp(haystack, needle, needle_len))
1227 return (gchar *)haystack;
1229 /* 'foo"bar"' -> foo"bar"
1230 "foo'bar'" -> foo'bar' */
1231 if (*haystack == '\'') {
1234 else if (!in_dquote)
1236 } else if (*haystack == '\"') {
1239 else if (!in_squote)
1250 gchar *strchr_parenthesis_close(const gchar *str, gchar op, gchar cl)
1253 gchar quote_chr = '"';
1255 gboolean in_quote = FALSE;
1259 if ((p = strchr_with_skip_quote(p, quote_chr, op))) {
1263 if (*p == op && !in_quote)
1265 else if (*p == cl && !in_quote)
1267 else if (*p == quote_chr)
1280 gchar **strsplit_parenthesis(const gchar *str, gchar op, gchar cl,
1283 GSList *string_list = NULL, *slist;
1285 const gchar *s_op, *s_cl;
1288 g_return_val_if_fail(str != NULL, NULL);
1291 max_tokens = G_MAXINT;
1293 s_op = strchr_with_skip_quote(str, '"', op);
1294 if (!s_op) return NULL;
1296 s_cl = strchr_parenthesis_close(str, op, cl);
1304 new_string = g_new(gchar, len + 1);
1305 strncpy(new_string, str, len);
1306 new_string[len] = 0;
1307 string_list = g_slist_prepend(string_list, new_string);
1311 while (*str && isspace(*(guchar *)str)) str++;
1313 string_list = g_slist_prepend(string_list,
1316 s_op = strchr_with_skip_quote(str, '"', op);
1317 if (!--max_tokens || !s_op) break;
1321 s_cl = strchr_parenthesis_close(str, op, cl);
1322 } while (--max_tokens && s_cl);
1325 str_array = g_new(gchar*, n);
1329 str_array[i--] = NULL;
1330 for (slist = string_list; slist; slist = slist->next)
1331 str_array[i--] = slist->data;
1333 g_slist_free(string_list);
1338 gchar **strsplit_with_quote(const gchar *str, const gchar *delim,
1341 GSList *string_list = NULL, *slist;
1342 gchar **str_array, *s, *new_str;
1343 guint i, n = 1, len;
1345 g_return_val_if_fail(str != NULL, NULL);
1346 g_return_val_if_fail(delim != NULL, NULL);
1349 max_tokens = G_MAXINT;
1351 s = strstr_with_skip_quote(str, delim);
1353 guint delimiter_len = strlen(delim);
1357 new_str = g_strndup(str, len);
1359 if (new_str[0] == '\'' || new_str[0] == '\"') {
1360 if (new_str[len - 1] == new_str[0]) {
1361 new_str[len - 1] = '\0';
1362 memmove(new_str, new_str + 1, len - 1);
1365 string_list = g_slist_prepend(string_list, new_str);
1367 str = s + delimiter_len;
1368 s = strstr_with_skip_quote(str, delim);
1369 } while (--max_tokens && s);
1373 new_str = g_strdup(str);
1374 if (new_str[0] == '\'' || new_str[0] == '\"') {
1376 if (new_str[len - 1] == new_str[0]) {
1377 new_str[len - 1] = '\0';
1378 memmove(new_str, new_str + 1, len - 1);
1381 string_list = g_slist_prepend(string_list, new_str);
1385 str_array = g_new(gchar*, n);
1389 str_array[i--] = NULL;
1390 for (slist = string_list; slist; slist = slist->next)
1391 str_array[i--] = slist->data;
1393 g_slist_free(string_list);
1398 gchar *get_abbrev_newsgroup_name(const gchar *group, gint len)
1400 gchar *abbrev_group;
1402 const gchar *p = group;
1405 g_return_val_if_fail(group != NULL, NULL);
1407 last = group + strlen(group);
1408 abbrev_group = ap = g_malloc(strlen(group) + 1);
1413 if ((ap - abbrev_group) + (last - p) > len && strchr(p, '.')) {
1415 while (*p != '.') p++;
1418 return abbrev_group;
1423 return abbrev_group;
1426 gchar *trim_string(const gchar *str, gint len)
1428 const gchar *p = str;
1433 if (!str) return NULL;
1434 if (strlen(str) <= len)
1435 return g_strdup(str);
1436 if (g_utf8_validate(str, -1, NULL) == FALSE)
1437 return g_strdup(str);
1439 while (*p != '\0') {
1440 mb_len = g_utf8_skip[*(guchar *)p];
1443 else if (new_len + mb_len > len)
1450 Xstrndup_a(new_str, str, new_len, return g_strdup(str));
1451 return g_strconcat(new_str, "...", NULL);
1454 GList *uri_list_extract_filenames(const gchar *uri_list)
1456 GList *result = NULL;
1458 gchar *escaped_utf8uri;
1465 while (isspace(*p)) p++;
1466 if (!strncmp(p, "file:", 5)) {
1469 while (*q && *q != '\n' && *q != '\r') q++;
1472 gchar *file, *locale_file = NULL;
1474 while (q > p && isspace(*q)) q--;
1475 Xalloca(escaped_utf8uri, q - p + 2,
1477 Xalloca(file, q - p + 2,
1480 strncpy(escaped_utf8uri, p, q - p + 1);
1481 escaped_utf8uri[q - p + 1] = '\0';
1482 decode_uri(file, escaped_utf8uri);
1483 #warning FIXME_GTK2 /* should we use g_filename_from_utf8()? */
1485 * g_filename_from_uri() rejects escaped/locale encoded uri
1486 * string which come from Nautilus.
1488 if (g_utf8_validate(file, -1, NULL))
1490 = conv_codeset_strdup(
1493 conv_get_locale_charset_str());
1495 locale_file = g_strdup(file + 5);
1496 result = g_list_append(result, locale_file);
1500 p = strchr(p, '\n');
1507 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1510 static gint axtoi(const gchar *hexstr)
1512 gint hi, lo, result;
1515 if ('0' <= hi && hi <= '9') {
1518 if ('a' <= hi && hi <= 'f') {
1521 if ('A' <= hi && hi <= 'F') {
1526 if ('0' <= lo && lo <= '9') {
1529 if ('a' <= lo && lo <= 'f') {
1532 if ('A' <= lo && lo <= 'F') {
1535 result = lo + (16 * hi);
1539 gboolean is_uri_string(const gchar *str)
1541 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1542 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1543 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1544 g_ascii_strncasecmp(str, "www.", 4) == 0);
1547 gchar *get_uri_path(const gchar *uri)
1549 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1550 return (gchar *)(uri + 7);
1551 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1552 return (gchar *)(uri + 8);
1553 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1554 return (gchar *)(uri + 6);
1556 return (gchar *)uri;
1559 gint get_uri_len(const gchar *str)
1563 if (is_uri_string(str)) {
1564 for (p = str; *p != '\0'; p++) {
1565 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1574 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1575 * plusses, and escape characters are used)
1577 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1579 gchar *dec = decoded_uri;
1580 const gchar *enc = encoded_uri;
1585 if (isxdigit((guchar)enc[0]) &&
1586 isxdigit((guchar)enc[1])) {
1604 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1605 gchar **subject, gchar **body)
1610 Xstrdup_a(tmp_mailto, mailto, return -1);
1612 if (!strncmp(tmp_mailto, "mailto:", 7))
1615 p = strchr(tmp_mailto, '?');
1622 *to = g_strdup(tmp_mailto);
1625 gchar *field, *value;
1642 if (*value == '\0') continue;
1644 if (cc && !*cc && !g_ascii_strcasecmp(field, "cc")) {
1645 *cc = g_strdup(value);
1646 } else if (bcc && !*bcc && !g_ascii_strcasecmp(field, "bcc")) {
1647 *bcc = g_strdup(value);
1648 } else if (subject && !*subject &&
1649 !g_ascii_strcasecmp(field, "subject")) {
1650 *subject = g_malloc(strlen(value) + 1);
1651 decode_uri(*subject, value);
1652 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1653 *body = g_malloc(strlen(value) + 1);
1654 decode_uri(*body, value);
1662 * We need this wrapper around g_get_home_dir(), so that
1663 * we can fix some Windoze things here. Should be done in glibc of course
1664 * but as long as we are not able to do our own extensions to glibc, we do
1667 const gchar *get_home_dir(void)
1669 #if HAVE_DOSISH_SYSTEM
1670 static gchar *home_dir;
1673 home_dir = read_w32_registry_string(NULL,
1674 "Software\\Sylpheed", "HomeDir" );
1675 if (!home_dir || !*home_dir) {
1676 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1677 const char *s = g_get_home_dir();
1679 home_dir = g_strdup (s);
1681 if (!home_dir || !*home_dir)
1682 home_dir = g_strdup ("c:\\sylpheed");
1684 debug_print("initialized home_dir to `%s'\n", home_dir);
1687 #else /* standard glib */
1688 return g_get_home_dir();
1692 const gchar *get_rc_dir(void)
1694 static gchar *rc_dir = NULL;
1697 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1703 const gchar *get_news_cache_dir(void)
1705 static gchar *news_cache_dir = NULL;
1707 if (!news_cache_dir)
1708 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1709 NEWS_CACHE_DIR, NULL);
1711 return news_cache_dir;
1714 const gchar *get_imap_cache_dir(void)
1716 static gchar *imap_cache_dir = NULL;
1718 if (!imap_cache_dir)
1719 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1720 IMAP_CACHE_DIR, NULL);
1722 return imap_cache_dir;
1725 const gchar *get_mbox_cache_dir(void)
1727 static gchar *mbox_cache_dir = NULL;
1729 if (!mbox_cache_dir)
1730 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1731 MBOX_CACHE_DIR, NULL);
1733 return mbox_cache_dir;
1736 const gchar *get_mime_tmp_dir(void)
1738 static gchar *mime_tmp_dir = NULL;
1741 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1742 MIME_TMP_DIR, NULL);
1744 return mime_tmp_dir;
1747 const gchar *get_template_dir(void)
1749 static gchar *template_dir = NULL;
1752 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1753 TEMPLATE_DIR, NULL);
1755 return template_dir;
1758 const gchar *get_header_cache_dir(void)
1760 static gchar *header_dir = NULL;
1763 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1764 HEADER_CACHE_DIR, NULL);
1769 const gchar *get_tmp_dir(void)
1771 static gchar *tmp_dir = NULL;
1774 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1780 gchar *get_tmp_file(void)
1783 static guint32 id = 0;
1785 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1786 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1791 const gchar *get_domain_name(void)
1793 static gchar *domain_name = NULL;
1799 if (uname(&uts) < 0) {
1800 perror("gethostname");
1801 domain_name = "unknown";
1803 if ((hp = my_gethostbyname(uts.nodename)) == NULL) {
1804 perror("gethostbyname");
1805 domain_name = g_strdup(uts.nodename);
1807 domain_name = g_strdup(hp->h_name);
1811 debug_print("domain name = %s\n", domain_name);
1817 off_t get_file_size(const gchar *file)
1821 if (stat(file, &s) < 0) {
1822 FILE_OP_ERROR(file, "stat");
1829 off_t get_file_size_as_crlf(const gchar *file)
1833 gchar buf[BUFFSIZE];
1835 if ((fp = fopen(file, "rb")) == NULL) {
1836 FILE_OP_ERROR(file, "fopen");
1840 while (fgets(buf, sizeof(buf), fp) != NULL) {
1842 size += strlen(buf) + 2;
1846 FILE_OP_ERROR(file, "fgets");
1855 off_t get_left_file_size(FILE *fp)
1861 if ((pos = ftell(fp)) < 0) {
1865 if (fseek(fp, 0L, SEEK_END) < 0) {
1869 if ((end = ftell(fp)) < 0) {
1874 if (fseek(fp, pos, SEEK_SET) < 0) {
1882 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1889 if (stat(file, &s) < 0) {
1890 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1894 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1900 gboolean is_dir_exist(const gchar *dir)
1907 if (stat(dir, &s) < 0) {
1908 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1912 if (S_ISDIR(s.st_mode))
1918 gboolean is_file_entry_exist(const gchar *file)
1925 if (stat(file, &s) < 0) {
1926 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1933 gboolean dirent_is_regular_file(struct dirent *d)
1937 #ifdef HAVE_DIRENT_D_TYPE
1938 if (d->d_type == DT_REG)
1940 else if (d->d_type != DT_UNKNOWN)
1944 return (stat(d->d_name, &s) == 0 && S_ISREG(s.st_mode));
1947 gboolean dirent_is_directory(struct dirent *d)
1951 #ifdef HAVE_DIRENT_D_TYPE
1952 if (d->d_type == DT_DIR)
1954 else if (d->d_type != DT_UNKNOWN)
1958 return (stat(d->d_name, &s) == 0 && S_ISDIR(s.st_mode));
1961 gint change_dir(const gchar *dir)
1963 gchar *prevdir = NULL;
1966 prevdir = g_get_current_dir();
1968 if (chdir(dir) < 0) {
1969 FILE_OP_ERROR(dir, "chdir");
1970 if (debug_mode) g_free(prevdir);
1972 } else if (debug_mode) {
1975 cwd = g_get_current_dir();
1976 if (strcmp(prevdir, cwd) != 0)
1977 g_print("current dir: %s\n", cwd);
1985 gint make_dir(const gchar *dir)
1987 if (mkdir(dir, S_IRWXU) < 0) {
1988 FILE_OP_ERROR(dir, "mkdir");
1991 if (chmod(dir, S_IRWXU) < 0)
1992 FILE_OP_ERROR(dir, "chmod");
1997 gint make_dir_hier(const gchar *dir)
2002 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2003 parent_dir = g_strndup(dir, p - dir);
2004 if (*parent_dir != '\0') {
2005 if (!is_dir_exist(parent_dir)) {
2006 if (make_dir(parent_dir) < 0) {
2015 if (!is_dir_exist(dir)) {
2016 if (make_dir(dir) < 0)
2023 gint remove_all_files(const gchar *dir)
2029 prev_dir = g_get_current_dir();
2031 if (chdir(dir) < 0) {
2032 FILE_OP_ERROR(dir, "chdir");
2037 if ((dp = opendir(".")) == NULL) {
2038 FILE_OP_ERROR(dir, "opendir");
2043 while ((d = readdir(dp)) != NULL) {
2044 if (!strcmp(d->d_name, ".") ||
2045 !strcmp(d->d_name, ".."))
2048 if (unlink(d->d_name) < 0)
2049 FILE_OP_ERROR(d->d_name, "unlink");
2054 if (chdir(prev_dir) < 0) {
2055 FILE_OP_ERROR(prev_dir, "chdir");
2065 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2072 prev_dir = g_get_current_dir();
2074 if (chdir(dir) < 0) {
2075 FILE_OP_ERROR(dir, "chdir");
2080 if ((dp = opendir(".")) == NULL) {
2081 FILE_OP_ERROR(dir, "opendir");
2086 while ((d = readdir(dp)) != NULL) {
2087 file_no = to_number(d->d_name);
2088 if (file_no > 0 && first <= file_no && file_no <= last) {
2089 if (is_dir_exist(d->d_name))
2091 if (unlink(d->d_name) < 0)
2092 FILE_OP_ERROR(d->d_name, "unlink");
2098 if (chdir(prev_dir) < 0) {
2099 FILE_OP_ERROR(prev_dir, "chdir");
2109 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2116 prev_dir = g_get_current_dir();
2118 if (chdir(dir) < 0) {
2119 FILE_OP_ERROR(dir, "chdir");
2124 if ((dp = opendir(".")) == NULL) {
2125 FILE_OP_ERROR(dir, "opendir");
2130 while ((d = readdir(dp)) != NULL) {
2131 file_no = to_number(d->d_name);
2132 if (file_no > 0 && (g_slist_find(numberlist, GINT_TO_POINTER(file_no)) == NULL)) {
2133 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2134 if (is_dir_exist(d->d_name))
2136 if (unlink(d->d_name) < 0)
2137 FILE_OP_ERROR(d->d_name, "unlink");
2143 if (chdir(prev_dir) < 0) {
2144 FILE_OP_ERROR(prev_dir, "chdir");
2154 gint remove_all_numbered_files(const gchar *dir)
2156 return remove_numbered_files(dir, 0, UINT_MAX);
2159 gint remove_expired_files(const gchar *dir, guint hours)
2166 time_t mtime, now, expire_time;
2168 prev_dir = g_get_current_dir();
2170 if (chdir(dir) < 0) {
2171 FILE_OP_ERROR(dir, "chdir");
2176 if ((dp = opendir(".")) == NULL) {
2177 FILE_OP_ERROR(dir, "opendir");
2183 expire_time = hours * 60 * 60;
2185 while ((d = readdir(dp)) != NULL) {
2186 file_no = to_number(d->d_name);
2188 if (stat(d->d_name, &s) < 0) {
2189 FILE_OP_ERROR(d->d_name, "stat");
2192 if (S_ISDIR(s.st_mode))
2194 mtime = MAX(s.st_mtime, s.st_atime);
2195 if (now - mtime > expire_time) {
2196 if (unlink(d->d_name) < 0)
2197 FILE_OP_ERROR(d->d_name, "unlink");
2204 if (chdir(prev_dir) < 0) {
2205 FILE_OP_ERROR(prev_dir, "chdir");
2215 gint remove_dir_recursive(const gchar *dir)
2222 /* g_print("dir = %s\n", dir); */
2224 if (stat(dir, &s) < 0) {
2225 FILE_OP_ERROR(dir, "stat");
2226 if (ENOENT == errno) return 0;
2230 if (!S_ISDIR(s.st_mode)) {
2231 if (unlink(dir) < 0) {
2232 FILE_OP_ERROR(dir, "unlink");
2239 prev_dir = g_get_current_dir();
2240 /* g_print("prev_dir = %s\n", prev_dir); */
2242 if (!path_cmp(prev_dir, dir)) {
2244 if (chdir("..") < 0) {
2245 FILE_OP_ERROR(dir, "chdir");
2248 prev_dir = g_get_current_dir();
2251 if (chdir(dir) < 0) {
2252 FILE_OP_ERROR(dir, "chdir");
2257 if ((dp = opendir(".")) == NULL) {
2258 FILE_OP_ERROR(dir, "opendir");
2264 /* remove all files in the directory */
2265 while ((d = readdir(dp)) != NULL) {
2266 if (!strcmp(d->d_name, ".") ||
2267 !strcmp(d->d_name, ".."))
2270 /* g_print("removing %s\n", d->d_name); */
2272 if (dirent_is_directory(d)) {
2273 if (remove_dir_recursive(d->d_name) < 0) {
2274 g_warning("can't remove directory\n");
2278 if (unlink(d->d_name) < 0)
2279 FILE_OP_ERROR(d->d_name, "unlink");
2285 if (chdir(prev_dir) < 0) {
2286 FILE_OP_ERROR(prev_dir, "chdir");
2293 if (rmdir(dir) < 0) {
2294 FILE_OP_ERROR(dir, "rmdir");
2302 /* this seems to be slower than the stdio version... */
2303 gint copy_file(const gchar *src, const gchar *dest)
2305 gint src_fd, dest_fd;
2309 gchar *dest_bak = NULL;
2311 if ((src_fd = open(src, O_RDONLY)) < 0) {
2312 FILE_OP_ERROR(src, "open");
2316 if (is_file_exist(dest)) {
2317 dest_bak = g_strconcat(dest, ".bak", NULL);
2318 if (rename(dest, dest_bak) < 0) {
2319 FILE_OP_ERROR(dest, "rename");
2326 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2327 FILE_OP_ERROR(dest, "open");
2330 if (rename(dest_bak, dest) < 0)
2331 FILE_OP_ERROR(dest_bak, "rename");
2337 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2342 n_write = write(dest_fd, bufp, len);
2344 g_warning("writing to %s failed.\n", dest);
2349 if (rename(dest_bak, dest) < 0)
2350 FILE_OP_ERROR(dest_bak, "rename");
2363 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2364 g_warning("File copy from %s to %s failed.\n", src, dest);
2367 if (rename(dest_bak, dest) < 0)
2368 FILE_OP_ERROR(dest_bak, "rename");
2381 * Append src file body to the tail of dest file.
2382 * Now keep_backup has no effects.
2384 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2386 FILE *src_fp, *dest_fp;
2390 gboolean err = FALSE;
2392 if ((src_fp = fopen(src, "rb")) == NULL) {
2393 FILE_OP_ERROR(src, "fopen");
2397 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2398 FILE_OP_ERROR(dest, "fopen");
2403 if (change_file_mode_rw(dest_fp, dest) < 0) {
2404 FILE_OP_ERROR(dest, "chmod");
2405 g_warning("can't change file mode\n");
2408 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2409 if (n_read < sizeof(buf) && ferror(src_fp))
2411 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2412 g_warning("writing to %s failed.\n", dest);
2420 if (ferror(src_fp)) {
2421 FILE_OP_ERROR(src, "fread");
2425 if (fclose(dest_fp) == EOF) {
2426 FILE_OP_ERROR(dest, "fclose");
2438 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2440 FILE *src_fp, *dest_fp;
2443 gchar *dest_bak = NULL;
2444 gboolean err = FALSE;
2446 if ((src_fp = fopen(src, "rb")) == NULL) {
2447 FILE_OP_ERROR(src, "fopen");
2450 if (is_file_exist(dest)) {
2451 dest_bak = g_strconcat(dest, ".bak", NULL);
2452 if (rename(dest, dest_bak) < 0) {
2453 FILE_OP_ERROR(dest, "rename");
2460 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2461 FILE_OP_ERROR(dest, "fopen");
2464 if (rename(dest_bak, dest) < 0)
2465 FILE_OP_ERROR(dest_bak, "rename");
2471 if (change_file_mode_rw(dest_fp, dest) < 0) {
2472 FILE_OP_ERROR(dest, "chmod");
2473 g_warning("can't change file mode\n");
2476 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2477 if (n_read < sizeof(buf) && ferror(src_fp))
2479 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2480 g_warning("writing to %s failed.\n", dest);
2485 if (rename(dest_bak, dest) < 0)
2486 FILE_OP_ERROR(dest_bak, "rename");
2493 if (ferror(src_fp)) {
2494 FILE_OP_ERROR(src, "fread");
2498 if (fclose(dest_fp) == EOF) {
2499 FILE_OP_ERROR(dest, "fclose");
2506 if (rename(dest_bak, dest) < 0)
2507 FILE_OP_ERROR(dest_bak, "rename");
2513 if (keep_backup == FALSE && dest_bak)
2521 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2523 if (overwrite == FALSE && is_file_exist(dest)) {
2524 g_warning("move_file(): file %s already exists.", dest);
2528 if (rename(src, dest) == 0) return 0;
2530 if (EXDEV != errno) {
2531 FILE_OP_ERROR(src, "rename");
2535 if (copy_file(src, dest, FALSE) < 0) return -1;
2542 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2545 gint bytes_left, to_read;
2548 if (fseek(fp, offset, SEEK_SET) < 0) {
2553 bytes_left = length;
2554 to_read = MIN(bytes_left, sizeof(buf));
2556 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2557 if (n_read < to_read && ferror(fp))
2559 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2562 bytes_left -= n_read;
2563 if (bytes_left == 0)
2565 to_read = MIN(bytes_left, sizeof(buf));
2576 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2579 gboolean err = FALSE;
2581 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2582 FILE_OP_ERROR(dest, "fopen");
2586 if (change_file_mode_rw(dest_fp, dest) < 0) {
2587 FILE_OP_ERROR(dest, "chmod");
2588 g_warning("can't change file mode\n");
2591 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2594 if (!err && fclose(dest_fp) == EOF) {
2595 FILE_OP_ERROR(dest, "fclose");
2600 g_warning("writing to %s failed.\n", dest);
2608 /* convert line endings into CRLF. If the last line doesn't end with
2609 * linebreak, add it.
2611 gchar *canonicalize_str(const gchar *str)
2617 for (p = str; *p != '\0'; ++p) {
2624 if (p == str || *(p - 1) != '\n')
2627 out = outp = g_malloc(new_len + 1);
2628 for (p = str; *p != '\0'; ++p) {
2635 if (p == str || *(p - 1) != '\n') {
2644 gint canonicalize_file(const gchar *src, const gchar *dest)
2646 FILE *src_fp, *dest_fp;
2647 gchar buf[BUFFSIZE];
2649 gboolean err = FALSE;
2650 gboolean last_linebreak = FALSE;
2652 if ((src_fp = fopen(src, "rb")) == NULL) {
2653 FILE_OP_ERROR(src, "fopen");
2657 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2658 FILE_OP_ERROR(dest, "fopen");
2663 if (change_file_mode_rw(dest_fp, dest) < 0) {
2664 FILE_OP_ERROR(dest, "chmod");
2665 g_warning("can't change file mode\n");
2668 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2672 if (len == 0) break;
2673 last_linebreak = FALSE;
2675 if (buf[len - 1] != '\n') {
2676 last_linebreak = TRUE;
2677 r = fputs(buf, dest_fp);
2678 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2679 r = fputs(buf, dest_fp);
2682 r = fwrite(buf, len - 1, 1, dest_fp);
2687 r = fputs("\r\n", dest_fp);
2691 g_warning("writing to %s failed.\n", dest);
2699 if (last_linebreak == TRUE) {
2700 if (fputs("\r\n", dest_fp) == EOF)
2704 if (ferror(src_fp)) {
2705 FILE_OP_ERROR(src, "fgets");
2709 if (fclose(dest_fp) == EOF) {
2710 FILE_OP_ERROR(dest, "fclose");
2722 gint canonicalize_file_replace(const gchar *file)
2726 tmp_file = get_tmp_file();
2728 if (canonicalize_file(file, tmp_file) < 0) {
2733 if (move_file(tmp_file, file, TRUE) < 0) {
2734 g_warning("can't replace %s .\n", file);
2744 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2746 FILE *src_fp, *dest_fp;
2747 gchar buf[BUFFSIZE];
2748 gboolean err = FALSE;
2750 if ((src_fp = fopen(src, "rb")) == NULL) {
2751 FILE_OP_ERROR(src, "fopen");
2755 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2756 FILE_OP_ERROR(dest, "fopen");
2761 if (change_file_mode_rw(dest_fp, dest) < 0) {
2762 FILE_OP_ERROR(dest, "chmod");
2763 g_warning("can't change file mode\n");
2766 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2768 if (fputs(buf, dest_fp) == EOF) {
2769 g_warning("writing to %s failed.\n", dest);
2777 if (ferror(src_fp)) {
2778 FILE_OP_ERROR(src, "fgets");
2782 if (fclose(dest_fp) == EOF) {
2783 FILE_OP_ERROR(dest, "fclose");
2795 gint uncanonicalize_file_replace(const gchar *file)
2799 tmp_file = get_tmp_file();
2801 if (uncanonicalize_file(file, tmp_file) < 0) {
2806 if (move_file(tmp_file, file, TRUE) < 0) {
2807 g_warning("can't replace %s .\n", file);
2817 gchar *normalize_newlines(const gchar *str)
2819 const gchar *p = str;
2822 out = outp = g_malloc(strlen(str) + 1);
2823 for (p = str; *p != '\0'; ++p) {
2825 if (*(p + 1) != '\n')
2836 gchar *get_outgoing_rfc2822_str(FILE *fp)
2838 gchar buf[BUFFSIZE];
2842 str = g_string_new(NULL);
2844 /* output header part */
2845 while (fgets(buf, sizeof(buf), fp) != NULL) {
2847 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2854 else if (next != ' ' && next != '\t') {
2858 if (fgets(buf, sizeof(buf), fp) == NULL)
2862 g_string_append(str, buf);
2863 g_string_append(str, "\r\n");
2869 /* output body part */
2870 while (fgets(buf, sizeof(buf), fp) != NULL) {
2873 g_string_append_c(str, '.');
2874 g_string_append(str, buf);
2875 g_string_append(str, "\r\n");
2879 g_string_free(str, FALSE);
2885 * Create a new boundary in a way that it is very unlikely that this
2886 * will occur in the following text. It would be easy to ensure
2887 * uniqueness if everything is either quoted-printable or base64
2888 * encoded (note that conversion is allowed), but because MIME bodies
2889 * may be nested, it may happen that the same boundary has already
2890 * been used. We avoid scanning the message for conflicts and hope the
2893 * boundary := 0*69<bchars> bcharsnospace
2894 * bchars := bcharsnospace / " "
2895 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2896 * "+" / "_" / "," / "-" / "." /
2897 * "/" / ":" / "=" / "?"
2899 * some special characters removed because of buggy MTAs
2902 gchar *generate_mime_boundary(const gchar *prefix)
2904 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2905 "abcdefghijklmnopqrstuvwxyz"
2914 /* We make the boundary depend on the pid, so that all running
2915 * processes generate different values even when they have been
2916 * started within the same second and srandom(time(NULL)) has been
2917 * used. I can't see whether this is really an advantage but it
2918 * doesn't do any harm.
2920 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2921 buf_uniq[i] = tbl[(rand() ^ pid) % (sizeof(tbl) - 1)];
2924 get_rfc822_date(buf_date, sizeof(buf_date));
2925 subst_char(buf_date, ' ', '_');
2926 subst_char(buf_date, ',', '_');
2927 subst_char(buf_date, ':', '_');
2929 return g_strdup_printf("%s_%s_%s", prefix ? prefix : "Multipart",
2930 buf_date, buf_uniq);
2933 gint change_file_mode_rw(FILE *fp, const gchar *file)
2936 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2938 return chmod(file, S_IRUSR|S_IWUSR);
2942 FILE *my_tmpfile(void)
2945 const gchar suffix[] = ".XXXXXX";
2946 const gchar *tmpdir;
2948 const gchar *progname;
2954 tmpdir = get_tmp_dir();
2955 tmplen = strlen(tmpdir);
2956 progname = g_get_prgname();
2957 if (progname == NULL)
2958 progname = "sylpheed-claws";
2959 proglen = strlen(progname);
2960 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2963 memcpy(fname, tmpdir, tmplen);
2964 fname[tmplen] = G_DIR_SEPARATOR;
2965 memcpy(fname + tmplen + 1, progname, proglen);
2966 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2968 fd = mkstemp(fname);
2974 fp = fdopen(fd, "w+b");
2979 #endif /* HAVE_MKSTEMP */
2984 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2988 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2989 fd = mkstemp(*filename);
2991 return fdopen(fd, "w+");
2994 FILE *str_open_as_stream(const gchar *str)
2999 g_return_val_if_fail(str != NULL, NULL);
3003 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3008 if (len == 0) return fp;
3010 if (fwrite(str, len, 1, fp) != 1) {
3011 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3020 gint str_write_to_file(const gchar *str, const gchar *file)
3025 g_return_val_if_fail(str != NULL, -1);
3026 g_return_val_if_fail(file != NULL, -1);
3028 if ((fp = fopen(file, "wb")) == NULL) {
3029 FILE_OP_ERROR(file, "fopen");
3039 if (fwrite(str, len, 1, fp) != 1) {
3040 FILE_OP_ERROR(file, "fwrite");
3046 if (fclose(fp) == EOF) {
3047 FILE_OP_ERROR(file, "fclose");
3055 gchar *file_read_to_str(const gchar *file)
3060 g_return_val_if_fail(file != NULL, NULL);
3062 if ((fp = fopen(file, "rb")) == NULL) {
3063 FILE_OP_ERROR(file, "fopen");
3067 str = file_read_stream_to_str(fp);
3074 gchar *file_read_stream_to_str(FILE *fp)
3081 g_return_val_if_fail(fp != NULL, NULL);
3083 array = g_byte_array_new();
3085 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3086 if (n_read < sizeof(buf) && ferror(fp))
3088 g_byte_array_append(array, buf, n_read);
3092 FILE_OP_ERROR("file stream", "fread");
3093 g_byte_array_free(array, TRUE);
3098 g_byte_array_append(array, buf, 1);
3099 str = (gchar *)array->data;
3100 g_byte_array_free(array, FALSE);
3102 if (!g_utf8_validate(str, -1, NULL)) {
3103 const gchar *src_codeset, *dest_codeset;
3105 src_codeset = conv_get_locale_charset_str();
3106 dest_codeset = CS_UTF_8;
3107 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3115 gint execute_async(gchar *const argv[])
3120 if ((pid = fork()) < 0) {
3125 if (pid == 0) { /* child process */
3128 if ((gch_pid = fork()) < 0) {
3133 if (gch_pid == 0) { /* grandchild process */
3134 execvp(argv[0], argv);
3143 waitpid(pid, &status, 0);
3145 if (WIFEXITED(status))
3146 return WEXITSTATUS(status);
3151 gint execute_sync(gchar *const argv[])
3156 if ((pid = fork()) < 0) {
3161 if (pid == 0) { /* child process */
3162 execvp(argv[0], argv);
3168 waitpid(pid, &status, 0);
3170 if (WIFEXITED(status))
3171 return WEXITSTATUS(status);
3176 gint execute_command_line(const gchar *cmdline, gboolean async)
3181 debug_print("executing: %s\n", cmdline);
3183 argv = strsplit_with_quote(cmdline, " ", 0);
3186 ret = execute_async(argv);
3188 ret = execute_sync(argv);
3195 gchar *get_command_output(const gchar *cmdline)
3197 gchar *child_stdout;
3200 g_return_val_if_fail(cmdline != NULL, NULL);
3202 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3204 g_warning("Can't execute command: %s\n", cmdline);
3208 return child_stdout;
3211 static gint is_unchanged_uri_char(char c)
3223 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3229 for(i = 0; i < strlen(uri) ; i++) {
3230 if (is_unchanged_uri_char(uri[i])) {
3231 if (k + 2 >= bufsize)
3233 encoded_uri[k++] = uri[i];
3236 char * hexa = "0123456789ABCDEF";
3238 if (k + 4 >= bufsize)
3240 encoded_uri[k++] = '%';
3241 encoded_uri[k++] = hexa[uri[i] / 16];
3242 encoded_uri[k++] = hexa[uri[i] % 16];
3248 gint open_uri(const gchar *uri, const gchar *cmdline)
3250 gchar buf[BUFFSIZE];
3252 gchar encoded_uri[BUFFSIZE];
3254 g_return_val_if_fail(uri != NULL, -1);
3256 /* an option to choose whether to use encode_uri or not ? */
3257 encode_uri(encoded_uri, BUFFSIZE, uri);
3260 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3261 !strchr(p + 2, '%'))
3262 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3265 g_warning("Open URI command line is invalid "
3266 "(there must be only one '%%s'): %s",
3268 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3271 execute_command_line(buf, TRUE);
3276 time_t remote_tzoffset_sec(const gchar *zone)
3278 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3284 time_t remoteoffset;
3286 strncpy(zone3, zone, 3);
3290 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3291 (c == '+' || c == '-')) {
3292 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3294 remoteoffset = -remoteoffset;
3295 } else if (!strncmp(zone, "UT" , 2) ||
3296 !strncmp(zone, "GMT", 2)) {
3298 } else if (strlen(zone3) == 3) {
3299 for (p = ustzstr; *p != '\0'; p += 3) {
3300 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3301 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3302 remoteoffset = iustz * 3600;
3308 } else if (strlen(zone3) == 1) {
3310 case 'Z': remoteoffset = 0; break;
3311 case 'A': remoteoffset = -1; break;
3312 case 'B': remoteoffset = -2; break;
3313 case 'C': remoteoffset = -3; break;
3314 case 'D': remoteoffset = -4; break;
3315 case 'E': remoteoffset = -5; break;
3316 case 'F': remoteoffset = -6; break;
3317 case 'G': remoteoffset = -7; break;
3318 case 'H': remoteoffset = -8; break;
3319 case 'I': remoteoffset = -9; break;
3320 case 'K': remoteoffset = -10; break; /* J is not used */
3321 case 'L': remoteoffset = -11; break;
3322 case 'M': remoteoffset = -12; break;
3323 case 'N': remoteoffset = 1; break;
3324 case 'O': remoteoffset = 2; break;
3325 case 'P': remoteoffset = 3; break;
3326 case 'Q': remoteoffset = 4; break;
3327 case 'R': remoteoffset = 5; break;
3328 case 'S': remoteoffset = 6; break;
3329 case 'T': remoteoffset = 7; break;
3330 case 'U': remoteoffset = 8; break;
3331 case 'V': remoteoffset = 9; break;
3332 case 'W': remoteoffset = 10; break;
3333 case 'X': remoteoffset = 11; break;
3334 case 'Y': remoteoffset = 12; break;
3335 default: remoteoffset = 0; break;
3337 remoteoffset = remoteoffset * 3600;
3341 return remoteoffset;
3344 time_t tzoffset_sec(time_t *now)
3350 lt = localtime(now);
3352 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3354 if (lt->tm_year < gmt.tm_year)
3356 else if (lt->tm_year > gmt.tm_year)
3358 else if (lt->tm_yday < gmt.tm_yday)
3360 else if (lt->tm_yday > gmt.tm_yday)
3363 if (off >= 24 * 60) /* should be impossible */
3364 off = 23 * 60 + 59; /* if not, insert silly value */
3365 if (off <= -24 * 60)
3366 off = -(23 * 60 + 59);
3371 /* calculate timezone offset */
3372 gchar *tzoffset(time_t *now)
3374 static gchar offset_string[6];
3380 lt = localtime(now);
3382 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3384 if (lt->tm_year < gmt.tm_year)
3386 else if (lt->tm_year > gmt.tm_year)
3388 else if (lt->tm_yday < gmt.tm_yday)
3390 else if (lt->tm_yday > gmt.tm_yday)
3398 if (off >= 24 * 60) /* should be impossible */
3399 off = 23 * 60 + 59; /* if not, insert silly value */
3401 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3403 return offset_string;
3406 void get_rfc822_date(gchar *buf, gint len)
3410 gchar day[4], mon[4];
3411 gint dd, hh, mm, ss, yyyy;
3416 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3417 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3418 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3419 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3422 void debug_set_mode(gboolean mode)
3427 gboolean debug_get_mode(void)
3432 void debug_print_real(const gchar *format, ...)
3435 gchar buf[BUFFSIZE];
3437 if (!debug_mode) return;
3439 va_start(args, format);
3440 g_vsnprintf(buf, sizeof(buf), format, args);
3446 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3448 if (subject == NULL)
3451 subject += subject_get_prefix_length(subject);
3453 return g_hash_table_lookup(subject_table, subject);
3456 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3459 if (subject == NULL || *subject == 0)
3461 subject += subject_get_prefix_length(subject);
3462 g_hash_table_insert(subject_table, subject, data);
3465 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3467 if (subject == NULL)
3470 subject += subject_get_prefix_length(subject);
3471 g_hash_table_remove(subject_table, subject);
3475 *\brief Check if a string is prefixed with known (combinations)
3476 * of prefixes. The function assumes that each prefix
3477 * is terminated by zero or exactly _one_ space.
3479 *\param str String to check for a prefixes
3481 *\return int Number of chars in the prefix that should be skipped
3482 * for a "clean" subject line. If no prefix was found, 0
3485 int subject_get_prefix_length(const gchar *subject)
3487 /*!< Array with allowable reply prefixes regexps. */
3488 static const gchar * const prefixes[] = {
3489 "Re\\:", /* "Re:" */
3490 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3491 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3492 "Aw\\:", /* "Aw:" (German) */
3493 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3494 "Res\\:", /* "Res:" (Brazilian Outlook) */
3495 "Fw\\:", /* "Fw:" Forward */
3496 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3497 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3498 "Rif\\:" /* "Rif:" (Italian Outlook) */
3501 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3504 static regex_t regex;
3505 static gboolean init_;
3507 if (!subject) return 0;
3508 if (!*subject) return 0;
3511 GString *s = g_string_new("");
3513 for (n = 0; n < PREFIXES; n++)
3514 /* Terminate each prefix regexpression by a
3515 * "\ ?" (zero or ONE space), and OR them */
3516 g_string_append_printf(s, "(%s\\ ?)%s",
3521 g_string_prepend(s, "(");
3522 g_string_append(s, ")+"); /* match at least once */
3523 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3526 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3527 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3528 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3529 debug_print("Error compiling regexp %s\n", s->str);
3530 g_string_free(s, TRUE);
3534 g_string_free(s, TRUE);
3538 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3544 guint g_stricase_hash(gconstpointer gptr)
3546 guint hash_result = 0;
3549 for (str = gptr; str && *str; str++) {
3550 if (isupper((guchar)*str)) hash_result += (*str + ' ');
3551 else hash_result += *str;
3557 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3559 const char *str1 = gptr1;
3560 const char *str2 = gptr2;
3562 return !g_utf8_collate(str1, str2);
3565 gint g_int_compare(gconstpointer a, gconstpointer b)
3567 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3570 gchar *generate_msgid(gchar *buf, gint len)
3579 addr = g_strconcat("@", get_domain_name(), NULL);
3581 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x%s",
3582 lt->tm_year + 1900, lt->tm_mon + 1,
3583 lt->tm_mday, lt->tm_hour,
3584 lt->tm_min, lt->tm_sec,
3585 (guint) rand(), addr);
3592 quote_cmd_argument()
3594 return a quoted string safely usable in argument of a command.
3596 code is extracted and adapted from etPan! project -- DINH V. Hoà .
3599 gint quote_cmd_argument(gchar * result, guint size,
3609 for(p = path ; * p != '\0' ; p ++) {
3611 if (isalnum((guchar)*p) || (* p == '/')) {
3612 if (remaining > 0) {
3618 result[size - 1] = '\0';
3623 if (remaining >= 2) {
3631 result[size - 1] = '\0';
3636 if (remaining > 0) {
3640 result[size - 1] = '\0';
3654 static void g_node_map_recursive(GNode *node, gpointer data)
3656 GNodeMapData *mapdata = (GNodeMapData *) data;
3658 GNodeMapData newmapdata;
3661 newdata = mapdata->func(node->data, mapdata->data);
3662 if (newdata != NULL) {
3663 newnode = g_node_new(newdata);
3664 g_node_append(mapdata->parent, newnode);
3666 newmapdata.parent = newnode;
3667 newmapdata.func = mapdata->func;
3668 newmapdata.data = mapdata->data;
3670 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3674 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3677 GNodeMapData mapdata;
3679 g_return_val_if_fail(node != NULL, NULL);
3680 g_return_val_if_fail(func != NULL, NULL);
3682 root = g_node_new(func(node->data, data));
3684 mapdata.parent = root;
3685 mapdata.func = func;
3686 mapdata.data = data;
3688 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3693 #define HEX_TO_INT(val, hex) \
3697 if ('0' <= c && c <= '9') { \
3699 } else if ('a' <= c && c <= 'f') { \
3700 val = c - 'a' + 10; \
3701 } else if ('A' <= c && c <= 'F') { \
3702 val = c - 'A' + 10; \
3708 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3715 if (hi == -1 || lo == -1)
3718 *out = (hi << 4) + lo;
3722 #define INT_TO_HEX(hex, val) \
3725 hex = '0' + (val); \
3727 hex = 'A' + (val) - 10; \
3730 void get_hex_str(gchar *out, guchar ch)
3734 INT_TO_HEX(hex, ch >> 4);
3736 INT_TO_HEX(hex, ch & 0x0f);
3742 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3744 #define G_PRINT_REF g_print
3748 *\brief Register ref counted pointer. It is based on GBoxed, so should
3749 * work with anything that uses the GType system. The semantics
3750 * are similar to a C++ auto pointer, with the exception that
3751 * C doesn't have automatic closure (calling destructors) when
3752 * exiting a block scope.
3753 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3754 * function directly.
3756 *\return GType A GType type.
3758 GType g_auto_pointer_register(void)
3760 static GType auto_pointer_type;
3761 if (!auto_pointer_type)
3763 g_boxed_type_register_static
3764 ("G_TYPE_AUTO_POINTER",
3765 (GBoxedCopyFunc) g_auto_pointer_copy,
3766 (GBoxedFreeFunc) g_auto_pointer_free);
3767 return auto_pointer_type;
3771 *\brief Structure with g_new() allocated pointer guarded by the
3774 typedef struct AutoPointerRef {
3775 void (*free) (gpointer);
3781 *\brief The auto pointer opaque structure that references the
3782 * pointer guard block.
3784 typedef struct AutoPointer {
3785 AutoPointerRef *ref;
3786 gpointer ptr; /*!< access to protected pointer */
3790 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3794 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3795 * ... when assigning, copying and freeing storage elements
3797 * gtk_list_store_new(N_S_COLUMNS,
3798 * G_TYPE_AUTO_POINTER,
3802 * Template *precious_data = g_new0(Template, 1);
3803 * g_pointer protect = g_auto_pointer_new(precious_data);
3805 * gtk_list_store_set(container, &iter,
3809 * ... the gtk_list_store has copied the pointer and
3810 * ... incremented its reference count, we should free
3811 * ... the auto pointer (in C++ a destructor would do
3812 * ... this for us when leaving block scope)
3814 * g_auto_pointer_free(protect);
3816 * ... gtk_list_store_set() now manages the data. When
3817 * ... *explicitly* requesting a pointer from the list
3818 * ... store, don't forget you get a copy that should be
3819 * ... freed with g_auto_pointer_free() eventually.
3823 *\param pointer Pointer to be guarded.
3825 *\return GAuto * Pointer that should be used in containers with
3828 GAuto *g_auto_pointer_new(gpointer p)
3830 AutoPointerRef *ref;
3836 ref = g_new0(AutoPointerRef, 1);
3837 ptr = g_new0(AutoPointer, 1);
3846 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3852 *\brief Allocate an autopointer using the passed \a free function to
3853 * free the guarded pointer
3855 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3862 aptr = g_auto_pointer_new(p);
3863 aptr->ref->free = free_;
3867 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3869 if (auto_ptr == NULL)
3871 return ((AutoPointer *) auto_ptr)->ptr;
3875 *\brief Copies an auto pointer by. It's mostly not necessary
3876 * to call this function directly, unless you copy/assign
3877 * the guarded pointer.
3879 *\param auto_ptr Auto pointer returned by previous call to
3880 * g_auto_pointer_new_XXX()
3882 *\return gpointer An auto pointer
3884 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3887 AutoPointerRef *ref;
3890 if (auto_ptr == NULL)
3895 newp = g_new0(AutoPointer, 1);
3898 newp->ptr = ref->pointer;
3901 G_PRINT_REF ("XXXX COPY(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3907 *\brief Free an auto pointer
3909 void g_auto_pointer_free(GAuto *auto_ptr)
3912 AutoPointerRef *ref;
3914 if (auto_ptr == NULL)
3920 if (--(ref->cnt) == 0) {
3921 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3922 ref->free(ref->pointer);
3925 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);