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