Debian Codegraph @

main/config.c

raw symbols SCIP
1 /*
2 * Asterisk -- An open source telephony toolkit.
3 *
4 * Copyright (C) 1999 - 2010, Digium, Inc.
5 *
6 * Mark Spencer <[email protected]>
7 *
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.
13 *
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.
17 */
18
19 /*! \file
20 *
21 * \brief Configuration File Parser
22 *
23 * \author Mark Spencer <[email protected]>
24 *
25 * Includes the Asterisk Realtime API - ARA
26 * See https://docs.asterisk.org
27 */
28
29 /*** MODULEINFO
30 <support_level>core</support_level>
31 ***/
32
33 /* This maintains the original "module reload extconfig" CLI command instead
34 * of replacing it with "module reload config". */
35 #undef AST_MODULE
36 #define AST_MODULE "extconfig"
37
38 #include "asterisk.h"
39
40 #include "asterisk/paths.h" /* use ast_config_AST_CONFIG_DIR */
41 #include "asterisk/network.h" /* we do some sockaddr manipulation here */
42
43 #include <string.h>
44 #include <libgen.h>
45 #include <time.h>
46 #include <sys/stat.h>
47 #include <sys/wait.h>
48
49 #include <math.h> /* HUGE_VAL */
50 #include <regex.h>
51
52 #include "asterisk/config.h"
53 #include "asterisk/cli.h"
54 #include "asterisk/lock.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/channel.h"
57 #include "asterisk/app.h"
58 #include "asterisk/astobj2.h"
59 #include "asterisk/strings.h" /* for the ast_str_*() API */
60 #include "asterisk/netsock2.h"
61 #include "asterisk/module.h"
62
63 #define MAX_NESTED_COMMENTS 128
64 #define COMMENT_START ";--"
65 #define COMMENT_END "--;"
66 #define COMMENT_META ';'
67 #define COMMENT_TAG '-'
68
69 /*!
70 * Define the minimum filename space to reserve for each
71 * ast_variable in case the filename is renamed later by
72 * ast_include_rename().
73 */
74 #define MIN_VARIABLE_FNAME_SPACE 40
75
76 static char *extconfig_conf = "extconfig.conf";
77
78 static struct ao2_container *cfg_hooks;
79 static void config_hook_exec(const char *filename, const char *module, const struct ast_config *cfg);
80 static inline struct ast_variable *variable_list_switch(struct ast_variable *l1, struct ast_variable *l2);
81 static int does_category_match(struct ast_category *cat, const char *category_name,
82 const char *match, char sep);
83
84 /*! \brief Structure to keep comments for rewriting configuration files */
85 struct ast_comment {
86 struct ast_comment *next;
87 /*! Comment body allocated after struct. */
88 char cmt[0];
89 };
90
91 /*! \brief Hold the mtime for config files, so if we don't need to reread our config, don't. */
92 struct cache_file_include {
93 AST_LIST_ENTRY(cache_file_include) list;
94 /*! Filename or wildcard pattern as specified by the including file. */
95 char include[0];
96 };
97
98 struct cache_file_mtime {
99 AST_LIST_ENTRY(cache_file_mtime) list;
100 AST_LIST_HEAD_NOLOCK(includes, cache_file_include) includes;
101 unsigned int has_exec:1;
102 /*! stat() file size */
103 unsigned long stat_size;
104 /*! stat() file modtime nanoseconds */
105 unsigned long stat_mtime_nsec;
106 /*! stat() file modtime seconds since epoc */
107 time_t stat_mtime;
108
109 /*! String stuffed in filename[] after the filename string. */
110 const char *who_asked;
111 /*! Filename and who_asked stuffed after it. */
112 char filename[0];
113 };
114
115 /*! Cached file mtime list. */
116 static AST_LIST_HEAD_STATIC(cfmtime_head, cache_file_mtime);
117
118 static int init_appendbuf(void *data)
119 {
120 struct ast_str **str = data;
121 *str = ast_str_create(16);
122 return *str ? 0 : -1;
123 }
124
125 AST_THREADSTORAGE_CUSTOM(appendbuf, init_appendbuf, ast_free_ptr);
126
127 /* comment buffers are better implemented using the ast_str_*() API */
128 #define CB_SIZE 250 /* initial size of comment buffers */
129
130 static void CB_ADD(struct ast_str **cb, const char *str)
131 {
132 ast_str_append(cb, 0, "%s", str);
133 }
134
135 static void CB_ADD_LEN(struct ast_str **cb, const char *str, int len)
136 {
137 char *s = ast_alloca(len + 1);
138
139 memcpy(s, str, len);
140 s[len] = '\0';
141 ast_str_append(cb, 0, "%s", s);
142 }
143
144 static void CB_RESET(struct ast_str *cb, struct ast_str *llb)
145 {
146 if (cb) {
147 ast_str_reset(cb);
148 }
149 if (llb) {
150 ast_str_reset(llb);
151 }
152 }
153
154 static struct ast_comment *ALLOC_COMMENT(struct ast_str *buffer)
155 {
156 struct ast_comment *x = NULL;
157 if (!buffer || !ast_str_strlen(buffer)) {
158 return NULL;
159 }
160 if ((x = ast_calloc(1, sizeof(*x) + ast_str_strlen(buffer) + 1))) {
161 strcpy(x->cmt, ast_str_buffer(buffer)); /* SAFE */
162 }
163 return x;
164 }
165
166 /* I need to keep track of each config file, and all its inclusions,
167 so that we can track blank lines in each */
168
169 struct inclfile {
170 char *fname;
171 int lineno;
172 };
173
174 static int hash_string(const void *obj, const int flags)
175 {
176 char *str = ((struct inclfile *) obj)->fname;
177 int total;
178
179 for (total = 0; *str; str++) {
180 unsigned int tmp = total;
181 total <<= 1; /* multiply by 2 */
182 total += tmp; /* multiply by 3 */
183 total <<= 2; /* multiply by 12 */
184 total += tmp; /* multiply by 13 */
185
186 total += ((unsigned int) (*str));
187 }
188 if (total < 0) {
189 total = -total;
190 }
191 return total;
192 }
193
194 static int hashtab_compare_strings(void *a, void *b, int flags)
195 {
196 const struct inclfile *ae = a, *be = b;
197 return !strcmp(ae->fname, be->fname) ? CMP_MATCH | CMP_STOP : 0;
198 }
199
200 static struct ast_config_map {
201 struct ast_config_map *next;
202 int priority;
203 /*! Stored in stuff[] at struct end. */
204 const char *name;
205 /*! Stored in stuff[] at struct end. */
206 const char *driver;
207 /*! Stored in stuff[] at struct end. */
208 const char *database;
209 /*! Stored in stuff[] at struct end. */
210 const char *table;
211 /*! Contents of name, driver, database, and table in that order stuffed here. */
212 char stuff[0];
213 } *config_maps = NULL;
214
215 AST_MUTEX_DEFINE_STATIC(config_lock);
216 static struct ast_config_engine *config_engine_list;
217
218 #define MAX_INCLUDE_LEVEL 10
219
220 struct ast_category_template_instance {
221 char name[80]; /* redundant? */
222 const struct ast_category *inst;
223 AST_LIST_ENTRY(ast_category_template_instance) next;
224 };
225
226 struct ast_category {
227 char name[80];
228 int ignored; /*!< do not let user of the config see this category -- set by (!) after the category decl; a template */
229 int include_level;
230 /*!
231 * \brief The file name from whence this declaration was read
232 * \note Will never be NULL
233 */
234 char *file;
235 int lineno;
236 AST_LIST_HEAD_NOLOCK(template_instance_list, ast_category_template_instance) template_instances;
237 struct ast_comment *precomments;
238 struct ast_comment *sameline;
239 struct ast_comment *trailing; /*!< the last object in the list will get assigned any trailing comments when EOF is hit */
240 /*! First category variable in the list. */
241 struct ast_variable *root;
242 /*! Last category variable in the list. */
243 struct ast_variable *last;
244 /*! Previous node in the list. */
245 struct ast_category *prev;
246 /*! Next node in the list. */
247 struct ast_category *next;
248 };
249
250 struct ast_config {
251 /*! First config category in the list. */
252 struct ast_category *root;
253 /*! Last config category in the list. */
254 struct ast_category *last;
255 struct ast_category *current;
256 struct ast_category *last_browse; /*!< used to cache the last category supplied via category_browse */
257 int include_level;
258 int max_include_level;
259 /*! First inclusion in the list. */
260 struct ast_config_include *includes_root;
261 /*! Last inclusion in the list. */
262 struct ast_config_include *includes_last;
263 };
264
265 struct config_included_file {
266 AST_LIST_ENTRY(config_included_file) next;
267 /*! #include path or matching #tryinclude paths */
268 char path[];
269 };
270
271 /*!
272 * \brief Types used for ast_include_new() include_type
273 */
274 enum include_statement_type {
275 /*! #include statements */
276 CONFIG_STATEMENT_INCLUDE = 0,
277 /*! #exec statements */
278 CONFIG_STATEMENT_EXEC = 1,
279 /*! #tryinclude statements */
280 CONFIG_STATEMENT_TRYINCLUDE = 2,
281 };
282
283 struct ast_config_include {
284 /*!
285 * \brief file name in which the include occurs
286 * \note Will never be NULL
287 */
288 char *include_location_file;
289 int include_location_lineno; /*!< lineno where include occurred */
290 enum include_statement_type include_type; /*!< #include, #exec, #tryinclude */
291 /*!
292 * \brief if it's an exec, you'll have both the /var/tmp to read, and the original script
293 * \note Will never be NULL if exec is non-zero
294 */
295 char *exec_file;
296 /*!
297 * \brief file name included
298 * \note Will never be NULL
299 */
300 char *included_file;
301 AST_LIST_HEAD_NOLOCK(included_files_list, config_included_file) included_files; /*!< list of #include/#tryinclude files */
302 int inclusion_count; /*!< if the file is included more than once, a running count thereof -- but, worry not,
303 we explode the instances and will include those-- so all entries will be unique */
304 int output; /*!< a flag to indicate if the inclusion has been output */
305 struct ast_comment *precomments;
306 struct ast_comment *sameline;
307 struct ast_comment *trailing; /*!< the last object in the list will get assigned any trailing comments when EOF is hit */
308 struct ast_config_include *next; /*!< ptr to next inclusion in the list */
309 };
310
311 static void ast_variable_destroy(struct ast_variable *doomed);
312 static void ast_includes_destroy(struct ast_config_include *incls);
313
314 struct ast_variable *_ast_variable_new(const char *name, const char *value, const char *filename, const char *file, const char *func, int lineno)
315 {
316 struct ast_variable *variable;
317 int name_len = strlen(name) + 1;
318 int val_len = strlen(value) + 1;
319 int fn_len = strlen(filename) + 1;
320
321 /* Ensure a minimum length in case the filename is changed later. */
322 if (fn_len < MIN_VARIABLE_FNAME_SPACE) {
323 fn_len = MIN_VARIABLE_FNAME_SPACE;
324 }
325
326 variable = __ast_calloc(1, fn_len + name_len + val_len + sizeof(*variable),
327 file, lineno, func);
328 if (variable) {
329 char *dst = variable->stuff; /* writable space starts here */
330
331 /* Put file first so ast_include_rename() can calculate space available. */
332 variable->file = strcpy(dst, filename);
333 dst += fn_len;
334 variable->name = strcpy(dst, name);
335 dst += name_len;
336 variable->value = strcpy(dst, value);
337 }
338 return variable;
339 }
340
341 /*!
342 * \internal
343 * \brief Move the contents from the source to the destination variable.
344 *
345 * \param dst_var Destination variable node
346 * \param src_var Source variable node
347 */
348 static void ast_variable_move(struct ast_variable *dst_var, struct ast_variable *src_var)
349 {
350 dst_var->lineno = src_var->lineno;
351 dst_var->object = src_var->object;
352 dst_var->blanklines = src_var->blanklines;
353 dst_var->precomments = src_var->precomments;
354 src_var->precomments = NULL;
355 dst_var->sameline = src_var->sameline;
356 src_var->sameline = NULL;
357 dst_var->trailing = src_var->trailing;
358 src_var->trailing = NULL;
359 }
360
361 static void make_fn(char *fn, size_t fn_size, const char *file, const char *configfile);
362
363 struct ast_config_include *ast_include_new(struct ast_config *conf, const char *from_file, const char *included_file, int include_type, const char *exec_file, int from_lineno, char *real_included_file_name, int real_included_file_name_size)
364 {
365 /* a file should be included ONCE. Otherwise, if one of the instances is changed,
366 * then all be changed. -- how do we know to include it? -- Handling modified
367 * instances is possible, I'd have
368 * to create a new master for each instance. */
369 struct ast_config_include *inc;
370 struct config_included_file *inc_file;
371 struct stat statbuf;
372 char fn[PATH_MAX];
373
374 inc = ast_include_find(conf, included_file);
375 if (inc) {
376 do {
377 inc->inclusion_count++;
378 snprintf(real_included_file_name, real_included_file_name_size, "%s~~%d", included_file, inc->inclusion_count);
379 } while (stat(real_included_file_name, &statbuf) == 0);
380 ast_log(LOG_WARNING, "'%s', line %d: Same File included more than once! This data will be saved in %s if saved back to disk.\n", from_file, from_lineno, real_included_file_name);
381 } else
382 *real_included_file_name = 0;
383
384 inc = ast_calloc(1,sizeof(struct ast_config_include));
385 if (!inc) {
386 return NULL;
387 }
388 inc->include_location_file = ast_strdup(from_file);
389 if (!inc->include_location_file) {
390 ast_includes_destroy(inc);
391 return NULL;
392 }
393 inc->include_location_lineno = from_lineno;
394 if (!ast_strlen_zero(real_included_file_name)) {
395 inc->included_file = ast_strdup(real_included_file_name);
396 } else {
397 inc->included_file = ast_strdup(included_file);
398 }
399 if (!inc->included_file) {
400 ast_includes_destroy(inc);
401 return NULL;
402 }
403
404 inc->include_type = include_type;
405
406 make_fn(fn, sizeof(fn), inc->included_file, from_file);
407 switch (inc->include_type) {
408 case CONFIG_STATEMENT_INCLUDE:
409 inc_file = ast_calloc(1, sizeof(*inc_file) + strlen(fn) + 1);
410 if (!inc_file) {
411 ast_includes_destroy(inc);
412 return NULL;
413 }
414 strcpy(inc_file->path, fn); /* safe */
415 AST_LIST_INSERT_TAIL(&inc->included_files, inc_file, next);
416 break;
417 case CONFIG_STATEMENT_TRYINCLUDE:
418 {
419 int glob_ret;
420 glob_t globbuf;
421
422 /* add files that match the pattern */
423 globbuf.gl_offs = 0;
424 glob_ret = glob(fn, MY_GLOB_FLAGS, NULL, &globbuf);
425 if (glob_ret == 0) {
426 int i;
427
428 for (i = 0; i < globbuf.gl_pathc; i++) {
429 char *matched_path = globbuf.gl_pathv[i];
430
431 if (access(matched_path, F_OK) != 0) {
432 /* skip #tryinclude paths that do not already exist. */
433 continue;
434 }
435
436 inc_file = ast_calloc(1, sizeof(*inc_file) + strlen(matched_path) + 1);
437 if (!inc_file) {
438 ast_includes_destroy(inc);
439 globfree(&globbuf);
440 return NULL;
441 }
442 strcpy(inc_file->path, matched_path); /* safe */
443 AST_LIST_INSERT_TAIL(&inc->included_files, inc_file, next);
444 }
445 }
446 globfree(&globbuf);
447 break;
448 }
449 case CONFIG_STATEMENT_EXEC:
450 inc->exec_file = ast_strdup(exec_file);
451 if (!inc->exec_file) {
452 ast_includes_destroy(inc);
453 return NULL;
454 }
455 break;
456 }
457
458 /* attach this new struct to the conf struct */
459 if (conf->includes_root && conf->includes_last) {
460 conf->includes_last->next = inc;
461 } else {
462 conf->includes_root = inc;
463 }
464 conf->includes_last = inc;
465
466 return inc;
467 }
468
469 void ast_include_rename(struct ast_config *conf, const char *from_file, const char *to_file)
470 {
471 struct ast_config_include *incl;
472 struct ast_category *cat;
473 char *str;
474
475 int from_len = strlen(from_file);
476 int to_len = strlen(to_file);
477
478 if (strcmp(from_file, to_file) == 0) /* no use wasting time if the name is the same */
479 return;
480
481 /* the manager code allows you to read in one config file, then
482 * write it back out under a different name. But, the new arrangement
483 * ties output lines to the file name. So, before you try to write
484 * the config file to disk, better riffle thru the data and make sure
485 * the file names are changed.
486 */
487 /* file names are on categories, includes (of course), and on variables. So,
488 * traverse all this and swap names */
489
490 for (incl = conf->includes_root; incl; incl = incl->next) {
491 if (strcmp(incl->include_location_file, from_file) == 0) {
492 if (from_len >= to_len)
493 strcpy(incl->include_location_file, to_file);
494 else {
495 /* Keep the old filename if the allocation fails. */
496 str = ast_strdup(to_file);
497 if (str) {
498 ast_free(incl->include_location_file);
499 incl->include_location_file = str;
500 }
501 }
502 }
503 }
504 for (cat = conf->root; cat; cat = cat->next) {
505 struct ast_variable **prev;
506 struct ast_variable *v;
507 struct ast_variable *new_var;
508
509 if (strcmp(cat->file, from_file) == 0) {
510 if (from_len >= to_len)
511 strcpy(cat->file, to_file);
512 else {
513 /* Keep the old filename if the allocation fails. */
514 str = ast_strdup(to_file);
515 if (str) {
516 ast_free(cat->file);
517 cat->file = str;
518 }
519 }
520 }
521 for (prev = &cat->root, v = cat->root; v; prev = &v->next, v = v->next) {
522 if (strcmp(v->file, from_file)) {
523 continue;
524 }
525
526 /*
527 * Calculate actual space available. The file string is
528 * intentionally stuffed before the name string just so we can
529 * do this.
530 */
531 if (to_len < v->name - v->file) {
532 /* The new name will fit in the available space. */
533 str = (char *) v->file;/* Stupid compiler complains about discarding qualifiers even though I used a cast. */
534 strcpy(str, to_file);/* SAFE */
535 continue;
536 }
537
538 /* Keep the old filename if the allocation fails. */
539 new_var = ast_variable_new(v->name, v->value, to_file);
540 if (!new_var) {
541 continue;
542 }
543
544 /* Move items from the old list node to the replacement node. */
545 ast_variable_move(new_var, v);
546
547 /* Replace the old node in the list with the new node. */
548 new_var->next = v->next;
549 if (cat->last == v) {
550 cat->last = new_var;
551 }
552 *prev = new_var;
553
554 ast_variable_destroy(v);
555
556 v = new_var;
557 }
558 }
559 }
560
561 struct ast_config_include *ast_include_find(struct ast_config *conf, const char *included_file)
562 {
563 struct ast_config_include *x;
564 for (x = conf->includes_root; x; x = x->next) {
565 if (strcmp(x->included_file, included_file) == 0)
566 return x;
567 }
568 return 0;
569 }
570
571
572 void ast_variable_append(struct ast_category *category, struct ast_variable *variable)
573 {
574 if (!variable)
575 return;
576 if (category->last)
577 category->last->next = variable;
578 else
579 category->root = variable;
580 category->last = variable;
581 while (category->last->next)
582 category->last = category->last->next;
583 }
584
585 void ast_variable_insert(struct ast_category *category, struct ast_variable *variable, const char *line)
586 {
587 struct ast_variable *cur = category->root;
588 int lineno;
589 int insertline;
590
591 if (!variable || sscanf(line, "%30d", &insertline) != 1) {
592 return;
593 }
594 if (!insertline) {
595 variable->next = category->root;
596 category->root = variable;
597 } else {
598 for (lineno = 1; lineno < insertline; lineno++) {
599 cur = cur->next;
600 if (!cur->next) {
601 break;
602 }
603 }
604 variable->next = cur->next;
605 cur->next = variable;
606 }
607 }
608
609 static void ast_comment_destroy(struct ast_comment **comment)
610 {
611 struct ast_comment *n, *p;
612
613 for (p = *comment; p; p = n) {
614 n = p->next;
615 ast_free(p);
616 }
617
618 *comment = NULL;
619 }
620
621 static void ast_variable_destroy(struct ast_variable *doomed)
622 {
623 ast_comment_destroy(&doomed->precomments);
624 ast_comment_destroy(&doomed->sameline);
625 ast_comment_destroy(&doomed->trailing);
626 ast_free(doomed);
627 }
628
629 struct ast_variable *ast_variables_dup(struct ast_variable *var)
630 {
631 struct ast_variable *cloned;
632 struct ast_variable *tmp;
633
634 if (!(cloned = ast_variable_new(var->name, var->value, var->file))) {
635 return NULL;
636 }
637
638 tmp = cloned;
639
640 while ((var = var->next)) {
641 if (!(tmp->next = ast_variable_new(var->name, var->value, var->file))) {
642 ast_variables_destroy(cloned);
643 return NULL;
644 }
645 tmp = tmp->next;
646 }
647
648 return cloned;
649 }
650
651 struct ast_variable *ast_variables_reverse(struct ast_variable *var)
652 {
653 struct ast_variable *var1, *var2;
654
655 var1 = var;
656
657 if (!var1 || !var1->next) {
658 return var1;
659 }
660
661 var2 = var1->next;
662 var1->next = NULL;
663
664 while (var2) {
665 struct ast_variable *next = var2->next;
666
667 var2->next = var1;
668 var1 = var2;
669 var2 = next;
670 }
671
672 return var1;
673 }
674
675 void ast_variables_destroy(struct ast_variable *var)
676 {
677 struct ast_variable *vn;
678
679 while (var) {
680 vn = var;
681 var = var->next;
682 ast_variable_destroy(vn);
683 }
684 }
685
686 struct ast_variable *ast_variable_browse(const struct ast_config *config, const char *category)
687 {
688 struct ast_category *cat;
689
690 if (config->last_browse && (config->last_browse->name == category)) {
691 cat = config->last_browse;
692 } else {
693 cat = ast_category_get(config, category, NULL);
694 }
695
696 return (cat) ? cat->root : NULL;
697 }
698
699 static inline struct ast_variable *variable_list_switch(struct ast_variable *l1, struct ast_variable *l2)
700 {
701 l1->next = l2->next;
702 l2->next = l1;
703 return l2;
704 }
705
706 struct ast_variable *ast_variable_list_sort(struct ast_variable *start)
707 {
708 struct ast_variable *p, *q;
709 struct ast_variable top;
710 int changed = 1;
711 memset(&top, 0, sizeof(top));
712 top.next = start;
713 if (start != NULL && start->next != NULL) {
714 while (changed) {
715 changed = 0;
716 q = &top;
717 p = top.next;
718 while (p->next != NULL) {
719 if (p->next != NULL && strcmp(p->name, p->next->name) > 0) {
720 q->next = variable_list_switch(p, p->next);
721 changed = 1;
722 }
723 q = p;
724 if (p->next != NULL)
725 p = p->next;
726 }
727 }
728 }
729 return top.next;
730 }
731
732 struct ast_variable *ast_variable_list_append_hint(struct ast_variable **head, struct ast_variable *search_hint, struct ast_variable *newvar)
733 {
734 struct ast_variable *curr;
735 struct ast_variable *sh = search_hint;
736 ast_assert(head != NULL);
737
738 if (!*head) {
739 *head = newvar;
740 } else {
741 if (sh == NULL) {
742 sh = *head;
743 }
744 for (curr = sh; curr->next; curr = curr->next);
745 curr->next = newvar;
746 }
747
748 for (curr = newvar; curr->next; curr = curr->next);
749
750 return curr;
751 }
752
753 int ast_variable_list_replace(struct ast_variable **head, struct ast_variable *replacement)
754 {
755 struct ast_variable *v, **prev = head;
756
757 for (v = *head; v; prev = &v->next, v = v->next) {
758 if (!strcmp(v->name, replacement->name)) {
759 replacement->next = v->next;
760 *prev = replacement;
761 ast_free(v);
762 return 0;
763 }
764 }
765
766 return -1;
767 }
768
769 int ast_variable_list_replace_variable(struct ast_variable **head, struct ast_variable *old,
770 struct ast_variable *new)
771 {
772 struct ast_variable *v, **prev = head;
773
774 for (v = *head; v; prev = &v->next, v = v->next) {
775 if (v == old) {
776 new->next = v->next;
777 *prev = new;
778 ast_free(v);
779 return 0;
780 }
781 }
782
783 return -1;
784 }
785
786 struct ast_str *ast_variable_list_join(const struct ast_variable *head, const char *item_separator,
787 const char *name_value_separator, const char *quote_char, struct ast_str **str)
788 {
789 struct ast_variable *var = (struct ast_variable *)head;
790 struct ast_str *local_str = NULL;
791
792 if (str == NULL || *str == NULL) {
793 local_str = ast_str_create(AST_MAX_USER_FIELD);
794 if (!local_str) {
795 return NULL;
796 }
797 } else {
798 local_str = *str;
799 }
800
801 for (; var; var = var->next) {
802 ast_str_append(&local_str, 0, "%s%s%s%s%s%s", var->name, name_value_separator, S_OR(quote_char, ""),
803 var->value, S_OR(quote_char, ""), var->next ? item_separator : "");
804 }
805
806 if (str != NULL) {
807 *str = local_str;
808 }
809 return local_str;
810 }
811
812 struct ast_variable *ast_variable_list_from_quoted_string(const char *input, const char *item_separator,
813 const char *name_value_separator, const char *quote_str)
814 {
815 char item_sep;
816 char nv_sep;
817 char quote;
818 struct ast_variable *new_list = NULL;
819 struct ast_variable *new_var = NULL;
820 char *item_string;
821 char *item;
822 char *item_name;
823 char *item_value;
824
825 if (ast_strlen_zero(input)) {
826 return NULL;
827 }
828
829 item_sep = ast_strlen_zero(item_separator) ? ',' : item_separator[0];
830 nv_sep = ast_strlen_zero(name_value_separator) ? '=' : name_value_separator[0];
831 quote = ast_strlen_zero(quote_str) ? '"' : quote_str[0];
832 item_string = ast_strip(ast_strdupa(input));
833
834 while ((item = ast_strsep_quoted(&item_string, item_sep, quote, AST_STRSEP_ALL))) {
835 item_name = ast_strsep_quoted(&item, nv_sep, quote, AST_STRSEP_ALL);
836 if (!item_name) {
837 ast_variables_destroy(new_list);
838 return NULL;
839 }
840
841 item_value = ast_strsep_quoted(&item, nv_sep, quote, AST_STRSEP_ALL);
842
843 new_var = ast_variable_new(item_name, item_value ?: "", "");
844 if (!new_var) {
845 ast_variables_destroy(new_list);
846 return NULL;
847 }
848 ast_variable_list_append(&new_list, new_var);
849 }
850 return new_list;
851 }
852
853 struct ast_variable *ast_variable_list_from_string(const char *input, const char *item_separator,
854 const char *name_value_separator)
855 {
856 return ast_variable_list_from_quoted_string(input, item_separator, name_value_separator, NULL);
857 }
858
859 const char *ast_config_option(struct ast_config *cfg, const char *cat, const char *var)
860 {
861 const char *tmp;
862 tmp = ast_variable_retrieve(cfg, cat, var);
863 if (!tmp) {
864 tmp = ast_variable_retrieve(cfg, "general", var);
865 }
866 return tmp;
867 }
868
869 const char *ast_variable_retrieve(struct ast_config *config, const char *category, const char *variable)
870 {
871 struct ast_variable *v;
872
873 if (category) {
874 for (v = ast_variable_browse(config, category); v; v = v->next) {
875 if (!strcasecmp(variable, v->name)) {
876 return v->value;
877 }
878 }
879 } else {
880 struct ast_category *cat;
881
882 for (cat = config->root; cat; cat = cat->next) {
883 for (v = cat->root; v; v = v->next) {
884 if (!strcasecmp(variable, v->name)) {
885 return v->value;
886 }
887 }
888 }
889 }
890
891 return NULL;
892 }
893
894 const char *ast_variable_retrieve_filtered(struct ast_config *config,
895 const char *category, const char *variable, const char *filter)
896 {
897 struct ast_category *cat = NULL;
898 const char *value;
899
900 while ((cat = ast_category_browse_filtered(config, category, cat, filter))) {
901 value = ast_variable_find(cat, variable);
902 if (value) {
903 return value;
904 }
905 }
906
907 return NULL;
908 }
909
910 const char *ast_variable_find(const struct ast_category *category, const char *variable)
911 {
912 return ast_variable_find_in_list(category->root, variable);
913 }
914
915 const struct ast_variable *ast_variable_find_variable_in_list(const struct ast_variable *list, const char *variable_name)
916 {
917 const struct ast_variable *v;
918
919 for (v = list; v; v = v->next) {
920 if (!strcasecmp(variable_name, v->name)) {
921 return v;
922 }
923 }
924 return NULL;
925 }
926
927 int ast_variables_match(const struct ast_variable *left, const struct ast_variable *right)
928 {
929 const char *op;
930
931 if (left == right) {
932 return 1;
933 }
934
935 if (!(left && right)) {
936 return 0;
937 }
938
939 op = strrchr(right->name, ' ');
940 if (op) {
941 op++;
942 }
943
944 return ast_strings_match(left->value, op ? ast_strdupa(op) : NULL, right->value);
945 }
946
947 int ast_variable_lists_match(const struct ast_variable *left, const struct ast_variable *right, int exact_match)
948 {
949 const struct ast_variable *field;
950 int right_count = 0;
951 int left_count = 0;
952
953 if (left == right) {
954 return 1;
955 }
956
957 if (!(left && right)) {
958 return 0;
959 }
960
961 for (field = right; field; field = field->next) {
962 const char *space = strrchr(field->name, ' ');
963 const struct ast_variable *old;
964 char * name = (char *)field->name;
965
966 if (space) {
967 name = ast_strdup(field->name);
968 if (!name) {
969 return 0;
970 }
971 name[space - field->name] = '\0';
972 }
973
974 old = ast_variable_find_variable_in_list(left, name);
975 if (name != field->name) {
976 ast_free(name);
977 }
978
979 if (exact_match) {
980 if (!old || strcmp(old->value, field->value)) {
981 return 0;
982 }
983 } else {
984 if (!ast_variables_match(old, field)) {
985 return 0;
986 }
987 }
988
989 right_count++;
990 }
991
992 if (exact_match) {
993 for (field = left; field; field = field->next) {
994 left_count++;
995 }
996
997 if (right_count != left_count) {
998 return 0;
999 }
1000 }
1001
1002 return 1;
1003 }
1004
1005 const char *ast_variable_find_in_list(const struct ast_variable *list, const char *variable)
1006 {
1007 const struct ast_variable *v;
1008
1009 for (v = list; v; v = v->next) {
1010 if (!strcasecmp(variable, v->name)) {
1011 return v->value;
1012 }
1013 }
1014 return NULL;
1015 }
1016
1017 const char *ast_variable_find_last_in_list(const struct ast_variable *list, const char *variable)
1018 {
1019 const struct ast_variable *v;
1020 const char *found = NULL;
1021
1022 for (v = list; v; v = v->next) {
1023 if (!strcasecmp(variable, v->name)) {
1024 found = v->value;
1025 }
1026 }
1027 return found;
1028 }
1029
1030 static struct ast_variable *variable_clone(const struct ast_variable *old)
1031 {
1032 struct ast_variable *new = ast_variable_new(old->name, old->value, old->file);
1033
1034 if (new) {
1035 new->lineno = old->lineno;
1036 new->object = old->object;
1037 new->blanklines = old->blanklines;
1038 /* TODO: clone comments? */
1039 }
1040
1041 return new;
1042 }
1043
1044 static void move_variables(struct ast_category *old, struct ast_category *new)
1045 {
1046 struct ast_variable *var = old->root;
1047
1048 old->root = NULL;
1049 /* we can just move the entire list in a single op */
1050 ast_variable_append(new, var);
1051 }
1052
1053 /*! \brief Returns true if ALL of the regex expressions and category name match.
1054 * Both can be NULL (I.E. no predicate) which results in a true return;
1055 */
1056 static int does_category_match(struct ast_category *cat, const char *category_name,
1057 const char *match, char sep)
1058 {
1059 char *dupmatch;
1060 char *nvp = NULL;
1061 int match_found = 0, match_expressions = 0;
1062 int template_ok = 0;
1063
1064 /* Only match on category name if it's not a NULL or empty string */
1065 if (!ast_strlen_zero(category_name) && strcasecmp(cat->name, category_name)) {
1066 return 0;
1067 }
1068
1069 /* If match is NULL or empty, automatically match if not a template */
1070 if (ast_strlen_zero(match)) {
1071 return !cat->ignored;
1072 }
1073
1074 dupmatch = ast_strdupa(match);
1075
1076 while ((nvp = ast_strsep(&dupmatch, sep, AST_STRSEP_STRIP))) {
1077 struct ast_variable *v;
1078 char *match_name;
1079 char *match_value = NULL;
1080 char *regerr;
1081 int rc;
1082 regex_t r_name, r_value;
1083
1084 match_expressions++;
1085
1086 match_name = ast_strsep(&nvp, '=', AST_STRSEP_STRIP);
1087 match_value = ast_strsep(&nvp, '=', AST_STRSEP_STRIP);
1088
1089 /* an empty match value is OK. A NULL match value (no =) is NOT. */
1090 if (match_value == NULL) {
1091 break;
1092 }
1093
1094 if (!strcmp("TEMPLATES", match_name)) {
1095 if (!strcasecmp("include", match_value)) {
1096 if (cat->ignored) {
1097 template_ok = 1;
1098 }
1099 match_found++;
1100 } else if (!strcasecmp("restrict", match_value)) {
1101 if (cat->ignored) {
1102 match_found++;
1103 template_ok = 1;
1104 } else {
1105 break;
1106 }
1107 }
1108 continue;
1109 }
1110
1111 if ((rc = regcomp(&r_name, match_name, REG_EXTENDED | REG_NOSUB))) {
1112 regerr = ast_alloca(128);
1113 regerror(rc, &r_name, regerr, 128);
1114 ast_log(LOG_ERROR, "Regular expression '%s' failed to compile: %s\n",
1115 match_name, regerr);
1116 regfree(&r_name);
1117 return 0;
1118 }
1119 if ((rc = regcomp(&r_value, match_value, REG_EXTENDED | REG_NOSUB))) {
1120 regerr = ast_alloca(128);
1121 regerror(rc, &r_value, regerr, 128);
1122 ast_log(LOG_ERROR, "Regular expression '%s' failed to compile: %s\n",
1123 match_value, regerr);
1124 regfree(&r_name);
1125 regfree(&r_value);
1126 return 0;
1127 }
1128
1129 for (v = cat->root; v; v = v->next) {
1130 if (!regexec(&r_name, v->name, 0, NULL, 0)
1131 && !regexec(&r_value, v->value, 0, NULL, 0)) {
1132 match_found++;
1133 break;
1134 }
1135 }
1136 regfree(&r_name);
1137 regfree(&r_value);
1138 }
1139 if (match_found == match_expressions && (!cat->ignored || template_ok)) {
1140 return 1;
1141 }
1142 return 0;
1143 }
1144
1145
1146 static struct ast_category *new_category(const char *name, const char *in_file, int lineno, int template)
1147 {
1148 struct ast_category *category;
1149
1150 category = ast_calloc(1, sizeof(*category));
1151 if (!category) {
1152 return NULL;
1153 }
1154 category->file = ast_strdup(in_file);
1155 if (!category->file) {
1156 ast_category_destroy(category);
1157 return NULL;
1158 }
1159 ast_copy_string(category->name, name, sizeof(category->name));
1160 category->lineno = lineno; /* if you don't know the lineno, set it to 999999 or something real big */
1161 category->ignored = template;
1162 return category;
1163 }
1164
1165 struct ast_category *ast_category_new(const char *name, const char *in_file, int lineno)
1166 {
1167 return new_category(name, in_file, lineno, 0);
1168 }
1169
1170 struct ast_category *ast_category_new_template(const char *name, const char *in_file, int lineno)
1171 {
1172 return new_category(name, in_file, lineno, 1);
1173 }
1174
1175 static struct ast_category *category_get_sep(const struct ast_config *config,
1176 const char *category_name, const char *filter, char sep, char pointer_match_possible)
1177 {
1178 struct ast_category *cat;
1179
1180 if (pointer_match_possible) {
1181 for (cat = config->root; cat; cat = cat->next) {
1182 if (cat->name == category_name && does_category_match(cat, category_name, filter, sep)) {
1183 return cat;
1184 }
1185 }
1186 }
1187
1188 for (cat = config->root; cat; cat = cat->next) {
1189 if (does_category_match(cat, category_name, filter, sep)) {
1190 return cat;
1191 }
1192 }
1193
1194 return NULL;
1195 }
1196
1197 struct ast_category *ast_category_get(const struct ast_config *config,
1198 const char *category_name, const char *filter)
1199 {
1200 return category_get_sep(config, category_name, filter, ',', 1);
1201 }
1202
1203 const char *ast_category_get_name(const struct ast_category *category)
1204 {
1205 return category->name;
1206 }
1207
1208 int ast_category_is_template(const struct ast_category *category)
1209 {
1210 return category->ignored;
1211 }
1212
1213 struct ast_str *ast_category_get_templates(const struct ast_category *category)
1214 {
1215 struct ast_category_template_instance *template;
1216 struct ast_str *str;
1217 int first = 1;
1218
1219 if (AST_LIST_EMPTY(&category->template_instances)) {
1220 return NULL;
1221 }
1222
1223 str = ast_str_create(128);
1224 if (!str) {
1225 return NULL;
1226 }
1227
1228 AST_LIST_TRAVERSE(&category->template_instances, template, next) {
1229 ast_str_append(&str, 0, "%s%s", first ? "" : ",", template->name);
1230 first = 0;
1231 }
1232
1233 return str;
1234 }
1235
1236 int ast_category_exist(const struct ast_config *config, const char *category_name,
1237 const char *filter)
1238 {
1239 return !!ast_category_get(config, category_name, filter);
1240 }
1241
1242 void ast_category_append(struct ast_config *config, struct ast_category *category)
1243 {
1244 if (config->last) {
1245 config->last->next = category;
1246 category->prev = config->last;
1247 } else {
1248 config->root = category;
1249 category->prev = NULL;
1250 }
1251 category->next = NULL;
1252 category->include_level = config->include_level;
1253
1254 config->last = category;
1255 config->current = category;
1256 }
1257
1258 int ast_category_insert(struct ast_config *config, struct ast_category *cat, const char *match)
1259 {
1260 struct ast_category *cur_category;
1261
1262 if (!config || !config->root || !cat || !match) {
1263 return -1;
1264 }
1265
1266 if (!strcasecmp(config->root->name, match)) {
1267 cat->next = config->root;
1268 cat->prev = NULL;
1269 config->root->prev = cat;
1270 config->root = cat;
1271 return 0;
1272 }
1273
1274 for (cur_category = config->root->next; cur_category; cur_category = cur_category->next) {
1275 if (!strcasecmp(cur_category->name, match)) {
1276 cat->prev = cur_category->prev;
1277 cat->prev->next = cat;
1278
1279 cat->next = cur_category;
1280 cur_category->prev = cat;
1281
1282 return 0;
1283 }
1284 }
1285
1286 return -1;
1287 }
1288
1289 static void ast_destroy_template_list(struct ast_category *cat)
1290 {
1291 struct ast_category_template_instance *x;
1292
1293 while ((x = AST_LIST_REMOVE_HEAD(&cat->template_instances, next)))
1294 ast_free(x);
1295 }
1296
1297 void ast_category_destroy(struct ast_category *cat)
1298 {
1299 ast_variables_destroy(cat->root);
1300 cat->root = NULL;
1301 cat->last = NULL;
1302 ast_comment_destroy(&cat->precomments);
1303 ast_comment_destroy(&cat->sameline);
1304 ast_comment_destroy(&cat->trailing);
1305 ast_destroy_template_list(cat);
1306 ast_free(cat->file);
1307 ast_free(cat);
1308 }
1309
1310 static void config_included_files_destroy(struct ast_config_include *incl)
1311 {
1312 struct config_included_file *x;
1313
1314 while ((x = AST_LIST_REMOVE_HEAD(&incl->included_files, next))) {
1315 ast_free(x);
1316 }
1317 }
1318
1319 static void ast_include_destroy(struct ast_config_include *incl)
1320 {
1321 ast_free(incl->include_location_file);
1322 ast_free(incl->exec_file);
1323 ast_free(incl->included_file);
1324 config_included_files_destroy(incl);
1325 ast_comment_destroy(&incl->precomments);
1326 ast_comment_destroy(&incl->sameline);
1327 ast_comment_destroy(&incl->trailing);
1328 ast_free(incl);
1329 }
1330
1331 static void ast_includes_destroy(struct ast_config_include *incls)
1332 {
1333 struct ast_config_include *incl, *inclnext;
1334
1335 for (incl = incls; incl; incl = inclnext) {
1336 inclnext = incl->next;
1337 ast_include_destroy(incl);
1338 }
1339 }
1340
1341 static struct ast_category *next_available_category(struct ast_category *cat,
1342 const char *name, const char *filter)
1343 {
1344 for (; cat && !does_category_match(cat, name, filter, ','); cat = cat->next);
1345
1346 return cat;
1347 }
1348
1349 /*! return the first var of a category */
1350 struct ast_variable *ast_category_first(struct ast_category *cat)
1351 {
1352 return (cat) ? cat->root : NULL;
1353 }
1354
1355 struct ast_variable *ast_category_root(struct ast_config *config, char *cat)
1356 {
1357 struct ast_category *category = ast_category_get(config, cat, NULL);
1358
1359 if (category)
1360 return category->root;
1361 return NULL;
1362 }
1363
1364 void ast_config_sort_categories(struct ast_config *config, int descending,
1365 int (*comparator)(struct ast_category *p, struct ast_category *q))
1366 {
1367 /*
1368 * The contents of this function are adapted from
1369 * an example of linked list merge sorting
1370 * copyright 2001 Simon Tatham.
1371 *
1372 * Permission is hereby granted, free of charge, to any person
1373 * obtaining a copy of this software and associated documentation
1374 * files (the "Software"), to deal in the Software without
1375 * restriction, including without limitation the rights to use,
1376 * copy, modify, merge, publish, distribute, sublicense, and/or
1377 * sell copies of the Software, and to permit persons to whom the
1378 * Software is furnished to do so, subject to the following
1379 * conditions:
1380 *
1381 * The above copyright notice and this permission notice shall be
1382 * included in all copies or substantial portions of the Software.
1383 *
1384 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
1385 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
1386 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
1387 * NONINFRINGEMENT. IN NO EVENT SHALL SIMON TATHAM BE LIABLE FOR
1388 * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
1389 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
1390 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
1391 * SOFTWARE.
1392 */
1393
1394 int insize = 1;
1395 struct ast_category *p, *q, *e, *tail;
1396 int nmerges, psize, qsize, i;
1397
1398 /* If the descending flag was sent, we'll apply inversion to the comparison function's return. */
1399 if (descending) {
1400 descending = -1;
1401 } else {
1402 descending = 1;
1403 }
1404
1405 if (!config->root) {
1406 return;
1407 }
1408
1409 while (1) {
1410 p = config->root;
1411 config->root = NULL;
1412 tail = NULL;
1413
1414 nmerges = 0; /* count number of merges we do in this pass */
1415
1416 while (p) {
1417 nmerges++; /* there exists a merge to be done */
1418
1419 /* step `insize' places along from p */
1420 q = p;
1421 psize = 0;
1422 for (i = 0; i < insize; i++) {
1423 psize++;
1424 q = q->next;
1425 if (!q) {
1426 break;
1427 }
1428 }
1429
1430 /* if q hasn't fallen off end, we have two lists to merge */
1431 qsize = insize;
1432
1433 /* now we have two lists; merge them */
1434 while (psize > 0 || (qsize > 0 && q)) {
1435 /* decide whether next element of merge comes from p or q */
1436 if (psize == 0) {
1437 /* p is empty; e must come from q. */
1438 e = q;
1439 q = q->next;
1440 qsize--;
1441 } else if (qsize == 0 || !q) {
1442 /* q is empty; e must come from p. */
1443 e = p; p = p->next; psize--;
1444 } else if ((comparator(p, q) * descending) <= 0) {
1445 /* First element of p is lower (or same) e must come from p. */
1446 e = p;
1447 p = p->next;
1448 psize--;
1449 } else {
1450 /* First element of q is lower; e must come from q. */
1451 e = q;
1452 q = q->next;
1453 qsize--;
1454 }
1455
1456 /* add the next element to the merged list */
1457 if (tail) {
1458 tail->next = e;
1459 } else {
1460 config->root = e;
1461 }
1462 tail = e;
1463 }
1464
1465 /* now p has stepped `insize' places along, and q has too */
1466 p = q;
1467 }
1468
1469 tail->next = NULL;
1470
1471 /* If we have done only one merge, we're finished. */
1472 if (nmerges <= 1) { /* allow for nmerges==0, the empty list case */
1473 return;
1474 }
1475
1476 /* Otherwise repeat, merging lists twice the size */
1477 insize *= 2;
1478 }
1479
1480 }
1481
1482 char *ast_category_browse(struct ast_config *config, const char *prev_name)
1483 {
1484 struct ast_category *cat;
1485
1486 if (!prev_name) {
1487 /* First time browse. */
1488 cat = config->root;
1489 } else if (config->last_browse && (config->last_browse->name == prev_name)) {
1490 /* Simple last browse found. */
1491 cat = config->last_browse->next;
1492 } else {
1493 /*
1494 * Config changed since last browse.
1495 *
1496 * First try cheap last browse search. (Rebrowsing a different
1497 * previous category?)
1498 */
1499 for (cat = config->root; cat; cat = cat->next) {
1500 if (cat->name == prev_name) {
1501 /* Found it. */
1502 cat = cat->next;
1503 break;
1504 }
1505 }
1506 if (!cat) {
1507 /*
1508 * Have to do it the hard way. (Last category was deleted and
1509 * re-added?)
1510 */
1511 for (cat = config->root; cat; cat = cat->next) {
1512 if (!strcasecmp(cat->name, prev_name)) {
1513 /* Found it. */
1514 cat = cat->next;
1515 break;
1516 }
1517 }
1518 }
1519 }
1520
1521 if (cat)
1522 cat = next_available_category(cat, NULL, NULL);
1523
1524 config->last_browse = cat;
1525 return (cat) ? cat->name : NULL;
1526 }
1527
1528 struct ast_category *ast_category_browse_filtered(struct ast_config *config,
1529 const char *category_name, struct ast_category *prev, const char *filter)
1530 {
1531 struct ast_category *cat;
1532
1533 if (!prev) {
1534 prev = config->root;
1535 } else {
1536 prev = prev->next;
1537 }
1538
1539 cat = next_available_category(prev, category_name, filter);
1540
1541 return cat;
1542 }
1543
1544 struct ast_variable *ast_category_detach_variables(struct ast_category *cat)
1545 {
1546 struct ast_variable *v;
1547
1548 v = cat->root;
1549 cat->root = NULL;
1550 cat->last = NULL;
1551
1552 return v;
1553 }
1554
1555 void ast_category_rename(struct ast_category *cat, const char *name)
1556 {
1557 ast_copy_string(cat->name, name, sizeof(cat->name));
1558 }
1559
1560 int ast_category_inherit(struct ast_category *new, const struct ast_category *base)
1561 {
1562 struct ast_variable *var;
1563 struct ast_category_template_instance *x;
1564
1565 x = ast_calloc(1, sizeof(*x));
1566 if (!x) {
1567 return -1;
1568 }
1569 strcpy(x->name, base->name);
1570 x->inst = base;
1571 AST_LIST_INSERT_TAIL(&new->template_instances, x, next);
1572 for (var = base->root; var; var = var->next) {
1573 struct ast_variable *cloned = variable_clone(var);
1574 if (!cloned) {
1575 return -1;
1576 }
1577 cloned->inherited = 1;
1578 ast_variable_append(new, cloned);
1579 }
1580 return 0;
1581 }
1582
1583 struct ast_config *ast_config_new(void)
1584 {
1585 struct ast_config *config;
1586
1587 if ((config = ast_calloc(1, sizeof(*config))))
1588 config->max_include_level = MAX_INCLUDE_LEVEL;
1589 return config;
1590 }
1591
1592 int ast_variable_delete(struct ast_category *category, const char *variable, const char *match, const char *line)
1593 {
1594 struct ast_variable *cur, *prev=NULL, *curn;
1595 int res = -1;
1596 int num_item = 0;
1597 int req_item;
1598
1599 req_item = -1;
1600 if (!ast_strlen_zero(line)) {
1601 /* Requesting to delete by item number. */
1602 if (sscanf(line, "%30d", &req_item) != 1
1603 || req_item < 0) {
1604 /* Invalid item number to delete. */
1605 return -1;
1606 }
1607 }
1608
1609 prev = NULL;
1610 cur = category->root;
1611 while (cur) {
1612 curn = cur->next;
1613 /* Delete by item number or by variable name with optional value. */
1614 if ((0 <= req_item && num_item == req_item)
1615 || (req_item < 0 && !strcasecmp(cur->name, variable)
1616 && (ast_strlen_zero(match) || !strcasecmp(cur->value, match)))) {
1617 if (prev) {
1618 prev->next = cur->next;
1619 if (cur == category->last)
1620 category->last = prev;
1621 } else {
1622 category->root = cur->next;
1623 if (cur == category->last)
1624 category->last = NULL;
1625 }
1626 ast_variable_destroy(cur);
1627 res = 0;
1628 } else
1629 prev = cur;
1630
1631 cur = curn;
1632 ++num_item;
1633 }
1634 return res;
1635 }
1636
1637 int ast_variable_update(struct ast_category *category, const char *variable,
1638 const char *value, const char *match, unsigned int object)
1639 {
1640 struct ast_variable *cur, *prev=NULL, *newer=NULL;
1641
1642 for (cur = category->root; cur; prev = cur, cur = cur->next) {
1643 if (strcasecmp(cur->name, variable) ||
1644 (!ast_strlen_zero(match) && strcasecmp(cur->value, match)))
1645 continue;
1646
1647 if (!(newer = ast_variable_new(variable, value, cur->file)))
1648 return -1;
1649
1650 ast_variable_move(newer, cur);
1651 newer->object = newer->object || object;
1652
1653 /* Replace the old node in the list with the new node. */
1654 newer->next = cur->next;
1655 if (prev)
1656 prev->next = newer;
1657 else
1658 category->root = newer;
1659 if (category->last == cur)
1660 category->last = newer;
1661
1662 ast_variable_destroy(cur);
1663
1664 return 0;
1665 }
1666
1667 /* Could not find variable to update */
1668 return -1;
1669 }
1670
1671 struct ast_category *ast_category_delete(struct ast_config *config,
1672 struct ast_category *category)
1673 {
1674 struct ast_category *prev;
1675
1676 if (!config || !category) {
1677 return NULL;
1678 }
1679
1680 if (category->prev) {
1681 category->prev->next = category->next;
1682 } else {
1683 config->root = category->next;
1684 }
1685
1686 if (category->next) {
1687 category->next->prev = category->prev;
1688 } else {
1689 config->last = category->prev;
1690 }
1691
1692 prev = category->prev;
1693
1694 if (config->last_browse == category) {
1695 config->last_browse = prev;
1696 }
1697
1698 ast_category_destroy(category);
1699
1700 return prev;
1701 }
1702
1703 int ast_category_empty(struct ast_category *category)
1704 {
1705 if (!category) {
1706 return -1;
1707 }
1708
1709 ast_variables_destroy(category->root);
1710 category->root = NULL;
1711 category->last = NULL;
1712
1713 return 0;
1714 }
1715
1716 void ast_config_destroy(struct ast_config *cfg)
1717 {
1718 struct ast_category *cat, *catn;
1719
1720 if (!cfg)
1721 return;
1722
1723 ast_includes_destroy(cfg->includes_root);
1724
1725 cat = cfg->root;
1726 while (cat) {
1727 catn = cat;
1728 cat = cat->next;
1729 ast_category_destroy(catn);
1730 }
1731 ast_free(cfg);
1732 }
1733
1734 struct ast_category *ast_config_get_current_category(const struct ast_config *cfg)
1735 {
1736 return cfg->current;
1737 }
1738
1739 void ast_config_set_current_category(struct ast_config *cfg, const struct ast_category *cat)
1740 {
1741 /* cast below is just to silence compiler warning about dropping "const" */
1742 cfg->current = (struct ast_category *) cat;
1743 }
1744
1745 /*!
1746 * \internal
1747 * \brief Create a new cfmtime list node.
1748 *
1749 * \param filename Config filename caching.
1750 * \param who_asked Who wanted to know.
1751 *
1752 * \retval cfmtime New node on success.
1753 * \retval NULL on error.
1754 */
1755 static struct cache_file_mtime *cfmtime_new(const char *filename, const char *who_asked)
1756 {
1757 struct cache_file_mtime *cfmtime;
1758 char *dst;
1759
1760 cfmtime = ast_calloc(1,
1761 sizeof(*cfmtime) + strlen(filename) + 1 + strlen(who_asked) + 1);
1762 if (!cfmtime) {
1763 return NULL;
1764 }
1765 dst = cfmtime->filename; /* writable space starts here */
1766 strcpy(dst, filename); /* Safe */
1767 dst += strlen(dst) + 1;
1768 cfmtime->who_asked = strcpy(dst, who_asked); /* Safe */
1769
1770 return cfmtime;
1771 }
1772
1773 enum config_cache_attribute_enum {
1774 ATTRIBUTE_INCLUDE = 0,
1775 ATTRIBUTE_EXEC = 1,
1776 };
1777
1778 /*!
1779 * \internal
1780 * \brief Save the stat() data to the cached file modtime struct.
1781 *
1782 * \param cfmtime Cached file modtime.
1783 * \param statbuf Buffer filled in by stat().
1784 */
1785 static void cfmstat_save(struct cache_file_mtime *cfmtime, struct stat *statbuf)
1786 {
1787 cfmtime->stat_size = statbuf->st_size;
1788 #if defined(HAVE_STRUCT_STAT_ST_MTIM)
1789 cfmtime->stat_mtime_nsec = statbuf->st_mtim.tv_nsec;
1790 #elif defined(HAVE_STRUCT_STAT_ST_MTIMENSEC)
1791 cfmtime->stat_mtime_nsec = statbuf->st_mtimensec;
1792 #elif defined(HAVE_STRUCT_STAT_ST_MTIMESPEC)
1793 cfmtime->stat_mtime_nsec = statbuf->st_mtimespec.tv_nsec;
1794 #else
1795 cfmtime->stat_mtime_nsec = 0;
1796 #endif
1797 cfmtime->stat_mtime = statbuf->st_mtime;
1798 }
1799
1800 /*!
1801 * \internal
1802 * \brief Compare the stat() data with the cached file modtime struct.
1803 *
1804 * \param cfmtime Cached file modtime.
1805 * \param statbuf Buffer filled in by stat().
1806 *
1807 * \retval non-zero if different.
1808 */
1809 static int cfmstat_cmp(struct cache_file_mtime *cfmtime, struct stat *statbuf)
1810 {
1811 struct cache_file_mtime cfm_buf;
1812
1813 cfmstat_save(&cfm_buf, statbuf);
1814
1815 return cfmtime->stat_size != cfm_buf.stat_size
1816 || cfmtime->stat_mtime != cfm_buf.stat_mtime
1817 || cfmtime->stat_mtime_nsec != cfm_buf.stat_mtime_nsec;
1818 }
1819
1820 /*!
1821 * \internal
1822 * \brief Clear the cached file modtime include list.
1823 *
1824 * \param cfmtime Cached file modtime.
1825 *
1826 * \note cfmtime_head is assumed already locked.
1827 */
1828 static void config_cache_flush_includes(struct cache_file_mtime *cfmtime)
1829 {
1830 struct cache_file_include *cfinclude;
1831
1832 while ((cfinclude = AST_LIST_REMOVE_HEAD(&cfmtime->includes, list))) {
1833 ast_free(cfinclude);
1834 }
1835 }
1836
1837 /*!
1838 * \internal
1839 * \brief Destroy the given cached file modtime entry.
1840 *
1841 * \param cfmtime Cached file modtime.
1842 *
1843 * \note cfmtime_head is assumed already locked.
1844 */
1845 static void config_cache_destroy_entry(struct cache_file_mtime *cfmtime)
1846 {
1847 config_cache_flush_includes(cfmtime);
1848 ast_free(cfmtime);
1849 }
1850
1851 /*!
1852 * \internal
1853 * \brief Remove and destroy the config cache entry for the filename and who_asked.
1854 *
1855 * \param filename Config filename.
1856 * \param who_asked Which module asked.
1857 */
1858 static void config_cache_remove(const char *filename, const char *who_asked)
1859 {
1860 struct cache_file_mtime *cfmtime;
1861
1862 AST_LIST_LOCK(&cfmtime_head);
1863 AST_LIST_TRAVERSE_SAFE_BEGIN(&cfmtime_head, cfmtime, list) {
1864 if (!strcmp(cfmtime->filename, filename)
1865 && !strcmp(cfmtime->who_asked, who_asked)) {
1866 AST_LIST_REMOVE_CURRENT(list);
1867 config_cache_destroy_entry(cfmtime);
1868 break;
1869 }
1870 }
1871 AST_LIST_TRAVERSE_SAFE_END;
1872 AST_LIST_UNLOCK(&cfmtime_head);
1873 }
1874
1875 static void config_cache_attribute(const char *configfile, enum config_cache_attribute_enum attrtype, const char *filename, const char *who_asked)
1876 {
1877 struct cache_file_mtime *cfmtime;
1878 struct cache_file_include *cfinclude;
1879
1880 /* Find our cached entry for this configuration file */
1881 AST_LIST_LOCK(&cfmtime_head);
1882 AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
1883 if (!strcmp(cfmtime->filename, configfile) && !strcmp(cfmtime->who_asked, who_asked))
1884 break;
1885 }
1886 if (!cfmtime) {
1887 cfmtime = cfmtime_new(configfile, who_asked);
1888 if (!cfmtime) {
1889 AST_LIST_UNLOCK(&cfmtime_head);
1890 return;
1891 }
1892 /* Note that the file mtime is initialized to 0, i.e. 1970 */
1893 AST_LIST_INSERT_SORTALPHA(&cfmtime_head, cfmtime, list, filename);
1894 }
1895
1896 switch (attrtype) {
1897 case ATTRIBUTE_INCLUDE:
1898 AST_LIST_TRAVERSE(&cfmtime->includes, cfinclude, list) {
1899 if (!strcmp(cfinclude->include, filename)) {
1900 AST_LIST_UNLOCK(&cfmtime_head);
1901 return;
1902 }
1903 }
1904 cfinclude = ast_calloc(1, sizeof(*cfinclude) + strlen(filename) + 1);
1905 if (!cfinclude) {
1906 AST_LIST_UNLOCK(&cfmtime_head);
1907 return;
1908 }
1909 strcpy(cfinclude->include, filename); /* Safe */
1910 AST_LIST_INSERT_TAIL(&cfmtime->includes, cfinclude, list);
1911 break;
1912 case ATTRIBUTE_EXEC:
1913 cfmtime->has_exec = 1;
1914 break;
1915 }
1916 AST_LIST_UNLOCK(&cfmtime_head);
1917 }
1918
1919 /*!
1920 * \internal
1921 * \brief Process an #exec include, reporting errors.
1922 *
1923 * For backwards compatibility we return success in most cases because we
1924 * do not want to prevent the rest of the configuration (or the module
1925 * loading that configuration) from loading.
1926 *
1927 * \param command The command to execute
1928 * \param output_file The filename to write to
1929 *
1930 * \retval 0 on success
1931 * \retval -1 on failure
1932 */
1933 static int handle_include_exec(const char *command, const char *output_file)
1934 {
1935 char buf[1024];
1936 FILE *fp;
1937 int status;
1938 struct stat output_file_info;
1939
1940 /* stderr to stdout, stdout to file */
1941 if (snprintf(buf, sizeof(buf), "%s 2>&1 > %s", command, output_file) >= sizeof(buf)) {
1942 ast_log(LOG_ERROR, "Failed to construct command string to execute %s.\n", command);
1943 return -1;
1944 }
1945
1946 ast_replace_sigchld();
1947
1948 errno = 0;
1949
1950 fp = popen(buf, "r");
1951 if (!fp) {
1952 ast_log(LOG_ERROR, "#exec <%s>: Failed to execute: %s\n",
1953 command,
1954 strerror(errno));
1955 ast_unreplace_sigchld();
1956 return 0;
1957 }
1958
1959 while (fgets(buf, sizeof(buf), fp)) {
1960 /* Ensure we have a \n at the end */
1961 if (strlen(buf) == sizeof(buf) - 1 && buf[sizeof(buf) - 2] != '\n') {
1962 ast_log(LOG_ERROR, "#exec <%s>: %s... <truncated>\n",
1963 command,
1964 buf);
1965
1966 /* Consume the rest of the line */
1967 while (fgets(buf, sizeof(buf), fp)) {
1968 if (strlen(buf) != sizeof(buf) - 1 || buf[sizeof(buf) - 2] == '\n') {
1969 break;
1970 }
1971 }
1972
1973 continue;
1974 }
1975
1976 /* `buf` has the newline, so we don't need to print it ourselves */
1977 ast_log(LOG_ERROR, "#exec <%s>: %s",
1978 command,
1979 buf);
1980 }
1981
1982 status = pclose(fp);
1983 if (status == -1) {
1984 ast_log(LOG_ERROR, "#exec <%s>: Failed to retrieve exit status: %s\n",
1985 command,
1986 strerror(errno));
1987 } else {
1988 status = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
1989 if (status) {
1990 ast_log(LOG_ERROR, "#exec <%s>: Exited with return value %d\n",
1991 command,
1992 status);
1993 }
1994 }
1995
1996 ast_unreplace_sigchld();
1997
1998 /* Check that the output file contains something */
1999 if (stat(output_file, &output_file_info) == -1) {
2000 ast_log(LOG_ERROR, "#exec <%s>: Unable to stat() temporary file `%s': %s\n",
2001 command,
2002 output_file,
2003 strerror(errno));
2004 } else if (output_file_info.st_size == 0) {
2005 ast_log(LOG_WARNING, "#exec <%s>: The program generated no usable output.\n",
2006 command);
2007 }
2008
2009 return 0;
2010 }
2011
2012 /*! \brief parse one line in the configuration.
2013 * \verbatim
2014 * We can have a category header [foo](...)
2015 * a directive #include, #tryinclude, #exec
2016 * or a regular line name = value
2017 * \endverbatim
2018 */
2019 static int process_text_line(struct ast_config *cfg, struct ast_category **cat,
2020 char *buf, int lineno, const char *configfile, struct ast_flags flags,
2021 struct ast_str *comment_buffer,
2022 struct ast_str *lline_buffer,
2023 const char *suggested_include_file,
2024 struct ast_category **last_cat,
2025 struct ast_variable **last_var,
2026 struct ast_config_include **last_inc,
2027 const char *who_asked)
2028 {
2029 char *c;
2030 char *cur = buf;
2031 struct ast_variable *v;
2032 char exec_file[512];
2033
2034 /* Actually parse the entry */
2035 if (cur[0] == '[') { /* A category header */
2036 /* format is one of the following:
2037 * [foo] define a new category named 'foo'
2038 * [foo](!) define a new template category named 'foo'
2039 * [foo](+) append to category 'foo', error if foo does not exist.
2040 * [foo](a) define a new category and inherit from category or template a.
2041 * You can put a comma-separated list of categories and templates
2042 * and '!' and '+' between parentheses, with obvious meaning.
2043 */
2044 struct ast_category *newcat;
2045 char *catname;
2046
2047 c = strchr(cur, ']');
2048 if (!c) {
2049 ast_log(LOG_WARNING, "parse error: no closing ']', line %d of %s\n", lineno, configfile);
2050 return -1;
2051 }
2052 *c++ = '\0';
2053 cur++;
2054 if (*c++ != '(')
2055 c = NULL;
2056 catname = cur;
2057 *cat = newcat = ast_category_new(catname,
2058 S_OR(suggested_include_file, cfg->include_level == 1 ? "" : configfile),
2059 lineno);
2060 if (!newcat) {
2061 return -1;
2062 }
2063 (*cat)->lineno = lineno;
2064
2065 /* add comments */
2066 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
2067 newcat->precomments = ALLOC_COMMENT(comment_buffer);
2068 newcat->sameline = ALLOC_COMMENT(lline_buffer);
2069 CB_RESET(comment_buffer, lline_buffer);
2070 }
2071
2072 /* If there are options or categories to inherit from, process them now */
2073 if (c) {
2074 if (!(cur = strchr(c, ')'))) {
2075 ast_category_destroy(newcat);
2076 ast_log(LOG_WARNING, "parse error: no closing ')', line %d of %s\n", lineno, configfile);
2077 return -1;
2078 }
2079 *cur = '\0';
2080 while ((cur = strsep(&c, ","))) {
2081 if (!strcasecmp(cur, "!")) {
2082 (*cat)->ignored = 1;
2083 } else if (cur[0] == '+') {
2084 char *filter = NULL;
2085
2086 if (cur[1] != ',') {
2087 filter = &cur[1];
2088 }
2089 *cat = category_get_sep(cfg, catname, filter, '&', 0);
2090 if (!(*cat)) {
2091 if (newcat) {
2092 ast_category_destroy(newcat);
2093 }
2094 ast_log(LOG_WARNING, "Category addition requested, but category '%s' does not exist, line %d of %s\n", catname, lineno, configfile);
2095 return -1;
2096 }
2097 if (newcat) {
2098 ast_config_set_current_category(cfg, *cat);
2099 (*cat)->ignored |= newcat->ignored;
2100 move_variables(newcat, *cat);
2101 ast_category_destroy(newcat);
2102 newcat = NULL;
2103 }
2104 } else {
2105 struct ast_category *base;
2106
2107 base = category_get_sep(cfg, cur, "TEMPLATES=include", ',', 0);
2108 if (!base) {
2109 if (newcat) {
2110 ast_category_destroy(newcat);
2111 }
2112 ast_log(LOG_WARNING, "Inheritance requested, but category '%s' does not exist, line %d of %s\n", cur, lineno, configfile);
2113 return -1;
2114 }
2115 if (ast_category_inherit(*cat, base)) {
2116 if (newcat) {
2117 ast_category_destroy(newcat);
2118 }
2119 ast_log(LOG_ERROR, "Inheritance requested, but allocation failed\n");
2120 return -1;
2121 }
2122 }
2123 }
2124 }
2125
2126 /*
2127 * We need to set *last_cat to newcat here regardless. If the
2128 * category is being appended to we have no place for trailing
2129 * comments on the appended category. The appended category
2130 * may be in another file or it already has trailing comments
2131 * that we would then leak.
2132 */
2133 *last_cat = newcat;
2134 *last_var = NULL;
2135 *last_inc = NULL;
2136 if (newcat) {
2137 ast_category_append(cfg, newcat);
2138 }
2139 } else if (cur[0] == '#') { /* A directive - #include, #tryinclude, or #exec */
2140 char *cur2;
2141 char real_inclusion_name[256];
2142 int include_type;
2143 struct ast_config_include *newinclude;
2144 struct ast_config *result;
2145
2146 cur++;
2147 c = cur;
2148 while (*c && (*c > 32)) {
2149 c++;
2150 }
2151
2152 if (*c) {
2153 *c = '\0';
2154 /* Find real argument */
2155 c = ast_strip(c + 1);
2156 if (!(*c)) {
2157 c = NULL;
2158 }
2159 } else {
2160 c = NULL;
2161 }
2162 if (!strcasecmp(cur, "include")) {
2163 include_type = CONFIG_STATEMENT_INCLUDE;
2164 } else if (!strcasecmp(cur, "tryinclude")) {
2165 include_type = CONFIG_STATEMENT_TRYINCLUDE;
2166 } else if (!strcasecmp(cur, "exec")) {
2167 if (!ast_opt_exec_includes) {
2168 ast_log(LOG_WARNING, "Cannot perform #exec unless execincludes option is enabled in asterisk.conf (options section)!\n");
2169 return 0; /* XXX is this correct ? or we should return -1 ? */
2170 }
2171 include_type = CONFIG_STATEMENT_EXEC;
2172 } else {
2173 ast_log(LOG_WARNING, "Unknown directive '#%s' at line %d of %s\n", cur, lineno, configfile);
2174 return 0; /* XXX is this correct ? or we should return -1 ? */
2175 }
2176
2177 if (c == NULL) {
2178 ast_log(LOG_WARNING, "Directive '#%s' needs an argument (%s) at line %d of %s\n",
2179 cur,
2180 (include_type != CONFIG_STATEMENT_EXEC) ? "filename" : "/path/to/executable",
2181 lineno,
2182 configfile);
2183 return 0; /* XXX is this correct ? or we should return -1 ? */
2184 }
2185
2186 cur = c;
2187 /* Strip off leading and trailing "'s and <>'s */
2188 /* Dequote */
2189 if ((*c == '"') || (*c == '<')) {
2190 char quote_char = *c;
2191 if (quote_char == '<') {
2192 quote_char = '>';
2193 }
2194
2195 if (*(c + strlen(c) - 1) == quote_char) {
2196 cur++;
2197 *(c + strlen(c) - 1) = '\0';
2198 }
2199 }
2200 cur2 = cur;
2201
2202 if (include_type == CONFIG_STATEMENT_EXEC) {
2203 /* #exec </path/to/executable>
2204 We create a tmp file, then we #include it, then we delete it. */
2205 struct timeval now = ast_tvnow();
2206
2207 if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE))
2208 config_cache_attribute(configfile, ATTRIBUTE_EXEC, NULL, who_asked);
2209 snprintf(exec_file, sizeof(exec_file), "/var/tmp/exec.%d%d.%ld", (int)now.tv_sec, (int)now.tv_usec, (long)pthread_self());
2210 if (handle_include_exec(cur, exec_file)) {
2211 return -1;
2212 }
2213 cur = exec_file;
2214 } else {
2215 if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE))
2216 config_cache_attribute(configfile, ATTRIBUTE_INCLUDE, cur, who_asked);
2217 exec_file[0] = '\0';
2218 }
2219 /* A #include */
2220 /* record this inclusion */
2221 newinclude = ast_include_new(cfg, cfg->include_level == 1 ? "" : configfile, cur, include_type, cur2, lineno, real_inclusion_name, sizeof(real_inclusion_name));
2222 if (!newinclude) {
2223 if (!ast_strlen_zero(exec_file)) {
2224 unlink(exec_file);
2225 }
2226 return -1;
2227 }
2228
2229 result = ast_config_internal_load(cur, cfg, flags, real_inclusion_name, who_asked);
2230 if (!ast_strlen_zero(exec_file)) {
2231 unlink(exec_file);
2232 }
2233 if (!result && (include_type != CONFIG_STATEMENT_TRYINCLUDE)) {
2234 ast_log(LOG_ERROR, "The file '%s' was listed as a #include but it does not exist.\n", cur);
2235 return -1;
2236 }
2237
2238 /* add comments */
2239 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
2240 newinclude->precomments = ALLOC_COMMENT(comment_buffer);
2241 newinclude->sameline = ALLOC_COMMENT(lline_buffer);
2242 CB_RESET(comment_buffer, lline_buffer);
2243 }
2244
2245 /* for now, any end-of-file (trailing) comments are after this #include */
2246 *last_cat = NULL;
2247 *last_var = NULL;
2248 *last_inc = newinclude;
2249 } else {
2250 /* Just a line (variable = value) */
2251 int object = 0;
2252 int is_escaped;
2253
2254 if (!(*cat)) {
2255 ast_log(LOG_WARNING,
2256 "parse error: No category context for line %d of %s\n", lineno, configfile);
2257 return -1;
2258 }
2259
2260 is_escaped = cur[0] == '\\';
2261 if (is_escaped) {
2262 /* First character is escaped. */
2263 ++cur;
2264 if (cur[0] < 33) {
2265 ast_log(LOG_ERROR, "Invalid escape in line %d of %s\n", lineno, configfile);
2266 return -1;
2267 }
2268 }
2269 c = strchr(cur + is_escaped, '=');
2270
2271 if (c && c > cur + is_escaped && (*(c - 1) == '+')) {
2272 struct ast_variable *var, *replace = NULL;
2273 struct ast_str **str = ast_threadstorage_get(&appendbuf, sizeof(*str));
2274
2275 if (!str || !*str) {
2276 return -1;
2277 }
2278
2279 *(c - 1) = '\0';
2280 c++;
2281 cur = ast_strip(cur);
2282
2283 /* Must iterate through category until we find last variable of same name (since there could be multiple) */
2284 for (var = ast_category_first(*cat); var; var = var->next) {
2285 if (!strcmp(var->name, cur)) {
2286 replace = var;
2287 }
2288 }
2289
2290 if (!replace) {
2291 /* Nothing to replace; just set a variable normally. */
2292 goto set_new_variable;
2293 }
2294
2295 ast_str_set(str, 0, "%s", replace->value);
2296 ast_str_append(str, 0, "%s", c);
2297 ast_str_trim_blanks(*str);
2298 ast_variable_update(*cat, replace->name, ast_skip_blanks(ast_str_buffer(*str)), replace->value, object);
2299 } else if (c) {
2300 *c = 0;
2301 c++;
2302 /* Ignore > in => */
2303 if (*c== '>') {
2304 object = 1;
2305 c++;
2306 }
2307 cur = ast_strip(cur);
2308 set_new_variable:
2309 if (ast_strlen_zero(cur)) {
2310 ast_log(LOG_WARNING, "No variable name in line %d of %s\n", lineno, configfile);
2311 } else if ((v = ast_variable_new(cur, ast_strip(c), S_OR(suggested_include_file, cfg->include_level == 1 ? "" : configfile)))) {
2312 v->lineno = lineno;
2313 v->object = object;
2314 *last_cat = NULL;
2315 *last_var = v;
2316 *last_inc = NULL;
2317 /* Put and reset comments */
2318 v->blanklines = 0;
2319 ast_variable_append(*cat, v);
2320 /* add comments */
2321 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
2322 v->precomments = ALLOC_COMMENT(comment_buffer);
2323 v->sameline = ALLOC_COMMENT(lline_buffer);
2324 CB_RESET(comment_buffer, lline_buffer);
2325 }
2326 } else {
2327 return -1;
2328 }
2329 } else {
2330 ast_log(LOG_WARNING, "No '=' (equal sign) in line %d of %s\n", lineno, configfile);
2331 }
2332 }
2333 return 0;
2334 }
2335
2336 static struct ast_config *config_text_file_load(const char *database, const char *table, const char *filename, struct ast_config *cfg, struct ast_flags flags, const char *suggested_include_file, const char *who_asked)
2337 {
2338 char fn[256];
2339 #if defined(LOW_MEMORY)
2340 char buf[512];
2341 #else
2342 char buf[8192];
2343 #endif
2344 char *new_buf, *comment_p, *process_buf;
2345 FILE *f;
2346 int lineno=0;
2347 int comment = 0, nest[MAX_NESTED_COMMENTS];
2348 struct ast_category *cat = NULL;
2349 int count = 0;
2350 struct stat statbuf;
2351 struct cache_file_mtime *cfmtime = NULL;
2352 struct cache_file_include *cfinclude;
2353 struct ast_category *last_cat = NULL;
2354 struct ast_variable *last_var = NULL;
2355 struct ast_config_include *last_inc = NULL;
2356 /*! Growable string buffer */
2357 struct ast_str *comment_buffer = NULL; /*!< this will be a comment collector.*/
2358 struct ast_str *lline_buffer = NULL; /*!< A buffer for stuff behind the ; */
2359 int glob_ret;
2360 glob_t globbuf;
2361
2362 if (cfg) {
2363 cat = ast_config_get_current_category(cfg);
2364 }
2365
2366 if (filename[0] == '/') {
2367 ast_copy_string(fn, filename, sizeof(fn));
2368 } else {
2369 snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_CONFIG_DIR, filename);
2370 }
2371
2372 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
2373 comment_buffer = ast_str_create(CB_SIZE);
2374 if (comment_buffer) {
2375 lline_buffer = ast_str_create(CB_SIZE);
2376 }
2377 if (!lline_buffer) {
2378 ast_free(comment_buffer);
2379 ast_log(LOG_ERROR, "Failed to initialize the comment buffer!\n");
2380 return NULL;
2381 }
2382 }
2383
2384 globbuf.gl_offs = 0; /* initialize it to silence gcc */
2385 glob_ret = glob(fn, MY_GLOB_FLAGS, NULL, &globbuf);
2386 if (glob_ret == GLOB_NOSPACE) {
2387 ast_log(LOG_WARNING,
2388 "Glob Expansion of pattern '%s' failed: Not enough memory\n", fn);
2389 } else if (glob_ret == GLOB_ABORTED) {
2390 ast_log(LOG_WARNING,
2391 "Glob Expansion of pattern '%s' failed: Read error\n", fn);
2392 } else {
2393 /* loop over expanded files */
2394 int i;
2395
2396 if (!cfg && (globbuf.gl_pathc != 1 || strcmp(fn, globbuf.gl_pathv[0]))) {
2397 /*
2398 * We just want a file changed answer and since we cannot
2399 * tell if a file was deleted with wildcard matching we will
2400 * assume that something has always changed. Also without
2401 * a lot of refactoring we couldn't check more than one file
2402 * for changes in the glob loop anyway.
2403 */
2404 globfree(&globbuf);
2405 ast_free(comment_buffer);
2406 ast_free(lline_buffer);
2407 return NULL;
2408 }
2409 for (i = 0; i < globbuf.gl_pathc; i++) {
2410 ast_copy_string(fn, globbuf.gl_pathv[i], sizeof(fn));
2411
2412 /*
2413 * The following is not a loop, but just a convenient way to define a block
2414 * (using do { } while(0) ), and be able to exit from it with 'continue'
2415 * or 'break' in case of errors. Nice trick.
2416 */
2417 do {
2418 if (stat(fn, &statbuf)) {
2419 if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE)) {
2420 config_cache_remove(fn, who_asked);
2421 }
2422 continue;
2423 }
2424
2425 if (!S_ISREG(statbuf.st_mode)) {
2426 ast_log(LOG_WARNING, "'%s' is not a regular file, ignoring\n", fn);
2427 if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE)) {
2428 config_cache_remove(fn, who_asked);
2429 }
2430 continue;
2431 }
2432
2433 if (!ast_test_flag(&flags, CONFIG_FLAG_NOCACHE)) {
2434 /* Find our cached entry for this configuration file */
2435 AST_LIST_LOCK(&cfmtime_head);
2436 AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
2437 if (!strcmp(cfmtime->filename, fn) && !strcmp(cfmtime->who_asked, who_asked)) {
2438 break;
2439 }
2440 }
2441 if (!cfmtime) {
2442 cfmtime = cfmtime_new(fn, who_asked);
2443 if (!cfmtime) {
2444 AST_LIST_UNLOCK(&cfmtime_head);
2445 continue;
2446 }
2447 /* Note that the file mtime is initialized to 0, i.e. 1970 */
2448 AST_LIST_INSERT_SORTALPHA(&cfmtime_head, cfmtime, list, filename);
2449 }
2450 }
2451
2452 if (cfmtime
2453 && !cfmtime->has_exec
2454 && !cfmstat_cmp(cfmtime, &statbuf)
2455 && ast_test_flag(&flags, CONFIG_FLAG_FILEUNCHANGED)) {
2456 int unchanged = 1;
2457
2458 /* File is unchanged, what about the (cached) includes (if any)? */
2459 AST_LIST_TRAVERSE(&cfmtime->includes, cfinclude, list) {
2460 if (!config_text_file_load(NULL, NULL, cfinclude->include,
2461 NULL, flags, "", who_asked)) {
2462 /* One change is enough to short-circuit and reload the whole shebang */
2463 unchanged = 0;
2464 break;
2465 }
2466 }
2467
2468 if (unchanged) {
2469 AST_LIST_UNLOCK(&cfmtime_head);
2470 globfree(&globbuf);
2471 ast_free(comment_buffer);
2472 ast_free(lline_buffer);
2473 return CONFIG_STATUS_FILEUNCHANGED;
2474 }
2475 }
2476
2477 /* If cfg is NULL, then we just want a file changed answer. */
2478 if (cfg == NULL) {
2479 if (cfmtime) {
2480 AST_LIST_UNLOCK(&cfmtime_head);
2481 }
2482 continue;
2483 }
2484
2485 if (cfmtime) {
2486 /* Forget about what we thought we knew about this file's includes. */
2487 cfmtime->has_exec = 0;
2488 config_cache_flush_includes(cfmtime);
2489
2490 cfmstat_save(cfmtime, &statbuf);
2491 AST_LIST_UNLOCK(&cfmtime_head);
2492 }
2493
2494 if (!(f = fopen(fn, "r"))) {
2495 ast_debug(1, "No file to parse: %s\n", fn);
2496 ast_verb(2, "Parsing '%s': Not found (%s)\n", fn, strerror(errno));
2497 continue;
2498 }
2499 count++;
2500 /* If we get to this point, then we're loading regardless */
2501 ast_clear_flag(&flags, CONFIG_FLAG_FILEUNCHANGED);
2502 ast_debug(1, "Parsing %s\n", fn);
2503 while (!feof(f)) {
2504 lineno++;
2505 if (fgets(buf, sizeof(buf), f)) {
2506 /* Skip lines that are too long */
2507 if (strlen(buf) == sizeof(buf) - 1 && buf[sizeof(buf) - 2] != '\n') {
2508 ast_log(LOG_WARNING, "Line %d too long, skipping. It begins with: %.32s...\n", lineno, buf);
2509 while (fgets(buf, sizeof(buf), f)) {
2510 if (strlen(buf) != sizeof(buf) - 1 || buf[sizeof(buf) - 2] == '\n') {
2511 break;
2512 }
2513 }
2514 continue;
2515 }
2516
2517 /* If there is a UTF-8 BOM, skip over it */
2518 if (lineno == 1) {
2519 #define UTF8_BOM "\xEF\xBB\xBF"
2520 size_t line_bytes = strlen(buf);
2521 size_t bom_bytes = sizeof(UTF8_BOM) - 1;
2522 if (line_bytes >= bom_bytes
2523 && !memcmp(buf, UTF8_BOM, bom_bytes)) {
2524 memmove(buf, &buf[bom_bytes], line_bytes - bom_bytes + 1);
2525 }
2526 #undef UTF8_BOM
2527 }
2528
2529 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)
2530 && lline_buffer
2531 && ast_str_strlen(lline_buffer)) {
2532 CB_ADD(&comment_buffer, ast_str_buffer(lline_buffer)); /* add the current lline buffer to the comment buffer */
2533 ast_str_reset(lline_buffer); /* erase the lline buffer */
2534 }
2535
2536 new_buf = buf;
2537 if (comment) {
2538 process_buf = NULL;
2539 } else {
2540 process_buf = buf;
2541 }
2542
2543 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)
2544 && (ast_strlen_zero(buf) || strlen(buf) == strspn(buf, " \t\n\r"))) {
2545 /* keep blank lines as comments */
2546 CB_ADD(&comment_buffer, "\n"); /* add newline to the comment buffer */
2547 continue; /* go get a new line, then */
2548 }
2549
2550 while ((comment_p = strchr(new_buf, COMMENT_META))) {
2551 if ((comment_p > new_buf) && (*(comment_p - 1) == '\\')) {
2552 /* Escaped semicolons aren't comments. */
2553 new_buf = comment_p;
2554 /* write over the \ and bring the null terminator with us */
2555 memmove(comment_p - 1, comment_p, strlen(comment_p) + 1);
2556 } else if (comment_p[1] == COMMENT_TAG && comment_p[2] == COMMENT_TAG && (comment_p[3] != '-')) {
2557 /* Meta-Comment start detected ";--" */
2558 if (comment < MAX_NESTED_COMMENTS) {
2559 *comment_p = '\0';
2560 new_buf = comment_p + 3;
2561 comment++;
2562 nest[comment-1] = lineno;
2563 } else {
2564 ast_log(LOG_ERROR, "Maximum nest limit of %d reached.\n", MAX_NESTED_COMMENTS);
2565 }
2566 } else if ((comment_p >= new_buf + 2) &&
2567 (*(comment_p - 1) == COMMENT_TAG) &&
2568 (*(comment_p - 2) == COMMENT_TAG)) {
2569 /* Meta-Comment end detected "--;" */
2570 comment--;
2571 new_buf = comment_p + 1;
2572 if (!comment) {
2573 /* Back to non-comment now */
2574 if (process_buf) {
2575 /* Actually have to move what's left over the top, then continue */
2576 char *oldptr;
2577
2578 oldptr = process_buf + strlen(process_buf);
2579 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
2580 CB_ADD(&comment_buffer, ";");
2581 CB_ADD_LEN(&comment_buffer, oldptr+1, new_buf-oldptr-1);
2582 }
2583
2584 memmove(oldptr, new_buf, strlen(new_buf) + 1);
2585 new_buf = oldptr;
2586 } else {
2587 process_buf = new_buf;
2588 }
2589 }
2590 } else {
2591 if (!comment) {
2592 /* If ; is found, and we are not nested in a comment,
2593 we immediately stop all comment processing */
2594 while ((comment_p > new_buf) && isspace(*(comment_p - 1))) {
2595 /* To preserve comment formatting we want to include any
2596 whitespace before the ";" */
2597 comment_p--;
2598 }
2599 if ((comment_p != new_buf) && (*comment_p == ' ') && (*(comment_p + 1) == ' ')) {
2600 /* If the comment (w/whitespace) does not start in column 1
2601 then, when written out, the preceeding variable/value will
2602 be separated from the comment by two spaces. To preserve
2603 comment formatting we should also take this into account. */
2604 comment_p += 2;
2605 }
2606 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
2607 CB_ADD(&lline_buffer, comment_p);
2608 }
2609 *comment_p = '\0';
2610 new_buf = comment_p;
2611 } else {
2612 new_buf = comment_p + 1;
2613 }
2614 }
2615 }
2616 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment && !process_buf ) {
2617 CB_ADD(&comment_buffer, buf); /* the whole line is a comment, store it */
2618 }
2619
2620 if (process_buf) {
2621 char *buffer = ast_strip(process_buf);
2622
2623 if (!ast_strlen_zero(buffer)) {
2624 if (process_text_line(cfg, &cat, buffer, lineno, fn,
2625 flags, comment_buffer, lline_buffer,
2626 suggested_include_file, &last_cat, &last_var, &last_inc,
2627 who_asked)) {
2628 cfg = CONFIG_STATUS_FILEINVALID;
2629 break;
2630 }
2631 }
2632 }
2633 }
2634 }
2635 /* end of file-- anything in a comment buffer? */
2636 if (last_cat) {
2637 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer)) {
2638 if (lline_buffer && ast_str_strlen(lline_buffer)) {
2639 CB_ADD(&comment_buffer, ast_str_buffer(lline_buffer)); /* add the current lline buffer to the comment buffer */
2640 ast_str_reset(lline_buffer); /* erase the lline buffer */
2641 }
2642 last_cat->trailing = ALLOC_COMMENT(comment_buffer);
2643 }
2644 } else if (last_var) {
2645 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer)) {
2646 if (lline_buffer && ast_str_strlen(lline_buffer)) {
2647 CB_ADD(&comment_buffer, ast_str_buffer(lline_buffer)); /* add the current lline buffer to the comment buffer */
2648 ast_str_reset(lline_buffer); /* erase the lline buffer */
2649 }
2650 last_var->trailing = ALLOC_COMMENT(comment_buffer);
2651 }
2652 } else if (last_inc) {
2653 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer)) {
2654 if (lline_buffer && ast_str_strlen(lline_buffer)) {
2655 CB_ADD(&comment_buffer, ast_str_buffer(lline_buffer)); /* add the current lline buffer to the comment buffer */
2656 ast_str_reset(lline_buffer); /* erase the lline buffer */
2657 }
2658 last_inc->trailing = ALLOC_COMMENT(comment_buffer);
2659 }
2660 } else {
2661 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS) && comment_buffer && ast_str_strlen(comment_buffer)) {
2662 ast_debug(1, "Nothing to attach comments to, discarded: %s\n", ast_str_buffer(comment_buffer));
2663 }
2664 }
2665 if (ast_test_flag(&flags, CONFIG_FLAG_WITHCOMMENTS)) {
2666 CB_RESET(comment_buffer, lline_buffer);
2667 }
2668
2669 fclose(f);
2670 } while (0);
2671 if (comment) {
2672 ast_log(LOG_WARNING, "Unterminated comment detected beginning on line %d\n", nest[comment - 1]);
2673 }
2674 if (cfg == NULL || cfg == CONFIG_STATUS_FILEUNCHANGED || cfg == CONFIG_STATUS_FILEINVALID) {
2675 break;
2676 }
2677 }
2678 globfree(&globbuf);
2679 }
2680
2681 ast_free(comment_buffer);
2682 ast_free(lline_buffer);
2683
2684 if (count == 0) {
2685 return NULL;
2686 }
2687
2688 return cfg;
2689 }
2690
2691
2692 /* NOTE: categories and variables each have a file and lineno attribute. On a save operation, these are used to determine
2693 which file and line number to write out to. Thus, an entire hierarchy of config files (via #include statements) can be
2694 recreated. BUT, care must be taken to make sure that every cat and var has the proper file name stored, or you may
2695 be shocked and mystified as to why things are not showing up in the files!
2696
2697 Also, All #include/#exec statements are recorded in the "includes" LL in the ast_config structure. The file name
2698 and line number are stored for each include, plus the name of the file included, so that these statements may be
2699 included in the output files on a file_save operation.
2700
2701 The lineno's are really just for relative placement in the file. There is no attempt to make sure that blank lines
2702 are included to keep the lineno's the same between input and output. The lineno fields are used mainly to determine
2703 the position of the #include and #exec directives. So, blank lines tend to disappear from a read/rewrite operation,
2704 and a header gets added.
2705
2706 vars and category heads are output in the order they are stored in the config file. So, if the software
2707 shuffles these at all, then the placement of #include directives might get a little mixed up, because the
2708 file/lineno data probably won't get changed.
2709
2710 */
2711
2712 static void gen_header(FILE *f1, const char *configfile, const char *fn, const char *generator)
2713 {
2714 char date[256]="";
2715 time_t t;
2716
2717 time(&t);
2718 ast_copy_string(date, ctime(&t), sizeof(date));
2719
2720 fprintf(f1, ";!\n");
2721 fprintf(f1, ";! Automatically generated configuration file\n");
2722 if (strcmp(configfile, fn))
2723 fprintf(f1, ";! Filename: %s (%s)\n", configfile, fn);
2724 else
2725 fprintf(f1, ";! Filename: %s\n", configfile);
2726 fprintf(f1, ";! Generator: %s\n", generator);
2727 fprintf(f1, ";! Creation Date: %s", date);
2728 fprintf(f1, ";!\n");
2729 }
2730
2731 static void inclfile_destroy(void *obj)
2732 {
2733 const struct inclfile *o = obj;
2734
2735 ast_free(o->fname);
2736 }
2737
2738 static void make_fn(char *fn, size_t fn_size, const char *file, const char *configfile)
2739 {
2740 if (ast_strlen_zero(file)) {
2741 if (configfile[0] == '/') {
2742 ast_copy_string(fn, configfile, fn_size);
2743 } else {
2744 snprintf(fn, fn_size, "%s/%s", ast_config_AST_CONFIG_DIR, configfile);
2745 }
2746 } else if (file[0] == '/') {
2747 ast_copy_string(fn, file, fn_size);
2748 } else {
2749 snprintf(fn, fn_size, "%s/%s", ast_config_AST_CONFIG_DIR, file);
2750 }
2751 }
2752
2753 static struct inclfile *set_fn(char *fn, size_t fn_size, const char *file, const char *configfile, struct ao2_container *fileset)
2754 {
2755 struct inclfile lookup;
2756 struct inclfile *fi;
2757
2758 make_fn(fn, fn_size, file, configfile);
2759 lookup.fname = fn;
2760 fi = ao2_find(fileset, &lookup, OBJ_POINTER);
2761 if (fi) {
2762 /* Found existing include file scratch pad. */
2763 return fi;
2764 }
2765
2766 /* set up a file scratch pad */
2767 fi = ao2_alloc(sizeof(struct inclfile), inclfile_destroy);
2768 if (!fi) {
2769 /* Scratch pad creation failed. */
2770 return NULL;
2771 }
2772 fi->fname = ast_strdup(fn);
2773 if (!fi->fname) {
2774 /* Scratch pad creation failed. */
2775 ao2_ref(fi, -1);
2776 return NULL;
2777 }
2778 fi->lineno = 1;
2779
2780 ao2_link(fileset, fi);
2781
2782 return fi;
2783 }
2784
2785 static int count_linefeeds(char *str)
2786 {
2787 int count = 0;
2788
2789 while (*str) {
2790 if (*str =='\n')
2791 count++;
2792 str++;
2793 }
2794 return count;
2795 }
2796
2797 static int count_linefeeds_in_comments(struct ast_comment *x)
2798 {
2799 int count = 0;
2800
2801 while (x) {
2802 count += count_linefeeds(x->cmt);
2803 x = x->next;
2804 }
2805 return count;
2806 }
2807
2808 static void insert_leading_blank_lines(FILE *fp, struct inclfile *fi, struct ast_comment *precomments, int lineno)
2809 {
2810 int precomment_lines;
2811 int i;
2812
2813 if (!fi) {
2814 /* No file scratch pad object so insert no blank lines. */
2815 return;
2816 }
2817
2818 precomment_lines = count_linefeeds_in_comments(precomments);
2819
2820 /* I don't have to worry about those ;! comments, they are
2821 stored in the precomments, but not printed back out.
2822 I did have to make sure that comments following
2823 the ;! header comments were not also deleted in the process */
2824 if (lineno - precomment_lines - fi->lineno < 0) { /* insertions can mess up the line numbering and produce negative numbers that mess things up */
2825 return;
2826 } else if (lineno == 0) {
2827 /* Line replacements also mess things up */
2828 return;
2829 } else if (lineno - precomment_lines - fi->lineno < 5) {
2830 /* Only insert less than 5 blank lines; if anything more occurs,
2831 * it's probably due to context deletion. */
2832 for (i = fi->lineno; i < lineno - precomment_lines; i++) {
2833 fprintf(fp, "\n");
2834 }
2835 } else {
2836 /* Deletion occurred - insert a single blank line, for separation of
2837 * contexts. */
2838 fprintf(fp, "\n");
2839 }
2840
2841 fi->lineno = lineno + 1; /* Advance the file lineno */
2842 }
2843
2844 int ast_config_text_file_save(const char *configfile, const struct ast_config *cfg, const char *generator)
2845 {
2846 return ast_config_text_file_save2(configfile, cfg, generator, CONFIG_SAVE_FLAG_PRESERVE_EFFECTIVE_CONTEXT);
2847 }
2848
2849 static int is_writable(const char *fn)
2850 {
2851 if (access(fn, F_OK)) {
2852 char *dn = dirname(ast_strdupa(fn));
2853
2854 if (access(dn, R_OK | W_OK)) {
2855 ast_log(LOG_ERROR, "Unable to write to directory %s (%s)\n", dn, strerror(errno));
2856 return 0;
2857 }
2858 } else {
2859 if (access(fn, R_OK | W_OK)) {
2860 ast_log(LOG_ERROR, "Unable to write %s (%s)\n", fn, strerror(errno));
2861 return 0;
2862 }
2863 }
2864
2865 return 1;
2866 }
2867
2868 static void print_comment(FILE *f, struct ast_comment *comment)
2869 {
2870 struct ast_comment *cmt;
2871
2872 for (cmt = comment; cmt; cmt = cmt->next) {
2873 char *line = ast_strdupa(cmt->cmt);
2874 char *nl;
2875
2876 while ((nl = strchr(line, '\n')) != NULL) {
2877 *nl = '\0';
2878 if (line[0] != ';' || line[1] != '!') {
2879 /* if not one of our generated header comments */
2880 fprintf(f, "%s\n", line);
2881 }
2882
2883 line = nl + 1;
2884 }
2885 }
2886 }
2887
2888 static void print_include(FILE *f, struct ast_config_include *incl)
2889 {
2890 switch (incl->include_type) {
2891 case CONFIG_STATEMENT_INCLUDE:
2892 fprintf(f, "#include \"%s\"\n", incl->included_file);
2893 break;
2894 case CONFIG_STATEMENT_TRYINCLUDE:
2895 fprintf(f, "#tryinclude \"%s\"\n", incl->included_file);
2896 break;
2897 case CONFIG_STATEMENT_EXEC:
2898 fprintf(f, "#exec \"%s\"\n", incl->exec_file);
2899 break;
2900 }
2901 }
2902
2903 int ast_config_text_file_save2(const char *configfile, const struct ast_config *cfg, const char *generator, uint32_t flags)
2904 {
2905 FILE *f;
2906 char fn[PATH_MAX];
2907 struct ast_variable *var;
2908 struct ast_category *cat;
2909 struct ast_comment *cmt;
2910 struct ast_config_include *incl;
2911 int blanklines = 0;
2912 struct ao2_container *fileset;
2913 struct inclfile *fi;
2914
2915 /* Check all the files for write access before attempting to modify any of them */
2916 for (incl = cfg->includes_root; incl; incl = incl->next) {
2917 /* reset all the output flags in case this isn't our first time saving this data */
2918 incl->output = 0;
2919
2920 if (incl->include_type != CONFIG_STATEMENT_EXEC) {
2921 struct config_included_file *included_file;
2922 int ok = 1;
2923
2924 /* Not a #exec. */
2925 /* For #include, make sure we have write access to the include file
2926 file or its parent directory. If the file itself doesn't exist,
2927 make sure we have write access to the directory. */
2928 /* For #tryinclude, we check the file(s) that match the pattern. */
2929
2930 AST_LIST_TRAVERSE(&incl->included_files, included_file, next) {
2931 if (!is_writable(included_file->path)) {
2932 /* the #tryinclude path exists but is not writable */
2933 ok = 0;
2934 break;
2935 }
2936 }
2937
2938 if (!ok) {
2939 /* at least one include file is not writable */
2940 return -1;
2941 }
2942 }
2943 }
2944
2945 /* now make sure we have write access to the main config file or its parent directory */
2946 make_fn(fn, sizeof(fn), 0, configfile);
2947 if (!is_writable(fn)) {
2948 return -1;
2949 }
2950
2951 fileset = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 1023,
2952 hash_string, NULL, hashtab_compare_strings);
2953 if (!fileset) {
2954 /* Container creation failed. */
2955 return -1;
2956 }
2957
2958 /* Now that we know we have write access to all files, it's safe to start truncating them */
2959
2960 /* go thru all the inclusions and make sure all the files involved (configfile plus all its inclusions)
2961 are all truncated to zero bytes and have that nice header*/
2962 /* Note: for #exec, we write out the directives but don't zero out the exec files */
2963 for (incl = cfg->includes_root; incl; incl = incl->next) {
2964 if (incl->include_type != CONFIG_STATEMENT_EXEC) {
2965 struct config_included_file *included_file;
2966
2967 AST_LIST_TRAVERSE(&incl->included_files, included_file, next) {
2968 fi = set_fn(fn, sizeof(fn), included_file->path, configfile, fileset);
2969 f = fopen(fn, "w");
2970 if (f) {
2971 ast_verb(2, "Saving tryinclude '%s'\n", fn);
2972 gen_header(f, configfile, fn, generator);
2973 fclose(f);
2974 } else {
2975 ast_log(LOG_ERROR, "Unable to write %s (%s)\n", fn, strerror(errno));
2976 }
2977 if (fi) {
2978 ao2_ref(fi, -1);
2979 }
2980 }
2981 }
2982 }
2983
2984 /* just set fn to absolute ver of configfile */
2985 fi = set_fn(fn, sizeof(fn), 0, configfile, fileset);
2986 if (
2987 #ifdef __CYGWIN__
2988 (f = fopen(fn, "w+"))
2989 #else
2990 (f = fopen(fn, "w"))
2991 #endif
2992 ) {
2993 ast_verb(2, "Saving '%s'\n", fn);
2994 gen_header(f, configfile, fn, generator);
2995 cat = cfg->root;
2996 fclose(f);
2997 if (fi) {
2998 ao2_ref(fi, -1);
2999 }
3000
3001 /* from here out, we open each involved file and concat the stuff we need to add to the end and immediately close... */
3002 /* since each var, cat, and associated comments can come from any file, we have to be
3003 mobile, and open each file, print, and close it on an entry-by-entry basis */
3004
3005 while (cat) {
3006 fi = set_fn(fn, sizeof(fn), cat->file, configfile, fileset);
3007 f = fopen(fn, "a");
3008 if (!f) {
3009 ast_log(LOG_ERROR, "Unable to write %s (%s)\n", fn, strerror(errno));
3010 if (fi) {
3011 ao2_ref(fi, -1);
3012 }
3013 ao2_ref(fileset, -1);
3014 return -1;
3015 }
3016
3017 /* dump any includes that happen before this category header */
3018 for (incl = cfg->includes_root; incl; incl = incl->next) {
3019 if (strcmp(incl->include_location_file, cat->file) == 0) {
3020 if (cat->lineno > incl->include_location_lineno && !incl->output) {
3021 /* add the precomments */
3022 insert_leading_blank_lines(f, fi, incl->precomments, incl->include_location_lineno);
3023 print_comment(f, incl->precomments);
3024 /* and the include */
3025 print_include(f, incl);
3026 incl->output = 1;
3027 }
3028 }
3029 }
3030
3031 /* dump any comments that happen before this category header */
3032 insert_leading_blank_lines(f, fi, cat->precomments, cat->lineno);
3033 print_comment(f, cat->precomments);
3034
3035 /* dump the category header */
3036 fprintf(f, "[%s]", cat->name);
3037 if (cat->ignored || !AST_LIST_EMPTY(&cat->template_instances)) {
3038 fprintf(f, "(");
3039 if (cat->ignored) {
3040 fprintf(f, "!");
3041 }
3042 if (cat->ignored && !AST_LIST_EMPTY(&cat->template_instances)) {
3043 fprintf(f, ",");
3044 }
3045 if (!AST_LIST_EMPTY(&cat->template_instances)) {
3046 struct ast_category_template_instance *x;
3047 AST_LIST_TRAVERSE(&cat->template_instances, x, next) {
3048 fprintf(f, "%s",x->name);
3049 if (x != AST_LIST_LAST(&cat->template_instances))
3050 fprintf(f, ",");
3051 }
3052 }
3053 fprintf(f, ")");
3054 }
3055 for(cmt = cat->sameline; cmt; cmt = cmt->next)
3056 {
3057 fprintf(f, "%s", cmt->cmt);
3058 }
3059 if (!cat->sameline)
3060 fprintf(f, "\n");
3061
3062 /* dump any trailing comments */
3063 print_comment(f, cat->trailing);
3064
3065 /* and we're all done */
3066 fclose(f);
3067 if (fi) {
3068 ao2_ref(fi, -1);
3069 }
3070
3071 var = cat->root;
3072 while (var) {
3073 struct ast_category_template_instance *x;
3074 int found = 0;
3075
3076 AST_LIST_TRAVERSE(&cat->template_instances, x, next) {
3077 struct ast_variable *v;
3078 for (v = x->inst->root; v; v = v->next) {
3079
3080 if (flags & CONFIG_SAVE_FLAG_PRESERVE_EFFECTIVE_CONTEXT) {
3081 if (!strcasecmp(var->name, v->name) && !strcmp(var->value, v->value)) {
3082 found = 1;
3083 break;
3084 }
3085 } else {
3086 if (var->inherited) {
3087 found = 1;
3088 break;
3089 } else {
3090 if (!strcasecmp(var->name, v->name) && !strcmp(var->value, v->value)) {
3091 found = 1;
3092 break;
3093 }
3094 }
3095 }
3096 }
3097 if (found) {
3098 break;
3099 }
3100 }
3101 if (found) {
3102 var = var->next;
3103 continue;
3104 }
3105 fi = set_fn(fn, sizeof(fn), var->file, configfile, fileset);
3106 f = fopen(fn, "a");
3107 if (!f) {
3108 ast_debug(1, "Unable to open for writing: %s\n", fn);
3109 ast_verb(2, "Unable to write %s (%s)\n", fn, strerror(errno));
3110 if (fi) {
3111 ao2_ref(fi, -1);
3112 }
3113 ao2_ref(fileset, -1);
3114 return -1;
3115 }
3116
3117 /* dump any includes that happen before this variable */
3118 for (incl = cfg->includes_root; incl; incl = incl->next) {
3119 if (strcmp(incl->include_location_file, var->file) == 0) {
3120 if (var->lineno > incl->include_location_lineno && !incl->output) {
3121 /* add the precomments */
3122 insert_leading_blank_lines(f, fi, incl->precomments, incl->include_location_lineno);
3123 print_comment(f, incl->precomments);
3124 /* and the include */
3125 print_include(f, incl);
3126 incl->output = 1;
3127 }
3128 }
3129 }
3130
3131 /* dump any comments that happen before this variable */
3132 insert_leading_blank_lines(f, fi, var->precomments, var->lineno);
3133 print_comment(f, var->precomments);
3134
3135 { /* Block for 'escaped' scope */
3136 int escaped_len = 2 * strlen(var->value) + 1;
3137 char escaped[escaped_len];
3138
3139 ast_escape_semicolons(var->value, escaped, escaped_len);
3140
3141 if (var->sameline) {
3142 fprintf(f, "%s %s %s %s", var->name, (var->object ? "=>" : "="),
3143 escaped, var->sameline->cmt);
3144 } else {
3145 fprintf(f, "%s %s %s\n", var->name, (var->object ? "=>" : "="),
3146 escaped);
3147 }
3148 }
3149
3150 /* dump any trailing comments */
3151 print_comment(f, var->trailing);
3152 if (var->blanklines) {
3153 blanklines = var->blanklines;
3154 while (blanklines--)
3155 fprintf(f, "\n");
3156 }
3157
3158 fclose(f);
3159 if (fi) {
3160 ao2_ref(fi, -1);
3161 }
3162
3163 var = var->next;
3164 }
3165 cat = cat->next;
3166 }
3167
3168
3169 /* Now, for files with trailing #include/#exec statements,
3170 we have to make sure every entry is output */
3171 for (incl = cfg->includes_root; incl; incl = incl->next) {
3172 if (!incl->output) {
3173 /* open the respective file */
3174 fi = set_fn(fn, sizeof(fn), incl->include_location_file, configfile, fileset);
3175 f = fopen(fn, "a");
3176 if (!f) {
3177 ast_debug(1, "Unable to open for writing: %s\n", fn);
3178 ast_verb(2, "Unable to write %s (%s)\n", fn, strerror(errno));
3179 if (fi) {
3180 ao2_ref(fi, -1);
3181 }
3182 ao2_ref(fileset, -1);
3183 return -1;
3184 }
3185
3186 /* add the precomments */
3187 insert_leading_blank_lines(f, fi, incl->precomments, incl->include_location_lineno);
3188 print_comment(f, incl->precomments);
3189 /* and the include */
3190 print_include(f, incl);
3191 /* and any trailing comments */
3192 print_comment(f, incl->trailing);
3193
3194 incl->output = 1;
3195 fclose(f);
3196 if (fi) {
3197 ao2_ref(fi, -1);
3198 }
3199 }
3200 }
3201
3202
3203 ast_verb(2, "Saving '%s': saved\n", fn);
3204 } else {
3205 ast_debug(1, "Unable to open for writing: %s\n", fn);
3206 ast_verb(2, "Unable to write '%s' (%s)\n", fn, strerror(errno));
3207 if (fi) {
3208 ao2_ref(fi, -1);
3209 }
3210 ao2_ref(fileset, -1);
3211 return -1;
3212 }
3213
3214 ao2_ref(fileset, -1); /* this should destroy the hash container */
3215
3216 /* pass new configuration to any config hooks */
3217 config_hook_exec(configfile, generator, cfg);
3218
3219 return 0;
3220 }
3221
3222 static void clear_config_maps(void)
3223 {
3224 struct ast_config_map *map;
3225
3226 while (config_maps) {
3227 map = config_maps;
3228 config_maps = config_maps->next;
3229 ast_free(map);
3230 }
3231 }
3232
3233 #ifdef TEST_FRAMEWORK
3234 int ast_realtime_append_mapping(const char *name, const char *driver, const char *database, const char *table, int priority)
3235 #else
3236 static int ast_realtime_append_mapping(const char *name, const char *driver, const char *database, const char *table, int priority)
3237 #endif
3238 {
3239 struct ast_config_map *map;
3240 char *dst;
3241 int length;
3242
3243 length = sizeof(*map);
3244 length += strlen(name) + 1;
3245 length += strlen(driver) + 1;
3246 length += strlen(database) + 1;
3247 if (table)
3248 length += strlen(table) + 1;
3249
3250 if (!(map = ast_calloc(1, length)))
3251 return -1;
3252
3253 dst = map->stuff; /* writable space starts here */
3254 map->name = strcpy(dst, name);
3255 dst += strlen(dst) + 1;
3256 map->driver = strcpy(dst, driver);
3257 dst += strlen(dst) + 1;
3258 map->database = strcpy(dst, database);
3259 if (table) {
3260 dst += strlen(dst) + 1;
3261 map->table = strcpy(dst, table);
3262 }
3263 map->priority = priority;
3264 map->next = config_maps;
3265 config_maps = map;
3266
3267 ast_verb(5, "Binding %s to %s/%s/%s\n", map->name, map->driver, map->database, map->table ? map->table : map->name);
3268
3269 return 0;
3270 }
3271
3272 static int reload_module(void)
3273 {
3274 struct ast_config *config, *configtmp;
3275 struct ast_variable *v;
3276 char *driver, *table, *database, *textpri, *stringp, *tmp;
3277 struct ast_flags flags = { CONFIG_FLAG_NOREALTIME };
3278 int pri;
3279 SCOPED_MUTEX(lock, &config_lock);
3280
3281 clear_config_maps();
3282
3283 configtmp = ast_config_new();
3284 if (!configtmp) {
3285 ast_log(LOG_ERROR, "Unable to allocate memory for new config\n");
3286 return -1;
3287 }
3288 config = ast_config_internal_load(extconfig_conf, configtmp, flags, "", "extconfig");
3289 if (config == CONFIG_STATUS_FILEINVALID) {
3290 return -1;
3291 } else if (!config) {
3292 ast_config_destroy(configtmp);
3293 return 0;
3294 }
3295
3296 for (v = ast_variable_browse(config, "settings"); v; v = v->next) {
3297 char buf[512];
3298 ast_copy_string(buf, v->value, sizeof(buf));
3299 stringp = buf;
3300 driver = strsep(&stringp, ",");
3301 if (!stringp) {
3302 ast_log(LOG_WARNING, "extconfig.conf: value '%s' ignored due to wrong format\n", v->value);
3303 continue;
3304 }
3305 if ((tmp = strchr(stringp, '\"')))
3306 stringp = tmp;
3307
3308 /* check if the database text starts with a double quote */
3309 if (*stringp == '"') {
3310 stringp++;
3311 database = strsep(&stringp, "\"");
3312 strsep(&stringp, ",");
3313 } else {
3314 /* apparently this text has no quotes */
3315 database = strsep(&stringp, ",");
3316 }
3317
3318 table = strsep(&stringp, ",");
3319 textpri = strsep(&stringp, ",");
3320 if (!textpri || !(pri = atoi(textpri))) {
3321 pri = 1;
3322 }
3323
3324 if (!strcmp(v->name, extconfig_conf)) {
3325 ast_log(LOG_WARNING, "Cannot bind '%s'!\n", extconfig_conf);
3326 continue;
3327 }
3328
3329 if (!strcmp(v->name, "asterisk.conf")) {
3330 ast_log(LOG_WARNING, "Cannot bind 'asterisk.conf'!\n");
3331 continue;
3332 }
3333
3334 if (!strcmp(v->name, "logger.conf")) {
3335 ast_log(LOG_WARNING, "Cannot bind 'logger.conf'!\n");
3336 continue;
3337 }
3338
3339 if (!driver || !database)
3340 continue;
3341 if (!strcasecmp(v->name, "iaxfriends")) {
3342 ast_log(LOG_WARNING, "The 'iaxfriends' table is obsolete, update your config to use iaxusers and iaxpeers, though they can point to the same table.\n");
3343 ast_realtime_append_mapping("iaxusers", driver, database, table ? table : "iaxfriends", pri);
3344 ast_realtime_append_mapping("iaxpeers", driver, database, table ? table : "iaxfriends", pri);
3345 } else
3346 ast_realtime_append_mapping(v->name, driver, database, table, pri);
3347 }
3348
3349 ast_config_destroy(config);
3350 return 0;
3351 }
3352
3353 int ast_config_engine_register(struct ast_config_engine *new)
3354 {
3355 struct ast_config_engine *ptr;
3356
3357 SCOPED_MUTEX(lock, &config_lock);
3358
3359 if (!config_engine_list) {
3360 config_engine_list = new;
3361 } else {
3362 for (ptr = config_engine_list; ptr->next; ptr=ptr->next);
3363 ptr->next = new;
3364 }
3365
3366 return 1;
3367 }
3368
3369 int ast_config_engine_deregister(struct ast_config_engine *del)
3370 {
3371 struct ast_config_engine *ptr, *last=NULL;
3372
3373 SCOPED_MUTEX(lock, &config_lock);
3374
3375 for (ptr = config_engine_list; ptr; ptr=ptr->next) {
3376 if (ptr == del) {
3377 if (last)
3378 last->next = ptr->next;
3379 else
3380 config_engine_list = ptr->next;
3381 break;
3382 }
3383 last = ptr;
3384 }
3385
3386 return 0;
3387 }
3388
3389 int ast_realtime_is_mapping_defined(const char *family)
3390 {
3391 struct ast_config_map *map;
3392 SCOPED_MUTEX(lock, &config_lock);
3393
3394 for (map = config_maps; map; map = map->next) {
3395 if (!strcasecmp(family, map->name)) {
3396 return 1;
3397 }
3398 }
3399 ast_debug(5, "Failed to find a realtime mapping for %s\n", family);
3400
3401 return 0;
3402 }
3403
3404 /*! \brief Find realtime engine for realtime family */
3405 static struct ast_config_engine *find_engine(const char *family, int priority, char *database, int dbsiz, char *table, int tabsiz)
3406 {
3407 struct ast_config_engine *eng, *ret = NULL;
3408 struct ast_config_map *map;
3409
3410 SCOPED_MUTEX(lock, &config_lock);
3411
3412 for (map = config_maps; map; map = map->next) {
3413 if (!strcasecmp(family, map->name) && (priority == map->priority)) {
3414 if (database)
3415 ast_copy_string(database, map->database, dbsiz);
3416 if (table)
3417 ast_copy_string(table, map->table ? map->table : family, tabsiz);
3418 break;
3419 }
3420 }
3421
3422 /* Check if the required driver (engine) exist */
3423 if (map) {
3424 for (eng = config_engine_list; !ret && eng; eng = eng->next) {
3425 if (!strcasecmp(eng->name, map->driver))
3426 ret = eng;
3427 }
3428 }
3429
3430 /* if we found a mapping, but the engine is not available, then issue a warning */
3431 if (map && !ret)
3432 ast_log(LOG_WARNING, "Realtime mapping for '%s' found to engine '%s', but the engine is not available\n", map->name, map->driver);
3433
3434 return ret;
3435 }
3436
3437 static struct ast_config_engine text_file_engine = {
3438 .name = "text",
3439 .load_func = config_text_file_load,
3440 };
3441
3442 struct ast_config *ast_config_copy(const struct ast_config *old)
3443 {
3444 struct ast_config *new_config = ast_config_new();
3445 struct ast_category *cat_iter;
3446
3447 if (!new_config) {
3448 return NULL;
3449 }
3450
3451 for (cat_iter = old->root; cat_iter; cat_iter = cat_iter->next) {
3452 struct ast_category *new_cat =
3453 ast_category_new(cat_iter->name, cat_iter->file, cat_iter->lineno);
3454 if (!new_cat) {
3455 goto fail;
3456 }
3457 ast_category_append(new_config, new_cat);
3458 if (cat_iter->root) {
3459 new_cat->root = ast_variables_dup(cat_iter->root);
3460 if (!new_cat->root) {
3461 goto fail;
3462 }
3463 new_cat->last = cat_iter->last;
3464 }
3465 }
3466
3467 return new_config;
3468
3469 fail:
3470 ast_config_destroy(new_config);
3471 return NULL;
3472 }
3473
3474
3475 struct ast_config *ast_config_internal_load(const char *filename, struct ast_config *cfg, struct ast_flags flags, const char *suggested_include_file, const char *who_asked)
3476 {
3477 char db[256];
3478 char table[256];
3479 struct ast_config_engine *loader = &text_file_engine;
3480 struct ast_config *result;
3481
3482 /* The config file itself bumps include_level by 1 */
3483 if (cfg->max_include_level > 0 && cfg->include_level == cfg->max_include_level + 1) {
3484 ast_log(LOG_WARNING, "Maximum Include level (%d) exceeded\n", cfg->max_include_level);
3485 return NULL;
3486 }
3487
3488 cfg->include_level++;
3489
3490 if (!ast_test_flag(&flags, CONFIG_FLAG_NOREALTIME) && config_engine_list) {
3491 struct ast_config_engine *eng;
3492
3493 eng = find_engine(filename, 1, db, sizeof(db), table, sizeof(table));
3494
3495
3496 if (eng && eng->load_func) {
3497 loader = eng;
3498 } else {
3499 eng = find_engine("global", 1, db, sizeof(db), table, sizeof(table));
3500 if (eng && eng->load_func)
3501 loader = eng;
3502 }
3503 }
3504
3505 result = loader->load_func(db, table, filename, cfg, flags, suggested_include_file, who_asked);
3506
3507 if (result && result != CONFIG_STATUS_FILEINVALID && result != CONFIG_STATUS_FILEUNCHANGED) {
3508 result->include_level--;
3509 config_hook_exec(filename, who_asked, result);
3510 } else if (result != CONFIG_STATUS_FILEINVALID) {
3511 cfg->include_level--;
3512 }
3513
3514 return result;
3515 }
3516
3517 struct ast_config *ast_config_load2(const char *filename, const char *who_asked, struct ast_flags flags)
3518 {
3519 struct ast_config *cfg;
3520 struct ast_config *result;
3521
3522 cfg = ast_config_new();
3523 if (!cfg)
3524 return NULL;
3525
3526 result = ast_config_internal_load(filename, cfg, flags, "", who_asked);
3527 if (!result || result == CONFIG_STATUS_FILEUNCHANGED || result == CONFIG_STATUS_FILEINVALID)
3528 ast_config_destroy(cfg);
3529
3530 return result;
3531 }
3532
3533 #define realtime_arguments_to_fields(ap, result) realtime_arguments_to_fields2(ap, 0, result)
3534
3535 /*!
3536 * \internal
3537 * \brief
3538 *
3539 * \param ap list of variable arguments
3540 * \param skip Skip argument pairs for this number of variables
3541 * \param result Address of a variables pointer to store the results
3542 * May be NULL if no arguments are parsed
3543 * Will be NULL on failure.
3544 *
3545 * \retval 0 on success or empty ap list
3546 * \retval -1 on failure
3547 */
3548 static int realtime_arguments_to_fields2(va_list ap, int skip, struct ast_variable **result)
3549 {
3550 struct ast_variable *first, *fields = NULL;
3551 const char *newparam;
3552 const char *newval;
3553
3554 /*
3555 * Previously we would do:
3556 *
3557 * va_start(ap, last);
3558 * x = realtime_arguments_to_fields(ap);
3559 * y = realtime_arguments_to_fields(ap);
3560 * va_end(ap);
3561 *
3562 * While this works on generic amd64 machines (2014), it doesn't on the
3563 * raspberry PI. The va_arg() manpage says:
3564 *
3565 * If ap is passed to a function that uses va_arg(ap, type) then
3566 * the value of ap is undefined after the return of that function.
3567 *
3568 * On the raspberry, ap seems to get reset after the call: the contents
3569 * of y would be equal to the contents of x.
3570 *
3571 * So, instead we allow the caller to skip past earlier argument sets
3572 * using the skip parameter:
3573 *
3574 * va_start(ap, last);
3575 * if (realtime_arguments_to_fields(ap, &x)) {
3576 * // FAILURE CONDITIONS
3577 * }
3578 * va_end(ap);
3579 * va_start(ap, last);
3580 * if (realtime_arguments_to_fields2(ap, 1, &y)) {
3581 * // FAILURE CONDITIONS
3582 * }
3583 * va_end(ap);
3584 */
3585 while (skip--) {
3586 /* There must be at least one argument. */
3587 newparam = va_arg(ap, const char *);
3588 newval = va_arg(ap, const char *);
3589 while ((newparam = va_arg(ap, const char *))) {
3590 newval = va_arg(ap, const char *);
3591 }
3592 }
3593
3594 /* Load up the first vars. */
3595 newparam = va_arg(ap, const char *);
3596 if (!newparam) {
3597 *result = NULL;
3598 return 0;
3599 }
3600 newval = va_arg(ap, const char *);
3601
3602 if (!(first = ast_variable_new(newparam, newval, ""))) {
3603 *result = NULL;
3604 return -1;
3605 }
3606
3607 while ((newparam = va_arg(ap, const char *))) {
3608 struct ast_variable *field;
3609
3610 newval = va_arg(ap, const char *);
3611 if (!(field = ast_variable_new(newparam, newval, ""))) {
3612 ast_variables_destroy(fields);
3613 ast_variables_destroy(first);
3614 *result = NULL;
3615 return -1;
3616 }
3617
3618 field->next = fields;
3619 fields = field;
3620 }
3621
3622 first->next = fields;
3623 fields = first;
3624
3625 *result = fields;
3626 return 0;
3627 }
3628
3629 struct ast_variable *ast_load_realtime_all_fields(const char *family, const struct ast_variable *fields)
3630 {
3631 struct ast_config_engine *eng;
3632 char db[256];
3633 char table[256];
3634 struct ast_variable *res=NULL;
3635 int i;
3636
3637 for (i = 1; ; i++) {
3638 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3639 if (eng->realtime_func) {
3640 res = eng->realtime_func(db, table, fields);
3641
3642 /* If a backend returns CONFIG_RT_NOT_FOUND, stop iteration and return NULL,
3643 * indicating that the requested record does not exist and no failover should occur.
3644 * Only continue iteration if the result is NULL and not CONFIG_RT_NOT_FOUND,
3645 * which signals a backend failure.
3646 */
3647 if (res == CONFIG_RT_NOT_FOUND) {
3648 return NULL;
3649 }
3650 if (res) {
3651 return res;
3652 }
3653 }
3654 } else {
3655 return NULL;
3656 }
3657 }
3658
3659 return res;
3660 }
3661
3662 struct ast_variable *ast_load_realtime_all(const char *family, ...)
3663 {
3664 RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
3665 struct ast_variable *res = NULL;
3666 va_list ap;
3667
3668 va_start(ap, family);
3669 realtime_arguments_to_fields(ap, &fields);
3670 va_end(ap);
3671
3672 if (fields) {
3673 res = ast_load_realtime_all_fields(family, fields);
3674 }
3675
3676 return res;
3677 }
3678
3679 struct ast_variable *ast_load_realtime_fields(const char *family, const struct ast_variable *fields)
3680 {
3681 struct ast_variable *res;
3682 struct ast_variable *cur;
3683 struct ast_variable **prev;
3684
3685 res = ast_load_realtime_all_fields(family, fields);
3686
3687 /* Filter the list. */
3688 prev = &res;
3689 cur = res;
3690 while (cur) {
3691 if (ast_strlen_zero(cur->value)) {
3692 /* Eliminate empty entries */
3693 struct ast_variable *next;
3694
3695 next = cur->next;
3696 *prev = next;
3697 ast_variable_destroy(cur);
3698 cur = next;
3699 } else {
3700 /* Make blank entries empty and keep them. */
3701 if (cur->value[0] == ' ' && cur->value[1] == '\0') {
3702 char *vptr = (char *) cur->value;
3703
3704 vptr[0] = '\0';
3705 }
3706
3707 prev = &cur->next;
3708 cur = cur->next;
3709 }
3710 }
3711 return res;
3712 }
3713
3714 struct ast_variable *ast_load_realtime(const char *family, ...)
3715 {
3716 RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
3717 int field_res = 0;
3718 va_list ap;
3719
3720 va_start(ap, family);
3721 if (realtime_arguments_to_fields(ap, &fields)) {
3722 field_res = -1;
3723 }
3724 va_end(ap);
3725
3726 if (field_res) {
3727 return NULL;
3728 }
3729
3730 if (!fields) {
3731 return NULL;
3732 }
3733
3734 return ast_load_realtime_fields(family, fields);
3735 }
3736
3737 /*! \brief Check if realtime engine is configured for family */
3738 int ast_check_realtime(const char *family)
3739 {
3740 struct ast_config_engine *eng;
3741 if (!ast_realtime_enabled()) {
3742 return 0; /* There are no engines at all so fail early */
3743 }
3744
3745 eng = find_engine(family, 1, NULL, 0, NULL, 0);
3746 if (eng)
3747 return 1;
3748 return 0;
3749 }
3750
3751 /*! \brief Check if there's any realtime engines loaded */
3752 int ast_realtime_enabled(void)
3753 {
3754 return config_maps ? 1 : 0;
3755 }
3756
3757 int ast_realtime_require_field(const char *family, ...)
3758 {
3759 struct ast_config_engine *eng;
3760 char db[256];
3761 char table[256];
3762 va_list ap, aq;
3763 int res = -1, i;
3764
3765 va_start(ap, family);
3766 for (i = 1; ; i++) {
3767 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3768 va_copy(aq, ap);
3769 /* If the require succeeds, it returns 0. */
3770 if (eng->require_func && !(res = eng->require_func(db, table, aq))) {
3771 va_end(aq);
3772 break;
3773 }
3774 va_end(aq);
3775 } else {
3776 break;
3777 }
3778 }
3779 va_end(ap);
3780
3781 return res;
3782 }
3783
3784 int ast_unload_realtime(const char *family)
3785 {
3786 struct ast_config_engine *eng;
3787 char db[256];
3788 char table[256];
3789 int res = -1, i;
3790
3791 for (i = 1; ; i++) {
3792 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3793 if (eng->unload_func) {
3794 /* Do this for ALL engines */
3795 res = eng->unload_func(db, table);
3796 }
3797 } else {
3798 break;
3799 }
3800 }
3801 return res;
3802 }
3803
3804 struct ast_config *ast_load_realtime_multientry_fields(const char *family, const struct ast_variable *fields)
3805 {
3806 struct ast_config_engine *eng;
3807 char db[256];
3808 char table[256];
3809 struct ast_config *res = NULL;
3810 int i;
3811
3812 for (i = 1; ; i++) {
3813 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3814 if (eng->realtime_multi_func && (res = eng->realtime_multi_func(db, table, fields))) {
3815 /* If we were returned an empty cfg, destroy it and return NULL */
3816 if (!res->root) {
3817 ast_config_destroy(res);
3818 res = NULL;
3819 }
3820 break;
3821 }
3822 } else {
3823 break;
3824 }
3825 }
3826
3827 return res;
3828 }
3829
3830 struct ast_config *ast_load_realtime_multientry(const char *family, ...)
3831 {
3832 RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
3833 va_list ap;
3834
3835 va_start(ap, family);
3836 realtime_arguments_to_fields(ap, &fields);
3837 va_end(ap);
3838
3839 if (!fields) {
3840 return NULL;
3841 }
3842
3843 return ast_load_realtime_multientry_fields(family, fields);
3844 }
3845
3846 int ast_update_realtime_fields(const char *family, const char *keyfield, const char *lookup, const struct ast_variable *fields)
3847 {
3848 struct ast_config_engine *eng;
3849 int res = -1, i;
3850 char db[256];
3851 char table[256];
3852
3853 for (i = 1; ; i++) {
3854 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3855 /* If the update succeeds, it returns >= 0. */
3856 if (eng->update_func && ((res = eng->update_func(db, table, keyfield, lookup, fields)) >= 0)) {
3857 break;
3858 }
3859 } else {
3860 break;
3861 }
3862 }
3863
3864 return res;
3865 }
3866
3867 int ast_update_realtime(const char *family, const char *keyfield, const char *lookup, ...)
3868 {
3869 RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
3870 va_list ap;
3871
3872 va_start(ap, lookup);
3873 realtime_arguments_to_fields(ap, &fields);
3874 va_end(ap);
3875
3876 if (!fields) {
3877 return -1;
3878 }
3879
3880 return ast_update_realtime_fields(family, keyfield, lookup, fields);
3881 }
3882
3883 int ast_update2_realtime_fields(const char *family, const struct ast_variable *lookup_fields, const struct ast_variable *update_fields)
3884 {
3885 struct ast_config_engine *eng;
3886 int res = -1, i;
3887 char db[256];
3888 char table[256];
3889
3890 for (i = 1; ; i++) {
3891 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3892 if (eng->update2_func && !(res = eng->update2_func(db, table, lookup_fields, update_fields))) {
3893 break;
3894 }
3895 } else {
3896 break;
3897 }
3898 }
3899
3900 return res;
3901 }
3902
3903 int ast_update2_realtime(const char *family, ...)
3904 {
3905 RAII_VAR(struct ast_variable *, lookup_fields, NULL, ast_variables_destroy);
3906 RAII_VAR(struct ast_variable *, update_fields, NULL, ast_variables_destroy);
3907 va_list ap;
3908
3909 va_start(ap, family);
3910 /* XXX: If we wanted to pass no lookup fields (select all), we'd be
3911 * out of luck. realtime_arguments_to_fields expects at least one key
3912 * value pair. */
3913 realtime_arguments_to_fields(ap, &lookup_fields);
3914 va_end(ap);
3915
3916 va_start(ap, family);
3917 realtime_arguments_to_fields2(ap, 1, &update_fields);
3918 va_end(ap);
3919
3920 if (!lookup_fields || !update_fields) {
3921 return -1;
3922 }
3923
3924 return ast_update2_realtime_fields(family, lookup_fields, update_fields);
3925 }
3926
3927 int ast_store_realtime_fields(const char *family, const struct ast_variable *fields)
3928 {
3929 struct ast_config_engine *eng;
3930 int res = -1, i;
3931 char db[256];
3932 char table[256];
3933
3934 for (i = 1; ; i++) {
3935 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3936 /* If the store succeeds, it returns >= 0*/
3937 if (eng->store_func && ((res = eng->store_func(db, table, fields)) >= 0)) {
3938 break;
3939 }
3940 } else {
3941 break;
3942 }
3943 }
3944
3945 return res;
3946 }
3947
3948 int ast_store_realtime(const char *family, ...)
3949 {
3950 RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
3951 va_list ap;
3952
3953 va_start(ap, family);
3954 realtime_arguments_to_fields(ap, &fields);
3955 va_end(ap);
3956
3957 if (!fields) {
3958 return -1;
3959 }
3960
3961 return ast_store_realtime_fields(family, fields);
3962 }
3963
3964 int ast_destroy_realtime_fields(const char *family, const char *keyfield, const char *lookup, const struct ast_variable *fields)
3965 {
3966 struct ast_config_engine *eng;
3967 int res = -1, i;
3968 char db[256];
3969 char table[256];
3970
3971 for (i = 1; ; i++) {
3972 if ((eng = find_engine(family, i, db, sizeof(db), table, sizeof(table)))) {
3973 if (eng->destroy_func && ((res = eng->destroy_func(db, table, keyfield, lookup, fields)) >= 0)) {
3974 break;
3975 }
3976 } else {
3977 break;
3978 }
3979 }
3980
3981 return res;
3982 }
3983
3984 int ast_destroy_realtime(const char *family, const char *keyfield, const char *lookup, ...)
3985 {
3986 RAII_VAR(struct ast_variable *, fields, NULL, ast_variables_destroy);
3987 int res = 0;
3988 va_list ap;
3989
3990 va_start(ap, lookup);
3991 if (realtime_arguments_to_fields(ap, &fields)) {
3992 res = -1;
3993 }
3994 va_end(ap);
3995
3996 if (res) {
3997 return -1;
3998 }
3999
4000 return ast_destroy_realtime_fields(family, keyfield, lookup, fields);
4001 }
4002
4003 char *ast_realtime_decode_chunk(char *chunk)
4004 {
4005 char *orig = chunk;
4006 for (; *chunk; chunk++) {
4007 if (*chunk == '^' && strchr("0123456789ABCDEFabcdef", chunk[1]) && strchr("0123456789ABCDEFabcdef", chunk[2])) {
4008 sscanf(chunk + 1, "%02hhX", (unsigned char *)chunk);
4009 memmove(chunk + 1, chunk + 3, strlen(chunk + 3) + 1);
4010 }
4011 }
4012 return orig;
4013 }
4014
4015 char *ast_realtime_encode_chunk(struct ast_str **dest, ssize_t maxlen, const char *chunk)
4016 {
4017 if (!strchr(chunk, ';') && !strchr(chunk, '^')) {
4018 ast_str_set(dest, maxlen, "%s", chunk);
4019 } else {
4020 ast_str_reset(*dest);
4021 for (; *chunk; chunk++) {
4022 if (strchr(";^", *chunk)) {
4023 ast_str_append(dest, maxlen, "^%02hhX", *chunk);
4024 } else {
4025 ast_str_append(dest, maxlen, "%c", *chunk);
4026 }
4027 }
4028 }
4029 return ast_str_buffer(*dest);
4030 }
4031
4032 /*! \brief Helper function to parse arguments
4033 * See documentation in config.h
4034 */
4035 int ast_parse_arg(const char *arg, enum ast_parse_flags flags,
4036 void *p_result, ...)
4037 {
4038 va_list ap;
4039 int error = 0;
4040
4041 va_start(ap, p_result);
4042 switch (flags & PARSE_TYPE) {
4043 case PARSE_INT32:
4044 {
4045 long int x = 0;
4046 int32_t *result = p_result;
4047 int32_t def = result ? *result : 0, high = INT32_MAX, low = INT32_MIN;
4048 char *endptr = NULL;
4049
4050 /* optional arguments: default value and/or (low, high) */
4051 if (flags & PARSE_DEFAULT) {
4052 def = va_arg(ap, int32_t);
4053 }
4054 if (flags & (PARSE_IN_RANGE | PARSE_OUT_RANGE)) {
4055 low = va_arg(ap, int32_t);
4056 high = va_arg(ap, int32_t);
4057 }
4058 if (ast_strlen_zero(arg)) {
4059 error = 1;
4060 goto int32_done;
4061 }
4062 errno = 0;
4063 x = strtol(arg, &endptr, 0);
4064 if (*endptr || errno || x < INT32_MIN || x > INT32_MAX) {
4065 /* Parse error, or type out of int32_t bounds */
4066 error = 1;
4067 goto int32_done;
4068 }
4069 error = (x < low) || (x > high);
4070 if (flags & PARSE_RANGE_DEFAULTS) {
4071 if (x < low) {
4072 def = low;
4073 } else if (x > high) {
4074 def = high;
4075 }
4076 }
4077 if (flags & PARSE_OUT_RANGE) {
4078 error = !error;
4079 }
4080 int32_done:
4081 if (result) {
4082 *result = error ? def : x;
4083 }
4084
4085 ast_debug(3, "extract int from [%s] in [%d, %d] gives [%ld](%d)\n",
4086 arg, low, high, result ? *result : x, error);
4087 break;
4088 }
4089
4090 case PARSE_UINT32:
4091 {
4092 unsigned long int x = 0;
4093 uint32_t *result = p_result;
4094 uint32_t def = result ? *result : 0, low = 0, high = UINT32_MAX;
4095 char *endptr = NULL;
4096
4097 /* optional argument: first default value, then range */
4098 if (flags & PARSE_DEFAULT) {
4099 def = va_arg(ap, uint32_t);
4100 }
4101 if (flags & (PARSE_IN_RANGE|PARSE_OUT_RANGE)) {
4102 /* range requested, update bounds */
4103 low = va_arg(ap, uint32_t);
4104 high = va_arg(ap, uint32_t);
4105 }
4106
4107 if (ast_strlen_zero(arg)) {
4108 error = 1;
4109 goto uint32_done;
4110 }
4111 /* strtoul will happily and silently negate negative numbers */
4112 arg = ast_skip_blanks(arg);
4113 if (*arg == '-') {
4114 error = 1;
4115 goto uint32_done;
4116 }
4117 errno = 0;
4118 x = strtoul(arg, &endptr, 0);
4119 if (*endptr || errno || x > UINT32_MAX) {
4120 error = 1;
4121 goto uint32_done;
4122 }
4123 error = (x < low) || (x > high);
4124 if (flags & PARSE_RANGE_DEFAULTS) {
4125 if (x < low) {
4126 def = low;
4127 } else if (x > high) {
4128 def = high;
4129 }
4130 }
4131 if (flags & PARSE_OUT_RANGE) {
4132 error = !error;
4133 }
4134 uint32_done:
4135 if (result) {
4136 *result = error ? def : x;
4137 }
4138 ast_debug(3, "extract uint from [%s] in [%u, %u] gives [%lu](%d)\n",
4139 arg, low, high, result ? *result : x, error);
4140 break;
4141 }
4142
4143 case PARSE_TIMELEN:
4144 {
4145 int x = 0;
4146 int *result = p_result;
4147 int def = result ? *result : 0;
4148 int high = INT_MAX;
4149 int low = INT_MIN;
4150 enum ast_timelen defunit;
4151
4152 defunit = va_arg(ap, enum ast_timelen);
4153 /* optional arguments: default value and/or (low, high) */
4154 if (flags & PARSE_DEFAULT) {
4155 def = va_arg(ap, int);
4156 }
4157 if (flags & (PARSE_IN_RANGE | PARSE_OUT_RANGE)) {
4158 low = va_arg(ap, int);
4159 high = va_arg(ap, int);
4160 }
4161 if (ast_strlen_zero(arg)) {
4162 error = 1;
4163 goto timelen_done;
4164 }
4165 error = ast_app_parse_timelen(arg, &x, defunit);
4166 if (error || x < INT_MIN || x > INT_MAX) {
4167 /* Parse error, or type out of int bounds */
4168 error = 1;
4169 goto timelen_done;
4170 }
4171 error = (x < low) || (x > high);
4172 if (flags & PARSE_RANGE_DEFAULTS) {
4173 if (x < low) {
4174 def = low;
4175 } else if (x > high) {
4176 def = high;
4177 }
4178 }
4179 if (flags & PARSE_OUT_RANGE) {
4180 error = !error;
4181 }
4182 timelen_done:
4183 if (result) {
4184 *result = error ? def : x;
4185 }
4186
4187 ast_debug(3, "extract timelen from [%s] in [%d, %d] gives [%d](%d)\n",
4188 arg, low, high, result ? *result : x, error);
4189 break;
4190 }
4191
4192 case PARSE_DOUBLE:
4193 {
4194 double *result = p_result;
4195 double x = 0, def = result ? *result : 0, low = -HUGE_VAL, high = HUGE_VAL;
4196 char *endptr = NULL;
4197
4198 /* optional argument: first default value, then range */
4199 if (flags & PARSE_DEFAULT) {
4200 def = va_arg(ap, double);
4201 }
4202 if (flags & (PARSE_IN_RANGE | PARSE_OUT_RANGE)) {
4203 /* range requested, update bounds */
4204 low = va_arg(ap, double);
4205 high = va_arg(ap, double);
4206 }
4207 if (ast_strlen_zero(arg)) {
4208 error = 1;
4209 goto double_done;
4210 }
4211 errno = 0;
4212 x = strtod(arg, &endptr);
4213 if (*endptr || errno == ERANGE) {
4214 error = 1;
4215 goto double_done;
4216 }
4217 error = (x < low) || (x > high);
4218 if (flags & PARSE_OUT_RANGE) {
4219 error = !error;
4220 }
4221 double_done:
4222 if (result) {
4223 *result = error ? def : x;
4224 }
4225 ast_debug(3, "extract double from [%s] in [%f, %f] gives [%f](%d)\n",
4226 arg, low, high, result ? *result : x, error);
4227 break;
4228 }
4229 case PARSE_ADDR:
4230 {
4231 struct ast_sockaddr *addr = (struct ast_sockaddr *)p_result;
4232
4233 if (!ast_sockaddr_parse(addr, arg, flags & PARSE_PORT_MASK)) {
4234 error = 1;
4235 }
4236
4237 ast_debug(3, "extract addr from %s gives %s(%d)\n",
4238 arg, ast_sockaddr_stringify(addr), error);
4239
4240 break;
4241 }
4242 case PARSE_INADDR: /* TODO Remove this (use PARSE_ADDR instead). */
4243 {
4244 char *port, *buf;
4245 struct sockaddr_in _sa_buf; /* buffer for the result */
4246 struct sockaddr_in *sa = p_result ?
4247 (struct sockaddr_in *)p_result : &_sa_buf;
4248 /* default is either the supplied value or the result itself */
4249 struct sockaddr_in *def = (flags & PARSE_DEFAULT) ?
4250 va_arg(ap, struct sockaddr_in *) : sa;
4251 struct ast_sockaddr addr = { {0,} };
4252
4253 memset(&_sa_buf, '\0', sizeof(_sa_buf)); /* clear buffer */
4254 /* duplicate the string to strip away the :port */
4255 port = ast_strdupa(arg);
4256 buf = strsep(&port, ":");
4257 sa->sin_family = AF_INET; /* assign family */
4258 /*
4259 * honor the ports flag setting, assign default value
4260 * in case of errors or field unset.
4261 */
4262 flags &= PARSE_PORT_MASK; /* the only flags left to process */
4263 if (port) {
4264 if (flags == PARSE_PORT_FORBID) {
4265 error = 1; /* port was forbidden */
4266 sa->sin_port = def->sin_port;
4267 } else if (flags == PARSE_PORT_IGNORE)
4268 sa->sin_port = def->sin_port;
4269 else /* accept or require */
4270 sa->sin_port = htons(strtol(port, NULL, 0));
4271 } else {
4272 sa->sin_port = def->sin_port;
4273 if (flags == PARSE_PORT_REQUIRE)
4274 error = 1;
4275 }
4276 /* Now deal with host part, even if we have errors before. */
4277 if (ast_sockaddr_resolve_first_af(&addr, buf, PARSE_PORT_FORBID, AF_INET)) {
4278 error = 1;
4279 sa->sin_addr = def->sin_addr;
4280 } else {
4281 struct sockaddr_in tmp;
4282 ast_sockaddr_to_sin(&addr, &tmp);
4283 sa->sin_addr = tmp.sin_addr;
4284 }
4285 ast_debug(3,
4286 "extract inaddr from [%s] gives [%s:%d](%d)\n",
4287 arg, ast_inet_ntoa(sa->sin_addr),
4288 ntohs(sa->sin_port), error);
4289 break;
4290 }
4291 }
4292 va_end(ap);
4293 return error;
4294 }
4295
4296 static char *handle_cli_core_show_config_mappings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4297 {
4298 struct ast_config_engine *eng;
4299 struct ast_config_map *map;
4300
4301 switch (cmd) {
4302 case CLI_INIT:
4303 e->command = "core show config mappings";
4304 e->usage =
4305 "Usage: core show config mappings\n"
4306 " Shows the filenames to config engines.\n";
4307 return NULL;
4308 case CLI_GENERATE:
4309 return NULL;
4310 }
4311
4312 {
4313 SCOPED_MUTEX(lock, &config_lock);
4314
4315 if (!config_engine_list) {
4316 ast_cli(a->fd, "No config mappings found.\n");
4317 } else {
4318 for (eng = config_engine_list; eng; eng = eng->next) {
4319 ast_cli(a->fd, "Config Engine: %s\n", eng->name);
4320 for (map = config_maps; map; map = map->next) {
4321 if (!strcasecmp(map->driver, eng->name)) {
4322 ast_cli(a->fd, "===> %s (db=%s, table=%s)\n", map->name, map->database,
4323 map->table ? map->table : map->name);
4324 }
4325 }
4326 }
4327 }
4328 }
4329
4330 return CLI_SUCCESS;
4331 }
4332
4333 static char *handle_cli_config_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4334 {
4335 struct cache_file_mtime *cfmtime;
4336 char *prev = "";
4337 int wordlen;
4338
4339 switch (cmd) {
4340 case CLI_INIT:
4341 e->command = "config reload";
4342 e->usage =
4343 "Usage: config reload <filename.conf>\n"
4344 " Reloads all modules that reference <filename.conf>\n";
4345 return NULL;
4346 case CLI_GENERATE:
4347 if (a->pos > 2) {
4348 return NULL;
4349 }
4350
4351 wordlen = strlen(a->word);
4352
4353 AST_LIST_LOCK(&cfmtime_head);
4354 AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
4355 /* Core configs cannot be reloaded */
4356 if (ast_strlen_zero(cfmtime->who_asked)) {
4357 continue;
4358 }
4359
4360 /* Skip duplicates - this only works because the list is sorted by filename */
4361 if (!strcmp(cfmtime->filename, prev)) {
4362 continue;
4363 }
4364
4365 if (!strncmp(cfmtime->filename, a->word, wordlen)) {
4366 if (ast_cli_completion_add(ast_strdup(cfmtime->filename))) {
4367 break;
4368 }
4369 }
4370
4371 /* Otherwise save that we've seen this filename */
4372 prev = cfmtime->filename;
4373 }
4374 AST_LIST_UNLOCK(&cfmtime_head);
4375
4376 return NULL;
4377 }
4378
4379 if (a->argc != 3) {
4380 return CLI_SHOWUSAGE;
4381 }
4382
4383 AST_LIST_LOCK(&cfmtime_head);
4384 AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
4385 if (!strcmp(cfmtime->filename, a->argv[2])) {
4386 char *buf = ast_alloca(strlen("module reload ") + strlen(cfmtime->who_asked) + 1);
4387 sprintf(buf, "module reload %s", cfmtime->who_asked);
4388 ast_cli_command(a->fd, buf);
4389 }
4390 }
4391 AST_LIST_UNLOCK(&cfmtime_head);
4392
4393 return CLI_SUCCESS;
4394 }
4395
4396 static char *handle_cli_config_list(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
4397 {
4398 struct cache_file_mtime *cfmtime;
4399
4400 switch (cmd) {
4401 case CLI_INIT:
4402 e->command = "config list";
4403 e->usage =
4404 "Usage: config list\n"
4405 " Show all modules that have loaded a configuration file\n";
4406 return NULL;
4407 case CLI_GENERATE:
4408 return NULL;
4409 }
4410
4411 AST_LIST_LOCK(&cfmtime_head);
4412 AST_LIST_TRAVERSE(&cfmtime_head, cfmtime, list) {
4413 ast_cli(a->fd, "%-20.20s %-50s\n", S_OR(cfmtime->who_asked, "core"), cfmtime->filename);
4414 }
4415 AST_LIST_UNLOCK(&cfmtime_head);
4416
4417 return CLI_SUCCESS;
4418 }
4419
4420 static struct ast_cli_entry cli_config[] = {
4421 AST_CLI_DEFINE(handle_cli_core_show_config_mappings, "Display config mappings (file names to config engines)"),
4422 AST_CLI_DEFINE(handle_cli_config_reload, "Force a reload on modules using a particular configuration file"),
4423 AST_CLI_DEFINE(handle_cli_config_list, "Show all files that have loaded a configuration file"),
4424 };
4425
4426 static void config_shutdown(void)
4427 {
4428 struct cache_file_mtime *cfmtime;
4429
4430 AST_LIST_LOCK(&cfmtime_head);
4431 while ((cfmtime = AST_LIST_REMOVE_HEAD(&cfmtime_head, list))) {
4432 config_cache_destroy_entry(cfmtime);
4433 }
4434 AST_LIST_UNLOCK(&cfmtime_head);
4435
4436 ast_cli_unregister_multiple(cli_config, ARRAY_LEN(cli_config));
4437
4438 clear_config_maps();
4439
4440 ao2_cleanup(cfg_hooks);
4441 cfg_hooks = NULL;
4442 }
4443
4444 int register_config_cli(void)
4445 {
4446 ast_cli_register_multiple(cli_config, ARRAY_LEN(cli_config));
4447 /* This is separate from the module load so cleanup can happen very late. */
4448 ast_register_cleanup(config_shutdown);
4449 return 0;
4450 }
4451
4452 struct cfg_hook {
4453 const char *name;
4454 const char *filename;
4455 const char *module;
4456 config_hook_cb hook_cb;
4457 };
4458
4459 static void hook_destroy(void *obj)
4460 {
4461 struct cfg_hook *hook = obj;
4462 ast_free((void *) hook->name);
4463 ast_free((void *) hook->filename);
4464 ast_free((void *) hook->module);
4465 }
4466
4467 static int hook_cmp(void *obj, void *arg, int flags)
4468 {
4469 struct cfg_hook *hook1 = obj;
4470 struct cfg_hook *hook2 = arg;
4471
4472 return !(strcasecmp(hook1->name, hook2->name)) ? CMP_MATCH | CMP_STOP : 0;
4473 }
4474
4475 static int hook_hash(const void *obj, const int flags)
4476 {
4477 const struct cfg_hook *hook = obj;
4478
4479 return ast_str_hash(hook->name);
4480 }
4481
4482 void ast_config_hook_unregister(const char *name)
4483 {
4484 struct cfg_hook tmp;
4485
4486 tmp.name = ast_strdupa(name);
4487
4488 ao2_find(cfg_hooks, &tmp, OBJ_POINTER | OBJ_UNLINK | OBJ_NODATA);
4489 }
4490
4491 static void config_hook_exec(const char *filename, const char *module, const struct ast_config *cfg)
4492 {
4493 struct ao2_iterator it;
4494 struct cfg_hook *hook;
4495 if (!(cfg_hooks)) {
4496 return;
4497 }
4498 it = ao2_iterator_init(cfg_hooks, 0);
4499 while ((hook = ao2_iterator_next(&it))) {
4500 if (!strcasecmp(hook->filename, filename) &&
4501 !strcasecmp(hook->module, module)) {
4502 struct ast_config *copy = ast_config_copy(cfg);
4503 hook->hook_cb(copy);
4504 }
4505 ao2_ref(hook, -1);
4506 }
4507 ao2_iterator_destroy(&it);
4508 }
4509
4510 int ast_config_hook_register(const char *name,
4511 const char *filename,
4512 const char *module,
4513 enum config_hook_flags flags,
4514 config_hook_cb hook_cb)
4515 {
4516 struct cfg_hook *hook;
4517 if (!cfg_hooks) {
4518 cfg_hooks = ao2_container_alloc_hash(AO2_ALLOC_OPT_LOCK_MUTEX, 0, 17,
4519 hook_hash, NULL, hook_cmp);
4520 if (!cfg_hooks) {
4521 return -1;
4522 }
4523 }
4524
4525 if (!(hook = ao2_alloc(sizeof(*hook), hook_destroy))) {
4526 return -1;
4527 }
4528
4529 hook->hook_cb = hook_cb;
4530 hook->filename = ast_strdup(filename);
4531 hook->name = ast_strdup(name);
4532 hook->module = ast_strdup(module);
4533
4534 ao2_link(cfg_hooks, hook);
4535 ao2_ref(hook, -1);
4536 return 0;
4537 }
4538
4539 static int unload_module(void)
4540 {
4541 return 0;
4542 }
4543
4544 static int load_module(void)
4545 {
4546 if (ast_opt_console) {
4547 ast_verb(0, "[ Initializing Custom Configuration Options ]\n");
4548 }
4549
4550 return reload_module() ? AST_MODULE_LOAD_FAILURE : AST_MODULE_LOAD_SUCCESS;
4551 }
4552
4553 /* This module explicitly loads before realtime drivers. */
4554 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS | AST_MODFLAG_LOAD_ORDER, "Configuration",
4555 .support_level = AST_MODULE_SUPPORT_CORE,
4556 .load = load_module,
4557 .unload = unload_module,
4558 .reload = reload_module,
4559 .load_pri = 0,
4560 );