2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief Core PBX routines.
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30 #include "asterisk/_private.h"
31 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
35 #if defined(HAVE_SYSINFO)
36 #include <sys/sysinfo.h>
39 #include <sys/loadavg.h>
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"
70 * \note I M P O R T A N T :
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 ;-)
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
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.
91 #define EXT_DATA_SIZE 256
93 #define EXT_DATA_SIZE 8192
96 #define SWITCH_DATA_LENGTH 256
98 #define VAR_BUF_SIZE 4096
101 #define VAR_SOFTTRAN 2
102 #define VAR_HARDTRAN 3
104 #define BACKGROUND_SKIP (1 << 0)
105 #define BACKGROUND_NOANSWER (1 << 1)
106 #define BACKGROUND_MATCHEXTEN (1 << 2)
107 #define BACKGROUND_PLAYBACK (1 << 3)
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),
116 #define WAITEXTEN_MOH (1 << 0)
117 #define WAITEXTEN_DIALTONE (1 << 1)
119 AST_APP_OPTIONS(waitexten_opts, {
120 AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
121 AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0),
127 static struct ast_taskprocessor *device_state_tps;
129 AST_THREADSTORAGE(switch_data);
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
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 */
156 /*! \brief ast_include: include= support in extensions.conf */
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 */
167 /*! \brief ast_sw: Switch statement in extensions.conf */
170 const char *registrar; /*!< Registrar */
171 char *data; /*!< Data load */
173 AST_LIST_ENTRY(ast_sw) list;
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];
184 /*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
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 */
196 struct scoreboard /* make sure all fields are 0 before calling new_find_extension */
198 int total_specificity;
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;
207 /*! \brief ast_context: An extension 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 */
224 /*! \brief ast_app: A registered application */
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 <name>' */
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 */
234 /*! \brief ast_state_cb: An extension state notify register item */
235 struct ast_state_cb {
238 ast_state_cb_type callback;
239 AST_LIST_ENTRY(ast_state_cb) entry;
242 /*! \brief Structure for dial plan hints
244 \note Hints are pointers from an extension in the dialplan to one or
245 more devices (tech/name)
246 - See \ref AstExtState
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 */
255 static const struct cfextension_states {
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" }
270 AST_LIST_ENTRY(statechange) entry;
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 */
281 int priority; /*!< Priority associated with this exception */
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);
329 /* a func for qsort to use to sort a char array */
330 static int compare_char(const void *a, const void *b)
336 else if ((*ac) == (*bc))
342 /* labels, contexts are case sensitive priority numbers are ints */
343 int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b)
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);
351 static int hashtab_compare_extens(const void *ah_a, const void *ah_b)
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 */
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 */
364 return 1; /* if there's matchcid on one but not the other, they are different */
368 static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b)
370 const struct ast_exten *ac = ah_a;
371 const struct ast_exten *bc = ah_b;
372 return ac->priority != bc->priority;
375 static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b)
377 const struct ast_exten *ac = ah_a;
378 const struct ast_exten *bc = ah_b;
379 return strcmp(ac->label, bc->label);
382 unsigned int ast_hashtab_hash_contexts(const void *obj)
384 const struct ast_context *ac = obj;
385 return ast_hashtab_hash_string(ac->name);
388 static unsigned int hashtab_hash_extens(const void *obj)
390 const struct ast_exten *ac = obj;
391 unsigned int x = ast_hashtab_hash_string(ac->exten);
394 y = ast_hashtab_hash_string(ac->cidmatch);
398 static unsigned int hashtab_hash_priority(const void *obj)
400 const struct ast_exten *ac = obj;
401 return ast_hashtab_hash_int(ac->priority);
404 static unsigned int hashtab_hash_labels(const void *obj)
406 const struct ast_exten *ac = obj;
407 return ast_hashtab_hash_string(ac->label);
411 AST_RWLOCK_DEFINE_STATIC(globalslock);
412 static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
414 static int autofallthrough = 1;
415 static int extenpatternmatchnew = 0;
416 static char *overrideswitch = NULL;
418 /*! \brief Subscription for device state change events */
419 static struct ast_event_sub *device_state_sub;
421 AST_MUTEX_DEFINE_STATIC(maxcalllock);
422 static int countcalls;
423 static int totalcalls;
425 static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
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);
435 /* These applications are built into the PBX core and do not
436 need separate modules */
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"
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"
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"
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"
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"
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"
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"
515 { "GotoIf", pbx_builtin_gotoif,
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"
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"
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"
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"
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"
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"
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"
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"
594 { "Progress", pbx_builtin_progress,
596 " Progress(): This application will request that in-band progress information\n"
597 "be provided to the calling channel.\n"
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"
607 { "ResetCDR", pbx_builtin_resetcdr,
608 "Resets the Call Data Record",
609 " ResetCDR([options]): This application causes the Call Data Record to be\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"
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"
624 { "SayAlpha", pbx_builtin_saycharacters,
626 " SayAlpha(string): This application will play the sounds that correspond to\n"
627 "the letters of the given string.\n"
630 { "SayDigits", pbx_builtin_saydigits,
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"
638 { "SayNumber", pbx_builtin_saynumber,
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"
646 { "SayPhonetic", pbx_builtin_sayphonetic,
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"
652 { "Set", pbx_builtin_setvar,
653 "Set channel variable or function value",
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"
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"
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"
676 { "SetAMAFlags", pbx_builtin_setamaflags,
678 " SetAMAFlags([flag]): This application will set the channel's AMA Flags for\n"
679 " billing purposes.\n"
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"
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"
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"
704 static struct ast_context *contexts;
705 static struct ast_hashtab *contexts_table = NULL;
707 AST_RWLOCK_DEFINE_STATIC(conlock); /*!< Lock for the ast_context list */
709 static AST_RWLIST_HEAD_STATIC(apps, ast_app);
711 static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
713 static int stateid = 1;
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.
720 static AST_RWLIST_HEAD_STATIC(hints, ast_hint);
722 static AST_LIST_HEAD_NOLOCK_STATIC(statecbs, ast_state_cb);
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 */
732 struct ast_module_user *u = NULL;
733 const char *saved_c_appl;
734 const char *saved_c_data;
736 if (c->cdr && !ast_check_hangup(c))
737 ast_cdr_setapp(c->cdr, app->name, data);
739 /* save channel values */
740 saved_c_appl= c->appl;
741 saved_c_data= c->data;
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;
757 /*! Go no deeper than this through includes (not counting loops) */
758 #define AST_PBX_MAX_STACK 128
760 /*! \brief Find application handle in linked list
762 struct ast_app *pbx_findapp(const char *app)
766 AST_RWLIST_RDLOCK(&apps);
767 AST_RWLIST_TRAVERSE(&apps, tmp, list) {
768 if (!strcasecmp(tmp->name, app))
771 AST_RWLIST_UNLOCK(&apps);
776 static struct ast_switch *pbx_findswitch(const char *sw)
778 struct ast_switch *asw;
780 AST_RWLIST_RDLOCK(&switches);
781 AST_RWLIST_TRAVERSE(&switches, asw, list) {
782 if (!strcasecmp(asw->name, sw))
785 AST_RWLIST_UNLOCK(&switches);
790 static inline int include_valid(struct ast_include *i)
795 return ast_check_timing(&(i->timing));
798 static void pbx_destroy(struct ast_pbx *p)
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:
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.
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) }
838 * { "f" } --next--> { "a" } --next--> { "x" exten_match: (c) }
839 * { "N" } --next--> { "X" } --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
843 * | { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
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...
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.
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.
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.
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.
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)
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. */
883 board->total_specificity = spec;
884 board->total_length = length;
885 board->exten = exten;
886 board->last_char = last;
888 #ifdef NEED_DEBUG_HERE
889 ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec);
893 void log_match_char_tree(struct match_char *node, char *prefix)
896 struct ast_str *my_prefix = ast_str_alloca(1024);
900 if (node && node->exten && node->exten)
901 snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
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);
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);
913 ast_str_set(&my_prefix, 0, "%s+ ", prefix);
916 log_match_char_tree(node->next_char, my_prefix->str);
919 log_match_char_tree(node->alt_char, prefix);
922 static void cli_match_char_tree(struct match_char *node, char *prefix, int fd)
925 struct ast_str *my_prefix = ast_str_alloca(1024);
929 if (node && node->exten && node->exten)
930 snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
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);
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);
942 ast_str_set(&my_prefix, 0, "%s+ ", prefix);
945 cli_match_char_tree(node->next_char, my_prefix->str, fd);
948 cli_match_char_tree(node->alt_char, prefix, fd);
951 static struct ast_exten *get_canmatch_exten(struct match_char *node)
953 /* find the exten at the end of the rope */
954 struct match_char *node2 = node;
956 for (node2 = node; node2; node2 = node2->next_char) {
958 #ifdef NEED_DEBUG_HERE
959 ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten);
964 #ifdef NEED_DEBUG_HERE
965 ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x);
970 static struct ast_exten *trie_find_next_match(struct match_char *node)
972 struct match_char *m3;
973 struct match_char *m4;
974 struct ast_exten *e3;
976 if (node && node->x[0] == '.' && !node->x[1]) /* dot and ! will ALWAYS be next match in a matchmore */
979 if (node && node->x[0] == '!' && !node->x[1])
982 if (!node || !node->next_char)
985 m3 = node->next_char;
989 for(m4=m3->alt_char; m4; m4 = m4->alt_char) {
993 for(m4=m3; m4; m4 = m4->alt_char) {
994 e3 = trie_find_next_match(m3);
1002 static char *action2str(enum ext_match_t action)
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)
1025 struct match_char *p; /* note minimal stack storage requirements */
1026 struct ast_exten pattern = { .label = label };
1029 ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree %s action=%s\n", str, tree->x, action2str(action));
1031 ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str, action2str(action));
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"); \
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 */ \
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 */ \
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 : \
1068 return; /* the first match is all we need */ \
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); \
1080 NEW_MATCHER_CHK_MATCH;
1081 NEW_MATCHER_RECURSE;
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;
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;
1093 } else if (p->x[0] == '.' && p->x[1] == 0) {
1094 /* how many chars will the . match against? */
1096 const char *str2 = str;
1097 while (*str2 && *str2 != '/') {
1101 if (p->exten && *str2 != '/') {
1102 update_scoreboard(score, length+i, spec+(i*p->specificity), p->exten, '.', callerid, p->deleted, p);
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 */
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 */
1115 } else if (p->x[0] == '!' && p->x[1] == 0) {
1116 /* how many chars will the . match against? */
1118 const char *str2 = str;
1119 while (*str2 && *str2 != '/') {
1123 if (p->exten && *str2 != '/') {
1124 update_scoreboard(score, length+1, spec+(p->specificity*i), p->exten, '!', callerid, p->deleted, p);
1126 ast_debug(4,"return because scoreboard has a '!' match--- %s\n", score->exten->exten);
1127 return; /* the first match is all we need */
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 */
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 */
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;
1152 ast_debug(4,"return at end of func\n");
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.
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.
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...
1172 static struct match_char *already_in_tree(struct match_char *current, char *pat)
1174 struct match_char *t;
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 */
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 */
1191 static void insert_in_next_chars_alt_char_list(struct match_char **parent_ptr, struct match_char *node)
1193 struct match_char *curr, *lcurr;
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)) {
1200 if ((*parent_ptr)->specificity > node->specificity){
1201 /* insert at head */
1202 node->alt_char = (*parent_ptr);
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;
1216 lcurr->alt_char = node;
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)
1226 struct match_char *m;
1228 if (!(m = ast_calloc(1, sizeof(*m))))
1231 if (!(m->x = ast_strdup(pattern))) {
1236 /* the specificity scores are the same as used in the old
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;
1250 m->specificity = specificity;
1252 if (!con->pattern_tree) {
1253 insert_in_next_chars_alt_char_list(&con->pattern_tree, m);
1255 if (already) { /* switch to the new regime (traversing vs appending)*/
1256 insert_in_next_chars_alt_char_list(nextcharptr, m);
1258 insert_in_next_chars_alt_char_list(¤t->next_char, m);
1265 static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly)
1267 struct match_char *m1 = NULL, *m2 = NULL, **m0;
1273 char *s1 = extenbuf;
1274 int l1 = strlen(e1->exten) + strlen(e1->cidmatch) + 2;
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);
1286 ast_log(LOG_DEBUG,"Adding exten %s%c%s to tree\n", s1, e1->matchcid? '/':' ', e1->matchcid? e1->cidmatch : "");
1288 m1 = con->pattern_tree; /* each pattern starts over at the root of the pattern tree */
1289 m0 = &con->pattern_tree;
1297 if (pattern && *s1 == '[' && *(s1-1) != '\\') {
1300 s1++; /* get past the '[' */
1301 while (*s1 != ']' && *(s1-1) != '\\' ) {
1303 if (*(s1+1) == ']') {
1306 } else if (*(s1+1) == '\\') {
1309 } else if (*(s1+1) == '-') {
1312 } else if (*(s1+1) == '[') {
1316 } else if (*s1 == '-') { /* remember to add some error checking to all this! */
1319 for (s3++; s3 <= s4; s3++) {
1327 *s2 = 0; /* null terminate the exploded range */
1328 /* sort the characters */
1330 specif = strlen(buf);
1331 qsort(buf, specif, 1, compare_char);
1341 if (*s1 == 'n') /* make sure n,x,z patterns are canonicalized to N,X,Z */
1343 else if (*s1 == 'x')
1345 else if (*s1 == 'z')
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 */
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 */
1366 m1 = m2; /* while m0 stays the same */
1370 m1 = add_pattern_node(con, m1, buf, pattern, already,specif, m0); /* m1 is the node just added */
1371 m0 = &m1->next_char;
1381 s1++; /* advance to next char */
1386 static void create_match_char_tree(struct ast_context *con)
1388 struct ast_hashtab_iter *t1;
1389 struct ast_exten *e1;
1391 int biggest_bucket, resizes, numobjs, numbucks;
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);
1398 t1 = ast_hashtab_start_traversal(con->root_table);
1399 while( (e1 = ast_hashtab_next(t1)) ) {
1401 add_exten_to_pattern_tree(con, e1, 0);
1403 ast_log(LOG_ERROR,"Attempt to create extension with no extension name.\n");
1405 ast_hashtab_end_traversal(t1);
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! */
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;
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;
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);
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
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)
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.
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.
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 ?
1460 * \brief helper functions to sort extensions and patterns in the desired way,
1461 * so that more specific patterns appear first.
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.
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.
1482 static int ext_cmp1(const char **p)
1485 int c, cmin = 0xff, count = 0;
1488 /* load, sign extend and advance pointer until we find
1489 * a valid character.
1491 while ( (c = *(*p)++) && (c == ' ' || c == '-') )
1492 ; /* ignore some characters */
1494 /* always return unless we have a set of chars */
1495 switch (toupper(c)) {
1496 default: /* ordinary character */
1497 return 0x0000 | (c & 0xff);
1499 case 'N': /* 2..9 */
1500 return 0x0700 | '2' ;
1502 case 'X': /* 0..9 */
1503 return 0x0900 | '0';
1505 case 'Z': /* 1..9 */
1506 return 0x0800 | '1';
1508 case '.': /* wildcard */
1511 case '!': /* earlymatch */
1512 return 0x20000; /* less specific than NULL */
1514 case '\0': /* empty string */
1518 case '[': /* pattern */
1521 /* locate end of set */
1522 end = strchr(*p, ']');
1525 ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
1526 return 0x40000; /* XXX make this entry go last... */
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 */
1540 for (; c1 <= c2; c1++) {
1541 uint32_t mask = 1 << (c1 % 32);
1542 if ( (chars[ c1 / 32 ] & mask) == 0)
1544 chars[ c1 / 32 ] |= mask;
1548 return count == 0 ? 0x30000 : (count | cmin);
1552 * \brief the full routine to compare extensions in rules.
1554 static int ext_cmp(const char *a, const char *b)
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.
1563 return (b[0] == '_') ? -1 : strcmp(a, b);
1565 /* Now we know a is a pattern; if b is not, a comes first */
1568 #if 0 /* old mode for ext matching */
1569 return strcmp(a, b);
1571 /* ok we need full pattern sorting routine */
1572 while (!ret && a && b)
1573 ret = ext_cmp1(&a) - ext_cmp1(&b);
1577 return (ret > 0) ? 1 : -1;
1580 int ast_extension_cmp(const char *a, const char *b)
1582 return ext_cmp(a, b);
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.
1597 static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
1599 mode &= E_MATCH_MASK; /* only consider the relevant bits */
1601 #ifdef NEED_DEBUG_HERE
1602 ast_log(LOG_NOTICE,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern, data, (int)mode);
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");
1612 if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
1613 int ld = strlen(data), lp = strlen(pattern);
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");
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);
1626 return !strcmp(pattern, data); /* 1 on match, 0 on fail */
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);
1632 return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
1634 #ifdef NEED_DEBUG_HERE
1635 ast_log(LOG_NOTICE,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld, pattern, data);
1640 pattern++; /* skip leading _ */
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.
1645 while (*data && *pattern && *pattern != '/') {
1648 if (*data == '-') { /* skip '-' in data (just a separator) */
1652 switch (toupper(*pattern)) {
1653 case '[': /* a range */
1654 end = strchr(pattern+1, ']'); /* XXX should deal with escapes ? */
1656 ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
1657 return 0; /* unconditional failure */
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 */
1664 pattern += 2; /* skip a total of 3 chars */
1667 } else if (*data == pattern[0])
1668 break; /* match found */
1670 if (pattern == end) {
1671 #ifdef NEED_DEBUG_HERE
1672 ast_log(LOG_NOTICE,"return (0) when pattern==end\n");
1676 pattern = end; /* skip and continue */
1679 if (*data < '2' || *data > '9') {
1680 #ifdef NEED_DEBUG_HERE
1681 ast_log(LOG_NOTICE,"return (0) N is matched\n");
1687 if (*data < '0' || *data > '9') {
1688 #ifdef NEED_DEBUG_HERE
1689 ast_log(LOG_NOTICE,"return (0) X is matched\n");
1695 if (*data < '1' || *data > '9') {
1696 #ifdef NEED_DEBUG_HERE
1697 ast_log(LOG_NOTICE,"return (0) Z is matched\n");
1702 case '.': /* Must match, even with more digits */
1703 #ifdef NEED_DEBUG_HERE
1704 ast_log(LOG_NOTICE,"return (1) when '.' is matched\n");
1707 case '!': /* Early match */
1708 #ifdef NEED_DEBUG_HERE
1709 ast_log(LOG_NOTICE,"return (2) when '!' is matched\n");
1713 case '-': /* Ignore these in patterns */
1714 data--; /* compensate the final data++ */
1717 if (*data != *pattern) {
1718 #ifdef NEED_DEBUG_HERE
1719 ast_log(LOG_NOTICE,"return (0) when *data(%c) != *pattern(%c)\n", *data, *pattern);
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");
1736 * match so far, but ran off the end of the data.
1737 * Depending on what is next, determine match or not.
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);
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");
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);
1753 return (mode == E_MATCH) ? 0 : 1; /* this is a failure for E_MATCH */
1758 * Wrapper around _extension_match_core() to do performance measurement
1759 * using the profiling code.
1761 static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
1764 static int prof_id = -2; /* marker for 'unallocated' id */
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);
1773 int ast_extension_match(const char *pattern, const char *data)
1775 return extension_match_core(pattern, data, E_MATCH);
1778 int ast_extension_close(const char *pattern, const char *data, int needmore)
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);
1785 struct fake_context /* this struct is purely for matching in the hashtab */
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;
1796 AST_LIST_HEAD_NOLOCK(, ast_sw) alts;
1797 ast_mutex_t macrolock;
1801 struct ast_context *ast_context_find(const char *name)
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);
1810 while ( (tmp = ast_walk_contexts(tmp)) ) {
1811 if (!name || !strcasecmp(name, tmp->name))
1815 ast_unlock_contexts();
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
1825 static int matchcid(const char *cidpattern, const char *callerid)
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 */
1830 if (ast_strlen_zero(callerid))
1831 return ast_strlen_zero(cidpattern) ? 1 : 0;
1833 return ast_extension_match(cidpattern, callerid);
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)
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;
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);
1856 if (ast_strlen_zero(exten))
1859 /* Initialize status if appropriate */
1860 if (q->stacklen == 0) {
1861 q->status = STATUS_NO_CONTEXT;
1864 q->foundcontext = NULL;
1865 } else if (q->stacklen >= AST_PBX_MAX_STACK) {
1866 ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
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))
1876 if (bypass) /* bypass means we only look there */
1878 else { /* look in contexts */
1879 struct fake_context item;
1880 strncpy(item.name,context,256);
1881 tmp = ast_hashtab_lookup(contexts_table,&item);
1884 while ((tmp = ast_walk_contexts(tmp)) ) {
1885 if (!strcmp(tmp->name, context))
1894 if (q->status < STATUS_NO_EXTENSION)
1895 q->status = STATUS_NO_EXTENSION;
1897 /* Do a search for matching extension */
1900 score.total_specificity = 0;
1902 score.total_length = 0;
1903 if (!tmp->pattern_tree && tmp->root_table)
1905 create_match_char_tree(tmp);
1907 ast_log(LOG_DEBUG,"Tree Created in context %s:\n", context);
1908 log_match_char_tree(tmp->pattern_tree," ");
1912 ast_log(LOG_NOTICE,"The Trie we are searching in:\n");
1913 log_match_char_tree(tmp->pattern_tree, ":: ");
1917 if (!ast_strlen_zero(overrideswitch)) {
1918 char *osw = ast_strdupa(overrideswitch), *name;
1919 struct ast_switch *asw;
1920 ast_switch_f *aswf = NULL;
1924 name = strsep(&osw, "/");
1925 asw = pbx_findswitch(name);
1928 ast_log(LOG_WARNING, "No such switch '%s'\n", name);
1932 if (osw && strchr(osw, '$')) {
1936 if (eval && !(tmpdata = ast_str_thread_get(&switch_data, 512))) {
1937 ast_log(LOG_WARNING, "Can't evaluate overrideswitch?!");
1940 /* Substitute variables now */
1941 pbx_substitute_variables_helper(chan, osw, tmpdata->str, tmpdata->len);
1942 datap = tmpdata->str;
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 */
1958 ast_autoservice_start(chan);
1960 res = aswf(chan, context, exten, priority, callerid, datap);
1962 ast_autoservice_stop(chan);
1965 if (res) { /* Got a match */
1968 q->foundcontext = context;
1969 /* XXX keep status = STATUS_NO_CONTEXT ? */
1975 if (extenpatternmatchnew) {
1976 new_find_extension(exten, &score, tmp->pattern_tree, 0, 0, callerid, label, action);
1977 eroot = score.exten;
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).
1983 #ifdef NEED_DEBUG_HERE
1984 ast_log(LOG_NOTICE,"Returning MATCHMORE NULL with exclamation point.\n");
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);
1994 return score.canmatch_exten;
1997 if ((action == E_MATCHMORE || action == E_CANMATCH) && eroot) {
1999 struct ast_exten *z = trie_find_next_match(score.node);
2001 #ifdef NEED_DEBUG_HERE
2002 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z->exten);
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);
2009 return score.canmatch_exten;
2011 #ifdef NEED_DEBUG_HERE
2012 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten NULL\n");
2018 #ifdef NEED_DEBUG_HERE
2019 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE NULL (no next_match)\n");
2021 return NULL; /* according to the code, complete matches are null matches in MATCHMORE mode */
2025 /* found entry, now look for the right priority */
2026 if (q->status < STATUS_NO_PRIORITY)
2027 q->status = STATUS_NO_PRIORITY;
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);
2034 e = ast_hashtab_lookup(eroot->peer_table, &pattern);
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);
2045 } else { /* the old/current default exten pattern match algorithm */
2047 /* scan the list trying to match extension and CID */
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 */
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).
2061 /* found entry, now look for the right priority */
2062 if (q->status < STATUS_NO_PRIORITY)
2063 q->status = STATUS_NO_PRIORITY;
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);
2070 e = ast_hashtab_lookup(eroot->peer_table, &pattern);
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 */
2085 if (e) { /* found a valid match */
2086 q->status = STATUS_SUCCESS;
2087 q->foundcontext = context;
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;
2101 ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
2104 /* Substitute variables now */
2107 if (!(tmpdata = ast_str_thread_get(&switch_data, 512))) {
2108 ast_log(LOG_WARNING, "Can't evaluate switch?!");
2111 pbx_substitute_variables_helper(chan, sw->data, tmpdata->str, tmpdata->len);
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 */
2121 datap = sw->eval ? tmpdata->str : sw->data;
2126 ast_autoservice_start(chan);
2127 res = aswf(chan, context, exten, priority, callerid, datap);
2129 ast_autoservice_stop(chan);
2131 if (res) { /* Got a match */
2134 q->foundcontext = context;
2135 /* XXX keep status = STATUS_NO_CONTEXT ? */
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);
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)
2161 static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
2168 for (; *var; var++) {
2172 } else if (*var == ')') {
2174 } else if (*var == ':' && parens == 0) {
2176 sscanf(var, "%d:%d", offset, length);
2177 return 1; /* offset:length valid */
2184 *\brief takes a substring. It is ok to call with value == workspace.
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.
2191 * \param workspace_len
2192 * Always return a copy in workspace.
2194 static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
2196 char *ret = workspace;
2197 int lr; /* length of the input string after the copy */
2199 ast_copy_string(workspace, value, workspace_len); /* always make a copy */
2201 lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
2203 /* Quick check if no need to do anything */
2204 if (offset == 0 && length >= lr) /* take the whole string */
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 */
2213 /* too large offset result in empty string so we know what to return */
2215 return ret + lr; /* the final '\0' */
2217 ret += offset; /* move to the start position */
2218 if (length >= 0 && length < lr - offset) /* truncate if necessary */
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';
2230 /*! \brief Support for Asterisk built-in variables in the dialplan
2233 - \ref AstVar Channel variables
2234 - \ref AstCauses The HANGUPCAUSE variable
2236 void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
2238 const char not_found = '\0';
2240 const char *s; /* the result */
2242 int i, need_substring;
2243 struct varshead *places[2] = { headp, &globals }; /* list of places where we may look */
2246 ast_channel_lock(c);
2247 places[0] = &c->varshead;
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'
2254 tmpvar = ast_strdupa(var); /* parse_variable_name modifies the string */
2255 need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);
2258 * Look first into predefined variables, then into variable lists.
2259 * Variable 's' points to the result, according to the following rules:
2260 * s == ¬_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 != ¬_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.
2272 s = ¬_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);
2280 } else if (!strcmp(var + 7, "ANI2")) { /* CALLINGANI2 */
2281 snprintf(workspace, workspacelen, "%d", c->cid.cid_ani2);
2283 } else if (!strcmp(var + 7, "TON")) { /* CALLINGTON */
2284 snprintf(workspace, workspacelen, "%d", c->cid.cid_ton);
2286 } else if (!strcmp(var + 7, "TNS")) { /* CALLINGTNS */
2287 snprintf(workspace, workspacelen, "%d", c->cid.cid_tns);
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")) {
2297 } else if (!strcmp(var, "CONTEXT")) {
2299 } else if (!strcmp(var, "PRIORITY")) {
2300 snprintf(workspace, workspacelen, "%d", c->priority);
2302 } else if (!strcmp(var, "CHANNEL")) {
2304 } else if (!strcmp(var, "UNIQUEID")) {
2306 } else if (!strcmp(var, "HANGUPCAUSE")) {
2307 snprintf(workspace, workspacelen, "%d", c->hangupcause);
2311 if (s == ¬_found) { /* look for more */
2312 if (!strcmp(var, "EPOCH")) {
2313 snprintf(workspace, workspacelen, "%u",(int)time(NULL));
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);
2322 /* if not found, look into chanvars or global vars */
2323 for (i = 0; s == ¬_found && i < (sizeof(places) / sizeof(places[0])); i++) {
2324 struct ast_var_t *variables;
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);
2335 if (places[i] == &globals)
2336 ast_rwlock_unlock(&globalslock);
2338 if (s == ¬_found || s == NULL)
2342 ast_copy_string(workspace, s, workspacelen);
2345 *ret = substring(*ret, offset, length, workspace, workspacelen);
2349 ast_channel_unlock(c);
2352 static void exception_store_free(void *data)
2354 struct pbx_exception *exception = data;
2355 ast_string_field_free_memory(exception);
2356 ast_free(exception);
2359 static struct ast_datastore_info exception_store_info = {
2360 .type = "EXCEPTION",
2361 .destroy = exception_store_free,
2364 int pbx_builtin_raise_exception(struct ast_channel *chan, void *vreason)
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;
2371 ds = ast_channel_datastore_alloc(&exception_store_info, NULL);
2374 exception = ast_calloc(1, sizeof(struct pbx_exception));
2376 ast_channel_datastore_free(ds);
2379 if (ast_string_field_init(exception, 128)) {
2380 ast_free(exception);
2381 ast_channel_datastore_free(ds);
2384 ds->data = exception;
2385 ast_channel_datastore_add(chan, ds);
2387 exception = ds->data;
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);
2397 static int acf_exception_read(struct ast_channel *chan, const char *name, char *data, char *buf, size_t buflen)
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)
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);
2417 static struct ast_custom_function exception_function = {
2418 .name = "EXCEPTION",
2419 .synopsis = "Retrieve the details of the current dialplan exception",
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,
2431 static char *handle_show_functions(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
2433 struct ast_custom_function *acf;
2439 e->command = "core show functions [like]";
2441 "Usage: core show functions [like <text>]\n"
2442 " List builtin functions, optionally only those matching a given string\n";
2448 if (a->argc == 5 && (!strcmp(a->argv[3], "like")) ) {
2450 } else if (a->argc != 3) {
2451 return CLI_SHOWUSAGE;
2454 ast_cli(a->fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
2456 AST_RWLIST_RDLOCK(&acf_root);
2457 AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
2458 if (!like || strstr(acf->name, a->argv[4])) {
2460 ast_cli(a->fd, "%-20.20s %-35.35s %s\n", acf->name, acf->syntax, acf->synopsis);
2463 AST_RWLIST_UNLOCK(&acf_root);
2465 ast_cli(a->fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
2470 static char *handle_show_function(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
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;
2484 e->command = "core show function";
2486 "Usage: core show function <function>\n"
2487 " Describe a particular dialplan function.\n";
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);
2499 AST_RWLIST_UNLOCK(&acf_root);
2505 return CLI_SHOWUSAGE;
2507 if (!(acf = ast_custom_function_find(a->argv[3]))) {
2508 ast_cli(a->fd, "No function by that name registered.\n");
2514 synopsis_size = strlen(acf->synopsis) + 23;
2516 synopsis_size = strlen("Not available") + 23;
2517 synopsis = alloca(synopsis_size);
2520 description_size = strlen(acf->desc) + 23;
2522 description_size = strlen("Not available") + 23;
2523 description = alloca(description_size);
2526 syntax_size = strlen(acf->syntax) + 23;
2528 syntax_size = strlen("Not available") + 23;
2529 syntax = alloca(syntax_size);
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);
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);
2546 ast_cli(a->fd,"%s%s%s\n\n%s%s\n\n%s%s\n", infotitle, stxtitle, syntax, syntitle, synopsis, destitle, description);
2551 struct ast_custom_function *ast_custom_function_find(const char *name)
2553 struct ast_custom_function *acf = NULL;
2555 AST_RWLIST_RDLOCK(&acf_root);
2556 AST_RWLIST_TRAVERSE(&acf_root, acf, acflist) {
2557 if (!strcmp(name, acf->name))
2560 AST_RWLIST_UNLOCK(&acf_root);
2565 int ast_custom_function_unregister(struct ast_custom_function *acf)
2567 struct ast_custom_function *cur;
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);
2577 return cur ? 0 : -1;
2580 int __ast_custom_function_register(struct ast_custom_function *acf, struct ast_module *mod)
2582 struct ast_custom_function *cur;
2590 AST_RWLIST_WRLOCK(&acf_root);
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);
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);
2607 AST_RWLIST_TRAVERSE_SAFE_END;
2609 AST_RWLIST_INSERT_TAIL(&acf_root, acf, acflist);
2611 AST_RWLIST_UNLOCK(&acf_root);
2613 ast_verb(2, "Registered custom function '%s'\n", term_color(tmps, acf->name, COLOR_BRCYAN, 0, sizeof(tmps)));
2618 /*! \brief return a pointer to the arguments of the function,
2619 * and terminates the function name with '\\0'
2621 static char *func_args(char *function)
2623 char *args = strchr(function, '(');
2626 ast_log(LOG_WARNING, "Function doesn't contain parentheses. Assuming null argument.\n");
2630 if ((p = strrchr(args, ')')) )
2633 ast_log(LOG_WARNING, "Can't find trailing parenthesis?\n");
2638 int ast_func_read(struct ast_channel *chan, const char *function, char *workspace, size_t len)
2640 char *copy = ast_strdupa(function);
2641 char *args = func_args(copy);
2642 struct ast_custom_function *acfptr = ast_custom_function_find(copy);
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);
2650 struct ast_module_user *u = NULL;
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);
2661 int ast_func_write(struct ast_channel *chan, const char *function, const char *value)
2663 char *copy = ast_strdupa(function);
2664 char *args = func_args(copy);
2665 struct ast_custom_function *acfptr = ast_custom_function_find(copy);
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);
2673 struct ast_module_user *u = NULL;
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);
2685 static void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count)
2687 /* Substitutes variables into cp2, based on string cp1, cp2 NO LONGER NEEDS TO BE ZEROED OUT!!!! */
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;
2695 int pos, brackets, needsub, len;
2697 *cp2 = 0; /* just in case nothing ends up there */
2699 while (!ast_strlen_zero(whereweare) && count) {
2700 /* Assume we're copying the whole remaining string */
2701 pos = strlen(whereweare);
2704 nextthing = strchr(whereweare, '$');
2706 switch (nextthing[1]) {
2708 nextvar = nextthing;
2709 pos = nextvar - whereweare;
2712 nextexp = nextthing;
2713 pos = nextexp - whereweare;
2721 /* Can't copy more than 'count' bytes */
2725 /* Copy that many bytes */
2726 memcpy(cp2, whereweare, pos);
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
2738 vars = vare = nextvar + 2;
2742 /* Find the end of it */
2743 while (brackets && *vare) {
2744 if ((vare[0] == '$') && (vare[1] == '{')) {
2746 } else if (vare[0] == '{') {
2748 } else if (vare[0] == '}') {
2750 } else if ((vare[0] == '$') && (vare[1] == '['))
2755 ast_log(LOG_WARNING, "Error in extension logic (missing '}')\n");
2756 len = vare - vars - 1;
2758 /* Skip totally over variable string */
2759 whereweare += (len + 3);
2762 var = alloca(VAR_BUF_SIZE);
2764 /* Store variable name (and truncate) */
2765 ast_copy_string(var, vars, len + 1);
2767 /* Substitute if necessary */
2770 ltmp = alloca(VAR_BUF_SIZE);
2772 pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
2779 workspace = alloca(VAR_BUF_SIZE);
2781 workspace[0] = '\0';
2783 parse_variable_name(vars, &offset, &offset2, &isfunction);
2785 /* Evaluate function */
2787 cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE) ? NULL : workspace;
2789 struct varshead old;
2790 struct ast_channel *c = ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/%p", vars);
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);
2799 ast_log(LOG_ERROR, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
2801 ast_debug(2, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
2803 /* Retrieve variable value */
2804 pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp);
2807 cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE);
2809 length = strlen(cp4);
2812 memcpy(cp2, cp4, length);
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
2821 vars = vare = nextexp + 2;
2825 /* Find the end of it */
2826 while (brackets && *vare) {
2827 if ((vare[0] == '$') && (vare[1] == '[')) {
2831 } else if (vare[0] == '[') {
2833 } else if (vare[0] == ']') {
2835 } else if ((vare[0] == '$') && (vare[1] == '{')) {
2842 ast_log(LOG_WARNING, "Error in extension logic (missing ']')\n");
2843 len = vare - vars - 1;
2845 /* Skip totally over expression */
2846 whereweare += (len + 3);
2849 var = alloca(VAR_BUF_SIZE);
2851 /* Store variable name (and truncate) */
2852 ast_copy_string(var, vars, len + 1);
2854 /* Substitute if necessary */
2857 ltmp = alloca(VAR_BUF_SIZE);
2859 pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
2865 length = ast_expr(vars, cp2, count, c);
2868 ast_debug(1, "Expression result is '%s'\n", cp2);
2877 void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
2879 pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count);
2882 void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count)
2884 pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count);
2887 static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e)
2891 /* Nothing more to do */
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);
2901 pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1);
2904 /*! \brief report AGI state for channel */
2905 const char *ast_agi_state(struct ast_channel *chan)
2907 if (ast_test_flag(chan, AST_FLAG_AGI))
2909 if (ast_test_flag(chan, AST_FLAG_FASTAGI))
2911 if (ast_test_flag(chan, AST_FLAG_ASYNCAGI))
2917 * \brief The return value depends on the action:
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,
2925 * \retval 0 on success.
2926 * \retval -1 on failure.
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.
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)
2938 struct ast_exten *e;
2939 struct ast_app *app;
2941 struct pbx_find_info q = { .stacklen = 0 }; /* the rest is reset in pbx_find_extension */
2942 char passdata[EXT_DATA_SIZE];
2944 int matching_action = (action == E_MATCH || action == E_CANMATCH || action == E_MATCHMORE);
2946 ast_rdlock_contexts();
2950 e = pbx_find_extension(c, con, &q, context, exten, priority, label, callerid, action);
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 */
2959 ast_unlock_contexts();
2960 return res; /* the priority we were looking for */
2961 } else { /* spawn */
2963 e->cached_app = pbx_findapp(e->app);
2964 app = e->cached_app;
2965 ast_unlock_contexts();
2967 ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
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);
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)),
2989 manager_event(EVENT_FLAG_DIALPLAN, "Newexten",
2994 "Application: %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 */
3001 } else if (q.swo) { /* not found here, but in another switch */
3002 ast_unlock_contexts();
3003 if (matching_action) {
3007 ast_log(LOG_WARNING, "No execution engine for switch %s\n", q.swo->name);
3010 return q.swo->exec(c, q.foundcontext ? q.foundcontext : context, exten, priority, callerid, q.data);