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