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