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