Fix use after free
[claws.git] / src / common / utils.h
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 1999-2014 Hiroyuki Yamamoto and the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
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.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  *
18  * The code of the g_utf8_substring function below is owned by
19  * Matthias Clasen <matthiasc@src.gnome.org>/<mclasen@redhat.com>
20  * and is got from GLIB 2.30
21  *
22  */
23
24 #ifndef __UTILS_H__
25 #define __UTILS_H__
26
27 #ifdef HAVE_CONFIG_H
28 #include "claws-features.h"
29 #endif
30
31 #ifdef HAVE_BACKTRACE
32 #include <execinfo.h>
33 #endif
34
35 #include <glib.h>
36 #include <glib-object.h>
37 #include <stdio.h>
38 #include <string.h>
39 #include <stdlib.h>
40 #include <unistd.h>
41 #include <sys/types.h>
42 #include <dirent.h>
43 #include <time.h>
44 #if HAVE_ALLOCA_H
45 #  include <alloca.h>
46 #endif
47 #if HAVE_WCHAR_H
48 #  include <wchar.h>
49 #endif
50
51 /* The Hurd doesn't have this limit */
52 #ifndef PATH_MAX
53   #define PATH_MAX 4196
54 #endif
55
56 #ifdef G_OS_WIN32
57
58 #define fsync _commit
59
60 #define pipe(phandles)  _pipe (phandles, 4096, _O_BINARY)
61 #endif
62 /* Wrappers for C library function that take pathname arguments. */
63 #  include <glib/gstdio.h>
64
65 /* why is this sometimes undefined !? */
66 #ifndef G_MAXOFFSET
67 typedef gint64 goffset;
68 #define G_MINOFFSET     G_MININT64
69 #define G_MAXOFFSET     G_MAXINT64
70 #endif
71
72 #ifndef HAVE_U32_TYPEDEF
73   #undef u32        /* maybe there is a macro with this name */
74   typedef guint32 u32;
75   #define HAVE_U32_TYPEDEF
76 #endif
77
78 #ifndef BIG_ENDIAN_HOST
79   #if (G_BYTE_ORDER == G_BIG_ENDIAN)
80     #define BIG_ENDIAN_HOST 1
81   #endif
82 #endif
83
84 #define CHDIR_RETURN_IF_FAIL(dir) \
85 { \
86         if (change_dir(dir) < 0) return; \
87 }
88
89 #define CHDIR_RETURN_VAL_IF_FAIL(dir, val) \
90 { \
91         if (change_dir(dir) < 0) return val; \
92 }
93
94 #define CHDIR_EXEC_CODE_RETURN_VAL_IF_FAIL(dir, val, code) \
95 { \
96         if (change_dir(dir) < 0) { \
97                 code \
98                 return val; \
99         } \
100 }
101
102 #define Xalloca(ptr, size, iffail) \
103 { \
104         if ((ptr = alloca(size)) == NULL) { \
105                 g_warning("can't allocate memory\n"); \
106                 iffail; \
107         } \
108 }
109
110 #define Xstrdup_a(ptr, str, iffail) \
111 { \
112         gchar *__tmp; \
113  \
114         if ((__tmp = alloca(strlen(str) + 1)) == NULL) { \
115                 g_warning("can't allocate memory\n"); \
116                 iffail; \
117         } else \
118                 strcpy(__tmp, str); \
119  \
120         ptr = __tmp; \
121 }
122
123 #define Xstrndup_a(ptr, str, len, iffail) \
124 { \
125         gchar *__tmp; \
126  \
127         if ((__tmp = alloca(len + 1)) == NULL) { \
128                 g_warning("can't allocate memory\n"); \
129                 iffail; \
130         } else { \
131                 strncpy(__tmp, str, len); \
132                 __tmp[len] = '\0'; \
133         } \
134  \
135         ptr = __tmp; \
136 }
137
138 #define Xstrcat_a(ptr, str1, str2, iffail) \
139 { \
140         gchar *__tmp; \
141         gint len1, len2; \
142  \
143         len1 = strlen(str1); \
144         len2 = strlen(str2); \
145         if ((__tmp = alloca(len1 + len2 + 1)) == NULL) { \
146                 g_warning("can't allocate memory\n"); \
147                 iffail; \
148         } else { \
149                 memcpy(__tmp, str1, len1); \
150                 memcpy(__tmp + len1, str2, len2 + 1); \
151         } \
152  \
153         ptr = __tmp; \
154 }
155
156 #define AUTORELEASE_STR(str, iffail) \
157 { \
158         gchar *__str; \
159         Xstrdup_a(__str, str, iffail); \
160         g_free(str); \
161         str = __str; \
162 }
163
164 #define FILE_OP_ERROR(file, func) \
165 { \
166         g_printerr("%s: ", file); \
167         fflush(stderr); \
168         perror(func); \
169 }
170
171 #define IS_ASCII(c) (((guchar) c) <= 0177 ? 1 : 0)
172
173 /* from NetworkManager */
174 #if (defined(HAVE_BACKTRACE) && !defined(__FreeBSD__))
175 #define print_backtrace()                                               \
176 G_STMT_START                                                            \
177 {                                                                       \
178         void *_call_stack[512];                                         \
179         int  _call_stack_size;                                          \
180         char **_symbols;                                                \
181         _call_stack_size = backtrace (_call_stack,                      \
182                                       G_N_ELEMENTS (_call_stack));      \
183         _symbols = backtrace_symbols (_call_stack, _call_stack_size);   \
184         if (_symbols != NULL)                                           \
185         {                                                               \
186                 int _i;                                                 \
187                 _i = 0;                                                 \
188                 g_print ("traceback:\n");                               \
189                 while (_i < _call_stack_size)                           \
190                 {                                                       \
191                         g_print ("%d:\t%s\n", _i, _symbols[_i]);        \
192                         _i++;                                           \
193                 }                                                       \
194                 free (_symbols);                                        \
195         }                                                               \
196 }                                                                       \
197 G_STMT_END
198 #else
199 #define print_backtrace()                                               \
200 G_STMT_START                                                            \
201 {                                                                       \
202 }                                                                       \
203 G_STMT_END
204 #endif
205
206
207 #define cm_return_val_if_fail(expr,val) G_STMT_START {                  \
208         if (!(expr)) {                                                  \
209                 g_print("%s:%d Condition %s failed\n", __FILE__, __LINE__, #expr);\
210                 print_backtrace();                                      \
211                 g_print("\n");                                          \
212                 return val;                                             \
213         }                                                               \
214 } G_STMT_END
215
216 #define cm_return_if_fail(expr) G_STMT_START {                          \
217         if (!(expr)) {                                                  \
218                 g_print("%s:%d Condition %s failed\n", __FILE__, __LINE__, #expr);\
219                 print_backtrace();                                      \
220                 g_print("\n");                                          \
221                 return;                                                 \
222         }                                                               \
223 } G_STMT_END
224
225 #ifndef MIN
226         #define MIN(a, b) ((a) < (b) ? (a) : (b))
227 #endif
228 #ifndef MAX
229         #define MAX(a, b) ((a) > (b) ? (a) : (b))
230 #endif
231
232 #ifdef __cplusplus
233 extern "C" {
234 #endif
235
236 typedef gpointer (*GNodeMapFunc)        (gpointer nodedata, gpointer data);
237
238 /* debug functions */
239 void debug_set_mode             (gboolean mode);
240 gboolean debug_get_mode         (void);
241
242 #ifndef __CYGWIN__
243 #define debug_print \
244         debug_print_real("%s:%d:", debug_srcname(__FILE__), __LINE__), \
245         debug_print_real
246 #else
247   /* FIXME: cygwin: why debug_srcname couldn't be resolved in library? */
248 #define debug_print \
249         debug_print_real("%s:%d:", __FILE__, __LINE__), \
250         debug_print_real
251 #endif
252
253 /* for macro expansion */
254 #define Str(x)  #x
255 #define Xstr(x) Str(x)
256
257
258 /* System related stuff.  */
259
260 gboolean superuser_p (void);
261
262 /* List utilities. */
263
264 GSList *slist_copy_deep         (GSList         *list,
265                                  GCopyFunc       func);
266
267 /* String utilities.  */
268
269 void list_free_strings          (GList          *list);
270 void slist_free_strings         (GSList         *list);
271 void slist_free_strings_full    (GSList         *list);
272
273 void hash_free_strings          (GHashTable     *table);
274
275 gint str_case_equal             (gconstpointer   v,
276                                  gconstpointer   v2);
277 guint str_case_hash             (gconstpointer   key);
278
279 void ptr_array_free_strings     (GPtrArray      *array);
280
281 /* number-string conversion */
282 gint to_number                  (const gchar *nstr);
283 gchar *itos_buf                 (gchar       *nstr,
284                                  gint         n);
285 gchar *itos                     (gint         n);
286 gchar *to_human_readable        (goffset      size);
287
288 /* alternative string functions */
289 gint strcmp2            (const gchar    *s1,
290                          const gchar    *s2);
291 gchar *strstr2          (const gchar    *s1,
292                          const gchar    *s2);
293 gint path_cmp           (const gchar    *s1,
294                          const gchar    *s2);
295 gchar *strretchomp      (gchar          *str);
296 gchar *strtailchomp     (gchar          *str,
297                          gchar           tail_char);
298 gchar *strcrchomp       (gchar          *str);
299 gint file_strip_crs     (const gchar    *file);
300 gchar *strcasestr       (const gchar    *haystack,
301                          const gchar    *needle);
302 gchar *strncasestr      (const gchar    *haystack,
303                          gint            haystack_len,
304                          const gchar    *needle);
305 gpointer my_memmem      (gconstpointer   haystack,
306                          size_t          haystacklen,
307                          gconstpointer   needle,
308                          size_t          needlelen);
309 gchar *strncpy2         (gchar          *dest,
310                          const gchar    *src,
311                          size_t          n);
312
313 gboolean is_next_nonascii       (const gchar *s);
314 gint get_next_word_len          (const gchar *s);
315
316 /* functions for string parsing */
317 gint subject_compare                    (const gchar    *s1,
318                                          const gchar    *s2);
319 gint subject_compare_for_sort           (const gchar    *s1,
320                                          const gchar    *s2);
321 void trim_subject                       (gchar          *str);
322 void eliminate_parenthesis              (gchar          *str,
323                                          gchar           op,
324                                          gchar           cl);
325 void extract_parenthesis                (gchar          *str,
326                                          gchar           op,
327                                          gchar           cl);
328
329 void extract_quote                      (gchar          *str,
330                                          gchar           quote_chr);
331 gchar *escape_internal_quotes           (gchar          *str,
332                                          gchar           quote_chr);
333 void eliminate_address_comment          (gchar          *str);
334 gchar *strchr_with_skip_quote           (const gchar    *str,
335                                          gint            quote_chr,
336                                          gint            c);
337 void extract_address                    (gchar          *str);
338 void extract_list_id_str                (gchar          *str);
339
340 GSList *address_list_append             (GSList         *addr_list,
341                                          const gchar    *str);
342 GSList *address_list_append_with_comments(GSList        *addr_list,
343                                          const gchar    *str);
344 GSList *references_list_prepend         (GSList         *msgid_list,
345                                          const gchar    *str);
346 GSList *references_list_append          (GSList         *msgid_list,
347                                          const gchar    *str);
348 GSList *newsgroup_list_append           (GSList         *group_list,
349                                          const gchar    *str);
350
351 GList *add_history                      (GList          *list,
352                                          const gchar    *str);
353
354 void remove_return                      (gchar          *str);
355 void remove_space                       (gchar          *str);
356 void unfold_line                        (gchar          *str);
357 void subst_char                         (gchar          *str,
358                                          gchar           orig,
359                                          gchar           subst);
360 void subst_chars                        (gchar          *str,   
361                                          gchar          *orig, 
362                                          gchar          subst);
363 void subst_for_filename                 (gchar          *str);
364 void subst_for_shellsafe_filename       (gchar          *str);
365 gboolean is_ascii_str                   (const gchar    *str);
366 gint get_quote_level                    (const gchar    *str,
367                                          const gchar    *quote_chars);
368 gint check_line_length                  (const gchar    *str,
369                                          gint            max_chars,
370                                          gint           *line);
371
372 gchar **strsplit_with_quote             (const gchar    *str,
373                                          const gchar    *delim,
374                                          gint            max_tokens);
375
376 gchar *get_abbrev_newsgroup_name        (const gchar    *group,
377                                          gint            len);
378 gchar *trim_string                      (const gchar    *str,
379                                          gint            len);
380
381 GList *uri_list_extract_filenames       (const gchar    *uri_list);
382 gboolean is_uri_string                  (const gchar    *str);
383 gchar *get_uri_path                     (const gchar    *uri);
384 gint get_uri_len                        (const gchar    *str);
385 void decode_uri                         (gchar          *decoded_uri,
386                                          const gchar    *encoded_uri);
387 void decode_uri_with_plus               (gchar          *decoded_uri, 
388                                          const gchar    *encoded_uri, 
389                                          gboolean        with_plus);
390 gint scan_mailto_url                    (const gchar    *mailto,
391                                          gchar         **from,
392                                          gchar         **to,
393                                          gchar         **cc,
394                                          gchar         **bcc,
395                                          gchar         **subject,
396                                          gchar         **body,
397                                          gchar         ***attach,
398                                          gchar         **inreplyto);
399
400 /* return static strings */
401 const gchar *get_home_dir               (void);
402 const gchar *get_rc_dir                 (void);
403 void  set_rc_dir                        (const gchar *dir);
404 gboolean rc_dir_is_alt                  (void);
405 const gchar *get_mail_base_dir          (void);
406 const gchar *get_news_cache_dir         (void);
407 const gchar *get_imap_cache_dir         (void);
408 const gchar *get_mime_tmp_dir           (void);
409 const gchar *get_template_dir           (void);
410 const gchar *get_plugin_dir             (void);
411 const gchar *get_tmp_dir                (void);
412 const gchar *get_locale_dir             (void);
413 gchar *get_tmp_file                     (void);
414 const gchar *get_domain_name            (void);
415 const gchar *get_desktop_file(void);
416 #ifdef G_OS_WIN32
417 const gchar *get_themes_dir             (void);
418 const gchar *get_cert_file              (void);
419 #endif
420 /* file / directory handling */
421 off_t get_file_size             (const gchar    *file);
422 off_t get_file_size_as_crlf     (const gchar    *file);
423
424 time_t get_file_mtime           (const gchar *file);
425
426 gboolean file_exist             (const gchar    *file,
427                                  gboolean        allow_fifo);
428 gboolean is_relative_filename   (const gchar *file);
429 gboolean is_dir_exist           (const gchar    *dir);
430 gboolean is_file_entry_exist    (const gchar    *file);
431 gboolean dirent_is_regular_file (struct dirent  *d);
432
433 #define is_file_exist(file)             file_exist(file, FALSE)
434 #define is_file_or_fifo_exist(file)     file_exist(file, TRUE)
435
436 gint change_dir                 (const gchar    *dir);
437 gint make_dir                   (const gchar    *dir);
438 gint make_dir_hier              (const gchar    *dir);
439 gint remove_all_files           (const gchar    *dir);
440 gint remove_numbered_files      (const gchar    *dir,
441                                  guint           first,
442                                  guint           last);
443 gint remove_numbered_files_not_in_list(const gchar *dir,
444                                        GSList *numberlist);
445 gint remove_all_numbered_files  (const gchar    *dir);
446 gint remove_dir_recursive       (const gchar    *dir);
447 gint append_file                (const gchar    *src,
448                                  const gchar    *dest,
449                                  gboolean        keep_backup);
450 gint rename_force               (const gchar    *oldpath,
451                                  const gchar    *newpath);
452 gint copy_file                  (const gchar    *src,
453                                  const gchar    *dest,
454                                  gboolean        keep_backup);
455 gint move_file                  (const gchar    *src,
456                                  const gchar    *dest,
457                                  gboolean        overwrite);
458 gint copy_dir                   (const gchar    *src,
459                                  const gchar    *dest);
460 gint copy_file_part_to_fp       (FILE           *fp,
461                                  off_t           offset,
462                                  size_t          length,
463                                  FILE           *dest_fp);
464 gint copy_file_part             (FILE           *fp,
465                                  off_t           offset,
466                                  size_t          length,
467                                  const gchar    *dest);
468
469 gchar *canonicalize_str         (const gchar    *str);
470 gint canonicalize_file          (const gchar    *src,
471                                  const gchar    *dest);
472 gint canonicalize_file_replace  (const gchar    *file);
473
474 gchar *normalize_newlines       (const gchar    *str);
475
476 gchar *get_outgoing_rfc2822_str (FILE           *fp);
477
478 gint change_file_mode_rw        (FILE           *fp,
479                                  const gchar    *file);
480 FILE *my_tmpfile                (void);
481 FILE *get_tmpfile_in_dir        (const gchar    *dir,
482                                  gchar         **filename);
483 FILE *str_open_as_stream        (const gchar    *str);
484 gint str_write_to_file          (const gchar    *str,
485                                  const gchar    *file);
486 gchar *file_read_to_str         (const gchar    *file);
487 gchar *file_read_stream_to_str  (FILE           *fp);
488 gchar *file_read_to_str_no_recode(const gchar *file);
489 gchar *file_read_stream_to_str_no_recode(FILE *fp);
490
491 char *fgets_crlf(char *buf, int size, FILE *stream);
492
493 /* process execution */
494 gint execute_command_line       (const gchar    *cmdline,
495                                  gboolean        async);
496 gchar *get_command_output       (const gchar    *cmdline);
497
498 /* open URI with external browser */
499 gint open_uri(const gchar *uri, const gchar *cmdline);
500 /* open file with text editor */
501 gint open_txt_editor(const gchar *filepath, const gchar *cmdline);
502
503 /* time functions */
504 time_t remote_tzoffset_sec      (const gchar    *zone);
505 time_t tzoffset_sec             (time_t         *now);
506 gchar *tzoffset                 (time_t         *now);
507 void get_rfc822_date            (gchar          *buf,
508                                  gint            len);
509
510 size_t fast_strftime            (gchar                  *buf, 
511                                  gint                    buflen, 
512                                  const gchar            *format, 
513                                  struct tm              *lt);
514
515 /* debugging */
516 void debug_print_real   (const gchar *format, ...) G_GNUC_PRINTF(1, 2);
517 const char * debug_srcname (const char *file);
518
519 /* subject threading */
520 void * subject_table_lookup(GHashTable *subject_table, gchar * subject);
521 void subject_table_insert(GHashTable *subject_table, gchar * subject,
522                           void * data);
523 void subject_table_remove(GHashTable *subject_table, gchar * subject);
524 void utils_free_regex(void);
525 gint subject_get_prefix_length (const gchar *subject);
526
527 /* quoting recognition */
528 const gchar * line_has_quote_char       (const gchar *str,
529                                          const gchar *quote_chars);
530
531 gint g_int_compare      (gconstpointer a, gconstpointer b);
532
533 gchar *generate_msgid           (gchar *buf, gint len, gchar *user_addr);
534 gchar *generate_mime_boundary   (const gchar *prefix);
535
536 gint quote_cmd_argument(gchar * result, guint size,
537                         const gchar * path);
538 GNode *g_node_map(GNode *node, GNodeMapFunc func, gpointer data);
539
540 gboolean get_hex_value(guchar *out, gchar c1, gchar c2);
541 void get_hex_str(gchar *out, guchar ch);
542
543 /* auto pointer for containers that support GType system */
544
545 #define G_TYPE_AUTO_POINTER     g_auto_pointer_register()
546 typedef struct AutoPointer      GAuto;
547 GType g_auto_pointer_register           (void);
548 GAuto *g_auto_pointer_new               (gpointer pointer);
549 GAuto *g_auto_pointer_new_with_free     (gpointer p, 
550                                          GFreeFunc free);
551 gpointer g_auto_pointer_get_ptr         (GAuto *auto_ptr);
552 GAuto *g_auto_pointer_copy              (GAuto *auto_ptr);
553 void g_auto_pointer_free                (GAuto *auto_ptr);
554 void replace_returns                    (gchar *str);
555 gboolean get_uri_part   (const gchar *start,
556                          const gchar *scanpos,
557                          const gchar **bp,
558                          const gchar **ep,
559                          gboolean hdr);
560 gchar *make_uri_string  (const gchar *bp,
561                          const gchar *ep);
562 gboolean get_email_part (const gchar *start, 
563                          const gchar *scanpos,
564                          const gchar **bp, 
565                          const gchar **ep,
566                          gboolean hdr);
567 gchar *make_email_string(const gchar *bp,
568                          const gchar *ep);
569 gchar *make_http_string (const gchar *bp,
570                          const gchar *ep);
571
572 gchar *mailcap_get_command_for_type(const gchar *type, 
573                                     const gchar *file_to_open);
574 void mailcap_update_default        (const gchar *type,
575                                     const gchar *command);
576
577 gboolean file_is_email(const gchar *filename);
578 gboolean sc_g_list_bigger(GList *list, gint max);
579 gboolean sc_g_slist_bigger(GSList *list, gint max);
580
581 int claws_unlink(const gchar *filename);
582
583 GMutex *cm_mutex_new(void);
584 void cm_mutex_free(GMutex *mutex);
585
586 int cm_canonicalize_filename(const gchar *filename, gchar **canonical_name);
587
588 #if !GLIB_CHECK_VERSION(2, 30, 0)
589 gchar   *g_utf8_substring         (const gchar *p,
590                                    glong        start_pos,
591                                    glong        end_pos) G_GNUC_MALLOC;
592 #endif
593
594 #ifdef __cplusplus
595 }
596 #endif
597
598 #endif /* __UTILS_H__ */