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