This solves bug 8342, whereby a crash occurs under certain circumstances while readin...
[asterisk/asterisk.git] / main / config.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
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 <markster@digium.com>
24  *
25  * Includes the Asterisk Realtime API - ARA
26  * See doc/realtime.txt and doc/extconfig.txt
27  */
28
29 #include "asterisk.h"
30
31 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
32
33 #include <stdio.h>
34 #include <unistd.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <errno.h>
38 #include <time.h>
39 #include <sys/stat.h>
40 #define AST_INCLUDE_GLOB 1
41 #ifdef AST_INCLUDE_GLOB
42 #if defined(__Darwin__) || defined(__CYGWIN__)
43 #define GLOB_ABORTED GLOB_ABEND
44 #endif
45 # include <glob.h>
46 #endif
47
48 #include "asterisk/config.h"
49 #include "asterisk/cli.h"
50 #include "asterisk/lock.h"
51 #include "asterisk/options.h"
52 #include "asterisk/logger.h"
53 #include "asterisk/utils.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/app.h"
56
57 #define MAX_NESTED_COMMENTS 128
58 #define COMMENT_START ";--"
59 #define COMMENT_END "--;"
60 #define COMMENT_META ';'
61 #define COMMENT_TAG '-'
62
63 static char *extconfig_conf = "extconfig.conf";
64
65 /*! Growable string buffer */
66 static char *comment_buffer;   /*!< this will be a comment collector.*/
67 static int   comment_buffer_size;  /*!< the amount of storage so far alloc'd for the comment_buffer */
68
69 static char *lline_buffer;    /*!< A buffer for stuff behind the ; */
70 static int  lline_buffer_size;
71
72
73 struct ast_comment {
74         struct ast_comment *next;
75         char cmt[0];
76 };
77
78 #define CB_INCR 250
79
80 static void CB_INIT(void)
81 {
82         if (!comment_buffer) {
83                 comment_buffer = ast_malloc(CB_INCR);
84                 if (!comment_buffer)
85                         return;
86                 comment_buffer[0] = 0;
87                 comment_buffer_size = CB_INCR;
88                 lline_buffer = ast_malloc(CB_INCR);
89                 lline_buffer[0] = 0;
90                 lline_buffer_size = CB_INCR;
91         } else {
92                 comment_buffer[0] = 0;
93                 lline_buffer[0] = 0;
94         }
95 }
96
97 static void  CB_ADD(char *str)
98 {
99         int rem = comment_buffer_size - strlen(comment_buffer) - 1;
100         int siz = strlen(str);
101         if (rem < siz+1) {
102                 comment_buffer = ast_realloc(comment_buffer, comment_buffer_size + CB_INCR + siz + 1);
103                 if (!comment_buffer)
104                         return;
105                 comment_buffer_size += CB_INCR+siz+1;
106         }
107         strcat(comment_buffer,str);
108 }
109
110 static void  CB_ADD_LEN(char *str, int len)
111 {
112         int cbl = strlen(comment_buffer) + 1;
113         int rem = comment_buffer_size - cbl;
114         if (rem < len+1) {
115                 comment_buffer = ast_realloc(comment_buffer, comment_buffer_size + CB_INCR + len + 1);
116                 if (!comment_buffer)
117                         return;
118                 comment_buffer_size += CB_INCR+len+1;
119         }
120         strncat(comment_buffer,str,len);
121         comment_buffer[cbl+len-1] = 0;
122 }
123
124 static void  LLB_ADD(char *str)
125 {
126         int rem = lline_buffer_size - strlen(lline_buffer) - 1;
127         int siz = strlen(str);
128         if (rem < siz+1) {
129                 lline_buffer = ast_realloc(lline_buffer, lline_buffer_size + CB_INCR + siz + 1);
130                 if (!lline_buffer)
131                         return;
132                 lline_buffer_size += CB_INCR + siz + 1;
133         }
134         strcat(lline_buffer,str);
135 }
136
137 static void CB_RESET(void )  
138
139         comment_buffer[0] = 0; 
140         lline_buffer[0] = 0;
141 }
142                 
143
144
145 static struct ast_comment *ALLOC_COMMENT(const char *buffer)
146
147         struct ast_comment *x = ast_calloc(1,sizeof(struct ast_comment)+strlen(buffer)+1);
148         strcpy(x->cmt, buffer);
149         return x;
150 }
151
152
153 static struct ast_config_map {
154         struct ast_config_map *next;
155         char *name;
156         char *driver;
157         char *database;
158         char *table;
159         char stuff[0];
160 } *config_maps = NULL;
161
162 AST_MUTEX_DEFINE_STATIC(config_lock);
163 static struct ast_config_engine *config_engine_list;
164
165 #define MAX_INCLUDE_LEVEL 10
166
167 struct ast_category {
168         char name[80];
169         int ignored;                    /*!< do not let user of the config see this category */
170         struct ast_comment *precomments;
171         struct ast_comment *sameline;
172         struct ast_variable *root;
173         struct ast_variable *last;
174         struct ast_category *next;
175 };
176
177 struct ast_config {
178         struct ast_category *root;
179         struct ast_category *last;
180         struct ast_category *current;
181         struct ast_category *last_browse;               /*!< used to cache the last category supplied via category_browse */
182         int include_level;
183         int max_include_level;
184 };
185
186 struct ast_variable *ast_variable_new(const char *name, const char *value) 
187 {
188         struct ast_variable *variable;
189         int name_len = strlen(name) + 1;        
190
191         if ((variable = ast_calloc(1, name_len + strlen(value) + 1 + sizeof(*variable)))) {
192                 variable->name = variable->stuff;
193                 variable->value = variable->stuff + name_len;           
194                 strcpy(variable->name,name);
195                 strcpy(variable->value,value);
196         }
197
198         return variable;
199 }
200
201 void ast_variable_append(struct ast_category *category, struct ast_variable *variable)
202 {
203         if (!variable)
204                 return;
205         if (category->last)
206                 category->last->next = variable;
207         else
208                 category->root = variable;
209         category->last = variable;
210 }
211
212 void ast_variables_destroy(struct ast_variable *v)
213 {
214         struct ast_variable *vn;
215
216         while(v) {
217                 vn = v;
218                 v = v->next;
219                 free(vn);
220         }
221 }
222
223 struct ast_variable *ast_variable_browse(const struct ast_config *config, const char *category)
224 {
225         struct ast_category *cat = NULL;
226
227         if (category && config->last_browse && (config->last_browse->name == category))
228                 cat = config->last_browse;
229         else
230                 cat = ast_category_get(config, category);
231
232         return (cat) ? cat->root : NULL;
233 }
234
235 const char *ast_config_option(struct ast_config *cfg, const char *cat, const char *var)
236 {
237         const char *tmp;
238         tmp = ast_variable_retrieve(cfg, cat, var);
239         if (!tmp)
240                 tmp = ast_variable_retrieve(cfg, "general", var);
241         return tmp;
242 }
243
244
245 const char *ast_variable_retrieve(const struct ast_config *config, const char *category, const char *variable)
246 {
247         struct ast_variable *v;
248
249         if (category) {
250                 for (v = ast_variable_browse(config, category); v; v = v->next) {
251                         if (!strcasecmp(variable, v->name))
252                                 return v->value;
253                 }
254         } else {
255                 struct ast_category *cat;
256
257                 for (cat = config->root; cat; cat = cat->next)
258                         for (v = cat->root; v; v = v->next)
259                                 if (!strcasecmp(variable, v->name))
260                                         return v->value;
261         }
262
263         return NULL;
264 }
265
266 static struct ast_variable *variable_clone(const struct ast_variable *old)
267 {
268         struct ast_variable *new = ast_variable_new(old->name, old->value);
269
270         if (new) {
271                 new->lineno = old->lineno;
272                 new->object = old->object;
273                 new->blanklines = old->blanklines;
274                 /* TODO: clone comments? */
275         }
276
277         return new;
278 }
279  
280 static void move_variables(struct ast_category *old, struct ast_category *new)
281 {
282         struct ast_variable *var = old->root;
283         old->root = NULL;
284 #if 1
285         /* we can just move the entire list in a single op */
286         ast_variable_append(new, var);
287 #else
288         while (var) {
289                 struct ast_variable *next = var->next;
290                 var->next = NULL;
291                 ast_variable_append(new, var);
292                 var = next;
293         }
294 #endif
295 }
296
297 struct ast_category *ast_category_new(const char *name) 
298 {
299         struct ast_category *category;
300
301         if ((category = ast_calloc(1, sizeof(*category))))
302                 ast_copy_string(category->name, name, sizeof(category->name));
303         return category;
304 }
305
306 static struct ast_category *category_get(const struct ast_config *config, const char *category_name, int ignored)
307 {
308         struct ast_category *cat;
309
310         /* try exact match first, then case-insensitive match */
311         for (cat = config->root; cat; cat = cat->next) {
312                 if (cat->name == category_name && (ignored || !cat->ignored))
313                         return cat;
314         }
315
316         for (cat = config->root; cat; cat = cat->next) {
317                 if (!strcasecmp(cat->name, category_name) && (ignored || !cat->ignored))
318                         return cat;
319         }
320
321         return NULL;
322 }
323
324 struct ast_category *ast_category_get(const struct ast_config *config, const char *category_name)
325 {
326         return category_get(config, category_name, 0);
327 }
328
329 int ast_category_exist(const struct ast_config *config, const char *category_name)
330 {
331         return !!ast_category_get(config, category_name);
332 }
333
334 void ast_category_append(struct ast_config *config, struct ast_category *category)
335 {
336         if (config->last)
337                 config->last->next = category;
338         else
339                 config->root = category;
340         config->last = category;
341         config->current = category;
342 }
343
344 void ast_category_destroy(struct ast_category *cat)
345 {
346         ast_variables_destroy(cat->root);
347         free(cat);
348 }
349
350 static struct ast_category *next_available_category(struct ast_category *cat)
351 {
352         for (; cat && cat->ignored; cat = cat->next);
353
354         return cat;
355 }
356
357 char *ast_category_browse(struct ast_config *config, const char *prev)
358 {       
359         struct ast_category *cat = NULL;
360
361         if (prev && config->last_browse && (config->last_browse->name == prev))
362                 cat = config->last_browse->next;
363         else if (!prev && config->root)
364                 cat = config->root;
365         else if (prev) {
366                 for (cat = config->root; cat; cat = cat->next) {
367                         if (cat->name == prev) {
368                                 cat = cat->next;
369                                 break;
370                         }
371                 }
372                 if (!cat) {
373                         for (cat = config->root; cat; cat = cat->next) {
374                                 if (!strcasecmp(cat->name, prev)) {
375                                         cat = cat->next;
376                                         break;
377                                 }
378                         }
379                 }
380         }
381         
382         if (cat)
383                 cat = next_available_category(cat);
384
385         config->last_browse = cat;
386         return (cat) ? cat->name : NULL;
387 }
388
389 struct ast_variable *ast_category_detach_variables(struct ast_category *cat)
390 {
391         struct ast_variable *v;
392
393         v = cat->root;
394         cat->root = NULL;
395
396         return v;
397 }
398
399 void ast_category_rename(struct ast_category *cat, const char *name)
400 {
401         ast_copy_string(cat->name, name, sizeof(cat->name));
402 }
403
404 static void inherit_category(struct ast_category *new, const struct ast_category *base)
405 {
406         struct ast_variable *var;
407
408         for (var = base->root; var; var = var->next)
409                 ast_variable_append(new, variable_clone(var));
410 }
411
412 struct ast_config *ast_config_new(void) 
413 {
414         struct ast_config *config;
415
416         if ((config = ast_calloc(1, sizeof(*config))))
417                 config->max_include_level = MAX_INCLUDE_LEVEL;
418         return config;
419 }
420
421 int ast_variable_delete(struct ast_category *category, char *variable, char *match)
422 {
423         struct ast_variable *cur, *prev=NULL, *curn;
424         int res = -1;
425         cur = category->root;
426         while (cur) {
427                 if (cur->name == variable) {
428                         if (prev) {
429                                 prev->next = cur->next;
430                                 if (cur == category->last)
431                                         category->last = prev;
432                         } else {
433                                 category->root = cur->next;
434                                 if (cur == category->last)
435                                         category->last = NULL;
436                         }
437                         cur->next = NULL;
438                         ast_variables_destroy(cur);
439                         return 0;
440                 }
441                 prev = cur;
442                 cur = cur->next;
443         }
444
445         prev = NULL;
446         cur = category->root;
447         while (cur) {
448                 curn = cur->next;
449                 if (!strcasecmp(cur->name, variable) && (ast_strlen_zero(match) || !strcasecmp(cur->value, match))) {
450                         if (prev) {
451                                 prev->next = cur->next;
452                                 if (cur == category->last)
453                                         category->last = prev;
454                         } else {
455                                 category->root = cur->next;
456                                 if (cur == category->last)
457                                         category->last = NULL;
458                         }
459                         cur->next = NULL;
460                         ast_variables_destroy(cur);
461                         res = 0;
462                 } else
463                         prev = cur;
464
465                 cur = curn;
466         }
467         return res;
468 }
469
470 int ast_variable_update(struct ast_category *category, char *variable, char *value, char *match)
471 {
472         struct ast_variable *cur, *prev=NULL, *newer;
473         newer = ast_variable_new(variable, value);
474         if (!newer)
475                 return -1;
476         cur = category->root;
477         while (cur) {
478                 if (cur->name == variable) {
479                         newer->next = cur->next;
480                         newer->object = cur->object;
481                         if (prev)
482                                 prev->next = newer;
483                         else
484                                 category->root = newer;
485                         if (category->last == cur)
486                                 category->last = newer;
487                         cur->next = NULL;
488                         ast_variables_destroy(cur);
489                         return 0;
490                 }
491                 prev = cur;
492                 cur = cur->next;
493         }
494
495         prev = NULL;
496         cur = category->root;
497         while (cur) {
498                 if (!strcasecmp(cur->name, variable) && (ast_strlen_zero(match) || !strcasecmp(cur->value, match))) {
499                         newer->next = cur->next;
500                         newer->object = cur->object;
501                         if (prev)
502                                 prev->next = newer;
503                         else
504                                 category->root = newer;
505                         if (category->last == cur)
506                                 category->last = newer;
507                         cur->next = NULL;
508                         ast_variables_destroy(cur);
509                         return 0;
510                 }
511                 prev = cur;
512                 cur = cur->next;
513         }
514         if (prev)
515                 prev->next = newer;
516         else
517                 category->root = newer;
518         return 0;
519 }
520
521 int ast_category_delete(struct ast_config *cfg, char *category)
522 {
523         struct ast_category *prev=NULL, *cat;
524         cat = cfg->root;
525         while(cat) {
526                 if (cat->name == category) {
527                         ast_variables_destroy(cat->root);
528                         if (prev) {
529                                 prev->next = cat->next;
530                                 if (cat == cfg->last)
531                                         cfg->last = prev;
532                         } else {
533                                 cfg->root = cat->next;
534                                 if (cat == cfg->last)
535                                         cfg->last = NULL;
536                         }
537                         free(cat);
538                         return 0;
539                 }
540                 prev = cat;
541                 cat = cat->next;
542         }
543
544         prev = NULL;
545         cat = cfg->root;
546         while(cat) {
547                 if (!strcasecmp(cat->name, category)) {
548                         ast_variables_destroy(cat->root);
549                         if (prev) {
550                                 prev->next = cat->next;
551                                 if (cat == cfg->last)
552                                         cfg->last = prev;
553                         } else {
554                                 cfg->root = cat->next;
555                                 if (cat == cfg->last)
556                                         cfg->last = NULL;
557                         }
558                         free(cat);
559                         return 0;
560                 }
561                 prev = cat;
562                 cat = cat->next;
563         }
564         return -1;
565 }
566
567 void ast_config_destroy(struct ast_config *cfg)
568 {
569         struct ast_category *cat, *catn;
570
571         if (!cfg)
572                 return;
573
574         cat = cfg->root;
575         while(cat) {
576                 ast_variables_destroy(cat->root);
577                 catn = cat;
578                 cat = cat->next;
579                 free(catn);
580         }
581         free(cfg);
582 }
583
584 struct ast_category *ast_config_get_current_category(const struct ast_config *cfg)
585 {
586         return cfg->current;
587 }
588
589 void ast_config_set_current_category(struct ast_config *cfg, const struct ast_category *cat)
590 {
591         /* cast below is just to silence compiler warning about dropping "const" */
592         cfg->current = (struct ast_category *) cat;
593 }
594
595 static int process_text_line(struct ast_config *cfg, struct ast_category **cat, char *buf, int lineno, const char *configfile, int withcomments)
596 {
597         char *c;
598         char *cur = buf;
599         struct ast_variable *v;
600         char cmd[512], exec_file[512];
601         int object, do_exec, do_include;
602
603         /* Actually parse the entry */
604         if (cur[0] == '[') {
605                 struct ast_category *newcat = NULL;
606                 char *catname;
607
608                 /* A category header */
609                 c = strchr(cur, ']');
610                 if (!c) {
611                         ast_log(LOG_WARNING, "parse error: no closing ']', line %d of %s\n", lineno, configfile);
612                         return -1;
613                 }
614                 *c++ = '\0';
615                 cur++;
616                 if (*c++ != '(')
617                         c = NULL;
618                 catname = cur;
619                 if (!(*cat = newcat = ast_category_new(catname))) {
620                         return -1;
621                 }
622                 /* add comments */
623                 if (withcomments && comment_buffer && comment_buffer[0] ) {
624                         newcat->precomments = ALLOC_COMMENT(comment_buffer);
625                 }
626                 if (withcomments && lline_buffer && lline_buffer[0] ) {
627                         newcat->sameline = ALLOC_COMMENT(lline_buffer);
628                 }
629                 if( withcomments )
630                         CB_RESET();
631                 
632                 /* If there are options or categories to inherit from, process them now */
633                 if (c) {
634                         if (!(cur = strchr(c, ')'))) {
635                                 ast_log(LOG_WARNING, "parse error: no closing ')', line %d of %s\n", lineno, configfile);
636                                 return -1;
637                         }
638                         *cur = '\0';
639                         while ((cur = strsep(&c, ","))) {
640                                 if (!strcasecmp(cur, "!")) {
641                                         (*cat)->ignored = 1;
642                                 } else if (!strcasecmp(cur, "+")) {
643                                         *cat = category_get(cfg, catname, 1);
644                                         if (!*cat) {
645                                                 ast_config_destroy(cfg);
646                                                 if (newcat)
647                                                         ast_category_destroy(newcat);
648                                                 ast_log(LOG_WARNING, "Category addition requested, but category '%s' does not exist, line %d of %s\n", catname, lineno, configfile);
649                                                 return -1;
650                                         }
651                                         if (newcat) {
652                                                 move_variables(newcat, *cat);
653                                                 ast_category_destroy(newcat);
654                                                 newcat = NULL;
655                                         }
656                                 } else {
657                                         struct ast_category *base;
658                                 
659                                         base = category_get(cfg, cur, 1);
660                                         if (!base) {
661                                                 ast_log(LOG_WARNING, "Inheritance requested, but category '%s' does not exist, line %d of %s\n", cur, lineno, configfile);
662                                                 return -1;
663                                         }
664                                         inherit_category(*cat, base);
665                                 }
666                         }
667                 }
668                 if (newcat)
669                         ast_category_append(cfg, *cat);
670         } else if (cur[0] == '#') {
671                 /* A directive */
672                 cur++;
673                 c = cur;
674                 while(*c && (*c > 32)) c++;
675                 if (*c) {
676                         *c = '\0';
677                         /* Find real argument */
678                         c = ast_skip_blanks(c + 1);
679                         if (!*c)
680                                 c = NULL;
681                 } else 
682                         c = NULL;
683                 do_include = !strcasecmp(cur, "include");
684                 if(!do_include)
685                         do_exec = !strcasecmp(cur, "exec");
686                 else
687                         do_exec = 0;
688                 if (do_exec && !ast_opt_exec_includes) {
689                         ast_log(LOG_WARNING, "Cannot perform #exec unless execincludes option is enabled in asterisk.conf (options section)!\n");
690                         do_exec = 0;
691                 }
692                 if (do_include || do_exec) {
693                         if (c) {
694                                 /* Strip off leading and trailing "'s and <>'s */
695                                 while((*c == '<') || (*c == '>') || (*c == '\"')) c++;
696                                 /* Get rid of leading mess */
697                                 cur = c;
698                                 while (!ast_strlen_zero(cur)) {
699                                         c = cur + strlen(cur) - 1;
700                                         if ((*c == '>') || (*c == '<') || (*c == '\"'))
701                                                 *c = '\0';
702                                         else
703                                                 break;
704                                 }
705                                 /* #exec </path/to/executable>
706                                    We create a tmp file, then we #include it, then we delete it. */
707                                 if (do_exec) { 
708                                         snprintf(exec_file, sizeof(exec_file), "/var/tmp/exec.%d.%ld", (int)time(NULL), (long)pthread_self());
709                                         snprintf(cmd, sizeof(cmd), "%s > %s 2>&1", cur, exec_file);
710                                         ast_safe_system(cmd);
711                                         cur = exec_file;
712                                 } else
713                                         exec_file[0] = '\0';
714                                 /* A #include */
715                                 do_include = ast_config_internal_load(cur, cfg, withcomments) ? 1 : 0;
716                                 if(!ast_strlen_zero(exec_file))
717                                         unlink(exec_file);
718                                 if(!do_include)
719                                         return 0;
720
721                         } else {
722                                 ast_log(LOG_WARNING, "Directive '#%s' needs an argument (%s) at line %d of %s\n", 
723                                                 do_exec ? "exec" : "include",
724                                                 do_exec ? "/path/to/executable" : "filename",
725                                                 lineno,
726                                                 configfile);
727                         }
728                 }
729                 else 
730                         ast_log(LOG_WARNING, "Unknown directive '%s' at line %d of %s\n", cur, lineno, configfile);
731         } else {
732                 /* Just a line (variable = value) */
733                 if (!*cat) {
734                         ast_log(LOG_WARNING,
735                                 "parse error: No category context for line %d of %s\n", lineno, configfile);
736                         return -1;
737                 }
738                 c = strchr(cur, '=');
739                 if (c) {
740                         *c = 0;
741                         c++;
742                         /* Ignore > in => */
743                         if (*c== '>') {
744                                 object = 1;
745                                 c++;
746                         } else
747                                 object = 0;
748                         if ((v = ast_variable_new(ast_strip(cur), ast_strip(c)))) {
749                                 v->lineno = lineno;
750                                 v->object = object;
751                                 /* Put and reset comments */
752                                 v->blanklines = 0;
753                                 ast_variable_append(*cat, v);
754                                 /* add comments */
755                                 if (withcomments && comment_buffer && comment_buffer[0] ) {
756                                         v->precomments = ALLOC_COMMENT(comment_buffer);
757                                 }
758                                 if (withcomments && lline_buffer && lline_buffer[0] ) {
759                                         v->sameline = ALLOC_COMMENT(lline_buffer);
760                                 }
761                                 if( withcomments )
762                                         CB_RESET();
763                                 
764                         } else {
765                                 return -1;
766                         }
767                 } else {
768                         ast_log(LOG_WARNING, "No '=' (equal sign) in line %d of %s\n", lineno, configfile);
769                 }
770         }
771         return 0;
772 }
773
774 static struct ast_config *config_text_file_load(const char *database, const char *table, const char *filename, struct ast_config *cfg, int withcomments)
775 {
776         char fn[256];
777         char buf[8192];
778         char *new_buf, *comment_p, *process_buf;
779         FILE *f;
780         int lineno=0;
781         int comment = 0, nest[MAX_NESTED_COMMENTS];
782         struct ast_category *cat = NULL;
783         int count = 0;
784         struct stat statbuf;
785         
786         cat = ast_config_get_current_category(cfg);
787
788         if (filename[0] == '/') {
789                 ast_copy_string(fn, filename, sizeof(fn));
790         } else {
791                 snprintf(fn, sizeof(fn), "%s/%s", (char *)ast_config_AST_CONFIG_DIR, filename);
792         }
793
794         if (withcomments) {
795                 CB_INIT();
796         }
797         
798 #ifdef AST_INCLUDE_GLOB
799         {
800                 int glob_ret;
801                 glob_t globbuf;
802                 globbuf.gl_offs = 0;    /* initialize it to silence gcc */
803 #ifdef SOLARIS
804                 glob_ret = glob(fn, GLOB_NOCHECK, NULL, &globbuf);
805 #else
806                 glob_ret = glob(fn, GLOB_NOMAGIC|GLOB_BRACE, NULL, &globbuf);
807 #endif
808                 if (glob_ret == GLOB_NOSPACE)
809                         ast_log(LOG_WARNING,
810                                 "Glob Expansion of pattern '%s' failed: Not enough memory\n", fn);
811                 else if (glob_ret  == GLOB_ABORTED)
812                         ast_log(LOG_WARNING,
813                                 "Glob Expansion of pattern '%s' failed: Read error\n", fn);
814                 else  {
815                         /* loop over expanded files */
816                         int i;
817                         for (i=0; i<globbuf.gl_pathc; i++) {
818                                 ast_copy_string(fn, globbuf.gl_pathv[i], sizeof(fn));
819 #endif
820         do {
821                 if (stat(fn, &statbuf))
822                         continue;
823
824                 if (!S_ISREG(statbuf.st_mode)) {
825                         ast_log(LOG_WARNING, "'%s' is not a regular file, ignoring\n", fn);
826                         continue;
827                 }
828                 if (option_verbose > 1) {
829                         ast_verbose(VERBOSE_PREFIX_2 "Parsing '%s': ", fn);
830                         fflush(stdout);
831                 }
832                 if (!(f = fopen(fn, "r"))) {
833                         if (option_debug)
834                                 ast_log(LOG_DEBUG, "No file to parse: %s\n", fn);
835                         if (option_verbose > 1)
836                                 ast_verbose( "Not found (%s)\n", strerror(errno));
837                         continue;
838                 }
839                 count++;
840                 if (option_debug)
841                         ast_log(LOG_DEBUG, "Parsing %s\n", fn);
842                 if (option_verbose > 1)
843                         ast_verbose("Found\n");
844                 while(!feof(f)) {
845                         lineno++;
846                         if (fgets(buf, sizeof(buf), f)) {
847                                 if ( withcomments ) {    
848                                         CB_ADD(lline_buffer);       /* add the current lline buffer to the comment buffer */
849                                         lline_buffer[0] = 0;        /* erase the lline buffer */
850                                 }
851                                 
852                                 new_buf = buf;
853                                 if (comment) 
854                                         process_buf = NULL;
855                                 else
856                                         process_buf = buf;
857                                 
858                                 while ((comment_p = strchr(new_buf, COMMENT_META))) {
859                                         if ((comment_p > new_buf) && (*(comment_p-1) == '\\')) {
860                                                 /* Yuck, gotta memmove */
861                                                 memmove(comment_p - 1, comment_p, strlen(comment_p) + 1);
862                                                 new_buf = comment_p;
863                                         } else if(comment_p[1] == COMMENT_TAG && comment_p[2] == COMMENT_TAG && (comment_p[3] != '-')) {
864                                                 /* Meta-Comment start detected ";--" */
865                                                 if (comment < MAX_NESTED_COMMENTS) {
866                                                         *comment_p = '\0';
867                                                         new_buf = comment_p + 3;
868                                                         comment++;
869                                                         nest[comment-1] = lineno;
870                                                 } else {
871                                                         ast_log(LOG_ERROR, "Maximum nest limit of %d reached.\n", MAX_NESTED_COMMENTS);
872                                                 }
873                                         } else if ((comment_p >= new_buf + 2) &&
874                                                    (*(comment_p - 1) == COMMENT_TAG) &&
875                                                    (*(comment_p - 2) == COMMENT_TAG)) {
876                                                 /* Meta-Comment end detected */
877                                                 comment--;
878                                                 new_buf = comment_p + 1;
879                                                 if (!comment) {
880                                                         /* Back to non-comment now */
881                                                         if (process_buf) {
882                                                                 /* Actually have to move what's left over the top, then continue */
883                                                                 char *oldptr;
884                                                                 oldptr = process_buf + strlen(process_buf);
885                                                                 if ( withcomments ) {
886                                                                         CB_ADD(";");
887                                                                         CB_ADD_LEN(oldptr+1,new_buf-oldptr-1);
888                                                                 }
889                                                                 
890                                                                 memmove(oldptr, new_buf, strlen(new_buf) + 1);
891                                                                 new_buf = oldptr;
892                                                         } else
893                                                                 process_buf = new_buf;
894                                                 }
895                                         } else {
896                                                 if (!comment) {
897                                                         /* If ; is found, and we are not nested in a comment, 
898                                                            we immediately stop all comment processing */
899                                                         if ( withcomments ) {
900                                                                 LLB_ADD(comment_p);
901                                                         }
902                                                         *comment_p = '\0'; 
903                                                         new_buf = comment_p;
904                                                 } else
905                                                         new_buf = comment_p + 1;
906                                         }
907                                 }
908                                 if( withcomments && comment && !process_buf )
909                                 {
910                                         CB_ADD(buf);  /* the whole line is a comment, store it */
911                                 }
912                                 
913                                 if (process_buf) {
914                                         char *buf = ast_strip(process_buf);
915                                         if (!ast_strlen_zero(buf)) {
916                                                 if (process_text_line(cfg, &cat, buf, lineno, filename, withcomments)) {
917                                                         cfg = NULL;
918                                                         break;
919                                                 }
920                                         }
921                                 }
922                         }
923                 }
924                 fclose(f);              
925         } while(0);
926         if (comment) {
927                 ast_log(LOG_WARNING,"Unterminated comment detected beginning on line %d\n", nest[comment]);
928         }
929 #ifdef AST_INCLUDE_GLOB
930                                         if (!cfg)
931                                                 break;
932                                 }
933                                 globfree(&globbuf);
934                         }
935                 }
936 #endif
937         if (withcomments) {
938                 if (comment_buffer) { 
939                         free(comment_buffer);
940                         free(lline_buffer);
941                         comment_buffer=0; 
942                         lline_buffer=0; 
943                         comment_buffer_size=0; 
944                         lline_buffer_size=0;
945                 }
946         }
947         if (count == 0)
948                 return NULL;
949
950         return cfg;
951 }
952
953 int config_text_file_save(const char *configfile, const struct ast_config *cfg, const char *generator)
954 {
955         FILE *f;
956         char fn[256];
957         char date[256]="";
958         time_t t;
959         struct ast_variable *var;
960         struct ast_category *cat;
961         struct ast_comment *cmt;
962         int blanklines = 0;
963
964         if (configfile[0] == '/') {
965                 ast_copy_string(fn, configfile, sizeof(fn));
966         } else {
967                 snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_CONFIG_DIR, configfile);
968         }
969         time(&t);
970         ast_copy_string(date, ctime(&t), sizeof(date));
971 #ifdef __CYGWIN__       
972         if ((f = fopen(fn, "w+"))) {
973 #else
974         if ((f = fopen(fn, "w"))) {
975 #endif      
976                 if (option_verbose > 1)
977                         ast_verbose(  VERBOSE_PREFIX_2 "Saving '%s': ", fn);
978                 fprintf(f, ";!\n");
979                 fprintf(f, ";! Automatically generated configuration file\n");
980                 fprintf(f, ";! Filename: %s (%s)\n", configfile, fn);
981                 fprintf(f, ";! Generator: %s\n", generator);
982                 fprintf(f, ";! Creation Date: %s", date);
983                 fprintf(f, ";!\n");
984                 cat = cfg->root;
985                 while(cat) {
986                         /* Dump section with any appropriate comment */
987                         for (cmt = cat->precomments; cmt; cmt=cmt->next)
988                         {
989                                 if (cmt->cmt[0] != ';' || cmt->cmt[1] != '!')
990                                         fprintf(f,"%s", cmt->cmt);
991                         }
992                         if (!cat->precomments)
993                                 fprintf(f,"\n");
994                         fprintf(f, "[%s]", cat->name);
995                         for(cmt = cat->sameline; cmt; cmt=cmt->next)
996                         {
997                                 fprintf(f,"%s", cmt->cmt);
998                         }
999                         if (!cat->sameline)
1000                                 fprintf(f,"\n");
1001                         var = cat->root;
1002                         while(var) {
1003                                 for (cmt = var->precomments; cmt; cmt=cmt->next)
1004                                 {
1005                                         if (cmt->cmt[0] != ';' || cmt->cmt[1] != '!')
1006                                                 fprintf(f,"%s", cmt->cmt);
1007                                 }
1008                                 if (var->sameline) 
1009                                         fprintf(f, "%s %s %s  %s", var->name, (var->object ? "=>" : "="), var->value, var->sameline->cmt);
1010                                 else    
1011                                         fprintf(f, "%s %s %s\n", var->name, (var->object ? "=>" : "="), var->value);
1012                                 if (var->blanklines) {
1013                                         blanklines = var->blanklines;
1014                                         while (blanklines--)
1015                                                 fprintf(f, "\n");
1016                                 }
1017                                         
1018                                 var = var->next;
1019                         }
1020 #if 0
1021                         /* Put an empty line */
1022                         fprintf(f, "\n");
1023 #endif
1024                         cat = cat->next;
1025                 }
1026                 if ((option_verbose > 1) && !option_debug)
1027                         ast_verbose("Saved\n");
1028         } else {
1029                 if (option_debug)
1030                         printf("Unable to open for writing: %s\n", fn);
1031                 if (option_verbose > 1)
1032                         printf( "Unable to write (%s)", strerror(errno));
1033                 return -1;
1034         }
1035         fclose(f);
1036         return 0;
1037 }
1038
1039 static void clear_config_maps(void) 
1040 {
1041         struct ast_config_map *map;
1042
1043         ast_mutex_lock(&config_lock);
1044
1045         while (config_maps) {
1046                 map = config_maps;
1047                 config_maps = config_maps->next;
1048                 free(map);
1049         }
1050                 
1051         ast_mutex_unlock(&config_lock);
1052 }
1053
1054 static int append_mapping(char *name, char *driver, char *database, char *table)
1055 {
1056         struct ast_config_map *map;
1057         int length;
1058
1059         length = sizeof(*map);
1060         length += strlen(name) + 1;
1061         length += strlen(driver) + 1;
1062         length += strlen(database) + 1;
1063         if (table)
1064                 length += strlen(table) + 1;
1065
1066         if (!(map = ast_calloc(1, length)))
1067                 return -1;
1068
1069         map->name = map->stuff;
1070         strcpy(map->name, name);
1071         map->driver = map->name + strlen(map->name) + 1;
1072         strcpy(map->driver, driver);
1073         map->database = map->driver + strlen(map->driver) + 1;
1074         strcpy(map->database, database);
1075         if (table) {
1076                 map->table = map->database + strlen(map->database) + 1;
1077                 strcpy(map->table, table);
1078         }
1079         map->next = config_maps;
1080
1081         if (option_verbose > 1)
1082                 ast_verbose(VERBOSE_PREFIX_2 "Binding %s to %s/%s/%s\n",
1083                             map->name, map->driver, map->database, map->table ? map->table : map->name);
1084
1085         config_maps = map;
1086         return 0;
1087 }
1088
1089 int read_config_maps(void) 
1090 {
1091         struct ast_config *config, *configtmp;
1092         struct ast_variable *v;
1093         char *driver, *table, *database, *stringp;
1094
1095         clear_config_maps();
1096
1097         configtmp = ast_config_new();
1098         configtmp->max_include_level = 1;
1099         config = ast_config_internal_load(extconfig_conf, configtmp, 0);
1100         if (!config) {
1101                 ast_config_destroy(configtmp);
1102                 return 0;
1103         }
1104
1105         for (v = ast_variable_browse(config, "settings"); v; v = v->next) {
1106                 stringp = v->value;
1107                 driver = strsep(&stringp, ",");
1108
1109                 /* check if the database text starts with a double quote */
1110                 if (*stringp == '"') {
1111                         stringp++;
1112                         database = strsep(&stringp, "\"");
1113                         strsep(&stringp, ",");
1114                 } else {
1115                         /* apparently this text has no quotes */
1116                         database = strsep(&stringp, ",");
1117                 }
1118
1119                 table = strsep(&stringp, ",");
1120
1121                 if (!strcmp(v->name, extconfig_conf)) {
1122                         ast_log(LOG_WARNING, "Cannot bind '%s'!\n", extconfig_conf);
1123                         continue;
1124                 }
1125
1126                 if (!strcmp(v->name, "asterisk.conf")) {
1127                         ast_log(LOG_WARNING, "Cannot bind 'asterisk.conf'!\n");
1128                         continue;
1129                 }
1130
1131                 if (!strcmp(v->name, "logger.conf")) {
1132                         ast_log(LOG_WARNING, "Cannot bind 'logger.conf'!\n");
1133                         continue;
1134                 }
1135
1136                 if (!driver || !database)
1137                         continue;
1138                 if (!strcasecmp(v->name, "sipfriends")) {
1139                         ast_log(LOG_WARNING, "The 'sipfriends' table is obsolete, update your config to use sipusers and sippeers, though they can point to the same table.\n");
1140                         append_mapping("sipusers", driver, database, table ? table : "sipfriends");
1141                         append_mapping("sippeers", driver, database, table ? table : "sipfriends");
1142                 } else if (!strcasecmp(v->name, "iaxfriends")) {
1143                         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");
1144                         append_mapping("iaxusers", driver, database, table ? table : "iaxfriends");
1145                         append_mapping("iaxpeers", driver, database, table ? table : "iaxfriends");
1146                 } else 
1147                         append_mapping(v->name, driver, database, table);
1148         }
1149                 
1150         ast_config_destroy(config);
1151         return 0;
1152 }
1153
1154 int ast_config_engine_register(struct ast_config_engine *new) 
1155 {
1156         struct ast_config_engine *ptr;
1157
1158         ast_mutex_lock(&config_lock);
1159
1160         if (!config_engine_list) {
1161                 config_engine_list = new;
1162         } else {
1163                 for (ptr = config_engine_list; ptr->next; ptr=ptr->next);
1164                 ptr->next = new;
1165         }
1166
1167         ast_mutex_unlock(&config_lock);
1168         ast_log(LOG_NOTICE,"Registered Config Engine %s\n", new->name);
1169
1170         return 1;
1171 }
1172
1173 int ast_config_engine_deregister(struct ast_config_engine *del) 
1174 {
1175         struct ast_config_engine *ptr, *last=NULL;
1176
1177         ast_mutex_lock(&config_lock);
1178
1179         for (ptr = config_engine_list; ptr; ptr=ptr->next) {
1180                 if (ptr == del) {
1181                         if (last)
1182                                 last->next = ptr->next;
1183                         else
1184                                 config_engine_list = ptr->next;
1185                         break;
1186                 }
1187                 last = ptr;
1188         }
1189
1190         ast_mutex_unlock(&config_lock);
1191
1192         return 0;
1193 }
1194
1195 /*! \brief Find realtime engine for realtime family */
1196 static struct ast_config_engine *find_engine(const char *family, char *database, int dbsiz, char *table, int tabsiz) 
1197 {
1198         struct ast_config_engine *eng, *ret = NULL;
1199         struct ast_config_map *map;
1200
1201         ast_mutex_lock(&config_lock);
1202
1203         for (map = config_maps; map; map = map->next) {
1204                 if (!strcasecmp(family, map->name)) {
1205                         if (database)
1206                                 ast_copy_string(database, map->database, dbsiz);
1207                         if (table)
1208                                 ast_copy_string(table, map->table ? map->table : family, tabsiz);
1209                         break;
1210                 }
1211         }
1212
1213         /* Check if the required driver (engine) exist */
1214         if (map) {
1215                 for (eng = config_engine_list; !ret && eng; eng = eng->next) {
1216                         if (!strcasecmp(eng->name, map->driver))
1217                                 ret = eng;
1218                 }
1219         }
1220
1221         ast_mutex_unlock(&config_lock);
1222         
1223         /* if we found a mapping, but the engine is not available, then issue a warning */
1224         if (map && !ret)
1225                 ast_log(LOG_WARNING, "Realtime mapping for '%s' found to engine '%s', but the engine is not available\n", map->name, map->driver);
1226
1227         return ret;
1228 }
1229
1230 static struct ast_config_engine text_file_engine = {
1231         .name = "text",
1232         .load_func = config_text_file_load,
1233 };
1234
1235 struct ast_config *ast_config_internal_load(const char *filename, struct ast_config *cfg, int withcomments)
1236 {
1237         char db[256];
1238         char table[256];
1239         struct ast_config_engine *loader = &text_file_engine;
1240         struct ast_config *result; 
1241
1242         if (cfg->include_level == cfg->max_include_level) {
1243                 ast_log(LOG_WARNING, "Maximum Include level (%d) exceeded\n", cfg->max_include_level);
1244                 return NULL;
1245         }
1246
1247         cfg->include_level++;
1248
1249         if (strcmp(filename, extconfig_conf) && strcmp(filename, "asterisk.conf") && config_engine_list) {
1250                 struct ast_config_engine *eng;
1251
1252                 eng = find_engine(filename, db, sizeof(db), table, sizeof(table));
1253
1254
1255                 if (eng && eng->load_func) {
1256                         loader = eng;
1257                 } else {
1258                         eng = find_engine("global", db, sizeof(db), table, sizeof(table));
1259                         if (eng && eng->load_func)
1260                                 loader = eng;
1261                 }
1262         }
1263
1264         result = loader->load_func(db, table, filename, cfg, withcomments);
1265
1266         if (result)
1267                 result->include_level--;
1268
1269         return result;
1270 }
1271
1272 struct ast_config *ast_config_load(const char *filename)
1273 {
1274         struct ast_config *cfg;
1275         struct ast_config *result;
1276
1277         cfg = ast_config_new();
1278         if (!cfg)
1279                 return NULL;
1280
1281         result = ast_config_internal_load(filename, cfg, 0);
1282         if (!result)
1283                 ast_config_destroy(cfg);
1284
1285         return result;
1286 }
1287
1288 struct ast_config *ast_config_load_with_comments(const char *filename)
1289 {
1290         struct ast_config *cfg;
1291         struct ast_config *result;
1292
1293         cfg = ast_config_new();
1294         if (!cfg)
1295                 return NULL;
1296
1297         result = ast_config_internal_load(filename, cfg, 1);
1298         if (!result)
1299                 ast_config_destroy(cfg);
1300
1301         return result;
1302 }
1303
1304 struct ast_variable *ast_load_realtime(const char *family, ...)
1305 {
1306         struct ast_config_engine *eng;
1307         char db[256]="";
1308         char table[256]="";
1309         struct ast_variable *res=NULL;
1310         va_list ap;
1311
1312         va_start(ap, family);
1313         eng = find_engine(family, db, sizeof(db), table, sizeof(table));
1314         if (eng && eng->realtime_func) 
1315                 res = eng->realtime_func(db, table, ap);
1316         va_end(ap);
1317
1318         return res;
1319 }
1320
1321 /*! \brief Check if realtime engine is configured for family */
1322 int ast_check_realtime(const char *family)
1323 {
1324         struct ast_config_engine *eng;
1325
1326         eng = find_engine(family, NULL, 0, NULL, 0);
1327         if (eng)
1328                 return 1;
1329         return 0;
1330
1331 }
1332
1333 struct ast_config *ast_load_realtime_multientry(const char *family, ...)
1334 {
1335         struct ast_config_engine *eng;
1336         char db[256]="";
1337         char table[256]="";
1338         struct ast_config *res=NULL;
1339         va_list ap;
1340
1341         va_start(ap, family);
1342         eng = find_engine(family, db, sizeof(db), table, sizeof(table));
1343         if (eng && eng->realtime_multi_func) 
1344                 res = eng->realtime_multi_func(db, table, ap);
1345         va_end(ap);
1346
1347         return res;
1348 }
1349
1350 int ast_update_realtime(const char *family, const char *keyfield, const char *lookup, ...)
1351 {
1352         struct ast_config_engine *eng;
1353         int res = -1;
1354         char db[256]="";
1355         char table[256]="";
1356         va_list ap;
1357
1358         va_start(ap, lookup);
1359         eng = find_engine(family, db, sizeof(db), table, sizeof(table));
1360         if (eng && eng->update_func) 
1361                 res = eng->update_func(db, table, keyfield, lookup, ap);
1362         va_end(ap);
1363
1364         return res;
1365 }
1366
1367 static int config_command(int fd, int argc, char **argv) 
1368 {
1369         struct ast_config_engine *eng;
1370         struct ast_config_map *map;
1371         
1372         ast_mutex_lock(&config_lock);
1373
1374         ast_cli(fd, "\n\n");
1375         for (eng = config_engine_list; eng; eng = eng->next) {
1376                 ast_cli(fd, "\nConfig Engine: %s\n", eng->name);
1377                 for (map = config_maps; map; map = map->next)
1378                         if (!strcasecmp(map->driver, eng->name)) {
1379                                 ast_cli(fd, "===> %s (db=%s, table=%s)\n", map->name, map->database,
1380                                         map->table ? map->table : map->name);
1381                         }
1382         }
1383         ast_cli(fd,"\n\n");
1384         
1385         ast_mutex_unlock(&config_lock);
1386
1387         return 0;
1388 }
1389
1390 static char show_config_help[] =
1391         "Usage: core show config mappings\n"
1392         "       Shows the filenames to config engines.\n";
1393
1394 static struct ast_cli_entry cli_config[] = {
1395         { { "core", "show", "config", "mappings", NULL },
1396         config_command, "Display config mappings (file names to config engines)",
1397         show_config_help },
1398 };
1399
1400 int register_config_cli() 
1401 {
1402         ast_cli_register_multiple(cli_config, sizeof(cli_config) / sizeof(struct ast_cli_entry));
1403         return 0;
1404 }