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