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