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;
1464 while (isspace(*p)) p++;
1465 if (!strncmp(p, "file:", 5)) {
1468 while (*q && *q != '\n' && *q != '\r') q++;
1471 gchar *file, *locale_file = NULL;
1473 while (q > p && isspace(*q)) q--;
1474 Xalloca(escaped_utf8uri, q - p + 2,
1476 Xalloca(file, q - p + 2,
1479 strncpy(escaped_utf8uri, p, q - p + 1);
1480 escaped_utf8uri[q - p + 1] = '\0';
1481 decode_uri(file, escaped_utf8uri);
1483 * g_filename_from_uri() rejects escaped/locale encoded uri
1484 * string which come from Nautilus.
1486 if (g_utf8_validate(file, -1, NULL))
1488 = conv_codeset_strdup(
1491 conv_get_locale_charset_str());
1493 locale_file = g_strdup(file + 5);
1494 result = g_list_append(result, locale_file);
1498 p = strchr(p, '\n');
1505 /* Converts two-digit hexadecimal to decimal. Used for unescaping escaped
1508 static gint axtoi(const gchar *hexstr)
1510 gint hi, lo, result;
1513 if ('0' <= hi && hi <= '9') {
1516 if ('a' <= hi && hi <= 'f') {
1519 if ('A' <= hi && hi <= 'F') {
1524 if ('0' <= lo && lo <= '9') {
1527 if ('a' <= lo && lo <= 'f') {
1530 if ('A' <= lo && lo <= 'F') {
1533 result = lo + (16 * hi);
1537 gboolean is_uri_string(const gchar *str)
1539 return (g_ascii_strncasecmp(str, "http://", 7) == 0 ||
1540 g_ascii_strncasecmp(str, "https://", 8) == 0 ||
1541 g_ascii_strncasecmp(str, "ftp://", 6) == 0 ||
1542 g_ascii_strncasecmp(str, "www.", 4) == 0);
1545 gchar *get_uri_path(const gchar *uri)
1547 if (g_ascii_strncasecmp(uri, "http://", 7) == 0)
1548 return (gchar *)(uri + 7);
1549 else if (g_ascii_strncasecmp(uri, "https://", 8) == 0)
1550 return (gchar *)(uri + 8);
1551 else if (g_ascii_strncasecmp(uri, "ftp://", 6) == 0)
1552 return (gchar *)(uri + 6);
1554 return (gchar *)uri;
1557 gint get_uri_len(const gchar *str)
1561 if (is_uri_string(str)) {
1562 for (p = str; *p != '\0'; p++) {
1563 if (!g_ascii_isgraph(*p) || strchr("()<>\"", *p))
1572 /* Decodes URL-Encoded strings (i.e. strings in which spaces are replaced by
1573 * plusses, and escape characters are used)
1575 void decode_uri(gchar *decoded_uri, const gchar *encoded_uri)
1577 gchar *dec = decoded_uri;
1578 const gchar *enc = encoded_uri;
1583 if (isxdigit((guchar)enc[0]) &&
1584 isxdigit((guchar)enc[1])) {
1602 gint scan_mailto_url(const gchar *mailto, gchar **to, gchar **cc, gchar **bcc,
1603 gchar **subject, gchar **body)
1608 Xstrdup_a(tmp_mailto, mailto, return -1);
1610 if (!strncmp(tmp_mailto, "mailto:", 7))
1613 p = strchr(tmp_mailto, '?');
1620 *to = g_strdup(tmp_mailto);
1623 gchar *field, *value;
1640 if (*value == '\0') continue;
1642 if (cc && !*cc && !g_ascii_strcasecmp(field, "cc")) {
1643 *cc = g_strdup(value);
1644 } else if (bcc && !*bcc && !g_ascii_strcasecmp(field, "bcc")) {
1645 *bcc = g_strdup(value);
1646 } else if (subject && !*subject &&
1647 !g_ascii_strcasecmp(field, "subject")) {
1648 *subject = g_malloc(strlen(value) + 1);
1649 decode_uri(*subject, value);
1650 } else if (body && !*body && !g_ascii_strcasecmp(field, "body")) {
1651 *body = g_malloc(strlen(value) + 1);
1652 decode_uri(*body, value);
1660 * We need this wrapper around g_get_home_dir(), so that
1661 * we can fix some Windoze things here. Should be done in glibc of course
1662 * but as long as we are not able to do our own extensions to glibc, we do
1665 const gchar *get_home_dir(void)
1667 #if HAVE_DOSISH_SYSTEM
1668 static gchar *home_dir;
1671 home_dir = read_w32_registry_string(NULL,
1672 "Software\\Sylpheed", "HomeDir" );
1673 if (!home_dir || !*home_dir) {
1674 if (getenv ("HOMEDRIVE") && getenv("HOMEPATH")) {
1675 const char *s = g_get_home_dir();
1677 home_dir = g_strdup (s);
1679 if (!home_dir || !*home_dir)
1680 home_dir = g_strdup ("c:\\sylpheed");
1682 debug_print("initialized home_dir to `%s'\n", home_dir);
1685 #else /* standard glib */
1686 return g_get_home_dir();
1690 const gchar *get_rc_dir(void)
1692 static gchar *rc_dir = NULL;
1695 rc_dir = g_strconcat(get_home_dir(), G_DIR_SEPARATOR_S,
1701 const gchar *get_news_cache_dir(void)
1703 static gchar *news_cache_dir = NULL;
1705 if (!news_cache_dir)
1706 news_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1707 NEWS_CACHE_DIR, NULL);
1709 return news_cache_dir;
1712 const gchar *get_imap_cache_dir(void)
1714 static gchar *imap_cache_dir = NULL;
1716 if (!imap_cache_dir)
1717 imap_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1718 IMAP_CACHE_DIR, NULL);
1720 return imap_cache_dir;
1723 const gchar *get_mbox_cache_dir(void)
1725 static gchar *mbox_cache_dir = NULL;
1727 if (!mbox_cache_dir)
1728 mbox_cache_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1729 MBOX_CACHE_DIR, NULL);
1731 return mbox_cache_dir;
1734 const gchar *get_mime_tmp_dir(void)
1736 static gchar *mime_tmp_dir = NULL;
1739 mime_tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1740 MIME_TMP_DIR, NULL);
1742 return mime_tmp_dir;
1745 const gchar *get_template_dir(void)
1747 static gchar *template_dir = NULL;
1750 template_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1751 TEMPLATE_DIR, NULL);
1753 return template_dir;
1756 const gchar *get_header_cache_dir(void)
1758 static gchar *header_dir = NULL;
1761 header_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1762 HEADER_CACHE_DIR, NULL);
1767 const gchar *get_tmp_dir(void)
1769 static gchar *tmp_dir = NULL;
1772 tmp_dir = g_strconcat(get_rc_dir(), G_DIR_SEPARATOR_S,
1778 gchar *get_tmp_file(void)
1781 static guint32 id = 0;
1783 tmp_file = g_strdup_printf("%s%ctmpfile.%08x",
1784 get_tmp_dir(), G_DIR_SEPARATOR, id++);
1789 const gchar *get_domain_name(void)
1791 static gchar *domain_name = NULL;
1797 if (uname(&uts) < 0) {
1798 perror("gethostname");
1799 domain_name = "unknown";
1801 if ((hp = my_gethostbyname(uts.nodename)) == NULL) {
1802 perror("gethostbyname");
1803 domain_name = g_strdup(uts.nodename);
1805 domain_name = g_strdup(hp->h_name);
1809 debug_print("domain name = %s\n", domain_name);
1815 off_t get_file_size(const gchar *file)
1819 if (stat(file, &s) < 0) {
1820 FILE_OP_ERROR(file, "stat");
1827 off_t get_file_size_as_crlf(const gchar *file)
1831 gchar buf[BUFFSIZE];
1833 if ((fp = fopen(file, "rb")) == NULL) {
1834 FILE_OP_ERROR(file, "fopen");
1838 while (fgets(buf, sizeof(buf), fp) != NULL) {
1840 size += strlen(buf) + 2;
1844 FILE_OP_ERROR(file, "fgets");
1853 off_t get_left_file_size(FILE *fp)
1859 if ((pos = ftell(fp)) < 0) {
1863 if (fseek(fp, 0L, SEEK_END) < 0) {
1867 if ((end = ftell(fp)) < 0) {
1872 if (fseek(fp, pos, SEEK_SET) < 0) {
1880 gboolean file_exist(const gchar *file, gboolean allow_fifo)
1887 if (stat(file, &s) < 0) {
1888 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1892 if (S_ISREG(s.st_mode) || (allow_fifo && S_ISFIFO(s.st_mode)))
1898 gboolean is_dir_exist(const gchar *dir)
1905 if (stat(dir, &s) < 0) {
1906 if (ENOENT != errno) FILE_OP_ERROR(dir, "stat");
1910 if (S_ISDIR(s.st_mode))
1916 gboolean is_file_entry_exist(const gchar *file)
1923 if (stat(file, &s) < 0) {
1924 if (ENOENT != errno) FILE_OP_ERROR(file, "stat");
1931 gboolean dirent_is_regular_file(struct dirent *d)
1935 #ifdef HAVE_DIRENT_D_TYPE
1936 if (d->d_type == DT_REG)
1938 else if (d->d_type != DT_UNKNOWN)
1942 return (stat(d->d_name, &s) == 0 && S_ISREG(s.st_mode));
1945 gboolean dirent_is_directory(struct dirent *d)
1949 #ifdef HAVE_DIRENT_D_TYPE
1950 if (d->d_type == DT_DIR)
1952 else if (d->d_type != DT_UNKNOWN)
1956 return (stat(d->d_name, &s) == 0 && S_ISDIR(s.st_mode));
1959 gint change_dir(const gchar *dir)
1961 gchar *prevdir = NULL;
1964 prevdir = g_get_current_dir();
1966 if (chdir(dir) < 0) {
1967 FILE_OP_ERROR(dir, "chdir");
1968 if (debug_mode) g_free(prevdir);
1970 } else if (debug_mode) {
1973 cwd = g_get_current_dir();
1974 if (strcmp(prevdir, cwd) != 0)
1975 g_print("current dir: %s\n", cwd);
1983 gint make_dir(const gchar *dir)
1985 if (mkdir(dir, S_IRWXU) < 0) {
1986 FILE_OP_ERROR(dir, "mkdir");
1989 if (chmod(dir, S_IRWXU) < 0)
1990 FILE_OP_ERROR(dir, "chmod");
1995 gint make_dir_hier(const gchar *dir)
2000 for (p = dir; (p = strchr(p, G_DIR_SEPARATOR)) != NULL; p++) {
2001 parent_dir = g_strndup(dir, p - dir);
2002 if (*parent_dir != '\0') {
2003 if (!is_dir_exist(parent_dir)) {
2004 if (make_dir(parent_dir) < 0) {
2013 if (!is_dir_exist(dir)) {
2014 if (make_dir(dir) < 0)
2021 gint remove_all_files(const gchar *dir)
2027 prev_dir = g_get_current_dir();
2029 if (chdir(dir) < 0) {
2030 FILE_OP_ERROR(dir, "chdir");
2035 if ((dp = opendir(".")) == NULL) {
2036 FILE_OP_ERROR(dir, "opendir");
2041 while ((d = readdir(dp)) != NULL) {
2042 if (!strcmp(d->d_name, ".") ||
2043 !strcmp(d->d_name, ".."))
2046 if (unlink(d->d_name) < 0)
2047 FILE_OP_ERROR(d->d_name, "unlink");
2052 if (chdir(prev_dir) < 0) {
2053 FILE_OP_ERROR(prev_dir, "chdir");
2063 gint remove_numbered_files(const gchar *dir, guint first, guint last)
2070 prev_dir = g_get_current_dir();
2072 if (chdir(dir) < 0) {
2073 FILE_OP_ERROR(dir, "chdir");
2078 if ((dp = opendir(".")) == NULL) {
2079 FILE_OP_ERROR(dir, "opendir");
2084 while ((d = readdir(dp)) != NULL) {
2085 file_no = to_number(d->d_name);
2086 if (file_no > 0 && first <= file_no && file_no <= last) {
2087 if (is_dir_exist(d->d_name))
2089 if (unlink(d->d_name) < 0)
2090 FILE_OP_ERROR(d->d_name, "unlink");
2096 if (chdir(prev_dir) < 0) {
2097 FILE_OP_ERROR(prev_dir, "chdir");
2107 gint remove_numbered_files_not_in_list(const gchar *dir, GSList *numberlist)
2114 prev_dir = g_get_current_dir();
2116 if (chdir(dir) < 0) {
2117 FILE_OP_ERROR(dir, "chdir");
2122 if ((dp = opendir(".")) == NULL) {
2123 FILE_OP_ERROR(dir, "opendir");
2128 while ((d = readdir(dp)) != NULL) {
2129 file_no = to_number(d->d_name);
2130 if (file_no > 0 && (g_slist_find(numberlist, GINT_TO_POINTER(file_no)) == NULL)) {
2131 debug_print("removing unwanted file %d from %s\n", file_no, dir);
2132 if (is_dir_exist(d->d_name))
2134 if (unlink(d->d_name) < 0)
2135 FILE_OP_ERROR(d->d_name, "unlink");
2141 if (chdir(prev_dir) < 0) {
2142 FILE_OP_ERROR(prev_dir, "chdir");
2152 gint remove_all_numbered_files(const gchar *dir)
2154 return remove_numbered_files(dir, 0, UINT_MAX);
2157 gint remove_expired_files(const gchar *dir, guint hours)
2164 time_t mtime, now, expire_time;
2166 prev_dir = g_get_current_dir();
2168 if (chdir(dir) < 0) {
2169 FILE_OP_ERROR(dir, "chdir");
2174 if ((dp = opendir(".")) == NULL) {
2175 FILE_OP_ERROR(dir, "opendir");
2181 expire_time = hours * 60 * 60;
2183 while ((d = readdir(dp)) != NULL) {
2184 file_no = to_number(d->d_name);
2186 if (stat(d->d_name, &s) < 0) {
2187 FILE_OP_ERROR(d->d_name, "stat");
2190 if (S_ISDIR(s.st_mode))
2192 mtime = MAX(s.st_mtime, s.st_atime);
2193 if (now - mtime > expire_time) {
2194 if (unlink(d->d_name) < 0)
2195 FILE_OP_ERROR(d->d_name, "unlink");
2202 if (chdir(prev_dir) < 0) {
2203 FILE_OP_ERROR(prev_dir, "chdir");
2213 gint remove_dir_recursive(const gchar *dir)
2220 /* g_print("dir = %s\n", dir); */
2222 if (stat(dir, &s) < 0) {
2223 FILE_OP_ERROR(dir, "stat");
2224 if (ENOENT == errno) return 0;
2228 if (!S_ISDIR(s.st_mode)) {
2229 if (unlink(dir) < 0) {
2230 FILE_OP_ERROR(dir, "unlink");
2237 prev_dir = g_get_current_dir();
2238 /* g_print("prev_dir = %s\n", prev_dir); */
2240 if (!path_cmp(prev_dir, dir)) {
2242 if (chdir("..") < 0) {
2243 FILE_OP_ERROR(dir, "chdir");
2246 prev_dir = g_get_current_dir();
2249 if (chdir(dir) < 0) {
2250 FILE_OP_ERROR(dir, "chdir");
2255 if ((dp = opendir(".")) == NULL) {
2256 FILE_OP_ERROR(dir, "opendir");
2262 /* remove all files in the directory */
2263 while ((d = readdir(dp)) != NULL) {
2264 if (!strcmp(d->d_name, ".") ||
2265 !strcmp(d->d_name, ".."))
2268 /* g_print("removing %s\n", d->d_name); */
2270 if (dirent_is_directory(d)) {
2271 if (remove_dir_recursive(d->d_name) < 0) {
2272 g_warning("can't remove directory\n");
2276 if (unlink(d->d_name) < 0)
2277 FILE_OP_ERROR(d->d_name, "unlink");
2283 if (chdir(prev_dir) < 0) {
2284 FILE_OP_ERROR(prev_dir, "chdir");
2291 if (rmdir(dir) < 0) {
2292 FILE_OP_ERROR(dir, "rmdir");
2300 /* this seems to be slower than the stdio version... */
2301 gint copy_file(const gchar *src, const gchar *dest)
2303 gint src_fd, dest_fd;
2307 gchar *dest_bak = NULL;
2309 if ((src_fd = open(src, O_RDONLY)) < 0) {
2310 FILE_OP_ERROR(src, "open");
2314 if (is_file_exist(dest)) {
2315 dest_bak = g_strconcat(dest, ".bak", NULL);
2316 if (rename(dest, dest_bak) < 0) {
2317 FILE_OP_ERROR(dest, "rename");
2324 if ((dest_fd = open(dest, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) < 0) {
2325 FILE_OP_ERROR(dest, "open");
2328 if (rename(dest_bak, dest) < 0)
2329 FILE_OP_ERROR(dest_bak, "rename");
2335 while ((n_read = read(src_fd, buf, sizeof(buf))) > 0) {
2340 n_write = write(dest_fd, bufp, len);
2342 g_warning("writing to %s failed.\n", dest);
2347 if (rename(dest_bak, dest) < 0)
2348 FILE_OP_ERROR(dest_bak, "rename");
2361 if (n_read < 0 || get_file_size(src) != get_file_size(dest)) {
2362 g_warning("File copy from %s to %s failed.\n", src, dest);
2365 if (rename(dest_bak, dest) < 0)
2366 FILE_OP_ERROR(dest_bak, "rename");
2379 * Append src file body to the tail of dest file.
2380 * Now keep_backup has no effects.
2382 gint append_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2384 FILE *src_fp, *dest_fp;
2388 gboolean err = FALSE;
2390 if ((src_fp = fopen(src, "rb")) == NULL) {
2391 FILE_OP_ERROR(src, "fopen");
2395 if ((dest_fp = fopen(dest, "ab")) == NULL) {
2396 FILE_OP_ERROR(dest, "fopen");
2401 if (change_file_mode_rw(dest_fp, dest) < 0) {
2402 FILE_OP_ERROR(dest, "chmod");
2403 g_warning("can't change file mode\n");
2406 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2407 if (n_read < sizeof(buf) && ferror(src_fp))
2409 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2410 g_warning("writing to %s failed.\n", dest);
2418 if (ferror(src_fp)) {
2419 FILE_OP_ERROR(src, "fread");
2423 if (fclose(dest_fp) == EOF) {
2424 FILE_OP_ERROR(dest, "fclose");
2436 gint copy_file(const gchar *src, const gchar *dest, gboolean keep_backup)
2438 FILE *src_fp, *dest_fp;
2441 gchar *dest_bak = NULL;
2442 gboolean err = FALSE;
2444 if ((src_fp = fopen(src, "rb")) == NULL) {
2445 FILE_OP_ERROR(src, "fopen");
2448 if (is_file_exist(dest)) {
2449 dest_bak = g_strconcat(dest, ".bak", NULL);
2450 if (rename(dest, dest_bak) < 0) {
2451 FILE_OP_ERROR(dest, "rename");
2458 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2459 FILE_OP_ERROR(dest, "fopen");
2462 if (rename(dest_bak, dest) < 0)
2463 FILE_OP_ERROR(dest_bak, "rename");
2469 if (change_file_mode_rw(dest_fp, dest) < 0) {
2470 FILE_OP_ERROR(dest, "chmod");
2471 g_warning("can't change file mode\n");
2474 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), src_fp)) > 0) {
2475 if (n_read < sizeof(buf) && ferror(src_fp))
2477 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2478 g_warning("writing to %s failed.\n", dest);
2483 if (rename(dest_bak, dest) < 0)
2484 FILE_OP_ERROR(dest_bak, "rename");
2491 if (ferror(src_fp)) {
2492 FILE_OP_ERROR(src, "fread");
2496 if (fclose(dest_fp) == EOF) {
2497 FILE_OP_ERROR(dest, "fclose");
2504 if (rename(dest_bak, dest) < 0)
2505 FILE_OP_ERROR(dest_bak, "rename");
2511 if (keep_backup == FALSE && dest_bak)
2519 gint move_file(const gchar *src, const gchar *dest, gboolean overwrite)
2521 if (overwrite == FALSE && is_file_exist(dest)) {
2522 g_warning("move_file(): file %s already exists.", dest);
2526 if (rename(src, dest) == 0) return 0;
2528 if (EXDEV != errno) {
2529 FILE_OP_ERROR(src, "rename");
2533 if (copy_file(src, dest, FALSE) < 0) return -1;
2540 gint copy_file_part_to_fp(FILE *fp, off_t offset, size_t length, FILE *dest_fp)
2543 gint bytes_left, to_read;
2546 if (fseek(fp, offset, SEEK_SET) < 0) {
2551 bytes_left = length;
2552 to_read = MIN(bytes_left, sizeof(buf));
2554 while ((n_read = fread(buf, sizeof(gchar), to_read, fp)) > 0) {
2555 if (n_read < to_read && ferror(fp))
2557 if (fwrite(buf, n_read, 1, dest_fp) < 1) {
2560 bytes_left -= n_read;
2561 if (bytes_left == 0)
2563 to_read = MIN(bytes_left, sizeof(buf));
2574 gint copy_file_part(FILE *fp, off_t offset, size_t length, const gchar *dest)
2577 gboolean err = FALSE;
2579 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2580 FILE_OP_ERROR(dest, "fopen");
2584 if (change_file_mode_rw(dest_fp, dest) < 0) {
2585 FILE_OP_ERROR(dest, "chmod");
2586 g_warning("can't change file mode\n");
2589 if (copy_file_part_to_fp(fp, offset, length, dest_fp) < 0)
2592 if (!err && fclose(dest_fp) == EOF) {
2593 FILE_OP_ERROR(dest, "fclose");
2598 g_warning("writing to %s failed.\n", dest);
2606 /* convert line endings into CRLF. If the last line doesn't end with
2607 * linebreak, add it.
2609 gchar *canonicalize_str(const gchar *str)
2615 for (p = str; *p != '\0'; ++p) {
2622 if (p == str || *(p - 1) != '\n')
2625 out = outp = g_malloc(new_len + 1);
2626 for (p = str; *p != '\0'; ++p) {
2633 if (p == str || *(p - 1) != '\n') {
2642 gint canonicalize_file(const gchar *src, const gchar *dest)
2644 FILE *src_fp, *dest_fp;
2645 gchar buf[BUFFSIZE];
2647 gboolean err = FALSE;
2648 gboolean last_linebreak = FALSE;
2650 if ((src_fp = fopen(src, "rb")) == NULL) {
2651 FILE_OP_ERROR(src, "fopen");
2655 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2656 FILE_OP_ERROR(dest, "fopen");
2661 if (change_file_mode_rw(dest_fp, dest) < 0) {
2662 FILE_OP_ERROR(dest, "chmod");
2663 g_warning("can't change file mode\n");
2666 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2670 if (len == 0) break;
2671 last_linebreak = FALSE;
2673 if (buf[len - 1] != '\n') {
2674 last_linebreak = TRUE;
2675 r = fputs(buf, dest_fp);
2676 } else if (len > 1 && buf[len - 1] == '\n' && buf[len - 2] == '\r') {
2677 r = fputs(buf, dest_fp);
2680 r = fwrite(buf, len - 1, 1, dest_fp);
2685 r = fputs("\r\n", dest_fp);
2689 g_warning("writing to %s failed.\n", dest);
2697 if (last_linebreak == TRUE) {
2698 if (fputs("\r\n", dest_fp) == EOF)
2702 if (ferror(src_fp)) {
2703 FILE_OP_ERROR(src, "fgets");
2707 if (fclose(dest_fp) == EOF) {
2708 FILE_OP_ERROR(dest, "fclose");
2720 gint canonicalize_file_replace(const gchar *file)
2724 tmp_file = get_tmp_file();
2726 if (canonicalize_file(file, tmp_file) < 0) {
2731 if (move_file(tmp_file, file, TRUE) < 0) {
2732 g_warning("can't replace %s .\n", file);
2742 gint uncanonicalize_file(const gchar *src, const gchar *dest)
2744 FILE *src_fp, *dest_fp;
2745 gchar buf[BUFFSIZE];
2746 gboolean err = FALSE;
2748 if ((src_fp = fopen(src, "rb")) == NULL) {
2749 FILE_OP_ERROR(src, "fopen");
2753 if ((dest_fp = fopen(dest, "wb")) == NULL) {
2754 FILE_OP_ERROR(dest, "fopen");
2759 if (change_file_mode_rw(dest_fp, dest) < 0) {
2760 FILE_OP_ERROR(dest, "chmod");
2761 g_warning("can't change file mode\n");
2764 while (fgets(buf, sizeof(buf), src_fp) != NULL) {
2766 if (fputs(buf, dest_fp) == EOF) {
2767 g_warning("writing to %s failed.\n", dest);
2775 if (ferror(src_fp)) {
2776 FILE_OP_ERROR(src, "fgets");
2780 if (fclose(dest_fp) == EOF) {
2781 FILE_OP_ERROR(dest, "fclose");
2793 gint uncanonicalize_file_replace(const gchar *file)
2797 tmp_file = get_tmp_file();
2799 if (uncanonicalize_file(file, tmp_file) < 0) {
2804 if (move_file(tmp_file, file, TRUE) < 0) {
2805 g_warning("can't replace %s .\n", file);
2815 gchar *normalize_newlines(const gchar *str)
2817 const gchar *p = str;
2820 out = outp = g_malloc(strlen(str) + 1);
2821 for (p = str; *p != '\0'; ++p) {
2823 if (*(p + 1) != '\n')
2834 gchar *get_outgoing_rfc2822_str(FILE *fp)
2836 gchar buf[BUFFSIZE];
2840 str = g_string_new(NULL);
2842 /* output header part */
2843 while (fgets(buf, sizeof(buf), fp) != NULL) {
2845 if (!g_ascii_strncasecmp(buf, "Bcc:", 4)) {
2852 else if (next != ' ' && next != '\t') {
2856 if (fgets(buf, sizeof(buf), fp) == NULL)
2860 g_string_append(str, buf);
2861 g_string_append(str, "\r\n");
2867 /* output body part */
2868 while (fgets(buf, sizeof(buf), fp) != NULL) {
2871 g_string_append_c(str, '.');
2872 g_string_append(str, buf);
2873 g_string_append(str, "\r\n");
2877 g_string_free(str, FALSE);
2883 * Create a new boundary in a way that it is very unlikely that this
2884 * will occur in the following text. It would be easy to ensure
2885 * uniqueness if everything is either quoted-printable or base64
2886 * encoded (note that conversion is allowed), but because MIME bodies
2887 * may be nested, it may happen that the same boundary has already
2888 * been used. We avoid scanning the message for conflicts and hope the
2891 * boundary := 0*69<bchars> bcharsnospace
2892 * bchars := bcharsnospace / " "
2893 * bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" /
2894 * "+" / "_" / "," / "-" / "." /
2895 * "/" / ":" / "=" / "?"
2897 * some special characters removed because of buggy MTAs
2900 gchar *generate_mime_boundary(const gchar *prefix)
2902 static gchar tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
2903 "abcdefghijklmnopqrstuvwxyz"
2912 /* We make the boundary depend on the pid, so that all running
2913 * processes generate different values even when they have been
2914 * started within the same second and srandom(time(NULL)) has been
2915 * used. I can't see whether this is really an advantage but it
2916 * doesn't do any harm.
2918 for (i = 0; i < sizeof(buf_uniq) - 1; i++)
2919 buf_uniq[i] = tbl[(rand() ^ pid) % (sizeof(tbl) - 1)];
2922 get_rfc822_date(buf_date, sizeof(buf_date));
2923 subst_char(buf_date, ' ', '_');
2924 subst_char(buf_date, ',', '_');
2925 subst_char(buf_date, ':', '_');
2927 return g_strdup_printf("%s_%s_%s", prefix ? prefix : "Multipart",
2928 buf_date, buf_uniq);
2931 gint change_file_mode_rw(FILE *fp, const gchar *file)
2934 return fchmod(fileno(fp), S_IRUSR|S_IWUSR);
2936 return chmod(file, S_IRUSR|S_IWUSR);
2940 FILE *my_tmpfile(void)
2943 const gchar suffix[] = ".XXXXXX";
2944 const gchar *tmpdir;
2946 const gchar *progname;
2952 tmpdir = get_tmp_dir();
2953 tmplen = strlen(tmpdir);
2954 progname = g_get_prgname();
2955 if (progname == NULL)
2956 progname = "sylpheed-claws";
2957 proglen = strlen(progname);
2958 Xalloca(fname, tmplen + 1 + proglen + sizeof(suffix),
2961 memcpy(fname, tmpdir, tmplen);
2962 fname[tmplen] = G_DIR_SEPARATOR;
2963 memcpy(fname + tmplen + 1, progname, proglen);
2964 memcpy(fname + tmplen + 1 + proglen, suffix, sizeof(suffix));
2966 fd = mkstemp(fname);
2972 fp = fdopen(fd, "w+b");
2977 #endif /* HAVE_MKSTEMP */
2982 FILE *get_tmpfile_in_dir(const gchar *dir, gchar **filename)
2986 *filename = g_strdup_printf("%s%csylpheed.XXXXXX", dir, G_DIR_SEPARATOR);
2987 fd = mkstemp(*filename);
2989 return fdopen(fd, "w+");
2992 FILE *str_open_as_stream(const gchar *str)
2997 g_return_val_if_fail(str != NULL, NULL);
3001 FILE_OP_ERROR("str_open_as_stream", "my_tmpfile");
3006 if (len == 0) return fp;
3008 if (fwrite(str, len, 1, fp) != 1) {
3009 FILE_OP_ERROR("str_open_as_stream", "fwrite");
3018 gint str_write_to_file(const gchar *str, const gchar *file)
3023 g_return_val_if_fail(str != NULL, -1);
3024 g_return_val_if_fail(file != NULL, -1);
3026 if ((fp = fopen(file, "wb")) == NULL) {
3027 FILE_OP_ERROR(file, "fopen");
3037 if (fwrite(str, len, 1, fp) != 1) {
3038 FILE_OP_ERROR(file, "fwrite");
3044 if (fclose(fp) == EOF) {
3045 FILE_OP_ERROR(file, "fclose");
3053 gchar *file_read_to_str(const gchar *file)
3058 g_return_val_if_fail(file != NULL, NULL);
3060 if ((fp = fopen(file, "rb")) == NULL) {
3061 FILE_OP_ERROR(file, "fopen");
3065 str = file_read_stream_to_str(fp);
3072 gchar *file_read_stream_to_str(FILE *fp)
3079 g_return_val_if_fail(fp != NULL, NULL);
3081 array = g_byte_array_new();
3083 while ((n_read = fread(buf, sizeof(gchar), sizeof(buf), fp)) > 0) {
3084 if (n_read < sizeof(buf) && ferror(fp))
3086 g_byte_array_append(array, buf, n_read);
3090 FILE_OP_ERROR("file stream", "fread");
3091 g_byte_array_free(array, TRUE);
3096 g_byte_array_append(array, buf, 1);
3097 str = (gchar *)array->data;
3098 g_byte_array_free(array, FALSE);
3100 if (!g_utf8_validate(str, -1, NULL)) {
3101 const gchar *src_codeset, *dest_codeset;
3103 src_codeset = conv_get_locale_charset_str();
3104 dest_codeset = CS_UTF_8;
3105 tmp = conv_codeset_strdup(str, src_codeset, dest_codeset);
3113 gint execute_async(gchar *const argv[])
3118 if ((pid = fork()) < 0) {
3123 if (pid == 0) { /* child process */
3126 if ((gch_pid = fork()) < 0) {
3131 if (gch_pid == 0) { /* grandchild process */
3132 execvp(argv[0], argv);
3141 waitpid(pid, &status, 0);
3143 if (WIFEXITED(status))
3144 return WEXITSTATUS(status);
3149 gint execute_sync(gchar *const argv[])
3154 if ((pid = fork()) < 0) {
3159 if (pid == 0) { /* child process */
3160 execvp(argv[0], argv);
3166 waitpid(pid, &status, 0);
3168 if (WIFEXITED(status))
3169 return WEXITSTATUS(status);
3174 gint execute_command_line(const gchar *cmdline, gboolean async)
3179 debug_print("executing: %s\n", cmdline);
3181 argv = strsplit_with_quote(cmdline, " ", 0);
3184 ret = execute_async(argv);
3186 ret = execute_sync(argv);
3193 gchar *get_command_output(const gchar *cmdline)
3195 gchar *child_stdout;
3198 g_return_val_if_fail(cmdline != NULL, NULL);
3200 if (g_spawn_command_line_sync(cmdline, &child_stdout, NULL, &status,
3202 g_warning("Can't execute command: %s\n", cmdline);
3206 return child_stdout;
3209 static gint is_unchanged_uri_char(char c)
3221 void encode_uri(gchar *encoded_uri, gint bufsize, const gchar *uri)
3227 for(i = 0; i < strlen(uri) ; i++) {
3228 if (is_unchanged_uri_char(uri[i])) {
3229 if (k + 2 >= bufsize)
3231 encoded_uri[k++] = uri[i];
3234 char * hexa = "0123456789ABCDEF";
3236 if (k + 4 >= bufsize)
3238 encoded_uri[k++] = '%';
3239 encoded_uri[k++] = hexa[uri[i] / 16];
3240 encoded_uri[k++] = hexa[uri[i] % 16];
3246 gint open_uri(const gchar *uri, const gchar *cmdline)
3248 gchar buf[BUFFSIZE];
3250 gchar encoded_uri[BUFFSIZE];
3252 g_return_val_if_fail(uri != NULL, -1);
3254 /* an option to choose whether to use encode_uri or not ? */
3255 encode_uri(encoded_uri, BUFFSIZE, uri);
3258 (p = strchr(cmdline, '%')) && *(p + 1) == 's' &&
3259 !strchr(p + 2, '%'))
3260 g_snprintf(buf, sizeof(buf), cmdline, encoded_uri);
3263 g_warning("Open URI command line is invalid "
3264 "(there must be only one '%%s'): %s",
3266 g_snprintf(buf, sizeof(buf), DEFAULT_BROWSER_CMD, encoded_uri);
3269 execute_command_line(buf, TRUE);
3274 time_t remote_tzoffset_sec(const gchar *zone)
3276 static gchar ustzstr[] = "PSTPDTMSTMDTCSTCDTESTEDT";
3282 time_t remoteoffset;
3284 strncpy(zone3, zone, 3);
3288 if (sscanf(zone, "%c%d", &c, &offset) == 2 &&
3289 (c == '+' || c == '-')) {
3290 remoteoffset = ((offset / 100) * 60 + (offset % 100)) * 60;
3292 remoteoffset = -remoteoffset;
3293 } else if (!strncmp(zone, "UT" , 2) ||
3294 !strncmp(zone, "GMT", 2)) {
3296 } else if (strlen(zone3) == 3) {
3297 for (p = ustzstr; *p != '\0'; p += 3) {
3298 if (!g_ascii_strncasecmp(p, zone3, 3)) {
3299 iustz = ((gint)(p - ustzstr) / 3 + 1) / 2 - 8;
3300 remoteoffset = iustz * 3600;
3306 } else if (strlen(zone3) == 1) {
3308 case 'Z': remoteoffset = 0; break;
3309 case 'A': remoteoffset = -1; break;
3310 case 'B': remoteoffset = -2; break;
3311 case 'C': remoteoffset = -3; break;
3312 case 'D': remoteoffset = -4; break;
3313 case 'E': remoteoffset = -5; break;
3314 case 'F': remoteoffset = -6; break;
3315 case 'G': remoteoffset = -7; break;
3316 case 'H': remoteoffset = -8; break;
3317 case 'I': remoteoffset = -9; break;
3318 case 'K': remoteoffset = -10; break; /* J is not used */
3319 case 'L': remoteoffset = -11; break;
3320 case 'M': remoteoffset = -12; break;
3321 case 'N': remoteoffset = 1; break;
3322 case 'O': remoteoffset = 2; break;
3323 case 'P': remoteoffset = 3; break;
3324 case 'Q': remoteoffset = 4; break;
3325 case 'R': remoteoffset = 5; break;
3326 case 'S': remoteoffset = 6; break;
3327 case 'T': remoteoffset = 7; break;
3328 case 'U': remoteoffset = 8; break;
3329 case 'V': remoteoffset = 9; break;
3330 case 'W': remoteoffset = 10; break;
3331 case 'X': remoteoffset = 11; break;
3332 case 'Y': remoteoffset = 12; break;
3333 default: remoteoffset = 0; break;
3335 remoteoffset = remoteoffset * 3600;
3339 return remoteoffset;
3342 time_t tzoffset_sec(time_t *now)
3348 lt = localtime(now);
3350 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3352 if (lt->tm_year < gmt.tm_year)
3354 else if (lt->tm_year > gmt.tm_year)
3356 else if (lt->tm_yday < gmt.tm_yday)
3358 else if (lt->tm_yday > gmt.tm_yday)
3361 if (off >= 24 * 60) /* should be impossible */
3362 off = 23 * 60 + 59; /* if not, insert silly value */
3363 if (off <= -24 * 60)
3364 off = -(23 * 60 + 59);
3369 /* calculate timezone offset */
3370 gchar *tzoffset(time_t *now)
3372 static gchar offset_string[6];
3378 lt = localtime(now);
3380 off = (lt->tm_hour - gmt.tm_hour) * 60 + lt->tm_min - gmt.tm_min;
3382 if (lt->tm_year < gmt.tm_year)
3384 else if (lt->tm_year > gmt.tm_year)
3386 else if (lt->tm_yday < gmt.tm_yday)
3388 else if (lt->tm_yday > gmt.tm_yday)
3396 if (off >= 24 * 60) /* should be impossible */
3397 off = 23 * 60 + 59; /* if not, insert silly value */
3399 sprintf(offset_string, "%c%02d%02d", sign, off / 60, off % 60);
3401 return offset_string;
3404 void get_rfc822_date(gchar *buf, gint len)
3408 gchar day[4], mon[4];
3409 gint dd, hh, mm, ss, yyyy;
3414 sscanf(asctime(lt), "%3s %3s %d %d:%d:%d %d\n",
3415 day, mon, &dd, &hh, &mm, &ss, &yyyy);
3416 g_snprintf(buf, len, "%s, %d %s %d %02d:%02d:%02d %s",
3417 day, dd, mon, yyyy, hh, mm, ss, tzoffset(&t));
3420 void debug_set_mode(gboolean mode)
3425 gboolean debug_get_mode(void)
3430 void debug_print_real(const gchar *format, ...)
3433 gchar buf[BUFFSIZE];
3435 if (!debug_mode) return;
3437 va_start(args, format);
3438 g_vsnprintf(buf, sizeof(buf), format, args);
3444 void * subject_table_lookup(GHashTable *subject_table, gchar * subject)
3446 if (subject == NULL)
3449 subject += subject_get_prefix_length(subject);
3451 return g_hash_table_lookup(subject_table, subject);
3454 void subject_table_insert(GHashTable *subject_table, gchar * subject,
3457 if (subject == NULL || *subject == 0)
3459 subject += subject_get_prefix_length(subject);
3460 g_hash_table_insert(subject_table, subject, data);
3463 void subject_table_remove(GHashTable *subject_table, gchar * subject)
3465 if (subject == NULL)
3468 subject += subject_get_prefix_length(subject);
3469 g_hash_table_remove(subject_table, subject);
3473 *\brief Check if a string is prefixed with known (combinations)
3474 * of prefixes. The function assumes that each prefix
3475 * is terminated by zero or exactly _one_ space.
3477 *\param str String to check for a prefixes
3479 *\return int Number of chars in the prefix that should be skipped
3480 * for a "clean" subject line. If no prefix was found, 0
3483 int subject_get_prefix_length(const gchar *subject)
3485 /*!< Array with allowable reply prefixes regexps. */
3486 static const gchar * const prefixes[] = {
3487 "Re\\:", /* "Re:" */
3488 "Re\\[[1-9][0-9]*\\]\\:", /* "Re[XXX]:" (non-conforming news mail clients) */
3489 "Antw\\:", /* "Antw:" (Dutch / German Outlook) */
3490 "Aw\\:", /* "Aw:" (German) */
3491 "Antwort\\:", /* "Antwort:" (German Lotus Notes) */
3492 "Res\\:", /* "Res:" (Brazilian Outlook) */
3493 "Fw\\:", /* "Fw:" Forward */
3494 "Enc\\:", /* "Enc:" Forward (Brazilian Outlook) */
3495 "Odp\\:", /* "Odp:" Re (Polish Outlook) */
3496 "Rif\\:" /* "Rif:" (Italian Outlook) */
3499 const int PREFIXES = sizeof prefixes / sizeof prefixes[0];
3502 static regex_t regex;
3503 static gboolean init_;
3505 if (!subject) return 0;
3506 if (!*subject) return 0;
3509 GString *s = g_string_new("");
3511 for (n = 0; n < PREFIXES; n++)
3512 /* Terminate each prefix regexpression by a
3513 * "\ ?" (zero or ONE space), and OR them */
3514 g_string_append_printf(s, "(%s\\ ?)%s",
3519 g_string_prepend(s, "(");
3520 g_string_append(s, ")+"); /* match at least once */
3521 g_string_prepend(s, "^\\ *"); /* from beginning of line */
3524 /* We now have something like "^\ *((PREFIX1\ ?)|(PREFIX2\ ?))+"
3525 * TODO: Should this be "^\ *(((PREFIX1)|(PREFIX2))\ ?)+" ??? */
3526 if (regcomp(®ex, s->str, REG_EXTENDED | REG_ICASE)) {
3527 debug_print("Error compiling regexp %s\n", s->str);
3528 g_string_free(s, TRUE);
3532 g_string_free(s, TRUE);
3536 if (!regexec(®ex, subject, 1, &pos, 0) && pos.rm_so != -1)
3542 guint g_stricase_hash(gconstpointer gptr)
3544 guint hash_result = 0;
3547 for (str = gptr; str && *str; str++) {
3548 if (isupper((guchar)*str)) hash_result += (*str + ' ');
3549 else hash_result += *str;
3555 gint g_stricase_equal(gconstpointer gptr1, gconstpointer gptr2)
3557 const char *str1 = gptr1;
3558 const char *str2 = gptr2;
3560 return !g_utf8_collate(str1, str2);
3563 gint g_int_compare(gconstpointer a, gconstpointer b)
3565 return GPOINTER_TO_INT(a) - GPOINTER_TO_INT(b);
3568 gchar *generate_msgid(gchar *buf, gint len)
3577 addr = g_strconcat("@", get_domain_name(), NULL);
3579 g_snprintf(buf, len, "%04d%02d%02d%02d%02d%02d.%08x%s",
3580 lt->tm_year + 1900, lt->tm_mon + 1,
3581 lt->tm_mday, lt->tm_hour,
3582 lt->tm_min, lt->tm_sec,
3583 (guint) rand(), addr);
3590 quote_cmd_argument()
3592 return a quoted string safely usable in argument of a command.
3594 code is extracted and adapted from etPan! project -- DINH V. Hoà .
3597 gint quote_cmd_argument(gchar * result, guint size,
3607 for(p = path ; * p != '\0' ; p ++) {
3609 if (isalnum((guchar)*p) || (* p == '/')) {
3610 if (remaining > 0) {
3616 result[size - 1] = '\0';
3621 if (remaining >= 2) {
3629 result[size - 1] = '\0';
3634 if (remaining > 0) {
3638 result[size - 1] = '\0';
3652 static void g_node_map_recursive(GNode *node, gpointer data)
3654 GNodeMapData *mapdata = (GNodeMapData *) data;
3656 GNodeMapData newmapdata;
3659 newdata = mapdata->func(node->data, mapdata->data);
3660 if (newdata != NULL) {
3661 newnode = g_node_new(newdata);
3662 g_node_append(mapdata->parent, newnode);
3664 newmapdata.parent = newnode;
3665 newmapdata.func = mapdata->func;
3666 newmapdata.data = mapdata->data;
3668 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &newmapdata);
3672 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data)
3675 GNodeMapData mapdata;
3677 g_return_val_if_fail(node != NULL, NULL);
3678 g_return_val_if_fail(func != NULL, NULL);
3680 root = g_node_new(func(node->data, data));
3682 mapdata.parent = root;
3683 mapdata.func = func;
3684 mapdata.data = data;
3686 g_node_children_foreach(node, G_TRAVERSE_ALL, g_node_map_recursive, &mapdata);
3691 #define HEX_TO_INT(val, hex) \
3695 if ('0' <= c && c <= '9') { \
3697 } else if ('a' <= c && c <= 'f') { \
3698 val = c - 'a' + 10; \
3699 } else if ('A' <= c && c <= 'F') { \
3700 val = c - 'A' + 10; \
3706 gboolean get_hex_value(guchar *out, gchar c1, gchar c2)
3713 if (hi == -1 || lo == -1)
3716 *out = (hi << 4) + lo;
3720 #define INT_TO_HEX(hex, val) \
3723 hex = '0' + (val); \
3725 hex = 'A' + (val) - 10; \
3728 void get_hex_str(gchar *out, guchar ch)
3732 INT_TO_HEX(hex, ch >> 4);
3734 INT_TO_HEX(hex, ch & 0x0f);
3740 #define G_PRINT_REF 1 == 1 ? (void) 0 : (void)
3742 #define G_PRINT_REF g_print
3746 *\brief Register ref counted pointer. It is based on GBoxed, so should
3747 * work with anything that uses the GType system. The semantics
3748 * are similar to a C++ auto pointer, with the exception that
3749 * C doesn't have automatic closure (calling destructors) when
3750 * exiting a block scope.
3751 * Use the \ref G_TYPE_AUTO_POINTER macro instead of calling this
3752 * function directly.
3754 *\return GType A GType type.
3756 GType g_auto_pointer_register(void)
3758 static GType auto_pointer_type;
3759 if (!auto_pointer_type)
3761 g_boxed_type_register_static
3762 ("G_TYPE_AUTO_POINTER",
3763 (GBoxedCopyFunc) g_auto_pointer_copy,
3764 (GBoxedFreeFunc) g_auto_pointer_free);
3765 return auto_pointer_type;
3769 *\brief Structure with g_new() allocated pointer guarded by the
3772 typedef struct AutoPointerRef {
3773 void (*free) (gpointer);
3779 *\brief The auto pointer opaque structure that references the
3780 * pointer guard block.
3782 typedef struct AutoPointer {
3783 AutoPointerRef *ref;
3784 gpointer ptr; /*!< access to protected pointer */
3788 *\brief Creates an auto pointer for a g_new()ed pointer. Example:
3792 * ... tell gtk_list_store it should use a G_TYPE_AUTO_POINTER
3793 * ... when assigning, copying and freeing storage elements
3795 * gtk_list_store_new(N_S_COLUMNS,
3796 * G_TYPE_AUTO_POINTER,
3800 * Template *precious_data = g_new0(Template, 1);
3801 * g_pointer protect = g_auto_pointer_new(precious_data);
3803 * gtk_list_store_set(container, &iter,
3807 * ... the gtk_list_store has copied the pointer and
3808 * ... incremented its reference count, we should free
3809 * ... the auto pointer (in C++ a destructor would do
3810 * ... this for us when leaving block scope)
3812 * g_auto_pointer_free(protect);
3814 * ... gtk_list_store_set() now manages the data. When
3815 * ... *explicitly* requesting a pointer from the list
3816 * ... store, don't forget you get a copy that should be
3817 * ... freed with g_auto_pointer_free() eventually.
3821 *\param pointer Pointer to be guarded.
3823 *\return GAuto * Pointer that should be used in containers with
3826 GAuto *g_auto_pointer_new(gpointer p)
3828 AutoPointerRef *ref;
3834 ref = g_new0(AutoPointerRef, 1);
3835 ptr = g_new0(AutoPointer, 1);
3845 G_PRINT_REF ("XXXX ALLOC(%lx)\n", p);
3851 *\brief Allocate an autopointer using the passed \a free function to
3852 * free the guarded pointer
3854 GAuto *g_auto_pointer_new_with_free(gpointer p, GFreeFunc free_)
3861 aptr = g_auto_pointer_new(p);
3862 aptr->ref->free = free_;
3866 gpointer g_auto_pointer_get_ptr(GAuto *auto_ptr)
3868 if (auto_ptr == NULL)
3870 return ((AutoPointer *) auto_ptr)->ptr;
3874 *\brief Copies an auto pointer by. It's mostly not necessary
3875 * to call this function directly, unless you copy/assign
3876 * the guarded pointer.
3878 *\param auto_ptr Auto pointer returned by previous call to
3879 * g_auto_pointer_new_XXX()
3881 *\return gpointer An auto pointer
3883 GAuto *g_auto_pointer_copy(GAuto *auto_ptr)
3886 AutoPointerRef *ref;
3889 if (auto_ptr == NULL)
3894 newp = g_new0(AutoPointer, 1);
3897 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) {
3922 G_PRINT_REF ("XXXX FREE(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);
3924 ref->free(ref->pointer);
3929 G_PRINT_REF ("XXXX DEREF(%lx) -- REF (%d)\n", ref->pointer, ref->cnt);