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