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