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