silly people that don't want to install/run autoconf :-)
[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 <stdio.h>
30 #include <unistd.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <errno.h>
34 #include <time.h>
35 #include <sys/stat.h>
36 #define AST_INCLUDE_GLOB 1
37 #ifdef AST_INCLUDE_GLOB
38 #if defined(__Darwin__) || defined(__CYGWIN__)
39 #define GLOB_ABORTED GLOB_ABEND
40 #endif
41 # include <glob.h>
42 #endif
43
44 #include "asterisk.h"
45
46 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
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 void ast_config_destroy(struct ast_config *cfg)
327 {
328         struct ast_category *cat, *catn;
329
330         if (!cfg)
331                 return;
332
333         cat = cfg->root;
334         while(cat) {
335                 ast_variables_destroy(cat->root);
336                 catn = cat;
337                 cat = cat->next;
338                 free(catn);
339         }
340         free(cfg);
341 }
342
343 struct ast_category *ast_config_get_current_category(const struct ast_config *cfg)
344 {
345         return cfg->current;
346 }
347
348 void ast_config_set_current_category(struct ast_config *cfg, const struct ast_category *cat)
349 {
350         /* cast below is just to silence compiler warning about dropping "const" */
351         cfg->current = (struct ast_category *) cat;
352 }
353
354 static int process_text_line(struct ast_config *cfg, struct ast_category **cat, char *buf, int lineno, const char *configfile)
355 {
356         char *c;
357         char *cur = buf;
358         struct ast_variable *v;
359         char cmd[512], exec_file[512];
360         int object, do_exec, do_include;
361
362         /* Actually parse the entry */
363         if (cur[0] == '[') {
364                 struct ast_category *newcat = NULL;
365                 char *catname;
366
367                 /* A category header */
368                 c = strchr(cur, ']');
369                 if (!c) {
370                         ast_log(LOG_WARNING, "parse error: no closing ']', line %d of %s\n", lineno, configfile);
371                         return -1;
372                 }
373                 *c++ = '\0';
374                 cur++;
375                 if (*c++ != '(')
376                         c = NULL;
377                 catname = cur;
378                 if (!(*cat = newcat = ast_category_new(catname))) {
379                         return -1;
380                 }
381                 /* If there are options or categories to inherit from, process them now */
382                 if (c) {
383                         if (!(cur = strchr(c, ')'))) {
384                                 ast_log(LOG_WARNING, "parse error: no closing ')', line %d of %s\n", lineno, configfile);
385                                 return -1;
386                         }
387                         *cur = '\0';
388                         while ((cur = strsep(&c, ","))) {
389                                 if (!strcasecmp(cur, "!")) {
390                                         (*cat)->ignored = 1;
391                                 } else if (!strcasecmp(cur, "+")) {
392                                         *cat = category_get(cfg, catname, 1);
393                                         if (!*cat) {
394                                                 ast_config_destroy(cfg);
395                                                 if (newcat)
396                                                         ast_category_destroy(newcat);
397                                                 ast_log(LOG_WARNING, "Category addition requested, but category '%s' does not exist, line %d of %s\n", catname, lineno, configfile);
398                                                 return -1;
399                                         }
400                                         if (newcat) {
401                                                 move_variables(newcat, *cat);
402                                                 ast_category_destroy(newcat);
403                                                 newcat = NULL;
404                                         }
405                                 } else {
406                                         struct ast_category *base;
407                                 
408                                         base = category_get(cfg, cur, 1);
409                                         if (!base) {
410                                                 ast_log(LOG_WARNING, "Inheritance requested, but category '%s' does not exist, line %d of %s\n", cur, lineno, configfile);
411                                                 return -1;
412                                         }
413                                         inherit_category(*cat, base);
414                                 }
415                         }
416                 }
417                 if (newcat)
418                         ast_category_append(cfg, *cat);
419         } else if (cur[0] == '#') {
420                 /* A directive */
421                 cur++;
422                 c = cur;
423                 while(*c && (*c > 32)) c++;
424                 if (*c) {
425                         *c = '\0';
426                         /* Find real argument */
427                         c = ast_skip_blanks(c + 1);
428                         if (!*c)
429                                 c = NULL;
430                 } else 
431                         c = NULL;
432                 do_include = !strcasecmp(cur, "include");
433                 if(!do_include)
434                         do_exec = !strcasecmp(cur, "exec");
435                 else
436                         do_exec = 0;
437                 if (do_exec && !ast_opt_exec_includes) {
438                         ast_log(LOG_WARNING, "Cannot perform #exec unless execincludes option is enabled in asterisk.conf (options section)!\n");
439                         do_exec = 0;
440                 }
441                 if (do_include || do_exec) {
442                         if (c) {
443                                 /* Strip off leading and trailing "'s and <>'s */
444                                 while((*c == '<') || (*c == '>') || (*c == '\"')) c++;
445                                 /* Get rid of leading mess */
446                                 cur = c;
447                                 while (!ast_strlen_zero(cur)) {
448                                         c = cur + strlen(cur) - 1;
449                                         if ((*c == '>') || (*c == '<') || (*c == '\"'))
450                                                 *c = '\0';
451                                         else
452                                                 break;
453                                 }
454                                 /* #exec </path/to/executable>
455                                    We create a tmp file, then we #include it, then we delete it. */
456                                 if (do_exec) { 
457                                         snprintf(exec_file, sizeof(exec_file), "/var/tmp/exec.%d.%ld", (int)time(NULL), (long)pthread_self());
458                                         snprintf(cmd, sizeof(cmd), "%s > %s 2>&1", cur, exec_file);
459                                         ast_safe_system(cmd);
460                                         cur = exec_file;
461                                 } else
462                                         exec_file[0] = '\0';
463                                 /* A #include */
464                                 do_include = ast_config_internal_load(cur, cfg) ? 1 : 0;
465                                 if(!ast_strlen_zero(exec_file))
466                                         unlink(exec_file);
467                                 if(!do_include)
468                                         return 0;
469
470                         } else {
471                                 ast_log(LOG_WARNING, "Directive '#%s' needs an argument (%s) at line %d of %s\n", 
472                                                 do_exec ? "exec" : "include",
473                                                 do_exec ? "/path/to/executable" : "filename",
474                                                 lineno,
475                                                 configfile);
476                         }
477                 }
478                 else 
479                         ast_log(LOG_WARNING, "Unknown directive '%s' at line %d of %s\n", cur, lineno, configfile);
480         } else {
481                 /* Just a line (variable = value) */
482                 if (!*cat) {
483                         ast_log(LOG_WARNING,
484                                 "parse error: No category context for line %d of %s\n", lineno, configfile);
485                         return -1;
486                 }
487                 c = strchr(cur, '=');
488                 if (c) {
489                         *c = 0;
490                         c++;
491                         /* Ignore > in => */
492                         if (*c== '>') {
493                                 object = 1;
494                                 c++;
495                         } else
496                                 object = 0;
497                         if ((v = ast_variable_new(ast_strip(cur), ast_strip(c)))) {
498                                 v->lineno = lineno;
499                                 v->object = object;
500                                 /* Put and reset comments */
501                                 v->blanklines = 0;
502                                 ast_variable_append(*cat, v);
503                         } else {
504                                 return -1;
505                         }
506                 } else {
507                         ast_log(LOG_WARNING, "No '=' (equal sign) in line %d of %s\n", lineno, configfile);
508                 }
509
510         }
511         return 0;
512 }
513
514 static struct ast_config *config_text_file_load(const char *database, const char *table, const char *filename, struct ast_config *cfg)
515 {
516         char fn[256];
517         char buf[8192];
518         char *new_buf, *comment_p, *process_buf;
519         FILE *f;
520         int lineno=0;
521         int comment = 0, nest[MAX_NESTED_COMMENTS];
522         struct ast_category *cat = NULL;
523         int count = 0;
524         struct stat statbuf;
525         
526         cat = ast_config_get_current_category(cfg);
527
528         if (filename[0] == '/') {
529                 ast_copy_string(fn, filename, sizeof(fn));
530         } else {
531                 snprintf(fn, sizeof(fn), "%s/%s", (char *)ast_config_AST_CONFIG_DIR, filename);
532         }
533
534 #ifdef AST_INCLUDE_GLOB
535         {
536                 int glob_ret;
537                 glob_t globbuf;
538                 globbuf.gl_offs = 0;    /* initialize it to silence gcc */
539 #ifdef SOLARIS
540                 glob_ret = glob(fn, GLOB_NOCHECK, NULL, &globbuf);
541 #else
542                 glob_ret = glob(fn, GLOB_NOMAGIC|GLOB_BRACE, NULL, &globbuf);
543 #endif
544                 if (glob_ret == GLOB_NOSPACE)
545                         ast_log(LOG_WARNING,
546                                 "Glob Expansion of pattern '%s' failed: Not enough memory\n", fn);
547                 else if (glob_ret  == GLOB_ABORTED)
548                         ast_log(LOG_WARNING,
549                                 "Glob Expansion of pattern '%s' failed: Read error\n", fn);
550                 else  {
551                         /* loop over expanded files */
552                         int i;
553                         for (i=0; i<globbuf.gl_pathc; i++) {
554                                 ast_copy_string(fn, globbuf.gl_pathv[i], sizeof(fn));
555 #endif
556         do {
557                 if (stat(fn, &statbuf))
558                         continue;
559
560                 if (!S_ISREG(statbuf.st_mode)) {
561                         ast_log(LOG_WARNING, "'%s' is not a regular file, ignoring\n", fn);
562                         continue;
563                 }
564                 if ((option_verbose > 1) && !option_debug) {
565                         ast_verbose(VERBOSE_PREFIX_2 "Parsing '%s': ", fn);
566                         fflush(stdout);
567                 }
568                 if (!(f = fopen(fn, "r"))) {
569                         if (option_debug)
570                                 ast_log(LOG_DEBUG, "No file to parse: %s\n", fn);
571                         else if (option_verbose > 1)
572                                 ast_verbose( "Not found (%s)\n", strerror(errno));
573                         continue;
574                 }
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                 }
641                 fclose(f);              
642         } while(0);
643         if (comment) {
644                 ast_log(LOG_WARNING,"Unterminated comment detected beginning on line %d\n", nest[comment]);
645         }
646 #ifdef AST_INCLUDE_GLOB
647                                         if (!cfg)
648                                                 break;
649                                 }
650                                 globfree(&globbuf);
651                         }
652                 }
653 #endif
654         if (count == 0)
655                 return NULL;
656
657         return cfg;
658 }
659
660 int config_text_file_save(const char *configfile, const struct ast_config *cfg, const char *generator)
661 {
662         FILE *f;
663         char fn[256];
664         char date[256]="";
665         time_t t;
666         struct ast_variable *var;
667         struct ast_category *cat;
668         int blanklines = 0;
669
670         if (configfile[0] == '/') {
671                 ast_copy_string(fn, configfile, sizeof(fn));
672         } else {
673                 snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_CONFIG_DIR, configfile);
674         }
675         time(&t);
676         ast_copy_string(date, ctime(&t), sizeof(date));
677 #ifdef __CYGWIN__       
678         if ((f = fopen(fn, "w+"))) {
679 #else
680         if ((f = fopen(fn, "w"))) {
681 #endif      
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
752         if (!(map = ast_calloc(1, length)))
753                 return -1;
754
755         map->name = map->stuff;
756         strcpy(map->name, name);
757         map->driver = map->name + strlen(map->name) + 1;
758         strcpy(map->driver, driver);
759         map->database = map->driver + strlen(map->driver) + 1;
760         strcpy(map->database, database);
761         if (table) {
762                 map->table = map->database + strlen(map->database) + 1;
763                 strcpy(map->table, table);
764         }
765         map->next = config_maps;
766
767         if (option_verbose > 1)
768                 ast_verbose(VERBOSE_PREFIX_2 "Binding %s to %s/%s/%s\n",
769                             map->name, map->driver, map->database, map->table ? map->table : map->name);
770
771         config_maps = map;
772         return 0;
773 }
774
775 int read_config_maps(void) 
776 {
777         struct ast_config *config, *configtmp;
778         struct ast_variable *v;
779         char *driver, *table, *database, *stringp;
780
781         clear_config_maps();
782
783         configtmp = ast_config_new();
784         configtmp->max_include_level = 1;
785         config = ast_config_internal_load(extconfig_conf, configtmp);
786         if (!config) {
787                 ast_config_destroy(configtmp);
788                 return 0;
789         }
790
791         for (v = ast_variable_browse(config, "settings"); v; v = v->next) {
792                 stringp = v->value;
793                 driver = strsep(&stringp, ",");
794
795                 /* check if the database text starts with a double quote */
796                 if (*stringp == '"') {
797                         stringp++;
798                         database = strsep(&stringp, "\"");
799                         strsep(&stringp, ",");
800                 } else {
801                         /* apparently this text has no quotes */
802                         database = strsep(&stringp, ",");
803                 }
804
805                 table = strsep(&stringp, ",");
806
807                 if (!strcmp(v->name, extconfig_conf)) {
808                         ast_log(LOG_WARNING, "Cannot bind '%s'!\n", extconfig_conf);
809                         continue;
810                 }
811
812                 if (!strcmp(v->name, "asterisk.conf")) {
813                         ast_log(LOG_WARNING, "Cannot bind 'asterisk.conf'!\n");
814                         continue;
815                 }
816
817                 if (!strcmp(v->name, "logger.conf")) {
818                         ast_log(LOG_WARNING, "Cannot bind 'logger.conf'!\n");
819                         continue;
820                 }
821
822                 if (!driver || !database)
823                         continue;
824                 if (!strcasecmp(v->name, "sipfriends")) {
825                         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");
826                         append_mapping("sipusers", driver, database, table ? table : "sipfriends");
827                         append_mapping("sippeers", driver, database, table ? table : "sipfriends");
828                 } else if (!strcasecmp(v->name, "iaxfriends")) {
829                         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");
830                         append_mapping("iaxusers", driver, database, table ? table : "iaxfriends");
831                         append_mapping("iaxpeers", driver, database, table ? table : "iaxfriends");
832                 } else 
833                         append_mapping(v->name, driver, database, table);
834         }
835                 
836         ast_config_destroy(config);
837         return 0;
838 }
839
840 int ast_config_engine_register(struct ast_config_engine *new) 
841 {
842         struct ast_config_engine *ptr;
843
844         ast_mutex_lock(&config_lock);
845
846         if (!config_engine_list) {
847                 config_engine_list = new;
848         } else {
849                 for (ptr = config_engine_list; ptr->next; ptr=ptr->next);
850                 ptr->next = new;
851         }
852
853         ast_mutex_unlock(&config_lock);
854         ast_log(LOG_NOTICE,"Registered Config Engine %s\n", new->name);
855
856         return 1;
857 }
858
859 int ast_config_engine_deregister(struct ast_config_engine *del) 
860 {
861         struct ast_config_engine *ptr, *last=NULL;
862
863         ast_mutex_lock(&config_lock);
864
865         for (ptr = config_engine_list; ptr; ptr=ptr->next) {
866                 if (ptr == del) {
867                         if (last)
868                                 last->next = ptr->next;
869                         else
870                                 config_engine_list = ptr->next;
871                         break;
872                 }
873                 last = ptr;
874         }
875
876         ast_mutex_unlock(&config_lock);
877
878         return 0;
879 }
880
881 /*! \brief Find realtime engine for realtime family */
882 static struct ast_config_engine *find_engine(const char *family, char *database, int dbsiz, char *table, int tabsiz) 
883 {
884         struct ast_config_engine *eng, *ret = NULL;
885         struct ast_config_map *map;
886
887         ast_mutex_lock(&config_lock);
888
889         for (map = config_maps; map; map = map->next) {
890                 if (!strcasecmp(family, map->name)) {
891                         if (database)
892                                 ast_copy_string(database, map->database, dbsiz);
893                         if (table)
894                                 ast_copy_string(table, map->table ? map->table : family, tabsiz);
895                         break;
896                 }
897         }
898
899         /* Check if the required driver (engine) exist */
900         if (map) {
901                 for (eng = config_engine_list; !ret && eng; eng = eng->next) {
902                         if (!strcasecmp(eng->name, map->driver))
903                                 ret = eng;
904                 }
905         }
906
907         ast_mutex_unlock(&config_lock);
908         
909         /* if we found a mapping, but the engine is not available, then issue a warning */
910         if (map && !ret)
911                 ast_log(LOG_WARNING, "Realtime mapping for '%s' found to engine '%s', but the engine is not available\n", map->name, map->driver);
912
913         return ret;
914 }
915
916 static struct ast_config_engine text_file_engine = {
917         .name = "text",
918         .load_func = config_text_file_load,
919 };
920
921 struct ast_config *ast_config_internal_load(const char *filename, struct ast_config *cfg)
922 {
923         char db[256];
924         char table[256];
925         struct ast_config_engine *loader = &text_file_engine;
926         struct ast_config *result;
927
928         if (cfg->include_level == cfg->max_include_level) {
929                 ast_log(LOG_WARNING, "Maximum Include level (%d) exceeded\n", cfg->max_include_level);
930                 return NULL;
931         }
932
933         cfg->include_level++;
934
935         if (strcmp(filename, extconfig_conf) && strcmp(filename, "asterisk.conf") && config_engine_list) {
936                 struct ast_config_engine *eng;
937
938                 eng = find_engine(filename, db, sizeof(db), table, sizeof(table));
939
940
941                 if (eng && eng->load_func) {
942                         loader = eng;
943                 } else {
944                         eng = find_engine("global", db, sizeof(db), table, sizeof(table));
945                         if (eng && eng->load_func)
946                                 loader = eng;
947                 }
948         }
949
950         result = loader->load_func(db, table, filename, cfg);
951
952         if (result)
953                 result->include_level--;
954
955         return result;
956 }
957
958 struct ast_config *ast_config_load(const char *filename)
959 {
960         struct ast_config *cfg;
961         struct ast_config *result;
962
963         cfg = ast_config_new();
964         if (!cfg)
965                 return NULL;
966
967         result = ast_config_internal_load(filename, cfg);
968         if (!result)
969                 ast_config_destroy(cfg);
970
971         return result;
972 }
973
974 struct ast_variable *ast_load_realtime(const char *family, ...)
975 {
976         struct ast_config_engine *eng;
977         char db[256]="";
978         char table[256]="";
979         struct ast_variable *res=NULL;
980         va_list ap;
981
982         va_start(ap, family);
983         eng = find_engine(family, db, sizeof(db), table, sizeof(table));
984         if (eng && eng->realtime_func) 
985                 res = eng->realtime_func(db, table, ap);
986         va_end(ap);
987
988         return res;
989 }
990
991 /*! \brief Check if realtime engine is configured for family */
992 int ast_check_realtime(const char *family)
993 {
994         struct ast_config_engine *eng;
995
996         eng = find_engine(family, NULL, 0, NULL, 0);
997         if (eng)
998                 return 1;
999         return 0;
1000
1001 }
1002
1003 struct ast_config *ast_load_realtime_multientry(const char *family, ...)
1004 {
1005         struct ast_config_engine *eng;
1006         char db[256]="";
1007         char table[256]="";
1008         struct ast_config *res=NULL;
1009         va_list ap;
1010
1011         va_start(ap, family);
1012         eng = find_engine(family, db, sizeof(db), table, sizeof(table));
1013         if (eng && eng->realtime_multi_func) 
1014                 res = eng->realtime_multi_func(db, table, ap);
1015         va_end(ap);
1016
1017         return res;
1018 }
1019
1020 int ast_update_realtime(const char *family, const char *keyfield, const char *lookup, ...)
1021 {
1022         struct ast_config_engine *eng;
1023         int res = -1;
1024         char db[256]="";
1025         char table[256]="";
1026         va_list ap;
1027
1028         va_start(ap, lookup);
1029         eng = find_engine(family, db, sizeof(db), table, sizeof(table));
1030         if (eng && eng->update_func) 
1031                 res = eng->update_func(db, table, keyfield, lookup, ap);
1032         va_end(ap);
1033
1034         return res;
1035 }
1036
1037 static int config_command(int fd, int argc, char **argv) 
1038 {
1039         struct ast_config_engine *eng;
1040         struct ast_config_map *map;
1041         
1042         ast_mutex_lock(&config_lock);
1043
1044         ast_cli(fd, "\n\n");
1045         for (eng = config_engine_list; eng; eng = eng->next) {
1046                 ast_cli(fd, "\nConfig Engine: %s\n", eng->name);
1047                 for (map = config_maps; map; map = map->next)
1048                         if (!strcasecmp(map->driver, eng->name)) {
1049                                 ast_cli(fd, "===> %s (db=%s, table=%s)\n", map->name, map->database,
1050                                         map->table ? map->table : map->name);
1051                         }
1052         }
1053         ast_cli(fd,"\n\n");
1054         
1055         ast_mutex_unlock(&config_lock);
1056
1057         return 0;
1058 }
1059
1060 static char show_config_help[] =
1061         "Usage: show config mappings\n"
1062         "       Shows the filenames to config engines.\n";
1063
1064 static struct ast_cli_entry config_command_struct = {
1065         { "show", "config", "mappings", NULL }, config_command, "Show Config mappings (file names to config engines)", show_config_help, NULL
1066 };
1067
1068 int register_config_cli() 
1069 {
1070         return ast_cli_register(&config_command_struct);
1071 }