Add libjack-dev to install_prereq.
[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, lcid, 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                 lcid = strlen(cid);
471                 len = strlen(a->word);
472                 if (le == 0 || lc == 0)
473                         goto error3;
474
475                 if (ast_rdlock_contexts()) {
476                         ast_log(LOG_ERROR, "Failed to lock context list\n");
477                         goto error3;
478                 }
479
480                 /* walk contexts */
481                 c = NULL;
482                 while ( (c = ast_walk_contexts(c)) ) {
483                         /* XXX locking on c ? */
484                         struct ast_exten *e;
485                         if (strcmp(ast_get_context_name(c), context) != 0)
486                                 continue;
487                         /* got it, we must match here */
488                         e = NULL;
489                         while ( (e = ast_walk_context_extensions(c, e)) ) {
490                                 struct ast_exten *priority;
491                                 char buffer[10];
492
493                                 if (cid && strcmp(ast_get_extension_cidmatch(e), cid) != 0) {
494                                         continue;
495                                 }
496                                 if (strcmp(ast_get_extension_name(e), exten) != 0)
497                                         continue;
498                                 /* XXX lock e ? */
499                                 priority = NULL;
500                                 while ( !ret && (priority = ast_walk_extension_priorities(e, priority)) ) {
501                                         snprintf(buffer, sizeof(buffer), "%u", ast_get_extension_priority(priority));
502                                         if (partial_match(buffer, a->word, len) && ++which > a->n) /* n-th match */
503                                                 ret = strdup(buffer);
504                                 }
505                                 break;
506                         }
507                         break;
508                 }
509                 ast_unlock_contexts();
510         error3:
511                 free(exten);
512         }
513         return ret; 
514 }
515
516 /*!
517  * Include context ...
518  */
519 static char *handle_cli_dialplan_add_include(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
520 {
521         switch (cmd) {
522         case CLI_INIT:
523                 e->command = "dialplan add include";
524                 e->usage =
525                         "Usage: dialplan add include <context> into <context>\n"
526                         "       Include a context in another context.\n";
527                 return NULL;
528         case CLI_GENERATE:
529                 return complete_dialplan_add_include(a);
530         }
531
532         if (a->argc != 6) /* dialplan add include CTX in CTX */
533                 return CLI_SHOWUSAGE;
534
535         /* fifth arg must be 'into' ... */
536         if (strcmp(a->argv[4], "into"))
537                 return CLI_SHOWUSAGE;
538
539         if (ast_context_add_include(a->argv[5], a->argv[3], registrar)) {
540                 switch (errno) {
541                 case ENOMEM:
542                         ast_cli(a->fd, "Out of memory for context addition\n");
543                         break;
544
545                 case EBUSY:
546                         ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
547                         break;
548
549                 case EEXIST:
550                         ast_cli(a->fd, "Context '%s' already included in '%s' context\n",
551                                 a->argv[3], a->argv[5]);
552                         break;
553
554                 case ENOENT:
555                 case EINVAL:
556                         ast_cli(a->fd, "There is no existence of context '%s'\n",
557                                 errno == ENOENT ? a->argv[5] : a->argv[3]);
558                         break;
559
560                 default:
561                         ast_cli(a->fd, "Failed to include '%s' in '%s' context\n",
562                                 a->argv[3], a->argv[5]);
563                         break;
564                 }
565                 return CLI_FAILURE;
566         }
567
568         /* show some info ... */
569         ast_cli(a->fd, "Context '%s' included in '%s' context\n",
570                 a->argv[3], a->argv[5]);
571
572         return CLI_SUCCESS;
573 }
574
575 static char *complete_dialplan_add_include(struct ast_cli_args *a)
576 {
577         struct ast_context *c;
578         int which = 0;
579         char *ret = NULL;
580         int len = strlen(a->word);
581
582         if (a->pos == 3) {              /* 'dialplan add include _X_' (context) ... */
583                 if (ast_rdlock_contexts()) {
584                         ast_log(LOG_ERROR, "Failed to lock context list\n");
585                         return NULL;
586                 }
587                 for (c = NULL; !ret && (c = ast_walk_contexts(c)); )
588                         if (partial_match(ast_get_context_name(c), a->word, len) && ++which > a->n)
589                                 ret = strdup(ast_get_context_name(c));
590                 ast_unlock_contexts();
591                 return ret;
592         } else if (a->pos == 4) { /* dialplan add include CTX _X_ */
593                 /* complete  as 'into' if context exists or we are unable to check */
594                 char *context, *dupline;
595                 const char *s = skip_words(a->line, 3); /* should not fail */
596
597                 if (a->n != 0)  /* only once */
598                         return NULL;
599
600                 /* parse context from line ... */
601                 context = dupline = strdup(s);
602                 if (!context) {
603                         ast_log(LOG_ERROR, "Out of free memory\n");
604                         return strdup("into");
605                 }
606                 strsep(&dupline, " ");
607
608                 /* check for context existence ... */
609                 if (ast_rdlock_contexts()) {
610                         ast_log(LOG_ERROR, "Failed to lock context list\n");
611                         /* our fault, we can't check, so complete 'into' ... */
612                         ret = strdup("into");
613                 } else {
614                         struct ast_context *ctx;
615                         for (ctx = NULL; !ret && (ctx = ast_walk_contexts(ctx)); )
616                                 if (!strcmp(context, ast_get_context_name(ctx)))
617                                         ret = strdup("into"); /* found */
618                         ast_unlock_contexts();
619                 }
620                 free(context);
621                 return ret;
622         } else if (a->pos == 5) { /* 'dialplan add include CTX into _X_' (dst context) */
623                 char *context, *dupline, *into;
624                 const char *s = skip_words(a->line, 3); /* should not fail */
625                 context = dupline = strdup(s);
626                 if (!dupline) {
627                         ast_log(LOG_ERROR, "Out of free memory\n");
628                         return NULL;
629                 }
630                 strsep(&dupline, " "); /* skip context */
631                 into = strsep(&dupline, " ");
632                 /* error if missing context or fifth word is not 'into' */
633                 if (!strlen(context) || strcmp(into, "into")) {
634                         ast_log(LOG_ERROR, "bad context %s or missing into %s\n",
635                                 context, into);
636                         goto error3;
637                 }
638
639                 if (ast_rdlock_contexts()) {
640                         ast_log(LOG_ERROR, "Failed to lock context list\n");
641                         goto error3;
642                 }
643
644                 for (c = NULL; (c = ast_walk_contexts(c)); )
645                         if (!strcmp(context, ast_get_context_name(c)))
646                                 break;
647                 if (c) { /* first context exists, go on... */
648                         /* go through all contexts ... */
649                         for (c = NULL; !ret && (c = ast_walk_contexts(c)); ) {
650                                 if (!strcmp(context, ast_get_context_name(c)))
651                                         continue; /* skip ourselves */
652                                 if (partial_match(ast_get_context_name(c), a->word, len) &&
653                                                 !lookup_ci(c, context) /* not included yet */ &&
654                                                 ++which > a->n)
655                                         ret = strdup(ast_get_context_name(c));
656                         }
657                 } else {
658                         ast_log(LOG_ERROR, "context %s not found\n", context);
659                 }
660                 ast_unlock_contexts();
661         error3:
662                 free(context);
663                 return ret;
664         }
665
666         return NULL;
667 }
668
669 /*!
670  * \brief 'save dialplan' CLI command implementation functions ...
671  */
672 static char *handle_cli_dialplan_save(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
673 {
674         char filename[256], overrideswitch[256] = "";
675         struct ast_context *c;
676         struct ast_config *cfg;
677         struct ast_variable *v;
678         int incomplete = 0; /* incomplete config write? */
679         FILE *output;
680         struct ast_flags config_flags = { 0 };
681         const char *base, *slash, *file;
682
683         switch (cmd) {
684         case CLI_INIT:
685                 e->command = "dialplan save";
686                 e->usage =
687                         "Usage: dialplan save [/path/to/extension/file]\n"
688                         "       Save dialplan created by pbx_config module.\n"
689                         "\n"
690                         "Example: dialplan save                 (/etc/asterisk/extensions.conf)\n"
691                         "         dialplan save /home/markster  (/home/markster/extensions.conf)\n";
692                 return NULL;
693         case CLI_GENERATE:
694                 return NULL;
695         }
696
697         if (! (static_config && !write_protect_config)) {
698                 ast_cli(a->fd,
699                         "I can't save dialplan now, see '%s' example file.\n",
700                         config);
701                 return CLI_FAILURE;
702         }
703
704         if (a->argc != 2 && a->argc != 3)
705                 return CLI_SHOWUSAGE;
706
707         if (ast_mutex_lock(&save_dialplan_lock)) {
708                 ast_cli(a->fd,
709                         "Failed to lock dialplan saving (another proccess saving?)\n");
710                 return CLI_FAILURE;
711         }
712         /* XXX the code here is quite loose, a pathname with .conf in it
713          * is assumed to be a complete pathname
714          */
715         if (a->argc == 3) {     /* have config path. Look for *.conf */
716                 base = a->argv[2];
717                 if (!strstr(a->argv[2], ".conf")) { /*no, this is assumed to be a pathname */
718                         /* if filename ends with '/', do not add one */
719                         slash = (*(a->argv[2] + strlen(a->argv[2]) -1) == '/') ? "/" : "";
720                         file = config;  /* default: 'extensions.conf' */
721                 } else {        /* yes, complete file name */
722                         slash = "";
723                         file = "";
724                 }
725         } else {
726                 /* no config file, default one */
727                 base = ast_config_AST_CONFIG_DIR;
728                 slash = "/";
729                 file = config;
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
910         switch (cmd) {
911         case CLI_INIT:
912                 e->command = "dialplan add extension";
913                 e->usage =
914                         "Usage: dialplan add extension <exten>,<priority>,<app>,<app-data>\n"
915                         "       into <context> [replace]\n\n"
916                         "       This command will add new extension into <context>. If there is an\n"
917                         "       existence of extension with the same priority and last 'replace'\n"
918                         "       arguments is given here we simply replace this extension.\n"
919                         "\n"
920                         "Example: dialplan add extension 6123,1,Dial,IAX/216.207.245.56/6123 into local\n"
921                         "         Now, you can dial 6123 and talk to Markster :)\n";
922                 return NULL;
923         case CLI_GENERATE:
924                 return complete_dialplan_add_extension(a);
925         }
926
927         /* check for arguments at first */
928         if (a->argc != 6 && a->argc != 7)
929                 return CLI_SHOWUSAGE;
930         if (strcmp(a->argv[4], "into"))
931                 return CLI_SHOWUSAGE;
932         if (a->argc == 7)
933                 if (strcmp(a->argv[6], "replace"))
934                         return CLI_SHOWUSAGE;
935
936         whole_exten = ast_strdupa(a->argv[3]);
937         exten = strsep(&whole_exten,",");
938         if (strchr(exten, '/')) {
939                 cidmatch = exten;
940                 strsep(&cidmatch,"/");
941         } else {
942                 cidmatch = NULL;
943         }
944         prior = strsep(&whole_exten,",");
945         if (prior) {
946                 if (!strcmp(prior, "hint")) {
947                         iprior = PRIORITY_HINT;
948                 } else {
949                         if (sscanf(prior, "%30d", &iprior) != 1) {
950                                 ast_cli(a->fd, "'%s' is not a valid priority\n", prior);
951                                 prior = NULL;
952                         }
953                 }
954         }
955         app = whole_exten;
956         if (app && (start = strchr(app, '(')) && (end = strrchr(app, ')'))) {
957                 *start = *end = '\0';
958                 app_data = start + 1;
959         } else {
960                 if (app) {
961                         app_data = strchr(app, ',');
962                         if (app_data) {
963                                 *app_data = '\0';
964                                 app_data++;
965                         }
966                 } else  
967                         app_data = NULL;
968         }
969
970         if (!exten || !prior || !app || (!app_data && iprior != PRIORITY_HINT))
971                 return CLI_SHOWUSAGE;
972
973         if (!app_data)
974                 app_data="";
975         if (ast_add_extension(a->argv[5], a->argc == 7 ? 1 : 0, exten, iprior, NULL, cidmatch, app,
976                 (void *)strdup(app_data), ast_free_ptr, registrar)) {
977                 switch (errno) {
978                 case ENOMEM:
979                         ast_cli(a->fd, "Out of free memory\n");
980                         break;
981
982                 case EBUSY:
983                         ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
984                         break;
985
986                 case ENOENT:
987                         ast_cli(a->fd, "No existence of '%s' context\n", a->argv[5]);
988                         break;
989
990                 case EEXIST:
991                         ast_cli(a->fd, "Extension %s@%s with priority %s already exists\n",
992                                 exten, a->argv[5], prior);
993                         break;
994
995                 default:
996                         ast_cli(a->fd, "Failed to add '%s,%s,%s,%s' extension into '%s' context\n",
997                                         exten, prior, app, app_data, a->argv[5]);
998                         break;
999                 }
1000                 return CLI_FAILURE;
1001         }
1002
1003         if (a->argc == 7)
1004                 ast_cli(a->fd, "Extension %s@%s (%s) replace by '%s,%s,%s,%s'\n",
1005                         exten, a->argv[5], prior, exten, prior, app, app_data);
1006         else
1007                 ast_cli(a->fd, "Extension '%s,%s,%s,%s' added into '%s' context\n",
1008                         exten, prior, app, app_data, a->argv[5]);
1009
1010         return CLI_SUCCESS;
1011 }
1012
1013 /*! dialplan add extension 6123,1,Dial,IAX/212.71.138.13/6123 into local */
1014 static char *complete_dialplan_add_extension(struct ast_cli_args *a)
1015 {
1016         int which = 0;
1017
1018         if (a->pos == 4) {              /* complete 'into' word ... */
1019                 return (a->n == 0) ? strdup("into") : NULL;
1020         } else if (a->pos == 5) { /* complete context */
1021                 struct ast_context *c = NULL;
1022                 int len = strlen(a->word);
1023                 char *res = NULL;
1024
1025                 /* try to lock contexts list ... */
1026                 if (ast_rdlock_contexts()) {
1027                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1028                         return NULL;
1029                 }
1030
1031                 /* walk through all contexts */
1032                 while ( !res && (c = ast_walk_contexts(c)) )
1033                         if (partial_match(ast_get_context_name(c), a->word, len) && ++which > a->n)
1034                                 res = strdup(ast_get_context_name(c));
1035                 ast_unlock_contexts();
1036                 return res;
1037         } else if (a->pos == 6) {
1038                 return a->n == 0 ? strdup("replace") : NULL;
1039         }
1040         return NULL;
1041 }
1042
1043 /*!
1044  * IGNOREPAT CLI stuff
1045  */
1046 static char *handle_cli_dialplan_add_ignorepat(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1047 {
1048         switch (cmd) {
1049         case CLI_INIT:
1050                 e->command = "dialplan add ignorepat";
1051                 e->usage =
1052                         "Usage: dialplan add ignorepat <pattern> into <context>\n"
1053                         "       This command adds a new ignore pattern into context <context>\n"
1054                         "\n"
1055                         "Example: dialplan add ignorepat _3XX into local\n";
1056                 return NULL;
1057         case CLI_GENERATE:
1058                 return complete_dialplan_add_ignorepat(a);
1059         }
1060
1061         if (a->argc != 6)
1062                 return CLI_SHOWUSAGE;
1063
1064         if (strcmp(a->argv[4], "into"))
1065                 return CLI_SHOWUSAGE;
1066
1067         if (ast_context_add_ignorepat(a->argv[5], a->argv[3], registrar)) {
1068                 switch (errno) {
1069                 case ENOMEM:
1070                         ast_cli(a->fd, "Out of free memory\n");
1071                         break;
1072
1073                 case ENOENT:
1074                         ast_cli(a->fd, "There is no existence of '%s' context\n", a->argv[5]);
1075                         break;
1076
1077                 case EEXIST:
1078                         ast_cli(a->fd, "Ignore pattern '%s' already included in '%s' context\n",
1079                                 a->argv[3], a->argv[5]);
1080                         break;
1081
1082                 case EBUSY:
1083                         ast_cli(a->fd, "Failed to lock context(s) list, please, try again later\n");
1084                         break;
1085
1086                 default:
1087                         ast_cli(a->fd, "Failed to add ingore pattern '%s' into '%s' context\n",
1088                                 a->argv[3], a->argv[5]);
1089                         break;
1090                 }
1091                 return CLI_FAILURE;
1092         }
1093
1094         ast_cli(a->fd, "Ignore pattern '%s' added into '%s' context\n",
1095                 a->argv[3], a->argv[5]);
1096
1097         return CLI_SUCCESS;
1098 }
1099
1100 static char *complete_dialplan_add_ignorepat(struct ast_cli_args *a)
1101 {
1102         if (a->pos == 4)
1103                 return a->n == 0 ? strdup("into") : NULL;
1104         else if (a->pos == 5) {
1105                 struct ast_context *c;
1106                 int which = 0;
1107                 char *dupline, *ignorepat = NULL;
1108                 const char *s;
1109                 char *ret = NULL;
1110                 int len = strlen(a->word);
1111
1112                 /* XXX skip first three words 'dialplan' 'add' 'ignorepat' */
1113                 s = skip_words(a->line, 3);
1114                 if (s == NULL)
1115                         return NULL;
1116                 dupline = strdup(s);
1117                 if (!dupline) {
1118                         ast_log(LOG_ERROR, "Malloc failure\n");
1119                         return NULL;
1120                 }
1121                 ignorepat = strsep(&dupline, " ");
1122
1123                 if (ast_rdlock_contexts()) {
1124                         ast_log(LOG_ERROR, "Failed to lock contexts list\n");
1125                         return NULL;
1126                 }
1127
1128                 for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
1129                         int found = 0;
1130
1131                         if (!partial_match(ast_get_context_name(c), a->word, len))
1132                                 continue; /* not mine */
1133                         if (ignorepat) /* there must be one, right ? */
1134                                 found = lookup_c_ip(c, ignorepat);
1135                         if (!found && ++which > a->n)
1136                                 ret = strdup(ast_get_context_name(c));
1137                 }
1138
1139                 free(ignorepat);
1140                 ast_unlock_contexts();
1141                 return ret;
1142         }
1143
1144         return NULL;
1145 }
1146
1147 static char *handle_cli_dialplan_remove_ignorepat(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1148 {
1149         switch (cmd) {
1150         case CLI_INIT:
1151                 e->command = "dialplan remove ignorepat";
1152                 e->usage =
1153                         "Usage: dialplan remove ignorepat <pattern> from <context>\n"
1154                         "       This command removes an ignore pattern from context <context>\n"
1155                         "\n"
1156                         "Example: dialplan remove ignorepat _3XX from local\n";
1157                 return NULL;
1158         case CLI_GENERATE:
1159                 return complete_dialplan_remove_ignorepat(a);
1160         }
1161
1162         if (a->argc != 6)
1163                 return CLI_SHOWUSAGE;
1164
1165         if (strcmp(a->argv[4], "from"))
1166                 return CLI_SHOWUSAGE;
1167
1168         if (ast_context_remove_ignorepat(a->argv[5], a->argv[3], registrar)) {
1169                 switch (errno) {
1170                 case EBUSY:
1171                         ast_cli(a->fd, "Failed to lock context(s) list, please try again later\n");
1172                         break;
1173
1174                 case ENOENT:
1175                         ast_cli(a->fd, "There is no existence of '%s' context\n", a->argv[5]);
1176                         break;
1177
1178                 case EINVAL:
1179                         ast_cli(a->fd, "There is no existence of '%s' ignore pattern in '%s' context\n",
1180                                         a->argv[3], a->argv[5]);
1181                         break;
1182
1183                 default:
1184                         ast_cli(a->fd, "Failed to remove ignore pattern '%s' from '%s' context\n",
1185                                         a->argv[3], a->argv[5]);
1186                         break;
1187                 }
1188                 return CLI_FAILURE;
1189         }
1190
1191         ast_cli(a->fd, "Ignore pattern '%s' removed from '%s' context\n",
1192                 a->argv[3], a->argv[5]);
1193         return CLI_SUCCESS;
1194 }
1195
1196 static char *complete_dialplan_remove_ignorepat(struct ast_cli_args *a)
1197 {
1198         struct ast_context *c;
1199         int which = 0;
1200         char *ret = NULL;
1201
1202         if (a->pos == 3) {
1203                 int len = strlen(a->word);
1204                 if (ast_rdlock_contexts()) {
1205                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1206                         return NULL;
1207                 }
1208
1209                 for (c = NULL; !ret && (c = ast_walk_contexts(c));) {
1210                         struct ast_ignorepat *ip;
1211
1212                         if (ast_rdlock_context(c))      /* error, skip it */
1213                                 continue;
1214                         
1215                         for (ip = NULL; !ret && (ip = ast_walk_context_ignorepats(c, ip));) {
1216                                 if (partial_match(ast_get_ignorepat_name(ip), a->word, len) && ++which > a->n) {
1217                                         /* n-th match */
1218                                         struct ast_context *cw = NULL;
1219                                         int found = 0;
1220                                         while ( (cw = ast_walk_contexts(cw)) && cw != c && !found) {
1221                                                 /* XXX do i stop on c, or skip it ? */
1222                                                 found = lookup_c_ip(cw, ast_get_ignorepat_name(ip));
1223                                         }
1224                                         if (!found)
1225                                                 ret = strdup(ast_get_ignorepat_name(ip));
1226                                 }
1227                         }
1228                         ast_unlock_context(c);
1229                 }
1230                 ast_unlock_contexts();
1231                 return ret;
1232         } else if (a->pos == 4) {
1233                  return a->n == 0 ? strdup("from") : NULL;
1234         } else if (a->pos == 5) { /* XXX check this */
1235                 char *dupline, *duplinet, *ignorepat;
1236                 int len = strlen(a->word);
1237
1238                 dupline = strdup(a->line);
1239                 if (!dupline) {
1240                         ast_log(LOG_WARNING, "Out of free memory\n");
1241                         return NULL;
1242                 }
1243
1244                 duplinet = dupline;
1245                 strsep(&duplinet, " ");
1246                 strsep(&duplinet, " ");
1247                 ignorepat = strsep(&duplinet, " ");
1248
1249                 if (!ignorepat) {
1250                         free(dupline);
1251                         return NULL;
1252                 }
1253
1254                 if (ast_rdlock_contexts()) {
1255                         ast_log(LOG_WARNING, "Failed to lock contexts list\n");
1256                         free(dupline);
1257                         return NULL;
1258                 }
1259
1260                 for (c = NULL; !ret && (c = ast_walk_contexts(c)); ) {
1261                         if (ast_rdlock_context(c))      /* fail, skip it */
1262                                 continue;
1263                         if (!partial_match(ast_get_context_name(c), a->word, len))
1264                                 continue;
1265                         if (lookup_c_ip(c, ignorepat) && ++which > a->n)
1266                                 ret = strdup(ast_get_context_name(c));
1267                         ast_unlock_context(c);
1268                 }
1269                 ast_unlock_contexts();
1270                 free(dupline);
1271                 return NULL;
1272         }
1273
1274         return NULL;
1275 }
1276
1277 static int pbx_load_module(void);
1278
1279 static char *handle_cli_dialplan_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1280 {
1281         switch (cmd) {
1282         case CLI_INIT:
1283                 e->command = "dialplan reload";
1284                 e->usage =
1285                         "Usage: dialplan reload\n"
1286                         "       Reload extensions.conf without reloading any other\n"
1287                         "       modules.  This command does not delete global variables\n"
1288                         "       unless clearglobalvars is set to yes in extensions.conf\n";
1289                 return NULL;
1290         case CLI_GENERATE:
1291                 return NULL;
1292         }
1293
1294         if (a->argc != 2)
1295                 return CLI_SHOWUSAGE;
1296
1297         if (clearglobalvars_config)
1298                 pbx_builtin_clear_globals();
1299
1300         pbx_load_module();
1301         ast_cli(a->fd, "Dialplan reloaded.\n");
1302         return CLI_SUCCESS;
1303 }
1304
1305 /*!
1306  * CLI entries for commands provided by this module
1307  */
1308 static struct ast_cli_entry cli_pbx_config[] = {
1309         AST_CLI_DEFINE(handle_cli_dialplan_add_extension,    "Add new extension into context"),
1310         AST_CLI_DEFINE(handle_cli_dialplan_remove_extension, "Remove a specified extension"),
1311         AST_CLI_DEFINE(handle_cli_dialplan_add_ignorepat,    "Add new ignore pattern"),
1312         AST_CLI_DEFINE(handle_cli_dialplan_remove_ignorepat, "Remove ignore pattern from context"),
1313         AST_CLI_DEFINE(handle_cli_dialplan_add_include,      "Include context in other context"),
1314         AST_CLI_DEFINE(handle_cli_dialplan_remove_include,   "Remove a specified include from context"),
1315         AST_CLI_DEFINE(handle_cli_dialplan_reload,           "Reload extensions and *only* extensions")
1316 };
1317
1318 static struct ast_cli_entry cli_dialplan_save =
1319         AST_CLI_DEFINE(handle_cli_dialplan_save, "Save dialplan");
1320
1321 /*!
1322  * Standard module functions ...
1323  */
1324 static int unload_module(void)
1325 {
1326         if (static_config && !write_protect_config)
1327                 ast_cli_unregister(&cli_dialplan_save);
1328         if (overrideswitch_config) {
1329                 ast_free(overrideswitch_config);
1330         }
1331         ast_cli_unregister_multiple(cli_pbx_config, ARRAY_LEN(cli_pbx_config));
1332         ast_context_destroy(NULL, registrar);
1333         return 0;
1334 }
1335
1336 /*!\note Protect against misparsing based upon commas in the middle of fields
1337  * like character classes.  We've taken steps to permit pretty much every other
1338  * printable character in a character class, so properly handling a comma at
1339  * this level is a natural extension.  This is almost like the standard
1340  * application parser in app.c, except that it handles square brackets. */
1341 static char *pbx_strsep(char **destructible, const char *delim)
1342 {
1343         int square = 0;
1344         char *res = *destructible;
1345         for (; destructible && *destructible && **destructible; (*destructible)++) {
1346                 if (**destructible == '[' && !strchr(delim, '[')) {
1347                         square++;
1348                 } else if (**destructible == ']' && !strchr(delim, ']')) {
1349                         if (square) {
1350                                 square--;
1351                         }
1352                 } else if (**destructible == '\\' && !strchr(delim, '\\')) {
1353                         (*destructible)++;
1354                 } else if (strchr(delim, **destructible) && !square) {
1355                         **destructible = '\0';
1356                         (*destructible)++;
1357                         break;
1358                 }
1359         }
1360         if (destructible && *destructible && **destructible == '\0') {
1361                 *destructible = NULL;
1362         }
1363         return res;
1364 }
1365
1366 static int pbx_load_config(const char *config_file)
1367 {
1368         struct ast_config *cfg;
1369         char *end;
1370         char *label;
1371 #ifdef LOW_MEMORY
1372         char realvalue[256];
1373 #else
1374         char realvalue[8192];
1375 #endif
1376         int lastpri = -2;
1377         struct ast_context *con;
1378         struct ast_variable *v;
1379         const char *cxt;
1380         const char *aft;
1381         const char *newpm, *ovsw;
1382         struct ast_flags config_flags = { 0 };
1383         char lastextension[256];
1384         cfg = ast_config_load(config_file, config_flags);
1385         if (!cfg || cfg == CONFIG_STATUS_FILEINVALID)
1386                 return 0;
1387
1388         /* Use existing config to populate the PBX table */
1389         static_config = ast_true(ast_variable_retrieve(cfg, "general", "static"));
1390         write_protect_config = ast_true(ast_variable_retrieve(cfg, "general", "writeprotect"));
1391         if ((aft = ast_variable_retrieve(cfg, "general", "autofallthrough")))
1392                 autofallthrough_config = ast_true(aft);
1393         if ((newpm = ast_variable_retrieve(cfg, "general", "extenpatternmatchnew")))
1394                 extenpatternmatchnew_config = ast_true(newpm);
1395         clearglobalvars_config = ast_true(ast_variable_retrieve(cfg, "general", "clearglobalvars"));
1396         if ((ovsw = ast_variable_retrieve(cfg, "general", "overrideswitch"))) {
1397                 if (overrideswitch_config) {
1398                         ast_free(overrideswitch_config);
1399                 }
1400                 if (!ast_strlen_zero(ovsw)) {
1401                         overrideswitch_config = ast_strdup(ovsw);
1402                 } else {
1403                         overrideswitch_config = NULL;
1404                 }
1405         }
1406
1407         ast_copy_string(userscontext, ast_variable_retrieve(cfg, "general", "userscontext") ?: "default", sizeof(userscontext));
1408                                                                     
1409         for (v = ast_variable_browse(cfg, "globals"); v; v = v->next) {
1410                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1411                 pbx_builtin_setvar_helper(NULL, v->name, realvalue);
1412         }
1413         for (cxt = ast_category_browse(cfg, NULL);
1414              cxt;
1415              cxt = ast_category_browse(cfg, cxt)) {
1416                 /* All categories but "general" or "globals" are considered contexts */
1417                 if (!strcasecmp(cxt, "general") || !strcasecmp(cxt, "globals")) {
1418                         continue;
1419                 }
1420                 if (!(con = ast_context_find_or_create(&local_contexts, local_table, cxt, registrar))) {
1421                         continue;
1422                 }
1423
1424                 /* Reset continuation items at the beginning of each context */
1425                 lastextension[0] = '\0';
1426                 lastpri = -2;
1427
1428                 for (v = ast_variable_browse(cfg, cxt); v; v = v->next) {
1429                         char *tc = NULL;
1430                         char realext[256] = "";
1431                         char *stringp, *ext;
1432
1433                         if (!strncasecmp(v->name, "same", 4)) {
1434                                 if (ast_strlen_zero(lastextension)) {
1435                                         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);
1436                                         continue;
1437                                 }
1438                                 if ((stringp = tc = ast_strdup(v->value))) {
1439                                         ast_copy_string(realext, lastextension, sizeof(realext));
1440                                         goto process_extension;
1441                                 }
1442                         } else if (!strcasecmp(v->name, "exten")) {
1443                                 int ipri;
1444                                 char *plus, *firstp;
1445                                 char *pri, *appl, *data, *cidmatch;
1446
1447                                 if (!(stringp = tc = ast_strdup(v->value))) {
1448                                         continue;
1449                                 }
1450
1451                                 ext = S_OR(pbx_strsep(&stringp, ","), "");
1452                                 pbx_substitute_variables_helper(NULL, ext, realext, sizeof(realext) - 1);
1453                                 ast_copy_string(lastextension, realext, sizeof(lastextension));
1454 process_extension:
1455                                 ipri = -2;
1456                                 if ((cidmatch = strchr(realext, '/'))) {
1457                                         *cidmatch++ = '\0';
1458                                         ast_shrink_phone_number(cidmatch);
1459                                 }
1460                                 pri = S_OR(strsep(&stringp, ","), "");
1461                                 pri = ast_skip_blanks(pri);
1462                                 pri = ast_trim_blanks(pri);
1463                                 if ((label = strchr(pri, '('))) {
1464                                         *label++ = '\0';
1465                                         if ((end = strchr(label, ')'))) {
1466                                                 *end = '\0';
1467                                         } else {
1468                                                 ast_log(LOG_WARNING, "Label missing trailing ')' at line %d\n", v->lineno);
1469                                         }
1470                                 }
1471                                 if ((plus = strchr(pri, '+'))) {
1472                                         *plus++ = '\0';
1473                                 }
1474                                 if (!strcmp(pri,"hint")) {
1475                                         ipri = PRIORITY_HINT;
1476                                 } else if (!strcmp(pri, "next") || !strcmp(pri, "n")) {
1477                                         if (lastpri > -2) {
1478                                                 ipri = lastpri + 1;
1479                                         } else {
1480                                                 ast_log(LOG_WARNING, "Can't use 'next' priority on the first entry at line %d!\n", v->lineno);
1481                                         }
1482                                 } else if (!strcmp(pri, "same") || !strcmp(pri, "s")) {
1483                                         if (lastpri > -2) {
1484                                                 ipri = lastpri;
1485                                         } else {
1486                                                 ast_log(LOG_WARNING, "Can't use 'same' priority on the first entry at line %d!\n", v->lineno);
1487                                         }
1488                                 } else if (sscanf(pri, "%30d", &ipri) != 1 &&
1489                                            (ipri = ast_findlabel_extension2(NULL, con, realext, pri, cidmatch)) < 1) {
1490                                         ast_log(LOG_WARNING, "Invalid priority/label '%s' at line %d\n", pri, v->lineno);
1491                                         ipri = 0;
1492                                 }
1493                                 appl = S_OR(stringp, "");
1494                                 /* Find the first occurrence of '(' */
1495                                 if (!(firstp = strchr(appl, '('))) {
1496                                         /* No arguments */
1497                                         data = "";
1498                                 } else {
1499                                         char *orig_appl = ast_strdup(appl);
1500
1501                                         if (!orig_appl)
1502                                                 return -1;
1503                                         
1504                                         appl = strsep(&stringp, "(");
1505
1506                                         /* check if there are variables or expressions without an application, like: exten => 100,hint,DAHDI/g0/${GLOBAL(var)}  */
1507                                         if (strstr(appl, "${") || strstr(appl, "$[")){
1508                                                 /* set appl to original one */
1509                                                 strcpy(appl, orig_appl);
1510                                                 /* set no data */
1511                                                 data = "";
1512                                         /* no variable before application found -> go ahead */
1513                                         } else {
1514                                                 data = S_OR(stringp, "");
1515                                                 if ((end = strrchr(data, ')'))) {
1516                                                         *end = '\0';
1517                                                 } else {
1518                                                         ast_log(LOG_WARNING, "No closing parenthesis found? '%s(%s' at line %d\n", appl, data, v->lineno);
1519                                                 }
1520                                         }
1521                                         ast_free(orig_appl);
1522                                 }
1523
1524                                 appl = ast_skip_blanks(appl);
1525                                 if (ipri) {
1526                                         if (plus) {
1527                                                 ipri += atoi(plus);
1528                                         }
1529                                         lastpri = ipri;
1530                                         if (!ast_opt_dont_warn && !strcmp(realext, "_.")) {
1531                                                 ast_log(LOG_WARNING, "The use of '_.' for an extension is strongly discouraged and can have unexpected behavior.  Please use '_X.' instead at line %d\n", v->lineno);
1532                                         }
1533                                         if (ast_add_extension2(con, 0, realext, ipri, label, cidmatch, appl, strdup(data), ast_free_ptr, registrar)) {
1534                                                 ast_log(LOG_WARNING, "Unable to register extension at line %d\n", v->lineno);
1535                                         }
1536                                 }
1537                                 free(tc);
1538                         } else if (!strcasecmp(v->name, "include")) {
1539                                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1540                                 if (ast_context_add_include2(con, realvalue, registrar)) {
1541                                         switch (errno) {
1542                                                 case ENOMEM:
1543                                                         ast_log(LOG_WARNING, "Out of memory for context addition\n");
1544                                                         break;
1545
1546                                                 case EBUSY:
1547                                                         ast_log(LOG_WARNING, "Failed to lock context(s) list, please try again later\n");
1548                                                         break;
1549
1550                                                 case EEXIST:
1551                                                         ast_log(LOG_WARNING, "Context '%s' already included in '%s' context on include at line %d\n",
1552                                                                         v->value, cxt, v->lineno);
1553                                                         break;
1554
1555                                                 case ENOENT:
1556                                                 case EINVAL:
1557                                                         ast_log(LOG_WARNING, "There is no existence of context '%s' included at line %d\n",
1558                                                                         errno == ENOENT ? v->value : cxt, v->lineno);
1559                                                         break;
1560
1561                                                 default:
1562                                                         ast_log(LOG_WARNING, "Failed to include '%s' in '%s' context at line %d\n",
1563                                                                         v->value, cxt, v->lineno);
1564                                                         break;
1565                                         }
1566                                 }
1567                         } else if (!strcasecmp(v->name, "ignorepat")) {
1568                                 pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1569                                 if (ast_context_add_ignorepat2(con, realvalue, registrar)) {
1570                                         ast_log(LOG_WARNING, "Unable to include ignorepat '%s' in context '%s' at line %d\n", v->value, cxt, v->lineno);
1571                                 }
1572                         } else if (!strcasecmp(v->name, "switch") || !strcasecmp(v->name, "lswitch") || !strcasecmp(v->name, "eswitch")) {
1573                                 char *stringp = realvalue;
1574                                 char *appl, *data;
1575                                 
1576                                 if (!strcasecmp(v->name, "switch")) {
1577                                         pbx_substitute_variables_helper(NULL, v->value, realvalue, sizeof(realvalue) - 1);
1578                                 } else {
1579                                         ast_copy_string(realvalue, v->value, sizeof(realvalue));
1580                                 }
1581                                 appl = strsep(&stringp, "/");
1582                                 data = S_OR(stringp, "");
1583                                 if (ast_context_add_switch2(con, appl, data, !strcasecmp(v->name, "eswitch"), registrar)) {
1584                                         ast_log(LOG_WARNING, "Unable to include switch '%s' in context '%s' at line %d\n", v->value, cxt, v->lineno);
1585                                 }
1586                         } else {
1587                                 ast_log(LOG_WARNING, "==!!== Unknown directive: %s at line %d -- IGNORING!!!\n", v->name, v->lineno);
1588                         }
1589                 }
1590         }
1591         ast_config_destroy(cfg);
1592         return 1;
1593 }
1594
1595 static void append_interface(char *iface, int maxlen, char *add)
1596 {
1597         int len = strlen(iface);
1598         if (strlen(add) + len < maxlen - 2) {
1599                 if (strlen(iface)) {
1600                         iface[len] = '&';
1601                         strcpy(iface + len + 1, add);
1602                 } else
1603                         strcpy(iface, add);
1604         }
1605 }
1606
1607 static void pbx_load_users(void)
1608 {
1609         struct ast_config *cfg;
1610         char *cat, *chan;
1611         const char *dahdichan;
1612         const char *hasexten, *altexts;
1613         char tmp[256];
1614         char iface[256];
1615         char dahdicopy[256];
1616         char *ext, altcopy[256];
1617         char *c;
1618         int len;
1619         int hasvoicemail;
1620         int start, finish, x;
1621         struct ast_context *con = NULL;
1622         struct ast_flags config_flags = { 0 };
1623         
1624         cfg = ast_config_load("users.conf", config_flags);
1625         if (!cfg)
1626                 return;
1627
1628         for (cat = ast_category_browse(cfg, NULL); cat ; cat = ast_category_browse(cfg, cat)) {
1629                 if (!strcasecmp(cat, "general"))
1630                         continue;
1631                 iface[0] = '\0';
1632                 len = sizeof(iface);
1633                 if (ast_true(ast_config_option(cfg, cat, "hassip"))) {
1634                         snprintf(tmp, sizeof(tmp), "SIP/%s", cat);
1635                         append_interface(iface, sizeof(iface), tmp);
1636                 }
1637                 if (ast_true(ast_config_option(cfg, cat, "hasiax"))) {
1638                         snprintf(tmp, sizeof(tmp), "IAX2/%s", cat);
1639                         append_interface(iface, sizeof(iface), tmp);
1640                 }
1641                 if (ast_true(ast_config_option(cfg, cat, "hash323"))) {
1642                         snprintf(tmp, sizeof(tmp), "H323/%s", cat);
1643                         append_interface(iface, sizeof(iface), tmp);
1644                 }
1645                 hasexten = ast_config_option(cfg, cat, "hasexten");
1646                 if (hasexten && !ast_true(hasexten))
1647                         continue;
1648                 hasvoicemail = ast_true(ast_config_option(cfg, cat, "hasvoicemail"));
1649                 dahdichan = ast_variable_retrieve(cfg, cat, "dahdichan");
1650                 if (!dahdichan)
1651                         dahdichan = ast_variable_retrieve(cfg, "general", "dahdichan");
1652                 if (!ast_strlen_zero(dahdichan)) {
1653                         ast_copy_string(dahdicopy, dahdichan, sizeof(dahdicopy));
1654                         c = dahdicopy;
1655                         chan = strsep(&c, ",");
1656                         while (chan) {
1657                                 if (sscanf(chan, "%30d-%30d", &start, &finish) == 2) {
1658                                         /* Range */
1659                                 } else if (sscanf(chan, "%30d", &start)) {
1660                                         /* Just one */
1661                                         finish = start;
1662                                 } else {
1663                                         start = 0; finish = 0;
1664                                 }
1665                                 if (finish < start) {
1666                                         x = finish;
1667                                         finish = start;
1668                                         start = x;
1669                                 }
1670                                 for (x = start; x <= finish; x++) {
1671                                         snprintf(tmp, sizeof(tmp), "DAHDI/%d", x);
1672                                         append_interface(iface, sizeof(iface), tmp);
1673                                 }
1674                                 chan = strsep(&c, ",");
1675                         }
1676                 }
1677                 if (!ast_strlen_zero(iface)) {
1678                         /* Only create a context here when it is really needed. Otherwise default empty context
1679                         created by pbx_config may conflict with the one explicitly created by pbx_ael */
1680                         if (!con)
1681                                 con = ast_context_find_or_create(&local_contexts, local_table, userscontext, registrar);
1682
1683                         if (!con) {
1684                                 ast_log(LOG_ERROR, "Can't find/create user context '%s'\n", userscontext);
1685                                 return;
1686                         }
1687
1688                         /* Add hint */
1689                         ast_add_extension2(con, 0, cat, -1, NULL, NULL, iface, NULL, NULL, registrar);
1690                         /* If voicemail, use "stdexten" else use plain old dial */
1691                         if (hasvoicemail) {
1692                                 snprintf(tmp, sizeof(tmp), "stdexten,%s,${HINT}", cat);
1693                                 ast_add_extension2(con, 0, cat, 1, NULL, NULL, "Macro", strdup(tmp), ast_free_ptr, registrar);
1694                         } else {
1695                                 ast_add_extension2(con, 0, cat, 1, NULL, NULL, "Dial", strdup("${HINT}"), ast_free_ptr, registrar);
1696                         }
1697                         altexts = ast_variable_retrieve(cfg, cat, "alternateexts");
1698                         if (!ast_strlen_zero(altexts)) {
1699                                 snprintf(tmp, sizeof(tmp), "%s,1", cat);
1700                                 ast_copy_string(altcopy, altexts, sizeof(altcopy));
1701                                 c = altcopy;
1702                                 ext = strsep(&c, ",");
1703                                 while (ext) {
1704                                         ast_add_extension2(con, 0, ext, 1, NULL, NULL, "Goto", strdup(tmp), ast_free_ptr, registrar);
1705                                         ext = strsep(&c, ",");
1706                                 }
1707                         }
1708                 }
1709         }
1710         ast_config_destroy(cfg);
1711 }
1712
1713 static int pbx_load_module(void)
1714 {
1715         struct ast_context *con;
1716
1717         if (!local_table)
1718                 local_table = ast_hashtab_create(17, ast_hashtab_compare_contexts, ast_hashtab_resize_java, ast_hashtab_newsize_java, ast_hashtab_hash_contexts, 0);
1719
1720         if (!pbx_load_config(config))
1721                 return AST_MODULE_LOAD_DECLINE;
1722         
1723         pbx_load_users();
1724
1725         ast_merge_contexts_and_delete(&local_contexts, local_table, registrar);
1726         local_table = NULL; /* the local table has been moved into the global one. */
1727         local_contexts = NULL;
1728
1729         for (con = NULL; (con = ast_walk_contexts(con));)
1730                 ast_context_verify_includes(con);
1731
1732         pbx_set_overrideswitch(overrideswitch_config);
1733         pbx_set_autofallthrough(autofallthrough_config);
1734         pbx_set_extenpatternmatchnew(extenpatternmatchnew_config);
1735
1736         return AST_MODULE_LOAD_SUCCESS;
1737 }
1738
1739 static int load_module(void)
1740 {
1741         if (pbx_load_module())
1742                 return AST_MODULE_LOAD_DECLINE;
1743  
1744         if (static_config && !write_protect_config)
1745                 ast_cli_register(&cli_dialplan_save);
1746         ast_cli_register_multiple(cli_pbx_config, ARRAY_LEN(cli_pbx_config));
1747
1748         return AST_MODULE_LOAD_SUCCESS;
1749 }
1750
1751 static int reload(void)
1752 {
1753         if (clearglobalvars_config)
1754                 pbx_builtin_clear_globals();
1755         return pbx_load_module();
1756 }
1757
1758 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Text Extension Configuration",
1759                 .load = load_module,
1760                 .unload = unload_module,
1761                 .reload = reload,
1762                );