Fix UPGRADE.txt files for Asterisk 10.
[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 (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>,<app-data>\n"
916                         "       into <context> [replace]\n\n"
917                         "       This command will add new extension into <context>. If there is an\n"
918                         "       existence of extension with the same priority and last 'replace'\n"
919                         "       arguments is given here we simply replace this extension.\n"
920                         "\n"
921                         "Example: dialplan add extension 6123,1,Dial,IAX/216.207.245.56/6123 into local\n"
922                         "         Now, you can dial 6123 and talk to Markster :)\n";
923                 return NULL;
924         case CLI_GENERATE:
925                 return complete_dialplan_add_extension(a);
926         }
927
928         /* check for arguments at first */
929         if (a->argc != 6 && a->argc != 7)
930                 return CLI_SHOWUSAGE;
931         if (strcmp(a->argv[4], "into"))
932                 return CLI_SHOWUSAGE;
933         if (a->argc == 7)
934                 if (strcmp(a->argv[6], "replace"))
935                         return CLI_SHOWUSAGE;
936
937         whole_exten = ast_strdupa(a->argv[3]);
938         exten = strsep(&whole_exten,",");
939         if (strchr(exten, '/')) {
940                 cidmatch = exten;
941                 strsep(&cidmatch,"/");
942         } else {
943                 cidmatch = NULL;
944         }
945         prior = strsep(&whole_exten,",");
946         if (prior) {
947                 if (!strcmp(prior, "hint")) {
948                         iprior = PRIORITY_HINT;
949                 } else {
950                         if (sscanf(prior, "%30d", &iprior) != 1) {
951                                 ast_cli(a->fd, "'%s' is not a valid priority\n", prior);
952                                 prior = NULL;
953                         }
954                 }
955         }
956         app = whole_exten;
957         if (app && (start = strchr(app, '(')) && (end = strrchr(app, ')'))) {
958                 *start = *end = '\0';
959                 app_data = start + 1;
960         } else {
961                 if (app) {
962                         app_data = strchr(app, ',');
963                         if (app_data) {
964                                 *app_data = '\0';
965                                 app_data++;
966                         }
967                 } else  
968                         app_data = NULL;
969         }
970
971         if (!exten || !prior || !app || (!app_data && iprior != PRIORITY_HINT))
972                 return CLI_SHOWUSAGE;
973         
974         into_context = a->argv[5];
975
976         if (!ast_context_find(into_context)) {
977                 ast_cli(a->fd, "Context '%s' did not exist prior to add extension - the context will be created.\n", into_context);
978         }
979
980         if (!ast_context_find_or_create(NULL, NULL, into_context, registrar)) {
981                 ast_cli(a->fd, "ast_context_find_or_create() failed\n");
982                 ast_cli(a->fd, "Failed to add '%s,%s,%s,%s' extension into '%s' context\n", exten, prior, app, app_data, into_context);
983                 return CLI_FAILURE;
984         }
985
986         if (!app_data)
987                 app_data="";
988         if (ast_add_extension(into_context, a->argc == 7 ? 1 : 0, exten, iprior, NULL, cidmatch, app,
989                 (void *)strdup(app_data), ast_free_ptr, registrar)) {
990                 switch (errno) {
991                 case ENOMEM:
992                         ast_cli(a->fd, "Out of free memory\n");
993                         break;
994
995                 case EBUSY:
996                         ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
997                         break;
998
999                 case ENOENT:
1000                         ast_cli(a->fd, "No existence of '%s' context\n", into_context);
1001                         break;
1002
1003                 case EEXIST:
1004                         ast_cli(a->fd, "Extension %s@%s with priority %s already exists\n",
1005                                 exten, into_context, prior);
1006                         break;
1007
1008                 default:
1009                         ast_cli(a->fd, "Failed to add '%s,%s,%s,%s' extension into '%s' context\n",
1010                                         exten, prior, app, app_data, into_context);
1011                         break;
1012                 }
1013                 return CLI_FAILURE;
1014         }
1015
1016         if (a->argc == 7)
1017                 ast_cli(a->fd, "Extension %s@%s (%s) replace by '%s,%s,%s,%s'\n",
1018                         exten, into_context, prior, exten, prior, app, app_data);
1019         else
1020                 ast_cli(a->fd, "Extension '%s,%s,%s,%s' added into '%s' context\n",
1021                         exten, prior, app, app_data, into_context);
1022
1023         return CLI_SUCCESS;
1024 }
1025
1026 /*! dialplan add extension 6123,1,Dial,IAX/212.71.138.13/6123 into local */
1027 static char *complete_dialplan_add_extension(struct ast_cli_args *a)
1028 {
1029         int which = 0;
1030
1031         if (a->pos == 4) {              /* complete 'into' word ... */
1032                 return (a->n == 0) ? strdup("into") : NULL;
1033         } else if (a->pos == 5) { /* complete context */
1034                 struct ast_context *c = NULL;
1035                 int len = strlen(a->word);
1036                 char *res = NULL;
1037
1038                 /* try to lock contexts list ... */
1039                 if (ast_rdlock_contexts()) {
1040                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1041                         return NULL;
1042                 }
1043
1044                 /* walk through all contexts */
1045                 while ( !res && (c = ast_walk_contexts(c)) )
1046                         if (partial_match(ast_get_context_name(c), a->word, len) && ++which > a->n)
1047                                 res = strdup(ast_get_context_name(c));
1048                 ast_unlock_contexts();
1049                 return res;
1050         } else if (a->pos == 6) {
1051                 return a->n == 0 ? strdup("replace") : NULL;
1052         }
1053         return NULL;
1054 }
1055
1056 /*!
1057  * IGNOREPAT CLI stuff
1058  */
1059 static char *handle_cli_dialplan_add_ignorepat(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1060 {
1061         switch (cmd) {
1062         case CLI_INIT:
1063                 e->command = "dialplan add ignorepat";
1064                 e->usage =
1065                         "Usage: dialplan add ignorepat <pattern> into <context>\n"
1066                         "       This command adds a new ignore pattern into context <context>\n"
1067                         "\n"
1068                         "Example: dialplan add ignorepat _3XX into local\n";
1069                 return NULL;
1070         case CLI_GENERATE:
1071                 return complete_dialplan_add_ignorepat(a);
1072         }
1073
1074         if (a->argc != 6)
1075                 return CLI_SHOWUSAGE;
1076
1077         if (strcmp(a->argv[4], "into"))
1078                 return CLI_SHOWUSAGE;
1079
1080         if (ast_context_add_ignorepat(a->argv[5], a->argv[3], registrar)) {
1081                 switch (errno) {
1082                 case ENOMEM:
1083                         ast_cli(a->fd, "Out of free memory\n");
1084                         break;
1085
1086                 case ENOENT:
1087                         ast_cli(a->fd, "There is no existence of '%s' context\n", a->argv[5]);
1088                         break;
1089
1090                 case EEXIST:
1091                         ast_cli(a->fd, "Ignore pattern '%s' already included in '%s' context\n",
1092                                 a->argv[3], a->argv[5]);
1093                         break;
1094
1095                 case EBUSY:
1096                         ast_cli(a->fd, "Failed to lock context(s) list, please, try again later\n");
1097                         break;
1098
1099                 default:
1100                         ast_cli(a->fd, "Failed to add ingore pattern '%s' into '%s' context\n",
1101                                 a->argv[3], a->argv[5]);
1102                         break;
1103                 }
1104                 return CLI_FAILURE;
1105         }
1106
1107         ast_cli(a->fd, "Ignore pattern '%s' added into '%s' context\n",
1108                 a->argv[3], a->argv[5]);
1109
1110         return CLI_SUCCESS;
1111 }
1112
1113 static char *complete_dialplan_add_ignorepat(struct ast_cli_args *a)
1114 {
1115         if (a->pos == 4)
1116                 return a->n == 0 ? strdup("into") : NULL;
1117         else if (a->pos == 5) {
1118                 struct ast_context *c;
1119                 int which = 0;
1120                 char *dupline, *ignorepat = NULL;
1121                 const char *s;
1122                 char *ret = NULL;
1123                 int len = strlen(a->word);
1124
1125                 /* XXX skip first three words 'dialplan' 'add' 'ignorepat' */
1126                 s = skip_words(a->line, 3);
1127                 if (s == NULL)
1128                         return NULL;
1129                 dupline = strdup(s);
1130                 if (!dupline) {
1131                         ast_log(LOG_ERROR, "Malloc failure\n");
1132                         return NULL;
1133                 }
1134                 ignorepat = strsep(&dupline, " ");
1135
1136                 if (ast_rdlock_contexts()) {
1137                         ast_log(LOG_ERROR, "Failed to lock contexts list\n");
1138                         return NULL;
1139                 }
1140
1141                 for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
1142                         int found = 0;
1143
1144                         if (!partial_match(ast_get_context_name(c), a->word, len))
1145                                 continue; /* not mine */
1146                         if (ignorepat) /* there must be one, right ? */
1147                                 found = lookup_c_ip(c, ignorepat);
1148                         if (!found && ++which > a->n)
1149                                 ret = strdup(ast_get_context_name(c));
1150                 }
1151
1152                 free(ignorepat);
1153                 ast_unlock_contexts();
1154                 return ret;
1155         }
1156
1157         return NULL;
1158 }
1159
1160 static char *handle_cli_dialplan_remove_ignorepat(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1161 {
1162         switch (cmd) {
1163         case CLI_INIT:
1164                 e->command = "dialplan remove ignorepat";
1165                 e->usage =
1166                         "Usage: dialplan remove ignorepat <pattern> from <context>\n"
1167                         "       This command removes an ignore pattern from context <context>\n"
1168                         "\n"
1169                         "Example: dialplan remove ignorepat _3XX from local\n";
1170                 return NULL;
1171         case CLI_GENERATE:
1172                 return complete_dialplan_remove_ignorepat(a);
1173         }
1174
1175         if (a->argc != 6)
1176                 return CLI_SHOWUSAGE;
1177
1178         if (strcmp(a->argv[4], "from"))
1179                 return CLI_SHOWUSAGE;
1180
1181         if (ast_context_remove_ignorepat(a->argv[5], a->argv[3], registrar)) {
1182                 switch (errno) {
1183                 case EBUSY:
1184                         ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
1185                         break;
1186
1187                 case ENOENT:
1188                         ast_cli(a->fd, "There is no existence of '%s' context\n", a->argv[5]);
1189                         break;
1190
1191                 case EINVAL:
1192                         ast_cli(a->fd, "There is no existence of '%s' ignore pattern in '%s' context\n",
1193                                         a->argv[3], a->argv[5]);
1194                         break;
1195
1196                 default:
1197                         ast_cli(a->fd, "Failed to remove ignore pattern '%s' from '%s' context\n",
1198                                         a->argv[3], a->argv[5]);
1199                         break;
1200                 }
1201                 return CLI_FAILURE;
1202         }
1203
1204         ast_cli(a->fd, "Ignore pattern '%s' removed from '%s' context\n",
1205                 a->argv[3], a->argv[5]);
1206         return CLI_SUCCESS;
1207 }
1208
1209 static char *complete_dialplan_remove_ignorepat(struct ast_cli_args *a)
1210 {
1211         struct ast_context *c;
1212         int which = 0;
1213         char *ret = NULL;
1214
1215         if (a->pos == 3) {
1216                 int len = strlen(a->word);
1217                 if (ast_rdlock_contexts()) {
1218                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1219                         return NULL;
1220                 }
1221
1222                 for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
1223                         struct ast_ignorepat *ip;
1224
1225                         if (ast_rdlock_context(c))      /* error, skip it */
1226                                 continue;
1227                         
1228                         for (ip = NULL; !ret && (ip = ast_walk_context_ignorepats(c, ip));) {
1229                                 if (partial_match(ast_get_ignorepat_name(ip), a->word, len) && ++which > a->n) {
1230                                         /* n-th match */
1231                                         struct ast_context *cw = NULL;
1232                                         int found = 0;
1233                                         while ( (cw = ast_walk_contexts(cw)) && cw != c && !found) {
1234                                                 /* XXX do i stop on c, or skip it ? */
1235                                                 found = lookup_c_ip(cw, ast_get_ignorepat_name(ip));
1236                                         }
1237                                         if (!found)
1238                                                 ret = strdup(ast_get_ignorepat_name(ip));
1239                                 }
1240                         }
1241                         ast_unlock_context(c);
1242                 }
1243                 ast_unlock_contexts();
1244                 return ret;
1245         } else if (a->pos == 4) {
1246                  return a->n == 0 ? strdup("from") : NULL;
1247         } else if (a->pos == 5) { /* XXX check this */
1248                 char *dupline, *duplinet, *ignorepat;
1249                 int len = strlen(a->word);
1250
1251                 dupline = strdup(a->line);
1252                 if (!dupline) {
1253                         ast_log(LOG_WARNING, "Out of free memory\n");
1254                         return NULL;
1255                 }
1256
1257                 duplinet = dupline;
1258                 strsep(&duplinet, " ");
1259                 strsep(&duplinet, " ");
1260                 ignorepat = strsep(&duplinet, " ");
1261
1262                 if (!ignorepat) {
1263                         free(dupline);
1264                         return NULL;
1265                 }
1266
1267                 if (ast_rdlock_contexts()) {
1268                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1269                         free(dupline);
1270                         return NULL;
1271                 }
1272
1273                 for (c = NULL; !ret && (c = ast_walk_contexts(c)); ) {
1274                         if (ast_rdlock_context(c))      /* fail, skip it */
1275                                 continue;
1276                         if (!partial_match(ast_get_context_name(c), a->word, len))
1277                                 continue;
1278                         if (lookup_c_ip(c, ignorepat) && ++which > a->n)
1279                                 ret = strdup(ast_get_context_name(c));
1280                         ast_unlock_context(c);
1281                 }
1282                 ast_unlock_contexts();
1283                 free(dupline);
1284                 return NULL;
1285         }
1286
1287         return NULL;
1288 }
1289
1290 static int pbx_load_module(void);
1291
1292 static char *handle_cli_dialplan_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1293 {
1294         switch (cmd) {
1295         case CLI_INIT:
1296                 e->command = "dialplan reload";
1297                 e->usage =
1298                         "Usage: dialplan reload\n"
1299                         "       Reload extensions.conf without reloading any other\n"
1300                         "       modules.  This command does not delete global variables\n"
1301                         "       unless clearglobalvars is set to yes in extensions.conf\n";
1302                 return NULL;
1303         case CLI_GENERATE:
1304                 return NULL;
1305         }
1306
1307         if (a->argc != 2)
1308                 return CLI_SHOWUSAGE;
1309
1310         if (clearglobalvars_config)
1311                 pbx_builtin_clear_globals();
1312
1313         pbx_load_module();
1314         ast_cli(a->fd, "Dialplan reloaded.\n");
1315         return CLI_SUCCESS;
1316 }
1317
1318 /*!
1319  * CLI entries for commands provided by this module
1320  */
1321 static struct ast_cli_entry cli_pbx_config[] = {
1322         AST_CLI_DEFINE(handle_cli_dialplan_add_extension,    "Add new extension into context"),
1323         AST_CLI_DEFINE(handle_cli_dialplan_remove_extension, "Remove a specified extension"),
1324         AST_CLI_DEFINE(handle_cli_dialplan_add_ignorepat,    "Add new ignore pattern"),
1325         AST_CLI_DEFINE(handle_cli_dialplan_remove_ignorepat, "Remove ignore pattern from context"),
1326         AST_CLI_DEFINE(handle_cli_dialplan_add_include,      "Include context in other context"),
1327         AST_CLI_DEFINE(handle_cli_dialplan_remove_include,   "Remove a specified include from context"),
1328         AST_CLI_DEFINE(handle_cli_dialplan_reload,           "Reload extensions and *only* extensions"),
1329         AST_CLI_DEFINE(handle_cli_dialplan_save,             "Save current dialplan into a file")
1330 };
1331
1332 static struct ast_cli_entry cli_dialplan_save =
1333         AST_CLI_DEFINE(handle_cli_dialplan_save, "Save dialplan");
1334
1335 /*!
1336  * Standard module functions ...
1337  */
1338 static int unload_module(void)
1339 {
1340         if (static_config && !write_protect_config)
1341                 ast_cli_unregister(&cli_dialplan_save);
1342         if (overrideswitch_config) {
1343                 ast_free(overrideswitch_config);
1344         }
1345         ast_cli_unregister_multiple(cli_pbx_config, ARRAY_LEN(cli_pbx_config));
1346         ast_context_destroy(NULL, registrar);
1347         return 0;
1348 }
1349
1350 /*!\note Protect against misparsing based upon commas in the middle of fields
1351  * like character classes.  We've taken steps to permit pretty much every other
1352  * printable character in a character class, so properly handling a comma at
1353  * this level is a natural extension.  This is almost like the standard
1354  * application parser in app.c, except that it handles square brackets. */
1355 static char *pbx_strsep(char **destructible, const char *delim)
1356 {
1357         int square = 0;
1358         char *res = *destructible;
1359         for (; destructible && *destructible && **destructible; (*destructible)++) {
1360                 if (**destructible == '[' && !strchr(delim, '[')) {
1361                         square++;
1362                 } else if (**destructible == ']' && !strchr(delim, ']')) {
1363                         if (square) {
1364                                 square--;
1365                         }
1366                 } else if (**destructible == '\\' && !strchr(delim, '\\')) {
1367                         (*destructible)++;
1368                 } else if (strchr(delim, **destructible) && !square) {
1369                         **destructible = '\0';
1370                         (*destructible)++;
1371                         break;
1372                 }
1373         }
1374         if (destructible && *destructible && **destructible == '\0') {
1375                 *destructible = NULL;
1376         }
1377         return res;
1378 }
1379
1380 static int pbx_load_config(const char *config_file)
1381 {
1382         struct ast_config *cfg;
1383         char *end;
1384         char *label;
1385 #ifdef LOW_MEMORY
1386         char realvalue[256];
1387 #else
1388         char realvalue[8192];
1389 #endif
1390         int lastpri = -2;
1391         struct ast_context *con;
1392         struct ast_variable *v;
1393         const char *cxt;
1394         const char *aft;
1395         const char *newpm, *ovsw;
1396         struct ast_flags config_flags = { 0 };
1397         char lastextension[256];
1398         cfg = ast_config_load(config_file, config_flags);
1399         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID)
1400                 return 0;
1401
1402         /* Use existing config to populate the PBX table */
1403         static_config = ast_true(ast_variable_retrieve(cfg, "general", "static"));
1404         write_protect_config = ast_true(ast_variable_retrieve(cfg, "general", "writeprotect"));
1405         if ((aft = ast_variable_retrieve(cfg, "general", "autofallthrough")))
1406                 autofallthrough_config = ast_true(aft);
1407         if ((newpm = ast_variable_retrieve(cfg, "general", "extenpatternmatchnew")))
1408                 extenpatternmatchnew_config = ast_true(newpm);
1409         clearglobalvars_config = ast_true(ast_variable_retrieve(cfg, "general", "clearglobalvars"));
1410         if ((ovsw = ast_variable_retrieve(cfg, "general", "overrideswitch"))) {
1411                 if (overrideswitch_config) {
1412                         ast_free(overrideswitch_config);
1413                 }
1414                 if (!ast_strlen_zero(ovsw)) {
1415                         overrideswitch_config = ast_strdup(ovsw);
1416                 } else {
1417                         overrideswitch_config = NULL;
1418                 }
1419         }
1420
1421         ast_copy_string(userscontext, ast_variable_retrieve(cfg, "general", "userscontext") ?: "default", sizeof(userscontext));
1422                                                                     
1423         for (v = ast_variable_browse(cfg, "globals"); v; v = v->next) {
1424                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1425                 pbx_builtin_setvar_helper(NULL, v->name, realvalue);
1426         }
1427         for (cxt = ast_category_browse(cfg, NULL);
1428              cxt;
1429              cxt = ast_category_browse(cfg, cxt)) {
1430                 /* All categories but "general" or "globals" are considered contexts */
1431                 if (!strcasecmp(cxt, "general") || !strcasecmp(cxt, "globals")) {
1432                         continue;
1433                 }
1434                 if (!(con = ast_context_find_or_create(&local_contexts, local_table, cxt, registrar))) {
1435                         continue;
1436                 }
1437
1438                 /* Reset continuation items at the beginning of each context */
1439                 lastextension[0] = '\0';
1440                 lastpri = -2;
1441
1442                 for (v = ast_variable_browse(cfg, cxt); v; v = v->next) {
1443                         char *tc = NULL;
1444                         char realext[256] = "";
1445                         char *stringp, *ext;
1446                         const char *vfile;
1447
1448                         /* get filename for error reporting from top level or an #include */
1449                         vfile = !*v->file ? config_file : v->file;
1450
1451                         if (!strncasecmp(v->name, "same", 4)) {
1452                                 if (ast_strlen_zero(lastextension)) {
1453                                         ast_log(LOG_ERROR,
1454                                                 "No previous pattern in the first entry of context '%s' to match '%s' at line %d of %s!\n",
1455                                                 cxt, v->name, v->lineno, vfile);
1456                                         continue;
1457                                 }
1458                                 if ((stringp = tc = ast_strdup(v->value))) {
1459                                         ast_copy_string(realext, lastextension, sizeof(realext));
1460                                         goto process_extension;
1461                                 }
1462                         } else if (!strcasecmp(v->name, "exten")) {
1463                                 int ipri;
1464                                 char *plus, *firstp;
1465                                 char *pri, *appl, *data, *cidmatch;
1466
1467                                 if (!(stringp = tc = ast_strdup(v->value))) {
1468                                         continue;
1469                                 }
1470
1471                                 ext = S_OR(pbx_strsep(&stringp, ","), "");
1472                                 pbx_substitute_variables_helper(NULL, ext, realext, sizeof(realext) - 1);
1473                                 ast_copy_string(lastextension, realext, sizeof(lastextension));
1474 process_extension:
1475                                 ipri = -2;
1476                                 if ((cidmatch = strchr(realext, '/'))) {
1477                                         *cidmatch++ = '\0';
1478                                         ast_shrink_phone_number(cidmatch);
1479                                 }
1480                                 pri = ast_strip(S_OR(strsep(&stringp, ","), ""));
1481                                 if ((label = strchr(pri, '('))) {
1482                                         *label++ = '\0';
1483                                         if ((end = strchr(label, ')'))) {
1484                                                 *end = '\0';
1485                                         } else {
1486                                                 ast_log(LOG_WARNING,
1487                                                         "Label missing trailing ')' at line %d of %s\n",
1488                                                         v->lineno, vfile);
1489                                                 ast_free(tc);
1490                                                 continue;
1491                                         }
1492                                 }
1493                                 if ((plus = strchr(pri, '+'))) {
1494                                         *plus++ = '\0';
1495                                 }
1496                                 if (!strcmp(pri,"hint")) {
1497                                         ipri = PRIORITY_HINT;
1498                                 } else if (!strcmp(pri, "next") || !strcmp(pri, "n")) {
1499                                         if (lastpri > -2) {
1500                                                 ipri = lastpri + 1;
1501                                         } else {
1502                                                 ast_log(LOG_WARNING,
1503                                                         "Can't use 'next' priority on the first entry at line %d of %s!\n",
1504                                                         v->lineno, vfile);
1505                                                 ast_free(tc);
1506                                                 continue;
1507                                         }
1508                                 } else if (!strcmp(pri, "same") || !strcmp(pri, "s")) {
1509                                         if (lastpri > -2) {
1510                                                 ipri = lastpri;
1511                                         } else {
1512                                                 ast_log(LOG_WARNING,
1513                                                         "Can't use 'same' priority on the first entry at line %d of %s!\n",
1514                                                         v->lineno, vfile);
1515                                                 ast_free(tc);
1516                                                 continue;
1517                                         }
1518                                 } else if (sscanf(pri, "%30d", &ipri) != 1 &&
1519                                            (ipri = ast_findlabel_extension2(NULL, con, realext, pri, cidmatch)) < 1) {
1520                                         ast_log(LOG_WARNING,
1521                                                 "Invalid priority/label '%s' at line %d of %s\n",
1522                                                 pri, v->lineno, vfile);
1523                                         ipri = 0;
1524                                         ast_free(tc);
1525                                         continue;
1526                                 } else if (ipri < 1) {
1527                                         ast_log(LOG_WARNING, "Invalid priority '%s' at line %d of %s\n",
1528                                                 pri, v->lineno, vfile);
1529                                         ast_free(tc);
1530                                         continue;
1531                                 }
1532                                 appl = S_OR(stringp, "");
1533                                 /* Find the first occurrence of '(' */
1534                                 if (!(firstp = strchr(appl, '('))) {
1535                                         /* No arguments */
1536                                         data = "";
1537                                 } else {
1538                                         char *orig_appl = ast_strdup(appl);
1539
1540                                         if (!orig_appl) {
1541                                                 ast_free(tc);
1542                                                 continue;
1543                                         }
1544
1545                                         appl = strsep(&stringp, "(");
1546
1547                                         /* check if there are variables or expressions without an application, like: exten => 100,hint,DAHDI/g0/${GLOBAL(var)}  */
1548                                         if (strstr(appl, "${") || strstr(appl, "$[")){
1549                                                 /* set appl to original one */
1550                                                 strcpy(appl, orig_appl);
1551                                                 /* set no data */
1552                                                 data = "";
1553                                         /* no variable before application found -> go ahead */
1554                                         } else {
1555                                                 data = S_OR(stringp, "");
1556                                                 if ((end = strrchr(data, ')'))) {
1557                                                         *end = '\0';
1558                                                 } else {
1559                                                         ast_log(LOG_WARNING,
1560                                                                 "No closing parenthesis found? '%s(%s' at line %d of %s\n",
1561                                                                 appl, data, v->lineno, vfile);
1562                                                 }
1563                                         }
1564                                         ast_free(orig_appl);
1565                                 }
1566
1567                                 appl = ast_skip_blanks(appl);
1568                                 if (ipri) {
1569                                         if (plus) {
1570                                                 ipri += atoi(plus);
1571                                         }
1572                                         lastpri = ipri;
1573                                         if (!ast_opt_dont_warn && (!strcmp(realext, "_.") || !strcmp(realext, "_!"))) {
1574                                                 ast_log(LOG_WARNING,
1575                                                         "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",
1576                                                         realext, realext[1], v->lineno, vfile);
1577                                         }
1578                                         if (ast_add_extension2(con, 0, realext, ipri, label, cidmatch, appl, strdup(data), ast_free_ptr, registrar)) {
1579                                                 ast_log(LOG_WARNING,
1580                                                         "Unable to register extension at line %d of %s\n",
1581                                                         v->lineno, vfile);
1582                                         }
1583                                 }
1584                                 free(tc);
1585                         } else if (!strcasecmp(v->name, "include")) {
1586                                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1587                                 if (ast_context_add_include2(con, realvalue, registrar)) {
1588                                         switch (errno) {
1589                                         case ENOMEM:
1590                                                 ast_log(LOG_WARNING, "Out of memory for context addition\n");
1591                                                 break;
1592
1593                                         case EBUSY:
1594                                                 ast_log(LOG_WARNING, "Failed to lock context(s) list, please try again later\n");
1595                                                 break;
1596
1597                                         case EEXIST:
1598                                                 ast_log(LOG_WARNING,
1599                                                         "Context '%s' already included in '%s' context on include at line %d of %s\n",
1600                                                         v->value, cxt, v->lineno, vfile);
1601                                                 break;
1602
1603                                         case ENOENT:
1604                                         case EINVAL:
1605                                                 ast_log(LOG_WARNING,
1606                                                         "There is no existence of context '%s' included at line %d of %s\n",
1607                                                         errno == ENOENT ? v->value : cxt, v->lineno, vfile);
1608                                                 break;
1609
1610                                         default:
1611                                                 ast_log(LOG_WARNING,
1612                                                         "Failed to include '%s' in '%s' context at line %d of %s\n",
1613                                                         v->value, cxt, v->lineno, vfile);
1614                                                 break;
1615                                         }
1616                                 }
1617                         } else if (!strcasecmp(v->name, "ignorepat")) {
1618                                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1619                                 if (ast_context_add_ignorepat2(con, realvalue, registrar)) {
1620                                         ast_log(LOG_WARNING,
1621                                                 "Unable to include ignorepat '%s' in context '%s' at line %d of %s\n",
1622                                                 v->value, cxt, v->lineno, vfile);
1623                                 }
1624                         } else if (!strcasecmp(v->name, "switch") || !strcasecmp(v->name, "lswitch") || !strcasecmp(v->name, "eswitch")) {
1625                                 char *stringp = realvalue;
1626                                 char *appl, *data;
1627                                 
1628                                 if (!strcasecmp(v->name, "switch")) {
1629                                         pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1630                                 } else {
1631                                         ast_copy_string(realvalue, v->value, sizeof(realvalue));
1632                                 }
1633                                 appl = strsep(&stringp, "/");
1634                                 data = S_OR(stringp, "");
1635                                 if (ast_context_add_switch2(con, appl, data, !strcasecmp(v->name, "eswitch"), registrar)) {
1636                                         ast_log(LOG_WARNING,
1637                                                 "Unable to include switch '%s' in context '%s' at line %d of %s\n",
1638                                                 v->value, cxt, v->lineno, vfile);
1639                                 }
1640                         } else {
1641                                 ast_log(LOG_WARNING,
1642                                         "==!!== Unknown directive: %s at line %d of %s -- IGNORING!!!\n",
1643                                         v->name, v->lineno, vfile);
1644                         }
1645                 }
1646         }
1647         ast_config_destroy(cfg);
1648         return 1;
1649 }
1650
1651 static void append_interface(char *iface, int maxlen, char *add)
1652 {
1653         int len = strlen(iface);
1654         if (strlen(add) + len < maxlen - 2) {
1655                 if (strlen(iface)) {
1656                         iface[len] = '&';
1657                         strcpy(iface + len + 1, add);
1658                 } else
1659                         strcpy(iface, add);
1660         }
1661 }
1662
1663 static void pbx_load_users(void)
1664 {
1665         struct ast_config *cfg;
1666         char *cat, *chan;
1667         const char *dahdichan;
1668         const char *hasexten, *altexts;
1669         char tmp[256];
1670         char iface[256];
1671         char dahdicopy[256];
1672         char *ext, altcopy[256];
1673         char *c;
1674         int hasvoicemail;
1675         int start, finish, x;
1676         struct ast_context *con = NULL;
1677         struct ast_flags config_flags = { 0 };
1678         
1679         cfg = ast_config_load("users.conf", config_flags);
1680         if (!cfg)
1681                 return;
1682
1683         for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
1684                 if (!strcasecmp(cat, "general"))
1685                         continue;
1686                 iface[0] = '\0';
1687                 if (ast_true(ast_config_option(cfg, cat, "hassip"))) {
1688                         snprintf(tmp, sizeof(tmp), "SIP/%s", cat);
1689                         append_interface(iface, sizeof(iface), tmp);
1690                 }
1691                 if (ast_true(ast_config_option(cfg, cat, "hasiax"))) {
1692                         snprintf(tmp, sizeof(tmp), "IAX2/%s", cat);
1693                         append_interface(iface, sizeof(iface), tmp);
1694                 }
1695                 if (ast_true(ast_config_option(cfg, cat, "hash323"))) {
1696                         snprintf(tmp, sizeof(tmp), "H323/%s", cat);
1697                         append_interface(iface, sizeof(iface), tmp);
1698                 }
1699                 hasexten = ast_config_option(cfg, cat, "hasexten");
1700                 if (hasexten && !ast_true(hasexten))
1701                         continue;
1702                 hasvoicemail = ast_true(ast_config_option(cfg, cat, "hasvoicemail"));
1703                 dahdichan = ast_variable_retrieve(cfg, cat, "dahdichan");
1704                 if (!dahdichan)
1705                         dahdichan = ast_variable_retrieve(cfg, "general", "dahdichan");
1706                 if (!ast_strlen_zero(dahdichan)) {
1707                         ast_copy_string(dahdicopy, dahdichan, sizeof(dahdicopy));
1708                         c = dahdicopy;
1709                         chan = strsep(&c, ",");
1710                         while (chan) {
1711                                 if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
1712                                         /* Range */
1713                                 } else if (sscanf(chan, "%30d", &start)) {
1714                                         /* Just one */
1715                                         finish = start;
1716                                 } else {
1717                                         start = 0; finish = 0;
1718                                 }
1719                                 if (finish < start) {
1720                                         x = finish;
1721                                         finish = start;
1722                                         start = x;
1723                                 }
1724                                 for (x = start; x <= finish; x++) {
1725                                         snprintf(tmp, sizeof(tmp), "DAHDI/%d", x);
1726                                         append_interface(iface, sizeof(iface), tmp);
1727                                 }
1728                                 chan = strsep(&c, ",");
1729                         }
1730                 }
1731                 if (!ast_strlen_zero(iface)) {
1732                         /* Only create a context here when it is really needed. Otherwise default empty context
1733                         created by pbx_config may conflict with the one explicitly created by pbx_ael */
1734                         if (!con)
1735                                 con = ast_context_find_or_create(&local_contexts, local_table, userscontext, registrar);
1736
1737                         if (!con) {
1738                                 ast_log(LOG_ERROR, "Can't find/create user context '%s'\n", userscontext);
1739                                 return;
1740                         }
1741
1742                         /* Add hint */
1743                         ast_add_extension2(con, 0, cat, -1, NULL, NULL, iface, NULL, NULL, registrar);
1744                         /* If voicemail, use "stdexten" else use plain old dial */
1745                         if (hasvoicemail) {
1746                                 snprintf(tmp, sizeof(tmp), "stdexten,%s,${HINT}", cat);
1747                                 ast_add_extension2(con, 0, cat, 1, NULL, NULL, "Macro", strdup(tmp), ast_free_ptr, registrar);
1748                         } else {
1749                                 ast_add_extension2(con, 0, cat, 1, NULL, NULL, "Dial", strdup("${HINT}"), ast_free_ptr, registrar);
1750                         }
1751                         altexts = ast_variable_retrieve(cfg, cat, "alternateexts");
1752                         if (!ast_strlen_zero(altexts)) {
1753                                 snprintf(tmp, sizeof(tmp), "%s,1", cat);
1754                                 ast_copy_string(altcopy, altexts, sizeof(altcopy));
1755                                 c = altcopy;
1756                                 ext = strsep(&c, ",");
1757                                 while (ext) {
1758                                         ast_add_extension2(con, 0, ext, 1, NULL, NULL, "Goto", strdup(tmp), ast_free_ptr, registrar);
1759                                         ext = strsep(&c, ",");
1760                                 }
1761                         }
1762                 }
1763         }
1764         ast_config_destroy(cfg);
1765 }
1766
1767 static int pbx_load_module(void)
1768 {
1769         struct ast_context *con;
1770
1771         if (!local_table)
1772                 local_table = ast_hashtab_create(17, ast_hashtab_compare_contexts, ast_hashtab_resize_java, ast_hashtab_newsize_java, ast_hashtab_hash_contexts, 0);
1773
1774         if (!pbx_load_config(config))
1775                 return AST_MODULE_LOAD_DECLINE;
1776         
1777         pbx_load_users();
1778
1779         ast_merge_contexts_and_delete(&local_contexts, local_table, registrar);
1780         local_table = NULL; /* the local table has been moved into the global one. */
1781         local_contexts = NULL;
1782
1783         for (con = NULL; (con = ast_walk_contexts(con));)
1784                 ast_context_verify_includes(con);
1785
1786         pbx_set_overrideswitch(overrideswitch_config);
1787         pbx_set_autofallthrough(autofallthrough_config);
1788         pbx_set_extenpatternmatchnew(extenpatternmatchnew_config);
1789
1790         return AST_MODULE_LOAD_SUCCESS;
1791 }
1792
1793 static int load_module(void)
1794 {
1795         if (static_config && !write_protect_config)
1796                 ast_cli_register(&cli_dialplan_save);
1797         ast_cli_register_multiple(cli_pbx_config, ARRAY_LEN(cli_pbx_config));
1798
1799         if (pbx_load_module())
1800                 return AST_MODULE_LOAD_DECLINE;
1801
1802         return AST_MODULE_LOAD_SUCCESS;
1803 }
1804
1805 static int reload(void)
1806 {
1807         if (clearglobalvars_config)
1808                 pbx_builtin_clear_globals();
1809         return pbx_load_module();
1810 }
1811
1812 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Text Extension Configuration",
1813                 .load = load_module,
1814                 .unload = unload_module,
1815                 .reload = reload,
1816                );