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