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