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