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