Merged revisions 19345 via svnmerge from
[asterisk/asterisk.git] / pbx / pbx_config.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, 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 Populate and remember extensions from static config file
22  *
23  * 
24  */
25
26 #include <sys/types.h>
27 #include <stdlib.h>
28 #include <stdio.h>
29 #include <string.h>
30 #include <ctype.h>
31 #include <errno.h>
32
33 #define STATIC_MODULE
34
35 #include "asterisk.h"
36
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38
39 #include "asterisk/pbx.h"
40 #include "asterisk/config.h"
41 #include "asterisk/options.h"
42 #include "asterisk/module.h"
43 #include "asterisk/logger.h"
44 #include "asterisk/cli.h"
45 #include "asterisk/callerid.h"
46
47 #ifdef __AST_DEBUG_MALLOC
48 static void FREE(void *ptr)
49 {
50         free(ptr);
51 }
52 #else
53 #define FREE free
54 #endif
55
56 static char *dtext = "Text Extension Configuration";
57 static char *config = "extensions.conf";
58 static char *registrar = "pbx_config";
59
60 static int static_config = 0;
61 static int write_protect_config = 1;
62 static int autofallthrough_config = 0;
63 static int clearglobalvars_config = 0;
64
65 AST_MUTEX_DEFINE_STATIC(save_dialplan_lock);
66
67 static struct ast_context *local_contexts = NULL;
68
69 /*
70  * Help for commands provided by this module ...
71  */
72 static char context_dont_include_help[] =
73 "Usage: dont include <context> in <context>\n"
74 "       Remove an included context from another context.\n";
75
76 static char context_remove_extension_help[] =
77 "Usage: remove extension exten@context [priority]\n"
78 "       Remove an extension from a given context. If a priority\n"
79 "       is given, only that specific priority from the given extension\n"
80 "       will be removed.\n";
81
82 static char context_add_include_help[] =
83 "Usage: include <context> in <context>\n"
84 "       Include a context in another context.\n";
85
86 static char save_dialplan_help[] =
87 "Usage: save dialplan [/path/to/extension/file]\n"
88 "       Save dialplan created by pbx_config module.\n"
89 "\n"
90 "Example: save dialplan                 (/etc/asterisk/extensions.conf)\n"
91 "         save dialplan /home/markster  (/home/markster/extensions.conf)\n";
92
93 static char context_add_extension_help[] =
94 "Usage: add extension <exten>,<priority>,<app>,<app-data> into <context>\n"
95 "       [replace]\n\n"
96 "       This command will add new extension into <context>. If there is an\n"
97 "       existence of extension with the same priority and last 'replace'\n"
98 "       arguments is given here we simply replace this extension.\n"
99 "\n"
100 "Example: add extension 6123,1,Dial,IAX/216.207.245.56/6123 into local\n"
101 "         Now, you can dial 6123 and talk to Markster :)\n";
102
103 static char context_add_ignorepat_help[] =
104 "Usage: add ignorepat <pattern> into <context>\n"
105 "       This command adds a new ignore pattern into context <context>\n"
106 "\n"
107 "Example: add ignorepat _3XX into local\n";
108
109 static char context_remove_ignorepat_help[] =
110 "Usage: remove ignorepat <pattern> from <context>\n"
111 "       This command removes an ignore pattern from context <context>\n"
112 "\n"
113 "Example: remove ignorepat _3XX from local\n";
114
115 static char reload_extensions_help[] =
116 "Usage: reload extensions.conf without reloading any other modules\n"
117 "       This command does not delete global variables unless\n"
118 "       clearglobalvars is set to yes in extensions.conf\n"
119 "\n"
120 "Example: extensions reload\n";
121
122 /*
123  * Implementation of functions provided by this module
124  */
125
126 /*!
127  * REMOVE INCLUDE command stuff
128  */
129 static int handle_context_dont_include(int fd, int argc, char *argv[])
130 {
131         if (argc != 5)
132                 return RESULT_SHOWUSAGE;
133
134         if (strcmp(argv[3], "in"))
135                 return RESULT_SHOWUSAGE;
136
137         if (!ast_context_remove_include(argv[4], argv[2], registrar)) {
138                 ast_cli(fd, "We are not including '%s' in '%s' now\n",
139                         argv[2], argv[4]);
140                 return RESULT_SUCCESS;
141         }
142
143         ast_cli(fd, "Failed to remove '%s' include from '%s' context\n",
144                 argv[2], argv[4]);
145         return RESULT_FAILURE;
146 }
147
148 /*! \brief return true if 'name' is included by context c */
149 static int lookup_ci(struct ast_context *c, const char *name)
150 {
151         struct ast_include *i = NULL;
152
153         if (ast_lock_context(c))        /* error, skip */
154                 return 0;
155         while ( (i = ast_walk_context_includes(c, i)) )
156                 if (!strcmp(name, ast_get_include_name(i)))
157                         break;
158         ast_unlock_context(c);
159         return i ? -1 /* success */ : 0;
160 }
161
162 /*! \brief return true if 'name' is in the ignorepats for context c */
163 static int lookup_c_ip(struct ast_context *c, const char *name)
164 {
165         struct ast_ignorepat *ip = NULL;
166
167         if (ast_lock_context(c))        /* error, skip */
168                 return 0;
169         while ( (ip = ast_walk_context_ignorepats(c, ip)) )
170                 if (!strcmp(name, ast_get_ignorepat_name(ip)))
171                         break;
172         ast_unlock_context(c);
173         return ip ? -1 /* success */ : 0;
174 }
175
176 /*! \brief moves to the n-th word in the string, or empty string if none */
177 static const char *skip_words(const char *p, int n)
178 {
179         int in_blank = 0;
180         for (;n && *p; p++) {
181                 if (isblank(*p) /* XXX order is important */ && !in_blank) {
182                         n--;    /* one word is gone */
183                         in_blank = 1;
184                 } else if (/* !is_blank(*p), we know already, && */ in_blank) {
185                         in_blank = 0;
186                 }
187         }
188         return p;
189 }
190
191 /*! \brief match the first 'len' chars of word. len==0 always succeeds */
192 static int partial_match(const char *s, const char *word, int len)
193 {
194         return (len == 0 || !strncmp(s, word, len));
195 }
196
197 /*! \brief split extension@context in two parts, return -1 on error.
198  * The return string is malloc'ed and pointed by *ext
199  */
200 static int split_ec(const char *src, char **ext, char ** const ctx)
201 {
202         char *c, *e = ast_strdup(src); /* now src is not used anymore */
203
204         if (e == NULL)
205                 return -1;      /* malloc error */
206         /* now, parse values from 'exten@context' */
207         *ext = e;
208         c = strchr(e, '@');
209         if (c == NULL)  /* no context part */
210                 *ctx = "";      /* it is not overwritten, anyways */
211         else {  /* found context, check for duplicity ... */
212                 *c++ = '\0';
213                 *ctx = c;
214                 if (strchr(c, '@')) { /* two @, not allowed */
215                         free(e);
216                         return -1;
217                 }
218         } 
219         return 0;
220 }
221
222 /* _X_ is the string we need to complete */
223 static char *complete_context_dont_include(const char *line, const char *word,
224         int pos, int state)
225 {
226         int which = 0;
227         char *res = NULL;
228         int len = strlen(word); /* how many bytes to match */
229         struct ast_context *c = NULL;
230
231         if (pos == 2) {         /* "dont include _X_" */
232                 if (ast_lock_contexts()) {
233                         ast_log(LOG_ERROR, "Failed to lock context list\n");
234                         return NULL;
235                 }
236                 /* walk contexts and their includes, return the n-th match */
237                 while (!res && (c = ast_walk_contexts(c))) {
238                         struct ast_include *i = NULL;
239
240                         if (ast_lock_context(c))        /* error ? skip this one */
241                                 continue;
242
243                         while ( !res && (i = ast_walk_context_includes(c, i)) ) {
244                                 const char *i_name = ast_get_include_name(i);
245                                 struct ast_context *nc = NULL;
246                                 int already_served = 0;
247
248                                 if (!partial_match(i_name, word, len))
249                                         continue;       /* not matched */
250
251                                 /* check if this include is already served or not */
252
253                                 /* go through all contexts again till we reach actual
254                                  * context or already_served = 1
255                                  */
256                                 while ( (nc = ast_walk_contexts(nc)) && nc != c && !already_served)
257                                         already_served = lookup_ci(nc, i_name);
258
259                                 if (!already_served && ++which > state)
260                                         res = strdup(i_name);
261                         }
262                         ast_unlock_context(c);
263                 }
264
265                 ast_unlock_contexts();
266                 return res;
267         } else if (pos == 3) { /* "dont include CTX _X_" */
268                 /*
269                  * complete as 'in', but only if previous context is really
270                  * included somewhere
271                  */
272                 char *context, *dupline;
273                 const char *s = skip_words(line, 2); /* skip 'dont' 'include' */
274
275                 if (state > 0)
276                         return NULL;
277                 context = dupline = strdup(s);
278                 if (!dupline) {
279                         ast_log(LOG_ERROR, "Out of free memory\n");
280                         return NULL;
281                 }
282                 strsep(&dupline, " ");
283
284                 if (ast_lock_contexts()) {
285                         ast_log(LOG_ERROR, "Failed to lock contexts list\n");
286                         free(context);
287                         return NULL;
288                 }
289
290                 /* go through all contexts and check if is included ... */
291                 while (!res && (c = ast_walk_contexts(c)))
292                         if (lookup_ci(c, context)) /* context is really included, complete "in" command */
293                                 res = strdup("in");
294                 ast_unlock_contexts();
295                 if (!res)
296                         ast_log(LOG_WARNING, "%s not included anywhere\n", context);
297                 free(context);
298                 return res;
299         } else if (pos == 4) { /* "dont include CTX in _X_" */
300                 /*
301                  * Context from which we removing include ... 
302                  */
303                 char *context, *dupline, *in;
304                 const char *s = skip_words(line, 2); /* skip 'dont' 'include' */
305                 context = dupline = strdup(s);
306                 if (!dupline) {
307                         ast_log(LOG_ERROR, "Out of free memory\n");
308                         return NULL;
309                 }
310
311                 strsep(&dupline, " "); /* skip context */
312
313                 /* third word must be 'in' */
314                 in = strsep(&dupline, " ");
315                 if (!in || strcmp(in, "in")) {
316                         free(context);
317                         return NULL;
318                 }
319
320                 if (ast_lock_contexts()) {
321                         ast_log(LOG_ERROR, "Failed to lock context list\n");
322                         free(context);
323                         return NULL;
324                 }
325
326                 /* walk through all contexts ... */
327                 c = NULL;
328                 while ( !res && (c = ast_walk_contexts(c))) {
329                         const char *c_name = ast_get_context_name(c);
330                         if (!partial_match(c_name, word, len))  /* not a good target */
331                                 continue;
332                         /* walk through all includes and check if it is our context */  
333                         if (lookup_ci(c, context) && ++which > state)
334                                 res = strdup(c_name);
335                 }
336                 ast_unlock_contexts();
337                 free(context);
338                 return res;
339         }
340
341         return NULL;
342 }
343
344 /*!
345  * REMOVE EXTENSION command stuff
346  */
347 static int handle_context_remove_extension(int fd, int argc, char *argv[])
348 {
349         int removing_priority = 0;
350         char *exten, *context;
351         int ret = RESULT_FAILURE;
352
353         if (argc != 4 && argc != 3) return RESULT_SHOWUSAGE;
354
355         /*
356          * Priority input checking ...
357          */
358         if (argc == 4) {
359                 char *c = argv[3];
360
361                 /* check for digits in whole parameter for right priority ...
362                  * why? because atoi (strtol) returns 0 if any characters in
363                  * string and whole extension will be removed, it's not good
364                  */
365                 if (!strcmp("hint", c))
366                         removing_priority = PRIORITY_HINT;
367                 else {
368                         while (*c && isdigit(*c))
369                                 c++;
370                         if (*c) { /* non-digit in string */
371                                 ast_cli(fd, "Invalid priority '%s'\n", argv[3]);
372                                 return RESULT_FAILURE;
373                         }
374                         removing_priority = atoi(argv[3]);
375                 }
376
377                 if (removing_priority == 0) {
378                         ast_cli(fd, "If you want to remove whole extension, please " \
379                                 "omit priority argument\n");
380                         return RESULT_FAILURE;
381                 }
382         }
383
384         /* XXX original overwrote argv[2] */
385         /*
386          * Format exten@context checking ...
387          */
388         if (split_ec(argv[2], &exten, &context))
389                 return RESULT_FAILURE; /* XXX malloc failure */
390         if ((!strlen(exten)) || (!(strlen(context)))) {
391                 ast_cli(fd, "Missing extension or context name in second argument '%s'\n",
392                         argv[2]);
393                 free(exten);
394                 return RESULT_FAILURE;
395         }
396
397         if (!ast_context_remove_extension(context, exten, removing_priority, registrar)) {
398                 if (!removing_priority)
399                         ast_cli(fd, "Whole extension %s@%s removed\n",
400                                 exten, context);
401                 else
402                         ast_cli(fd, "Extension %s@%s with priority %d removed\n",
403                                 exten, context, removing_priority);
404                         
405                 ret = RESULT_SUCCESS;
406         } else {
407                 ast_cli(fd, "Failed to remove extension %s@%s\n", exten, context);
408                 ret = RESULT_FAILURE;
409         }
410         free(exten);
411         return ret;
412 }
413
414 #define BROKEN_READLINE 1
415
416 #ifdef BROKEN_READLINE
417 /*
418  * There is one funny thing, when you have word like 300@ and you hit
419  * <tab>, you arguments will like as your word is '300 ', so it '@'
420  * characters acts sometimes as word delimiter and sometimes as a part
421  * of word
422  *
423  * This fix function, allocates new word variable and store here every
424  * time xxx@yyy always as one word and correct pos is set too
425  *
426  * It's ugly, I know, but I'm waiting for Mark suggestion if upper is
427  * bug or feature ...
428  */
429 static int fix_complete_args(const char *line, char **word, int *pos)
430 {
431         char *_line, *_strsep_line, *_previous_word = NULL, *_word = NULL;
432         int words = 0;
433
434         _line = strdup(line);
435
436         _strsep_line = _line;
437         while (_strsep_line) {
438                 _previous_word = _word;
439                 _word = strsep(&_strsep_line, " ");
440
441                 if (_word && strlen(_word)) words++;
442         }
443
444
445         if (_word || _previous_word) {
446                 if (_word) {
447                         if (!strlen(_word)) words++;
448                         *word = strdup(_word);
449                 } else
450                         *word = strdup(_previous_word);
451                 *pos = words - 1;
452                 free(_line);
453                 return 0;
454         }
455
456         free(_line);
457         return -1;
458 }
459 #endif /* BROKEN_READLINE */
460
461 static char *complete_context_remove_extension(const char *line, const char *word, int pos,
462         int state)
463 {
464         char *ret = NULL;
465         int which = 0;
466
467 #ifdef BROKEN_READLINE
468         char *word2;
469         /*
470          * Fix arguments, *word is a new allocated structure, REMEMBER to
471          * free *word when you want to return from this function ...
472          */
473         if (fix_complete_args(line, &word2, &pos)) {
474                 ast_log(LOG_ERROR, "Out of free memory\n");
475                 return NULL;
476         }
477         word = word2;
478 #endif
479
480         if (pos == 2) { /* 'remove extension _X_' (exten@context ... */
481                 struct ast_context *c = NULL;
482                 char *context = NULL, *exten = NULL;
483                 int le = 0;     /* length of extension */
484                 int lc = 0;     /* length of context */
485
486                 lc = split_ec(word, &exten, &context);
487 #ifdef BROKEN_READLINE
488                 free(word2);
489 #endif
490                 if (lc) /* error */
491                         return NULL;
492                 le = strlen(exten);
493                 lc = strlen(context);
494
495                 if (ast_lock_contexts()) {
496                         ast_log(LOG_ERROR, "Failed to lock context list\n");
497                         goto error2;
498                 }
499
500                 /* find our context ... */
501                 while ( (c = ast_walk_contexts(c)) ) {  /* match our context if any */
502                         struct ast_exten *e = NULL;
503                         /* XXX locking ? */
504                         if (!partial_match(ast_get_context_name(c), context, lc))
505                                 continue;       /* context not matched */
506                         while ( (e = ast_walk_context_extensions(c, e)) ) { /* try to complete extensions ... */
507                                 if ( partial_match(ast_get_extension_name(e), exten, le) && ++which > state) { /* n-th match */
508                                         /* If there is an extension then return exten@context. XXX otherwise ? */
509                                         if (exten)
510                                                 asprintf(&ret, "%s@%s", ast_get_extension_name(e), ast_get_context_name(c));
511                                         break;
512                                 }
513                         }
514                         if (e)  /* got a match */
515                                 break;
516                 }
517
518                 ast_unlock_contexts();
519         error2:
520                 if (exten)
521                         free(exten);
522         } else if (pos == 3) { /* 'remove extension EXT _X_' (priority) */
523                 char *exten = NULL, *context, *p;
524                 struct ast_context *c;
525                 int le, lc, len;
526                 const char *s = skip_words(line, 2); /* skip 'remove' 'extension' */
527                 int i = split_ec(s, &exten, &context);  /* parse ext@context */
528
529                 if (i)  /* error */
530                         goto error3;
531                 if ( (p = strchr(exten, ' ')) ) /* remove space after extension */
532                         *p = '\0';
533                 if ( (p = strchr(context, ' ')) ) /* remove space after context */
534                         *p = '\0';
535                 le = strlen(exten);
536                 lc = strlen(context);
537                 len = strlen(word);
538                 if (le == 0 || lc == 0)
539                         goto error3;
540
541                 if (ast_lock_contexts()) {
542                         ast_log(LOG_ERROR, "Failed to lock context list\n");
543                         goto error3;
544                 }
545
546                 /* walk contexts */
547                 c = NULL;
548                 while ( (c = ast_walk_contexts(c)) ) {
549                         /* XXX locking on c ? */
550                         struct ast_exten *e;
551                         if (strcmp(ast_get_context_name(c), context) != 0)
552                                 continue;
553                         /* got it, we must match here */
554                         e = NULL;
555                         while ( (e = ast_walk_context_extensions(c, e)) ) {
556                                 struct ast_exten *priority;
557                                 char buffer[10];
558
559                                 if (strcmp(ast_get_extension_name(e), exten) != 0)
560                                         continue;
561                                 /* XXX lock e ? */
562                                 priority = NULL;
563                                 while ( !ret && (priority = ast_walk_extension_priorities(e, priority)) ) {
564                                         snprintf(buffer, sizeof(buffer), "%u", ast_get_extension_priority(priority));
565                                         if (partial_match(buffer, word, len) && ++which > state) /* n-th match */
566                                                 ret = strdup(buffer);
567                                 }
568                                 break;
569                         }
570                         break;
571                 }
572                 ast_unlock_contexts();
573         error3:
574                 if (exten)
575                         free(exten);
576 #ifdef BROKEN_READLINE
577                 free(word2);
578 #endif
579         }
580         return ret; 
581 }
582
583 /*!
584  * Include context ...
585  */
586 static int handle_context_add_include(int fd, int argc, char *argv[])
587 {
588         if (argc != 5) /* include context CTX in CTX */
589                 return RESULT_SHOWUSAGE;
590
591         /* third arg must be 'in' ... */
592         if (strcmp(argv[3], "in") && strcmp(argv[3], "into")) /* XXX why both ? */
593                 return RESULT_SHOWUSAGE;
594
595         if (ast_context_add_include(argv[4], argv[2], registrar)) {
596                 switch (errno) {
597                 case ENOMEM:
598                         ast_cli(fd, "Out of memory for context addition\n");
599                         break;
600
601                 case EBUSY:
602                         ast_cli(fd, "Failed to lock context(s) list, please try again later\n");
603                         break;
604
605                 case EEXIST:
606                         ast_cli(fd, "Context '%s' already included in '%s' context\n",
607                                 argv[2], argv[4]);
608                         break;
609
610                 case ENOENT:
611                 case EINVAL:
612                         ast_cli(fd, "There is no existence of context '%s'\n",
613                                 errno == ENOENT ? argv[4] : argv[2]);
614                         break;
615
616                 default:
617                         ast_cli(fd, "Failed to include '%s' in '%s' context\n",
618                                 argv[2], argv[4]);
619                         break;
620                 }
621                 return RESULT_FAILURE;
622         }
623
624         /* show some info ... */
625         ast_cli(fd, "Context '%s' included in '%s' context\n",
626                 argv[2], argv[4]);
627
628         return RESULT_SUCCESS;
629 }
630
631 static char *complete_context_add_include(const char *line, const char *word, int pos,
632     int state)
633 {
634         struct ast_context *c;
635         int which = 0;
636         char *ret = NULL;
637         int len = strlen(word);
638
639         if (pos == 2) {         /* 'include context _X_' (context) ... */
640                 if (ast_lock_contexts()) {
641                         ast_log(LOG_ERROR, "Failed to lock context list\n");
642                         return NULL;
643                 }
644                 for (c = NULL; !ret && (c = ast_walk_contexts(c)); )
645                         if (partial_match(ast_get_context_name(c), word, len) && ++which > state)
646                                 ret = strdup(ast_get_context_name(c));
647                 ast_unlock_contexts();
648                 return ret;
649         } else if (pos == 3) { /* include context CTX _X_ */
650                 /* complete  as 'in' if context exists or we are unable to check */
651                 char *context, *dupline;
652                 struct ast_context *c;
653                 const char *s = skip_words(line, 2);    /* should not fail */
654
655                 if (state != 0) /* only once */
656                         return NULL;
657
658                 /* parse context from line ... */
659                 context = dupline = strdup(s);
660                 if (!context) {
661                         ast_log(LOG_ERROR, "Out of free memory\n");
662                         return strdup("in");
663                 }
664                 strsep(&dupline, " ");
665
666                 /* check for context existence ... */
667                 if (ast_lock_contexts()) {
668                         ast_log(LOG_ERROR, "Failed to lock context list\n");
669                         /* our fault, we can't check, so complete 'in' ... */
670                         ret = strdup("in");
671                 } else {
672                         for (c = NULL; !ret && (c = ast_walk_contexts(c)); )
673                                 if (!strcmp(context, ast_get_context_name(c)))
674                                         ret = strdup("in"); /* found */
675                         ast_unlock_contexts();
676                 }
677                 free(context);
678                 return ret;
679         } else if (pos == 4) { /* 'include context CTX in _X_' (dst context) */
680                 char *context, *dupline, *in;
681                 const char *s = skip_words(line, 2); /* should not fail */
682                 context = dupline = strdup(s);
683                 if (!dupline) {
684                         ast_log(LOG_ERROR, "Out of free memory\n");
685                         return NULL;
686                 }
687                 strsep(&dupline, " "); /* skip context */
688                 in = strsep(&dupline, " ");
689                 /* error if missing context or third word is not 'in' */
690                 if (!strlen(context) || strcmp(in, "in")) {
691                         ast_log(LOG_ERROR, "bad context %s or missing in %s\n",
692                                 context, in);
693                         goto error3;
694                 }
695
696                 if (ast_lock_contexts()) {
697                         ast_log(LOG_ERROR, "Failed to lock context list\n");
698                         goto error3;
699                 }
700
701                 for (c = NULL; (c = ast_walk_contexts(c)); )
702                         if (!strcmp(context, ast_get_context_name(c)))
703                                 break;
704                 if (c) { /* first context exists, go on... */
705                         /* go through all contexts ... */
706                         for (c = NULL; !ret && (c = ast_walk_contexts(c)); ) {
707                                 if (!strcmp(context, ast_get_context_name(c)))
708                                         continue; /* skip ourselves */
709                                 if (partial_match(ast_get_context_name(c), word, len) &&
710                                                 !lookup_ci(c, context) /* not included yet */ &&
711                                                 ++which > state)
712                                         ret = strdup(ast_get_context_name(c));
713                         }
714                 } else {
715                         ast_log(LOG_ERROR, "context %s not found\n", context);
716                 }
717                 ast_unlock_contexts();
718         error3:
719                 free(context);
720                 return ret;
721         }
722
723         return NULL;
724 }
725
726 /*!
727  * \brief 'save dialplan' CLI command implementation functions ...
728  */
729 static int handle_save_dialplan(int fd, int argc, char *argv[])
730 {
731         char filename[256];
732         struct ast_context *c;
733         struct ast_config *cfg;
734         struct ast_variable *v;
735         int incomplete = 0; /* incomplete config write? */
736         FILE *output;
737
738         const char *base, *slash, *file;
739
740         if (! (static_config && !write_protect_config)) {
741                 ast_cli(fd,
742                         "I can't save dialplan now, see '%s' example file.\n",
743                         config);
744                 return RESULT_FAILURE;
745         }
746
747         if (argc != 2 && argc != 3)
748                 return RESULT_SHOWUSAGE;
749
750         if (ast_mutex_lock(&save_dialplan_lock)) {
751                 ast_cli(fd,
752                         "Failed to lock dialplan saving (another proccess saving?)\n");
753                 return RESULT_FAILURE;
754         }
755         /* XXX the code here is quite loose, a pathname with .conf in it
756          * is assumed to be a complete pathname
757          */
758         if (argc == 3) {        /* have config path. Look for *.conf */
759                 base = argv[2];
760                 if (!strstr(argv[2], ".conf")) { /*no, this is assumed to be a pathname */
761                         /* if filename ends with '/', do not add one */
762                         slash = (*(argv[2] + strlen(argv[2]) -1) == '/') ? "/" : "";
763                         file = config;  /* default: 'extensions.conf' */
764                 } else {        /* yes, complete file name */
765                         slash = "";
766                         file = "";
767                 }
768         } else {
769                 /* no config file, default one */
770                 base = ast_config_AST_CONFIG_DIR;
771                 slash = "/";
772                 file = config;
773         }
774         snprintf(filename, sizeof(filename), "%s%s%s", base, slash, config);
775
776         cfg = ast_config_load("extensions.conf");
777
778         /* try to lock contexts list */
779         if (ast_lock_contexts()) {
780                 ast_cli(fd, "Failed to lock contexts list\n");
781                 ast_mutex_unlock(&save_dialplan_lock);
782                 ast_config_destroy(cfg);
783                 return RESULT_FAILURE;
784         }
785
786         /* create new file ... */
787         if (!(output = fopen(filename, "wt"))) {
788                 ast_cli(fd, "Failed to create file '%s'\n",
789                         filename);
790                 ast_unlock_contexts();
791                 ast_mutex_unlock(&save_dialplan_lock);
792                 ast_config_destroy(cfg);
793                 return RESULT_FAILURE;
794         }
795
796         /* fireout general info */
797         fprintf(output, "[general]\nstatic=%s\nwriteprotect=%s\n\n",
798                 static_config ? "yes" : "no",
799                 write_protect_config ? "yes" : "no");
800
801         if ((v = ast_variable_browse(cfg, "globals"))) {
802                 fprintf(output, "[globals]\n");
803                 while(v) {
804                         fprintf(output, "%s => %s\n", v->name, v->value);
805                         v = v->next;
806                 }
807                 fprintf(output, "\n");
808         }
809
810         ast_config_destroy(cfg);
811         
812 #define PUT_CTX_HDR     do { \
813         if (!context_header_written) {  \
814                 fprintf(output, "[%s]\n", ast_get_context_name(c));     \
815                 context_header_written = 1;     \
816         }       \
817         } while (0)
818
819         /* walk all contexts */
820         for (c = NULL; (c = ast_walk_contexts(c)); ) {
821                 int context_header_written = 0;
822                 struct ast_exten *e, *last_written_e = NULL;
823                 struct ast_include *i;
824                 struct ast_ignorepat *ip;
825                 struct ast_sw *sw;
826
827                 /* try to lock context and fireout all info */  
828                 if (ast_lock_context(c)) { /* lock failure */
829                         incomplete = 1;
830                         continue;
831                 }
832                 /* registered by this module? */
833                 /* XXX do we need this ? */
834                 if (!strcmp(ast_get_context_registrar(c), registrar)) {
835                         fprintf(output, "[%s]\n", ast_get_context_name(c));
836                         context_header_written = 1;
837                 }
838
839                 /* walk extensions ... */
840                 for (e = NULL; (e = ast_walk_context_extensions(c, e)); ) {
841                         struct ast_exten *p = NULL;
842
843                         /* fireout priorities */
844                         while ( (p = ast_walk_extension_priorities(e, p)) ) {
845                                 if (strcmp(ast_get_extension_registrar(p), registrar) != 0) /* not this source */
846                                         continue;
847                 
848                                 /* make empty line between different extensions */      
849                                 if (last_written_e != NULL &&
850                                             strcmp(ast_get_extension_name(last_written_e),
851                                                     ast_get_extension_name(p)))
852                                         fprintf(output, "\n");
853                                 last_written_e = p;
854                         
855                                 PUT_CTX_HDR;
856
857                                 if (ast_get_extension_priority(p)==PRIORITY_HINT) { /* easy */
858                                         fprintf(output, "exten => %s,hint,%s\n",
859                                                     ast_get_extension_name(p),
860                                                     ast_get_extension_app(p));
861                                 } else { /* copy and replace '|' with ',' */
862                                         const char *sep, *cid;
863                                         char *tempdata = strdup(ast_get_extension_app_data(p));
864                                         char *s;
865
866                                         if (!tempdata) { /* XXX error duplicating string ? */
867                                                 incomplete = 1;
868                                                 continue;
869                                         }
870                                         for (s = tempdata; *s; s++)
871                                                 if (*s == '|')
872                                                         *s = ',';
873                                         if (ast_get_extension_matchcid(p)) {
874                                                 sep = "/";
875                                                 cid = ast_get_extension_cidmatch(p);
876                                         } else {
877                                                 sep = cid = "";
878                                         }
879                                         fprintf(output, "exten => %s%s%s,%d,%s(%s)\n",
880                                             ast_get_extension_name(p), sep, cid,
881                                             ast_get_extension_priority(p),
882                                             ast_get_extension_app(p), tempdata);
883                                         free(tempdata);
884                                 }
885                         }
886                 }
887
888                 /* written any extensions? ok, write space between exten & inc */
889                 if (last_written_e)
890                         fprintf(output, "\n");
891
892                 /* walk through includes */
893                 for (i = NULL; (i = ast_walk_context_includes(c, i)) ; ) {
894                         if (strcmp(ast_get_include_registrar(i), registrar) != 0)
895                                 continue; /* not mine */
896                         PUT_CTX_HDR;
897                         fprintf(output, "include => %s\n", ast_get_include_name(i));
898                 }
899                 if (ast_walk_context_includes(c, NULL))
900                         fprintf(output, "\n");
901
902                 /* walk through switches */
903                 for (sw = NULL; (sw = ast_walk_context_switches(c, sw)) ; ) {
904                         if (strcmp(ast_get_switch_registrar(sw), registrar) != 0)
905                                 continue; /* not mine */
906                         PUT_CTX_HDR;
907                         fprintf(output, "switch => %s/%s\n",
908                                     ast_get_switch_name(sw), ast_get_switch_data(sw));
909                 }
910
911                 if (ast_walk_context_switches(c, NULL))
912                         fprintf(output, "\n");
913
914                 /* fireout ignorepats ... */
915                 for (ip = NULL; (ip = ast_walk_context_ignorepats(c, ip)); ) {
916                         if (strcmp(ast_get_ignorepat_registrar(ip), registrar) != 0)
917                                 continue; /* not mine */
918                         PUT_CTX_HDR;
919                         fprintf(output, "ignorepat => %s\n",
920                                                 ast_get_ignorepat_name(ip));
921                 }
922
923                 ast_unlock_context(c);
924         }       
925
926         ast_unlock_contexts();
927         ast_mutex_unlock(&save_dialplan_lock);
928         fclose(output);
929
930         if (incomplete) {
931                 ast_cli(fd, "Saved dialplan is incomplete\n");
932                 return RESULT_FAILURE;
933         }
934
935         ast_cli(fd, "Dialplan successfully saved into '%s'\n",
936                 filename);
937         return RESULT_SUCCESS;
938 }
939
940 /*!
941  * \brief ADD EXTENSION command stuff
942  */
943 static int handle_context_add_extension(int fd, int argc, char *argv[])
944 {
945         char *whole_exten;
946         char *exten, *prior;
947         int iprior = -2;
948         char *cidmatch, *app, *app_data;
949         char *start, *end;
950
951         /* check for arguments at first */
952         if (argc != 5 && argc != 6)
953                 return RESULT_SHOWUSAGE;
954         if (strcmp(argv[3], "into"))
955                 return RESULT_SHOWUSAGE;
956         if (argc == 6) if (strcmp(argv[5], "replace")) return RESULT_SHOWUSAGE;
957
958         /* XXX overwrite argv[2] */
959         whole_exten = argv[2];
960         exten   = strsep(&whole_exten,",");
961         if (strchr(exten, '/')) {
962                 cidmatch = exten;
963                 strsep(&cidmatch,"/");
964         } else {
965                 cidmatch = NULL;
966         }
967         prior       = strsep(&whole_exten,",");
968         if (prior) {
969                 if (!strcmp(prior, "hint")) {
970                         iprior = PRIORITY_HINT;
971                 } else {
972                         if (sscanf(prior, "%d", &iprior) != 1) {
973                                 ast_cli(fd, "'%s' is not a valid priority\n", prior);
974                                 prior = NULL;
975                         }
976                 }
977         }
978         app = whole_exten;
979         if (app && (start = strchr(app, '(')) && (end = strrchr(app, ')'))) {
980                 *start = *end = '\0';
981                 app_data = start + 1;
982                 ast_process_quotes_and_slashes(app_data, ',', '|');
983         } else {
984                 if (app) {
985                         app_data = strchr(app, ',');
986                         if (app_data) {
987                                 *app_data = '\0';
988                                 app_data++;
989                         }
990                 } else  
991                         app_data = NULL;
992         }
993
994         if (!exten || !prior || !app || (!app_data && iprior != PRIORITY_HINT))
995                 return RESULT_SHOWUSAGE;
996
997         if (!app_data)
998                 app_data="";
999         if (ast_add_extension(argv[4], argc == 6 ? 1 : 0, exten, iprior, NULL, cidmatch, app,
1000                 (void *)strdup(app_data), free, registrar)) {
1001                 switch (errno) {
1002                 case ENOMEM:
1003                         ast_cli(fd, "Out of free memory\n");
1004                         break;
1005
1006                 case EBUSY:
1007                         ast_cli(fd, "Failed to lock context(s) list, please try again later\n");
1008                         break;
1009
1010                 case ENOENT:
1011                         ast_cli(fd, "No existence of '%s' context\n", argv[4]);
1012                         break;
1013
1014                 case EEXIST:
1015                         ast_cli(fd, "Extension %s@%s with priority %s already exists\n",
1016                                 exten, argv[4], prior);
1017                         break;
1018
1019                 default:
1020                         ast_cli(fd, "Failed to add '%s,%s,%s,%s' extension into '%s' context\n",
1021                                         exten, prior, app, app_data, argv[4]);
1022                         break;
1023                 }
1024                 return RESULT_FAILURE;
1025         }
1026
1027         if (argc == 6) 
1028                 ast_cli(fd, "Extension %s@%s (%s) replace by '%s,%s,%s,%s'\n",
1029                         exten, argv[4], prior, exten, prior, app, app_data);
1030         else
1031                 ast_cli(fd, "Extension '%s,%s,%s,%s' added into '%s' context\n",
1032                         exten, prior, app, app_data, argv[4]);
1033
1034         return RESULT_SUCCESS;
1035 }
1036
1037 /*! add extension 6123,1,Dial,IAX/212.71.138.13/6123 into local */
1038 static char *complete_context_add_extension(const char *line, const char *word,
1039         int pos, int state)
1040 {
1041         int which = 0;
1042
1043         if (pos == 3) {         /* complete 'into' word ... */
1044                 return (state == 0) ? strdup("into") : NULL;
1045         } else if (pos == 4) { /* complete context */
1046                 struct ast_context *c = NULL;
1047                 int len = strlen(word);
1048                 char *res = NULL;
1049
1050                 /* try to lock contexts list ... */
1051                 if (ast_lock_contexts()) {
1052                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1053                         return NULL;
1054                 }
1055
1056                 /* walk through all contexts */
1057                 while ( !res && (c = ast_walk_contexts(c)) )
1058                         if (partial_match(ast_get_context_name(c), word, len) && ++which > state)
1059                                 res = strdup(ast_get_context_name(c));
1060                 ast_unlock_contexts();
1061                 return res;
1062         } else if (pos == 5) {
1063                 return state == 0 ? strdup("replace") : NULL;
1064         }
1065         return NULL;
1066 }
1067
1068 /*!
1069  * IGNOREPAT CLI stuff
1070  */
1071 static int handle_context_add_ignorepat(int fd, int argc, char *argv[])
1072 {
1073         if (argc != 5)
1074                 return RESULT_SHOWUSAGE;
1075         if (strcmp(argv[3], "into"))
1076                 return RESULT_SHOWUSAGE;
1077
1078         if (ast_context_add_ignorepat(argv[4], argv[2], registrar)) {
1079                 switch (errno) {
1080                 case ENOMEM:
1081                         ast_cli(fd, "Out of free memory\n");
1082                         break;
1083
1084                 case ENOENT:
1085                         ast_cli(fd, "There is no existence of '%s' context\n", argv[4]);
1086                         break;
1087
1088                 case EEXIST:
1089                         ast_cli(fd, "Ignore pattern '%s' already included in '%s' context\n",
1090                                 argv[2], argv[4]);
1091                         break;
1092
1093                 case EBUSY:
1094                         ast_cli(fd, "Failed to lock context(s) list, please, try again later\n");
1095                         break;
1096
1097                 default:
1098                         ast_cli(fd, "Failed to add ingore pattern '%s' into '%s' context\n",
1099                                 argv[2], argv[4]);
1100                         break;
1101                 }
1102                 return RESULT_FAILURE;
1103         }
1104
1105         ast_cli(fd, "Ignore pattern '%s' added into '%s' context\n",
1106                 argv[2], argv[4]);
1107         return RESULT_SUCCESS;
1108 }
1109
1110 static char *complete_context_add_ignorepat(const char *line, const char *word,
1111         int pos, int state)
1112 {
1113         if (pos == 3)
1114                 return state == 0 ? strdup("into") : NULL;
1115         else if (pos == 4) {
1116                 struct ast_context *c;
1117                 int which = 0;
1118                 char *dupline, *ignorepat = NULL;
1119                 const char *s;
1120                 char *ret = NULL;
1121                 int len = strlen(word);
1122
1123                 /* XXX skip first two words 'add' 'ignorepat' */
1124                 s = skip_words(line, 2);
1125                 if (s == NULL)
1126                         return NULL;
1127                 dupline = strdup(s);
1128                 if (!dupline) {
1129                         ast_log(LOG_ERROR, "Malloc failure\n");
1130                         return NULL;
1131                 }
1132                 ignorepat = strsep(&dupline, " ");
1133
1134                 if (ast_lock_contexts()) {
1135                         ast_log(LOG_ERROR, "Failed to lock contexts list\n");
1136                         return NULL;
1137                 }
1138
1139                 for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
1140                         int found = 0;
1141
1142                         if (!partial_match(ast_get_context_name(c), word, len))
1143                                 continue; /* not mine */
1144                         if (ignorepat) /* there must be one, right ? */
1145                                 found = lookup_c_ip(c, ignorepat);
1146                         if (!found && ++which > state)
1147                                 ret = strdup(ast_get_context_name(c));
1148                 }
1149
1150                 if (ignorepat)
1151                         free(ignorepat);
1152                 ast_unlock_contexts();
1153                 return ret;
1154         }
1155
1156         return NULL;
1157 }
1158
1159 static int handle_context_remove_ignorepat(int fd, int argc, char *argv[])
1160 {
1161         if (argc != 5)
1162                 return RESULT_SHOWUSAGE;
1163         if (strcmp(argv[3], "from"))
1164                 return RESULT_SHOWUSAGE;
1165
1166         if (ast_context_remove_ignorepat(argv[4], argv[2], registrar)) {
1167                 switch (errno) {
1168                 case EBUSY:
1169                         ast_cli(fd, "Failed to lock context(s) list, please try again later\n");
1170                         break;
1171
1172                 case ENOENT:
1173                         ast_cli(fd, "There is no existence of '%s' context\n", argv[4]);
1174                         break;
1175
1176                 case EINVAL:
1177                         ast_cli(fd, "There is no existence of '%s' ignore pattern in '%s' context\n",
1178                                         argv[2], argv[4]);
1179                         break;
1180
1181                 default:
1182                         ast_cli(fd, "Failed to remove ignore pattern '%s' from '%s' context\n", argv[2], argv[4]);
1183                         break;
1184                 }
1185                 return RESULT_FAILURE;
1186         }
1187
1188         ast_cli(fd, "Ignore pattern '%s' removed from '%s' context\n",
1189                 argv[2], argv[4]);
1190         return RESULT_SUCCESS;
1191 }
1192
1193 static int pbx_load_module(void);
1194
1195 static int handle_reload_extensions(int fd, int argc, char *argv[])
1196 {
1197         if (argc!=2)
1198                 return RESULT_SHOWUSAGE;
1199         pbx_load_module();
1200         return RESULT_SUCCESS;
1201 }
1202
1203 static char *complete_context_remove_ignorepat(const char *line, const char *word,
1204         int pos, int state)
1205 {
1206         struct ast_context *c;
1207         int which = 0;
1208         char *ret = NULL;
1209
1210         if (pos == 2) {
1211                 int len = strlen(word);
1212                 if (ast_lock_contexts()) {
1213                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1214                         return NULL;
1215                 }
1216
1217                 for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
1218                         struct ast_ignorepat *ip;
1219
1220                         if (ast_lock_context(c))        /* error, skip it */
1221                                 continue;
1222                         
1223                         for (ip = NULL; !ret && (ip = ast_walk_context_ignorepats(c, ip));) {
1224                                 if (partial_match(ast_get_ignorepat_name(ip), word, len) && ++which > state) {
1225                                         /* n-th match */
1226                                         struct ast_context *cw = NULL;
1227                                         int found = 0;
1228                                         while ( (cw = ast_walk_contexts(cw)) && cw != c && !found) {
1229                                                 /* XXX do i stop on c, or skip it ? */
1230                                                 found = lookup_c_ip(cw, ast_get_ignorepat_name(ip));
1231                                         }
1232                                         if (!found)
1233                                                 ret = strdup(ast_get_ignorepat_name(ip));
1234                                 }
1235                         }
1236                         ast_unlock_context(c);
1237                 }
1238                 ast_unlock_contexts();
1239                 return ret;
1240         } else if (pos == 3) {
1241                  return state == 0 ? strdup("from") : NULL;
1242         } else if (pos == 4) { /* XXX check this */
1243                 char *dupline, *duplinet, *ignorepat;
1244                 int len = strlen(word);
1245
1246                 dupline = strdup(line);
1247                 if (!dupline) {
1248                         ast_log(LOG_WARNING, "Out of free memory\n");
1249                         return NULL;
1250                 }
1251
1252                 duplinet = dupline;
1253                 strsep(&duplinet, " ");
1254                 strsep(&duplinet, " ");
1255                 ignorepat = strsep(&duplinet, " ");
1256
1257                 if (!ignorepat) {
1258                         free(dupline);
1259                         return NULL;
1260                 }
1261
1262                 if (ast_lock_contexts()) {
1263                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1264                         free(dupline);
1265                         return NULL;
1266                 }
1267
1268                 for (c = NULL; !ret && (c = ast_walk_contexts(c)); ) {
1269                         if (ast_lock_context(c))        /* fail, skip it */
1270                                 continue;
1271                         if (!partial_match(ast_get_context_name(c), word, len))
1272                                 continue;
1273                         if (lookup_c_ip(c, ignorepat) && ++which > state)
1274                                 ret = strdup(ast_get_context_name(c));
1275                         ast_unlock_context(c);
1276                 }
1277                 ast_unlock_contexts();
1278                 free(dupline);
1279                 return NULL;
1280         }
1281
1282         return NULL;
1283 }
1284
1285 /*!
1286  * CLI entries for commands provided by this module
1287  */
1288 static struct ast_cli_entry context_dont_include_cli =
1289         { { "dont", "include", NULL }, handle_context_dont_include,
1290                 "Remove a specified include from context", context_dont_include_help,
1291                 complete_context_dont_include };
1292
1293 static struct ast_cli_entry context_remove_extension_cli =
1294         { { "remove", "extension", NULL }, handle_context_remove_extension,
1295                 "Remove a specified extension", context_remove_extension_help,
1296                 complete_context_remove_extension };
1297
1298 static struct ast_cli_entry context_add_include_cli =
1299         { { "include", "context", NULL }, handle_context_add_include,
1300                 "Include context in other context", context_add_include_help,
1301                 complete_context_add_include };
1302
1303 static struct ast_cli_entry save_dialplan_cli =
1304         { { "save", "dialplan", NULL }, handle_save_dialplan,
1305                 "Save dialplan", save_dialplan_help };
1306
1307 static struct ast_cli_entry context_add_extension_cli =
1308         { { "add", "extension", NULL }, handle_context_add_extension,
1309                 "Add new extension into context", context_add_extension_help,
1310                 complete_context_add_extension };
1311
1312 static struct ast_cli_entry context_add_ignorepat_cli =
1313         { { "add", "ignorepat", NULL }, handle_context_add_ignorepat,
1314                 "Add new ignore pattern", context_add_ignorepat_help,
1315                 complete_context_add_ignorepat };
1316
1317 static struct ast_cli_entry context_remove_ignorepat_cli =
1318         { { "remove", "ignorepat", NULL }, handle_context_remove_ignorepat,
1319                 "Remove ignore pattern from context", context_remove_ignorepat_help,
1320                 complete_context_remove_ignorepat };
1321
1322 static struct ast_cli_entry reload_extensions_cli = 
1323         { { "extensions", "reload", NULL}, handle_reload_extensions,
1324                 "Reload extensions and *only* extensions", reload_extensions_help };
1325
1326 /*!
1327  * Standard module functions ...
1328  */
1329 STATIC_MODULE int unload_module(void)
1330 {
1331         ast_cli_unregister(&context_add_extension_cli);
1332         if (static_config && !write_protect_config)
1333                 ast_cli_unregister(&save_dialplan_cli);
1334         ast_cli_unregister(&context_add_include_cli);
1335         ast_cli_unregister(&context_dont_include_cli);
1336         ast_cli_unregister(&context_remove_extension_cli);
1337         ast_cli_unregister(&context_remove_ignorepat_cli);
1338         ast_cli_unregister(&context_add_ignorepat_cli);
1339         ast_cli_unregister(&reload_extensions_cli);
1340         ast_context_destroy(NULL, registrar);
1341         return 0;
1342 }
1343
1344 static void pbx_load_config(const char *config_file)
1345 {
1346         struct ast_config *cfg;
1347         char *end;
1348         char *label;
1349         char realvalue[256];
1350         int lastpri = -2;
1351         struct ast_context *con;
1352         struct ast_variable *v;
1353         char *cxt;
1354
1355         cfg = ast_config_load(config_file);
1356         if (!cfg)
1357                 return;
1358
1359         /* Use existing config to populate the PBX table */
1360         static_config = ast_true(ast_variable_retrieve(cfg, "general", "static"));
1361         write_protect_config = ast_true(ast_variable_retrieve(cfg, "general", "writeprotect"));
1362         autofallthrough_config = ast_true(ast_variable_retrieve(cfg, "general", "autofallthrough"));
1363         clearglobalvars_config = ast_true(ast_variable_retrieve(cfg, "general", "clearglobalvars"));
1364         ast_set2_flag(&ast_options, !ast_false(ast_variable_retrieve(cfg, "general", "priorityjumping")), AST_OPT_FLAG_PRIORITY_JUMPING);
1365                                                                     
1366         for (v = ast_variable_browse(cfg, "globals"); v; v = v->next) {
1367                 memset(realvalue, 0, sizeof(realvalue));
1368                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1369                 pbx_builtin_setvar_helper(NULL, v->name, realvalue);
1370         }
1371         for (cxt = NULL; (cxt = ast_category_browse(cfg, cxt)); ) {
1372
1373                 /* All categories but "general" or "globals" are considered contexts */
1374                 if (!strcasecmp(cxt, "general") || !strcasecmp(cxt, "globals"))
1375                         continue;
1376                 con=ast_context_create(&local_contexts,cxt, registrar);
1377                 if (con == NULL)
1378                         continue;
1379
1380                 for (v = ast_variable_browse(cfg, cxt); v; v = v->next) {
1381                         if (!strcasecmp(v->name, "exten")) {
1382                                 char *tc = strdup(v->value);
1383                                 if (tc == NULL)
1384                                         fprintf(stderr,"Error strdup returned NULL in %s\n",__PRETTY_FUNCTION__);
1385                                 else {
1386                                         int ipri = -2;
1387                                         char realext[256]="";
1388                                         char *plus, *firstp, *firstc;
1389                                         char *pri, *appl, *data, *cidmatch;
1390                                         char *stringp = tc;
1391                                         char *ext = strsep(&stringp, ",");
1392                                         if (!ext)
1393                                                 ext="";
1394                                         pbx_substitute_variables_helper(NULL, ext, realext, sizeof(realext) - 1);
1395                                         cidmatch = strchr(realext, '/');
1396                                         if (cidmatch) {
1397                                                 *cidmatch++ = '\0';
1398                                                 ast_shrink_phone_number(cidmatch);
1399                                         }
1400                                         pri = strsep(&stringp, ",");
1401                                         if (!pri)
1402                                                 pri="";
1403                                         label = strchr(pri, '(');
1404                                         if (label) {
1405                                                 *label++ = '\0';
1406                                                 end = strchr(label, ')');
1407                                                 if (end)
1408                                                         *end = '\0';
1409                                                 else
1410                                                         ast_log(LOG_WARNING, "Label missing trailing ')' at line %d\n", v->lineno);
1411                                         }
1412                                         plus = strchr(pri, '+');
1413                                         if (plus)
1414                                                 *plus++ = '\0';
1415                                         if (!strcmp(pri,"hint"))
1416                                                 ipri=PRIORITY_HINT;
1417                                         else if (!strcmp(pri, "next") || !strcmp(pri, "n")) {
1418                                                 if (lastpri > -2)
1419                                                         ipri = lastpri + 1;
1420                                                 else
1421                                                         ast_log(LOG_WARNING, "Can't use 'next' priority on the first entry!\n");
1422                                         } else if (!strcmp(pri, "same") || !strcmp(pri, "s")) {
1423                                                 if (lastpri > -2)
1424                                                         ipri = lastpri;
1425                                                 else
1426                                                         ast_log(LOG_WARNING, "Can't use 'same' priority on the first entry!\n");
1427                                         } else if (sscanf(pri, "%d", &ipri) != 1 &&
1428                                             (ipri = ast_findlabel_extension2(NULL, con, realext, pri, cidmatch)) < 1) {
1429                                                 ast_log(LOG_WARNING, "Invalid priority/label '%s' at line %d\n", pri, v->lineno);
1430                                                 ipri = 0;
1431                                         }
1432                                         appl = S_OR(stringp, "");
1433                                         /* Find the first occurrence of either '(' or ',' */
1434                                         firstc = strchr(appl, ',');
1435                                         firstp = strchr(appl, '(');
1436                                         if (firstc && (!firstp || firstc < firstp)) {
1437                                                 /* comma found, no parenthesis */
1438                                                 /* or both found, but comma found first */
1439                                                 appl = strsep(&stringp, ",");
1440                                                 data = stringp;
1441                                         } else if (!firstc && !firstp) {
1442                                                 /* Neither found */
1443                                                 data = "";
1444                                         } else {
1445                                                 /* Final remaining case is parenthesis found first */
1446                                                 appl = strsep(&stringp, "(");
1447                                                 data = stringp;
1448                                                 end = strrchr(data, ')');
1449                                                 if ((end = strrchr(data, ')'))) {
1450                                                         *end = '\0';
1451                                                 } else {
1452                                                         ast_log(LOG_WARNING, "No closing parenthesis found? '%s(%s'\n", appl, data);
1453                                                 }
1454                                                 ast_process_quotes_and_slashes(data, ',', '|');
1455                                         }
1456
1457                                         if (!data)
1458                                                 data="";
1459                                         appl = ast_skip_blanks(appl);
1460                                         if (ipri) {
1461                                                 if (plus)
1462                                                         ipri += atoi(plus);
1463                                                 lastpri = ipri;
1464                                                 if (!ast_opt_dont_warn && !strcmp(realext, "_."))
1465                                                         ast_log(LOG_WARNING, "The use of '_.' for an extension is strongly discouraged and can have unexpected behavior.  Please use '_X.' instead at line %d\n", v->lineno);
1466                                                 if (ast_add_extension2(con, 0, realext, ipri, label, cidmatch, appl, strdup(data), FREE, registrar)) {
1467                                                         ast_log(LOG_WARNING, "Unable to register extension at line %d\n", v->lineno);
1468                                                 }
1469                                         }
1470                                         free(tc);
1471                                 }
1472                         } else if (!strcasecmp(v->name, "include")) {
1473                                 memset(realvalue, 0, sizeof(realvalue));
1474                                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1475                                 if (ast_context_add_include2(con, realvalue, registrar))
1476                                         ast_log(LOG_WARNING, "Unable to include context '%s' in context '%s'\n", v->value, cxt);
1477                         } else if (!strcasecmp(v->name, "ignorepat")) {
1478                                 memset(realvalue, 0, sizeof(realvalue));
1479                                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1480                                 if (ast_context_add_ignorepat2(con, realvalue, registrar))
1481                                         ast_log(LOG_WARNING, "Unable to include ignorepat '%s' in context '%s'\n", v->value, cxt);
1482                         } else if (!strcasecmp(v->name, "switch") || !strcasecmp(v->name, "lswitch") || !strcasecmp(v->name, "eswitch")) {
1483                                 char *stringp= realvalue;
1484                                 char *appl, *data;
1485
1486                                 memset(realvalue, 0, sizeof(realvalue));
1487                                 if (!strcasecmp(v->name, "switch"))
1488                                         pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1489                                 else
1490                                         ast_copy_string(realvalue, v->value, sizeof(realvalue));
1491                                 appl = strsep(&stringp, "/");
1492                                 data = strsep(&stringp, ""); /* XXX what for ? */
1493                                 if (!data)
1494                                         data = "";
1495                                 if (ast_context_add_switch2(con, appl, data, !strcasecmp(v->name, "eswitch"), registrar))
1496                                         ast_log(LOG_WARNING, "Unable to include switch '%s' in context '%s'\n", v->value, cxt);
1497                         }
1498                 }
1499         }
1500         ast_config_destroy(cfg);
1501 }
1502
1503 static int pbx_load_module(void)
1504 {
1505         struct ast_context *con;
1506
1507         pbx_load_config(config);
1508         ast_merge_contexts_and_delete(&local_contexts, registrar);
1509
1510         for (con = NULL; (con = ast_walk_contexts(con));)
1511                 ast_context_verify_includes(con);
1512
1513         pbx_set_autofallthrough(autofallthrough_config);
1514
1515         return 0;
1516 }
1517
1518 STATIC_MODULE int load_module(void)
1519 {
1520         if (pbx_load_module())
1521                 return -1;
1522  
1523         ast_cli_register(&context_remove_extension_cli);
1524         ast_cli_register(&context_dont_include_cli);
1525         ast_cli_register(&context_add_include_cli);
1526         if (static_config && !write_protect_config)
1527                 ast_cli_register(&save_dialplan_cli);
1528         ast_cli_register(&context_add_extension_cli);
1529         ast_cli_register(&context_add_ignorepat_cli);
1530         ast_cli_register(&context_remove_ignorepat_cli);
1531         ast_cli_register(&reload_extensions_cli);
1532
1533         return 0;
1534 }
1535
1536 STATIC_MODULE int reload(void)
1537 {
1538         if (clearglobalvars_config)
1539                 pbx_builtin_clear_globals();
1540         pbx_load_module();
1541         return 0;
1542 }
1543
1544 STATIC_MODULE int usecount(void)
1545 {
1546         return 0;
1547 }
1548
1549 STATIC_MODULE const char *description(void)
1550 {
1551         return dtext;
1552 }
1553
1554 STATIC_MODULE const char *key(void)
1555 {
1556         return ASTERISK_GPL_KEY;
1557 }
1558
1559 STD_MOD(MOD_1, reload, NULL, NULL);