issue #5638
[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  * Includes the Asterisk Realtime API - ARA
24  * See README.realtime
25  */
26
27 #include <stdio.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <errno.h>
32 #include <time.h>
33 #include <sys/stat.h>
34 #define AST_INCLUDE_GLOB 1
35 #ifdef AST_INCLUDE_GLOB
36 #if defined(__Darwin__) || defined(__CYGWIN__)
37 #define GLOB_ABORTED GLOB_ABEND
38 #endif
39 # include <glob.h>
40 #endif
41
42 #include "asterisk.h"
43
44 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
45
46 #include "asterisk/config.h"
47 #include "asterisk/cli.h"
48 #include "asterisk/lock.h"
49 #include "asterisk/options.h"
50 #include "asterisk/logger.h"
51 #include "asterisk/utils.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/app.h"
54
55 #define MAX_NESTED_COMMENTS 128
56 #define COMMENT_START ";--"
57 #define COMMENT_END "--;"
58 #define COMMENT_META ';'
59 #define COMMENT_TAG '-'
60
61 static char *extconfig_conf = "extconfig.conf";
62
63 static struct ast_config_map {
64         struct ast_config_map *next;
65         char *name;
66         char *driver;
67         char *database;
68         char *table;
69         char stuff[0];
70 } *config_maps = NULL;
71
72 AST_MUTEX_DEFINE_STATIC(config_lock);
73 static struct ast_config_engine *config_engine_list;
74
75 #define MAX_INCLUDE_LEVEL 10
76
77 struct ast_comment {
78         struct ast_comment *next;
79         char cmt[0];
80 };
81
82 struct ast_category {
83         char name[80];
84         int ignored;                    /* do not let user of the config see this category */
85         struct ast_variable *root;
86         struct ast_variable *last;
87         struct ast_category *next;
88 };
89
90 struct ast_config {
91         struct ast_category *root;
92         struct ast_category *last;
93         struct ast_category *current;
94         struct ast_category *last_browse;               /* used to cache the last category supplied via category_browse */
95         int include_level;
96         int max_include_level;
97 };
98
99 struct ast_variable *ast_variable_new(const char *name, const char *value) 
100 {
101         struct ast_variable *variable;
102
103         int length = strlen(name) + strlen(value) + 2 + sizeof(struct ast_variable);
104         variable = malloc(length);
105         if (variable) {
106                 memset(variable, 0, length);
107                 variable->name = variable->stuff;
108                 variable->value = variable->stuff + strlen(name) + 1;           
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         category = malloc(sizeof(struct ast_category));
205         if (category) {
206                 memset(category, 0, sizeof(struct ast_category));
207                 ast_copy_string(category->name, name, sizeof(category->name));
208         }
209
210         return category;
211 }
212
213 static struct ast_category *category_get(const struct ast_config *config, const char *category_name, int ignored)
214 {
215         struct ast_category *cat;
216
217         for (cat = config->root; cat; cat = cat->next) {
218                 if (cat->name == category_name && (ignored || !cat->ignored))
219                         return cat;
220         }
221
222         for (cat = config->root; cat; cat = cat->next) {
223                 if (!strcasecmp(cat->name, category_name) && (ignored || !cat->ignored))
224                         return cat;
225         }
226
227         return NULL;
228 }
229
230 struct ast_category *ast_category_get(const struct ast_config *config, const char *category_name)
231 {
232         return category_get(config, category_name, 0);
233 }
234
235 int ast_category_exist(const struct ast_config *config, const char *category_name)
236 {
237         return !!ast_category_get(config, category_name);
238 }
239
240 void ast_category_append(struct ast_config *config, struct ast_category *category)
241 {
242         if (config->last)
243                 config->last->next = category;
244         else
245                 config->root = category;
246         config->last = category;
247         config->current = category;
248 }
249
250 void ast_category_destroy(struct ast_category *cat)
251 {
252         ast_variables_destroy(cat->root);
253         free(cat);
254 }
255
256 static struct ast_category *next_available_category(struct ast_category *cat)
257 {
258         for (; cat && cat->ignored; cat = cat->next);
259
260         return cat;
261 }
262
263 char *ast_category_browse(struct ast_config *config, const char *prev)
264 {       
265         struct ast_category *cat = NULL;
266
267         if (prev && config->last_browse && (config->last_browse->name == prev))
268                 cat = config->last_browse->next;
269         else if (!prev && config->root)
270                         cat = config->root;
271         else if (prev) {
272                 for (cat = config->root; cat; cat = cat->next) {
273                         if (cat->name == prev) {
274                                 cat = cat->next;
275                                 break;
276                         }
277                 }
278                 if (!cat) {
279                         for (cat = config->root; cat; cat = cat->next) {
280                                 if (!strcasecmp(cat->name, prev)) {
281                                         cat = cat->next;
282                                         break;
283                                 }
284                         }
285                 }
286         }
287         
288         if (cat)
289                 cat = next_available_category(cat);
290
291         config->last_browse = cat;
292         if (cat)
293                 return cat->name;
294         else
295                 return NULL;
296 }
297
298 struct ast_variable *ast_category_detach_variables(struct ast_category *cat)
299 {
300         struct ast_variable *v;
301
302         v = cat->root;
303         cat->root = NULL;
304
305         return v;
306 }
307
308 void ast_category_rename(struct ast_category *cat, const char *name)
309 {
310         ast_copy_string(cat->name, name, sizeof(cat->name));
311 }
312
313 static void inherit_category(struct ast_category *new, const struct ast_category *base)
314 {
315         struct ast_variable *var;
316
317         for (var = base->root; var; var = var->next) {
318                 struct ast_variable *v;
319                 
320                 v = variable_clone(var);
321                 if (v)
322                         ast_variable_append(new, v);
323         }
324 }
325
326 struct ast_config *ast_config_new(void) 
327 {
328         struct ast_config *config;
329
330         config = malloc(sizeof(*config));
331         if (config) {
332                 memset(config, 0, sizeof(*config));
333                 config->max_include_level = MAX_INCLUDE_LEVEL;
334         }
335
336         return config;
337 }
338
339 void ast_config_destroy(struct ast_config *cfg)
340 {
341         struct ast_category *cat, *catn;
342
343         if (!cfg)
344                 return;
345
346         cat = cfg->root;
347         while(cat) {
348                 ast_variables_destroy(cat->root);
349                 catn = cat;
350                 cat = cat->next;
351                 free(catn);
352         }
353         free(cfg);
354 }
355
356 struct ast_category *ast_config_get_current_category(const struct ast_config *cfg)
357 {
358         return cfg->current;
359 }
360
361 void ast_config_set_current_category(struct ast_config *cfg, const struct ast_category *cat)
362 {
363         /* cast below is just to silence compiler warning about dropping "const" */
364         cfg->current = (struct ast_category *) cat;
365 }
366
367 static int process_text_line(struct ast_config *cfg, struct ast_category **cat, char *buf, int lineno, const char *configfile)
368 {
369         char *c;
370         char *cur = buf;
371         struct ast_variable *v;
372         char cmd[512], exec_file[512];
373         int object, do_exec, do_include;
374
375         /* Actually parse the entry */
376         if (cur[0] == '[') {
377                 struct ast_category *newcat = NULL;
378                 char *catname;
379
380                 /* A category header */
381                 c = strchr(cur, ']');
382                 if (!c) {
383                         ast_log(LOG_WARNING, "parse error: no closing ']', line %d of %s\n", lineno, configfile);
384                         return -1;
385                 }
386                 *c++ = '\0';
387                 cur++;
388                 if (*c++ != '(')
389                         c = NULL;
390                 catname = cur;
391                 *cat = newcat = ast_category_new(catname);
392                 if (!newcat) {
393                         ast_log(LOG_WARNING, "Out of memory, line %d of %s\n", lineno, configfile);
394                         return -1;
395                 }
396                 /* If there are options or categories to inherit from, process them now */
397                 if (c) {
398                         if (!(cur = strchr(c, ')'))) {
399                                 ast_log(LOG_WARNING, "parse error: no closing ')', line %d of %s\n", lineno, configfile);
400                                 return -1;
401                         }
402                         *cur = '\0';
403                         while ((cur = strsep(&c, ","))) {
404                                 if (!strcasecmp(cur, "!")) {
405                                         (*cat)->ignored = 1;
406                                 } else if (!strcasecmp(cur, "+")) {
407                                         *cat = category_get(cfg, catname, 1);
408                                         if (!*cat) {
409                                                 ast_config_destroy(cfg);
410                                                 if (newcat)
411                                                         ast_category_destroy(newcat);
412                                                 ast_log(LOG_WARNING, "Category addition requested, but category '%s' does not exist, line %d of %s\n", catname, lineno, configfile);
413                                                 return -1;
414                                         }
415                                         if (newcat) {
416                                                 move_variables(newcat, *cat);
417                                                 ast_category_destroy(newcat);
418                                                 newcat = NULL;
419                                         }
420                                 } else {
421                                         struct ast_category *base;
422                                 
423                                         base = category_get(cfg, cur, 1);
424                                         if (!base) {
425                                                 ast_log(LOG_WARNING, "Inheritance requested, but category '%s' does not exist, line %d of %s\n", cur, lineno, configfile);
426                                                 return -1;
427                                         }
428                                         inherit_category(*cat, base);
429                                 }
430                         }
431                 }
432                 if (newcat)
433                         ast_category_append(cfg, *cat);
434         } else if (cur[0] == '#') {
435                 /* A directive */
436                 cur++;
437                 c = cur;
438                 while(*c && (*c > 32)) c++;
439                 if (*c) {
440                         *c = '\0';
441                         c++;
442                         /* Find real argument */
443                         while(*c  && (*c < 33)) c++;
444                         if (!*c)
445                                 c = NULL;
446                 } else 
447                         c = NULL;
448                 do_include = !strcasecmp(cur, "include");
449                 if(!do_include)
450                         do_exec = !strcasecmp(cur, "exec");
451                 else
452                         do_exec = 0;
453                 if (do_exec && !option_exec_includes) {
454                         ast_log(LOG_WARNING, "Cannot perform #exec unless execincludes option is enabled in asterisk.conf (options section)!\n");
455                         do_exec = 0;
456                 }
457                 if (do_include || do_exec) {
458                         if (c) {
459                                 /* Strip off leading and trailing "'s and <>'s */
460                                 while((*c == '<') || (*c == '>') || (*c == '\"')) c++;
461                                 /* Get rid of leading mess */
462                                 cur = c;
463                                 while (!ast_strlen_zero(cur)) {
464                                         c = cur + strlen(cur) - 1;
465                                         if ((*c == '>') || (*c == '<') || (*c == '\"'))
466                                                 *c = '\0';
467                                         else
468                                                 break;
469                                 }
470                                 /* #exec </path/to/executable>
471                                    We create a tmp file, then we #include it, then we delete it. */
472                                 if (do_exec) { 
473                                         snprintf(exec_file, sizeof(exec_file), "/var/tmp/exec.%ld.%ld", time(NULL), (long)pthread_self());
474                                         snprintf(cmd, sizeof(cmd), "%s > %s 2>&1", cur, exec_file);
475                                         ast_safe_system(cmd);
476                                         cur = exec_file;
477                                 } else
478                                         exec_file[0] = '\0';
479                                 /* A #include */
480                                 do_include = ast_config_internal_load(cur, cfg) ? 1 : 0;
481                                 if(!ast_strlen_zero(exec_file))
482                                         unlink(exec_file);
483                                 if(!do_include)
484                                         return 0;
485
486                         } else {
487                                 ast_log(LOG_WARNING, "Directive '#%s' needs an argument (%s) at line %d of %s\n", 
488                                                 do_exec ? "exec" : "include",
489                                                 do_exec ? "/path/to/executable" : "filename",
490                                                 lineno,
491                                                 configfile);
492                         }
493                 }
494                 else 
495                         ast_log(LOG_WARNING, "Unknown directive '%s' at line %d of %s\n", cur, lineno, configfile);
496         } else {
497                 /* Just a line (variable = value) */
498                 if (!*cat) {
499                         ast_log(LOG_WARNING,
500                                 "parse error: No category context for line %d of %s\n", lineno, configfile);
501                         return -1;
502                 }
503                 c = strchr(cur, '=');
504                 if (c) {
505                         *c = 0;
506                         c++;
507                         /* Ignore > in => */
508                         if (*c== '>') {
509                                 object = 1;
510                                 c++;
511                         } else
512                                 object = 0;
513                         v = ast_variable_new(ast_strip(cur), ast_strip(c));
514                         if (v) {
515                                 v->lineno = lineno;
516                                 v->object = object;
517                                 /* Put and reset comments */
518                                 v->blanklines = 0;
519                                 ast_variable_append(*cat, v);
520                         } else {
521                                 ast_log(LOG_WARNING, "Out of memory, line %d\n", lineno);
522                                 return -1;
523                         }
524                 } else {
525                         ast_log(LOG_WARNING, "No '=' (equal sign) in line %d of %s\n", lineno, configfile);
526                 }
527
528         }
529         return 0;
530 }
531
532 static struct ast_config *config_text_file_load(const char *database, const char *table, const char *filename, struct ast_config *cfg)
533 {
534         char fn[256];
535         char buf[8192];
536         char *new_buf, *comment_p, *process_buf;
537         FILE *f;
538         int lineno=0;
539         int comment = 0, nest[MAX_NESTED_COMMENTS];
540         struct ast_category *cat = NULL;
541         int count = 0;
542         struct stat statbuf;
543         
544         cat = ast_config_get_current_category(cfg);
545
546         if (filename[0] == '/') {
547                 ast_copy_string(fn, filename, sizeof(fn));
548         } else {
549                 snprintf(fn, sizeof(fn), "%s/%s", (char *)ast_config_AST_CONFIG_DIR, filename);
550         }
551
552 #ifdef AST_INCLUDE_GLOB
553         {
554                 int glob_ret;
555                 glob_t globbuf;
556                 globbuf.gl_offs = 0;    /* initialize it to silence gcc */
557 #ifdef SOLARIS
558                 glob_ret = glob(fn, GLOB_NOCHECK, NULL, &globbuf);
559 #else
560                 glob_ret = glob(fn, GLOB_NOMAGIC|GLOB_BRACE, NULL, &globbuf);
561 #endif
562                 if (glob_ret == GLOB_NOSPACE)
563                         ast_log(LOG_WARNING,
564                                 "Glob Expansion of pattern '%s' failed: Not enough memory\n", fn);
565                 else if (glob_ret  == GLOB_ABORTED)
566                         ast_log(LOG_WARNING,
567                                 "Glob Expansion of pattern '%s' failed: Read error\n", fn);
568                 else  {
569                         /* loop over expanded files */
570                         int i;
571                         for (i=0; i<globbuf.gl_pathc; i++) {
572                                 ast_copy_string(fn, globbuf.gl_pathv[i], sizeof(fn));
573 #endif
574         do {
575                 if (stat(fn, &statbuf))
576                         continue;
577
578                 if (!S_ISREG(statbuf.st_mode)) {
579                         ast_log(LOG_WARNING, "'%s' is not a regular file, ignoring\n", fn);
580                         continue;
581                 }
582                 if ((option_verbose > 1) && !option_debug) {
583                         ast_verbose(VERBOSE_PREFIX_2 "Parsing '%s': ", fn);
584                         fflush(stdout);
585                 }
586                 if (!(f = fopen(fn, "r"))) {
587                         if (option_debug)
588                                 ast_log(LOG_DEBUG, "No file to parse: %s\n", fn);
589                         else if (option_verbose > 1)
590                                 ast_verbose( "Not found (%s)\n", strerror(errno));
591                         continue;
592                 }
593                 count++;
594                 if (option_debug)
595                         ast_log(LOG_DEBUG, "Parsing %s\n", fn);
596                 else if (option_verbose > 1)
597                         ast_verbose("Found\n");
598                 while(!feof(f)) {
599                         lineno++;
600                         if (fgets(buf, sizeof(buf), f)) {
601                                 new_buf = buf;
602                                 if (comment)
603                                         process_buf = NULL;
604                                 else
605                                         process_buf = buf;
606                                 while ((comment_p = strchr(new_buf, COMMENT_META))) {
607                                         if ((comment_p > new_buf) && (*(comment_p-1) == '\\')) {
608                                                 /* Yuck, gotta memmove */
609                                                 memmove(comment_p - 1, comment_p, strlen(comment_p) + 1);
610                                                 new_buf = comment_p;
611                                         } else if(comment_p[1] == COMMENT_TAG && comment_p[2] == COMMENT_TAG && (comment_p[3] != '-')) {
612                                                 /* Meta-Comment start detected ";--" */
613                                                 if (comment < MAX_NESTED_COMMENTS) {
614                                                         *comment_p = '\0';
615                                                         new_buf = comment_p + 3;
616                                                         comment++;
617                                                         nest[comment-1] = lineno;
618                                                 } else {
619                                                         ast_log(LOG_ERROR, "Maximum nest limit of %d reached.\n", MAX_NESTED_COMMENTS);
620                                                 }
621                                         } else if ((comment_p >= new_buf + 2) &&
622                                                    (*(comment_p - 1) == COMMENT_TAG) &&
623                                                    (*(comment_p - 2) == COMMENT_TAG)) {
624                                                 /* Meta-Comment end detected */
625                                                 comment--;
626                                                 new_buf = comment_p + 1;
627                                                 if (!comment) {
628                                                         /* Back to non-comment now */
629                                                         if (process_buf) {
630                                                                 /* Actually have to move what's left over the top, then continue */
631                                                                 char *oldptr;
632                                                                 oldptr = process_buf + strlen(process_buf);
633                                                                 memmove(oldptr, new_buf, strlen(new_buf) + 1);
634                                                                 new_buf = oldptr;
635                                                         } else
636                                                                 process_buf = new_buf;
637                                                 }
638                                         } else {
639                                                 if (!comment) {
640                                                         /* If ; is found, and we are not nested in a comment, 
641                                                            we immediately stop all comment processing */
642                                                         *comment_p = '\0'; 
643                                                         new_buf = comment_p;
644                                                 } else
645                                                         new_buf = comment_p + 1;
646                                         }
647                                 }
648                                 if (process_buf) {
649                                         char *buf = ast_strip(process_buf);
650                                         if (!ast_strlen_zero(buf)) {
651                                                 if (process_text_line(cfg, &cat, buf, lineno, filename)) {
652                                                         cfg = NULL;
653                                                         break;
654                                                 }
655                                         }
656                                 }
657                         }
658                 }
659                 fclose(f);              
660         } while(0);
661         if (comment) {
662                 ast_log(LOG_WARNING,"Unterminated comment detected beginning on line %d\n", nest[comment]);
663         }
664 #ifdef AST_INCLUDE_GLOB
665                                         if (!cfg)
666                                                 break;
667                                 }
668                                 globfree(&globbuf);
669                         }
670                 }
671 #endif
672         if (count == 0)
673                 return NULL;
674
675         return cfg;
676 }
677
678 int config_text_file_save(const char *configfile, const struct ast_config *cfg, const char *generator)
679 {
680         FILE *f;
681         char fn[256];
682         char date[256]="";
683         time_t t;
684         struct ast_variable *var;
685         struct ast_category *cat;
686         int blanklines = 0;
687
688         if (configfile[0] == '/') {
689                 ast_copy_string(fn, configfile, sizeof(fn));
690         } else {
691                 snprintf(fn, sizeof(fn), "%s/%s", ast_config_AST_CONFIG_DIR, configfile);
692         }
693         time(&t);
694         ast_copy_string(date, ctime(&t), sizeof(date));
695 #ifdef __CYGWIN__       
696         if ((f = fopen(fn, "w+"))) {
697 #else
698         if ((f = fopen(fn, "w"))) {
699 #endif      
700                 if ((option_verbose > 1) && !option_debug)
701                         ast_verbose(  VERBOSE_PREFIX_2 "Saving '%s': ", fn);
702                 fprintf(f, ";!\n");
703                 fprintf(f, ";! Automatically generated configuration file\n");
704                 fprintf(f, ";! Filename: %s (%s)\n", configfile, fn);
705                 fprintf(f, ";! Generator: %s\n", generator);
706                 fprintf(f, ";! Creation Date: %s", date);
707                 fprintf(f, ";!\n");
708                 cat = cfg->root;
709                 while(cat) {
710                         /* Dump section with any appropriate comment */
711                         fprintf(f, "[%s]\n", cat->name);
712                         var = cat->root;
713                         while(var) {
714                                 if (var->sameline) 
715                                         fprintf(f, "%s %s %s  ; %s\n", var->name, (var->object ? "=>" : "="), var->value, var->sameline->cmt);
716                                 else    
717                                         fprintf(f, "%s %s %s\n", var->name, (var->object ? "=>" : "="), var->value);
718                                 if (var->blanklines) {
719                                         blanklines = var->blanklines;
720                                         while (blanklines--)
721                                                 fprintf(f, "\n");
722                                 }
723                                         
724                                 var = var->next;
725                         }
726 #if 0
727                         /* Put an empty line */
728                         fprintf(f, "\n");
729 #endif
730                         cat = cat->next;
731                 }
732         } else {
733                 if (option_debug)
734                         printf("Unable to open for writing: %s\n", fn);
735                 else if (option_verbose > 1)
736                         printf( "Unable to write (%s)", strerror(errno));
737                 return -1;
738         }
739         fclose(f);
740         return 0;
741 }
742
743 static void clear_config_maps(void) 
744 {
745         struct ast_config_map *map;
746
747         ast_mutex_lock(&config_lock);
748
749         while (config_maps) {
750                 map = config_maps;
751                 config_maps = config_maps->next;
752                 free(map);
753         }
754                 
755         ast_mutex_unlock(&config_lock);
756 }
757
758 static int append_mapping(char *name, char *driver, char *database, char *table)
759 {
760         struct ast_config_map *map;
761         int length;
762
763         length = sizeof(*map);
764         length += strlen(name) + 1;
765         length += strlen(driver) + 1;
766         length += strlen(database) + 1;
767         if (table)
768                 length += strlen(table) + 1;
769         map = malloc(length);
770
771         if (!map)
772                 return -1;
773
774         memset(map, 0, length);
775         map->name = map->stuff;
776         strcpy(map->name, name);
777         map->driver = map->name + strlen(map->name) + 1;
778         strcpy(map->driver, driver);
779         map->database = map->driver + strlen(map->driver) + 1;
780         strcpy(map->database, database);
781         if (table) {
782                 map->table = map->database + strlen(map->database) + 1;
783                 strcpy(map->table, table);
784         }
785         map->next = config_maps;
786
787         if (option_verbose > 1)
788                 ast_verbose(VERBOSE_PREFIX_2 "Binding %s to %s/%s/%s\n",
789                             map->name, map->driver, map->database, map->table ? map->table : map->name);
790
791         config_maps = map;
792         return 0;
793 }
794
795 void read_config_maps(void) 
796 {
797         struct ast_config *config, *configtmp;
798         struct ast_variable *v;
799         char *driver, *table, *database, *stringp;
800
801         clear_config_maps();
802
803         configtmp = ast_config_new();
804         configtmp->max_include_level = 1;
805         config = ast_config_internal_load(extconfig_conf, configtmp);
806         if (!config) {
807                 ast_config_destroy(configtmp);
808                 return;
809         }
810
811         for (v = ast_variable_browse(config, "settings"); v; v = v->next) {
812                 stringp = v->value;
813                 driver = strsep(&stringp, ",");
814                 database = strsep(&stringp, ",");
815                 table = strsep(&stringp, ",");
816                         
817                 if (!strcmp(v->name, extconfig_conf)) {
818                         ast_log(LOG_WARNING, "Cannot bind '%s'!\n", extconfig_conf);
819                         continue;
820                 }
821
822                 if (!strcmp(v->name, "asterisk.conf")) {
823                         ast_log(LOG_WARNING, "Cannot bind 'asterisk.conf'!\n");
824                         continue;
825                 }
826
827                 if (!strcmp(v->name, "logger.conf")) {
828                         ast_log(LOG_WARNING, "Cannot bind 'logger.conf'!\n");
829                         continue;
830                 }
831
832                 if (!driver || !database)
833                         continue;
834                 if (!strcasecmp(v->name, "sipfriends")) {
835                         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");
836                         append_mapping("sipusers", driver, database, table ? table : "sipfriends");
837                         append_mapping("sippeers", driver, database, table ? table : "sipfriends");
838                 } else if (!strcasecmp(v->name, "iaxfriends")) {
839                         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");
840                         append_mapping("iaxusers", driver, database, table ? table : "iaxfriends");
841                         append_mapping("iaxpeers", driver, database, table ? table : "iaxfriends");
842                 } else 
843                         append_mapping(v->name, driver, database, table);
844         }
845                 
846         ast_config_destroy(config);
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 /*--- find_engine: 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 /*--- ast_check_realtime: 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 }