2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2006, Digium, Inc.
6 * Steve Murphy <murf@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
22 * A condensation of the pbx_config stuff, to read into exensions.conf, and provide an interface to the data there,
23 * for operations outside of asterisk. A huge, awful hack.
27 #include "asterisk/autoconfig.h"
36 #include <sys/types.h>
38 #include <sys/resource.h>
44 #if !defined(SOLARIS) && !defined(__CYGWIN__)
51 #include <sys/param.h>
52 #define ASINCLUDE_GLOB 1
53 #ifdef AST_INCLUDE_GLOB
54 #if defined(__Darwin__) || defined(__CYGWIN__)
55 #define GLOB_ABORTED GLOB_ABEND
60 static char ast_config_AST_CONFIG_DIR[PATH_MAX] = {"/etc/asterisk"};
61 #define AST_API_MODULE 1 /* gimme the inline defs! */
64 char x; /* basically empty! */
69 #include "asterisk/inline_api.h"
70 #include "asterisk/compat.h"
71 #include "asterisk/compiler.h"
72 #include "asterisk/endian.h"
73 #include "asterisk/ast_expr.h"
74 #include "asterisk/ael_structs.h"
75 #include "asterisk/pval.h"
78 #define EVENTLOG "event_log"
79 #define QUEUELOG "queue_log"
81 #define DEBUG_M(a) { \
85 #define VERBOSE_PREFIX_1 " "
86 #define VERBOSE_PREFIX_2 " == "
87 #define VERBOSE_PREFIX_3 " -- "
88 #define VERBOSE_PREFIX_4 " > "
90 /* IN CONFLICT: void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
91 __attribute__ ((format (printf, 5, 6))); */
93 static void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...) __attribute__ ((format (printf,5,6)));
96 void ast_backtrace(void);
98 void ast_queue_log(const char *queuename, const char *callid, const char *agent, const char *event, const char *fmt, ...)
99 __attribute__ ((format (printf, 5, 6)));
101 /* IN CONFLICT: void ast_verbose(const char *fmt, ...)
102 __attribute__ ((format (printf, 1, 2))); */
104 int ast_register_verbose(void (*verboser)(const char *string));
105 int ast_unregister_verbose(void (*verboser)(const char *string));
107 void ast_console_puts(const char *string);
109 void ast_console_puts_mutable(const char *string);
110 void ast_console_toggle_mute(int fd);
112 #define _A_ __FILE__, __LINE__, __PRETTY_FUNCTION__
117 #define __LOG_DEBUG 0
118 #define LOG_DEBUG __LOG_DEBUG, _A_
123 #define __LOG_EVENT 1
124 #define LOG_EVENT __LOG_EVENT, _A_
129 #define __LOG_NOTICE 2
130 #define LOG_NOTICE __LOG_NOTICE, _A_
135 #define __LOG_WARNING 3
136 #define LOG_WARNING __LOG_WARNING, _A_
141 #define __LOG_ERROR 4
142 #define LOG_ERROR __LOG_ERROR, _A_
147 #define __LOG_VERBOSE 5
148 #define LOG_VERBOSE __LOG_VERBOSE, _A_
154 #define LOG_DTMF __LOG_DTMF, _A_
158 static unsigned int __unsigned_int_flags_dummy;
160 struct ast_flags { /* stolen from utils.h */
163 #define ast_test_flag(p,flag) ({ \
164 typeof ((p)->flags) __p = (p)->flags; \
165 typeof (__unsigned_int_flags_dummy) __x = 0; \
166 (void) (&__p == &__x); \
167 ((p)->flags & (flag)); \
170 #define ast_set2_flag(p,value,flag) do { \
171 typeof ((p)->flags) __p = (p)->flags; \
172 typeof (__unsigned_int_flags_dummy) __x = 0; \
173 (void) (&__p == &__x); \
175 (p)->flags |= (flag); \
177 (p)->flags &= ~(flag); \
181 #ifdef __AST_DEBUG_MALLOC
182 static void ast_free(void *ptr) attribute_unused;
183 static void ast_free(void *ptr)
188 #define ast_free free
191 #ifndef __AST_DEBUG_MALLOC
193 #define MALLOC_FAILURE_MSG \
194 ast_log(LOG_ERROR, "Memory Allocation Failure in function %s at line %d of %s\n", func, lineno, file);
196 * \brief A wrapper for malloc()
198 * ast_malloc() is a wrapper for malloc() that will generate an Asterisk log
199 * message in the case that the allocation fails.
201 * The argument and return value are the same as malloc()
203 #define ast_malloc(len) \
204 _ast_malloc((len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
207 void * attribute_malloc _ast_malloc(size_t len, const char *file, int lineno, const char *func),
211 if (!(p = malloc(len)))
219 * \brief A wrapper for calloc()
221 * ast_calloc() is a wrapper for calloc() that will generate an Asterisk log
222 * message in the case that the allocation fails.
224 * The arguments and return value are the same as calloc()
226 #define ast_calloc(num, len) \
227 _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
230 void * attribute_malloc _ast_calloc(size_t num, size_t len, const char *file, int lineno, const char *func),
234 if (!(p = calloc(num, len)))
242 * \brief A wrapper for calloc() for use in cache pools
244 * ast_calloc_cache() is a wrapper for calloc() that will generate an Asterisk log
245 * message in the case that the allocation fails. When memory debugging is in use,
246 * the memory allocated by this function will be marked as 'cache' so it can be
247 * distinguished from normal memory allocations.
249 * The arguments and return value are the same as calloc()
251 #define ast_calloc_cache(num, len) \
252 _ast_calloc((num), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
255 * \brief A wrapper for realloc()
257 * ast_realloc() is a wrapper for realloc() that will generate an Asterisk log
258 * message in the case that the allocation fails.
260 * The arguments and return value are the same as realloc()
262 #define ast_realloc(p, len) \
263 _ast_realloc((p), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
266 void * attribute_malloc _ast_realloc(void *p, size_t len, const char *file, int lineno, const char *func),
270 if (!(newp = realloc(p, len)))
278 * \brief A wrapper for strdup()
280 * ast_strdup() is a wrapper for strdup() that will generate an Asterisk log
281 * message in the case that the allocation fails.
283 * ast_strdup(), unlike strdup(), can safely accept a NULL argument. If a NULL
284 * argument is provided, ast_strdup will return NULL without generating any
285 * kind of error log message.
287 * The argument and return value are the same as strdup()
289 #define ast_strdup(str) \
290 _ast_strdup((str), __FILE__, __LINE__, __PRETTY_FUNCTION__)
293 char * attribute_malloc _ast_strdup(const char *str, const char *file, int lineno, const char *func),
298 if (!(newstr = strdup(str)))
307 * \brief A wrapper for strndup()
309 * ast_strndup() is a wrapper for strndup() that will generate an Asterisk log
310 * message in the case that the allocation fails.
312 * ast_strndup(), unlike strndup(), can safely accept a NULL argument for the
313 * string to duplicate. If a NULL argument is provided, ast_strdup will return
314 * NULL without generating any kind of error log message.
316 * The arguments and return value are the same as strndup()
318 #define ast_strndup(str, len) \
319 _ast_strndup((str), (len), __FILE__, __LINE__, __PRETTY_FUNCTION__)
322 char * attribute_malloc _ast_strndup(const char *str, size_t len, const char *file, int lineno, const char *func),
327 if (!(newstr = strndup(str, len)))
336 * \brief A wrapper for asprintf()
338 * ast_asprintf() is a wrapper for asprintf() that will generate an Asterisk log
339 * message in the case that the allocation fails.
341 * The arguments and return value are the same as asprintf()
343 #define ast_asprintf(ret, fmt, ...) \
344 _ast_asprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, fmt, __VA_ARGS__)
347 int _ast_asprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, ...),
353 if ((res = vasprintf(ret, fmt, ap)) == -1)
362 * \brief A wrapper for vasprintf()
364 * ast_vasprintf() is a wrapper for vasprintf() that will generate an Asterisk log
365 * message in the case that the allocation fails.
367 * The arguments and return value are the same as vasprintf()
369 #define ast_vasprintf(ret, fmt, ap) \
370 _ast_vasprintf((ret), __FILE__, __LINE__, __PRETTY_FUNCTION__, (fmt), (ap))
373 int _ast_vasprintf(char **ret, const char *file, int lineno, const char *func, const char *fmt, va_list ap),
377 if ((res = vasprintf(ret, fmt, ap)) == -1)
386 /* If astmm is in use, let it handle these. Otherwise, it will report that
387 all allocations are coming from this header file */
389 #define ast_malloc(a) malloc(a)
390 #define ast_calloc(a,b) calloc(a,b)
391 #define ast_realloc(a,b) realloc(a,b)
392 #define ast_strdup(a) strdup(a)
393 #define ast_strndup(a,b) strndup(a,b)
394 #define ast_asprintf(a,b,c) asprintf(a,b,c)
395 #define ast_vasprintf(a,b,c) vasprintf(a,b,c)
397 #endif /* AST_DEBUG_MALLOC */
399 #if !defined(ast_strdupa) && defined(__GNUC__)
401 \brief duplicate a string in memory from the stack
402 \param s The string to duplicate
404 This macro will duplicate the given string. It returns a pointer to the stack
405 allocatted memory for the new string.
407 #define ast_strdupa(s) \
410 const char *__old = (s); \
411 size_t __len = strlen(__old) + 1; \
412 char *__new = __builtin_alloca(__len); \
413 memcpy (__new, __old, __len); \
421 #define MAX_NESTED_COMMENTS 128
422 #define COMMENT_START ";--"
423 #define COMMENT_END "--;"
424 #define COMMENT_META ';'
425 #define COMMENT_TAG '-'
427 static char *extconfig_conf = "extconfig.conf";
429 /*! Growable string buffer */
430 static char *comment_buffer; /*!< this will be a comment collector.*/
431 static int comment_buffer_size; /*!< the amount of storage so far alloc'd for the comment_buffer */
433 static char *lline_buffer; /*!< A buffer for stuff behind the ; */
434 static int lline_buffer_size;
439 struct ast_comment *next;
443 static void CB_INIT(void)
445 if (!comment_buffer) {
446 comment_buffer = ast_malloc(CB_INCR);
449 comment_buffer[0] = 0;
450 comment_buffer_size = CB_INCR;
451 lline_buffer = ast_malloc(CB_INCR);
455 lline_buffer_size = CB_INCR;
457 comment_buffer[0] = 0;
462 static void CB_ADD(char *str)
464 int rem = comment_buffer_size - strlen(comment_buffer) - 1;
465 int siz = strlen(str);
467 comment_buffer = ast_realloc(comment_buffer, comment_buffer_size + CB_INCR + siz + 1);
470 comment_buffer_size += CB_INCR+siz+1;
472 strcat(comment_buffer,str);
475 static void CB_ADD_LEN(char *str, int len)
477 int cbl = strlen(comment_buffer) + 1;
478 int rem = comment_buffer_size - cbl;
480 comment_buffer = ast_realloc(comment_buffer, comment_buffer_size + CB_INCR + len + 1);
483 comment_buffer_size += CB_INCR+len+1;
485 strncat(comment_buffer,str,len);
486 comment_buffer[cbl+len-1] = 0;
489 static void LLB_ADD(char *str)
491 int rem = lline_buffer_size - strlen(lline_buffer) - 1;
492 int siz = strlen(str);
494 lline_buffer = ast_realloc(lline_buffer, lline_buffer_size + CB_INCR + siz + 1);
497 lline_buffer_size += CB_INCR + siz + 1;
499 strcat(lline_buffer,str);
502 static void CB_RESET(void )
504 comment_buffer[0] = 0;
508 /*! \brief Keep track of how many threads are currently trying to wait*() on
510 static unsigned int safe_system_level = 0;
511 static void *safe_system_prev_handler;
513 /*! \brief NULL handler so we can collect the child exit status */
514 static void null_sig_handler(int signal)
519 void ast_replace_sigchld(void);
521 void ast_replace_sigchld(void)
525 level = safe_system_level++;
527 /* only replace the handler if it has not already been done */
529 safe_system_prev_handler = signal(SIGCHLD, null_sig_handler);
533 void ast_unreplace_sigchld(void);
535 void ast_unreplace_sigchld(void)
539 level = --safe_system_level;
541 /* only restore the handler if we are the last one */
543 signal(SIGCHLD, safe_system_prev_handler);
547 int ast_safe_system(const char *s);
549 int ast_safe_system(const char *s)
552 #ifdef HAVE_WORKING_FORK
556 struct rusage rusage;
559 #if defined(HAVE_WORKING_FORK) || defined(HAVE_WORKING_VFORK)
560 ast_replace_sigchld();
562 #ifdef HAVE_WORKING_FORK
569 #ifdef HAVE_WORKING_FORK
570 /* Close file descriptors and launch system command */
571 for (x = STDERR_FILENO + 1; x < 4096; x++)
574 execl("/bin/sh", "/bin/sh", "-c", s, (char *) NULL);
576 } else if (pid > 0) {
578 res = wait4(pid, &status, 0, &rusage);
580 res = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
582 } else if (errno != EINTR)
586 ast_log(LOG_WARNING, "Fork failed: %s\n", strerror(errno));
590 ast_unreplace_sigchld();
598 static struct ast_comment *ALLOC_COMMENT(const char *buffer)
600 struct ast_comment *x = ast_calloc(1,sizeof(struct ast_comment)+strlen(buffer)+1);
601 strcpy(x->cmt, buffer);
605 static struct ast_config_map {
606 struct ast_config_map *next;
612 } *config_maps = NULL;
614 static struct ast_config_engine *config_engine_list;
616 #define MAX_INCLUDE_LEVEL 10
619 struct ast_category {
621 int ignored; /*!< do not let user of the config see this category */
623 struct ast_comment *precomments;
624 struct ast_comment *sameline;
625 struct ast_variable *root;
626 struct ast_variable *last;
627 struct ast_category *next;
631 struct ast_category *root;
632 struct ast_category *last;
633 struct ast_category *current;
634 struct ast_category *last_browse; /*!< used to cache the last category supplied via category_browse */
636 int max_include_level;
639 typedef struct ast_config *config_load_func(const char *database, const char *table, const char *configfile, struct ast_config *config, int withcomments);
640 typedef struct ast_variable *realtime_var_get(const char *database, const char *table, va_list ap);
641 typedef struct ast_config *realtime_multi_get(const char *database, const char *table, va_list ap);
642 typedef int realtime_update(const char *database, const char *table, const char *keyfield, const char *entity, va_list ap);
644 /*! \brief Configuration engine structure, used to define realtime drivers */
645 struct ast_config_engine {
647 config_load_func *load_func;
648 realtime_var_get *realtime_func;
649 realtime_multi_get *realtime_multi_func;
650 realtime_update *update_func;
651 struct ast_config_engine *next;
654 static struct ast_config_engine *config_engine_list;
658 struct ast_variable {
662 int object; /*!< 0 for variable, 1 for object */
663 int blanklines; /*!< Number of blanklines following entry */
664 struct ast_comment *precomments;
665 struct ast_comment *sameline;
666 struct ast_variable *next;
670 static const char *ast_variable_retrieve(const struct ast_config *config, const char *category, const char *variable);
671 static struct ast_config *config_text_file_load(const char *database, const char *table, const char *filename, struct ast_config *cfg, int withcomments);
673 struct ast_config *localized_config_load_with_comments(const char *filename);
674 static char *ast_category_browse(struct ast_config *config, const char *prev);
675 static struct ast_variable *ast_variable_browse(const struct ast_config *config, const char *category);
676 static void ast_variables_destroy(struct ast_variable *v);
677 static void ast_config_destroy(struct ast_config *cfg);
679 static struct ast_variable *ast_variable_new(const char *name, const char *value);
681 static struct ast_variable *ast_variable_new(const char *name, const char *value)
683 struct ast_variable *variable;
684 int name_len = strlen(name) + 1;
686 if ((variable = ast_calloc(1, name_len + strlen(value) + 1 + sizeof(*variable)))) {
687 variable->name = variable->stuff;
688 variable->value = variable->stuff + name_len;
689 strcpy(variable->name,name);
690 strcpy(variable->value,value);
696 static void ast_variable_append(struct ast_category *category, struct ast_variable *variable);
698 static void ast_variable_append(struct ast_category *category, struct ast_variable *variable)
703 category->last->next = variable;
705 category->root = variable;
706 category->last = variable;
707 while (category->last->next)
708 category->last = category->last->next;
711 static struct ast_category *category_get(const struct ast_config *config, const char *category_name, int ignored);
713 static struct ast_category *category_get(const struct ast_config *config, const char *category_name, int ignored)
715 struct ast_category *cat;
717 /* try exact match first, then case-insensitive match */
718 for (cat = config->root; cat; cat = cat->next) {
719 if (cat->name == category_name && (ignored || !cat->ignored))
723 for (cat = config->root; cat; cat = cat->next) {
724 if (!strcasecmp(cat->name, category_name) && (ignored || !cat->ignored))
731 static struct ast_category *ast_category_get(const struct ast_config *config, const char *category_name)
733 return category_get(config, category_name, 0);
736 static struct ast_variable *ast_variable_browse(const struct ast_config *config, const char *category)
738 struct ast_category *cat = NULL;
740 if (category && config->last_browse && (config->last_browse->name == category))
741 cat = config->last_browse;
743 cat = ast_category_get(config, category);
745 return (cat) ? cat->root : NULL;
748 static const char *ast_variable_retrieve(const struct ast_config *config, const char *category, const char *variable)
750 struct ast_variable *v;
753 for (v = ast_variable_browse(config, category); v; v = v->next) {
754 if (!strcasecmp(variable, v->name))
758 struct ast_category *cat;
760 for (cat = config->root; cat; cat = cat->next)
761 for (v = cat->root; v; v = v->next)
762 if (!strcasecmp(variable, v->name))
769 static struct ast_variable *variable_clone(const struct ast_variable *old)
771 struct ast_variable *new = ast_variable_new(old->name, old->value);
774 new->lineno = old->lineno;
775 new->object = old->object;
776 new->blanklines = old->blanklines;
777 /* TODO: clone comments? */
783 static void ast_variables_destroy(struct ast_variable *v)
785 struct ast_variable *vn;
794 static void ast_config_destroy(struct ast_config *cfg)
796 struct ast_category *cat, *catn;
803 ast_variables_destroy(cat->root);
812 /* options.h declars ast_options extern; I need it static? */
814 #define AST_CACHE_DIR_LEN 512
815 #define AST_FILENAME_MAX 80
817 /*! \ingroup main_options */
818 enum ast_option_flags {
819 /*! Allow \#exec in config files */
820 AST_OPT_FLAG_EXEC_INCLUDES = (1 << 0),
822 AST_OPT_FLAG_NO_FORK = (1 << 1),
824 AST_OPT_FLAG_QUIET = (1 << 2),
826 AST_OPT_FLAG_CONSOLE = (1 << 3),
827 /*! Run in realtime Linux priority */
828 AST_OPT_FLAG_HIGH_PRIORITY = (1 << 4),
829 /*! Initialize keys for RSA authentication */
830 AST_OPT_FLAG_INIT_KEYS = (1 << 5),
831 /*! Remote console */
832 AST_OPT_FLAG_REMOTE = (1 << 6),
833 /*! Execute an asterisk CLI command upon startup */
834 AST_OPT_FLAG_EXEC = (1 << 7),
835 /*! Don't use termcap colors */
836 AST_OPT_FLAG_NO_COLOR = (1 << 8),
837 /*! Are we fully started yet? */
838 AST_OPT_FLAG_FULLY_BOOTED = (1 << 9),
839 /*! Trascode via signed linear */
840 AST_OPT_FLAG_TRANSCODE_VIA_SLIN = (1 << 10),
841 /*! Enable priority jumping in applications */
842 AST_OPT_FLAG_PRIORITY_JUMPING = (1 << 11),
843 /*! Dump core on a seg fault */
844 AST_OPT_FLAG_DUMP_CORE = (1 << 12),
845 /*! Cache sound files */
846 AST_OPT_FLAG_CACHE_RECORD_FILES = (1 << 13),
847 /*! Display timestamp in CLI verbose output */
848 AST_OPT_FLAG_TIMESTAMP = (1 << 14),
849 /*! Override config */
850 AST_OPT_FLAG_OVERRIDE_CONFIG = (1 << 15),
852 AST_OPT_FLAG_RECONNECT = (1 << 16),
853 /*! Transmit Silence during Record() */
854 AST_OPT_FLAG_TRANSMIT_SILENCE = (1 << 17),
855 /*! Suppress some warnings */
856 AST_OPT_FLAG_DONT_WARN = (1 << 18),
857 /*! End CDRs before the 'h' extension */
858 AST_OPT_FLAG_END_CDR_BEFORE_H_EXTEN = (1 << 19),
859 /*! Use Zaptel Timing for generators if available */
860 AST_OPT_FLAG_INTERNAL_TIMING = (1 << 20),
861 /*! Always fork, even if verbose or debug settings are non-zero */
862 AST_OPT_FLAG_ALWAYS_FORK = (1 << 21),
863 /*! Disable log/verbose output to remote consoles */
864 AST_OPT_FLAG_MUTE = (1 << 22)
867 /*! These are the options that set by default when Asterisk starts */
868 #define AST_DEFAULT_OPTIONS AST_OPT_FLAG_TRANSCODE_VIA_SLIN
870 #define ast_opt_exec_includes ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC_INCLUDES)
871 #define ast_opt_no_fork ast_test_flag(&ast_options, AST_OPT_FLAG_NO_FORK)
872 #define ast_opt_quiet ast_test_flag(&ast_options, AST_OPT_FLAG_QUIET)
873 #define ast_opt_console ast_test_flag(&ast_options, AST_OPT_FLAG_CONSOLE)
874 #define ast_opt_high_priority ast_test_flag(&ast_options, AST_OPT_FLAG_HIGH_PRIORITY)
875 #define ast_opt_init_keys ast_test_flag(&ast_options, AST_OPT_FLAG_INIT_KEYS)
876 #define ast_opt_remote ast_test_flag(&ast_options, AST_OPT_FLAG_REMOTE)
877 #define ast_opt_exec ast_test_flag(&ast_options, AST_OPT_FLAG_EXEC)
878 #define ast_opt_no_color ast_test_flag(&ast_options, AST_OPT_FLAG_NO_COLOR)
879 #define ast_fully_booted ast_test_flag(&ast_options, AST_OPT_FLAG_FULLY_BOOTED)
880 #define ast_opt_transcode_via_slin ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSCODE_VIA_SLIN)
881 #define ast_opt_priority_jumping ast_test_flag(&ast_options, AST_OPT_FLAG_PRIORITY_JUMPING)
882 #define ast_opt_dump_core ast_test_flag(&ast_options, AST_OPT_FLAG_DUMP_CORE)
883 #define ast_opt_cache_record_files ast_test_flag(&ast_options, AST_OPT_FLAG_CACHE_RECORD_FILES)
884 #define ast_opt_timestamp ast_test_flag(&ast_options, AST_OPT_FLAG_TIMESTAMP)
885 #define ast_opt_override_config ast_test_flag(&ast_options, AST_OPT_FLAG_OVERRIDE_CONFIG)
886 #define ast_opt_reconnect ast_test_flag(&ast_options, AST_OPT_FLAG_RECONNECT)
887 #define ast_opt_transmit_silence ast_test_flag(&ast_options, AST_OPT_FLAG_TRANSMIT_SILENCE)
888 #define ast_opt_dont_warn ast_test_flag(&ast_options, AST_OPT_FLAG_DONT_WARN)
889 #define ast_opt_end_cdr_before_h_exten ast_test_flag(&ast_options, AST_OPT_FLAG_END_CDR_BEFORE_H_EXTEN)
890 #define ast_opt_internal_timing ast_test_flag(&ast_options, AST_OPT_FLAG_INTERNAL_TIMING)
891 #define ast_opt_always_fork ast_test_flag(&ast_options, AST_OPT_FLAG_ALWAYS_FORK)
892 #define ast_opt_mute ast_test_flag(&ast_options, AST_OPT_FLAG_MUTE)
894 /* IN CONFLICT: extern int option_verbose; */
895 /* IN CONFLICT: extern int option_debug; */ /*!< Debugging */
896 extern int option_maxcalls; /*!< Maximum number of simultaneous channels */
897 extern double option_maxload;
898 extern char defaultlanguage[];
900 extern time_t ast_startuptime;
901 extern time_t ast_lastreloadtime;
902 extern pid_t ast_mainpid;
904 extern char record_cache_dir[AST_CACHE_DIR_LEN];
905 extern char debug_filename[AST_FILENAME_MAX];
907 extern int ast_language_is_prefix;
913 #ifndef HAVE_MTX_PROFILE
914 #define __MTX_PROF(a) return pthread_mutex_lock((a))
916 #define __MTX_PROF(a) do { \
918 /* profile only non-blocking events */ \
919 ast_mark(mtx_prof, 1); \
920 i = pthread_mutex_trylock((a)); \
921 ast_mark(mtx_prof, 0); \
925 return pthread_mutex_lock((a)); \
927 #endif /* HAVE_MTX_PROFILE */
929 #define AST_PTHREADT_NULL (pthread_t) -1
930 #define AST_PTHREADT_STOP (pthread_t) -2
932 #if defined(SOLARIS) || defined(BSD)
933 #define AST_MUTEX_INIT_W_CONSTRUCTORS
934 #endif /* SOLARIS || BSD */
936 /* Asterisk REQUIRES recursive (not error checking) mutexes
937 and will not run without them. */
938 #if defined(PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP)
939 #define PTHREAD_MUTEX_INIT_VALUE PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
940 #define AST_MUTEX_KIND PTHREAD_MUTEX_RECURSIVE_NP
942 #define PTHREAD_MUTEX_INIT_VALUE PTHREAD_MUTEX_INITIALIZER
943 #define AST_MUTEX_KIND PTHREAD_MUTEX_RECURSIVE
944 #endif /* PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP */
948 #define __ast_mutex_logger(...) do { if (canlog) ast_log(LOG_ERROR, __VA_ARGS__); else fprintf(stderr, __VA_ARGS__); } while (0)
951 #define DO_THREAD_CRASH do { *((int *)(0)) = 1; } while(0)
953 #define DO_THREAD_CRASH do { } while (0)
956 #define AST_MUTEX_INIT_VALUE { PTHREAD_MUTEX_INIT_VALUE, { NULL }, { 0 }, 0, { NULL }, { 0 } }
958 #define AST_MAX_REENTRANCY 10
960 struct ast_mutex_info {
961 pthread_mutex_t mutex;
962 /*! Track which thread holds this lock */
963 unsigned int track:1;
964 const char *file[AST_MAX_REENTRANCY];
965 int lineno[AST_MAX_REENTRANCY];
967 const char *func[AST_MAX_REENTRANCY];
968 pthread_t thread[AST_MAX_REENTRANCY];
971 typedef struct ast_mutex_info ast_mutex_t;
973 typedef pthread_cond_t ast_cond_t;
975 static pthread_mutex_t empty_mutex;
977 static void __attribute__((constructor)) init_empty_mutex(void)
979 memset(&empty_mutex, 0, sizeof(empty_mutex));
982 static inline int __ast_pthread_mutex_init_attr(const char *filename, int lineno, const char *func,
983 const char *mutex_name, ast_mutex_t *t,
984 pthread_mutexattr_t *attr)
986 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
987 int canlog = strcmp(filename, "logger.c");
989 if ((t->mutex) != ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
990 if ((t->mutex) != (empty_mutex)) {
991 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is already initialized.\n",
992 filename, lineno, func, mutex_name);
993 __ast_mutex_logger("%s line %d (%s): Error: previously initialization of mutex '%s'.\n",
994 t->file[0], t->lineno[0], t->func[0], mutex_name);
1001 t->file[0] = filename;
1002 t->lineno[0] = lineno;
1007 return pthread_mutex_init(&t->mutex, attr);
1010 static inline int __ast_pthread_mutex_init(const char *filename, int lineno, const char *func,
1011 const char *mutex_name, ast_mutex_t *t)
1013 static pthread_mutexattr_t attr;
1015 pthread_mutexattr_init(&attr);
1016 pthread_mutexattr_settype(&attr, AST_MUTEX_KIND);
1018 return __ast_pthread_mutex_init_attr(filename, lineno, func, mutex_name, t, &attr);
1020 #define ast_mutex_init(pmutex) __ast_pthread_mutex_init(__FILE__, __LINE__, __PRETTY_FUNCTION__, #pmutex, pmutex)
1022 static inline int __ast_pthread_mutex_destroy(const char *filename, int lineno, const char *func,
1023 const char *mutex_name, ast_mutex_t *t)
1026 int canlog = strcmp(filename, "logger.c");
1028 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1029 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
1030 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
1031 filename, lineno, func, mutex_name);
1035 res = pthread_mutex_trylock(&t->mutex);
1038 pthread_mutex_unlock(&t->mutex);
1041 __ast_mutex_logger("%s line %d (%s): Error: attempt to destroy invalid mutex '%s'.\n",
1042 filename, lineno, func, mutex_name);
1045 __ast_mutex_logger("%s line %d (%s): Error: attempt to destroy locked mutex '%s'.\n",
1046 filename, lineno, func, mutex_name);
1047 __ast_mutex_logger("%s line %d (%s): Error: '%s' was locked here.\n",
1048 t->file[t->reentrancy-1], t->lineno[t->reentrancy-1], t->func[t->reentrancy-1], mutex_name);
1052 if ((res = pthread_mutex_destroy(&t->mutex)))
1053 __ast_mutex_logger("%s line %d (%s): Error destroying mutex: %s\n",
1054 filename, lineno, func, strerror(res));
1055 #ifndef PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
1057 t->mutex = PTHREAD_MUTEX_INIT_VALUE;
1059 t->file[0] = filename;
1060 t->lineno[0] = lineno;
1066 static inline int __ast_pthread_mutex_lock(const char *filename, int lineno, const char *func,
1067 const char* mutex_name, ast_mutex_t *t)
1070 int canlog = strcmp(filename, "logger.c");
1072 #if defined(AST_MUTEX_INIT_W_CONSTRUCTORS)
1073 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
1074 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
1075 filename, lineno, func, mutex_name);
1078 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1080 #ifdef DETECT_DEADLOCKS
1082 time_t seconds = time(NULL);
1085 #ifdef HAVE_MTX_PROFILE
1086 ast_mark(mtx_prof, 1);
1088 res = pthread_mutex_trylock(&t->mutex);
1089 #ifdef HAVE_MTX_PROFILE
1090 ast_mark(mtx_prof, 0);
1093 current = time(NULL);
1094 if ((current - seconds) && (!((current - seconds) % 5))) {
1095 __ast_mutex_logger("%s line %d (%s): Deadlock? waited %d sec for mutex '%s'?\n",
1096 filename, lineno, func, (int)(current - seconds), mutex_name);
1097 __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
1098 t->file[t->reentrancy-1], t->lineno[t->reentrancy-1],
1099 t->func[t->reentrancy-1], mutex_name);
1103 } while (res == EBUSY);
1106 #ifdef HAVE_MTX_PROFILE
1107 ast_mark(mtx_prof, 1);
1108 res = pthread_mutex_trylock(&t->mutex);
1109 ast_mark(mtx_prof, 0);
1112 res = pthread_mutex_lock(&t->mutex);
1113 #endif /* DETECT_DEADLOCKS */
1116 if (t->reentrancy < AST_MAX_REENTRANCY) {
1117 t->file[t->reentrancy] = filename;
1118 t->lineno[t->reentrancy] = lineno;
1119 t->func[t->reentrancy] = func;
1120 t->thread[t->reentrancy] = pthread_self();
1123 __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
1124 filename, lineno, func, mutex_name);
1127 __ast_mutex_logger("%s line %d (%s): Error obtaining mutex: %s\n",
1128 filename, lineno, func, strerror(errno));
1135 static inline int __ast_pthread_mutex_trylock(const char *filename, int lineno, const char *func,
1136 const char* mutex_name, ast_mutex_t *t)
1139 int canlog = strcmp(filename, "logger.c");
1141 #if defined(AST_MUTEX_INIT_W_CONSTRUCTORS)
1142 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
1143 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
1144 filename, lineno, func, mutex_name);
1147 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1149 if (!(res = pthread_mutex_trylock(&t->mutex))) {
1150 if (t->reentrancy < AST_MAX_REENTRANCY) {
1151 t->file[t->reentrancy] = filename;
1152 t->lineno[t->reentrancy] = lineno;
1153 t->func[t->reentrancy] = func;
1154 t->thread[t->reentrancy] = pthread_self();
1157 __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
1158 filename, lineno, func, mutex_name);
1161 __ast_mutex_logger("%s line %d (%s): Warning: '%s' was locked here.\n",
1162 t->file[t->reentrancy-1], t->lineno[t->reentrancy-1], t->func[t->reentrancy-1], mutex_name);
1168 static inline int __ast_pthread_mutex_unlock(const char *filename, int lineno, const char *func,
1169 const char *mutex_name, ast_mutex_t *t)
1172 int canlog = strcmp(filename, "logger.c");
1174 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1175 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
1176 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
1177 filename, lineno, func, mutex_name);
1181 if (t->reentrancy && (t->thread[t->reentrancy-1] != pthread_self())) {
1182 __ast_mutex_logger("%s line %d (%s): attempted unlock mutex '%s' without owning it!\n",
1183 filename, lineno, func, mutex_name);
1184 __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
1185 t->file[t->reentrancy-1], t->lineno[t->reentrancy-1], t->func[t->reentrancy-1], mutex_name);
1189 if (--t->reentrancy < 0) {
1190 __ast_mutex_logger("%s line %d (%s): mutex '%s' freed more times than we've locked!\n",
1191 filename, lineno, func, mutex_name);
1195 if (t->reentrancy < AST_MAX_REENTRANCY) {
1196 t->file[t->reentrancy] = NULL;
1197 t->lineno[t->reentrancy] = 0;
1198 t->func[t->reentrancy] = NULL;
1199 t->thread[t->reentrancy] = 0;
1202 if ((res = pthread_mutex_unlock(&t->mutex))) {
1203 __ast_mutex_logger("%s line %d (%s): Error releasing mutex: %s\n",
1204 filename, lineno, func, strerror(res));
1211 static inline int __ast_cond_init(const char *filename, int lineno, const char *func,
1212 const char *cond_name, ast_cond_t *cond, pthread_condattr_t *cond_attr)
1214 return pthread_cond_init(cond, cond_attr);
1217 static inline int __ast_cond_signal(const char *filename, int lineno, const char *func,
1218 const char *cond_name, ast_cond_t *cond)
1220 return pthread_cond_signal(cond);
1223 static inline int __ast_cond_broadcast(const char *filename, int lineno, const char *func,
1224 const char *cond_name, ast_cond_t *cond)
1226 return pthread_cond_broadcast(cond);
1229 static inline int __ast_cond_destroy(const char *filename, int lineno, const char *func,
1230 const char *cond_name, ast_cond_t *cond)
1232 return pthread_cond_destroy(cond);
1235 static inline int __ast_cond_wait(const char *filename, int lineno, const char *func,
1236 const char *cond_name, const char *mutex_name,
1237 ast_cond_t *cond, ast_mutex_t *t)
1240 int canlog = strcmp(filename, "logger.c");
1242 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1243 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
1244 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
1245 filename, lineno, func, mutex_name);
1249 if (t->reentrancy && (t->thread[t->reentrancy-1] != pthread_self())) {
1250 __ast_mutex_logger("%s line %d (%s): attempted unlock mutex '%s' without owning it!\n",
1251 filename, lineno, func, mutex_name);
1252 __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
1253 t->file[t->reentrancy-1], t->lineno[t->reentrancy-1], t->func[t->reentrancy-1], mutex_name);
1257 if (--t->reentrancy < 0) {
1258 __ast_mutex_logger("%s line %d (%s): mutex '%s' freed more times than we've locked!\n",
1259 filename, lineno, func, mutex_name);
1263 if (t->reentrancy < AST_MAX_REENTRANCY) {
1264 t->file[t->reentrancy] = NULL;
1265 t->lineno[t->reentrancy] = 0;
1266 t->func[t->reentrancy] = NULL;
1267 t->thread[t->reentrancy] = 0;
1270 if ((res = pthread_cond_wait(cond, &t->mutex))) {
1271 __ast_mutex_logger("%s line %d (%s): Error waiting on condition mutex '%s'\n",
1272 filename, lineno, func, strerror(res));
1275 if (t->reentrancy < AST_MAX_REENTRANCY) {
1276 t->file[t->reentrancy] = filename;
1277 t->lineno[t->reentrancy] = lineno;
1278 t->func[t->reentrancy] = func;
1279 t->thread[t->reentrancy] = pthread_self();
1282 __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
1283 filename, lineno, func, mutex_name);
1290 static inline int __ast_cond_timedwait(const char *filename, int lineno, const char *func,
1291 const char *cond_name, const char *mutex_name, ast_cond_t *cond,
1292 ast_mutex_t *t, const struct timespec *abstime)
1295 int canlog = strcmp(filename, "logger.c");
1297 #ifdef AST_MUTEX_INIT_W_CONSTRUCTORS
1298 if ((t->mutex) == ((pthread_mutex_t) PTHREAD_MUTEX_INITIALIZER)) {
1299 __ast_mutex_logger("%s line %d (%s): Error: mutex '%s' is uninitialized.\n",
1300 filename, lineno, func, mutex_name);
1304 if (t->reentrancy && (t->thread[t->reentrancy-1] != pthread_self())) {
1305 __ast_mutex_logger("%s line %d (%s): attempted unlock mutex '%s' without owning it!\n",
1306 filename, lineno, func, mutex_name);
1307 __ast_mutex_logger("%s line %d (%s): '%s' was locked here.\n",
1308 t->file[t->reentrancy-1], t->lineno[t->reentrancy-1], t->func[t->reentrancy-1], mutex_name);
1312 if (--t->reentrancy < 0) {
1313 __ast_mutex_logger("%s line %d (%s): mutex '%s' freed more times than we've locked!\n",
1314 filename, lineno, func, mutex_name);
1318 if (t->reentrancy < AST_MAX_REENTRANCY) {
1319 t->file[t->reentrancy] = NULL;
1320 t->lineno[t->reentrancy] = 0;
1321 t->func[t->reentrancy] = NULL;
1322 t->thread[t->reentrancy] = 0;
1325 if ((res = pthread_cond_timedwait(cond, &t->mutex, abstime)) && (res != ETIMEDOUT)) {
1326 __ast_mutex_logger("%s line %d (%s): Error waiting on condition mutex '%s'\n",
1327 filename, lineno, func, strerror(res));
1330 if (t->reentrancy < AST_MAX_REENTRANCY) {
1331 t->file[t->reentrancy] = filename;
1332 t->lineno[t->reentrancy] = lineno;
1333 t->func[t->reentrancy] = func;
1334 t->thread[t->reentrancy] = pthread_self();
1337 __ast_mutex_logger("%s line %d (%s): '%s' really deep reentrancy!\n",
1338 filename, lineno, func, mutex_name);
1345 #define ast_mutex_destroy(a) __ast_pthread_mutex_destroy(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
1346 #define ast_mutex_lock(a) __ast_pthread_mutex_lock(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
1347 #define ast_mutex_unlock(a) __ast_pthread_mutex_unlock(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
1348 #define ast_mutex_trylock(a) __ast_pthread_mutex_trylock(__FILE__, __LINE__, __PRETTY_FUNCTION__, #a, a)
1349 #define ast_cond_init(cond, attr) __ast_cond_init(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond, attr)
1350 #define ast_cond_destroy(cond) __ast_cond_destroy(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond)
1351 #define ast_cond_signal(cond) __ast_cond_signal(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond)
1352 #define ast_cond_broadcast(cond) __ast_cond_broadcast(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, cond)
1353 #define ast_cond_wait(cond, mutex) __ast_cond_wait(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, #mutex, cond, mutex)
1354 #define ast_cond_timedwait(cond, mutex, time) __ast_cond_timedwait(__FILE__, __LINE__, __PRETTY_FUNCTION__, #cond, #mutex, cond, mutex, time)
1356 #else /* !DEBUG_THREADS */
1359 typedef pthread_mutex_t ast_mutex_t;
1361 #define AST_MUTEX_INIT_VALUE ((ast_mutex_t) PTHREAD_MUTEX_INIT_VALUE)
1363 static inline int ast_mutex_init(ast_mutex_t *pmutex)
1365 pthread_mutexattr_t attr;
1367 pthread_mutexattr_init(&attr);
1368 pthread_mutexattr_settype(&attr, AST_MUTEX_KIND);
1370 return pthread_mutex_init(pmutex, &attr);
1373 #define ast_pthread_mutex_init(pmutex,a) pthread_mutex_init(pmutex,a)
1375 static inline int ast_mutex_unlock(ast_mutex_t *pmutex)
1377 return pthread_mutex_unlock(pmutex);
1380 static inline int ast_mutex_destroy(ast_mutex_t *pmutex)
1382 return pthread_mutex_destroy(pmutex);
1385 static inline int ast_mutex_lock(ast_mutex_t *pmutex)
1390 static inline int ast_mutex_trylock(ast_mutex_t *pmutex)
1392 return pthread_mutex_trylock(pmutex);
1395 typedef pthread_cond_t ast_cond_t;
1397 static inline int ast_cond_init(ast_cond_t *cond, pthread_condattr_t *cond_attr)
1399 return pthread_cond_init(cond, cond_attr);
1402 static inline int ast_cond_signal(ast_cond_t *cond)
1404 return pthread_cond_signal(cond);
1407 static inline int ast_cond_broadcast(ast_cond_t *cond)
1409 return pthread_cond_broadcast(cond);
1412 static inline int ast_cond_destroy(ast_cond_t *cond)
1414 return pthread_cond_destroy(cond);
1417 static inline int ast_cond_wait(ast_cond_t *cond, ast_mutex_t *t)
1419 return pthread_cond_wait(cond, t);
1422 static inline int ast_cond_timedwait(ast_cond_t *cond, ast_mutex_t *t, const struct timespec *abstime)
1424 return pthread_cond_timedwait(cond, t, abstime);
1427 #endif /* !DEBUG_THREADS */
1429 #if defined(AST_MUTEX_INIT_W_CONSTRUCTORS)
1430 /* If AST_MUTEX_INIT_W_CONSTRUCTORS is defined, use file scope
1431 constructors/destructors to create/destroy mutexes. */
1432 #define __AST_MUTEX_DEFINE(scope, mutex) \
1433 scope ast_mutex_t mutex = AST_MUTEX_INIT_VALUE; \
1434 static void __attribute__ ((constructor)) init_##mutex(void) \
1436 ast_mutex_init(&mutex); \
1438 static void __attribute__ ((destructor)) fini_##mutex(void) \
1440 ast_mutex_destroy(&mutex); \
1442 #else /* !AST_MUTEX_INIT_W_CONSTRUCTORS */
1443 /* By default, use static initialization of mutexes. */
1444 #define __AST_MUTEX_DEFINE(scope, mutex) \
1445 scope ast_mutex_t mutex = AST_MUTEX_INIT_VALUE
1446 #endif /* AST_MUTEX_INIT_W_CONSTRUCTORS */
1448 #define pthread_mutex_t use_ast_mutex_t_instead_of_pthread_mutex_t
1449 #define pthread_mutex_lock use_ast_mutex_lock_instead_of_pthread_mutex_lock
1450 #define pthread_mutex_unlock use_ast_mutex_unlock_instead_of_pthread_mutex_unlock
1451 #define pthread_mutex_trylock use_ast_mutex_trylock_instead_of_pthread_mutex_trylock
1452 #define pthread_mutex_init use_ast_mutex_init_instead_of_pthread_mutex_init
1453 #define pthread_mutex_destroy use_ast_mutex_destroy_instead_of_pthread_mutex_destroy
1454 #define pthread_cond_t use_ast_cond_t_instead_of_pthread_cond_t
1455 #define pthread_cond_init use_ast_cond_init_instead_of_pthread_cond_init
1456 #define pthread_cond_destroy use_ast_cond_destroy_instead_of_pthread_cond_destroy
1457 #define pthread_cond_signal use_ast_cond_signal_instead_of_pthread_cond_signal
1458 #define pthread_cond_broadcast use_ast_cond_broadcast_instead_of_pthread_cond_broadcast
1459 #define pthread_cond_wait use_ast_cond_wait_instead_of_pthread_cond_wait
1460 #define pthread_cond_timedwait use_ast_cond_timedwait_instead_of_pthread_cond_timedwait
1462 #define AST_MUTEX_DEFINE_STATIC(mutex) __AST_MUTEX_DEFINE(static, mutex)
1464 #define AST_MUTEX_INITIALIZER __use_AST_MUTEX_DEFINE_STATIC_rather_than_AST_MUTEX_INITIALIZER__
1466 #define gethostbyname __gethostbyname__is__not__reentrant__use__ast_gethostbyname__instead__
1469 #define pthread_create __use_ast_pthread_create_instead__
1472 typedef pthread_rwlock_t ast_rwlock_t;
1474 static inline int ast_rwlock_init(ast_rwlock_t *prwlock)
1476 pthread_rwlockattr_t attr;
1478 pthread_rwlockattr_init(&attr);
1480 #ifdef HAVE_PTHREAD_RWLOCK_PREFER_WRITER_NP
1481 pthread_rwlockattr_setkind_np(&attr, PTHREAD_RWLOCK_PREFER_WRITER_NP);
1484 return pthread_rwlock_init(prwlock, &attr);
1487 static inline int ast_rwlock_destroy(ast_rwlock_t *prwlock)
1489 return pthread_rwlock_destroy(prwlock);
1492 static inline int ast_rwlock_unlock(ast_rwlock_t *prwlock)
1494 return pthread_rwlock_unlock(prwlock);
1497 static inline int ast_rwlock_rdlock(ast_rwlock_t *prwlock)
1499 return pthread_rwlock_rdlock(prwlock);
1502 static inline int ast_rwlock_tryrdlock(ast_rwlock_t *prwlock)
1504 return pthread_rwlock_tryrdlock(prwlock);
1507 static inline int ast_rwlock_wrlock(ast_rwlock_t *prwlock)
1509 return pthread_rwlock_wrlock(prwlock);
1512 static inline int ast_rwlock_trywrlock(ast_rwlock_t *prwlock)
1514 return pthread_rwlock_trywrlock(prwlock);
1517 /* Statically declared read/write locks */
1519 #ifndef HAVE_PTHREAD_RWLOCK_INITIALIZER
1520 #define __AST_RWLOCK_DEFINE(scope, rwlock) \
1521 scope ast_rwlock_t rwlock; \
1522 static void __attribute__ ((constructor)) init_##rwlock(void) \
1524 ast_rwlock_init(&rwlock); \
1526 static void __attribute__ ((destructor)) fini_##rwlock(void) \
1528 ast_rwlock_destroy(&rwlock); \
1531 #define AST_RWLOCK_INIT_VALUE PTHREAD_RWLOCK_INITIALIZER
1532 #define __AST_RWLOCK_DEFINE(scope, rwlock) \
1533 scope ast_rwlock_t rwlock = AST_RWLOCK_INIT_VALUE
1536 #define AST_RWLOCK_DEFINE_STATIC(rwlock) __AST_RWLOCK_DEFINE(static, rwlock)
1539 * Initial support for atomic instructions.
1540 * For platforms that have it, use the native cpu instruction to
1541 * implement them. For other platforms, resort to a 'slow' version
1542 * (defined in utils.c) that protects the atomic instruction with
1544 * The slow versions is always available, for testing purposes,
1545 * as ast_atomic_fetchadd_int_slow()
1548 int ast_atomic_fetchadd_int_slow(volatile int *p, int v);
1550 #if defined(HAVE_OSX_ATOMICS)
1551 #include "libkern/OSAtomic.h"
1554 /*! \brief Atomically add v to *p and return * the previous value of *p.
1555 * This can be used to handle reference counts, and the return value
1556 * can be used to generate unique identifiers.
1559 #if defined(HAVE_GCC_ATOMICS)
1560 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1562 return __sync_fetch_and_add(p, v);
1564 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 4)
1565 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1567 return OSAtomicAdd32(v, (int32_t *) p);
1569 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 8)
1570 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1572 return OSAtomicAdd64(v, (int64_t *) p);
1573 #elif defined (__i386__)
1574 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1577 " lock xaddl %0, %1 ; "
1578 : "+r" (v), /* 0 (result) */
1580 : "m" (*p)); /* 2 */
1583 #else /* low performance version in utils.c */
1584 AST_INLINE_API(int ast_atomic_fetchadd_int(volatile int *p, int v),
1586 return ast_atomic_fetchadd_int_slow(p, v);
1590 /*! \brief decrement *p by 1 and return true if the variable has reached 0.
1591 * Useful e.g. to check if a refcount has reached 0.
1593 #if defined(HAVE_GCC_ATOMICS)
1594 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1596 return __sync_sub_and_fetch(p, 1) == 0;
1598 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 4)
1599 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1601 return OSAtomicAdd32( -1, (int32_t *) p) == 0;
1603 #elif defined(HAVE_OSX_ATOMICS) && (SIZEOF_INT == 8)
1604 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1606 return OSAtomicAdd64( -1, (int64_t *) p) == 0;
1608 AST_INLINE_API(int ast_atomic_dec_and_test(volatile int *p),
1610 int a = ast_atomic_fetchadd_int(p, -1);
1611 return a == 1; /* true if the value is 0 now (so it was 1 previously) */
1615 #ifndef DEBUG_CHANNEL_LOCKS
1616 /*! \brief Lock a channel. If DEBUG_CHANNEL_LOCKS is defined
1617 in the Makefile, print relevant output for debugging */
1618 #define ast_channel_lock(x) ast_mutex_lock(&x->lock)
1619 /*! \brief Unlock a channel. If DEBUG_CHANNEL_LOCKS is defined
1620 in the Makefile, print relevant output for debugging */
1621 #define ast_channel_unlock(x) ast_mutex_unlock(&x->lock)
1622 /*! \brief Try locking a channel. If DEBUG_CHANNEL_LOCKS is defined
1623 in the Makefile, print relevant output for debugging */
1624 #define ast_channel_trylock(x) ast_mutex_trylock(&x->lock)
1629 /*! \brief Lock AST channel (and print debugging output)
1630 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
1631 int ast_channel_lock(struct ast_channel *chan);
1633 /*! \brief Unlock AST channel (and print debugging output)
1634 \note You need to enable DEBUG_CHANNEL_LOCKS for this function
1636 int ast_channel_unlock(struct ast_channel *chan);
1638 /*! \brief Lock AST channel (and print debugging output)
1639 \note You need to enable DEBUG_CHANNEL_LOCKS for this function */
1640 int ast_channel_trylock(struct ast_channel *chan);
1646 #define AST_LIST_LOCK(head) \
1647 ast_mutex_lock(&(head)->lock)
1650 \brief Write locks a list.
1651 \param head This is a pointer to the list head structure
1653 This macro attempts to place an exclusive write lock in the
1654 list head structure pointed to by head.
1655 Returns non-zero on success, 0 on failure
1657 #define AST_RWLIST_WRLOCK(head) \
1658 ast_rwlock_wrlock(&(head)->lock)
1661 \brief Read locks a list.
1662 \param head This is a pointer to the list head structure
1664 This macro attempts to place a read lock in the
1665 list head structure pointed to by head.
1666 Returns non-zero on success, 0 on failure
1668 #define AST_RWLIST_RDLOCK(head) \
1669 ast_rwlock_rdlock(&(head)->lock)
1672 \brief Locks a list, without blocking if the list is locked.
1673 \param head This is a pointer to the list head structure
1675 This macro attempts to place an exclusive lock in the
1676 list head structure pointed to by head.
1677 Returns non-zero on success, 0 on failure
1679 #define AST_LIST_TRYLOCK(head) \
1680 ast_mutex_trylock(&(head)->lock)
1683 \brief Write locks a list, without blocking if the list is locked.
1684 \param head This is a pointer to the list head structure
1686 This macro attempts to place an exclusive write lock in the
1687 list head structure pointed to by head.
1688 Returns non-zero on success, 0 on failure
1690 #define AST_RWLIST_TRYWRLOCK(head) \
1691 ast_rwlock_trywrlock(&(head)->lock)
1694 \brief Read locks a list, without blocking if the list is locked.
1695 \param head This is a pointer to the list head structure
1697 This macro attempts to place a read lock in the
1698 list head structure pointed to by head.
1699 Returns non-zero on success, 0 on failure
1701 #define AST_RWLIST_TRYRDLOCK(head) \
1702 ast_rwlock_tryrdlock(&(head)->lock)
1705 \brief Attempts to unlock a list.
1706 \param head This is a pointer to the list head structure
1708 This macro attempts to remove an exclusive lock from the
1709 list head structure pointed to by head. If the list
1710 was not locked by this thread, this macro has no effect.
1712 #define AST_LIST_UNLOCK(head) \
1713 ast_mutex_unlock(&(head)->lock)
1716 \brief Attempts to unlock a read/write based list.
1717 \param head This is a pointer to the list head structure
1719 This macro attempts to remove a read or write lock from the
1720 list head structure pointed to by head. If the list
1721 was not locked by this thread, this macro has no effect.
1723 #define AST_RWLIST_UNLOCK(head) \
1724 ast_rwlock_unlock(&(head)->lock)
1727 \brief Defines a structure to be used to hold a list of specified type.
1728 \param name This will be the name of the defined structure.
1729 \param type This is the type of each list entry.
1731 This macro creates a structure definition that can be used
1732 to hold a list of the entries of type \a type. It does not actually
1733 declare (allocate) a structure; to do that, either follow this
1734 macro with the desired name of the instance you wish to declare,
1735 or use the specified \a name to declare instances elsewhere.
1739 static AST_LIST_HEAD(entry_list, entry) entries;
1742 This would define \c struct \c entry_list, and declare an instance of it named
1743 \a entries, all intended to hold a list of type \c struct \c entry.
1745 #define AST_LIST_HEAD(name, type) \
1747 struct type *first; \
1748 struct type *last; \
1753 \brief Defines a structure to be used to hold a read/write list of specified type.
1754 \param name This will be the name of the defined structure.
1755 \param type This is the type of each list entry.
1757 This macro creates a structure definition that can be used
1758 to hold a list of the entries of type \a type. It does not actually
1759 declare (allocate) a structure; to do that, either follow this
1760 macro with the desired name of the instance you wish to declare,
1761 or use the specified \a name to declare instances elsewhere.
1765 static AST_RWLIST_HEAD(entry_list, entry) entries;
1768 This would define \c struct \c entry_list, and declare an instance of it named
1769 \a entries, all intended to hold a list of type \c struct \c entry.
1771 #define AST_RWLIST_HEAD(name, type) \
1773 struct type *first; \
1774 struct type *last; \
1775 ast_rwlock_t lock; \
1779 \brief Defines a structure to be used to hold a list of specified type (with no lock).
1780 \param name This will be the name of the defined structure.
1781 \param type This is the type of each list entry.
1783 This macro creates a structure definition that can be used
1784 to hold a list of the entries of type \a type. It does not actually
1785 declare (allocate) a structure; to do that, either follow this
1786 macro with the desired name of the instance you wish to declare,
1787 or use the specified \a name to declare instances elsewhere.
1791 static AST_LIST_HEAD_NOLOCK(entry_list, entry) entries;
1794 This would define \c struct \c entry_list, and declare an instance of it named
1795 \a entries, all intended to hold a list of type \c struct \c entry.
1797 #define AST_LIST_HEAD_NOLOCK(name, type) \
1799 struct type *first; \
1800 struct type *last; \
1804 \brief Defines initial values for a declaration of AST_LIST_HEAD
1806 #define AST_LIST_HEAD_INIT_VALUE { \
1809 .lock = AST_MUTEX_INIT_VALUE, \
1813 \brief Defines initial values for a declaration of AST_RWLIST_HEAD
1815 #define AST_RWLIST_HEAD_INIT_VALUE { \
1818 .lock = AST_RWLOCK_INIT_VALUE, \
1822 \brief Defines initial values for a declaration of AST_LIST_HEAD_NOLOCK
1824 #define AST_LIST_HEAD_NOLOCK_INIT_VALUE { \
1830 \brief Defines a structure to be used to hold a list of specified type, statically initialized.
1831 \param name This will be the name of the defined structure.
1832 \param type This is the type of each list entry.
1834 This macro creates a structure definition that can be used
1835 to hold a list of the entries of type \a type, and allocates an instance
1836 of it, initialized to be empty.
1840 static AST_LIST_HEAD_STATIC(entry_list, entry);
1843 This would define \c struct \c entry_list, intended to hold a list of
1844 type \c struct \c entry.
1846 #if defined(AST_MUTEX_INIT_W_CONSTRUCTORS)
1847 #define AST_LIST_HEAD_STATIC(name, type) \
1849 struct type *first; \
1850 struct type *last; \
1853 static void __attribute__ ((constructor)) init_##name(void) \
1855 AST_LIST_HEAD_INIT(&name); \
1857 static void __attribute__ ((destructor)) fini_##name(void) \
1859 AST_LIST_HEAD_DESTROY(&name); \
1861 struct __dummy_##name
1863 #define AST_LIST_HEAD_STATIC(name, type) \
1865 struct type *first; \
1866 struct type *last; \
1868 } name = AST_LIST_HEAD_INIT_VALUE
1872 \brief Defines a structure to be used to hold a read/write list of specified type, statically initialized.
1873 \param name This will be the name of the defined structure.
1874 \param type This is the type of each list entry.
1876 This macro creates a structure definition that can be used
1877 to hold a list of the entries of type \a type, and allocates an instance
1878 of it, initialized to be empty.
1882 static AST_RWLIST_HEAD_STATIC(entry_list, entry);
1885 This would define \c struct \c entry_list, intended to hold a list of
1886 type \c struct \c entry.
1888 #ifndef AST_RWLOCK_INIT_VALUE
1889 #define AST_RWLIST_HEAD_STATIC(name, type) \
1891 struct type *first; \
1892 struct type *last; \
1893 ast_rwlock_t lock; \
1895 static void __attribute__ ((constructor)) init_##name(void) \
1897 AST_RWLIST_HEAD_INIT(&name); \
1899 static void __attribute__ ((destructor)) fini_##name(void) \
1901 AST_RWLIST_HEAD_DESTROY(&name); \
1903 struct __dummy_##name
1905 #define AST_RWLIST_HEAD_STATIC(name, type) \
1907 struct type *first; \
1908 struct type *last; \
1909 ast_rwlock_t lock; \
1910 } name = AST_RWLIST_HEAD_INIT_VALUE
1914 \brief Defines a structure to be used to hold a list of specified type, statically initialized.
1916 This is the same as AST_LIST_HEAD_STATIC, except without the lock included.
1918 #define AST_LIST_HEAD_NOLOCK_STATIC(name, type) \
1920 struct type *first; \
1921 struct type *last; \
1922 } name = AST_LIST_HEAD_NOLOCK_INIT_VALUE
1925 \brief Initializes a list head structure with a specified first entry.
1926 \param head This is a pointer to the list head structure
1927 \param entry pointer to the list entry that will become the head of the list
1929 This macro initializes a list head structure by setting the head
1930 entry to the supplied value and recreating the embedded lock.
1932 #define AST_LIST_HEAD_SET(head, entry) do { \
1933 (head)->first = (entry); \
1934 (head)->last = (entry); \
1935 ast_mutex_init(&(head)->lock); \
1939 \brief Initializes an rwlist head structure with a specified first entry.
1940 \param head This is a pointer to the list head structure
1941 \param entry pointer to the list entry that will become the head of the list
1943 This macro initializes a list head structure by setting the head
1944 entry to the supplied value and recreating the embedded lock.
1946 #define AST_RWLIST_HEAD_SET(head, entry) do { \
1947 (head)->first = (entry); \
1948 (head)->last = (entry); \
1949 ast_rwlock_init(&(head)->lock); \
1953 \brief Initializes a list head structure with a specified first entry.
1954 \param head This is a pointer to the list head structure
1955 \param entry pointer to the list entry that will become the head of the list
1957 This macro initializes a list head structure by setting the head
1958 entry to the supplied value.
1960 #define AST_LIST_HEAD_SET_NOLOCK(head, entry) do { \
1961 (head)->first = (entry); \
1962 (head)->last = (entry); \
1966 \brief Declare a forward link structure inside a list entry.
1967 \param type This is the type of each list entry.
1969 This macro declares a structure to be used to link list entries together.
1970 It must be used inside the definition of the structure named in
1971 \a type, as follows:
1976 AST_LIST_ENTRY(list_entry) list;
1980 The field name \a list here is arbitrary, and can be anything you wish.
1982 #define AST_LIST_ENTRY(type) \
1984 struct type *next; \
1987 #define AST_RWLIST_ENTRY AST_LIST_ENTRY
1990 \brief Returns the first entry contained in a list.
1991 \param head This is a pointer to the list head structure
1993 #define AST_LIST_FIRST(head) ((head)->first)
1995 #define AST_RWLIST_FIRST AST_LIST_FIRST
1998 \brief Returns the last entry contained in a list.
1999 \param head This is a pointer to the list head structure
2001 #define AST_LIST_LAST(head) ((head)->last)
2003 #define AST_RWLIST_LAST AST_LIST_LAST
2006 \brief Returns the next entry in the list after the given entry.
2007 \param elm This is a pointer to the current entry.
2008 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2009 used to link entries of this list together.
2011 #define AST_LIST_NEXT(elm, field) ((elm)->field.next)
2013 #define AST_RWLIST_NEXT AST_LIST_NEXT
2016 \brief Checks whether the specified list contains any entries.
2017 \param head This is a pointer to the list head structure
2019 Returns non-zero if the list has entries, zero if not.
2021 #define AST_LIST_EMPTY(head) (AST_LIST_FIRST(head) == NULL)
2023 #define AST_RWLIST_EMPTY AST_LIST_EMPTY
2026 \brief Loops over (traverses) the entries in a list.
2027 \param head This is a pointer to the list head structure
2028 \param var This is the name of the variable that will hold a pointer to the
2029 current list entry on each iteration. It must be declared before calling
2031 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2032 used to link entries of this list together.
2034 This macro is use to loop over (traverse) the entries in a list. It uses a
2035 \a for loop, and supplies the enclosed code with a pointer to each list
2036 entry as it loops. It is typically used as follows:
2038 static AST_LIST_HEAD(entry_list, list_entry) entries;
2042 AST_LIST_ENTRY(list_entry) list;
2045 struct list_entry *current;
2047 AST_LIST_TRAVERSE(&entries, current, list) {
2048 (do something with current here)
2051 \warning If you modify the forward-link pointer contained in the \a current entry while
2052 inside the loop, the behavior will be unpredictable. At a minimum, the following
2053 macros will modify the forward-link pointer, and should not be used inside
2054 AST_LIST_TRAVERSE() against the entry pointed to by the \a current pointer without
2055 careful consideration of their consequences:
2056 \li AST_LIST_NEXT() (when used as an lvalue)
2057 \li AST_LIST_INSERT_AFTER()
2058 \li AST_LIST_INSERT_HEAD()
2059 \li AST_LIST_INSERT_TAIL()
2061 #define AST_LIST_TRAVERSE(head,var,field) \
2062 for((var) = (head)->first; (var); (var) = (var)->field.next)
2064 #define AST_RWLIST_TRAVERSE AST_LIST_TRAVERSE
2067 \brief Loops safely over (traverses) the entries in a list.
2068 \param head This is a pointer to the list head structure
2069 \param var This is the name of the variable that will hold a pointer to the
2070 current list entry on each iteration. It must be declared before calling
2072 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2073 used to link entries of this list together.
2075 This macro is used to safely loop over (traverse) the entries in a list. It
2076 uses a \a for loop, and supplies the enclosed code with a pointer to each list
2077 entry as it loops. It is typically used as follows:
2080 static AST_LIST_HEAD(entry_list, list_entry) entries;
2084 AST_LIST_ENTRY(list_entry) list;
2087 struct list_entry *current;
2089 AST_LIST_TRAVERSE_SAFE_BEGIN(&entries, current, list) {
2090 (do something with current here)
2092 AST_LIST_TRAVERSE_SAFE_END;
2095 It differs from AST_LIST_TRAVERSE() in that the code inside the loop can modify
2096 (or even free, after calling AST_LIST_REMOVE_CURRENT()) the entry pointed to by
2097 the \a current pointer without affecting the loop traversal.
2099 #define AST_LIST_TRAVERSE_SAFE_BEGIN(head, var, field) { \
2100 typeof((head)->first) __list_next; \
2101 typeof((head)->first) __list_prev = NULL; \
2102 typeof((head)->first) __new_prev = NULL; \
2103 for ((var) = (head)->first, __new_prev = (var), \
2104 __list_next = (var) ? (var)->field.next : NULL; \
2106 __list_prev = __new_prev, (var) = __list_next, \
2107 __new_prev = (var), \
2108 __list_next = (var) ? (var)->field.next : NULL \
2111 #define AST_RWLIST_TRAVERSE_SAFE_BEGIN AST_LIST_TRAVERSE_SAFE_BEGIN
2114 \brief Removes the \a current entry from a list during a traversal.
2115 \param head This is a pointer to the list head structure
2116 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2117 used to link entries of this list together.
2119 \note This macro can \b only be used inside an AST_LIST_TRAVERSE_SAFE_BEGIN()
2120 block; it is used to unlink the current entry from the list without affecting
2121 the list traversal (and without having to re-traverse the list to modify the
2122 previous entry, if any).
2124 #define AST_LIST_REMOVE_CURRENT(head, field) \
2125 __new_prev->field.next = NULL; \
2126 __new_prev = __list_prev; \
2128 __list_prev->field.next = __list_next; \
2130 (head)->first = __list_next; \
2132 (head)->last = __list_prev;
2134 #define AST_RWLIST_REMOVE_CURRENT AST_LIST_REMOVE_CURRENT
2137 \brief Inserts a list entry before the current entry during a traversal.
2138 \param head This is a pointer to the list head structure
2139 \param elm This is a pointer to the entry to be inserted.
2140 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2141 used to link entries of this list together.
2143 \note This macro can \b only be used inside an AST_LIST_TRAVERSE_SAFE_BEGIN()
2146 #define AST_LIST_INSERT_BEFORE_CURRENT(head, elm, field) do { \
2147 if (__list_prev) { \
2148 (elm)->field.next = __list_prev->field.next; \
2149 __list_prev->field.next = elm; \
2151 (elm)->field.next = (head)->first; \
2152 (head)->first = (elm); \
2154 __new_prev = (elm); \
2157 #define AST_RWLIST_INSERT_BEFORE_CURRENT AST_LIST_INSERT_BEFORE_CURRENT
2160 \brief Closes a safe loop traversal block.
2162 #define AST_LIST_TRAVERSE_SAFE_END }
2164 #define AST_RWLIST_TRAVERSE_SAFE_END AST_LIST_TRAVERSE_SAFE_END
2167 \brief Initializes a list head structure.
2168 \param head This is a pointer to the list head structure
2170 This macro initializes a list head structure by setting the head
2171 entry to \a NULL (empty list) and recreating the embedded lock.
2173 #define AST_LIST_HEAD_INIT(head) { \
2174 (head)->first = NULL; \
2175 (head)->last = NULL; \
2176 ast_mutex_init(&(head)->lock); \
2180 \brief Initializes an rwlist head structure.
2181 \param head This is a pointer to the list head structure
2183 This macro initializes a list head structure by setting the head
2184 entry to \a NULL (empty list) and recreating the embedded lock.
2186 #define AST_RWLIST_HEAD_INIT(head) { \
2187 (head)->first = NULL; \
2188 (head)->last = NULL; \
2189 ast_rwlock_init(&(head)->lock); \
2193 \brief Destroys a list head structure.
2194 \param head This is a pointer to the list head structure
2196 This macro destroys a list head structure by setting the head
2197 entry to \a NULL (empty list) and destroying the embedded lock.
2198 It does not free the structure from memory.
2200 #define AST_LIST_HEAD_DESTROY(head) { \
2201 (head)->first = NULL; \
2202 (head)->last = NULL; \
2203 ast_mutex_destroy(&(head)->lock); \
2207 \brief Destroys an rwlist head structure.
2208 \param head This is a pointer to the list head structure
2210 This macro destroys a list head structure by setting the head
2211 entry to \a NULL (empty list) and destroying the embedded lock.
2212 It does not free the structure from memory.
2214 #define AST_RWLIST_HEAD_DESTROY(head) { \
2215 (head)->first = NULL; \
2216 (head)->last = NULL; \
2217 ast_rwlock_destroy(&(head)->lock); \
2221 \brief Initializes a list head structure.
2222 \param head This is a pointer to the list head structure
2224 This macro initializes a list head structure by setting the head
2225 entry to \a NULL (empty list). There is no embedded lock handling
2228 #define AST_LIST_HEAD_INIT_NOLOCK(head) { \
2229 (head)->first = NULL; \
2230 (head)->last = NULL; \
2234 \brief Inserts a list entry after a given entry.
2235 \param head This is a pointer to the list head structure
2236 \param listelm This is a pointer to the entry after which the new entry should
2238 \param elm This is a pointer to the entry to be inserted.
2239 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2240 used to link entries of this list together.
2242 #define AST_LIST_INSERT_AFTER(head, listelm, elm, field) do { \
2243 (elm)->field.next = (listelm)->field.next; \
2244 (listelm)->field.next = (elm); \
2245 if ((head)->last == (listelm)) \
2246 (head)->last = (elm); \
2249 #define AST_RWLIST_INSERT_AFTER AST_LIST_INSERT_AFTER
2252 \brief Inserts a list entry at the head of a list.
2253 \param head This is a pointer to the list head structure
2254 \param elm This is a pointer to the entry to be inserted.
2255 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2256 used to link entries of this list together.
2258 #define AST_LIST_INSERT_HEAD(head, elm, field) do { \
2259 (elm)->field.next = (head)->first; \
2260 (head)->first = (elm); \
2261 if (!(head)->last) \
2262 (head)->last = (elm); \
2265 #define AST_RWLIST_INSERT_HEAD AST_LIST_INSERT_HEAD
2268 \brief Appends a list entry to the tail of a list.
2269 \param head This is a pointer to the list head structure
2270 \param elm This is a pointer to the entry to be appended.
2271 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2272 used to link entries of this list together.
2274 Note: The link field in the appended entry is \b not modified, so if it is
2275 actually the head of a list itself, the entire list will be appended
2276 temporarily (until the next AST_LIST_INSERT_TAIL is performed).
2278 #define AST_LIST_INSERT_TAIL(head, elm, field) do { \
2279 if (!(head)->first) { \
2280 (head)->first = (elm); \
2281 (head)->last = (elm); \
2283 (head)->last->field.next = (elm); \
2284 (head)->last = (elm); \
2288 #define AST_RWLIST_INSERT_TAIL AST_LIST_INSERT_TAIL
2291 \brief Appends a whole list to the tail of a list.
2292 \param head This is a pointer to the list head structure
2293 \param list This is a pointer to the list to be appended.
2294 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2295 used to link entries of this list together.
2297 #define AST_LIST_APPEND_LIST(head, list, field) do { \
2298 if (!(head)->first) { \
2299 (head)->first = (list)->first; \
2300 (head)->last = (list)->last; \
2302 (head)->last->field.next = (list)->first; \
2303 (head)->last = (list)->last; \
2307 #define AST_RWLIST_APPEND_LIST AST_LIST_APPEND_LIST
2310 \brief Removes and returns the head entry from a list.
2311 \param head This is a pointer to the list head structure
2312 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2313 used to link entries of this list together.
2315 Removes the head entry from the list, and returns a pointer to it.
2316 This macro is safe to call on an empty list.
2318 #define AST_LIST_REMOVE_HEAD(head, field) ({ \
2319 typeof((head)->first) cur = (head)->first; \
2321 (head)->first = cur->field.next; \
2322 cur->field.next = NULL; \
2323 if ((head)->last == cur) \
2324 (head)->last = NULL; \
2329 #define AST_RWLIST_REMOVE_HEAD AST_LIST_REMOVE_HEAD
2332 \brief Removes a specific entry from a list.
2333 \param head This is a pointer to the list head structure
2334 \param elm This is a pointer to the entry to be removed.
2335 \param field This is the name of the field (declared using AST_LIST_ENTRY())
2336 used to link entries of this list together.
2337 \warning The removed entry is \b not freed nor modified in any way.
2339 #define AST_LIST_REMOVE(head, elm, field) do { \
2340 if ((head)->first == (elm)) { \
2341 (head)->first = (elm)->field.next; \
2342 if ((head)->last == (elm)) \
2343 (head)->last = NULL; \
2345 typeof(elm) curelm = (head)->first; \
2346 while (curelm && (curelm->field.next != (elm))) \
2347 curelm = curelm->field.next; \
2349 curelm->field.next = (elm)->field.next; \
2350 if ((head)->last == (elm)) \
2351 (head)->last = curelm; \
2354 (elm)->field.next = NULL; \
2357 #define AST_RWLIST_REMOVE AST_LIST_REMOVE
2362 AST_LIST_ENTRY(ast_var_t) entries;
2367 AST_LIST_HEAD_NOLOCK(varshead, ast_var_t);
2369 AST_RWLOCK_DEFINE_STATIC(globalslock);
2370 static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
2373 /* IN CONFLICT: struct ast_var_t *ast_var_assign(const char *name, const char *value); */
2375 static struct ast_var_t *ast_var_assign(const char *name, const char *value);
2377 static void ast_var_delete(struct ast_var_t *var);
2380 #define AST_MAX_EXTENSION 80 /*!< Max length of an extension */
2384 #define PRIORITY_HINT -1 /*!< Special Priority for a hint */
2386 enum ast_extension_states {
2387 AST_EXTENSION_REMOVED = -2, /*!< Extension removed */
2388 AST_EXTENSION_DEACTIVATED = -1, /*!< Extension hint removed */
2389 AST_EXTENSION_NOT_INUSE = 0, /*!< No device INUSE or BUSY */
2390 AST_EXTENSION_INUSE = 1 << 0, /*!< One or more devices INUSE */
2391 AST_EXTENSION_BUSY = 1 << 1, /*!< All devices BUSY */
2392 AST_EXTENSION_UNAVAILABLE = 1 << 2, /*!< All devices UNAVAILABLE/UNREGISTERED */
2393 AST_EXTENSION_RINGING = 1 << 3, /*!< All devices RINGING */
2394 AST_EXTENSION_ONHOLD = 1 << 4, /*!< All devices ONHOLD */
2397 struct ast_custom_function {
2398 const char *name; /*!< Name */
2399 const char *synopsis; /*!< Short description for "show functions" */
2400 const char *desc; /*!< Help text that explains it all */
2401 const char *syntax; /*!< Syntax description */
2402 int (*read)(struct ast_channel *, const char *, char *, char *, size_t); /*!< Read function, if read is supported */
2403 int (*write)(struct ast_channel *, const char *, char *, const char *); /*!< Write function, if write is supported */
2404 AST_RWLIST_ENTRY(ast_custom_function) acflist;
2407 typedef int (ast_switch_f)(struct ast_channel *chan, const char *context,
2408 const char *exten, int priority, const char *callerid, const char *data);
2411 AST_LIST_ENTRY(ast_switch) list;
2412 const char *name; /*!< Name of the switch */
2413 const char *description; /*!< Description of the switch */
2415 ast_switch_f *exists;
2416 ast_switch_f *canmatch;
2418 ast_switch_f *matchmore;
2422 static char *config = "extensions.conf";
2423 static char *registrar = "conf2ael";
2424 static char userscontext[AST_MAX_EXTENSION] = "default";
2425 static int static_config = 0;
2426 static int write_protect_config = 1;
2427 static int autofallthrough_config = 0;
2428 static int clearglobalvars_config = 0;
2429 /*! Go no deeper than this through includes (not counting loops) */
2430 #define AST_PBX_MAX_STACK 128
2431 static void pbx_substitute_variables_helper(struct ast_channel *c,const char *cp1,char *cp2,int count);
2434 /* taken from strings.h */
2436 static force_inline int ast_strlen_zero(const char *s)
2438 return (!s || (*s == '\0'));
2441 #define S_OR(a, b) (!ast_strlen_zero(a) ? (a) : (b))
2444 void ast_copy_string(char *dst, const char *src, size_t size),
2446 while (*src && size) {
2450 if (__builtin_expect(!size, 0))
2457 char *ast_skip_blanks(const char *str),
2459 while (*str && *str < 33)
2466 \brief Trims trailing whitespace characters from a string.
2467 \param ast_trim_blanks function being used
2468 \param str the input string
2469 \return a pointer to the modified string
2472 char *ast_trim_blanks(char *str),
2477 work += strlen(work) - 1;
2478 /* It's tempting to only want to erase after we exit this loop,
2479 but since ast_trim_blanks *could* receive a constant string
2480 (which we presumably wouldn't have to touch), we shouldn't
2481 actually set anything unless we must, and it's easier just
2482 to set each position to \0 than to keep track of a variable
2484 while ((work >= str) && *work < 33)
2492 \brief Strip leading/trailing whitespace from a string.
2493 \param s The string to be stripped (will be modified).
2494 \return The stripped string.
2496 This functions strips all leading and trailing whitespace
2497 characters from the input string, and returns a pointer to
2498 the resulting string. The string is modified in place.
2501 char *ast_strip(char *s),
2503 s = ast_skip_blanks(s);
2511 /* stolen from callerid.c */
2513 /*! \brief Clean up phone string
2514 * remove '(', ' ', ')', non-trailing '.', and '-' not in square brackets.
2515 * Basically, remove anything that could be invalid in a pattern.
2517 static void ast_shrink_phone_number(char *n)
2522 for (x=0; n[x]; x++) {
2541 if (!strchr("()", n[x]))
2549 /* stolen from chanvars.c */
2551 static const char *ast_var_name(const struct ast_var_t *var)
2555 if (var == NULL || (name = var->name) == NULL)
2557 /* Return the name without the initial underscores */
2558 if (name[0] == '_') {
2567 /* stolen from asterisk.c */
2569 static struct ast_flags ast_options = { AST_DEFAULT_OPTIONS };
2570 static int option_verbose = 0; /*!< Verbosity level */
2571 static int option_debug = 0; /*!< Debug level */
2574 /* experiment 1: see if it's easier just to use existing config code
2575 * to read in the extensions.conf file. In this scenario,
2576 I have to rip/copy code from other modules, because they
2577 are staticly declared as-is. A solution would be to move
2578 the ripped code to another location and make them available
2579 to other modules and standalones */
2581 /* Our own version of ast_log, since the expr parser uses it. -- stolen from utils/check_expr.c */
2583 static void ast_log(int level, const char *file, int line, const char *function, const char *fmt, ...)
2588 printf("LOG: lev:%d file:%s line:%d func: %s ",
2589 level, file, line, function);
2595 static void ast_verbose(const char *fmt, ...)
2600 printf("VERBOSE: ");
2606 /* stolen from main/utils.c */
2607 static char *ast_process_quotes_and_slashes(char *start, char find, char replace_with)
2609 char *dataPut = start;
2613 for (; *start; start++) {
2615 *dataPut++ = *start; /* Always goes verbatim */
2618 if (*start == '\\') {
2619 inEscape = 1; /* Do not copy \ into the data */
2620 } else if (*start == '\'') {
2621 inQuotes = 1 - inQuotes; /* Do not copy ' into the data */
2623 /* Replace , with |, unless in quotes */
2624 *dataPut++ = inQuotes ? *start : ((*start == find) ? replace_with : *start);
2628 if (start != dataPut)
2633 static int ast_true(const char *s)
2635 if (ast_strlen_zero(s))
2638 /* Determine if this is a true value */
2639 if (!strcasecmp(s, "yes") ||
2640 !strcasecmp(s, "true") ||
2641 !strcasecmp(s, "y") ||
2642 !strcasecmp(s, "t") ||
2643 !strcasecmp(s, "1") ||
2644 !strcasecmp(s, "on"))
2650 /* stolen from pbx.c */
2651 #define VAR_BUF_SIZE 4096
2653 #define VAR_NORMAL 1
2654 #define VAR_SOFTTRAN 2
2655 #define VAR_HARDTRAN 3
2657 #define BACKGROUND_SKIP (1 << 0)
2658 #define BACKGROUND_NOANSWER (1 << 1)
2659 #define BACKGROUND_MATCHEXTEN (1 << 2)
2660 #define BACKGROUND_PLAYBACK (1 << 3)
2663 \brief ast_exten: An extension
2664 The dialplan is saved as a linked list with each context
2665 having it's own linked list of extensions - one item per
2669 char *exten; /*!< Extension name */
2670 int matchcid; /*!< Match caller id ? */
2671 const char *cidmatch; /*!< Caller id to match for this extension */
2672 int priority; /*!< Priority */
2673 const char *label; /*!< Label */
2674 struct ast_context *parent; /*!< The context this extension belongs to */
2675 const char *app; /*!< Application to execute */
2676 struct ast_app *cached_app; /*!< Cached location of application */
2677 void *data; /*!< Data to use (arguments) */
2678 void (*datad)(void *); /*!< Data destructor */
2679 struct ast_exten *peer; /*!< Next higher priority with our extension */
2680 const char *registrar; /*!< Registrar */
2681 struct ast_exten *next; /*!< Extension with a greater ID */
2685 typedef int (*ast_state_cb_type)(char *context, char* id, enum ast_extension_states state, void *data);
2687 int hastime; /*!< If time construct exists */
2688 unsigned int monthmask; /*!< Mask for month */
2689 unsigned int daymask; /*!< Mask for date */
2690 unsigned int dowmask; /*!< Mask for day of week (mon-sun) */
2691 unsigned int minmask[24]; /*!< Mask for minute */
2694 /*! \brief ast_include: include= support in extensions.conf */
2695 struct ast_include {
2697 const char *rname; /*!< Context to include */
2698 const char *registrar; /*!< Registrar */
2699 int hastime; /*!< If time construct exists */
2700 struct ast_timing timing; /*!< time construct */
2701 struct ast_include *next; /*!< Link them together */
2705 /*! \brief ast_sw: Switch statement in extensions.conf */
2708 const char *registrar; /*!< Registrar */
2709 char *data; /*!< Data load */
2711 AST_LIST_ENTRY(ast_sw) list;
2716 /*! \brief ast_ignorepat: Ignore patterns in dial plan */
2717 struct ast_ignorepat {
2718 const char *registrar;
2719 struct ast_ignorepat *next;
2720 const char pattern[0];
2723 /*! \brief ast_context: An extension context */
2724 struct ast_context {
2725 ast_rwlock_t lock; /*!< A lock to prevent multiple threads from clobbering the context */
2726 struct ast_exten *root; /*!< The root of the list of extensions */
2727 struct ast_context *next; /*!< Link them together */
2728 struct ast_include *includes; /*!< Include other contexts */
2729 struct ast_ignorepat *ignorepats; /*!< Patterns for which to continue playing dialtone */
2730 const char *registrar; /*!< Registrar */
2731 AST_LIST_HEAD_NOLOCK(, ast_sw) alts; /*!< Alternative switches */
2732 ast_mutex_t macrolock; /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
2733 char name[0]; /*!< Name of the context */
2737 /*! \brief ast_app: A registered application */
2739 int (*execute)(struct ast_channel *chan, void *data);
2740 const char *synopsis; /*!< Synopsis text for 'show applications' */
2741 const char *description; /*!< Description (help text) for 'show application <name>' */
2742 AST_RWLIST_ENTRY(ast_app) list; /*!< Next app in list */
2743 void *module; /*!< Module this app belongs to */
2744 char name[0]; /*!< Name of the application */
2748 /*! \brief ast_state_cb: An extension state notify register item */
2749 struct ast_state_cb {
2752 ast_state_cb_type callback;
2753 struct ast_state_cb *next;
2756 /*! \brief Structure for dial plan hints
2758 \note Hints are pointers from an extension in the dialplan to one or
2759 more devices (tech/name)
2760 - See \ref AstExtState
2763 struct ast_exten *exten; /*!< Extension */
2764 int laststate; /*!< Last known state */
2765 struct ast_state_cb *callbacks; /*!< Callback list for this extension */
2766 AST_RWLIST_ENTRY(ast_hint) list;/*!< Pointer to next hint in list */
2772 struct ast_state_cb *callbacks;
2774 AST_LIST_ENTRY(store_hint) list;
2778 AST_LIST_HEAD(store_hints, store_hint);
2780 static const struct cfextension_states {
2781 int extension_state;
2782 const char * const text;
2783 } extension_states[] = {
2784 { AST_EXTENSION_NOT_INUSE, "Idle" },
2785 { AST_EXTENSION_INUSE, "InUse" },
2786 { AST_EXTENSION_BUSY, "Busy" },
2787 { AST_EXTENSION_UNAVAILABLE, "Unavailable" },
2788 { AST_EXTENSION_RINGING, "Ringing" },
2789 { AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
2790 { AST_EXTENSION_ONHOLD, "Hold" },
2791 { AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD, "InUse&Hold" }
2793 #define STATUS_NO_CONTEXT 1
2794 #define STATUS_NO_EXTENSION 2
2795 #define STATUS_NO_PRIORITY 3
2796 #define STATUS_NO_LABEL 4
2797 #define STATUS_SUCCESS 5
2800 #if defined ( __i386__) && (defined(__FreeBSD__) || defined(linux))
2801 #if defined(__FreeBSD__)
2802 #include <machine/cpufunc.h>
2803 #elif defined(linux)
2804 static __inline uint64_t
2809 __asm __volatile(".byte 0x0f, 0x31" : "=A" (rv));
2813 #else /* supply a dummy function on other platforms */
2814 static __inline uint64_t
2822 static struct ast_var_t *ast_var_assign(const char *name, const char *value)
2824 struct ast_var_t *var;
2825 int name_len = strlen(name) + 1;
2826 int value_len = strlen(value) + 1;
2828 if (!(var = ast_calloc(sizeof(*var) + name_len + value_len, sizeof(char)))) {
2832 ast_copy_string(var->name, name, name_len);
2833 var->value = var->name + name_len;
2834 ast_copy_string(var->value, value, value_len);
2839 static void ast_var_delete(struct ast_var_t *var)
2846 /* chopped this one off at the knees! */
2847 static int ast_func_write(struct ast_channel *chan, const char *function, const char *value)
2850 /* ast_log(LOG_ERROR, "Function %s not registered\n", function); we are not interested in the details here */
2855 static unsigned int ast_app_separate_args(char *buf, char delim, char **array, int arraylen)
2859 int paren = 0, quote = 0;
2861 if (!buf || !array || !arraylen)
2864 memset(array, 0, arraylen * sizeof(*array));
2868 for (argc = 0; *scan && (argc < arraylen - 1); argc++) {
2870 for (; *scan; scan++) {
2873 else if (*scan == ')') {
2876 } else if (*scan == '"' && delim != '"') {
2877 quote = quote ? 0 : 1;
2878 /* Remove quote character from argument */
2879 memmove(scan, scan + 1, strlen(scan));
2881 } else if (*scan == '\\') {
2882 /* Literal character, don't parse */
2883 memmove(scan, scan + 1, strlen(scan));
2884 } else if ((*scan == delim) && !paren && !quote) {
2892 array[argc++] = scan;
2897 static void pbx_builtin_setvar_helper(struct ast_channel *chan, const char *name, const char *value)
2899 struct ast_var_t *newvariable;
2900 struct varshead *headp;
2901 const char *nametail = name;
2903 /* XXX may need locking on the channel ? */
2904 if (name[strlen(name)-1] == ')') {
2905 char *function = ast_strdupa(name);
2907 ast_func_write(chan, function, value);
2913 /* For comparison purposes, we have to strip leading underscores */
2914 if (*nametail == '_') {
2916 if (*nametail == '_')
2920 AST_LIST_TRAVERSE (headp, newvariable, entries) {
2921 if (strcasecmp(ast_var_name(newvariable), nametail) == 0) {
2922 /* there is already such a variable, delete it */
2923 AST_LIST_REMOVE(headp, newvariable, entries);
2924 ast_var_delete(newvariable);
2930 if ((option_verbose > 1) && (headp == &globals))
2931 ast_verbose(VERBOSE_PREFIX_2 "Setting global variable '%s' to '%s'\n", name, value);
2932 newvariable = ast_var_assign(name, value);
2933 AST_LIST_INSERT_HEAD(headp, newvariable, entries);
2938 static int pbx_builtin_setvar(struct ast_channel *chan, void *data)
2940 char *name, *value, *mydata;
2942 char *argv[24]; /* this will only support a maximum of 24 variables being set in a single operation */
2946 if (ast_strlen_zero(data)) {
2947 ast_log(LOG_WARNING, "Set requires at least one variable name/value pair.\n");
2951 mydata = ast_strdupa(data);
2952 argc = ast_app_separate_args(mydata, '|', argv, sizeof(argv) / sizeof(argv[0]));
2954 /* check for a trailing flags argument */
2955 if ((argc > 1) && !strchr(argv[argc-1], '=')) {
2957 if (strchr(argv[argc], 'g'))
2961 for (x = 0; x < argc; x++) {
2963 if ((value = strchr(name, '='))) {
2965 pbx_builtin_setvar_helper((global) ? NULL : chan, name, value);
2967 ast_log(LOG_WARNING, "Ignoring entry '%s' with no = (and not last 'options' entry)\n", name);
2973 int localized_pbx_builtin_setvar(struct ast_channel *chan, void *data);
2975 int localized_pbx_builtin_setvar(struct ast_channel *chan, void *data)
2977 return pbx_builtin_setvar(chan, data);
2981 /*! \brief Helper for get_range.
2982 * return the index of the matching entry, starting from 1.
2983 * If names is not supplied, try numeric values.
2986 static int lookup_name(const char *s, char *const names[], int max)
2991 for (i = 0; names[i]; i++) {
2992 if (!strcasecmp(s, names[i]))
2995 } else if (sscanf(s, "%d", &i) == 1 && i >= 1 && i <= max) {
2998 return 0; /* error return */
3001 /*! \brief helper function to return a range up to max (7, 12, 31 respectively).
3002 * names, if supplied, is an array of names that should be mapped to numbers.
3004 static unsigned get_range(char *src, int max, char *const names[], const char *msg)
3006 int s, e; /* start and ending position */
3007 unsigned int mask = 0;
3009 /* Check for whole range */
3010 if (ast_strlen_zero(src) || !strcmp(src, "*")) {
3014 /* Get start and ending position */
3015 char *c = strchr(src, '-');
3018 /* Find the start */
3019 s = lookup_name(src, names, max);
3021 ast_log(LOG_WARNING, "Invalid %s '%s', assuming none\n", msg, src);
3025 if (c) { /* find end of range */
3026 e = lookup_name(c, names, max);
3028 ast_log(LOG_WARNING, "Invalid end %s '%s', assuming none\n", msg, c);
3035 /* Fill the mask. Remember that ranges are cyclic */
3036 mask = 1 << e; /* initialize with last element */
3049 /*! \brief store a bitmask of valid times, one bit each 2 minute */
3050 static void get_timerange(struct ast_timing *i, char *times)
3058 /* start disabling all times, fill the fields with 0's, as they may contain garbage */
3059 memset(i->minmask, 0, sizeof(i->minmask));
3061 /* 2-minutes per bit, since the mask has only 32 bits :( */
3062 /* Star is all times */
3063 if (ast_strlen_zero(times) || !strcmp(times, "*")) {
3064 for (x=0; x<24; x++)
3065 i->minmask[x] = 0x3fffffff; /* 30 bits */
3068 /* Otherwise expect a range */
3069 e = strchr(times, '-');
3071 ast_log(LOG_WARNING, "Time range is not valid. Assuming no restrictions based on time.\n");
3075 /* XXX why skip non digits ? */
3076 while (*e && !isdigit(*e))
3079 ast_log(LOG_WARNING, "Invalid time range. Assuming no restrictions based on time.\n");
3082 if (sscanf(times, "%d:%d", &s1, &s2) != 2) {
3083 ast_log(LOG_WARNING, "%s isn't a time. Assuming no restrictions based on time.\n", times);
3086 if (sscanf(e, "%d:%d", &e1, &e2) != 2) {
3087 ast_log(LOG_WARNING, "%s isn't a time. Assuming no restrictions based on time.\n", e);
3090 /* XXX this needs to be optimized */
3092 s1 = s1 * 30 + s2/2;
3093 if ((s1 < 0) || (s1 >= 24*30)) {
3094 ast_log(LOG_WARNING, "%s isn't a valid start time. Assuming no time.\n", times);
3097 e1 = e1 * 30 + e2/2;
3098 if ((e1 < 0) || (e1 >= 24*30)) {
3099 ast_log(LOG_WARNING, "%s isn't a valid end time. Assuming no time.\n", e);
3102 /* Go through the time and enable each appropriate bit */
3103 for (x=s1;x != e1;x = (x + 1) % (24 * 30)) {
3104 i->minmask[x/30] |= (1 << (x % 30));
3106 /* Do the last one */
3107 i->minmask[x/30] |= (1 << (x % 30));
3109 for (cth=0; cth<24; cth++) {
3110 /* Initialize masks to blank */
3111 i->minmask[cth] = 0;
3112 for (ctm=0; ctm<30; ctm++) {
3114 /* First hour with more than one hour */
3115 (((cth == s1) && (ctm >= s2)) &&
3118 || (((cth == s1) && (ctm >= s2)) &&
3119 ((cth == e1) && (ctm <= e2)))
3120 /* In between first and last hours (more than 2 hours) */
3123 /* Last hour with more than one hour */
3125 ((cth == e1) && (ctm <= e2)))
3127 i->minmask[cth] |= (1 << (ctm / 2));
3135 static void null_datad(void *foo)
3139 /*! \brief Find realtime engine for realtime family */
3140 static struct ast_config_engine *find_engine(const char *family, char *database, int dbsiz, char *table, int tabsiz)
3142 struct ast_config_engine *eng, *ret = NULL;
3143 struct ast_config_map *map;
3146 for (map = config_maps; map; map = map->next) {
3147 if (!strcasecmp(family, map->name)) {
3149 ast_copy_string(database, map->database, dbsiz);
3151 ast_copy_string(table, map->table ? map->table : family, tabsiz);
3156 /* Check if the required driver (engine) exist */
3158 for (eng = config_engine_list; !ret && eng; eng = eng->next) {
3159 if (!strcasecmp(eng->name, map->driver))
3165 /* if we found a mapping, but the engine is not available, then issue a warning */
3167 ast_log(LOG_WARNING, "Realtime mapping for '%s' found to engine '%s', but the engine is not available\n", map->name, map->driver);
3172 struct ast_category *ast_config_get_current_category(const struct ast_config *cfg);
3174 struct ast_category *ast_config_get_current_category(const struct ast_config *cfg)
3176 return cfg->current;
3179 static struct ast_category *ast_category_new(const char *name);
3181 static struct ast_category *ast_category_new(const char *name)
3183 struct ast_category *category;
3185 if ((category = ast_calloc(1, sizeof(*category))))
3186 ast_copy_string(category->name, name, sizeof(category->name));
3190 struct ast_category *localized_category_get(const struct ast_config *config, const char *category_name);
3192 struct ast_category *localized_category_get(const struct ast_config *config, const char *category_name)
3194 return category_get(config, category_name, 0);
3197 static void move_variables(struct ast_category *old, struct ast_category *new)
3199 struct ast_variable *var = old->root;
3202 /* we can just move the entire list in a single op */
3203 ast_variable_append(new, var);
3206 struct ast_variable *next = var->next;
3208 ast_variable_append(new, var);
3214 static void inherit_category(struct ast_category *new, const struct ast_category *base)
3216 struct ast_variable *var;
3218 for (var = base->root; var; var = var->next)
3219 ast_variable_append(new, variable_clone(var));
3222 static void ast_category_append(struct ast_config *config, struct ast_category *category);
3224 static void ast_category_append(struct ast_config *config, struct ast_category *category)
3227 config->last->next = category;
3229 config->root = category;
3230 config->last = category;
3231 config->current = category;
3234 static void ast_category_destroy(struct ast_category *cat);
3236 static void ast_category_destroy(struct ast_category *cat)
3238 ast_variables_destroy(cat->root);
3242 static struct ast_config_engine text_file_engine = {
3244 .load_func = config_text_file_load,
3248 static struct ast_config *ast_config_internal_load(const char *filename, struct ast_config *cfg, int withcomments);
3250 static struct ast_config *ast_config_internal_load(const char *filename, struct ast_config *cfg, int withcomments)
3254 struct ast_config_engine *loader = &text_file_engine;
3255 struct ast_config *result;
3257 if (cfg->include_level == cfg->max_include_level) {
3258 ast_log(LOG_WARNING, "Maximum Include level (%d) exceeded\n", cfg->max_include_level);
3262 cfg->include_level++;
3263 /* silence is golden!
3264 ast_log(LOG_WARNING, "internal loading file %s level=%d\n", filename, cfg->include_level);
3267 if (strcmp(filename, extconfig_conf) && strcmp(filename, "asterisk.conf") && config_engine_list) {
3268 struct ast_config_engine *eng;
3270 eng = find_engine(filename, db, sizeof(db), table, sizeof(table));
3273 if (eng && eng->load_func) {
3276 eng = find_engine("global", db, sizeof(db), table, sizeof(table));
3277 if (eng && eng->load_func)
3282 result = loader->load_func(db, table, filename, cfg, withcomments);
3283 /* silence is golden
3284 ast_log(LOG_WARNING, "finished internal loading file %s level=%d\n", filename, cfg->include_level);
3288 result->include_level--;
3294 static int process_text_line(struct ast_config *cfg, struct ast_category **cat, char *buf, int lineno, const char *configfile, int withcomments)
3298 struct ast_variable *v;
3299 char cmd[512], exec_file[512];
3300 int object, do_exec, do_include;
3302 /* Actually parse the entry */
3303 if (cur[0] == '[') {
3304 struct ast_category *newcat = NULL;
3307 /* A category header */
3308 c = strchr(cur, ']');
3310 ast_log(LOG_WARNING, "parse error: no closing ']', line %d of %s\n", lineno, configfile);
3318 if (!(*cat = newcat = ast_category_new(catname))) {
3322 if (withcomments && comment_buffer && comment_buffer[0] ) {
3323 newcat->precomments = ALLOC_COMMENT(comment_buffer);
3325 if (withcomments && lline_buffer && lline_buffer[0] ) {
3326 newcat->sameline = ALLOC_COMMENT(lline_buffer);