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/event.h"
63 #include "asterisk/hashtab.h"
64 #include "asterisk/module.h"
65 #include "asterisk/indications.h"
66 #include "asterisk/taskprocessor.h"
67 #include "asterisk/xmldoc.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 <application name="Answer" language="en_US">
93 Answer a channel if ringing.
96 <parameter name="delay">
97 <para>Asterisk will wait this number of milliseconds before returning to
98 the dialplan after answering the call.</para>
102 <para>If the call has not been answered, this application will
103 answer it. Otherwise, it has no effect on the call.</para>
106 <ref type="application">Hangup</ref>
109 <application name="BackGround" language="en_US">
111 Play an audio file while waiting for digits of an extension to go to.
114 <parameter name="filenames" required="true" argsep="&">
115 <argument name="filename1" required="true" />
116 <argument name="filename2" multiple="true" />
118 <parameter name="options">
121 <para>Causes the playback of the message to be skipped
122 if the channel is not in the <literal>up</literal> state (i.e. it
123 hasn't been answered yet). If this happens, the
124 application will return immediately.</para>
127 <para>Don't answer the channel before playing the files.</para>
130 <para>Only break if a digit hit matches a one digit
131 extension in the destination context.</para>
135 <parameter name="langoverride">
136 <para>Explicitly specifies which language to attempt to use for the requested sound files.</para>
138 <parameter name="context">
139 <para>This is the dialplan context that this application will use when exiting
140 to a dialed extension.</para>
144 <para>This application will play the given list of files <emphasis>(do not put extension)</emphasis>
145 while waiting for an extension to be dialed by the calling channel. To continue waiting
146 for digits after this application has finished playing files, the <literal>WaitExten</literal>
147 application should be used.</para>
148 <para>If one of the requested sound files does not exist, call processing will be terminated.</para>
149 <para>This application sets the following channel variable upon completion:</para>
151 <variable name="BACKGROUNDSTATUS">
152 <para>The status of the background attempt as a text string.</para>
153 <value name="SUCCESS" />
154 <value name="FAILED" />
159 <ref type="application">ControlPlayback</ref>
160 <ref type="application">WaitExten</ref>
161 <ref type="application">BackgroundDetect</ref>
162 <ref type="function">TIMEOUT</ref>
165 <application name="Busy" language="en_US">
167 Indicate the Busy condition.
170 <parameter name="timeout">
171 <para>If specified, the calling channel will be hung up after the specified number of seconds.
172 Otherwise, this application will wait until the calling channel hangs up.</para>
176 <para>This application will indicate the busy condition to the calling channel.</para>
179 <ref type="application">Congestion</ref>
180 <ref type="application">Progess</ref>
181 <ref type="application">Playtones</ref>
182 <ref type="application">Hangup</ref>
185 <application name="Congestion" language="en_US">
187 Indicate the Congestion condition.
190 <parameter name="timeout">
191 <para>If specified, the calling channel will be hung up after the specified number of seconds.
192 Otherwise, this application will wait until the calling channel hangs up.</para>
196 <para>This application will indicate the congestion condition to the calling channel.</para>
199 <ref type="application">Busy</ref>
200 <ref type="application">Progess</ref>
201 <ref type="application">Playtones</ref>
202 <ref type="application">Hangup</ref>
205 <application name="ExecIfTime" language="en_US">
207 Conditional application execution based on the current time.
210 <parameter name="day_condition" required="true">
211 <argument name="times" required="true" />
212 <argument name="weekdays" required="true" />
213 <argument name="mdays" required="true" />
214 <argument name="months" required="true" />
215 <argument name="timezone" required="false" />
217 <parameter name="appname" required="true" hasparams="optional">
218 <argument name="appargs" required="true" />
222 <para>This application will execute the specified dialplan application, with optional
223 arguments, if the current time matches the given time specification.</para>
226 <ref type="application">Exec</ref>
227 <ref type="application">TryExec</ref>
230 <application name="Goto" language="en_US">
232 Jump to a particular priority, extension, or context.
235 <parameter name="context" />
236 <parameter name="extensions" />
237 <parameter name="priority" required="true" />
240 <para>This application will set the current context, extension, and priority in the channel structure.
241 After it completes, the pbx engine will continue dialplan execution at the specified location.
242 If no specific <replaceable>extension</replaceable>, or <replaceable>extension</replaceable> and
243 <replaceable>context</replaceable>, are specified, then this application will
244 just set the specified <replaceable>priority</replaceable> of the current extension.</para>
245 <para>At least a <replaceable>priority</replaceable> is required as an argument, or the goto will
246 return a <literal>-1</literal>, and the channel and call will be terminated.</para>
247 <para>If the location that is put into the channel information is bogus, and asterisk cannot
248 find that location in the dialplan, then the execution engine will try to find and execute the code in
249 the <literal>i</literal> (invalid) extension in the current context. If that does not exist, it will try to execute the
250 <literal>h</literal> extension. If either or neither the <literal>h</literal> or <literal>i</literal> extensions
251 have been defined, the channel is hung up, and the execution of instructions on the channel is terminated.
252 What this means is that, for example, you specify a context that does not exist, then
253 it will not be possible to find the <literal>h</literal> or <literal>i</literal> extensions,
254 and the call will terminate!</para>
257 <ref type="application">GotoIf</ref>
258 <ref type="application">GotoIfTime</ref>
259 <ref type="application">Gosub</ref>
260 <ref type="application">Macro</ref>
263 <application name="GotoIf" language="en_US">
268 <parameter name="condition" required="true" />
269 <parameter name="destination" required="true" argsep=":">
270 <argument name="labeliftrue">
271 <para>Continue at <replaceable>labeliftrue</replaceable> if the condition is true.</para>
273 <argument name="labeliffalse">
274 <para>Continue at <replaceable>labeliffalse</replaceable> if the condition is false.</para>
279 <para>This application will set the current context, extension, and priority in the channel structure
280 based on the evaluation of the given condition. After this application completes, the
281 pbx engine will continue dialplan execution at the specified location in the dialplan.
282 The labels are specified with the same syntax as used within the Goto application.
283 If the label chosen by the condition is omitted, no jump is performed, and the execution passes to the
284 next instruction. If the target location is bogus, and does not exist, the execution engine will try
285 to find and execute the code in the <literal>i</literal> (invalid) extension in the current context.
286 If that does not exist, it will try to execute the <literal>h</literal> extension.
287 If either or neither the <literal>h</literal> or <literal>i</literal> extensions have been defined,
288 the channel is hung up, and the execution of instructions on the channel is terminated.
289 Remember that this command can set the current context, and if the context specified
290 does not exist, then it will not be able to find any 'h' or 'i' extensions there, and
291 the channel and call will both be terminated!.</para>
294 <ref type="application">Goto</ref>
295 <ref type="application">GotoIfTime</ref>
296 <ref type="application">GosubIf</ref>
297 <ref type="application">MacroIf</ref>
300 <application name="GotoIfTime" language="en_US">
302 Conditional Goto based on the current time.
305 <parameter name="condition" required="true">
306 <argument name="times" required="true" />
307 <argument name="weekdays" required="true" />
308 <argument name="mdays" required="true" />
309 <argument name="months" required="true" />
310 <argument name="timezone" required="false" />
312 <parameter name="destination" required="true" argsep=":">
313 <argument name="labeliftrue" />
314 <argument name="labeliffalse" />
318 <para>This application will set the context, extension, and priority in the channel structure
319 based on the evaluation of the given time specification. After this application completes,
320 the pbx engine will continue dialplan execution at the specified location in the dialplan.
321 If the current time is within the given time specification, the channel will continue at
322 <replaceable>labeliftrue</replaceable>. Otherwise the channel will continue at <replaceable>labeliffalse</replaceable>.
323 If the label chosen by the condition is omitted, no jump is performed, and execution passes to the next
324 instruction. If the target jump location is bogus, the same actions would be taken as for <literal>Goto</literal>.
325 Further information on the time specification can be found in examples
326 illustrating how to do time-based context includes in the dialplan.</para>
329 <ref type="application">GotoIf</ref>
330 <ref type="function">IFTIME</ref>
333 <application name="ImportVar" language="en_US">
335 Import a variable from a channel into a new variable.
338 <parameter name="newvar" required="true" />
339 <parameter name="vardata" required="true">
340 <argument name="channelname" required="true" />
341 <argument name="variable" required="true" />
345 <para>This application imports a <replaceable>variable</replaceable> from the specified
346 <replaceable>channel</replaceable> (as opposed to the current one) and stores it as a variable
347 (<replaceable>newvar</replaceable>) in the current channel (the channel that is calling this
348 application). Variables created by this application have the same inheritance properties as those
349 created with the <literal>Set</literal> application.</para>
352 <ref type="application">Set</ref>
355 <application name="Hangup" language="en_US">
357 Hang up the calling channel.
360 <parameter name="causecode">
361 <para>If a <replaceable>causecode</replaceable> is given the channel's
362 hangup cause will be set to the given value.</para>
366 <para>This application will hang up the calling channel.</para>
369 <ref type="application">Answer</ref>
370 <ref type="application">Busy</ref>
371 <ref type="application">Congestion</ref>
374 <application name="Incomplete" language="en_US">
376 Returns AST_PBX_INCOMPLETE value.
380 <para>If specified, then Incomplete will not attempt to answer the channel first.</para>
381 <note><para>Most channel types need to be in Answer state in order to receive DTMF.</para></note>
385 <para>Signals the PBX routines that the previous matched extension is incomplete
386 and that further input should be allowed before matching can be considered
387 to be complete. Can be used within a pattern match when certain criteria warrants
388 a longer match.</para>
391 <application name="NoOp" language="en_US">
393 Do Nothing (No Operation).
396 <parameter name="text">
397 <para>Any text provided can be viewed at the Asterisk CLI.</para>
401 <para>This application does nothing. However, it is useful for debugging purposes.</para>
402 <para>This method can be used to see the evaluations of variables or functions without having any effect.</para>
405 <ref type="application">Verbose</ref>
406 <ref type="application">Log</ref>
409 <application name="Proceeding" language="en_US">
415 <para>This application will request that a proceeding message be provided to the calling channel.</para>
418 <application name="Progress" language="en_US">
424 <para>This application will request that in-band progress information be provided to the calling channel.</para>
427 <ref type="application">Busy</ref>
428 <ref type="application">Congestion</ref>
429 <ref type="application">Ringing</ref>
430 <ref type="application">Playtones</ref>
433 <application name="RaiseException" language="en_US">
435 Handle an exceptional condition.
438 <parameter name="reason" required="true" />
441 <para>This application will jump to the <literal>e</literal> extension in the current context, setting the
442 dialplan function EXCEPTION(). If the <literal>e</literal> extension does not exist, the call will hangup.</para>
445 <ref type="function">Exception</ref>
448 <application name="ResetCDR" language="en_US">
450 Resets the Call Data Record.
453 <parameter name="options">
456 <para>Store the current CDR record before resetting it.</para>
459 <para>Store any stacked records.</para>
462 <para>Save CDR variables.</para>
465 <para>Enable CDR only (negate effects of NoCDR).</para>
471 <para>This application causes the Call Data Record to be reset.</para>
474 <ref type="application">ForkCDR</ref>
475 <ref type="application">NoCDR</ref>
478 <application name="Ringing" language="en_US">
480 Indicate ringing tone.
484 <para>This application will request that the channel indicate a ringing tone to the user.</para>
487 <ref type="application">Busy</ref>
488 <ref type="application">Congestion</ref>
489 <ref type="application">Progress</ref>
490 <ref type="application">Playtones</ref>
493 <application name="SayAlpha" language="en_US">
498 <parameter name="string" required="true" />
501 <para>This application will play the sounds that correspond to the letters of the
502 given <replaceable>string</replaceable>.</para>
505 <ref type="application">SayDigits</ref>
506 <ref type="application">SayNumber</ref>
507 <ref type="application">SayPhonetic</ref>
508 <ref type="function">CHANNEL</ref>
511 <application name="SayDigits" language="en_US">
516 <parameter name="digits" required="true" />
519 <para>This application will play the sounds that correspond to the digits of
520 the given number. This will use the language that is currently set for the channel.</para>
523 <ref type="application">SayAlpha</ref>
524 <ref type="application">SayNumber</ref>
525 <ref type="application">SayPhonetic</ref>
526 <ref type="function">CHANNEL</ref>
529 <application name="SayNumber" language="en_US">
534 <parameter name="digits" required="true" />
535 <parameter name="gender" />
538 <para>This application will play the sounds that correspond to the given <replaceable>digits</replaceable>.
539 Optionally, a <replaceable>gender</replaceable> may be specified. This will use the language that is currently
540 set for the channel. See the LANGUAGE() function for more information on setting the language for the channel.</para>
543 <ref type="application">SayAlpha</ref>
544 <ref type="application">SayDigits</ref>
545 <ref type="application">SayPhonetic</ref>
546 <ref type="function">CHANNEL</ref>
549 <application name="SayPhonetic" language="en_US">
554 <parameter name="string" required="true" />
557 <para>This application will play the sounds from the phonetic alphabet that correspond to the
558 letters in the given <replaceable>string</replaceable>.</para>
561 <ref type="application">SayAlpha</ref>
562 <ref type="application">SayDigits</ref>
563 <ref type="application">SayNumber</ref>
566 <application name="Set" language="en_US">
568 Set channel variable or function value.
571 <parameter name="name" required="true" />
572 <parameter name="value" required="true" />
575 <para>This function can be used to set the value of channel variables or dialplan functions.
576 When setting variables, if the variable name is prefixed with <literal>_</literal>,
577 the variable will be inherited into channels created from the current channel.
578 If the variable name is prefixed with <literal>__</literal>, the variable will be
579 inherited into channels created from the current channel and all children channels.</para>
580 <note><para>If (and only if), in <filename>/etc/asterisk/asterisk.conf</filename>, you have
581 a <literal>[compat]</literal> category, and you have <literal>app_set = 1.6</literal> under that,then
582 the behavior of this app changes, and does not strip surrounding quotes from the right hand side as
583 it did previously in 1.4. The <literal>app_set = 1.6</literal> is only inserted if <literal>make samples</literal>
584 is executed, or if users insert this by hand into the <filename>asterisk.conf</filename> file.
585 The advantages of not stripping out quoting, and not caring about the separator characters (comma and vertical bar)
586 were sufficient to make these changes in 1.6. Confusion about how many backslashes would be needed to properly
587 protect separators and quotes in various database access strings has been greatly
588 reduced by these changes.</para></note>
591 <ref type="application">MSet</ref>
592 <ref type="function">GLOBAL</ref>
593 <ref type="function">SET</ref>
594 <ref type="function">ENV</ref>
597 <application name="MSet" language="en_US">
599 Set channel variable(s) or function value(s).
602 <parameter name="set1" required="true" argsep="=">
603 <argument name="name1" required="true" />
604 <argument name="value1" required="true" />
606 <parameter name="set2" multiple="true" argsep="=">
607 <argument name="name2" required="true" />
608 <argument name="value2" required="true" />
612 <para>This function can be used to set the value of channel variables or dialplan functions.
613 When setting variables, if the variable name is prefixed with <literal>_</literal>,
614 the variable will be inherited into channels created from the current channel
615 If the variable name is prefixed with <literal>__</literal>, the variable will be
616 inherited into channels created from the current channel and all children channels.
617 MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus
618 prone to doing things that you may not expect. For example, it strips surrounding
619 double-quotes from the right-hand side (value). If you need to put a separator
620 character (comma or vert-bar), you will need to escape them by inserting a backslash
621 before them. Avoid its use if possible.</para>
624 <ref type="application">Set</ref>
627 <application name="SetAMAFlags" language="en_US">
632 <parameter name="flag" />
635 <para>This application will set the channel's AMA Flags for billing purposes.</para>
638 <ref type="function">CDR</ref>
641 <application name="Wait" language="en_US">
646 <parameter name="seconds" required="true">
647 <para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
648 application to wait for 1.5 seconds.</para>
652 <para>This application waits for a specified number of <replaceable>seconds</replaceable>.</para>
655 <application name="WaitExten" language="en_US">
657 Waits for an extension to be entered.
660 <parameter name="seconds">
661 <para>Can be passed with fractions of a second. For example, <literal>1.5</literal> will ask the
662 application to wait for 1.5 seconds.</para>
664 <parameter name="options">
667 <para>Provide music on hold to the caller while waiting for an extension.</para>
669 <para>Specify the class for music on hold.</para>
676 <para>This application waits for the user to enter a new extension for a specified number
677 of <replaceable>seconds</replaceable>.</para>
680 <ref type="application">Background</ref>
681 <ref type="function">TIMEOUT</ref>
684 <function name="EXCEPTION" language="en_US">
686 Retrieve the details of the current dialplan exception.
689 <parameter name="field" required="true">
690 <para>The following fields are available for retrieval:</para>
693 <para>INVALID, ERROR, RESPONSETIMEOUT, ABSOLUTETIMEOUT, or custom
694 value set by the RaiseException() application</para>
696 <enum name="context">
697 <para>The context executing when the exception occurred.</para>
700 <para>The extension executing when the exception occurred.</para>
702 <enum name="priority">
703 <para>The numeric priority executing when the exception occurred.</para>
709 <para>Retrieve the details (specified <replaceable>field</replaceable>) of the current dialplan exception.</para>
712 <ref type="application">RaiseException</ref>
718 #define EXT_DATA_SIZE 256
720 #define EXT_DATA_SIZE 8192
723 #define SWITCH_DATA_LENGTH 256
725 #define VAR_BUF_SIZE 4096
728 #define VAR_SOFTTRAN 2
729 #define VAR_HARDTRAN 3
731 #define BACKGROUND_SKIP (1 << 0)
732 #define BACKGROUND_NOANSWER (1 << 1)
733 #define BACKGROUND_MATCHEXTEN (1 << 2)
734 #define BACKGROUND_PLAYBACK (1 << 3)
736 AST_APP_OPTIONS(background_opts, {
737 AST_APP_OPTION('s', BACKGROUND_SKIP),
738 AST_APP_OPTION('n', BACKGROUND_NOANSWER),
739 AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
740 AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
743 #define WAITEXTEN_MOH (1 << 0)
744 #define WAITEXTEN_DIALTONE (1 << 1)
746 AST_APP_OPTIONS(waitexten_opts, {
747 AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 0),
748 AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE, 0),
754 static struct ast_taskprocessor *device_state_tps;
756 AST_THREADSTORAGE(switch_data);
757 AST_THREADSTORAGE(extensionstate_buf);
760 \brief ast_exten: An extension
761 The dialplan is saved as a linked list with each context
762 having it's own linked list of extensions - one item per
766 char *exten; /*!< Extension name */
767 int matchcid; /*!< Match caller id ? */
768 const char *cidmatch; /*!< Caller id to match for this extension */
769 int priority; /*!< Priority */
770 const char *label; /*!< Label */
771 struct ast_context *parent; /*!< The context this extension belongs to */
772 const char *app; /*!< Application to execute */
773 struct ast_app *cached_app; /*!< Cached location of application */
774 void *data; /*!< Data to use (arguments) */
775 void (*datad)(void *); /*!< Data destructor */
776 struct ast_exten *peer; /*!< Next higher priority with our extension */
777 struct ast_hashtab *peer_table; /*!< Priorities list in hashtab form -- only on the head of the peer list */
778 struct ast_hashtab *peer_label_table; /*!< labeled priorities in the peers -- only on the head of the peer list */
779 const char *registrar; /*!< Registrar */
780 struct ast_exten *next; /*!< Extension with a greater ID */
784 /*! \brief ast_include: include= support in extensions.conf */
787 const char *rname; /*!< Context to include */
788 const char *registrar; /*!< Registrar */
789 int hastime; /*!< If time construct exists */
790 struct ast_timing timing; /*!< time construct */
791 struct ast_include *next; /*!< Link them together */
795 /*! \brief ast_sw: Switch statement in extensions.conf */
798 const char *registrar; /*!< Registrar */
799 char *data; /*!< Data load */
801 AST_LIST_ENTRY(ast_sw) list;
805 /*! \brief ast_ignorepat: Ignore patterns in dial plan */
806 struct ast_ignorepat {
807 const char *registrar;
808 struct ast_ignorepat *next;
809 const char pattern[0];
812 /*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
815 int is_pattern; /* the pattern started with '_' */
816 int deleted; /* if this is set, then... don't return it */
817 char *x; /* the pattern itself-- matches a single char */
818 int specificity; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */
819 struct match_char *alt_char;
820 struct match_char *next_char;
821 struct ast_exten *exten; /* attached to last char of a pattern for exten */
824 struct scoreboard /* make sure all fields are 0 before calling new_find_extension */
826 int total_specificity;
828 char last_char; /* set to ! or . if they are the end of the pattern */
829 int canmatch; /* if the string to match was just too short */
830 struct match_char *node;
831 struct ast_exten *canmatch_exten;
832 struct ast_exten *exten;
835 /*! \brief ast_context: An extension context */
837 ast_rwlock_t lock; /*!< A lock to prevent multiple threads from clobbering the context */
838 struct ast_exten *root; /*!< The root of the list of extensions */
839 struct ast_hashtab *root_table; /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree */
840 struct match_char *pattern_tree; /*!< A tree to speed up extension pattern matching */
841 struct ast_context *next; /*!< Link them together */
842 struct ast_include *includes; /*!< Include other contexts */
843 struct ast_ignorepat *ignorepats; /*!< Patterns for which to continue playing dialtone */
844 char *registrar; /*!< Registrar -- make sure you malloc this, as the registrar may have to survive module unloads */
845 int refcount; /*!< each module that would have created this context should inc/dec this as appropriate */
846 AST_LIST_HEAD_NOLOCK(, ast_sw) alts; /*!< Alternative switches */
847 ast_mutex_t macrolock; /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
848 char name[0]; /*!< Name of the context */
851 /*! \brief ast_app: A registered application */
853 int (*execute)(struct ast_channel *chan, void *data);
854 AST_DECLARE_STRING_FIELDS(
855 AST_STRING_FIELD(synopsis); /*!< Synopsis text for 'show applications' */
856 AST_STRING_FIELD(description); /*!< Description (help text) for 'show application <name>' */
857 AST_STRING_FIELD(syntax); /*!< Syntax text for 'core show applications' */
858 AST_STRING_FIELD(arguments); /*!< Arguments description */
859 AST_STRING_FIELD(seealso); /*!< See also */
861 enum ast_doc_src docsrc;/*!< Where the documentation come from. */
862 AST_RWLIST_ENTRY(ast_app) list; /*!< Next app in list */
863 struct ast_module *module; /*!< Module this app belongs to */
864 char name[0]; /*!< Name of the application */
867 /*! \brief ast_state_cb: An extension state notify register item */
868 struct ast_state_cb {
871 ast_state_cb_type callback;
872 AST_LIST_ENTRY(ast_state_cb) entry;
875 /*! \brief Structure for dial plan hints
877 \note Hints are pointers from an extension in the dialplan to one or
878 more devices (tech/name)
879 - See \ref AstExtState
882 struct ast_exten *exten; /*!< Extension */
883 int laststate; /*!< Last known state */
884 AST_LIST_HEAD_NOLOCK(, ast_state_cb) callbacks; /*!< Callback list for this extension */
885 AST_RWLIST_ENTRY(ast_hint) list;/*!< Pointer to next hint in list */
888 static const struct cfextension_states {
890 const char * const text;
891 } extension_states[] = {
892 { AST_EXTENSION_NOT_INUSE, "Idle" },
893 { AST_EXTENSION_INUSE, "InUse" },
894 { AST_EXTENSION_BUSY, "Busy" },
895 { AST_EXTENSION_UNAVAILABLE, "Unavailable" },
896 { AST_EXTENSION_RINGING, "Ringing" },
897 { AST_EXTENSION_INUSE | AST_EXTENSION_RINGING, "InUse&Ringing" },
898 { AST_EXTENSION_ONHOLD, "Hold" },
899 { AST_EXTENSION_INUSE | AST_EXTENSION_ONHOLD, "InUse&Hold" }
903 AST_LIST_ENTRY(statechange) entry;
907 struct pbx_exception {
908 AST_DECLARE_STRING_FIELDS(
909 AST_STRING_FIELD(context); /*!< Context associated with this exception */
910 AST_STRING_FIELD(exten); /*!< Exten associated with this exception */
911 AST_STRING_FIELD(reason); /*!< The exception reason */
914 int priority; /*!< Priority associated with this exception */
917 static int pbx_builtin_answer(struct ast_channel *, void *);
918 static int pbx_builtin_goto(struct ast_channel *, void *);
919 static int pbx_builtin_hangup(struct ast_channel *, void *);
920 static int pbx_builtin_background(struct ast_channel *, void *);
921 static int pbx_builtin_wait(struct ast_channel *, void *);
922 static int pbx_builtin_waitexten(struct ast_channel *, void *);
923 static int pbx_builtin_incomplete(struct ast_channel *, void *);
924 static int pbx_builtin_resetcdr(struct ast_channel *, void *);
925 static int pbx_builtin_setamaflags(struct ast_channel *, void *);
926 static int pbx_builtin_ringing(struct ast_channel *, void *);
927 static int pbx_builtin_proceeding(struct ast_channel *, void *);
928 static int pbx_builtin_progress(struct ast_channel *, void *);
929 static int pbx_builtin_congestion(struct ast_channel *, void *);
930 static int pbx_builtin_busy(struct ast_channel *, void *);
931 static int pbx_builtin_noop(struct ast_channel *, void *);
932 static int pbx_builtin_gotoif(struct ast_channel *, void *);
933 static int pbx_builtin_gotoiftime(struct ast_channel *, void *);
934 static int pbx_builtin_execiftime(struct ast_channel *, void *);
935 static int pbx_builtin_saynumber(struct ast_channel *, void *);
936 static int pbx_builtin_saydigits(struct ast_channel *, void *);
937 static int pbx_builtin_saycharacters(struct ast_channel *, void *);
938 static int pbx_builtin_sayphonetic(struct ast_channel *, void *);
939 static int matchcid(const char *cidpattern, const char *callerid);
940 int pbx_builtin_setvar(struct ast_channel *, void *);
941 void log_match_char_tree(struct match_char *node, char *prefix); /* for use anywhere */
942 int pbx_builtin_setvar_multiple(struct ast_channel *, void *);
943 static int pbx_builtin_importvar(struct ast_channel *, void *);
944 static void set_ext_pri(struct ast_channel *c, const char *exten, int pri);
945 static void new_find_extension(const char *str, struct scoreboard *score,
946 struct match_char *tree, int length, int spec, const char *callerid,
947 const char *label, enum ext_match_t action);
948 static struct match_char *already_in_tree(struct match_char *current, char *pat);
949 static struct match_char *add_exten_to_pattern_tree(struct ast_context *con,
950 struct ast_exten *e1, int findonly);
951 static struct match_char *add_pattern_node(struct ast_context *con,
952 struct match_char *current, char *pattern, int is_pattern,
953 int already, int specificity, struct match_char **parent);
954 static void create_match_char_tree(struct ast_context *con);
955 static struct ast_exten *get_canmatch_exten(struct match_char *node);
956 static void destroy_pattern_tree(struct match_char *pattern_tree);
957 int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b);
958 static int hashtab_compare_extens(const void *ha_a, const void *ah_b);
959 static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b);
960 static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b);
961 unsigned int ast_hashtab_hash_contexts(const void *obj);
962 static unsigned int hashtab_hash_extens(const void *obj);
963 static unsigned int hashtab_hash_priority(const void *obj);
964 static unsigned int hashtab_hash_labels(const void *obj);
965 static void __ast_internal_context_destroy( struct ast_context *con);
967 /* a func for qsort to use to sort a char array */
968 static int compare_char(const void *a, const void *b)
974 else if ((*ac) == (*bc))
980 /* labels, contexts are case sensitive priority numbers are ints */
981 int ast_hashtab_compare_contexts(const void *ah_a, const void *ah_b)
983 const struct ast_context *ac = ah_a;
984 const struct ast_context *bc = ah_b;
985 if (!ac || !bc) /* safety valve, but it might prevent a crash you'd rather have happen */
987 /* assume context names are registered in a string table! */
988 return strcmp(ac->name, bc->name);
991 static int hashtab_compare_extens(const void *ah_a, const void *ah_b)
993 const struct ast_exten *ac = ah_a;
994 const struct ast_exten *bc = ah_b;
995 int x = strcmp(ac->exten, bc->exten);
996 if (x) { /* if exten names are diff, then return */
1000 /* but if they are the same, do the cidmatch values match? */
1001 if (ac->matchcid && bc->matchcid) {
1002 return strcmp(ac->cidmatch,bc->cidmatch);
1003 } else if (!ac->matchcid && !bc->matchcid) {
1004 return 0; /* if there's no matchcid on either side, then this is a match */
1006 return 1; /* if there's matchcid on one but not the other, they are different */
1010 static int hashtab_compare_exten_numbers(const void *ah_a, const void *ah_b)
1012 const struct ast_exten *ac = ah_a;
1013 const struct ast_exten *bc = ah_b;
1014 return ac->priority != bc->priority;
1017 static int hashtab_compare_exten_labels(const void *ah_a, const void *ah_b)
1019 const struct ast_exten *ac = ah_a;
1020 const struct ast_exten *bc = ah_b;
1021 return strcmp(ac->label, bc->label);
1024 unsigned int ast_hashtab_hash_contexts(const void *obj)
1026 const struct ast_context *ac = obj;
1027 return ast_hashtab_hash_string(ac->name);
1030 static unsigned int hashtab_hash_extens(const void *obj)
1032 const struct ast_exten *ac = obj;
1033 unsigned int x = ast_hashtab_hash_string(ac->exten);
1036 y = ast_hashtab_hash_string(ac->cidmatch);
1040 static unsigned int hashtab_hash_priority(const void *obj)
1042 const struct ast_exten *ac = obj;
1043 return ast_hashtab_hash_int(ac->priority);
1046 static unsigned int hashtab_hash_labels(const void *obj)
1048 const struct ast_exten *ac = obj;
1049 return ast_hashtab_hash_string(ac->label);
1053 AST_RWLOCK_DEFINE_STATIC(globalslock);
1054 static struct varshead globals = AST_LIST_HEAD_NOLOCK_INIT_VALUE;
1056 static int autofallthrough = 1;
1057 static int extenpatternmatchnew = 0;
1058 static char *overrideswitch = NULL;
1060 /*! \brief Subscription for device state change events */
1061 static struct ast_event_sub *device_state_sub;
1063 AST_MUTEX_DEFINE_STATIC(maxcalllock);
1064 static int countcalls;
1065 static int totalcalls;
1067 static AST_RWLIST_HEAD_STATIC(acf_root, ast_custom_function);
1069 /*! \brief Declaration of builtin applications */
1070 static struct pbx_builtin {
1071 char name[AST_MAX_APP];
1072 int (*execute)(struct ast_channel *chan, void *data);
1075 /* These applications are built into the PBX core and do not
1076 need separate modules */
1078 { "Answer", pbx_builtin_answer },
1079 { "BackGround", pbx_builtin_background },
1080 { "Busy", pbx_builtin_busy },
1081 { "Congestion", pbx_builtin_congestion },
1082 { "ExecIfTime", pbx_builtin_execiftime },
1083 { "Goto", pbx_builtin_goto },
1084 { "GotoIf", pbx_builtin_gotoif },
1085 { "GotoIfTime", pbx_builtin_gotoiftime },
1086 { "ImportVar", pbx_builtin_importvar },
1087 { "Hangup", pbx_builtin_hangup },
1088 { "Incomplete", pbx_builtin_incomplete },
1089 { "NoOp", pbx_builtin_noop },
1090 { "Proceeding", pbx_builtin_proceeding },
1091 { "Progress", pbx_builtin_progress },
1092 { "RaiseException", pbx_builtin_raise_exception },
1093 { "ResetCDR", pbx_builtin_resetcdr },
1094 { "Ringing", pbx_builtin_ringing },
1095 { "SayAlpha", pbx_builtin_saycharacters },
1096 { "SayDigits", pbx_builtin_saydigits },
1097 { "SayNumber", pbx_builtin_saynumber },
1098 { "SayPhonetic", pbx_builtin_sayphonetic },
1099 { "Set", pbx_builtin_setvar },
1100 { "MSet", pbx_builtin_setvar_multiple },
1101 { "SetAMAFlags", pbx_builtin_setamaflags },
1102 { "Wait", pbx_builtin_wait },
1103 { "WaitExten", pbx_builtin_waitexten }
1106 static struct ast_context *contexts;
1107 static struct ast_hashtab *contexts_table = NULL;
1109 AST_RWLOCK_DEFINE_STATIC(conlock); /*!< Lock for the ast_context list */
1111 static AST_RWLIST_HEAD_STATIC(apps, ast_app);
1113 static AST_RWLIST_HEAD_STATIC(switches, ast_switch);
1115 static int stateid = 1;
1117 When holding this list's lock, do _not_ do anything that will cause conlock
1118 to be taken, unless you _already_ hold it. The ast_merge_contexts_and_delete
1119 function will take the locks in conlock/hints order, so any other
1120 paths that require both locks must also take them in that order.
1122 static AST_RWLIST_HEAD_STATIC(hints, ast_hint);
1124 static AST_LIST_HEAD_NOLOCK_STATIC(statecbs, ast_state_cb);
1126 #ifdef CONTEXT_DEBUG
1128 /* these routines are provided for doing run-time checks
1129 on the extension structures, in case you are having
1130 problems, this routine might help you localize where
1131 the problem is occurring. It's kinda like a debug memory
1132 allocator's arena checker... It'll eat up your cpu cycles!
1133 but you'll see, if you call it in the right places,
1134 right where your problems began...
1137 /* you can break on the check_contexts_trouble()
1138 routine in your debugger to stop at the moment
1139 there's a problem */
1140 void check_contexts_trouble(void);
1142 void check_contexts_trouble(void)
1148 static struct ast_context *find_context_locked(const char *context);
1149 int check_contexts(char *, int);
1151 int check_contexts(char *file, int line )
1153 struct ast_hashtab_iter *t1;
1154 struct ast_context *c1, *c2;
1156 struct ast_exten *e1, *e2, *e3;
1157 struct ast_exten ex;
1159 /* try to find inconsistencies */
1160 /* is every context in the context table in the context list and vice-versa ? */
1162 if (!contexts_table) {
1163 ast_log(LOG_NOTICE,"Called from: %s:%d: No contexts_table!\n", file, line);
1167 t1 = ast_hashtab_start_traversal(contexts_table);
1168 while( (c1 = ast_hashtab_next(t1))) {
1169 for(c2=contexts;c2;c2=c2->next) {
1170 if (!strcmp(c1->name, c2->name)) {
1176 ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the linked list\n", file, line, c1->name);
1177 check_contexts_trouble();
1180 ast_hashtab_end_traversal(t1);
1181 for(c2=contexts;c2;c2=c2->next) {
1182 c1 = find_context_locked(c2->name);
1184 ast_log(LOG_NOTICE,"Called from: %s:%d: Could not find the %s context in the hashtab\n", file, line, c2->name);
1185 check_contexts_trouble();
1187 ast_unlock_contexts();
1190 /* loop thru all contexts, and verify the exten structure compares to the
1191 hashtab structure */
1192 for(c2=contexts;c2;c2=c2->next) {
1193 c1 = find_context_locked(c2->name);
1197 ast_unlock_contexts();
1199 /* is every entry in the root list also in the root_table? */
1200 for(e1 = c1->root; e1; e1=e1->next)
1202 char dummy_name[1024];
1203 ex.exten = dummy_name;
1204 ex.matchcid = e1->matchcid;
1205 ex.cidmatch = e1->cidmatch;
1206 ast_copy_string(dummy_name, e1->exten, sizeof(dummy_name));
1207 e2 = ast_hashtab_lookup(c1->root_table, &ex);
1210 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s (CID match: %s) but it is not in its root_table\n", file, line, c2->name, dummy_name, e1->cidmatch );
1212 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, dummy_name );
1214 check_contexts_trouble();
1218 /* is every entry in the root_table also in the root list? */
1219 if (!c2->root_table) {
1221 ast_log(LOG_NOTICE,"Called from: %s:%d: No c2->root_table for context %s!\n", file, line, c2->name);
1225 t1 = ast_hashtab_start_traversal(c2->root_table);
1226 while( (e2 = ast_hashtab_next(t1)) ) {
1227 for(e1=c2->root;e1;e1=e1->next) {
1228 if (!strcmp(e1->exten, e2->exten)) {
1234 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context records the exten %s but it is not in its root_table\n", file, line, c2->name, e2->exten);
1235 check_contexts_trouble();
1239 ast_hashtab_end_traversal(t1);
1242 /* is every priority reflected in the peer_table at the head of the list? */
1244 /* is every entry in the root list also in the root_table? */
1245 /* are the per-extension peer_tables in the right place? */
1247 for(e1 = c2->root; e1; e1 = e1->next) {
1249 for(e2=e1;e2;e2=e2->peer) {
1250 ex.priority = e2->priority;
1251 if (e2 != e1 && e2->peer_table) {
1252 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
1253 check_contexts_trouble();
1256 if (e2 != e1 && e2->peer_label_table) {
1257 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority has a peer_label_table entry, and shouldn't!\n", file, line, c2->name, e1->exten, e2->priority );
1258 check_contexts_trouble();
1261 if (e2 == e1 && !e2->peer_table){
1262 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_table!\n", file, line, c2->name, e1->exten, e2->priority );
1263 check_contexts_trouble();
1266 if (e2 == e1 && !e2->peer_label_table) {
1267 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority doesn't have a peer_label_table!\n", file, line, c2->name, e1->exten, e2->priority );
1268 check_contexts_trouble();
1272 e3 = ast_hashtab_lookup(e1->peer_table, &ex);
1274 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer_table\n", file, line, c2->name, e1->exten, e2->priority );
1275 check_contexts_trouble();
1279 if (!e1->peer_table){
1280 ast_log(LOG_NOTICE,"Called from: %s:%d: No e1->peer_table!\n", file, line);
1284 /* is every entry in the peer_table also in the peer list? */
1285 t1 = ast_hashtab_start_traversal(e1->peer_table);
1286 while( (e2 = ast_hashtab_next(t1)) ) {
1287 for(e3=e1;e3;e3=e3->peer) {
1288 if (e3->priority == e2->priority) {
1294 ast_log(LOG_NOTICE,"Called from: %s:%d: The %s context, %s exten, %d priority is not reflected in the peer list\n", file, line, c2->name, e1->exten, e2->priority );
1295 check_contexts_trouble();
1298 ast_hashtab_end_traversal(t1);
1306 \note This function is special. It saves the stack so that no matter
1307 how many times it is called, it returns to the same place */
1308 int pbx_exec(struct ast_channel *c, /*!< Channel */
1309 struct ast_app *app, /*!< Application */
1310 void *data) /*!< Data for execution */
1313 struct ast_module_user *u = NULL;
1314 const char *saved_c_appl;
1315 const char *saved_c_data;
1317 if (c->cdr && !ast_check_hangup(c))
1318 ast_cdr_setapp(c->cdr, app->name, data);
1320 /* save channel values */
1321 saved_c_appl= c->appl;
1322 saved_c_data= c->data;
1324 c->appl = app->name;
1327 u = __ast_module_user_add(app->module, c);
1328 res = app->execute(c, S_OR(data, ""));
1329 if (app->module && u)
1330 __ast_module_user_remove(app->module, u);
1331 /* restore channel values */
1332 c->appl = saved_c_appl;
1333 c->data = saved_c_data;
1338 /*! Go no deeper than this through includes (not counting loops) */
1339 #define AST_PBX_MAX_STACK 128
1341 /*! \brief Find application handle in linked list
1343 struct ast_app *pbx_findapp(const char *app)
1345 struct ast_app *tmp;
1347 AST_RWLIST_RDLOCK(&apps);
1348 AST_RWLIST_TRAVERSE(&apps, tmp, list) {
1349 if (!strcasecmp(tmp->name, app))
1352 AST_RWLIST_UNLOCK(&apps);
1357 static struct ast_switch *pbx_findswitch(const char *sw)
1359 struct ast_switch *asw;
1361 AST_RWLIST_RDLOCK(&switches);
1362 AST_RWLIST_TRAVERSE(&switches, asw, list) {
1363 if (!strcasecmp(asw->name, sw))
1366 AST_RWLIST_UNLOCK(&switches);
1371 static inline int include_valid(struct ast_include *i)
1376 return ast_check_timing(&(i->timing));
1379 static void pbx_destroy(struct ast_pbx *p)
1384 /* form a tree that fully describes all the patterns in a context's extensions
1385 * in this tree, a "node" represents an individual character or character set
1386 * meant to match the corresponding character in a dial string. The tree
1387 * consists of a series of match_char structs linked in a chain
1388 * via the alt_char pointers. More than one pattern can share the same parts of the
1389 * tree as other extensions with the same pattern to that point.
1390 * My first attempt to duplicate the finding of the 'best' pattern was flawed in that
1391 * I misunderstood the general algorithm. I thought that the 'best' pattern
1392 * was the one with lowest total score. This was not true. Thus, if you have
1393 * patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is
1394 * the "best" match because it has fewer X's, and is therefore more specific,
1395 * but this is not how the old algorithm works. It sorts matching patterns
1396 * in a similar collating sequence as sorting alphabetic strings, from left to
1397 * right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match,
1398 * because "1" is more specific than "X".
1399 * So, to accomodate this philosophy, I sort the tree branches along the alt_char
1400 * line so they are lowest to highest in specificity numbers. This way, as soon
1401 * as we encounter our first complete match, we automatically have the "best"
1402 * match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE.
1403 * If anyone would like to resurrect the "wrong" pattern trie searching algorithm,
1404 * they are welcome to revert pbx to before 1 Apr 2008.
1405 * As an example, consider these 4 extensions:
1411 * In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over
1412 * most numbers. For all numbers beginning with 307754, (b) should always win.
1414 * These pattern should form a (sorted) tree that looks like this:
1415 * { "3" } --next--> { "0" } --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) }
1419 * { "f" } --next--> { "a" } --next--> { "x" exten_match: (c) }
1420 * { "N" } --next--> { "X" } --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
1424 * | { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
1428 * In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take
1429 * fewer CPU cycles than a call to strchr("23456789",*z), where *z is the char to match...
1431 * traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern, it calls itself
1432 * on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length.
1433 * We pass a pointer to a scoreboard down through, also.
1434 * The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension.
1435 * The first complete match ends the traversal, which should make this version of the pattern matcher faster
1436 * the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both
1437 * these cases, the reason we can stop immediately, is because the first pattern match found will be the "best"
1438 * according to the sort criteria.
1439 * Hope the limit on stack depth won't be a problem... this routine should
1440 * be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch.
1442 * In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d. All are
1443 * of length 10; they have total specificities of 24580, 10246, and 25090, respectively, not that this matters
1444 * at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have
1445 * left the specificity totals in the code as an artifact; at some point, I will strip it out.
1447 * Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown,
1448 * because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup
1449 * can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or
1450 * more times faster in extreme cases.
1452 * MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you
1453 * can have patterns in your CID field as well.
1458 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)
1460 /* if this extension is marked as deleted, then skip this -- if it never shows
1461 on the scoreboard, it will never be found, nor will halt the traversal. */
1464 board->total_specificity = spec;
1465 board->total_length = length;
1466 board->exten = exten;
1467 board->last_char = last;
1469 #ifdef NEED_DEBUG_HERE
1470 ast_log(LOG_NOTICE,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten->exten, length, spec);
1474 void log_match_char_tree(struct match_char *node, char *prefix)
1477 struct ast_str *my_prefix = ast_str_alloca(1024);
1481 if (node && node->exten && node->exten)
1482 snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
1484 if (strlen(node->x) > 1) {
1485 ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
1486 node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
1487 node->exten ? node->exten->exten : "", extenstr);
1489 ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y':'N',
1490 node->deleted? 'D':'-', node->specificity, node->exten? "EXTEN:":"",
1491 node->exten ? node->exten->exten : "", extenstr);
1494 ast_str_set(&my_prefix, 0, "%s+ ", prefix);
1496 if (node->next_char)
1497 log_match_char_tree(node->next_char, ast_str_buffer(my_prefix));
1500 log_match_char_tree(node->alt_char, prefix);
1503 static void cli_match_char_tree(struct match_char *node, char *prefix, int fd)
1506 struct ast_str *my_prefix = ast_str_alloca(1024);
1510 if (node && node->exten && node->exten)
1511 snprintf(extenstr, sizeof(extenstr), "(%p)", node->exten);
1513 if (strlen(node->x) > 1) {
1514 ast_cli(fd, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
1515 node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
1516 node->exten ? node->exten->exten : "", extenstr);
1518 ast_cli(fd, "%s%s:%c:%c:%d:%s%s%s\n", prefix, node->x, node->is_pattern ? 'Y' : 'N',
1519 node->deleted ? 'D' : '-', node->specificity, node->exten? "EXTEN:" : "",
1520 node->exten ? node->exten->exten : "", extenstr);
1523 ast_str_set(&my_prefix, 0, "%s+ ", prefix);
1525 if (node->next_char)
1526 cli_match_char_tree(node->next_char, ast_str_buffer(my_prefix), fd);
1529 cli_match_char_tree(node->alt_char, prefix, fd);
1532 static struct ast_exten *get_canmatch_exten(struct match_char *node)
1534 /* find the exten at the end of the rope */
1535 struct match_char *node2 = node;
1537 for (node2 = node; node2; node2 = node2->next_char) {
1539 #ifdef NEED_DEBUG_HERE
1540 ast_log(LOG_NOTICE,"CanMatch_exten returns exten %s(%p)\n", node2->exten->exten, node2->exten);
1542 return node2->exten;
1545 #ifdef NEED_DEBUG_HERE
1546 ast_log(LOG_NOTICE,"CanMatch_exten returns NULL, match_char=%s\n", node->x);
1551 static struct ast_exten *trie_find_next_match(struct match_char *node)
1553 struct match_char *m3;
1554 struct match_char *m4;
1555 struct ast_exten *e3;
1557 if (node && node->x[0] == '.' && !node->x[1]) /* dot and ! will ALWAYS be next match in a matchmore */
1560 if (node && node->x[0] == '!' && !node->x[1])
1563 if (!node || !node->next_char)
1566 m3 = node->next_char;
1570 for(m4=m3->alt_char; m4; m4 = m4->alt_char) {
1574 for(m4=m3; m4; m4 = m4->alt_char) {
1575 e3 = trie_find_next_match(m3);
1583 static char *action2str(enum ext_match_t action)
1604 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)
1606 struct match_char *p; /* note minimal stack storage requirements */
1607 struct ast_exten pattern = { .label = label };
1610 ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree %s action=%s\n", str, tree->x, action2str(action));
1612 ast_log(LOG_NOTICE,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str, action2str(action));
1614 for (p=tree; p; p=p->alt_char) {
1615 if (p->x[0] == 'N') {
1616 if (p->x[1] == 0 && *str >= '2' && *str <= '9' ) {
1617 #define NEW_MATCHER_CHK_MATCH \
1618 if (p->exten && !(*(str+1))) { /* if a shorter pattern matches along the way, might as well report it */ \
1619 if (action == E_MATCH || action == E_SPAWN || action == E_FINDLABEL) { /* if in CANMATCH/MATCHMORE, don't let matches get in the way */ \
1620 update_scoreboard(score, length+1, spec+p->specificity, p->exten,0,callerid, p->deleted, p); \
1621 if (!p->deleted) { \
1622 if (action == E_FINDLABEL) { \
1623 if (ast_hashtab_lookup(score->exten->peer_label_table, &pattern)) { \
1624 ast_debug(4, "Found label in preferred extension\n"); \
1628 ast_debug(4,"returning an exact match-- first found-- %s\n", p->exten->exten); \
1629 return; /* the first match, by definition, will be the best, because of the sorted tree */ \
1635 #define NEW_MATCHER_RECURSE \
1636 if (p->next_char && ( *(str+1) || (p->next_char->x[0] == '/' && p->next_char->x[1] == 0) \
1637 || p->next_char->x[0] == '!')) { \
1638 if (*(str+1) || p->next_char->x[0] == '!') { \
1639 new_find_extension(str+1, score, p->next_char, length+1, spec+p->specificity, callerid, label, action); \
1640 if (score->exten) { \
1641 ast_debug(4,"returning an exact match-- %s\n", score->exten->exten); \
1642 return; /* the first match is all we need */ \
1645 new_find_extension("/", score, p->next_char, length+1, spec+p->specificity, callerid, label, action); \
1646 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { \
1647 ast_debug(4,"returning a (can/more) match--- %s\n", score->exten ? score->exten->exten : \
1649 return; /* the first match is all we need */ \
1652 } else if (p->next_char && !*(str+1)) { \
1653 score->canmatch = 1; \
1654 score->canmatch_exten = get_canmatch_exten(p); \
1655 if (action == E_CANMATCH || action == E_MATCHMORE) { \
1656 ast_debug(4,"returning a canmatch/matchmore--- str=%s\n", str); \
1661 NEW_MATCHER_CHK_MATCH;
1662 NEW_MATCHER_RECURSE;
1664 } else if (p->x[0] == 'Z') {
1665 if (p->x[1] == 0 && *str >= '1' && *str <= '9' ) {
1666 NEW_MATCHER_CHK_MATCH;
1667 NEW_MATCHER_RECURSE;
1669 } else if (p->x[0] == 'X') {
1670 if (p->x[1] == 0 && *str >= '0' && *str <= '9' ) {
1671 NEW_MATCHER_CHK_MATCH;
1672 NEW_MATCHER_RECURSE;
1674 } else if (p->x[0] == '.' && p->x[1] == 0) {
1675 /* how many chars will the . match against? */
1677 const char *str2 = str;
1678 while (*str2 && *str2 != '/') {
1682 if (p->exten && *str2 != '/') {
1683 update_scoreboard(score, length+i, spec+(i*p->specificity), p->exten, '.', callerid, p->deleted, p);
1685 ast_debug(4,"return because scoreboard has a match with '/'--- %s\n", score->exten->exten);
1686 return; /* the first match is all we need */
1689 if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
1690 new_find_extension("/", score, p->next_char, length+i, spec+(p->specificity*i), callerid, label, action);
1691 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
1692 ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set--- %s\n", score->exten ? score->exten->exten : "NULL");
1693 return; /* the first match is all we need */
1696 } else if (p->x[0] == '!' && p->x[1] == 0) {
1697 /* how many chars will the . match against? */
1699 const char *str2 = str;
1700 while (*str2 && *str2 != '/') {
1704 if (p->exten && *str2 != '/') {
1705 update_scoreboard(score, length+1, spec+(p->specificity*i), p->exten, '!', callerid, p->deleted, p);
1707 ast_debug(4,"return because scoreboard has a '!' match--- %s\n", score->exten->exten);
1708 return; /* the first match is all we need */
1711 if (p->next_char && p->next_char->x[0] == '/' && p->next_char->x[1] == 0) {
1712 new_find_extension("/", score, p->next_char, length+i, spec+(p->specificity*i), callerid, label, action);
1713 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
1714 ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/' and '!'--- %s\n", score->exten ? score->exten->exten : "NULL");
1715 return; /* the first match is all we need */
1718 } else if (p->x[0] == '/' && p->x[1] == 0) {
1719 /* the pattern in the tree includes the cid match! */
1720 if (p->next_char && callerid && *callerid) {
1721 new_find_extension(callerid, score, p->next_char, length+1, spec, callerid, label, action);
1722 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) {
1723 ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/'--- %s\n", score->exten ? score->exten->exten : "NULL");
1724 return; /* the first match is all we need */
1727 } else if (strchr(p->x, *str)) {
1728 ast_debug(4, "Nothing strange about this match\n");
1729 NEW_MATCHER_CHK_MATCH;
1730 NEW_MATCHER_RECURSE;
1733 ast_debug(4,"return at end of func\n");
1736 /* the algorithm for forming the extension pattern tree is also a bit simple; you
1737 * traverse all the extensions in a context, and for each char of the extension,
1738 * you see if it exists in the tree; if it doesn't, you add it at the appropriate
1739 * spot. What more can I say? At the end of each exten, you cap it off by adding the
1740 * address of the extension involved. Duplicate patterns will be complained about.
1742 * Ideally, this would be done for each context after it is created and fully
1743 * filled. It could be done as a finishing step after extensions.conf or .ael is
1744 * loaded, or it could be done when the first search is encountered. It should only
1745 * have to be done once, until the next unload or reload.
1747 * I guess forming this pattern tree would be analogous to compiling a regex. Except
1748 * that a regex only handles 1 pattern, really. This trie holds any number
1749 * of patterns. Well, really, it **could** be considered a single pattern,
1750 * where the "|" (or) operator is allowed, I guess, in a way, sort of...
1753 static struct match_char *already_in_tree(struct match_char *current, char *pat)
1755 struct match_char *t;
1760 for (t = current; t; t = t->alt_char) {
1761 if (!strcmp(pat, t->x)) /* uh, we may want to sort exploded [] contents to make matching easy */
1768 /* The first arg is the location of the tree ptr, or the
1769 address of the next_char ptr in the node, so we can mess
1770 with it, if we need to insert at the beginning of the list */
1772 static void insert_in_next_chars_alt_char_list(struct match_char **parent_ptr, struct match_char *node)
1774 struct match_char *curr, *lcurr;
1776 /* insert node into the tree at "current", so the alt_char list from current is
1777 sorted in increasing value as you go to the leaves */
1778 if (!(*parent_ptr)) {
1781 if ((*parent_ptr)->specificity > node->specificity){
1782 /* insert at head */
1783 node->alt_char = (*parent_ptr);
1786 lcurr = *parent_ptr;
1787 for (curr=(*parent_ptr)->alt_char; curr; curr = curr->alt_char) {
1788 if (curr->specificity > node->specificity) {
1789 node->alt_char = curr;
1790 lcurr->alt_char = node;
1796 lcurr->alt_char = node;
1804 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)
1806 struct match_char *m;
1808 if (!(m = ast_calloc(1, sizeof(*m))))
1811 if (!(m->x = ast_strdup(pattern))) {
1816 /* the specificity scores are the same as used in the old
1818 m->is_pattern = is_pattern;
1819 if (specificity == 1 && is_pattern && pattern[0] == 'N')
1820 m->specificity = 0x0802;
1821 else if (specificity == 1 && is_pattern && pattern[0] == 'Z')
1822 m->specificity = 0x0901;
1823 else if (specificity == 1 && is_pattern && pattern[0] == 'X')
1824 m->specificity = 0x0a00;
1825 else if (specificity == 1 && is_pattern && pattern[0] == '.')
1826 m->specificity = 0x10000;
1827 else if (specificity == 1 && is_pattern && pattern[0] == '!')
1828 m->specificity = 0x20000;
1830 m->specificity = specificity;
1832 if (!con->pattern_tree) {
1833 insert_in_next_chars_alt_char_list(&con->pattern_tree, m);
1835 if (already) { /* switch to the new regime (traversing vs appending)*/
1836 insert_in_next_chars_alt_char_list(nextcharptr, m);
1838 insert_in_next_chars_alt_char_list(¤t->next_char, m);
1845 static struct match_char *add_exten_to_pattern_tree(struct ast_context *con, struct ast_exten *e1, int findonly)
1847 struct match_char *m1 = NULL, *m2 = NULL, **m0;
1853 char *s1 = extenbuf;
1854 int l1 = strlen(e1->exten) + strlen(e1->cidmatch) + 2;
1857 strncpy(extenbuf,e1->exten,sizeof(extenbuf));
1858 if (e1->matchcid && l1 <= sizeof(extenbuf)) {
1859 strcat(extenbuf,"/");
1860 strcat(extenbuf,e1->cidmatch);
1861 } else if (l1 > sizeof(extenbuf)) {
1862 ast_log(LOG_ERROR,"The pattern %s/%s is too big to deal with: it will be ignored! Disaster!\n", e1->exten, e1->cidmatch);
1866 ast_log(LOG_DEBUG,"Adding exten %s%c%s to tree\n", s1, e1->matchcid? '/':' ', e1->matchcid? e1->cidmatch : "");
1868 m1 = con->pattern_tree; /* each pattern starts over at the root of the pattern tree */
1869 m0 = &con->pattern_tree;
1877 if (pattern && *s1 == '[' && *(s1-1) != '\\') {
1880 s1++; /* get past the '[' */
1881 while (*s1 != ']' && *(s1-1) != '\\' ) {
1883 if (*(s1+1) == ']') {
1886 } else if (*(s1+1) == '\\') {
1889 } else if (*(s1+1) == '-') {
1892 } else if (*(s1+1) == '[') {
1896 } else if (*s1 == '-') { /* remember to add some error checking to all this! */
1899 for (s3++; s3 <= s4; s3++) {
1907 *s2 = 0; /* null terminate the exploded range */
1908 /* sort the characters */
1910 specif = strlen(buf);
1911 qsort(buf, specif, 1, compare_char);
1921 if (*s1 == 'n') /* make sure n,x,z patterns are canonicalized to N,X,Z */
1923 else if (*s1 == 'x')
1925 else if (*s1 == 'z')
1934 if (already && (m2=already_in_tree(m1,buf)) && m2->next_char) {
1935 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...
1936 a shorter pattern might win if the longer one doesn't match */
1940 m1 = m2->next_char; /* m1 points to the node to compare against */
1941 m0 = &m2->next_char; /* m0 points to the ptr that points to m1 */
1942 } else { /* not already OR not m2 OR nor m2->next_char */
1946 m1 = m2; /* while m0 stays the same */
1950 m1 = add_pattern_node(con, m1, buf, pattern, already,specif, m0); /* m1 is the node just added */
1951 m0 = &m1->next_char;
1961 s1++; /* advance to next char */
1966 static void create_match_char_tree(struct ast_context *con)
1968 struct ast_hashtab_iter *t1;
1969 struct ast_exten *e1;
1971 int biggest_bucket, resizes, numobjs, numbucks;
1973 ast_log(LOG_DEBUG,"Creating Extension Trie for context %s\n", con->name);
1974 ast_hashtab_get_stats(con->root_table, &biggest_bucket, &resizes, &numobjs, &numbucks);
1975 ast_log(LOG_DEBUG,"This tree has %d objects in %d bucket lists, longest list=%d objects, and has resized %d times\n",
1976 numobjs, numbucks, biggest_bucket, resizes);
1978 t1 = ast_hashtab_start_traversal(con->root_table);
1979 while( (e1 = ast_hashtab_next(t1)) ) {
1981 add_exten_to_pattern_tree(con, e1, 0);
1983 ast_log(LOG_ERROR,"Attempt to create extension with no extension name.\n");
1985 ast_hashtab_end_traversal(t1);
1988 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! */
1990 /* destroy all the alternates */
1991 if (pattern_tree->alt_char) {
1992 destroy_pattern_tree(pattern_tree->alt_char);
1993 pattern_tree->alt_char = 0;
1995 /* destroy all the nexts */
1996 if (pattern_tree->next_char) {
1997 destroy_pattern_tree(pattern_tree->next_char);
1998 pattern_tree->next_char = 0;
2000 pattern_tree->exten = 0; /* never hurts to make sure there's no pointers laying around */
2001 if (pattern_tree->x)
2002 free(pattern_tree->x);
2007 * Special characters used in patterns:
2008 * '_' underscore is the leading character of a pattern.
2009 * In other position it is treated as a regular char.
2010 * . one or more of any character. Only allowed at the end of
2012 * ! zero or more of anything. Also impacts the result of CANMATCH
2013 * and MATCHMORE. Only allowed at the end of a pattern.
2014 * In the core routine, ! causes a match with a return code of 2.
2015 * In turn, depending on the search mode: (XXX check if it is implemented)
2016 * - E_MATCH retuns 1 (does match)
2017 * - E_MATCHMORE returns 0 (no match)
2018 * - E_CANMATCH returns 1 (does match)
2020 * / should not appear as it is considered the separator of the CID info.
2021 * XXX at the moment we may stop on this char.
2023 * X Z N match ranges 0-9, 1-9, 2-9 respectively.
2024 * [ denotes the start of a set of character. Everything inside
2025 * is considered literally. We can have ranges a-d and individual
2026 * characters. A '[' and '-' can be considered literally if they
2027 * are just before ']'.
2028 * XXX currently there is no way to specify ']' in a range, nor \ is
2029 * considered specially.
2031 * When we compare a pattern with a specific extension, all characters in the extension
2032 * itself are considered literally.
2033 * XXX do we want to consider space as a separator as well ?
2034 * XXX do we want to consider the separators in non-patterns as well ?
2038 * \brief helper functions to sort extensions and patterns in the desired way,
2039 * so that more specific patterns appear first.
2041 * ext_cmp1 compares individual characters (or sets of), returning
2042 * an int where bits 0-7 are the ASCII code of the first char in the set,
2043 * while bit 8-15 are the cardinality of the set minus 1.
2044 * This way more specific patterns (smaller cardinality) appear first.
2045 * Wildcards have a special value, so that we can directly compare them to
2046 * sets by subtracting the two values. In particular:
2047 * 0x000xx one character, xx
2048 * 0x0yyxx yy character set starting with xx
2049 * 0x10000 '.' (one or more of anything)
2050 * 0x20000 '!' (zero or more of anything)
2051 * 0x30000 NUL (end of string)
2052 * 0x40000 error in set.
2053 * The pointer to the string is advanced according to needs.
2055 * 1. the empty set is equivalent to NUL.
2056 * 2. given that a full set has always 0 as the first element,
2057 * we could encode the special cases as 0xffXX where XX
2058 * is 1, 2, 3, 4 as used above.
2060 static int ext_cmp1(const char **p)
2063 int c, cmin = 0xff, count = 0;
2066 /* load, sign extend and advance pointer until we find
2067 * a valid character.
2071 /* always return unless we have a set of chars */
2072 switch (toupper(c)) {
2073 default: /* ordinary character */
2074 return 0x0000 | (c & 0xff);
2076 case 'N': /* 2..9 */
2077 return 0x0800 | '2' ;
2079 case 'X': /* 0..9 */
2080 return 0x0A00 | '0';
2082 case 'Z': /* 1..9 */
2083 return 0x0900 | '1';
2085 case '.': /* wildcard */
2088 case '!': /* earlymatch */
2089 return 0x20000; /* less specific than NULL */
2091 case '\0': /* empty string */
2095 case '[': /* pattern */
2098 /* locate end of set */
2099 end = strchr(*p, ']');
2102 ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
2103 return 0x40000; /* XXX make this entry go last... */
2106 memset(chars, '\0', sizeof(chars)); /* clear all chars in the set */
2107 for (; *p < end ; (*p)++) {
2108 unsigned char c1, c2; /* first-last char in range */
2109 c1 = (unsigned char)((*p)[0]);
2110 if (*p + 2 < end && (*p)[1] == '-') { /* this is a range */
2111 c2 = (unsigned char)((*p)[2]);
2112 *p += 2; /* skip a total of 3 chars */
2113 } else /* individual character */
2117 for (; c1 <= c2; c1++) {
2118 uint32_t mask = 1 << (c1 % 32);
2119 if ( (chars[ c1 / 32 ] & mask) == 0)
2121 chars[ c1 / 32 ] |= mask;
2125 return count == 0 ? 0x30000 : (count | cmin);
2129 * \brief the full routine to compare extensions in rules.
2131 static int ext_cmp(const char *a, const char *b)
2133 /* make sure non-patterns come first.
2134 * If a is not a pattern, it either comes first or
2135 * we use strcmp to compare the strings.
2140 return (b[0] == '_') ? -1 : strcmp(a, b);
2142 /* Now we know a is a pattern; if b is not, a comes first */
2145 #if 0 /* old mode for ext matching */
2146 return strcmp(a, b);
2148 /* ok we need full pattern sorting routine */
2149 while (!ret && a && b)
2150 ret = ext_cmp1(&a) - ext_cmp1(&b);
2154 return (ret > 0) ? 1 : -1;
2157 int ast_extension_cmp(const char *a, const char *b)
2159 return ext_cmp(a, b);
2164 * \brief used ast_extension_{match|close}
2165 * mode is as follows:
2166 * E_MATCH success only on exact match
2167 * E_MATCHMORE success only on partial match (i.e. leftover digits in pattern)
2168 * E_CANMATCH either of the above.
2169 * \retval 0 on no-match
2170 * \retval 1 on match
2171 * \retval 2 on early match.
2174 static int _extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
2176 mode &= E_MATCH_MASK; /* only consider the relevant bits */
2178 #ifdef NEED_DEBUG_HERE
2179 ast_log(LOG_NOTICE,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern, data, (int)mode);
2182 if ( (mode == E_MATCH) && (pattern[0] == '_') && (!strcasecmp(pattern,data)) ) { /* note: if this test is left out, then _x. will not match _x. !!! */
2183 #ifdef NEED_DEBUG_HERE
2184 ast_log(LOG_NOTICE,"return (1) - pattern matches pattern\n");
2189 if (pattern[0] != '_') { /* not a pattern, try exact or partial match */
2190 int ld = strlen(data), lp = strlen(pattern);
2192 if (lp < ld) { /* pattern too short, cannot match */
2193 #ifdef NEED_DEBUG_HERE
2194 ast_log(LOG_NOTICE,"return (0) - pattern too short, cannot match\n");
2198 /* depending on the mode, accept full or partial match or both */
2199 if (mode == E_MATCH) {
2200 #ifdef NEED_DEBUG_HERE
2201 ast_log(LOG_NOTICE,"return (!strcmp(%s,%s) when mode== E_MATCH)\n", pattern, data);
2203 return !strcmp(pattern, data); /* 1 on match, 0 on fail */
2205 if (ld == 0 || !strncasecmp(pattern, data, ld)) { /* partial or full match */
2206 #ifdef NEED_DEBUG_HERE
2207 ast_log(LOG_NOTICE,"return (mode(%d) == E_MATCHMORE ? lp(%d) > ld(%d) : 1)\n", mode, lp, ld);
2209 return (mode == E_MATCHMORE) ? lp > ld : 1; /* XXX should consider '!' and '/' ? */
2211 #ifdef NEED_DEBUG_HERE
2212 ast_log(LOG_NOTICE,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld, pattern, data);
2217 pattern++; /* skip leading _ */
2219 * XXX below we stop at '/' which is a separator for the CID info. However we should
2220 * not store '/' in the pattern at all. When we insure it, we can remove the checks.
2222 while (*data && *pattern && *pattern != '/') {
2225 if (*data == '-') { /* skip '-' in data (just a separator) */
2229 switch (toupper(*pattern)) {
2230 case '[': /* a range */
2231 end = strchr(pattern+1, ']'); /* XXX should deal with escapes ? */
2233 ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");
2234 return 0; /* unconditional failure */
2236 for (pattern++; pattern != end; pattern++) {
2237 if (pattern+2 < end && pattern[1] == '-') { /* this is a range */
2238 if (*data >= pattern[0] && *data <= pattern[2])
2239 break; /* match found */
2241 pattern += 2; /* skip a total of 3 chars */
2244 } else if (*data == pattern[0])
2245 break; /* match found */
2247 if (pattern == end) {
2248 #ifdef NEED_DEBUG_HERE
2249 ast_log(LOG_NOTICE,"return (0) when pattern==end\n");
2253 pattern = end; /* skip and continue */
2256 if (*data < '2' || *data > '9') {
2257 #ifdef NEED_DEBUG_HERE
2258 ast_log(LOG_NOTICE,"return (0) N is matched\n");
2264 if (*data < '0' || *data > '9') {
2265 #ifdef NEED_DEBUG_HERE
2266 ast_log(LOG_NOTICE,"return (0) X is matched\n");
2272 if (*data < '1' || *data > '9') {
2273 #ifdef NEED_DEBUG_HERE
2274 ast_log(LOG_NOTICE,"return (0) Z is matched\n");
2279 case '.': /* Must match, even with more digits */
2280 #ifdef NEED_DEBUG_HERE
2281 ast_log(LOG_NOTICE,"return (1) when '.' is matched\n");
2284 case '!': /* Early match */
2285 #ifdef NEED_DEBUG_HERE
2286 ast_log(LOG_NOTICE,"return (2) when '!' is matched\n");
2290 case '-': /* Ignore these in patterns */
2291 data--; /* compensate the final data++ */
2294 if (*data != *pattern) {
2295 #ifdef NEED_DEBUG_HERE
2296 ast_log(LOG_NOTICE,"return (0) when *data(%c) != *pattern(%c)\n", *data, *pattern);
2305 if (*data) /* data longer than pattern, no match */ {
2306 #ifdef NEED_DEBUG_HERE
2307 ast_log(LOG_NOTICE,"return (0) when data longer than pattern\n");
2313 * match so far, but ran off the end of the data.
2314 * Depending on what is next, determine match or not.
2316 if (*pattern == '\0' || *pattern == '/') { /* exact match */
2317 #ifdef NEED_DEBUG_HERE
2318 ast_log(LOG_NOTICE,"at end, return (%d) in 'exact match'\n", (mode==E_MATCHMORE) ? 0 : 1);
2320 return (mode == E_MATCHMORE) ? 0 : 1; /* this is a failure for E_MATCHMORE */
2321 } else if (*pattern == '!') { /* early match */
2322 #ifdef NEED_DEBUG_HERE
2323 ast_log(LOG_NOTICE,"at end, return (2) when '!' is matched\n");
2326 } else { /* partial match */
2327 #ifdef NEED_DEBUG_HERE
2328 ast_log(LOG_NOTICE,"at end, return (%d) which deps on E_MATCH\n", (mode == E_MATCH) ? 0 : 1);
2330 return (mode == E_MATCH) ? 0 : 1; /* this is a failure for E_MATCH */
2335 * Wrapper around _extension_match_core() to do performance measurement
2336 * using the profiling code.
2338 static int extension_match_core(const char *pattern, const char *data, enum ext_match_t mode)
2341 static int prof_id = -2; /* marker for 'unallocated' id */
2343 prof_id = ast_add_profile("ext_match", 0);
2344 ast_mark(prof_id, 1);
2345 i = _extension_match_core(pattern, data, mode);
2346 ast_mark(prof_id, 0);
2350 int ast_extension_match(const char *pattern, const char *data)
2352 return extension_match_core(pattern, data, E_MATCH);
2355 int ast_extension_close(const char *pattern, const char *data, int needmore)
2357 if (needmore != E_MATCHMORE && needmore != E_CANMATCH)
2358 ast_log(LOG_WARNING, "invalid argument %d\n", needmore);
2359 return extension_match_core(pattern, data, needmore);
2362 struct fake_context /* this struct is purely for matching in the hashtab */
2365 struct ast_exten *root;
2366 struct ast_hashtab *root_table;
2367 struct match_char *pattern_tree;
2368 struct ast_context *next;
2369 struct ast_include *includes;
2370 struct ast_ignorepat *ignorepats;
2371 const char *registrar;
2373 AST_LIST_HEAD_NOLOCK(, ast_sw) alts;
2374 ast_mutex_t macrolock;
2378 struct ast_context *ast_context_find(const char *name)
2380 struct ast_context *tmp = NULL;
2381 struct fake_context item;
2382 strncpy(item.name,name,256);
2383 ast_rdlock_contexts();
2384 if( contexts_table ) {
2385 tmp = ast_hashtab_lookup(contexts_table,&item);
2387 while ( (tmp = ast_walk_contexts(tmp)) ) {
2388 if (!name || !strcasecmp(name, tmp->name))
2392 ast_unlock_contexts();
2396 #define STATUS_NO_CONTEXT 1
2397 #define STATUS_NO_EXTENSION 2
2398 #define STATUS_NO_PRIORITY 3
2399 #define STATUS_NO_LABEL 4
2400 #define STATUS_SUCCESS 5
2402 static int matchcid(const char *cidpattern, const char *callerid)
2404 /* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
2405 failing to get a number should count as a match, otherwise not */
2407 if (ast_strlen_zero(callerid))
2408 return ast_strlen_zero(cidpattern) ? 1 : 0;
2410 return ast_extension_match(cidpattern, callerid);
2413 struct ast_exten *pbx_find_extension(struct ast_channel *chan,
2414 struct ast_context *bypass, struct pbx_find_info *q,
2415 const char *context, const char *exten, int priority,
2416 const char *label, const char *callerid, enum ext_match_t action)
2419 struct ast_context *tmp = NULL;
2420 struct ast_exten *e = NULL, *eroot = NULL;
2421 struct ast_include *i = NULL;
2422 struct ast_sw *sw = NULL;
2423 struct ast_exten pattern = {NULL, };
2424 struct scoreboard score = {0, };
2425 struct ast_str *tmpdata = NULL;
2427 pattern.label = label;
2428 pattern.priority = priority;
2429 #ifdef NEED_DEBUG_HERE
2430 ast_log(LOG_NOTICE,"Looking for cont/ext/prio/label/action = %s/%s/%d/%s/%d\n", context, exten, priority, label, (int)action);
2433 /* Initialize status if appropriate */
2434 if (q->stacklen == 0) {
2435 q->status = STATUS_NO_CONTEXT;
2438 q->foundcontext = NULL;
2439 } else if (q->stacklen >= AST_PBX_MAX_STACK) {
2440 ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
2444 /* Check first to see if we've already been checked */
2445 for (x = 0; x < q->stacklen; x++) {
2446 if (!strcasecmp(q->incstack[x], context))
2450 if (bypass) /* bypass means we only look there */
2452 else { /* look in contexts */
2453 struct fake_context item;
2454 strncpy(item.name,context,256);
2455 tmp = ast_hashtab_lookup(contexts_table,&item);
2458 while ((tmp = ast_walk_contexts(tmp)) ) {
2459 if (!strcmp(tmp->name, context))
2468 if (q->status < STATUS_NO_EXTENSION)
2469 q->status = STATUS_NO_EXTENSION;
2471 /* Do a search for matching extension */
2474 score.total_specificity = 0;
2476 score.total_length = 0;
2477 if (!tmp->pattern_tree && tmp->root_table)
2479 create_match_char_tree(tmp);
2481 ast_log(LOG_DEBUG,"Tree Created in context %s:\n", context);
2482 log_match_char_tree(tmp->pattern_tree," ");
2486 ast_log(LOG_NOTICE,"The Trie we are searching in:\n");
2487 log_match_char_tree(tmp->pattern_tree, ":: ");
2491 if (!ast_strlen_zero(overrideswitch)) {
2492 char *osw = ast_strdupa(overrideswitch), *name;
2493 struct ast_switch *asw;
2494 ast_switch_f *aswf = NULL;
2498 name = strsep(&osw, "/");
2499 asw = pbx_findswitch(name);
2502 ast_log(LOG_WARNING, "No such switch '%s'\n", name);
2506 if (osw && strchr(osw, '$')) {
2510 if (eval && !(tmpdata = ast_str_thread_get(&switch_data, 512))) {
2511 ast_log(LOG_WARNING, "Can't evaluate overrideswitch?!");
2514 /* Substitute variables now */
2515 pbx_substitute_variables_helper(chan, osw, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
2516 datap = ast_str_buffer(tmpdata);
2521 /* equivalent of extension_match_core() at the switch level */
2522 if (action == E_CANMATCH)
2523 aswf = asw->canmatch;
2524 else if (action == E_MATCHMORE)
2525 aswf = asw->matchmore;
2526 else /* action == E_MATCH */
2532 ast_autoservice_start(chan);
2534 res = aswf(chan, context, exten, priority, callerid, datap);
2536 ast_autoservice_stop(chan);
2539 if (res) { /* Got a match */
2542 q->foundcontext = context;
2543 /* XXX keep status = STATUS_NO_CONTEXT ? */
2549 if (extenpatternmatchnew) {
2550 new_find_extension(exten, &score, tmp->pattern_tree, 0, 0, callerid, label, action);
2551 eroot = score.exten;
2553 if (score.last_char == '!' && action == E_MATCHMORE) {
2554 /* We match an extension ending in '!'.
2555 * The decision in this case is final and is NULL (no match).
2557 #ifdef NEED_DEBUG_HERE
2558 ast_log(LOG_NOTICE,"Returning MATCHMORE NULL with exclamation point.\n");
2563 if (!eroot && (action == E_CANMATCH || action == E_MATCHMORE) && score.canmatch_exten) {
2564 q->status = STATUS_SUCCESS;
2565 #ifdef NEED_DEBUG_HERE
2566 ast_log(LOG_NOTICE,"Returning CANMATCH exten %s\n", score.canmatch_exten->exten);
2568 return score.canmatch_exten;
2571 if ((action == E_MATCHMORE || action == E_CANMATCH) && eroot) {
2573 struct ast_exten *z = trie_find_next_match(score.node);
2575 #ifdef NEED_DEBUG_HERE
2576 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z->exten);
2579 if (score.canmatch_exten) {
2580 #ifdef NEED_DEBUG_HERE
2581 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE canmatchmatch exten %s(%p)\n", score.canmatch_exten->exten, score.canmatch_exten);
2583 return score.canmatch_exten;
2585 #ifdef NEED_DEBUG_HERE
2586 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE next_match exten NULL\n");
2592 #ifdef NEED_DEBUG_HERE
2593 ast_log(LOG_NOTICE,"Returning CANMATCH/MATCHMORE NULL (no next_match)\n");
2595 return NULL; /* according to the code, complete matches are null matches in MATCHMORE mode */
2599 /* found entry, now look for the right priority */
2600 if (q->status < STATUS_NO_PRIORITY)
2601 q->status = STATUS_NO_PRIORITY;
2603 if (action == E_FINDLABEL && label ) {
2604 if (q->status < STATUS_NO_LABEL)
2605 q->status = STATUS_NO_LABEL;
2606 e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
2608 e = ast_hashtab_lookup(eroot->peer_table, &pattern);
2610 if (e) { /* found a valid match */
2611 q->status = STATUS_SUCCESS;
2612 q->foundcontext = context;
2613 #ifdef NEED_DEBUG_HERE
2614 ast_log(LOG_NOTICE,"Returning complete match of exten %s\n", e->exten);
2619 } else { /* the old/current default exten pattern match algorithm */
2621 /* scan the list trying to match extension and CID */
2623 while ( (eroot = ast_walk_context_extensions(tmp, eroot)) ) {
2624 int match = extension_match_core(eroot->exten, exten, action);
2625 /* 0 on fail, 1 on match, 2 on earlymatch */
2627 if (!match || (eroot->matchcid && !matchcid(eroot->cidmatch, callerid)))
2628 continue; /* keep trying */
2629 if (match == 2 && action == E_MATCHMORE) {
2630 /* We match an extension ending in '!'.
2631 * The decision in this case is final and is NULL (no match).
2635 /* found entry, now look for the right priority */
2636 if (q->status < STATUS_NO_PRIORITY)
2637 q->status = STATUS_NO_PRIORITY;
2639 if (action == E_FINDLABEL && label ) {
2640 if (q->status < STATUS_NO_LABEL)
2641 q->status = STATUS_NO_LABEL;
2642 e = ast_hashtab_lookup(eroot->peer_label_table, &pattern);
2644 e = ast_hashtab_lookup(eroot->peer_table, &pattern);
2647 while ( (e = ast_walk_extension_priorities(eroot, e)) ) {
2648 /* Match label or priority */
2649 if (action == E_FINDLABEL) {
2650 if (q->status < STATUS_NO_LABEL)
2651 q->status = STATUS_NO_LABEL;
2652 if (label && e->label && !strcmp(label, e->label))
2653 break; /* found it */
2654 } else if (e->priority == priority) {
2655 break; /* found it */
2656 } /* else keep searching */
2659 if (e) { /* found a valid match */
2660 q->status = STATUS_SUCCESS;
2661 q->foundcontext = context;
2668 /* Check alternative switches */
2669 AST_LIST_TRAVERSE(&tmp->alts, sw, list) {
2670 struct ast_switch *asw = pbx_findswitch(sw->name);
2671 ast_switch_f *aswf = NULL;
2675 ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
2678 /* Substitute variables now */
2681 if (!(tmpdata = ast_str_thread_get(&switch_data, 512))) {
2682 ast_log(LOG_WARNING, "Can't evaluate switch?!");
2685 pbx_substitute_variables_helper(chan, sw->data, ast_str_buffer(tmpdata), ast_str_size(tmpdata));
2688 /* equivalent of extension_match_core() at the switch level */
2689 if (action == E_CANMATCH)
2690 aswf = asw->canmatch;
2691 else if (action == E_MATCHMORE)
2692 aswf = asw->matchmore;
2693 else /* action == E_MATCH */
2695 datap = sw->eval ? ast_str_buffer(tmpdata) : sw->data;
2700 ast_autoservice_start(chan);
2701 res = aswf(chan, context, exten, priority, callerid, datap);
2703 ast_autoservice_stop(chan);
2705 if (res) { /* Got a match */
2708 q->foundcontext = context;
2709 /* XXX keep status = STATUS_NO_CONTEXT ? */
2713 q->incstack[q->stacklen++] = tmp->name; /* Setup the stack */
2714 /* Now try any includes we have in this context */
2715 for (i = tmp->includes; i; i = i->next) {
2716 if (include_valid(i)) {
2717 if ((e = pbx_find_extension(chan, bypass, q, i->rname, exten, priority, label, callerid, action))) {
2718 #ifdef NEED_DEBUG_HERE
2719 ast_log(LOG_NOTICE,"Returning recursive match of %s\n", e->exten);
2731 * \brief extract offset:length from variable name.
2732 * \return 1 if there is a offset:length part, which is
2733 * trimmed off (values go into variables)
2735 static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
2742 for (; *var; var++) {
2746 } else if (*var == ')') {
2748 } else if (*var == ':' && parens == 0) {
2750 sscanf(var, "%d:%d", offset, length);
2751 return 1; /* offset:length valid */
2758 *\brief takes a substring. It is ok to call with value == workspace.
2760 * \param offset < 0 means start from the end of the string and set the beginning
2761 * to be that many characters back.
2762 * \param length is the length of the substring, a value less than 0 means to leave
2763 * that many off the end.
2765 * \param workspace_len
2766 * Always return a copy in workspace.
2768 static char *substring(const char *value, int offset, int length, char *workspace, size_t workspace_len)
2770 char *ret = workspace;
2771 int lr; /* length of the input string after the copy */
2773 ast_copy_string(workspace, value, workspace_len); /* always make a copy */
2775 lr = strlen(ret); /* compute length after copy, so we never go out of the workspace */
2777 /* Quick check if no need to do anything */
2778 if (offset == 0 && length >= lr) /* take the whole string */
2781 if (offset < 0) { /* translate negative offset into positive ones */
2782 offset = lr + offset;
2783 if (offset < 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
2787 /* too large offset result in empty string so we know what to return */
2789 return ret + lr; /* the final '\0' */
2791 ret += offset; /* move to the start position */
2792 if (length >= 0 && length < lr - offset) /* truncate if necessary */
2794 else if (length < 0) {
2795 if (lr > offset - length) /* After we remove from the front and from the rear, is there anything left? */
2796 ret[lr + length - offset] = '\0';
2804 /*! \brief Support for Asterisk built-in variables in the dialplan
2807 - \ref AstVar Channel variables
2808 - \ref AstCauses The HANGUPCAUSE variable
2810 void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
2812 const char not_found = '\0';
2814 const char *s; /* the result */
2816 int i, need_substring;
2817 struct varshead *places[2] = { headp, &globals }; /* list of places where we may look */
2820 ast_channel_lock(c);
2821 places[0] = &c->varshead;
2824 * Make a copy of var because parse_variable_name() modifies the string.
2825 * Then if called directly, we might need to run substring() on the result;
2826 * remember this for later in 'need_substring', 'offset' and 'length'
2828 tmpvar = ast_strdupa(var); /* parse_variable_name modifies the string */
2829 need_substring = parse_variable_name(tmpvar, &offset, &length, &i /* ignored */);
2832 * Look first into predefined variables, then into variable lists.
2833 * Variable 's' points to the result, according to the following rules:
2834 * s == ¬_found (set at the beginning) means that we did not find a
2835 * matching variable and need to look into more places.
2836 * If s != ¬_found, s is a valid result string as follows:
2837 * s = NULL if the variable does not have a value;
2838 * you typically do this when looking for an unset predefined variable.
2839 * s = workspace if the result has been assembled there;
2840 * typically done when the result is built e.g. with an snprintf(),
2841 * so we don't need to do an additional copy.
2842 * s != workspace in case we have a string, that needs to be copied
2843 * (the ast_copy_string is done once for all at the end).
2844 * Typically done when the result is already available in some string.
2846 s = ¬_found; /* default value */
2847 if (c) { /* This group requires a valid channel */
2848 /* Names with common parts are looked up a piece at a time using strncmp. */
2849 if (!strncmp(var, "CALL", 4)) {
2850 if (!strncmp(var + 4, "ING", 3)) {
2851 if (!strcmp(var + 7, "PRES")) { /* CALLINGPRES */
2852 snprintf(workspace, workspacelen, "%d", c->cid.cid_pres);
2854 } else if (!strcmp(var + 7, "ANI2")) { /* CALLINGANI2 */
2855 snprintf(workspace, workspacelen, "%d", c->cid.cid_ani2);
2857 } else if (!strcmp(var + 7, "TON")) { /* CALLINGTON */
2858 snprintf(workspace, workspacelen, "%d", c->cid.cid_ton);
2860 } else if (!strcmp(var + 7, "TNS")) { /* CALLINGTNS */
2861 snprintf(workspace, workspacelen, "%d", c->cid.cid_tns);
2865 } else if (!strcmp(var, "HINT")) {
2866 s = ast_get_hint(workspace, workspacelen, NULL, 0, c, c->context, c->exten) ? workspace : NULL;
2867 } else if (!strcmp(var, "HINTNAME")) {
2868 s = ast_get_hint(NULL, 0, workspace, workspacelen, c, c->context, c->exten) ? workspace : NULL;
2869 } else if (!strcmp(var, "EXTEN")) {