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