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