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