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