Changing name of global api call to ast_*
[asterisk/asterisk.git] / main / pbx.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, 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 Core PBX routines.
22  *
23  * \author Mark Spencer <markster@digium.com>
24  */
25
26 #include "asterisk.h"
27
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
29
30 #include "asterisk/_private.h"
31 #include "asterisk/paths.h"     /* use ast_config_AST_SYSTEM_NAME */
32 #include <ctype.h>
33 #include <time.h>
34 #include <sys/time.h>
35 #if defined(HAVE_SYSINFO)
36 #include <sys/sysinfo.h>
37 #endif
38 #if defined(SOLARIS)
39 #include <sys/loadavg.h>
40 #endif
41
42 #include "asterisk/lock.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/file.h"
47 #include "asterisk/callerid.h"
48 #include "asterisk/cdr.h"
49 #include "asterisk/config.h"
50 #include "asterisk/term.h"
51 #include "asterisk/time.h"
52 #include "asterisk/manager.h"
53 #include "asterisk/ast_expr.h"
54 #include "asterisk/linkedlists.h"
55 #define SAY_STUBS       /* generate declarations and stubs for say methods */
56 #include "asterisk/say.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/causes.h"
59 #include "asterisk/musiconhold.h"
60 #include "asterisk/app.h"
61 #include "asterisk/devicestate.h"
62 #include "asterisk/stringfields.h"
63 #include "asterisk/event.h"
64 #include "asterisk/hashtab.h"
65 #include "asterisk/module.h"
66 #include "asterisk/indications.h"
67 #include "asterisk/taskprocessor.h"
68
69 /*!
70  * \note I M P O R T A N T :
71  *
72  *              The speed of extension handling will likely be among the most important
73  * aspects of this PBX.  The switching scheme as it exists right now isn't
74  * terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
75  * of priorities, but a constant search time here would be great ;-)
76  *
77  * A new algorithm to do searching based on a 'compiled' pattern tree is introduced
78  * here, and shows a fairly flat (constant) search time, even for over
79  * 10000 patterns. 
80  *
81  * Also, using a hash table for context/priority name lookup can help prevent
82  * the find_extension routines from absorbing exponential cpu cycles as the number 
83  * of contexts/priorities grow. I've previously tested find_extension with red-black trees, 
84  * which have O(log2(n)) speed. Right now, I'm using hash tables, which do 
85  * searches (ideally) in O(1) time. While these techniques do not yield much 
86  * speed in small dialplans, they are worth the trouble in large dialplans.
87  *
88  */
89
90 #ifdef LOW_MEMORY
91 #define EXT_DATA_SIZE 256
92 #else
93 #define EXT_DATA_SIZE 8192
94 #endif
95
96 #define SWITCH_DATA_LENGTH 256
97
98 #define VAR_BUF_SIZE 4096
99
100 #define VAR_NORMAL              1
101 #define VAR_SOFTTRAN    2
102 #define VAR_HARDTRAN    3
103
104 #define BACKGROUND_SKIP         (1 << 0)
105 #define BACKGROUND_NOANSWER     (1 << 1)
106 #define BACKGROUND_MATCHEXTEN   (1 << 2)
107 #define BACKGROUND_PLAYBACK     (1 << 3)
108
109 AST_APP_OPTIONS(background_opts, {
110         AST_APP_OPTION('s', BACKGROUND_SKIP),
111         AST_APP_OPTION('n', BACKGROUND_NOANSWER),
112         AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
113         AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
114 });
115
116 #define WAITEXTEN_MOH           (1 << 0)
117 #define WAITEXTEN_DIALTONE      (1 << 1)
118
119 AST_APP_OPTIONS(waitexten_opts, {
120         AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
121         AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0),
122 });
123
124 struct ast_context;
125 struct ast_app;
126
127 static struct ast_taskprocessor *device_state_tps;
128
129 AST_THREADSTORAGE(switch_data);
130
131 /*!
132    \brief ast_exten: An extension
133         The dialplan is saved as a linked list with each context
134         having it's own linked list of extensions - one item per
135         priority.
136 */
137 struct ast_exten {
138         char *exten;                    /*!< Extension name */
139         int matchcid;                   /*!< Match caller id ? */
140         const char *cidmatch;           /*!< Caller id to match for this extension */
141         int priority;                   /*!< Priority */
142         const char *label;              /*!< Label */
143         struct ast_context *parent;     /*!< The context this extension belongs to  */
144         const char *app;                /*!< Application to execute */
145         struct ast_app *cached_app;     /*!< Cached location of application */
146         void *data;                     /*!< Data to use (arguments) */
147         void (*datad)(void *);          /*!< Data destructor */
148         struct ast_exten *peer;         /*!< Next higher priority with our extension */
149         struct ast_hashtab *peer_table;    /*!< Priorities list in hashtab form -- only on the head of the peer list */
150         struct ast_hashtab *peer_label_table; /*!< labeled priorities in the peers -- only on the head of the peer list */
151         const char *registrar;          /*!< Registrar */
152         struct ast_exten *next;         /*!< Extension with a greater ID */
153         char stuff[0];
154 };
155
156 /*! \brief ast_include: include= support in extensions.conf */
157 struct ast_include {
158         const char *name;
159         const char *rname;                      /*!< Context to include */
160         const char *registrar;                  /*!< Registrar */
161         int hastime;                            /*!< If time construct exists */
162         struct ast_timing timing;               /*!< time construct */
163         struct ast_include *next;               /*!< Link them together */
164         char stuff[0];
165 };
166
167 /*! \brief ast_sw: Switch statement in extensions.conf */
168 struct ast_sw {
169         char *name;
170         const char *registrar;                  /*!< Registrar */
171         char *data;                             /*!< Data load */
172         int eval;
173         AST_LIST_ENTRY(ast_sw) list;
174         char stuff[0];
175 };
176
177 /*! \brief ast_ignorepat: Ignore patterns in dial plan */
178 struct ast_ignorepat {
179         const char *registrar;
180         struct ast_ignorepat *next;
181         const char pattern[0];
182 };
183
184 /*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
185 struct match_char
186 {
187         int is_pattern; /* the pattern started with '_' */
188         int deleted;    /* if this is set, then... don't return it */
189         char *x;       /* the pattern itself-- matches a single char */
190         int specificity; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */
191         struct match_char *alt_char;
192         struct match_char *next_char;
193         struct ast_exten *exten; /* attached to last char of a pattern for exten */
194 };
195
196 struct scoreboard  /* make sure all fields are 0 before calling new_find_extension */
197 {
198         int total_specificity;
199         int total_length;
200         char last_char;   /* set to ! or . if they are the end of the pattern */
201         int canmatch;     /* if the string to match was just too short */
202         struct match_char *node;
203         struct ast_exten *canmatch_exten;
204         struct ast_exten *exten;
205 };
206
207 /*! \brief ast_context: An extension context */
208 struct ast_context {
209         ast_rwlock_t lock;                      /*!< A lock to prevent multiple threads from clobbering the context */
210         struct ast_exten *root;                 /*!< The root of the list of extensions */
211         struct ast_hashtab *root_table;            /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree  */
212         struct match_char *pattern_tree;        /*!< A tree to speed up extension pattern matching */
213         struct ast_context *next;               /*!< Link them together */
214         struct ast_include *includes;           /*!< Include other contexts */
215         struct ast_ignorepat *ignorepats;       /*!< Patterns for which to continue playing dialtone */
216         const char *registrar;                  /*!< Registrar */
217         int refcount;                   /*!< each module that would have created this context should inc/dec this as appropriate */
218         AST_LIST_HEAD_NOLOCK(, ast_sw) alts;    /*!< Alternative switches */
219         ast_mutex_t macrolock;                  /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
220         char name[0];                           /*!< Name of the context */
221 };
222
223
224 /*! \brief ast_app: A registered application */
225 struct ast_app {
226         int (*execute)(struct ast_channel *chan, void *data);
227         const char *synopsis;                   /*!< Synopsis text for 'show applications' */
228         const char *description;                /*!< Description (help text) for 'show application &lt;name&gt;' */
229         AST_RWLIST_ENTRY(ast_app) list;         /*!< Next app in list */
230         struct ast_module *module;              /*!< Module this app belongs to */
231         char name[0];                           /*!< Name of the application */
232 };
233
234 /*! \brief ast_state_cb: An extension state notify register item */
235 struct ast_state_cb {
236         int id;
237         void *data;
238         ast_state_cb_type callback;
239         AST_LIST_ENTRY(ast_state_cb) entry;
240 };
241
242 /*! \brief Structure for dial plan hints
243
244   \note Hints are pointers from an extension in the dialplan to one or
245   more devices (tech/name) 
246         - See \ref AstExtState
247 */
248 struct ast_hint {
249         struct ast_exten *exten;        /*!< Extension */
250         int laststate;                  /*!< Last known state */
251         AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks; /*!< Callback list for this extension */
252         AST_RWLIST_ENTRY(ast_hint) list;/*!< Pointer to next hint in list */
253 };
254
255 static const struct cfextension_states {
256         int extension_state;
257         const char * const text;
258 } extension_states[] = {
259         { AST_EXTENSION_NOT_INUSE,                     "Idle" },
260         { AST_EXTENSION_INUSE,                         "InUse" },
261         { AST_EXTENSION_BUSY,                          "Busy" },
262         { AST_EXTENSION_UNAVAILABLE,                   "Unavailable" },
263         { AST_EXTENSION_RINGING,                       "Ringing" },
264         { AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
265         { AST_EXTENSION_ONHOLD,                        "Hold" },
266         { AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD,  "InUse&Hold" }
267 };
268
269 struct statechange {
270         AST_LIST_ENTRY(statechange) entry;
271         char dev[0];
272 };
273
274 struct pbx_exception {
275         AST_DECLARE_STRING_FIELDS(
276                 AST_STRING_FIELD(context);      /*!< Context associated with this exception */
277                 AST_STRING_FIELD(exten);        /*!< Exten associated with this exception */
278                 AST_STRING_FIELD(reason);               /*!< The exception reason */
279         );
280
281         int priority;                           /*!< Priority associated with this exception */
282 };
283
284 static int pbx_builtin_answer(struct ast_channel *, void *);
285 static int pbx_builtin_goto(struct ast_channel *, void *);
286 static int pbx_builtin_hangup(struct ast_channel *, void *);
287 static int pbx_builtin_background(struct ast_channel *, void *);
288 static int pbx_builtin_wait(struct ast_channel *, void *);
289 static int pbx_builtin_waitexten(struct ast_channel *, void *);
290 static int pbx_builtin_incomplete(struct ast_channel *, void *);
291 static int pbx_builtin_keepalive(struct ast_channel *, void *);
292 static int pbx_builtin_resetcdr(struct ast_channel *, void *);
293 static int pbx_builtin_setamaflags(struct ast_channel *, void *);
294 static int pbx_builtin_ringing(struct ast_channel *, void *);
295 static int pbx_builtin_progress(struct ast_channel *, void *);
296 static int pbx_builtin_congestion(struct ast_channel *, void *);
297 static int pbx_builtin_busy(struct ast_channel *, void *);
298 static int pbx_builtin_noop(struct ast_channel *, void *);
299 static int pbx_builtin_gotoif(struct ast_channel *, void *);
300 static int pbx_builtin_gotoiftime(struct ast_channel *, void *);
301 static int pbx_builtin_execiftime(struct ast_channel *, void *);
302 static int pbx_builtin_saynumber(struct ast_channel *, void *);
303 static int pbx_builtin_saydigits(struct ast_channel *, void *);
304 static int pbx_builtin_saycharacters(struct ast_channel *, void *);
305 static int pbx_builtin_sayphonetic(struct ast_channel *, void *);
306 static int matchcid(const char *cidpattern, const char *callerid);
307 int pbx_builtin_setvar(struct ast_channel *, void *);
308 void log_match_char_tree(struct match_char *node, char *prefix); /* for use anywhere */
309 int pbx_builtin_setvar_multiple(struct ast_channel *, void *);
310 static int pbx_builtin_importvar(struct ast_channel *, void *);
311 static void set_ext_pri(struct ast_channel *c, const char *exten, int pri); 
312 static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *callerid, const char *label, enum ext_match_t action);
313 static struct match_char *already_in_tree(struct match_char *current, char *pat);
314 static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly);
315 static struct match_char *add_pattern_node(struct ast_context *con, struct match_char *current, char *pattern, int is_pattern, int already, int specificity, struct match_char **parent);
316 static void create_match_char_tree(struct ast_context *con);
317 static struct ast_exten *get_canmatch_exten(struct match_char *node);
318 static void destroy_pattern_tree(struct match_char *pattern_tree);
319 int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b);
320 static int hashtab_compare_extens(const void *ha_a, const void *ah_b);
321 static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b);
322 static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b);
323 unsigned int ast_hashtab_hash_contexts(const void *obj);
324 static unsigned int hashtab_hash_extens(const void *obj);
325 static unsigned int hashtab_hash_priority(const void *obj);
326 static unsigned int hashtab_hash_labels(const void *obj);
327 static void __ast_internal_context_destroy( struct ast_context *con);
328
329 /* a func for qsort to use to sort a char array */
330 static int compare_char(const void *a, const void *b)
331 {
332         const char *ac = a;
333         const char *bc = b;
334         if ((*ac) < (*bc))
335                 return -1;
336         else if ((*ac) == (*bc))
337                 return 0;
338         else
339                 return 1;
340 }
341
342 /* labels, contexts are case sensitive  priority numbers are ints */
343 int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b)
344 {
345         const struct ast_context *ac = ah_a;
346         const struct ast_context *bc = ah_b;
347         /* assume context names are registered in a string table! */
348         return strcmp(ac->name, bc->name);
349 }
350
351 static int hashtab_compare_extens(const void *ah_a, const void *ah_b)
352 {
353         const struct ast_exten *ac = ah_a;
354         const struct ast_exten *bc = ah_b;
355         int x = strcmp(ac->exten, bc->exten);
356         if (x) /* if exten names are diff, then return */
357                 return x;
358         /* but if they are the same, do the cidmatch values match? */
359         if (ac->matchcid && bc->matchcid) {
360                 return strcmp(ac->cidmatch,bc->cidmatch);
361         } else if (!ac->matchcid && !bc->matchcid) {
362                 return 0; /* if there's no matchcid on either side, then this is a match */
363         } else {
364                 return 1; /* if there's matchcid on one but not the other, they are different */
365         }
366 }
367
368 static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b)
369 {
370         const struct ast_exten *ac = ah_a;
371         const struct ast_exten *bc = ah_b;
372         return ac->priority != bc->priority;
373 }
374
375 static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b)
376 {
377         const struct ast_exten *ac = ah_a;
378         const struct ast_exten *bc = ah_b;
379         return strcmp(ac->label, bc->label);
380 }
381
382 unsigned int ast_hashtab_hash_contexts(const void *obj)
383 {
384         const struct ast_context *ac = obj;
385         return ast_hashtab_hash_string(ac->name);
386 }
387
388 static unsigned int hashtab_hash_extens(const void *obj)
389 {
390         const struct ast_exten *ac = obj;
391         unsigned int x = ast_hashtab_hash_string(ac->exten);
392         unsigned int y = 0;
393         if (ac->matchcid)
394                 y = ast_hashtab_hash_string(ac->cidmatch);
395         return x+y;
396 }
397
398 static unsigned int hashtab_hash_priority(const void *obj)
399 {
400         const struct ast_exten *ac = obj;
401         return ast_hashtab_hash_int(ac->priority);
402 }
403
404 static unsigned int hashtab_hash_labels(const void *obj)
405 {
406         const struct ast_exten *ac = obj;
407         return ast_hashtab_hash_string(ac->label);
408 }
409
410
411 AST_RWLOCK_DEFINE_STATIC(globalslock);
412 static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
413
414 static int autofallthrough = 1;
415 static int extenpatternmatchnew = 0;
416 static char *overrideswitch = NULL;
417
418 /*! \brief Subscription for device state change events */
419 static struct ast_event_sub *device_state_sub;
420
421 AST_MUTEX_DEFINE_STATIC(maxcalllock);
422 static int countcalls;
423 static int totalcalls;
424
425 static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
426
427 /*! \brief Declaration of builtin applications */
428 static struct pbx_builtin {
429         char name[AST_MAX_APP];
430         int (*execute)(struct ast_channel *chan, void *data);
431         char *synopsis;
432         char *description;
433 } builtins[] =
434 {
435         /* These applications are built into the PBX core and do not
436            need separate modules */
437
438         { "Answer", pbx_builtin_answer,
439         "Answer a channel if ringing",
440         "  Answer([delay]): If the call has not been answered, this application will\n"
441         "answer it. Otherwise, it has no effect on the call. If a delay is specified,\n"
442         "Asterisk will wait this number of milliseconds before returning to\n"
443         "the dialplan after answering the call.\n"
444         },
445
446         { "BackGround", pbx_builtin_background,
447         "Play an audio file while waiting for digits of an extension to go to.",
448         "  Background(filename1[&filename2...][,options[,langoverride][,context]]):\n"
449         "This application will play the given list of files (do not put extension)\n"
450         "while waiting for an extension to be dialed by the calling channel. To\n"
451         "continue waiting for digits after this application has finished playing\n"
452         "files, the WaitExten application should be used. The 'langoverride' option\n"
453         "explicitly specifies which language to attempt to use for the requested sound\n"
454         "files. If a 'context' is specified, this is the dialplan context that this\n"
455         "application will use when exiting to a dialed extension."
456         "  If one of the requested sound files does not exist, call processing will be\n"
457         "terminated.\n"
458         "  Options:\n"
459         "    s - Causes the playback of the message to be skipped\n"
460         "          if the channel is not in the 'up' state (i.e. it\n"
461         "          hasn't been answered yet). If this happens, the\n"
462         "          application will return immediately.\n"
463         "    n - Don't answer the channel before playing the files.\n"
464         "    m - Only break if a digit hit matches a one digit\n"
465         "          extension in the destination context.\n"
466         "This application sets the following channel variable upon completion:\n"
467         " BACKGROUNDSTATUS    The status of the background attempt as a text string, one of\n"
468         "               SUCCESS | FAILED\n"
469         "See Also: Playback (application) -- Play sound file(s) to the channel,\n"
470         "                                    that cannot be interrupted\n"
471         },
472
473         { "Busy", pbx_builtin_busy,
474         "Indicate the Busy condition",
475         "  Busy([timeout]): This application will indicate the busy condition to\n"
476         "the calling channel. If the optional timeout is specified, the calling channel\n"
477         "will be hung up after the specified number of seconds. Otherwise, this\n"
478         "application will wait until the calling channel hangs up.\n"
479         },
480
481         { "Congestion", pbx_builtin_congestion,
482         "Indicate the Congestion condition",
483         "  Congestion([timeout]): This application will indicate the congestion\n"
484         "condition to the calling channel. If the optional timeout is specified, the\n"
485         "calling channel will be hung up after the specified number of seconds.\n"
486         "Otherwise, this application will wait until the calling channel hangs up.\n"
487         },
488
489         { "ExecIfTime", pbx_builtin_execiftime,
490         "Conditional application execution based on the current time",
491         "  ExecIfTime(<times>,<weekdays>,<mdays>,<months>?appname[(appargs)]):\n"
492         "This application will execute the specified dialplan application, with optional\n"
493         "arguments, if the current time matches the given time specification.\n"
494         },
495
496         { "Goto", pbx_builtin_goto,
497         "Jump to a particular priority, extension, or context",
498         "  Goto([[context,]extension,]priority): This application will set the current\n"
499         "context, extension, and priority in the channel structure. After it completes, the\n"
500         "pbx engine will continue dialplan execution at the specified location.\n"
501         "If no specific extension, or extension and context, are specified, then this\n"
502         "application will just set the specified priority of the current extension.\n"
503         "  At least a priority is required as an argument, or the goto will return a -1,\n"
504         "and the channel and call will be terminated.\n"
505         "  If the location that is put into the channel information is bogus, and asterisk cannot\n"
506         "find that location in the dialplan,\n"
507         "then the execution engine will try to find and execute the code in the 'i' (invalid)\n"
508         "extension in the current context. If that does not exist, it will try to execute the\n"
509         "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
510         "channel is hung up, and the execution of instructions on the channel is terminated.\n"
511         "What this means is that, for example, you specify a context that does not exist, then\n"
512         "it will not be possible to find the 'h' or 'i' extensions, and the call will terminate!\n"
513         },
514
515         { "GotoIf", pbx_builtin_gotoif,
516         "Conditional goto",
517         "  GotoIf(condition?[labeliftrue]:[labeliffalse]): This application will set the current\n"
518         "context, extension, and priority in the channel structure based on the evaluation of\n"
519         "the given condition. After this application completes, the\n"
520         "pbx engine will continue dialplan execution at the specified location in the dialplan.\n"
521         "The channel will continue at\n"
522         "'labeliftrue' if the condition is true, or 'labeliffalse' if the condition is\n"
523         "false. The labels are specified with the same syntax as used within the Goto\n"
524         "application.  If the label chosen by the condition is omitted, no jump is\n"
525         "performed, and the execution passes to the next instruction.\n"
526         "If the target location is bogus, and does not exist, the execution engine will try \n"
527         "to find and execute the code in the 'i' (invalid)\n"
528         "extension in the current context. If that does not exist, it will try to execute the\n"
529         "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
530         "channel is hung up, and the execution of instructions on the channel is terminated.\n"
531         "Remember that this command can set the current context, and if the context specified\n"
532         "does not exist, then it will not be able to find any 'h' or 'i' extensions there, and\n"
533         "the channel and call will both be terminated!\n"
534         },
535
536         { "GotoIfTime", pbx_builtin_gotoiftime,
537         "Conditional Goto based on the current time",
538         "  GotoIfTime(<times>,<weekdays>,<mdays>,<months>?[labeliftrue]:[labeliffalse]):\n"
539         "This application will set the context, extension, and priority in the channel structure\n"
540         "based on the evaluation of the given time specification. After this application completes,\n"
541         "the pbx engine will continue dialplan execution at the specified location in the dialplan.\n"
542         "If the current time is within the given time specification, the channel will continue at\n"
543         "'labeliftrue'. Otherwise the channel will continue at 'labeliffalse'. If the label chosen\n"
544         "by the condition is omitted, no jump is performed, and execution passes to the next\n"
545         "instruction. If the target jump location is bogus, the same actions would be taken as for\n"
546         "Goto.\n"
547         "Further information on the time specification can be found in examples\n"
548         "illustrating how to do time-based context includes in the dialplan.\n"
549         },
550
551         { "ImportVar", pbx_builtin_importvar,
552         "Import a variable from a channel into a new variable",
553         "  ImportVar(newvar=channelname,variable): This application imports a variable\n"
554         "from the specified channel (as opposed to the current one) and stores it as\n"
555         "a variable in the current channel (the channel that is calling this\n"
556         "application). Variables created by this application have the same inheritance\n"
557         "properties as those created with the Set application. See the documentation for\n"
558         "Set for more information.\n"
559         },
560
561         { "Hangup", pbx_builtin_hangup,
562         "Hang up the calling channel",
563         "  Hangup([causecode]): This application will hang up the calling channel.\n"
564         "If a causecode is given the channel's hangup cause will be set to the given\n"
565         "value.\n"
566         },
567
568         { "Incomplete", pbx_builtin_incomplete,
569         "returns AST_PBX_INCOMPLETE value",
570         "  Incomplete([n]): Signals the PBX routines that the previous matched extension\n"
571         "is incomplete and that further input should be allowed before matching can\n"
572         "be considered to be complete.  Can be used within a pattern match when\n"
573         "certain criteria warrants a longer match.\n"
574         "  If the 'n' option is specified, then Incomplete will not attempt to answer\n"
575         "the channel first.  Note that most channel types need to be in Answer state\n"
576         "in order to receive DTMF.\n"
577         },
578
579         { "KeepAlive", pbx_builtin_keepalive,
580         "returns AST_PBX_KEEPALIVE value",
581         "  KeepAlive(): This application is chiefly meant for internal use with Gosubs.\n"
582         "Please do not run it alone from the dialplan!\n"
583         },
584
585         { "NoOp", pbx_builtin_noop,
586         "Do Nothing (No Operation)",
587         "  NoOp(): This application does nothing. However, it is useful for debugging\n"
588         "purposes. Any text that is provided as arguments to this application can be\n"
589         "viewed at the Asterisk CLI. This method can be used to see the evaluations of\n"
590         "variables or functions without having any effect. Alternatively, see the\n"
591   "Verbose() application for finer grain control of output at custom verbose levels.\n"
592         },
593
594         { "Progress", pbx_builtin_progress,
595         "Indicate progress",
596         "  Progress(): This application will request that in-band progress information\n"
597         "be provided to the calling channel.\n"
598         },
599
600         { "RaiseException", pbx_builtin_raise_exception,
601         "Handle an exceptional condition",
602         "  RaiseException(<reason>): This application will jump to the \"e\" extension\n"
603         "in the current context, setting the dialplan function EXCEPTION(). If the \"e\"\n"
604         "extension does not exist, the call will hangup.\n"
605         },
606
607         { "ResetCDR", pbx_builtin_resetcdr,
608         "Resets the Call Data Record",
609         "  ResetCDR([options]):  This application causes the Call Data Record to be\n"
610         "reset.\n"
611         "  Options:\n"
612         "    w -- Store the current CDR record before resetting it.\n"
613         "    a -- Store any stacked records.\n"
614         "    v -- Save CDR variables.\n"
615         "    e -- Enable CDR only (negate effects of NoCDR).\n"
616         },
617
618         { "Ringing", pbx_builtin_ringing,
619         "Indicate ringing tone",
620         "  Ringing(): This application will request that the channel indicate a ringing\n"
621         "tone to the user.\n"
622         },
623
624         { "SayAlpha", pbx_builtin_saycharacters,
625         "Say Alpha",
626         "  SayAlpha(string): This application will play the sounds that correspond to\n"
627         "the letters of the given string.\n"
628         },
629
630         { "SayDigits", pbx_builtin_saydigits,
631         "Say Digits",
632         "  SayDigits(digits): This application will play the sounds that correspond\n"
633         "to the digits of the given number. This will use the language that is currently\n"
634         "set for the channel. See the LANGUAGE function for more information on setting\n"
635         "the language for the channel.\n"
636         },
637
638         { "SayNumber", pbx_builtin_saynumber,
639         "Say Number",
640         "  SayNumber(digits[,gender]): This application will play the sounds that\n"
641         "correspond to the given number. Optionally, a gender may be specified.\n"
642         "This will use the language that is currently set for the channel. See the\n"
643         "LANGUAGE function for more information on setting the language for the channel.\n"
644         },
645
646         { "SayPhonetic", pbx_builtin_sayphonetic,
647         "Say Phonetic",
648         "  SayPhonetic(string): This application will play the sounds from the phonetic\n"
649         "alphabet that correspond to the letters in the given string.\n"
650         },
651
652         { "Set", pbx_builtin_setvar,
653         "Set channel variable or function value",
654         "  Set(name=value)\n"
655         "This function can be used to set the value of channel variables or dialplan\n"
656         "functions. When setting variables, if the variable name is prefixed with _,\n"
657         "the variable will be inherited into channels created from the current\n"
658         "channel. If the variable name is prefixed with __, the variable will be\n"
659         "inherited into channels created from the current channel and all children\n"
660         "channels.\n"
661         },
662
663         { "MSet", pbx_builtin_setvar_multiple,
664         "Set channel variable(s) or function value(s)",
665         "  MSet(name1=value1,name2=value2,...)\n"
666         "This function can be used to set the value of channel variables or dialplan\n"
667         "functions. When setting variables, if the variable name is prefixed with _,\n"
668         "the variable will be inherited into channels created from the current\n"
669         "channel. If the variable name is prefixed with __, the variable will be\n"
670         "inherited into channels created from the current channel and all children\n"
671         "channels.\n\n"
672         "MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus\n"
673         "prone to doing things that you may not expect.  Avoid its use if possible.\n"
674         },
675
676         { "SetAMAFlags", pbx_builtin_setamaflags,
677         "Set the AMA Flags",
678         "  SetAMAFlags([flag]): This application will set the channel's AMA Flags for\n"
679         "  billing purposes.\n"
680         },
681
682         { "Wait", pbx_builtin_wait,
683         "Waits for some time",
684         "  Wait(seconds): This application waits for a specified number of seconds.\n"
685         "Then, dialplan execution will continue at the next priority.\n"
686         "  Note that the seconds can be passed with fractions of a second. For example,\n"
687         "'1.5' will ask the application to wait for 1.5 seconds.\n"
688         },
689
690         { "WaitExten", pbx_builtin_waitexten,
691         "Waits for an extension to be entered",
692         "  WaitExten([seconds][,options]): This application waits for the user to enter\n"
693         "a new extension for a specified number of seconds.\n"
694         "  Note that the seconds can be passed with fractions of a second. For example,\n"
695         "'1.5' will ask the application to wait for 1.5 seconds.\n"
696         "  Options:\n"
697         "    m[(x)] - Provide music on hold to the caller while waiting for an extension.\n"
698         "               Optionally, specify the class for music on hold within parenthesis.\n"
699         "See Also: Playback(application), Background(application).\n"
700         },
701
702 };
703
704 static struct ast_context *contexts;
705 static struct ast_hashtab *contexts_table = NULL;
706
707 AST_RWLOCK_DEFINE_STATIC(conlock);              /*!< Lock for the ast_context list */
708
709 static AST_RWLIST_HEAD_STATIC(apps, ast_app);
710
711 static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
712
713 static int stateid = 1;
714 /* WARNING:
715    When holding this list's lock, do _not_ do anything that will cause conlock
716    to be taken, unless you _already_ hold it. The ast_merge_contexts_and_delete
717    function will take the locks in conlock/hints order, so any other
718    paths that require both locks must also take them in that order.
719 */
720 static AST_RWLIST_HEAD_STATIC(hints, ast_hint);
721
722 static AST_LIST_HEAD_NOLOCK_STATIC(statecbs, ast_state_cb);
723
724 /*
725    \note This function is special. It saves the stack so that no matter
726    how many times it is called, it returns to the same place */
727 int pbx_exec(struct ast_channel *c,             /*!< Channel */
728              struct ast_app *app,               /*!< Application */
729              void *data)                        /*!< Data for execution */
730 {
731         int res;
732         struct ast_module_user *u = NULL;
733         const char *saved_c_appl;
734         const char *saved_c_data;
735
736         if (c->cdr && !ast_check_hangup(c))
737                 ast_cdr_setapp(c->cdr, app->name, data);
738
739         /* save channel values */
740         saved_c_appl= c->appl;
741         saved_c_data= c->data;
742
743         c->appl = app->name;
744         c->data = data;
745         if (app->module)
746                 u = __ast_module_user_add(app->module, c);
747         res = app->execute(c, S_OR(data, ""));
748         if (app->module && u)
749                 __ast_module_user_remove(app->module, u);
750         /* restore channel values */
751         c->appl = saved_c_appl;
752         c->data = saved_c_data;
753         return res;
754 }
755
756
757 /*! Go no deeper than this through includes (not counting loops) */
758 #define AST_PBX_MAX_STACK       128
759
760 /*! \brief Find application handle in linked list
761  */
762 struct ast_app *pbx_findapp(const char *app)
763 {
764         struct ast_app *tmp;
765
766         AST_RWLIST_RDLOCK(&apps);
767         AST_RWLIST_TRAVERSE(&apps, tmp, list) {
768                 if (!strcasecmp(tmp->name, app))
769                         break;
770         }
771         AST_RWLIST_UNLOCK(&apps);
772
773         return tmp;
774 }
775
776 static struct ast_switch *pbx_findswitch(const char *sw)
777 {
778         struct ast_switch *asw;
779
780         AST_RWLIST_RDLOCK(&switches);
781         AST_RWLIST_TRAVERSE(&switches, asw, list) {
782                 if (!strcasecmp(asw->name, sw))
783                         break;
784         }
785         AST_RWLIST_UNLOCK(&switches);
786
787         return asw;
788 }
789
790 static inline int include_valid(struct ast_include *i)
791 {
792         if (!i->hastime)
793                 return 1;
794
795         return ast_check_timing(&(i->timing));
796 }
797
798 static void pbx_destroy(struct ast_pbx *p)
799 {
800         ast_free(p);
801 }
802
803 /* form a tree that fully describes all the patterns in a context's extensions 
804  * in this tree, a "node" represents an individual character or character set
805  * meant to match the corresponding character in a dial string. The tree 
806  * consists of a series of match_char structs linked in a chain
807  * via the alt_char pointers. More than one pattern can share the same parts of the 
808  * tree as other extensions with the same pattern to that point. 
809  * My first attempt to duplicate the finding of the 'best' pattern was flawed in that
810  * I misunderstood the general algorithm. I thought that the 'best' pattern
811  * was the one with lowest total score. This was not true. Thus, if you have
812  * patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is
813  * the "best" match because it has fewer X's, and is therefore more specific, 
814  * but this is not how the old algorithm works. It sorts matching patterns
815  * in a similar collating sequence as sorting alphabetic strings, from left to 
816  * right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match,
817  * because "1" is more specific than "X".
818  * So, to accomodate this philosophy, I sort the tree branches along the alt_char
819  * line so they are lowest to highest in specificity numbers. This way, as soon
820  * as we encounter our first complete match, we automatically have the "best" 
821  * match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE.
822  * If anyone would like to resurrect the "wrong" pattern trie searching algorithm,
823  * they are welcome to revert pbx to before 1 Apr 2008.
824  * As an example, consider these 4 extensions:
825  * (a) NXXNXXXXXX
826  * (b) 307754XXXX 
827  * (c) fax
828  * (d) NXXXXXXXXX
829  *
830  * In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over
831  * most numbers. For all numbers beginning with 307754, (b) should always win.
832  *
833  * These pattern should form a (sorted) tree that looks like this:
834  *   { "3" }  --next-->  { "0" }  --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) }
835  *      |
836  *      |alt
837  *      |
838  *   { "f" }  --next-->  { "a" }  --next--> { "x"  exten_match: (c) }
839  *   { "N" }  --next-->  { "X" }  --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
840  *      |                                                        |
841  *      |                                                        |alt
842  *      |alt                                                     |
843  *      |                                                     { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
844  *      |
845  *     NULL
846  *
847  *   In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take
848  *   fewer CPU cycles than a call to index("23456789",*z), where *z is the char to match...
849  *
850  *   traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern,  it calls itself
851  *   on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length.
852  *   We pass a pointer to a scoreboard down through, also.
853  *   The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension.
854  *   The first complete match ends the traversal, which should make this version of the pattern matcher faster
855  *   the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both
856  *   these cases, the reason we can stop immediately, is because the first pattern match found will be the "best"
857  *   according to the sort criteria.
858  *   Hope the limit on stack depth won't be a problem... this routine should 
859  *   be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch.
860  *
861  *   In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d.  All are
862  *   of length 10; they have total specificities of  24580, 10246, and 25090, respectively, not that this matters
863  *   at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have
864  *   left the specificity totals in the code as an artifact; at some point, I will strip it out.
865  *
866  *   Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown,
867  *   because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup
868  *   can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or
869  *   more times faster in extreme cases.
870  *
871  *   MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you
872  *   can have patterns in your CID field as well.
873  *
874  * */
875
876
877 static void update_scoreboard(struct scoreboard *board, int length, int spec, struct ast_exten *exten, char last, const char *callerid, int deleted, struct match_char *node)
878 {
879         /* if this extension is marked as deleted, then skip this -- if it never shows
880            on the scoreboard, it will never be found, nor will halt the traversal. */
881         if (deleted)
882                 return;
883         board->total_specificity = spec;
884         board->total_length = length;
885         board->exten = exten;
886         board->last_char = last;
887         board->node = node;
888 #ifdef NEED_DEBUG_HERE
889         ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec);
890 #endif
891 }
892
893 void log_match_char_tree(struct match_char *node, char *prefix)
894 {
895         char extenstr[40];
896         struct ast_str *my_prefix = ast_str_alloca(1024); 
897
898         extenstr[0] = '\0';
899
900         if (node && node->exten && node->exten)
901                 snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
902         
903         if (strlen(node->x) > 1) {
904                 ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N', 
905                         node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"", 
906                         node->exten ? node->exten->exten : "", extenstr);
907         } else {
908                 ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N', 
909                         node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"", 
910                         node->exten ? node->exten->exten : "", extenstr);
911         }
912
913         ast_str_set(&my_prefix, 0, "%s+       ", prefix);
914
915         if (node->next_char)
916                 log_match_char_tree(node->next_char, my_prefix->str);
917
918         if (node->alt_char)
919                 log_match_char_tree(node->alt_char, prefix);
920 }
921
922 static void cli_match_char_tree(struct match_char *node, char *prefix, int fd)
923 {
924         char extenstr[40];
925         struct ast_str *my_prefix = ast_str_alloca(1024);
926         
927         extenstr[0] = '\0';
928
929         if (node && node->exten && node->exten)
930                 snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
931         
932         if (strlen(node->x) > 1) {
933                 ast_cli(fd, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N', 
934                         node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "", 
935                         node->exten ? node->exten->exten : "", extenstr);
936         } else {
937                 ast_cli(fd, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N', 
938                         node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "", 
939                         node->exten ? node->exten->exten : "", extenstr);
940         }
941
942         ast_str_set(&my_prefix, 0, "%s+       ", prefix);
943
944         if (node->next_char)
945                 cli_match_char_tree(node->next_char, my_prefix->str, fd);
946
947         if (node->alt_char)
948                 cli_match_char_tree(node->alt_char, prefix, fd);
949 }
950
951 static struct ast_exten *get_canmatch_exten(struct match_char *node)
952 {
953         /* find the exten at the end of the rope */
954         struct match_char *node2 = node;
955
956         for (node2 = node; node2; node2 = node2->next_char) {
957                 if (node2->exten) {
958 #ifdef NEED_DEBUG_HERE
959                         ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten);
960 #endif
961                         return node2->exten;
962                 }
963         }
964 #ifdef NEED_DEBUG_HERE
965         ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x);
966 #endif
967         return 0;
968 }
969
970 static struct ast_exten *trie_find_next_match(struct match_char *node)
971 {
972         struct match_char *m3;
973         struct match_char *m4;
974         struct ast_exten *e3;
975         
976         if (node && node->x[0] == '.' && !node->x[1]) /* dot and ! will ALWAYS be next match in a matchmore */
977                 return node->exten;
978         
979         if (node && node->x[0] == '!' && !node->x[1])
980                 return node->exten;
981         
982         if (!node || !node->next_char)
983                 return NULL;
984         
985         m3 = node->next_char;
986
987         if (m3->exten)
988                 return m3->exten;
989         for(m4=m3->alt_char; m4; m4 = m4->alt_char) {
990                 if (m4->exten)
991                         return m4->exten;
992         }
993         for(m4=m3; m4; m4 = m4->alt_char) {
994                 e3 = trie_find_next_match(m3);
995                 if (e3)
996                         return e3;
997         }
998         return NULL;
999 }
1000
1001 #ifdef DEBUG_THIS
1002 static char *action2str(enum ext_match_t action)
1003 {
1004         switch(action)
1005         {
1006         case E_MATCH:
1007                 return "MATCH";
1008         case E_CANMATCH:
1009                 return "CANMATCH";
1010         case E_MATCHMORE:
1011                 return "MATCHMORE";
1012         case E_FINDLABEL:
1013                 return "FINDLABEL";
1014         case E_SPAWN:
1015                 return "SPAWN";
1016         default:
1017                 return "?ACTION?";
1018         }
1019 }
1020
1021 #endif
1022
1023 static void new_find_extension(const char *str, struct scoreboard *score, struct match_char *tree, int length, int spec, const char *label, const char *callerid, enum ext_match_t action)
1024 {
1025         struct match_char *p; /* note minimal stack storage requirements */
1026         struct ast_exten pattern = { .label = label };
1027 #ifdef DEBUG_THIS
1028         if (tree)
1029                 ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree %s action=%s\n", str, tree->x, action2str(action));
1030         else
1031                 ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str, action2str(action));
1032 #endif
1033         for (p=tree; p; p=p->alt_char) {
1034                 if (p->x[0] == 'N') {
1035                         if (p->x[1] == 0 && *str >= '2' && *str <= '9' ) {
1036 #define NEW_MATCHER_CHK_MATCH          \
1037                                 if (p->exten && !(*(str+1))) { /* if a shorter pattern matches along the way, might as well report it */             \
1038                                         if (action == E_MATCH || action == E_SPAWN || action == E_FINDLABEL) { /* if in CANMATCH/MATCHMORE, don't let matches get in the way */   \
1039                                                 update_scoreboard(score, length+1, spec+p->specificity, p->exten,0,callerid, p->deleted, p);                 \
1040                                                 if (!p->deleted) {                                                                                           \
1041                                                         if (action == E_FINDLABEL) {                                                                             \
1042                                                                 if (ast_hashtab_lookup(score->exten->peer_label_table, &pattern)) {                                  \
1043                                                                         ast_debug(4, "Found label in preferred extension\n");                                            \
1044                                                                         return;                                                                                          \
1045                                                                 }                                                                                                    \
1046                                                         } else {                                                                                                 \
1047                                                                 ast_debug(4,"returning an exact match-- first found-- %s\n", p->exten->exten);                       \
1048                                                                 return; /* the first match, by definition, will be the best, because of the sorted tree */           \
1049                                                         }                                                                                                        \
1050                                                 }                                                                                                            \
1051                                         }                                                                                                                \
1052                                 }
1053                                 
1054 #define NEW_MATCHER_RECURSE                \
1055                                 if (p->next_char && ( *(str+1) || (p->next_char->x[0] == '/' && p->next_char->x[1] == 0)                 \
1056                                                || p->next_char->x[0] == '!')) {                                          \
1057                                         if (*(str+1) || p->next_char->x[0] == '!') {                                                         \
1058                                                 new_find_extension(str+1, score, p->next_char, length+1, spec+p->specificity, callerid, label, action); \
1059                                                 if (score->exten)  {                                                                             \
1060                                                 ast_debug(4,"returning an exact match-- %s\n", score->exten->exten);                         \
1061                                                         return; /* the first match is all we need */                                                 \
1062                                                 }                                                                                                                                                \
1063                                         } else {                                                                                             \
1064                                                 new_find_extension("/", score, p->next_char, length+1, spec+p->specificity, callerid, label, action);    \
1065                                                 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {      \
1066                                                 ast_debug(4,"returning a (can/more) match--- %s\n", score->exten ? score->exten->exten :     \
1067                                        "NULL");                                                                        \
1068                                                         return; /* the first match is all we need */                                                 \
1069                                                 }                                                                                                                                                \
1070                                         }                                                                                                    \
1071                                 } else if (p->next_char && !*(str+1)) {                                                                  \
1072                                         score->canmatch = 1;                                                                                 \
1073                                         score->canmatch_exten = get_canmatch_exten(p);                                                       \
1074                                         if (action == E_CANMATCH || action == E_MATCHMORE) {                                                 \
1075                                         ast_debug(4,"returning a canmatch/matchmore--- str=%s\n", str);                                  \
1076                                                 return;                                                                                          \
1077                                         }                                                                                                                                                    \
1078                                 }
1079                                 
1080                                 NEW_MATCHER_CHK_MATCH;
1081                                 NEW_MATCHER_RECURSE;
1082                         }
1083                 } else if (p->x[0] == 'Z') {
1084                         if (p->x[1] == 0 && *str >= '1' && *str <= '9' ) {
1085                                 NEW_MATCHER_CHK_MATCH;
1086                                 NEW_MATCHER_RECURSE;
1087                         }
1088                 } else if (p->x[0] == 'X') { 
1089                         if (p->x[1] == 0 && *str >= '0' && *str <= '9' ) {
1090                                 NEW_MATCHER_CHK_MATCH;
1091                                 NEW_MATCHER_RECURSE;
1092                         }
1093                 } else if (p->x[0] == '.' && p->x[1] == 0) {
1094                         /* how many chars will the . match against? */
1095                         int i = 0;
1096                         const char *str2 = str;
1097                         while (*str2 && *str2 != '/') {
1098                                 str2++;
1099                                 i++;
1100                         }
1101                         if (p->exten && *str2 != '/') {
1102                                 update_scoreboard(score, length+i, spec+(i*p->specificity), p->exten, '.', callerid, p->deleted, p);
1103                                 if (score->exten) {
1104                                         ast_debug(4,"return because scoreboard has a match with '/'--- %s\n", score->exten->exten);
1105                                         return; /* the first match is all we need */
1106                                 }
1107                         }
1108                         if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
1109                                 new_find_extension("/", score, p->next_char, length+i, spec+(p->specificity*i), callerid, label, action);
1110                                 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
1111                                         ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set--- %s\n", score->exten ? score->exten->exten : "NULL");
1112                                         return; /* the first match is all we need */
1113                                 }
1114                         }
1115                 } else if (p->x[0] == '!' && p->x[1] == 0) {
1116                         /* how many chars will the . match against? */
1117                         int i = 1;
1118                         const char *str2 = str;
1119                         while (*str2 && *str2 != '/') {
1120                                 str2++;
1121                                 i++;
1122                         }
1123                         if (p->exten && *str2 != '/') {
1124                                 update_scoreboard(score, length+1, spec+(p->specificity*i), p->exten, '!', callerid, p->deleted, p);
1125                                 if (score->exten) {
1126                                         ast_debug(4,"return because scoreboard has a '!' match--- %s\n", score->exten->exten);
1127                                         return; /* the first match is all we need */
1128                                 }
1129                         }
1130                         if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
1131                                 new_find_extension("/", score, p->next_char, length+i, spec+(p->specificity*i), callerid, label, action);
1132                                 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
1133                                         ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/' and '!'--- %s\n", score->exten ? score->exten->exten : "NULL");
1134                                         return; /* the first match is all we need */
1135                                 }
1136                         }
1137                 } else if (p->x[0] == '/' && p->x[1] == 0) {
1138                         /* the pattern in the tree includes the cid match! */
1139                         if (p->next_char && callerid && *callerid) {
1140                                 new_find_extension(callerid, score, p->next_char, length+1, spec, callerid, label, action);
1141                                 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
1142                                         ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/'--- %s\n", score->exten ? score->exten->exten : "NULL");
1143                                         return; /* the first match is all we need */
1144                                 }
1145                         }
1146                 } else if (index(p->x, *str)) {
1147                         ast_debug(4, "Nothing strange about this match\n");
1148                         NEW_MATCHER_CHK_MATCH;
1149                         NEW_MATCHER_RECURSE;
1150                 }
1151         }
1152         ast_debug(4,"return at end of func\n");
1153 }
1154
1155 /* the algorithm for forming the extension pattern tree is also a bit simple; you 
1156  * traverse all the extensions in a context, and for each char of the extension,
1157  * you see if it exists in the tree; if it doesn't, you add it at the appropriate
1158  * spot. What more can I say? At the end of each exten, you cap it off by adding the
1159  * address of the extension involved. Duplicate patterns will be complained about.
1160  *
1161  * Ideally, this would be done for each context after it is created and fully 
1162  * filled. It could be done as a finishing step after extensions.conf or .ael is
1163  * loaded, or it could be done when the first search is encountered. It should only
1164  * have to be done once, until the next unload or reload.
1165  *
1166  * I guess forming this pattern tree would be analogous to compiling a regex. Except
1167  * that a regex only handles 1 pattern, really. This trie holds any number
1168  * of patterns. Well, really, it **could** be considered a single pattern,
1169  * where the "|" (or) operator is allowed, I guess, in a way, sort of...
1170  */
1171
1172 static struct match_char *already_in_tree(struct match_char *current, char *pat)
1173 {
1174         struct match_char *t;
1175
1176         if (!current)
1177                 return 0;
1178
1179         for (t = current; t; t = t->alt_char) {
1180                 if (!strcmp(pat, t->x)) /* uh, we may want to sort exploded [] contents to make matching easy */
1181                         return t;
1182         }
1183
1184         return 0;
1185 }
1186
1187 /* The first arg is the location of the tree ptr, or the 
1188    address of the next_char ptr in the node, so we can mess
1189    with it, if we need to insert at the beginning of the list */
1190
1191 static void insert_in_next_chars_alt_char_list(struct match_char **parent_ptr, struct match_char *node)
1192 {
1193         struct match_char *curr, *lcurr;
1194         
1195         /* insert node into the tree at "current", so the alt_char list from current is
1196            sorted in increasing value as you go to the leaves */
1197         if (!(*parent_ptr)) {
1198                 *parent_ptr = node;
1199         } else {
1200                 if ((*parent_ptr)->specificity > node->specificity){
1201                         /* insert at head */
1202                         node->alt_char = (*parent_ptr);
1203                         *parent_ptr = node;
1204                 } else {
1205                         lcurr = *parent_ptr;
1206                         for (curr=(*parent_ptr)->alt_char; curr; curr = curr->alt_char) {
1207                                 if (curr->specificity > node->specificity) {
1208                                         node->alt_char = curr;
1209                                         lcurr->alt_char = node;
1210                                         break;
1211                                 }
1212                                 lcurr = curr;
1213                         }
1214                         if (!curr)
1215                         {
1216                                 lcurr->alt_char = node;
1217                         }
1218                 }
1219         }
1220 }
1221
1222
1223
1224 static struct match_char *add_pattern_node(struct ast_context *con, struct match_char *current, char *pattern, int is_pattern, int already, int specificity, struct match_char **nextcharptr)
1225 {
1226         struct match_char *m;
1227         
1228         if (!(m = ast_calloc(1, sizeof(*m))))
1229                 return NULL;
1230
1231         if (!(m->x = ast_strdup(pattern))) {
1232                 ast_free(m);
1233                 return NULL;
1234         }
1235
1236         /* the specificity scores are the same as used in the old
1237            pattern matcher. */
1238         m->is_pattern = is_pattern;
1239         if (specificity == 1 && is_pattern && pattern[0] == 'N')
1240                 m->specificity = 0x0802;
1241         else if (specificity == 1 && is_pattern && pattern[0] == 'Z')
1242                 m->specificity = 0x0901;
1243         else if (specificity == 1 && is_pattern && pattern[0] == 'X')
1244                 m->specificity = 0x0a00;
1245         else if (specificity == 1 && is_pattern && pattern[0] == '.')
1246                 m->specificity = 0x10000;
1247         else if (specificity == 1 && is_pattern && pattern[0] == '!')
1248                 m->specificity = 0x20000;
1249         else
1250                 m->specificity = specificity;
1251         
1252         if (!con->pattern_tree) {
1253                 insert_in_next_chars_alt_char_list(&con->pattern_tree, m);
1254         } else {
1255                 if (already) { /* switch to the new regime (traversing vs appending)*/
1256                         insert_in_next_chars_alt_char_list(nextcharptr, m);
1257                 } else {
1258                         insert_in_next_chars_alt_char_list(&current->next_char, m);
1259                 }
1260         }
1261
1262         return m;
1263 }
1264
1265 static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly)
1266 {
1267         struct match_char *m1 = NULL, *m2 = NULL, **m0;
1268         int specif;
1269         int already;
1270         int pattern = 0;
1271         char buf[256];
1272         char extenbuf[512];
1273         char *s1 = extenbuf;
1274         int l1 = strlen(e1->exten) + strlen(e1->cidmatch) + 2;
1275         
1276
1277         strncpy(extenbuf,e1->exten,sizeof(extenbuf));
1278         if (e1->matchcid &&  l1 <= sizeof(extenbuf)) {
1279                 strcat(extenbuf,"/");
1280                 strcat(extenbuf,e1->cidmatch);
1281         } else if (l1 > sizeof(extenbuf)) {
1282                 ast_log(LOG_ERROR,"The pattern %s/%s is too big to deal with: it will be ignored! Disaster!\n", e1->exten, e1->cidmatch);
1283                 return 0;
1284         }
1285 #ifdef NEED_DEBUG
1286         ast_log(LOG_DEBUG,"Adding exten %s%c%s to tree\n", s1, e1->matchcid? '/':' ', e1->matchcid? e1->cidmatch : "");
1287 #endif
1288         m1 = con->pattern_tree; /* each pattern starts over at the root of the pattern tree */
1289         m0 = &con->pattern_tree;
1290         already = 1;
1291
1292         if ( *s1 == '_') {
1293                 pattern = 1;
1294                 s1++;
1295         }
1296         while( *s1 ) {
1297                 if (pattern && *s1 == '[' && *(s1-1) != '\\') {
1298                         char *s2 = buf;
1299                         buf[0] = 0;
1300                         s1++; /* get past the '[' */
1301                         while (*s1 != ']' && *(s1-1) != '\\' ) {
1302                                 if (*s1 == '\\') {
1303                                         if (*(s1+1) == ']') {
1304                                                 *s2++ = ']';
1305                                                 s1++;s1++;
1306                                         } else if (*(s1+1) == '\\') {
1307                                                 *s2++ = '\\';
1308                                                 s1++;s1++;
1309                                         } else if (*(s1+1) == '-') {
1310                                                 *s2++ = '-';
1311                                                 s1++; s1++;
1312                                         } else if (*(s1+1) == '[') {
1313                                                 *s2++ = '[';
1314                                                 s1++; s1++;
1315                                         }
1316                                 } else if (*s1 == '-') { /* remember to add some error checking to all this! */
1317                                         char s3 = *(s1-1);
1318                                         char s4 = *(s1+1);
1319                                         for (s3++; s3 <= s4; s3++) {
1320                                                 *s2++ = s3;
1321                                         }
1322                                         s1++; s1++;
1323                                 } else {
1324                                         *s2++ = *s1++;
1325                                 }
1326                         }
1327                         *s2 = 0; /* null terminate the exploded range */
1328                         /* sort the characters */
1329
1330                         specif = strlen(buf);
1331                         qsort(buf, specif, 1, compare_char);
1332                         specif <<= 8;
1333                         specif += buf[0];
1334                 } else {
1335                         
1336                         if (*s1 == '\\') {
1337                                 s1++;
1338                                 buf[0] = *s1;
1339                         } else {
1340                                 if (pattern) {
1341                                         if (*s1 == 'n') /* make sure n,x,z patterns are canonicalized to N,X,Z */
1342                                                 *s1 = 'N';
1343                                         else if (*s1 == 'x')
1344                                                 *s1 = 'X';
1345                                         else if (*s1 == 'z')
1346                                                 *s1 = 'Z';
1347                                 }
1348                                 buf[0] = *s1;
1349                         }
1350                         buf[1] = 0;
1351                         specif = 1;
1352                 }
1353                 m2 = 0;
1354                 if (already && (m2=already_in_tree(m1,buf)) && m2->next_char) {
1355                         if (!(*(s1+1))) {  /* if this is the end of the pattern, but not the end of the tree, then mark this node with the exten...
1356                                                                 a shorter pattern might win if the longer one doesn't match */
1357                                 m2->exten = e1;
1358                                 m2->deleted = 0;
1359                         }
1360                         m1 = m2->next_char; /* m1 points to the node to compare against */
1361                         m0 = &m2->next_char; /* m0 points to the ptr that points to m1 */
1362                 } else { /* not already OR not m2 OR nor m2->next_char */
1363                         if (m2) {
1364                                 if (findonly)
1365                                         return m2;
1366                                 m1 = m2; /* while m0 stays the same */
1367                         } else {
1368                                 if (findonly)
1369                                         return m1;
1370                                 m1 = add_pattern_node(con, m1, buf, pattern, already,specif, m0); /* m1 is the node just added */
1371                                 m0 = &m1->next_char;
1372                         }
1373                         
1374                         if (!(*(s1+1))) {
1375                                 m1->deleted = 0;
1376                                 m1->exten = e1;
1377                         }
1378                         
1379                         already = 0;
1380                 }
1381                 s1++; /* advance to next char */
1382         }
1383         return m1;
1384 }
1385
1386 static void create_match_char_tree(struct ast_context *con)
1387 {
1388         struct ast_hashtab_iter *t1;
1389         struct ast_exten *e1;
1390 #ifdef NEED_DEBUG
1391         int biggest_bucket, resizes, numobjs, numbucks;
1392         
1393         ast_log(LOG_DEBUG,"Creating Extension Trie for context %s\n", con->name);
1394         ast_hashtab_get_stats(con->root_table, &biggest_bucket, &resizes, &numobjs, &numbucks);
1395         ast_log(LOG_DEBUG,"This tree has %d objects in %d bucket lists, longest list=%d objects, and has resized %d times\n",
1396                         numobjs, numbucks, biggest_bucket, resizes);
1397 #endif
1398         t1 = ast_hashtab_start_traversal(con->root_table);
1399         while( (e1 = ast_hashtab_next(t1)) ) {
1400                 if (e1->exten)
1401                         add_exten_to_pattern_tree(con, e1, 0);
1402                 else
1403                         ast_log(LOG_ERROR,"Attempt to create extension with no extension name.\n");
1404         }
1405         ast_hashtab_end_traversal(t1);
1406 }
1407
1408 static void destroy_pattern_tree(struct match_char *pattern_tree) /* pattern tree is a simple binary tree, sort of, so the proper way to destroy it is... recursively! */
1409 {
1410         /* destroy all the alternates */
1411         if (pattern_tree->alt_char) {
1412                 destroy_pattern_tree(pattern_tree->alt_char);
1413                 pattern_tree->alt_char = 0;
1414         }
1415         /* destroy all the nexts */
1416         if (pattern_tree->next_char) {
1417                 destroy_pattern_tree(pattern_tree->next_char);
1418                 pattern_tree->next_char = 0;
1419         }
1420         pattern_tree->exten = 0; /* never hurts to make sure there's no pointers laying around */
1421         if (pattern_tree->x)
1422                 free(pattern_tree->x);
1423         free(pattern_tree);
1424 }
1425
1426 /*
1427  * Special characters used in patterns:
1428  *      '_'     underscore is the leading character of a pattern.
1429  *              In other position it is treated as a regular char.
1430  *      ' ' '-' space and '-' are separator and ignored.
1431  *      .       one or more of any character. Only allowed at the end of
1432  *              a pattern.
1433  *      !       zero or more of anything. Also impacts the result of CANMATCH
1434  *              and MATCHMORE. Only allowed at the end of a pattern.
1435  *              In the core routine, ! causes a match with a return code of 2.
1436  *              In turn, depending on the search mode: (XXX check if it is implemented)
1437  *              - E_MATCH retuns 1 (does match)
1438  *              - E_MATCHMORE returns 0 (no match)
1439  *              - E_CANMATCH returns 1 (does match)
1440  *
1441  *      /       should not appear as it is considered the separator of the CID info.
1442  *              XXX at the moment we may stop on this char.
1443  *
1444  *      X Z N   match ranges 0-9, 1-9, 2-9 respectively.
1445  *      [       denotes the start of a set of character. Everything inside
1446  *              is considered literally. We can have ranges a-d and individual
1447  *              characters. A '[' and '-' can be considered literally if they
1448  *              are just before ']'.
1449  *              XXX currently there is no way to specify ']' in a range, nor \ is
1450  *              considered specially.
1451  *
1452  * When we compare a pattern with a specific extension, all characters in the extension
1453  * itself are considered literally with the only exception of '-' which is considered
1454  * as a separator and thus ignored.
1455  * XXX do we want to consider space as a separator as well ?
1456  * XXX do we want to consider the separators in non-patterns as well ?
1457  */
1458
1459 /*!
1460  * \brief helper functions to sort extensions and patterns in the desired way,
1461  * so that more specific patterns appear first.
1462  *
1463  * ext_cmp1 compares individual characters (or sets of), returning
1464  * an int where bits 0-7 are the ASCII code of the first char in the set,
1465  * while bit 8-15 are the cardinality of the set minus 1.
1466  * This way more specific patterns (smaller cardinality) appear first.
1467  * Wildcards have a special value, so that we can directly compare them to
1468  * sets by subtracting the two values. In particular:
1469  *      0x000xx         one character, xx
1470  *      0x0yyxx         yy character set starting with xx
1471  *      0x10000         '.' (one or more of anything)
1472  *      0x20000         '!' (zero or more of anything)
1473  *      0x30000         NUL (end of string)
1474  *      0x40000         error in set.
1475  * The pointer to the string is advanced according to needs.
1476  * NOTES:
1477  *      1. the empty set is equivalent to NUL.
1478  *      2. given that a full set has always 0 as the first element,
1479  *         we could encode the special cases as 0xffXX where XX
1480  *         is 1, 2, 3, 4 as used above.
1481  */
1482 static int ext_cmp1(const char **p)
1483 {
1484         uint32_t chars[8];
1485         int c, cmin = 0xff, count = 0;
1486         const char *end;
1487
1488         /* load, sign extend and advance pointer until we find
1489          * a valid character.
1490          */
1491         while ( (c = *(*p)++) && (c == ' ' || c == '-') )
1492                 ;       /* ignore some characters */
1493
1494         /* always return unless we have a set of chars */
1495         switch (toupper(c)) {
1496         default:        /* ordinary character */
1497                 return 0x0000 | (c & 0xff);
1498
1499         case 'N':       /* 2..9 */
1500                 return 0x0700 | '2' ;
1501
1502         case 'X':       /* 0..9 */
1503                 return 0x0900 | '0';
1504
1505         case 'Z':       /* 1..9 */
1506                 return 0x0800 | '1';
1507
1508         case '.':       /* wildcard */
1509                 return 0x10000;
1510
1511         case '!':       /* earlymatch */
1512                 return 0x20000; /* less specific than NULL */
1513
1514         case '\0':      /* empty string */
1515                 *p = NULL;
1516                 return 0x30000;
1517
1518         case '[':       /* pattern */
1519                 break;
1520         }
1521         /* locate end of set */
1522         end = strchr(*p, ']');  
1523
1524         if (end == NULL) {
1525                 ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
1526                 return 0x40000; /* XXX make this entry go last... */
1527         }
1528
1529         bzero(chars, sizeof(chars));    /* clear all chars in the set */
1530         for (; *p < end  ; (*p)++) {
1531                 unsigned char c1, c2;   /* first-last char in range */
1532                 c1 = (unsigned char)((*p)[0]);
1533                 if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */
1534                         c2 = (unsigned char)((*p)[2]);
1535                         *p += 2;        /* skip a total of 3 chars */
1536                 } else                  /* individual character */
1537                         c2 = c1;
1538                 if (c1 < cmin)
1539                         cmin = c1;
1540                 for (; c1 <= c2; c1++) {
1541                         uint32_t mask = 1 << (c1 % 32);
1542                         if ( (chars[ c1 / 32 ] & mask) == 0)
1543                                 count += 0x100;
1544                         chars[ c1 / 32 ] |= mask;
1545                 }
1546         }
1547         (*p)++;
1548         return count == 0 ? 0x30000 : (count | cmin);
1549 }
1550
1551 /*!
1552  * \brief the full routine to compare extensions in rules.
1553  */
1554 static int ext_cmp(const char *a, const char *b)
1555 {
1556         /* make sure non-patterns come first.
1557          * If a is not a pattern, it either comes first or
1558          * we use strcmp to compare the strings.
1559          */
1560         int ret = 0;
1561
1562         if (a[0] != '_')
1563                 return (b[0] == '_') ? -1 : strcmp(a, b);
1564
1565         /* Now we know a is a pattern; if b is not, a comes first */
1566         if (b[0] != '_')
1567                 return 1;
1568 #if 0   /* old mode for ext matching */
1569         return strcmp(a, b);
1570 #endif
1571         /* ok we need full pattern sorting routine */
1572         while (!ret && a && b)
1573                 ret = ext_cmp1(&a) - ext_cmp1(&b);
1574         if (ret == 0)
1575                 return 0;
1576         else
1577                 return (ret > 0) ? 1 : -1;
1578 }
1579
1580 int ast_extension_cmp(const char *a, const char *b)
1581 {
1582         return ext_cmp(a, b);
1583 }
1584
1585 /*!
1586  * \internal
1587  * \brief used ast_extension_{match|close}
1588  * mode is as follows:
1589  *      E_MATCH         success only on exact match
1590  *      E_MATCHMORE     success only on partial match (i.e. leftover digits in pattern)
1591  *      E_CANMATCH      either of the above.
1592  * \retval 0 on no-match
1593  * \retval 1 on match
1594  * \retval 2 on early match.
1595  */
1596
1597 static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
1598 {
1599         mode &= E_MATCH_MASK;   /* only consider the relevant bits */
1600         
1601 #ifdef NEED_DEBUG_HERE
1602         ast_log(LOG_NOTICE,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern, data, (int)mode);
1603 #endif
1604         
1605         if ( (mode == E_MATCH) && (pattern[0] == '_') && (!strcasecmp(pattern,data)) ) { /* note: if this test is left out, then _x. will not match _x. !!! */
1606 #ifdef NEED_DEBUG_HERE
1607                 ast_log(LOG_NOTICE,"return (1) - pattern matches pattern\n");
1608 #endif
1609                 return 1;
1610         }
1611
1612         if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
1613                 int ld = strlen(data), lp = strlen(pattern);
1614                 
1615                 if (lp < ld) {          /* pattern too short, cannot match */
1616 #ifdef NEED_DEBUG_HERE
1617                         ast_log(LOG_NOTICE,"return (0) - pattern too short, cannot match\n");
1618 #endif
1619                         return 0;
1620                 }
1621                 /* depending on the mode, accept full or partial match or both */
1622                 if (mode == E_MATCH) {
1623 #ifdef NEED_DEBUG_HERE
1624                         ast_log(LOG_NOTICE,"return (!strcmp(%s,%s) when mode== E_MATCH)\n", pattern, data);
1625 #endif
1626                         return !strcmp(pattern, data); /* 1 on match, 0 on fail */
1627                 } 
1628                 if (ld == 0 || !strncasecmp(pattern, data, ld)) { /* partial or full match */
1629 #ifdef NEED_DEBUG_HERE
1630                         ast_log(LOG_NOTICE,"return (mode(%d) == E_MATCHMORE ? lp(%d) > ld(%d) : 1)\n", mode, lp, ld);
1631 #endif
1632                         return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
1633                 } else {
1634 #ifdef NEED_DEBUG_HERE
1635                         ast_log(LOG_NOTICE,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld, pattern, data);
1636 #endif
1637                         return 0;
1638                 }
1639         }
1640         pattern++; /* skip leading _ */
1641         /*
1642          * XXX below we stop at '/' which is a separator for the CID info. However we should
1643          * not store '/' in the pattern at all. When we insure it, we can remove the checks.
1644          */
1645         while (*data && *pattern && *pattern != '/') {
1646                 const char *end;
1647
1648                 if (*data == '-') { /* skip '-' in data (just a separator) */
1649                         data++;
1650                         continue;
1651                 }
1652                 switch (toupper(*pattern)) {
1653                 case '[':       /* a range */
1654                         end = strchr(pattern+1, ']'); /* XXX should deal with escapes ? */
1655                         if (end == NULL) {
1656                                 ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
1657                                 return 0;       /* unconditional failure */
1658                         }
1659                         for (pattern++; pattern != end; pattern++) {
1660                                 if (pattern+2 < end && pattern[1] == '-') { /* this is a range */
1661                                         if (*data >= pattern[0] && *data <= pattern[2])
1662                                                 break;  /* match found */
1663                                         else {
1664                                                 pattern += 2; /* skip a total of 3 chars */
1665                                                 continue;
1666                                         }
1667                                 } else if (*data == pattern[0])
1668                                         break;  /* match found */
1669                         }
1670                         if (pattern == end) {
1671 #ifdef NEED_DEBUG_HERE
1672                                 ast_log(LOG_NOTICE,"return (0) when pattern==end\n");
1673 #endif
1674                                 return 0;
1675                         }
1676                         pattern = end;  /* skip and continue */
1677                         break;
1678                 case 'N':
1679                         if (*data < '2' || *data > '9') {
1680 #ifdef NEED_DEBUG_HERE
1681                                 ast_log(LOG_NOTICE,"return (0) N is matched\n");
1682 #endif
1683                                 return 0;
1684                         }
1685                         break;
1686                 case 'X':
1687                         if (*data < '0' || *data > '9') {
1688 #ifdef NEED_DEBUG_HERE
1689                                 ast_log(LOG_NOTICE,"return (0) X is matched\n");
1690 #endif
1691                                 return 0;
1692                         }
1693                         break;
1694                 case 'Z':
1695                         if (*data < '1' || *data > '9') {
1696 #ifdef NEED_DEBUG_HERE
1697                                 ast_log(LOG_NOTICE,"return (0) Z is matched\n");
1698 #endif
1699                                 return 0;
1700                         }
1701                         break;
1702                 case '.':       /* Must match, even with more digits */
1703 #ifdef NEED_DEBUG_HERE
1704                         ast_log(LOG_NOTICE,"return (1) when '.' is matched\n");
1705 #endif
1706                         return 1;
1707                 case '!':       /* Early match */
1708 #ifdef NEED_DEBUG_HERE
1709                         ast_log(LOG_NOTICE,"return (2) when '!' is matched\n");
1710 #endif
1711                         return 2;
1712                 case ' ':
1713                 case '-':       /* Ignore these in patterns */
1714                         data--; /* compensate the final data++ */
1715                         break;
1716                 default:
1717                         if (*data != *pattern) {
1718 #ifdef NEED_DEBUG_HERE
1719                                 ast_log(LOG_NOTICE,"return (0) when *data(%c) != *pattern(%c)\n", *data, *pattern);
1720 #endif
1721                                 return 0;
1722                         }
1723                         
1724                 }
1725                 data++;
1726                 pattern++;
1727         }
1728         if (*data)                      /* data longer than pattern, no match */ {
1729 #ifdef NEED_DEBUG_HERE
1730                 ast_log(LOG_NOTICE,"return (0) when data longer than pattern\n");
1731 #endif
1732                 return 0;
1733         }
1734         
1735         /*
1736          * match so far, but ran off the end of the data.
1737          * Depending on what is next, determine match or not.
1738          */
1739         if (*pattern == '\0' || *pattern == '/') {      /* exact match */
1740 #ifdef NEED_DEBUG_HERE
1741                 ast_log(LOG_NOTICE,"at end, return (%d) in 'exact match'\n", (mode==E_MATCHMORE) ? 0 : 1);
1742 #endif
1743                 return (mode == E_MATCHMORE) ? 0 : 1;   /* this is a failure for E_MATCHMORE */
1744         } else if (*pattern == '!')     {               /* early match */
1745 #ifdef NEED_DEBUG_HERE
1746                 ast_log(LOG_NOTICE,"at end, return (2) when '!' is matched\n");
1747 #endif
1748                 return 2;
1749         } else {                                                /* partial match */
1750 #ifdef NEED_DEBUG_HERE
1751                 ast_log(LOG_NOTICE,"at end, return (%d) which deps on E_MATCH\n", (mode == E_MATCH) ? 0 : 1);
1752 #endif
1753                 return (mode == E_MATCH) ? 0 : 1;       /* this is a failure for E_MATCH */
1754         }
1755 }
1756
1757 /*
1758  * Wrapper around _extension_match_core() to do performance measurement
1759  * using the profiling code.
1760  */
1761 static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
1762 {
1763         int i;
1764         static int prof_id = -2;        /* marker for 'unallocated' id */
1765         if (prof_id == -2)
1766                 prof_id = ast_add_profile("ext_match", 0);
1767         ast_mark(prof_id, 1);
1768         i = _extension_match_core(pattern, data, mode);
1769         ast_mark(prof_id, 0);
1770         return i;
1771 }
1772
1773 int ast_extension_match(const char *pattern, const char *data)
1774 {
1775         return extension_match_core(pattern, data, E_MATCH);
1776 }
1777
1778 int ast_extension_close(const char *pattern, const char *data, int needmore)
1779 {
1780         if (needmore != E_MATCHMORE && needmore != E_CANMATCH)
1781                 ast_log(LOG_WARNING, "invalid argument %d\n", needmore);
1782         return extension_match_core(pattern, data, needmore);
1783 }
1784
1785 struct fake_context /* this struct is purely for matching in the hashtab */
1786 {
1787         ast_rwlock_t lock;                      
1788         struct ast_exten *root;         
1789         struct ast_hashtab *root_table;            
1790         struct match_char *pattern_tree;       
1791         struct ast_context *next;       
1792         struct ast_include *includes;           
1793         struct ast_ignorepat *ignorepats;       
1794         const char *registrar;
1795         int refcount;
1796         AST_LIST_HEAD_NOLOCK(, ast_sw) alts;    
1797         ast_mutex_t macrolock;          
1798         char name[256];         
1799 };
1800
1801 struct ast_context *ast_context_find(const char *name)
1802 {
1803         struct ast_context *tmp = NULL;
1804         struct fake_context item;
1805         strncpy(item.name,name,256);
1806         ast_rdlock_contexts();
1807         if( contexts_table ) {
1808                 tmp = ast_hashtab_lookup(contexts_table,&item);
1809         } else {
1810                 while ( (tmp = ast_walk_contexts(tmp)) ) {
1811                         if (!name || !strcasecmp(name, tmp->name))
1812                                 break;
1813                 }
1814         }
1815         ast_unlock_contexts();
1816         return tmp;
1817 }
1818
1819 #define STATUS_NO_CONTEXT       1
1820 #define STATUS_NO_EXTENSION     2
1821 #define STATUS_NO_PRIORITY      3
1822 #define STATUS_NO_LABEL         4
1823 #define STATUS_SUCCESS          5
1824
1825 static int matchcid(const char *cidpattern, const char *callerid)
1826 {
1827         /* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
1828            failing to get a number should count as a match, otherwise not */
1829
1830         if (ast_strlen_zero(callerid))
1831                 return ast_strlen_zero(cidpattern) ? 1 : 0;
1832
1833         return ast_extension_match(cidpattern, callerid);
1834 }
1835
1836 struct ast_exten *pbx_find_extension(struct ast_channel *chan,
1837         struct ast_context *bypass, struct pbx_find_info *q,
1838         const char *context, const char *exten, int priority,
1839         const char *label, const char *callerid, enum ext_match_t action)
1840 {
1841         int x, res;
1842         struct ast_context *tmp = NULL;
1843         struct ast_exten *e = NULL, *eroot = NULL;
1844         struct ast_include *i = NULL;
1845         struct ast_sw *sw = NULL;
1846         struct ast_exten pattern = {NULL, };
1847         struct scoreboard score = {0, };
1848         struct ast_str *tmpdata = NULL;
1849
1850         pattern.label = label;
1851         pattern.priority = priority;
1852 #ifdef NEED_DEBUG_HERE
1853         ast_log(LOG_NOTICE,"Looking for cont/ext/prio/label/action = %s/%s/%d/%s/%d\n", context, exten, priority, label, (int)action);
1854 #endif
1855
1856         if (ast_strlen_zero(exten))
1857                 return NULL;
1858
1859         /* Initialize status if appropriate */
1860         if (q->stacklen == 0) {
1861                 q->status = STATUS_NO_CONTEXT;
1862                 q->swo = NULL;
1863                 q->data = NULL;
1864                 q->foundcontext = NULL;
1865         } else if (q->stacklen >= AST_PBX_MAX_STACK) {
1866                 ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
1867                 return NULL;
1868         }
1869
1870         /* Check first to see if we've already been checked */
1871         for (x = 0; x < q->stacklen; x++) {
1872                 if (!strcasecmp(q->incstack[x], context))
1873                         return NULL;
1874         }
1875
1876         if (bypass)     /* bypass means we only look there */
1877                 tmp = bypass;
1878         else {  /* look in contexts */
1879                 struct fake_context item;
1880                 strncpy(item.name,context,256);
1881                 tmp = ast_hashtab_lookup(contexts_table,&item);
1882 #ifdef NOTNOW
1883                 tmp = NULL;
1884                 while ((tmp = ast_walk_contexts(tmp)) ) {
1885                         if (!strcmp(tmp->name, context))
1886                                 break;
1887                 }
1888 #endif
1889                 if (!tmp)
1890                         return NULL;
1891                 
1892         }
1893
1894         if (q->status < STATUS_NO_EXTENSION)
1895                 q->status = STATUS_NO_EXTENSION;
1896         
1897         /* Do a search for matching extension */
1898
1899         eroot = NULL;
1900         score.total_specificity = 0;
1901         score.exten = 0;
1902         score.total_length = 0;
1903         if (!tmp->pattern_tree && tmp->root_table)
1904         {
1905                 create_match_char_tree(tmp);
1906 #ifdef NEED_DEBUG
1907                 ast_log(LOG_DEBUG,"Tree Created in context %s:\n", context);
1908                 log_match_char_tree(tmp->pattern_tree," ");
1909 #endif
1910         }
1911 #ifdef NEED_DEBUG
1912         ast_log(LOG_NOTICE,"The Trie we are searching in:\n");
1913         log_match_char_tree(tmp->pattern_tree, "::  ");
1914 #endif
1915
1916         do {
1917                 if (!ast_strlen_zero(overrideswitch)) {
1918                         char *osw = ast_strdupa(overrideswitch), *name;
1919                         struct ast_switch *asw;
1920                         ast_switch_f *aswf = NULL;
1921                         char *datap;
1922                         int eval = 0;
1923
1924                         name = strsep(&osw, "/");
1925                         asw = pbx_findswitch(name);
1926
1927                         if (!asw) {
1928                                 ast_log(LOG_WARNING, "No such switch '%s'\n", name);
1929                                 break;
1930                         }
1931
1932                         if (osw && strchr(osw, '$')) {
1933                                 eval = 1;
1934                         }
1935
1936                         if (eval && !(tmpdata = ast_str_thread_get(&switch_data, 512))) {
1937                                 ast_log(LOG_WARNING, "Can't evaluate overrideswitch?!");
1938                                 break;
1939                         } else if (eval) {
1940                                 /* Substitute variables now */
1941                                 pbx_substitute_variables_helper(chan, osw, tmpdata->str, tmpdata->len);
1942                                 datap = tmpdata->str;
1943                         } else {
1944                                 datap = osw;
1945                         }
1946
1947                         /* equivalent of extension_match_core() at the switch level */
1948                         if (action == E_CANMATCH)
1949                                 aswf = asw->canmatch;
1950                         else if (action == E_MATCHMORE)
1951                                 aswf = asw->matchmore;
1952                         else /* action == E_MATCH */
1953                                 aswf = asw->exists;
1954                         if (!aswf) {
1955                                 res = 0;
1956                         } else {
1957                                 if (chan) {
1958                                         ast_autoservice_start(chan);
1959                                 }
1960                                 res = aswf(chan, context, exten, priority, callerid, datap);
1961                                 if (chan) {
1962                                         ast_autoservice_stop(chan);
1963                                 }
1964                         }
1965                         if (res) {      /* Got a match */
1966                                 q->swo = asw;
1967                                 q->data = datap;
1968                                 q->foundcontext = context;
1969                                 /* XXX keep status = STATUS_NO_CONTEXT ? */
1970                                 return NULL;
1971                         }
1972                 }
1973         } while (0);
1974
1975         if (extenpatternmatchnew) {
1976                 new_find_extension(exten, &score, tmp->pattern_tree, 0, 0, callerid, label, action);
1977                 eroot = score.exten;
1978                 
1979                 if (score.last_char == '!' && action == E_MATCHMORE) {
1980                         /* We match an extension ending in '!'.
1981                          * The decision in this case is final and is NULL (no match).
1982                          */
1983 #ifdef NEED_DEBUG_HERE
1984                         ast_log(LOG_NOTICE,"Returning MATCHMORE NULL with exclamation point.\n");
1985 #endif
1986                         return NULL;
1987                 }
1988                 
1989                 if (!eroot && (action == E_CANMATCH || action == E_MATCHMORE) && score.canmatch_exten) {
1990                         q->status = STATUS_SUCCESS;
1991 #ifdef NEED_DEBUG_HERE
1992                         ast_log(LOG_NOTICE,"Returning CANMATCH exten %s\n", score.canmatch_exten->exten);
1993 #endif
1994                         return score.canmatch_exten;
1995                 }
1996                 
1997                 if ((action == E_MATCHMORE || action == E_CANMATCH)  && eroot) {
1998                         if (score.node) {
1999                                 struct ast_exten *z = trie_find_next_match(score.node);
2000                                 if (z) {
2001 #ifdef NEED_DEBUG_HERE
2002                                         ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z->exten);
2003 #endif
2004                                 } else {
2005                                         if (score.canmatch_exten) {
2006 #ifdef NEED_DEBUG_HERE
2007                                                 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE canmatchmatch exten %s(%p)\n", score.canmatch_exten->exten, score.canmatch_exten);
2008 #endif
2009                                                 return score.canmatch_exten;
2010                                         } else {
2011 #ifdef NEED_DEBUG_HERE
2012                                                 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten NULL\n");
2013 #endif
2014                                         }
2015                                 }
2016                                 return z;
2017                         }
2018 #ifdef NEED_DEBUG_HERE
2019                         ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE NULL (no next_match)\n");
2020 #endif
2021                         return NULL;  /* according to the code, complete matches are null matches in MATCHMORE mode */
2022                 }
2023                 
2024                 if (eroot) {
2025                         /* found entry, now look for the right priority */
2026                         if (q->status < STATUS_NO_PRIORITY)
2027                                 q->status = STATUS_NO_PRIORITY;
2028                         e = NULL;
2029                         if (action == E_FINDLABEL && label ) {
2030                                 if (q->status < STATUS_NO_LABEL)
2031                                         q->status = STATUS_NO_LABEL;
2032                                 e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
2033                         } else {
2034                                 e = ast_hashtab_lookup(eroot->peer_table, &pattern);
2035                         }
2036                         if (e) {        /* found a valid match */
2037                                 q->status = STATUS_SUCCESS;
2038                                 q->foundcontext = context;
2039 #ifdef NEED_DEBUG_HERE
2040                                 ast_log(LOG_NOTICE,"Returning complete match of exten %s\n", e->exten);
2041 #endif
2042                                 return e;
2043                         }
2044                 }
2045         } else {   /* the old/current default exten pattern match algorithm */
2046                 
2047                 /* scan the list trying to match extension and CID */
2048                 eroot = NULL;
2049                 while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) {
2050                         int match = extension_match_core(eroot->exten, exten, action);
2051                         /* 0 on fail, 1 on match, 2 on earlymatch */
2052                         
2053                         if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid)))
2054                                 continue;       /* keep trying */
2055                         if (match == 2 && action == E_MATCHMORE) {
2056                                 /* We match an extension ending in '!'.
2057                                  * The decision in this case is final and is NULL (no match).
2058                                  */
2059                                 return NULL;
2060                         }
2061                         /* found entry, now look for the right priority */
2062                         if (q->status < STATUS_NO_PRIORITY)
2063                                 q->status = STATUS_NO_PRIORITY;
2064                         e = NULL;
2065                         if (action == E_FINDLABEL && label ) {
2066                                 if (q->status < STATUS_NO_LABEL)
2067                                         q->status = STATUS_NO_LABEL;
2068                                 e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
2069                         } else {
2070                                 e = ast_hashtab_lookup(eroot->peer_table, &pattern);
2071                         }
2072 #ifdef NOTNOW
2073                         while ( (e = ast_walk_extension_priorities(eroot, e)) ) {
2074                                 /* Match label or priority */
2075                                 if (action == E_FINDLABEL) {
2076                                         if (q->status < STATUS_NO_LABEL)
2077                                                 q->status = STATUS_NO_LABEL;
2078                                         if (label && e->label && !strcmp(label, e->label))
2079                                                 break;  /* found it */
2080                                 } else if (e->priority == priority) {
2081                                         break;  /* found it */
2082                                 } /* else keep searching */
2083                         }
2084 #endif
2085                         if (e) {        /* found a valid match */
2086                                 q->status = STATUS_SUCCESS;
2087                                 q->foundcontext = context;
2088                                 return e;
2089                         }
2090                 }
2091         }
2092         
2093         
2094         /* Check alternative switches */
2095         AST_LIST_TRAVERSE(&tmp->alts, sw, list) {
2096                 struct ast_switch *asw = pbx_findswitch(sw->name);
2097                 ast_switch_f *aswf = NULL;
2098                 char *datap;
2099
2100                 if (!asw) {
2101                         ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
2102                         continue;
2103                 }
2104                 /* Substitute variables now */
2105                 
2106                 if (sw->eval) {
2107                         if (!(tmpdata = ast_str_thread_get(&switch_data, 512))) {
2108                                 ast_log(LOG_WARNING, "Can't evaluate switch?!");
2109                                 continue;
2110                         }
2111                         pbx_substitute_variables_helper(chan, sw->data, tmpdata->str, tmpdata->len);
2112                 }
2113
2114                 /* equivalent of extension_match_core() at the switch level */
2115                 if (action == E_CANMATCH)
2116                         aswf = asw->canmatch;
2117                 else if (action == E_MATCHMORE)
2118                         aswf = asw->matchmore;
2119                 else /* action == E_MATCH */
2120                         aswf = asw->exists;
2121                 datap = sw->eval ? tmpdata->str : sw->data;
2122                 if (!aswf)
2123                         res = 0;
2124                 else {
2125                         if (chan)
2126                                 ast_autoservice_start(chan);
2127                         res = aswf(chan, context, exten, priority, callerid, datap);
2128                         if (chan)
2129                                 ast_autoservice_stop(chan);
2130                 }
2131                 if (res) {      /* Got a match */
2132                         q->swo = asw;
2133                         q->data = datap;
2134                         q->foundcontext = context;
2135                         /* XXX keep status = STATUS_NO_CONTEXT ? */
2136                         return NULL;
2137                 }
2138         }
2139         q->incstack[q->stacklen++] = tmp->name; /* Setup the stack */
2140         /* Now try any includes we have in this context */
2141         for (i = tmp->includes; i; i = i->next) {
2142                 if (include_valid(i)) {
2143                         if ((e = pbx_find_extension(chan, bypass, q, i->rname, exten, priority, label, callerid, action))) {
2144 #ifdef NEED_DEBUG_HERE
2145                                 ast_log(LOG_NOTICE,"Returning recursive match of %s\n", e->exten);
2146 #endif
2147                                 return e;
2148                         }
2149                         if (q->swo)
2150                                 return NULL;
2151                 }
2152         }
2153         return NULL;
2154 }
2155
2156 /*! 
2157  * \brief extract offset:length from variable name.
2158  * \return 1 if there is a offset:length part, which is
2159  * trimmed off (values go into variables)
2160  */
2161 static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
2162 {
2163         int parens = 0;
2164
2165         *offset = 0;
2166         *length = INT_MAX;
2167         *isfunc = 0;
2168         for (; *var; var++) {
2169                 if (*var == '(') {
2170                         (*isfunc)++;
2171                         parens++;
2172                 } else if (*var == ')') {
2173                         parens--;
2174                 } else if (*var == ':' && parens == 0) {
2175                         *var++ = '\0';
2176                         sscanf(var, "%d:%d", offset, length);
2177                         return 1; /* offset:length valid */
2178                 }
2179         }
2180         return 0;
2181 }
2182
2183 /*! 
2184  *\brief takes a substring. It is ok to call with value == workspace.
2185  * \param value
2186  * \param offset < 0 means start from the end of the string and set the beginning
2187  *   to be that many characters back.
2188  * \param length is the length of the substring, a value less than 0 means to leave
2189  * that many off the end.
2190  * \param workspace
2191  * \param workspace_len
2192  * Always return a copy in workspace.
2193  */
2194 static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
2195 {
2196         char *ret = workspace;
2197         int lr; /* length of the input string after the copy */
2198
2199         ast_copy_string(workspace, value, workspace_len); /* always make a copy */
2200
2201         lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
2202
2203         /* Quick check if no need to do anything */
2204         if (offset == 0 && length >= lr)        /* take the whole string */
2205                 return ret;
2206
2207         if (offset < 0) {       /* translate negative offset into positive ones */
2208                 offset = lr + offset;
2209                 if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
2210                         offset = 0;
2211         }
2212
2213         /* too large offset result in empty string so we know what to return */
2214         if (offset >= lr)
2215                 return ret + lr;        /* the final '\0' */
2216
2217         ret += offset;          /* move to the start position */
2218         if (length >= 0 && length < lr - offset)        /* truncate if necessary */
2219                 ret[length] = '\0';
2220         else if (length < 0) {
2221                 if (lr > offset - length) /* After we remove from the front and from the rear, is there anything left? */
2222                         ret[lr + length - offset] = '\0';
2223                 else
2224                         ret[0] = '\0';
2225         }
2226
2227         return ret;
2228 }
2229
2230 /*! \brief  Support for Asterisk built-in variables in the dialplan
2231
2232 \note   See also
2233         - \ref AstVar   Channel variables
2234         - \ref AstCauses The HANGUPCAUSE variable
2235  */
2236 void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
2237 {
2238         const char not_found = '\0';
2239         char *tmpvar;
2240         const char *s;  /* the result */
2241         int offset, length;
2242         int i, need_substring;
2243         struct varshead *places[2] = { headp, &globals };       /* list of places where we may look */
2244
2245         if (c) {
2246                 ast_channel_lock(c);
2247                 places[0] = &c->varshead;
2248         }
2249         /*
2250          * Make a copy of var because parse_variable_name() modifies the string.
2251          * Then if called directly, we might need to run substring() on the result;
2252          * remember this for later in 'need_substring', 'offset' and 'length'
2253          */
2254         tmpvar = ast_strdupa(var);      /* parse_variable_name modifies the string */
2255         need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);
2256
2257         /*
2258          * Look first into predefined variables, then into variable lists.
2259          * Variable 's' points to the result, according to the following rules:
2260          * s == &not_found (set at the beginning) means that we did not find a
2261          *      matching variable and need to look into more places.
2262          * If s != &not_found, s is a valid result string as follows:
2263          * s = NULL if the variable does not have a value;
2264          *      you typically do this when looking for an unset predefined variable.
2265          * s = workspace if the result has been assembled there;
2266          *      typically done when the result is built e.g. with an snprintf(),
2267          *      so we don't need to do an additional copy.
2268          * s != workspace in case we have a string, that needs to be copied
2269          *      (the ast_copy_string is done once for all at the end).
2270          *      Typically done when the result is already available in some string.
2271          */
2272         s = &not_found; /* default value */
2273         if (c) {        /* This group requires a valid channel */
2274                 /* Names with common parts are looked up a piece at a time using strncmp. */
2275                 if (!strncmp(var, "CALL", 4)) {
2276                         if (!strncmp(var + 4, "ING", 3)) {
2277                                 if (!strcmp(var + 7, "PRES")) {                 /* CALLINGPRES */
2278                                         snprintf(workspace, workspacelen, "%d", c->cid.cid_pres);
2279                                         s = workspace;
2280                                 } else if (!strcmp(var + 7, "ANI2")) {          /* CALLINGANI2 */
2281                                         snprintf(workspace, workspacelen, "%d", c->cid.cid_ani2);
2282                                         s = workspace;
2283                                 } else if (!strcmp(var + 7, "TON")) {           /* CALLINGTON */
2284                                         snprintf(workspace, workspacelen, "%d", c->cid.cid_ton);
2285                                         s = workspace;
2286                                 } else if (!strcmp(var + 7, "TNS")) {           /* CALLINGTNS */
2287                                         snprintf(workspace, workspacelen, "%d", c->cid.cid_tns);
2288                                         s = workspace;
2289                                 }
2290                         }
2291                 } else if (!strcmp(var, "HINT")) {
2292                         s = ast_get_hint(workspace, workspacelen, NULL, 0, c, c->context, c->exten) ? workspace : NULL;
2293                 } else if (!strcmp(var, "HINTNAME")) {
2294                         s = ast_get_hint(NULL, 0, workspace, workspacelen, c, c->context, c->exten) ? workspace : NULL;
2295                 } else if (!strcmp(var, "EXTEN")) {
2296                         s = c->exten;
2297                 } else if (!strcmp(var, "CONTEXT")) {
2298                         s = c->context;
2299                 } else if (!strcmp(var, "PRIORITY")) {
2300                         snprintf(workspace, workspacelen, "%d", c->priority);
2301                         s = workspace;
2302                 } else if (!strcmp(var, "CHANNEL")) {
2303                         s = c->name;
2304                 } else if (!strcmp(var, "UNIQUEID")) {
2305                         s = c->uniqueid;
2306                 } else if (!strcmp(var, "HANGUPCAUSE")) {
2307                         snprintf(workspace, workspacelen, "%d", c->hangupcause);
2308                         s = workspace;
2309                 }
2310         }
2311         if (s == &not_found) { /* look for more */
2312                 if (!strcmp(var, "EPOCH")) {
2313                         snprintf(workspace, workspacelen, "%u",(int)time(NULL));
2314                         s = workspace;
2315                 } else if (!strcmp(var, "SYSTEMNAME")) {
2316                         s = ast_config_AST_SYSTEM_NAME;
2317                 } else if (!strcmp(var, "ENTITYID")) {
2318                         ast_eid_to_str(workspace, workspacelen, &g_eid);
2319                         s = workspace;
2320                 }
2321         }
2322         /* if not found, look into chanvars or global vars */
2323         for (i = 0; s == &not_found && i < (sizeof(places) / sizeof(places[0])); i++) {
2324                 struct ast_var_t *variables;
2325                 if (!places[i])
2326                         continue;
2327                 if (places[i] == &globals)
2328                         ast_rwlock_rdlock(&globalslock);
2329                 AST_LIST_TRAVERSE(places[i], variables, entries) {
2330                         if (!strcasecmp(ast_var_name(variables), var)) {
2331                                 s = ast_var_value(variables);
2332                                 break;
2333                         }
2334                 }
2335                 if (places[i] == &globals)
2336                         ast_rwlock_unlock(&globalslock);
2337         }
2338         if (s == &not_found || s == NULL)
2339                 *ret = NULL;
2340         else {
2341                 if (s != workspace)
2342                         ast_copy_string(workspace, s, workspacelen);
2343                 *ret = workspace;
2344                 if (need_substring)
2345                         *ret = substring(*ret, offset, length, workspace, workspacelen);
2346         }
2347
2348         if (c)
2349                 ast_channel_unlock(c);
2350 }
2351
2352 static void exception_store_free(void *data)
2353 {
2354         struct pbx_exception *exception = data;
2355         ast_string_field_free_memory(exception);
2356         ast_free(exception);
2357 }
2358
2359 static struct ast_datastore_info exception_store_info = {
2360         .type = "EXCEPTION",
2361         .destroy = exception_store_free,
2362 };
2363
2364 int pbx_builtin_raise_exception(struct ast_channel *chan, void *vreason)
2365 {
2366         const char *reason = vreason;
2367         struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
2368         struct pbx_exception *exception = NULL;
2369
2370         if (!ds) {
2371                 ds = ast_channel_datastore_alloc(&exception_store_info, NULL);
2372                 if (!ds)
2373                         return -1;
2374                 exception = ast_calloc(1, sizeof(struct pbx_exception));
2375                 if (!exception) {
2376                         ast_channel_datastore_free(ds);
2377                         return -1;
2378                 }
2379                 if (ast_string_field_init(exception, 128)) {
2380                         ast_free(exception);
2381                         ast_channel_datastore_free(ds);
2382                         return -1;
2383                 }
2384                 ds->data = exception;
2385                 ast_channel_datastore_add(chan, ds);
2386         } else
2387                 exception = ds->data;
2388
2389         ast_string_field_set(exception, reason, reason);
2390         ast_string_field_set(exception, context, chan->context);
2391         ast_string_field_set(exception, exten, chan->exten);
2392         exception->priority = chan->priority;
2393         set_ext_pri(chan, "e", 0);
2394         return 0;
2395 }
2396
2397 static int acf_exception_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
2398 {
2399         struct ast_datastore *ds = ast_channel_datastore_find(chan, &exception_store_info, NULL);
2400         struct pbx_exception *exception = NULL;
2401         if (!ds || !ds->data)
2402                 return -1;
2403         exception = ds->data;
2404         if (!strcasecmp(data, "REASON"))
2405                 ast_copy_string(buf, exception->reason, buflen);
2406         else if (!strcasecmp(data, "CONTEXT"))
2407                 ast_copy_string(buf, exception->context, buflen);
2408         else if (!strncasecmp(data, "EXTEN", 5))
2409                 ast_copy_string(buf, exception->exten, buflen);
2410         else if (!strcasecmp(data, "PRIORITY"))
2411                 snprintf(buf, buflen, "%d", exception->priority);
2412         else
2413                 return -1;
2414         return 0;
2415 }
2416
2417 static struct ast_custom_function exception_function = {
2418         .name = "EXCEPTION",
2419         .synopsis = "Retrieve the details of the current dialplan exception",
2420         .desc =
2421 "The following fields are available for retrieval:\n"
2422 "  reason    INVALID, ERROR, RESPONSETIMEOUT, ABSOLUTETIMEOUT, or custom\n"
2423 "               value set by the RaiseException() application\n"
2424 "  context   The context executing when the exception occurred\n"
2425 "  exten     The extension executing when the exception occurred\n"
2426 "  priority  The numeric priority executing when the exception occurred\n",
2427         .syntax = "EXCEPTION(<field>)",
2428         .read = acf_exception_read,
2429 };
2430
2431 static char *handle_show_functions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2432 {
2433         struct ast_custom_function *acf;
2434         int count_acf = 0;
2435         int like = 0;
2436
2437         switch (cmd) {
2438         case CLI_INIT:
2439                 e->command = "core show functions [like]";
2440                 e->usage = 
2441                         "Usage: core show functions [like <text>]\n"
2442                         "       List builtin functions, optionally only those matching a given string\n";
2443                 return NULL;
2444         case CLI_GENERATE:
2445                 return NULL;
2446         }
2447
2448         if (a->argc == 5 && (!strcmp(a->argv[3], "like")) ) {
2449                 like = 1;
2450         } else if (a->argc != 3) {
2451                 return CLI_SHOWUSAGE;
2452         }
2453
2454         ast_cli(a->fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
2455
2456         AST_RWLIST_RDLOCK(&acf_root);
2457         AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
2458                 if (!like || strstr(acf->name, a->argv[4])) {
2459                         count_acf++;
2460                         ast_cli(a->fd, "%-20.20s  %-35.35s  %s\n", acf->name, acf->syntax, acf->synopsis);
2461                 }
2462         }
2463         AST_RWLIST_UNLOCK(&acf_root);
2464
2465         ast_cli(a->fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
2466
2467         return CLI_SUCCESS;
2468 }
2469
2470 static char *handle_show_function(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2471 {
2472         struct ast_custom_function *acf;
2473         /* Maximum number of characters added by terminal coloring is 22 */
2474         char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40];
2475         char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL;
2476         char stxtitle[40], *syntax = NULL;
2477         int synopsis_size, description_size, syntax_size;
2478         char *ret = NULL;
2479         int which = 0;
2480         int wordlen;
2481
2482         switch (cmd) {
2483         case CLI_INIT:
2484                 e->command = "core show function";
2485                 e->usage = 
2486                         "Usage: core show function <function>\n"
2487                         "       Describe a particular dialplan function.\n";
2488                 return NULL;
2489         case CLI_GENERATE:      
2490                 wordlen = strlen(a->word);
2491                 /* case-insensitive for convenience in this 'complete' function */
2492                 AST_RWLIST_RDLOCK(&acf_root);
2493                 AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
2494                         if (!strncasecmp(a->word, acf->name, wordlen) && ++which > a->n) {
2495                                 ret = ast_strdup(acf->name);
2496                                 break;
2497                         }
2498                 }
2499                 AST_RWLIST_UNLOCK(&acf_root);
2500
2501                 return ret;
2502         }
2503
2504         if (a->argc < 4)
2505                 return CLI_SHOWUSAGE;
2506
2507         if (!(acf = ast_custom_function_find(a->argv[3]))) {
2508                 ast_cli(a->fd, "No function by that name registered.\n");
2509                 return CLI_FAILURE;
2510
2511         }
2512
2513         if (acf->synopsis)
2514                 synopsis_size = strlen(acf->synopsis) + 23;
2515         else
2516                 synopsis_size = strlen("Not available") + 23;
2517         synopsis = alloca(synopsis_size);
2518
2519         if (acf->desc)
2520                 description_size = strlen(acf->desc) + 23;
2521         else
2522                 description_size = strlen("Not available") + 23;
2523         description = alloca(description_size);
2524
2525         if (acf->syntax)
2526                 syntax_size = strlen(acf->syntax) + 23;
2527         else
2528                 syntax_size = strlen("Not available") + 23;
2529         syntax = alloca(syntax_size);
2530
2531         snprintf(info, 64 + AST_MAX_APP, "\n  -= Info about function '%s' =- \n\n", acf->name);
2532         term_color(infotitle, info, COLOR_MAGENTA, 0, 64 + AST_MAX_APP + 22);
2533         term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
2534         term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
2535         term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
2536         term_color(syntax,
2537                    acf->syntax ? acf->syntax : "Not available",
2538                    COLOR_CYAN, 0, syntax_size);
2539         term_color(synopsis,
2540                    acf->synopsis ? acf->synopsis : "Not available",
2541                    COLOR_CYAN, 0, synopsis_size);
2542         term_color(description,
2543                    acf->desc ? acf->desc : "Not available",
2544                    COLOR_CYAN, 0, description_size);
2545
2546         ast_cli(a->fd,"%s%s%s\n\n%s%s\n\n%s%s\n", infotitle, stxtitle, syntax, syntitle, synopsis, destitle, description);
2547
2548         return CLI_SUCCESS;
2549 }
2550
2551 struct ast_custom_function *ast_custom_function_find(const char *name)
2552 {
2553         struct ast_custom_function *acf = NULL;
2554
2555         AST_RWLIST_RDLOCK(&acf_root);
2556         AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
2557                 if (!strcmp(name, acf->name))
2558                         break;
2559         }
2560         AST_RWLIST_UNLOCK(&acf_root);
2561
2562         return acf;
2563 }
2564
2565 int ast_custom_function_unregister(struct ast_custom_function *acf)
2566 {
2567         struct ast_custom_function *cur;
2568
2569         if (!acf)
2570                 return -1;
2571
2572         AST_RWLIST_WRLOCK(&acf_root);
2573         if ((cur = AST_RWLIST_REMOVE(&acf_root, acf, acflist)))
2574                 ast_verb(2, "Unregistered custom function %s\n", cur->name);
2575         AST_RWLIST_UNLOCK(&acf_root);
2576
2577         return cur ? 0 : -1;
2578 }
2579
2580 int __ast_custom_function_register(struct ast_custom_function *acf, struct ast_module *mod)
2581 {
2582         struct ast_custom_function *cur;
2583         char tmps[80];
2584
2585         if (!acf)
2586                 return -1;
2587
2588         acf->mod = mod;
2589
2590         AST_RWLIST_WRLOCK(&acf_root);
2591
2592         AST_RWLIST_TRAVERSE(&acf_root, cur, acflist) {
2593                 if (!strcmp(acf->name, cur->name)) {
2594                         ast_log(LOG_ERROR, "Function %s already registered.\n", acf->name);
2595                         AST_RWLIST_UNLOCK(&acf_root);
2596                         return -1;
2597                 }
2598         }
2599
2600         /* Store in alphabetical order */
2601         AST_RWLIST_TRAVERSE_SAFE_BEGIN(&acf_root, cur, acflist) {
2602                 if (strcasecmp(acf->name, cur->name) < 0) {
2603                         AST_RWLIST_INSERT_BEFORE_CURRENT(acf, acflist);
2604                         break;
2605                 }
2606         }
2607         AST_RWLIST_TRAVERSE_SAFE_END;
2608         if (!cur)
2609                 AST_RWLIST_INSERT_TAIL(&acf_root, acf, acflist);
2610
2611         AST_RWLIST_UNLOCK(&acf_root);
2612
2613         ast_verb(2, "Registered custom function '%s'\n", term_color(tmps, acf->name, COLOR_BRCYAN, 0, sizeof(tmps)));
2614
2615         return 0;
2616 }
2617
2618 /*! \brief return a pointer to the arguments of the function,
2619  * and terminates the function name with '\\0'
2620  */
2621 static char *func_args(char *function)
2622 {
2623         char *args = strchr(function, '(');
2624
2625         if (!args)
2626                 ast_log(LOG_WARNING, "Function doesn't contain parentheses.  Assuming null argument.\n");
2627         else {
2628                 char *p;
2629                 *args++ = '\0';
2630                 if ((p = strrchr(args, ')')) )
2631                         *p = '\0';
2632                 else
2633                         ast_log(LOG_WARNING, "Can't find trailing parenthesis?\n");
2634         }
2635         return args;
2636 }
2637
2638 int ast_func_read(struct ast_channel *chan, const char *function, char *workspace, size_t len)
2639 {
2640         char *copy = ast_strdupa(function);
2641         char *args = func_args(copy);
2642         struct ast_custom_function *acfptr = ast_custom_function_find(copy);
2643
2644         if (acfptr == NULL)
2645                 ast_log(LOG_ERROR, "Function %s not registered\n", copy);
2646         else if (!acfptr->read)
2647                 ast_log(LOG_ERROR, "Function %s cannot be read\n", copy);
2648         else {
2649                 int res;
2650                 struct ast_module_user *u = NULL;
2651                 if (acfptr->mod)
2652                         u = __ast_module_user_add(acfptr->mod, chan);
2653                 res = acfptr->read(chan, copy, args, workspace, len);
2654                 if (acfptr->mod && u)
2655                         __ast_module_user_remove(acfptr->mod, u);
2656                 return res;
2657         }
2658         return -1;
2659 }
2660
2661 int ast_func_write(struct ast_channel *chan, const char *function, const char *value)
2662 {
2663         char *copy = ast_strdupa(function);
2664         char *args = func_args(copy);
2665         struct ast_custom_function *acfptr = ast_custom_function_find(copy);
2666
2667         if (acfptr == NULL)
2668                 ast_log(LOG_ERROR, "Function %s not registered\n", copy);
2669         else if (!acfptr->write)
2670                 ast_log(LOG_ERROR, "Function %s cannot be written to\n", copy);
2671         else {
2672                 int res;
2673                 struct ast_module_user *u = NULL;
2674                 if (acfptr->mod)
2675                         u = __ast_module_user_add(acfptr->mod, chan);
2676                 res = acfptr->write(chan, copy, args, value);
2677                 if (acfptr->mod && u)
2678                         __ast_module_user_remove(acfptr->mod, u);
2679                 return res;
2680         }
2681
2682         return -1;
2683 }
2684
2685 static void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count)
2686 {
2687         /* Substitutes variables into cp2, based on string cp1, cp2 NO LONGER NEEDS TO BE ZEROED OUT!!!!  */
2688         char *cp4;
2689         const char *tmp, *whereweare;
2690         int length, offset, offset2, isfunction;
2691         char *workspace = NULL;
2692         char *ltmp = NULL, *var = NULL;
2693         char *nextvar, *nextexp, *nextthing;
2694         char *vars, *vare;
2695         int pos, brackets, needsub, len;
2696         
2697         *cp2 = 0; /* just in case nothing ends up there */
2698         whereweare=tmp=cp1;
2699         while (!ast_strlen_zero(whereweare) && count) {
2700                 /* Assume we're copying the whole remaining string */
2701                 pos = strlen(whereweare);
2702                 nextvar = NULL;
2703                 nextexp = NULL;
2704                 nextthing = strchr(whereweare, '$');
2705                 if (nextthing) {
2706                         switch (nextthing[1]) {
2707                         case '{':
2708                                 nextvar = nextthing;
2709                                 pos = nextvar - whereweare;
2710                                 break;
2711                         case '[':
2712                                 nextexp = nextthing;
2713                                 pos = nextexp - whereweare;
2714                                 break;
2715                         default:
2716                                 pos = 1;
2717                         }
2718                 }
2719
2720                 if (pos) {
2721                         /* Can't copy more than 'count' bytes */
2722                         if (pos > count)
2723                                 pos = count;
2724
2725                         /* Copy that many bytes */
2726                         memcpy(cp2, whereweare, pos);
2727
2728                         count -= pos;
2729                         cp2 += pos;
2730                         whereweare += pos;
2731                         *cp2 = 0;
2732                 }
2733
2734                 if (nextvar) {
2735                         /* We have a variable.  Find the start and end, and determine
2736                            if we are going to have to recursively call ourselves on the
2737                            contents */
2738                         vars = vare = nextvar + 2;
2739                         brackets = 1;
2740                         needsub = 0;
2741
2742                         /* Find the end of it */
2743                         while (brackets && *vare) {
2744                                 if ((vare[0] == '$') && (vare[1] == '{')) {
2745                                         needsub++;
2746                                 } else if (vare[0] == '{') {
2747                                         brackets++;
2748                                 } else if (vare[0] == '}') {
2749                                         brackets--;
2750                                 } else if ((vare[0] == '$') && (vare[1] == '['))
2751                                         needsub++;
2752                                 vare++;
2753                         }
2754                         if (brackets)
2755                                 ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
2756                         len = vare - vars - 1;
2757
2758                         /* Skip totally over variable string */
2759                         whereweare += (len + 3);
2760
2761                         if (!var)
2762                                 var = alloca(VAR_BUF_SIZE);
2763
2764                         /* Store variable name (and truncate) */
2765                         ast_copy_string(var, vars, len + 1);
2766
2767                         /* Substitute if necessary */
2768                         if (needsub) {
2769                                 if (!ltmp)
2770                                         ltmp = alloca(VAR_BUF_SIZE);
2771
2772                                 pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
2773                                 vars = ltmp;
2774                         } else {
2775                                 vars = var;
2776                         }
2777
2778                         if (!workspace)
2779                                 workspace = alloca(VAR_BUF_SIZE);
2780
2781                         workspace[0] = '\0';
2782
2783                         parse_variable_name(vars, &offset, &offset2, &isfunction);
2784                         if (isfunction) {
2785                                 /* Evaluate function */
2786                                 if (c || !headp)
2787                                         cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
2788                                 else {
2789                                         struct varshead old;
2790                                         struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/%p", vars);
2791                                         if (c) {
2792                                                 memcpy(&old, &c->varshead, sizeof(old));
2793                                                 memcpy(&c->varshead, headp, sizeof(c->varshead));
2794                                                 cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
2795                                                 /* Don't deallocate the varshead that was passed in */
2796                                                 memcpy(&c->varshead, &old, sizeof(c->varshead));
2797                                                 ast_channel_free(c);
2798                                         } else
2799                                                 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution.  Function results may be blank.\n");
2800                                 }
2801                                 ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
2802                         } else {
2803                                 /* Retrieve variable value */
2804                                 pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp);
2805                         }
2806                         if (cp4) {
2807                                 cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE);
2808
2809                                 length = strlen(cp4);
2810                                 if (length > count)
2811                                         length = count;
2812                                 memcpy(cp2, cp4, length);
2813                                 count -= length;
2814                                 cp2 += length;
2815                                 *cp2 = 0;
2816                         }
2817                 } else if (nextexp) {
2818                         /* We have an expression.  Find the start and end, and determine
2819                            if we are going to have to recursively call ourselves on the
2820                            contents */
2821                         vars = vare = nextexp + 2;
2822                         brackets = 1;
2823                         needsub = 0;
2824
2825                         /* Find the end of it */
2826                         while (brackets && *vare) {
2827                                 if ((vare[0] == '$') && (vare[1] == '[')) {
2828                                         needsub++;
2829                                         brackets++;
2830                                         vare++;
2831                                 } else if (vare[0] == '[') {
2832                                         brackets++;
2833                                 } else if (vare[0] == ']') {
2834                                         brackets--;
2835                                 } else if ((vare[0] == '$') && (vare[1] == '{')) {
2836                                         needsub++;
2837                                         vare++;
2838                                 }
2839                                 vare++;
2840                         }
2841                         if (brackets)
2842                                 ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
2843                         len = vare - vars - 1;
2844
2845                         /* Skip totally over expression */
2846                         whereweare += (len + 3);
2847
2848                         if (!var)
2849                                 var = alloca(VAR_BUF_SIZE);
2850
2851                         /* Store variable name (and truncate) */
2852                         ast_copy_string(var, vars, len + 1);
2853
2854                         /* Substitute if necessary */
2855                         if (needsub) {
2856                                 if (!ltmp)
2857                                         ltmp = alloca(VAR_BUF_SIZE);
2858
2859                                 pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
2860                                 vars = ltmp;
2861                         } else {
2862                                 vars = var;
2863                         }
2864
2865                         length = ast_expr(vars, cp2, count, c);
2866
2867                         if (length) {
2868                                 ast_debug(1, "Expression result is '%s'\n", cp2);
2869                                 count -= length;
2870                                 cp2 += length;
2871                                 *cp2 = 0;
2872                         }
2873                 }
2874         }
2875 }
2876
2877 void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
2878 {
2879         pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count);
2880 }
2881
2882 void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count)
2883 {
2884         pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count);
2885 }
2886
2887 static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e)
2888 {
2889         const char *tmp;
2890
2891         /* Nothing more to do */
2892         if (!e->data)
2893                 return;
2894
2895         /* No variables or expressions in e->data, so why scan it? */
2896         if ((!(tmp = strchr(e->data, '$'))) || (!strstr(tmp, "${") && !strstr(tmp, "$["))) {
2897                 ast_copy_string(passdata, e->data, datalen);
2898                 return;
2899         }
2900
2901         pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1);
2902 }
2903
2904 /*! \brief report AGI state for channel */
2905 const char *ast_agi_state(struct ast_channel *chan)
2906 {
2907         if (ast_test_flag(chan, AST_FLAG_AGI))
2908                 return "AGI";
2909         if (ast_test_flag(chan, AST_FLAG_FASTAGI))
2910                 return "FASTAGI";
2911         if (ast_test_flag(chan, AST_FLAG_ASYNCAGI))
2912                 return "ASYNCAGI";
2913         return "";
2914 }
2915
2916 /*! 
2917  * \brief The return value depends on the action:
2918  *
2919  * E_MATCH, E_CANMATCH, E_MATCHMORE require a real match,
2920  *      and return 0 on failure, -1 on match;
2921  * E_FINDLABEL maps the label to a priority, and returns
2922  *      the priority on success, ... XXX
2923  * E_SPAWN, spawn an application,
2924  *      
2925  * \retval 0 on success.
2926  * \retval  -1 on failure.
2927  *
2928  * \note The channel is auto-serviced in this function, because doing an extension
2929  * match may block for a long time.  For example, if the lookup has to use a network
2930  * dialplan switch, such as DUNDi or IAX2, it may take a while.  However, the channel
2931  * auto-service code will queue up any important signalling frames to be processed
2932  * after this is done.
2933  */
2934 static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con,
2935   const char *context, const char *exten, int priority,
2936   const char *label, const char *callerid, enum ext_match_t action, int *found, int combined_find_spawn)
2937 {
2938         struct ast_exten *e;
2939         struct ast_app *app;
2940         int res;
2941         struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
2942         char passdata[EXT_DATA_SIZE];
2943
2944         int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE);
2945
2946         ast_rdlock_contexts();
2947         if (found)
2948                 *found = 0;
2949
2950         e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action);
2951         if (e) {
2952                 if (found)
2953                         *found = 1;
2954                 if (matching_action) {
2955                         ast_unlock_contexts();
2956                         return -1;      /* success, we found it */
2957                 } else if (action == E_FINDLABEL) { /* map the label to a priority */
2958                         res = e->priority;
2959                         ast_unlock_contexts();
2960                         return res;     /* the priority we were looking for */
2961                 } else {        /* spawn */
2962                         if (!e->cached_app)
2963                                 e->cached_app = pbx_findapp(e->app);
2964                         app = e->cached_app;
2965                         ast_unlock_contexts();
2966                         if (!app) {
2967                                 ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
2968                                 return -1;
2969                         }
2970                         if (c->context != context)
2971                                 ast_copy_string(c->context, context, sizeof(c->context));
2972                         if (c->exten != exten)
2973                                 ast_copy_string(c->exten, exten, sizeof(c->exten));
2974                         c->priority = priority;
2975                         pbx_substitute_variables(passdata, sizeof(passdata), c, e);
2976 #ifdef CHANNEL_TRACE
2977                         ast_channel_trace_update(c);
2978 #endif
2979                         ast_debug(1, "Launching '%s'\n", app->name);
2980                         if (VERBOSITY_ATLEAST(3)) {
2981                                 char tmp[80], tmp2[80], tmp3[EXT_DATA_SIZE];
2982                                 ast_verb(3, "Executing [%s@%s:%d] %s(\"%s\", \"%s\") %s\n",
2983                                         exten, context, priority,
2984                                         term_color(tmp, app->name, COLOR_BRCYAN, 0, sizeof(tmp)),
2985                                         term_color(tmp2, c->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)),
2986                                         term_color(tmp3, passdata, COLOR_BRMAGENTA, 0, sizeof(tmp3)),
2987                                         "in new stack");
2988                         }
2989                         manager_event(EVENT_FLAG_DIALPLAN, "Newexten",
2990                                         "Channel: %s\r\n"
2991                                         "Context: %s\r\n"
2992                                         "Extension: %s\r\n"
2993                                         "Priority: %d\r\n"
2994                                         "Application: %s\r\n"
2995                                         "AppData: %s\r\n"
2996                                         "Uniqueid: %s\r\n"
2997                                         "AGIstate: %s\r\n",
2998                                         c->name, c->context, c->exten, c->priority, app->name, passdata, c->uniqueid, ast_agi_state(c));
2999                         return pbx_exec(c, app, passdata);      /* 0 on success, -1 on failure */
3000                 }
3001         } else if (q.swo) {     /* not found here, but in another switch */
3002                 ast_unlock_contexts();
3003                 if (matching_action) {
3004                         return -1;
3005                 } else {
3006                         if (!q.swo->exec) {
3007                                 ast_log(LOG_WARNING, "No execution engine for switch %s\n", q.swo->name);
3008                                 res = -1;
3009                         }
3010                         return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data);
3011                 }