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