update doxygen docs to specify authors
[asterisk/asterisk.git] / pbx.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Core PBX routines.
22  *
23  * \author Mark Spencer <markster@digium.com> 
24  */
25
26 #include <sys/types.h>
27 #include <string.h>
28 #include <unistd.h>
29 #include <stdlib.h>
30 #include <stdio.h>
31 #include <ctype.h>
32 #include <errno.h>
33 #include <time.h>
34 #include <sys/time.h>
35
36 #include "asterisk.h"
37
38 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
39
40 #include "asterisk/lock.h"
41 #include "asterisk/cli.h"
42 #include "asterisk/pbx.h"
43 #include "asterisk/channel.h"
44 #include "asterisk/options.h"
45 #include "asterisk/logger.h"
46 #include "asterisk/file.h"
47 #include "asterisk/callerid.h"
48 #include "asterisk/cdr.h"
49 #include "asterisk/config.h"
50 #include "asterisk/term.h"
51 #include "asterisk/manager.h"
52 #include "asterisk/ast_expr.h"
53 #include "asterisk/linkedlists.h"
54 #include "asterisk/say.h"
55 #include "asterisk/utils.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/musiconhold.h"
58 #include "asterisk/app.h"
59 #include "asterisk/devicestate.h"
60 #include "asterisk/compat.h"
61
62 /*!
63  * \note I M P O R T A N T :
64  *
65  *              The speed of extension handling will likely be among the most important
66  * aspects of this PBX.  The switching scheme as it exists right now isn't
67  * terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
68  * of priorities, but a constant search time here would be great ;-) 
69  *
70  */
71
72 #ifdef LOW_MEMORY
73 #define EXT_DATA_SIZE 256
74 #else
75 #define EXT_DATA_SIZE 8192
76 #endif
77
78 #define SWITCH_DATA_LENGTH 256
79
80 #define VAR_BUF_SIZE 4096
81
82 #define VAR_NORMAL              1
83 #define VAR_SOFTTRAN    2
84 #define VAR_HARDTRAN    3
85
86 #define BACKGROUND_SKIP         (1 << 0)
87 #define BACKGROUND_NOANSWER     (1 << 1)
88 #define BACKGROUND_MATCHEXTEN   (1 << 2)
89 #define BACKGROUND_PLAYBACK     (1 << 3)
90
91 AST_APP_OPTIONS(background_opts, {
92         AST_APP_OPTION('s', BACKGROUND_SKIP),
93         AST_APP_OPTION('n', BACKGROUND_NOANSWER),
94         AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN),
95         AST_APP_OPTION('p', BACKGROUND_PLAYBACK),
96 });
97
98 #define WAITEXTEN_MOH           (1 << 0)
99
100 AST_APP_OPTIONS(waitexten_opts, {
101         AST_APP_OPTION_ARG('m', WAITEXTEN_MOH, 1),
102 });
103
104 struct ast_context;
105
106 /*!
107    \brief ast_exten: An extension 
108         The dialplan is saved as a linked list with each context
109         having it's own linked list of extensions - one item per
110         priority.
111 */
112 struct ast_exten {
113         char *exten;                    /*!< Extension name */
114         int matchcid;                   /*!< Match caller id ? */
115         char *cidmatch;                 /*!< Caller id to match for this extension */
116         int priority;                   /*!< Priority */
117         char *label;                    /*!< Label */
118         struct ast_context *parent;     /*!< The context this extension belongs to  */
119         char *app;                      /*!< Application to execute */
120         void *data;                     /*!< Data to use (arguments) */
121         void (*datad)(void *);          /*!< Data destructor */
122         struct ast_exten *peer;         /*!< Next higher priority with our extension */
123         const char *registrar;          /*!< Registrar */
124         struct ast_exten *next;         /*!< Extension with a greater ID */
125         char stuff[0];
126 };
127
128 /*! \brief ast_include: include= support in extensions.conf */
129 struct ast_include {
130         char *name;             
131         char *rname;                            /*!< Context to include */
132         const char *registrar;                  /*!< Registrar */
133         int hastime;                            /*!< If time construct exists */
134         struct ast_timing timing;               /*!< time construct */
135         struct ast_include *next;               /*!< Link them together */
136         char stuff[0];
137 };
138
139 /*! \brief ast_sw: Switch statement in extensions.conf */
140 struct ast_sw {
141         char *name;
142         const char *registrar;                  /*!< Registrar */
143         char *data;                             /*!< Data load */
144         int eval;
145         struct ast_sw *next;                    /*!< Link them together */
146         char *tmpdata;
147         char stuff[0];
148 };
149
150 /*! \brief ast_ignorepat: Ignore patterns in dial plan */
151 struct ast_ignorepat {
152         const char *registrar;
153         struct ast_ignorepat *next;
154         char pattern[0];
155 };
156
157 /*! \brief ast_context: An extension context */
158 struct ast_context {
159         ast_mutex_t lock;                       /*!< A lock to prevent multiple threads from clobbering the context */
160         struct ast_exten *root;                 /*!< The root of the list of extensions */
161         struct ast_context *next;               /*!< Link them together */
162         struct ast_include *includes;           /*!< Include other contexts */
163         struct ast_ignorepat *ignorepats;       /*!< Patterns for which to continue playing dialtone */
164         const char *registrar;                  /*!< Registrar */
165         struct ast_sw *alts;                    /*!< Alternative switches */
166         char name[0];                           /*!< Name of the context */
167 };
168
169
170 /*! \brief ast_app: A registered application */
171 struct ast_app {
172         int (*execute)(struct ast_channel *chan, void *data);
173         const char *synopsis;                   /*!< Synopsis text for 'show applications' */
174         const char *description;                /*!< Description (help text) for 'show application <name>' */
175         struct ast_app *next;                   /*!< Next app in list */
176         char name[0];                           /*!< Name of the application */
177 };
178
179 /*! \brief ast_state_cb: An extension state notify register item */
180 struct ast_state_cb {
181         int id;
182         void *data;
183         ast_state_cb_type callback;
184         struct ast_state_cb *next;
185 };
186             
187 /*! \brief Structure for dial plan hints
188
189   Hints are pointers from an extension in the dialplan to one or
190   more devices (tech/name) */
191 struct ast_hint {
192         struct ast_exten *exten;        /*!< Extension */
193         int laststate;                  /*!< Last known state */
194         struct ast_state_cb *callbacks; /*!< Callback list for this extension */
195         struct ast_hint *next;          /*!< Pointer to next hint in list */
196 };
197
198 int ast_pbx_outgoing_cdr_failed(void);
199
200 static int pbx_builtin_answer(struct ast_channel *, void *);
201 static int pbx_builtin_goto(struct ast_channel *, void *);
202 static int pbx_builtin_hangup(struct ast_channel *, void *);
203 static int pbx_builtin_background(struct ast_channel *, void *);
204 static int pbx_builtin_wait(struct ast_channel *, void *);
205 static int pbx_builtin_waitexten(struct ast_channel *, void *);
206 static int pbx_builtin_resetcdr(struct ast_channel *, void *);
207 static int pbx_builtin_setamaflags(struct ast_channel *, void *);
208 static int pbx_builtin_ringing(struct ast_channel *, void *);
209 static int pbx_builtin_progress(struct ast_channel *, void *);
210 static int pbx_builtin_congestion(struct ast_channel *, void *);
211 static int pbx_builtin_busy(struct ast_channel *, void *);
212 static int pbx_builtin_setglobalvar(struct ast_channel *, void *);
213 static int pbx_builtin_noop(struct ast_channel *, void *);
214 static int pbx_builtin_gotoif(struct ast_channel *, void *);
215 static int pbx_builtin_gotoiftime(struct ast_channel *, void *);
216 static int pbx_builtin_execiftime(struct ast_channel *, void *);
217 static int pbx_builtin_saynumber(struct ast_channel *, void *);
218 static int pbx_builtin_saydigits(struct ast_channel *, void *);
219 static int pbx_builtin_saycharacters(struct ast_channel *, void *);
220 static int pbx_builtin_sayphonetic(struct ast_channel *, void *);
221 int pbx_builtin_setvar(struct ast_channel *, void *);
222 static int pbx_builtin_importvar(struct ast_channel *, void *);
223
224 static struct varshead globals;
225
226 static int autofallthrough = 0;
227
228 AST_MUTEX_DEFINE_STATIC(maxcalllock);
229 static int countcalls = 0;
230
231 AST_MUTEX_DEFINE_STATIC(acflock);               /*!< Lock for the custom function list */
232 static struct ast_custom_function *acf_root = NULL;
233
234 /*! \brief Declaration of builtin applications */
235 static struct pbx_builtin {
236         char name[AST_MAX_APP];
237         int (*execute)(struct ast_channel *chan, void *data);
238         char *synopsis;
239         char *description;
240 } builtins[] = 
241 {
242         /* These applications are built into the PBX core and do not
243            need separate modules */
244
245         { "Answer", pbx_builtin_answer, 
246         "Answer a channel if ringing", 
247         "  Answer([delay]): If the call has not been answered, this application will\n"
248         "answer it. Otherwise, it has no effect on the call. If a delay is specified,\n"
249         "Asterisk will wait this number of milliseconds before answering the call.\n"
250         },
251
252         { "BackGround", pbx_builtin_background,
253         "Play a file while awaiting extension",
254         "  Background(filename1[&filename2...][|options[|langoverride][|context]]):\n"
255         "This application will play the given list of files while waiting for an\n"
256         "extension to be dialed by the calling channel. To continue waiting for digits\n"
257         "after this application has finished playing files, the WaitExten application\n"
258         "should be used. The 'langoverride' option explicity specifies which language\n"
259         "to attempt to use for the requested sound files. If a 'context' is specified,\n"
260         "this is the dialplan context that this application will use when exiting to a\n"
261         "dialed extension."
262         "  If one of the requested sound files does not exist, call processing will be\n"
263         "terminated.\n"
264         "  Options:\n"
265         "    s - causes the playback of the message to be skipped\n"
266         "          if the channel is not in the 'up' state (i.e. it\n"
267         "          hasn't been answered yet.) If this happens, the\n"
268         "          application will return immediately.\n"
269         "    n - don't answer the channel before playing the files\n"
270         "    m - only break if a digit hit matches a one digit\n"
271         "          extension in the destination context\n"
272         },
273
274         { "Busy", pbx_builtin_busy,
275         "Indicate the Busy condition",
276         "  Busy([timeout]): This application will indicate the busy condition to\n"
277         "the calling channel. If the optional timeout is specified, the calling channel\n"
278         "will be hung up after the specified number of seconds. Otherwise, this\n"
279         "application will wait until the calling channel hangs up.\n"
280         },
281
282         { "Congestion", pbx_builtin_congestion,
283         "Indicate the Congestion condition",
284         "  Congestion([timeout]): This application will indicate the congenstion\n"
285         "condition to the calling channel. If the optional timeout is specified, the\n"
286         "calling channel will be hung up after the specified number of seconds.\n"
287         "Otherwise, this application will wait until the calling channel hangs up.\n"
288         },
289
290         { "Goto", pbx_builtin_goto, 
291         "Jump to a particular priority, extension, or context",
292         "  Goto([[context|]extension|]priority): This application will cause the\n"
293         "calling channel to continue dialplan execution at the specified priority.\n"
294         "If no specific extension, or extension and context, are specified, then this\n"
295         "application will jump to the specified priority of the current extension.\n"
296         "  If the attempt to jump to another location in the dialplan is not successful,\n"
297         "then the channel will continue at the next priority of the current extension.\n"
298         },
299
300         { "GotoIf", pbx_builtin_gotoif,
301         "Conditional goto",
302         "  GotoIf(Condition?[label1]:[label2]): This application will cause the calling\n"
303         "channel to jump to the speicifed location in the dialplan based on the\n"
304         "evaluation of the given condition. The channel will continue at 'label1' if the\n"
305         "condition is true, or 'label2' if the condition is false. The labels are\n"
306         "specified in the same syntax that is used with the Goto application.\n"
307         },
308
309         { "GotoIfTime", pbx_builtin_gotoiftime,
310         "Conditional Goto based on the current time",
311         "  GotoIfTime(<times>|<weekdays>|<mdays>|<months>?[[context|]exten|]priority):\n"
312         "This application will have the calling channel jump to the speicified location\n"
313         "int the dialplan if the current time matches the given time specification.\n"
314         "Further information on the time specification can be found in examples\n"
315         "illustrating how to do time-based context includes in the dialplan.\n" 
316         },
317
318         { "ExecIfTime", pbx_builtin_execiftime,
319         "Conditional application execution based on the current time",
320         "  ExecIfTime(<times>|<weekdays>|<mdays>|<months>?appname[|appargs]):\n"
321         "This application will execute the specified dialplan application, with optional\n"
322         "arguments, if the current time matches the given time specification. Further\n"
323         "information on the time speicification can be found in examples illustrating\n"
324         "how to do time-based context includes in the dialplan.\n"
325         },
326         
327         { "Hangup", pbx_builtin_hangup,
328         "Hang up the calling channel",
329         "  Hangup(): This application will hang up the calling channel.\n"
330         },
331
332         { "NoOp", pbx_builtin_noop,
333         "Do Nothing",
334         "  NoOp(): This applicatiion does nothing. However, it is useful for debugging\n"
335         "purposes. Any text that is provided as arguments to this application can be\n"
336         "viewed at the Asterisk CLI. This method can be used to see the evaluations of\n"
337         "variables or functions without having any effect." 
338         },
339
340         { "Progress", pbx_builtin_progress,
341         "Indicate progress",
342         "  Progress(): This application will request that in-band progress information\n"
343         "be provided to the calling channel.\n"
344         },
345
346         { "ResetCDR", pbx_builtin_resetcdr,
347         "Resets the Call Data Record",
348         "  ResetCDR([options]):  This application causes the Call Data Record to be\n"
349         "reset.\n"
350         "  Options:\n"
351         "    w -- Store the current CDR record before resetting it.\n"
352         "    a -- Store any stacked records.\n"
353         "    v -- Save CDR variables.\n"
354         },
355
356         { "Ringing", pbx_builtin_ringing,
357         "Indicate ringing tone",
358         "  Ringing(): This application will request that the channel indicate a ringing\n"
359         "tone to the user.\n"
360         },
361
362         { "SayNumber", pbx_builtin_saynumber,
363         "Say Number",
364         "  SayNumber(digits[,gender]): This application will play the sounds that\n"
365         "correspond to the given number. Optionally, a gender may be specified.\n"
366         "This will use the language that is currently set for the channel. See the\n"
367         "LANGUAGE function for more information on setting the language for the channel.\n"     
368         },
369
370         { "SayDigits", pbx_builtin_saydigits,
371         "Say Digits",
372         "  SayDigits(digits): This application will play the sounds that correspond\n"
373         "to the digits of the given number. This will use the language that is currently\n"
374         "set for the channel. See the LANGUAGE function for more information on setting\n"
375         "the language for the channel.\n"
376         },
377
378         { "SayAlpha", pbx_builtin_saycharacters,
379         "Say Alpha",
380         "  SayAlpha(string): This application will play the sounds that correspond to\n"
381         "the letters of the given string.\n" 
382         },
383
384         { "SayPhonetic", pbx_builtin_sayphonetic,
385         "Say Phonetic",
386         "  SayPhonetic(string): This application will play the sounds from the phonetic\n"
387         "alphabet that correspond to the letters in the given string.\n"
388         },
389
390         { "SetAMAFlags", pbx_builtin_setamaflags,
391         "Set the AMA Flags",
392         "  SetAMAFlags([flag]): This channel will set the channel's AMA Flags for billing\n"
393         "purposes.\n"
394         },
395
396         { "SetGlobalVar", pbx_builtin_setglobalvar,
397         "Set a global variable to a given value",
398         "  SetGlobalVar(variable=value): This application sets a given global variable to\n"
399         "the specified value.\n"
400         },
401
402         { "Set", pbx_builtin_setvar,
403         "Set channel variable(s) or function value(s)",
404         "  Set(name1=value1|name2=value2|..[|options])\n"
405         "This function can be used to set the value of channel variables or dialplan\n"
406         "functions. It will accept up to 24 name/value pairs. When setting variables,\n"
407         "if the variable name is prefixed with _, the variable will be inherited into\n"
408         "channels created from the current channel. If the variable name is prefixed\n"
409         "with __, the variable will be inherited into channels created from the current\n"
410         "channel and all children channels.\n"
411         "  Options:\n" 
412         "    g - Set variable globally instead of on the channel\n"
413         "        (applies only to variables, not functions)\n"
414         },
415
416         { "ImportVar", pbx_builtin_importvar,
417         "Import a variable from a channel into a new variable",
418         "  ImportVar(newvar=channelname|variable): This application imports a variable\n"
419         "from the specified channel (as opposed to the current one) and stores it as\n"
420         "a variable in the current channel (the channel that is calling this\n"
421         "application). Variables created by this application have the same inheritance\n"
422         "properties as those created with the Set application. See the documentation for\n"
423         "Set for more information.\n"
424         },
425
426         { "Wait", pbx_builtin_wait, 
427         "Waits for some time", 
428         "  Wait(seconds): This application waits for a specified number of seconds.\n"
429         "Then, dialplan execution will continue at the next priority.\n"
430         "  Note that the seconds can be passed with fractions of a second. For example,\n"
431         "'1.5' will ask the application to wait for 1.5 seconds.\n" 
432         },
433
434         { "WaitExten", pbx_builtin_waitexten, 
435         "Waits for an extension to be entered", 
436         "  WaitExten([seconds][|options]): This application waits for the user to enter\n"
437         "a new extension for a specified number of seconds.\n"
438         "  Note that the seconds can be passed with fractions of a second. For example,\n"
439         "'1.5' will ask the application to wait for 1.5 seconds.\n" 
440         "  Options:\n"
441         "    m[(x)] - Provide music on hold to the caller while waiting for an extension.\n"
442         "               Optionally, specify the class for music on hold within parenthesis.\n"
443         },
444
445 };
446
447 static struct ast_context *contexts = NULL;
448 AST_MUTEX_DEFINE_STATIC(conlock);               /*!< Lock for the ast_context list */
449 static struct ast_app *apps = NULL;
450 AST_MUTEX_DEFINE_STATIC(applock);               /*!< Lock for the application list */
451
452 struct ast_switch *switches = NULL;
453 AST_MUTEX_DEFINE_STATIC(switchlock);            /*!< Lock for switches */
454
455 AST_MUTEX_DEFINE_STATIC(hintlock);              /*!< Lock for extension state notifys */
456 static int stateid = 1;
457 struct ast_hint *hints = NULL;
458 struct ast_state_cb *statecbs = NULL;
459
460 /* 
461    \note This function is special. It saves the stack so that no matter
462    how many times it is called, it returns to the same place */
463 int pbx_exec(struct ast_channel *c,             /*!< Channel */
464                 struct ast_app *app,            /*!< Application */
465                 void *data,                     /*!< Data for execution */
466                 int newstack)                   /*!< Force stack increment */
467 {
468         int res;
469         
470         char *saved_c_appl;
471         char *saved_c_data;
472         
473         int (*execute)(struct ast_channel *chan, void *data) = app->execute; 
474
475         if (newstack) {
476                 if (c->cdr)
477                         ast_cdr_setapp(c->cdr, app->name, data);
478
479                 /* save channel values */
480                 saved_c_appl= c->appl;
481                 saved_c_data= c->data;
482
483                 c->appl = app->name;
484                 c->data = data;         
485                 res = execute(c, data);
486                 /* restore channel values */
487                 c->appl= saved_c_appl;
488                 c->data= saved_c_data;
489                 return res;
490         } else
491                 ast_log(LOG_WARNING, "You really didn't want to call this function with newstack set to 0\n");
492         return -1;
493 }
494
495
496 /*! Go no deeper than this through includes (not counting loops) */
497 #define AST_PBX_MAX_STACK       128
498
499 #define HELPER_EXISTS 0
500 #define HELPER_SPAWN 1
501 #define HELPER_EXEC 2
502 #define HELPER_CANMATCH 3
503 #define HELPER_MATCHMORE 4
504 #define HELPER_FINDLABEL 5
505
506 /*! \brief Find application handle in linked list
507  */
508 struct ast_app *pbx_findapp(const char *app) 
509 {
510         struct ast_app *tmp;
511
512         if (ast_mutex_lock(&applock)) {
513                 ast_log(LOG_WARNING, "Unable to obtain application lock\n");
514                 return NULL;
515         }
516         for (tmp = apps; tmp; tmp = tmp->next) {
517                 if (!strcasecmp(tmp->name, app))
518                         break;
519         }
520         ast_mutex_unlock(&applock);
521         return tmp;
522 }
523
524 static struct ast_switch *pbx_findswitch(const char *sw)
525 {
526         struct ast_switch *asw;
527
528         if (ast_mutex_lock(&switchlock)) {
529                 ast_log(LOG_WARNING, "Unable to obtain application lock\n");
530                 return NULL;
531         }
532         for (asw = switches; asw; asw = asw->next) {
533                 if (!strcasecmp(asw->name, sw))
534                         break;
535         }
536         ast_mutex_unlock(&switchlock);
537         return asw;
538 }
539
540 static inline int include_valid(struct ast_include *i)
541 {
542         if (!i->hastime)
543                 return 1;
544
545         return ast_check_timing(&(i->timing));
546 }
547
548 static void pbx_destroy(struct ast_pbx *p)
549 {
550         free(p);
551 }
552
553 #define EXTENSION_MATCH_CORE(data,pattern,match) {\
554         /* All patterns begin with _ */\
555         if (pattern[0] != '_') \
556                 return 0;\
557         /* Start optimistic */\
558         match=1;\
559         pattern++;\
560         while(match && *data && *pattern && (*pattern != '/')) {\
561                 while (*data == '-' && (*(data+1) != '\0')) data++;\
562                 switch(toupper(*pattern)) {\
563                 case '[': \
564                 {\
565                         int i,border=0;\
566                         char *where;\
567                         match=0;\
568                         pattern++;\
569                         where=strchr(pattern,']');\
570                         if (where)\
571                                 border=(int)(where-pattern);\
572                         if (!where || border > strlen(pattern)) {\
573                                 ast_log(LOG_WARNING, "Wrong usage of [] in the extension\n");\
574                                 return match;\
575                         }\
576                         for (i=0; i<border; i++) {\
577                                 int res=0;\
578                                 if (i+2<border)\
579                                         if (pattern[i+1]=='-') {\
580                                                 if (*data >= pattern[i] && *data <= pattern[i+2]) {\
581                                                         res=1;\
582                                                 } else {\
583                                                         i+=2;\
584                                                         continue;\
585                                                 }\
586                                         }\
587                                 if (res==1 || *data==pattern[i]) {\
588                                         match = 1;\
589                                         break;\
590                                 }\
591                         }\
592                         pattern+=border;\
593                         break;\
594                 }\
595                 case 'N':\
596                         if ((*data < '2') || (*data > '9'))\
597                                 match=0;\
598                         break;\
599                 case 'X':\
600                         if ((*data < '0') || (*data > '9'))\
601                                 match = 0;\
602                         break;\
603                 case 'Z':\
604                         if ((*data < '1') || (*data > '9'))\
605                                 match = 0;\
606                         break;\
607                 case '.':\
608                         /* Must match */\
609                         return 1;\
610                 case '!':\
611                         /* Early match */\
612                         return 2;\
613                 case ' ':\
614                 case '-':\
615                         /* Ignore these characters */\
616                         data--;\
617                         break;\
618                 default:\
619                         if (*data != *pattern)\
620                                 match =0;\
621                 }\
622                 data++;\
623                 pattern++;\
624         }\
625         /* If we ran off the end of the data and the pattern ends in '!', match */\
626         if (match && !*data && (*pattern == '!'))\
627                 return 2;\
628 }
629
630 int ast_extension_match(const char *pattern, const char *data)
631 {
632         int match;
633         /* If they're the same return */
634         if (!strcmp(pattern, data))
635                 return 1;
636         EXTENSION_MATCH_CORE(data,pattern,match);
637         /* Must be at the end of both */
638         if (*data || (*pattern && (*pattern != '/')))
639                 match = 0;
640         return match;
641 }
642
643 int ast_extension_close(const char *pattern, const char *data, int needmore)
644 {
645         int match;
646         /* If "data" is longer, it can'be a subset of pattern unless
647            pattern is a pattern match */
648         if ((strlen(pattern) < strlen(data)) && (pattern[0] != '_'))
649                 return 0;
650         
651         if ((ast_strlen_zero((char *)data) || !strncasecmp(pattern, data, strlen(data))) && 
652                 (!needmore || (strlen(pattern) > strlen(data)))) {
653                 return 1;
654         }
655         EXTENSION_MATCH_CORE(data,pattern,match);
656         /* If there's more or we don't care about more, or if it's a possible early match, 
657            return non-zero; otherwise it's a miss */
658         if (!needmore || *pattern || match == 2) {
659                 return match;
660         } else
661                 return 0;
662 }
663
664 struct ast_context *ast_context_find(const char *name)
665 {
666         struct ast_context *tmp;
667         ast_mutex_lock(&conlock);
668         if (name) {
669                 for (tmp = contexts; tmp; tmp = tmp->next) {
670                         if (!strcasecmp(name, tmp->name))
671                                 break;
672                 }
673         } else
674                 tmp = contexts;
675         ast_mutex_unlock(&conlock);
676         return tmp;
677 }
678
679 #define STATUS_NO_CONTEXT       1
680 #define STATUS_NO_EXTENSION     2
681 #define STATUS_NO_PRIORITY      3
682 #define STATUS_NO_LABEL         4
683 #define STATUS_SUCCESS          5
684
685 static int matchcid(const char *cidpattern, const char *callerid)
686 {
687         int failresult;
688         
689         /* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
690            failing to get a number should count as a match, otherwise not */
691
692         if (!ast_strlen_zero(cidpattern))
693                 failresult = 0;
694         else
695                 failresult = 1;
696
697         if (!callerid)
698                 return failresult;
699
700         return ast_extension_match(cidpattern, callerid);
701 }
702
703 static struct ast_exten *pbx_find_extension(struct ast_channel *chan, struct ast_context *bypass, const char *context, const char *exten, int priority, const char *label, const char *callerid, int action, char *incstack[], int *stacklen, int *status, struct ast_switch **swo, char **data, const char **foundcontext)
704 {
705         int x, res;
706         struct ast_context *tmp;
707         struct ast_exten *e, *eroot;
708         struct ast_include *i;
709         struct ast_sw *sw;
710         struct ast_switch *asw;
711
712         /* Initialize status if appropriate */
713         if (!*stacklen) {
714                 *status = STATUS_NO_CONTEXT;
715                 *swo = NULL;
716                 *data = NULL;
717         }
718         /* Check for stack overflow */
719         if (*stacklen >= AST_PBX_MAX_STACK) {
720                 ast_log(LOG_WARNING, "Maximum PBX stack exceeded\n");
721                 return NULL;
722         }
723         /* Check first to see if we've already been checked */
724         for (x = 0; x < *stacklen; x++) {
725                 if (!strcasecmp(incstack[x], context))
726                         return NULL;
727         }
728         if (bypass)
729                 tmp = bypass;
730         else
731                 tmp = contexts;
732         for (; tmp; tmp = tmp->next) {
733                 /* Match context */
734                 if (bypass || !strcmp(tmp->name, context)) {
735                         struct ast_exten *earlymatch = NULL;
736
737                         if (*status < STATUS_NO_EXTENSION)
738                                 *status = STATUS_NO_EXTENSION;
739                         for (eroot = tmp->root; eroot; eroot = eroot->next) {
740                                 int match = 0;
741                                 /* Match extension */
742                                 if ((((action != HELPER_MATCHMORE) && ast_extension_match(eroot->exten, exten)) ||
743                                      ((action == HELPER_CANMATCH) && (ast_extension_close(eroot->exten, exten, 0))) ||
744                                      ((action == HELPER_MATCHMORE) && (match = ast_extension_close(eroot->exten, exten, 1)))) &&
745                                      (!eroot->matchcid || matchcid(eroot->cidmatch, callerid))) {
746
747                                         if (action == HELPER_MATCHMORE && match == 2 && !earlymatch) {
748                                                 /* It matched an extension ending in a '!' wildcard
749                                                    So ignore it for now, unless there's a better match */
750                                                 earlymatch = eroot;
751                                         } else {
752                                                 if (*status < STATUS_NO_PRIORITY)
753                                                         *status = STATUS_NO_PRIORITY;
754                                                 for (e = eroot; e; e = e->peer) {
755                                                         /* Match priority */
756                                                         if (action == HELPER_FINDLABEL) {
757                                                                 if (*status < STATUS_NO_LABEL)
758                                                                         *status = STATUS_NO_LABEL;
759                                                                 if (label && e->label && !strcmp(label, e->label)) {
760                                                                         *status = STATUS_SUCCESS;
761                                                                         *foundcontext = context;
762                                                                         return e;
763                                                                 }
764                                                         } else if (e->priority == priority) {
765                                                                 *status = STATUS_SUCCESS;
766                                                                 *foundcontext = context;
767                                                                 return e;
768                                                         }
769                                                 }
770                                         }
771                                 }
772                         }
773                         if (earlymatch) {
774                                 /* Bizarre logic for HELPER_MATCHMORE. We return zero to break out 
775                                    of the loop waiting for more digits, and _then_ match (normally)
776                                    the extension we ended up with. We got an early-matching wildcard
777                                    pattern, so return NULL to break out of the loop. */
778                                 return NULL;
779                         }
780                         /* Check alternative switches */
781                         for (sw = tmp->alts; sw; sw = sw->next) {
782                                 if ((asw = pbx_findswitch(sw->name))) {
783                                         /* Substitute variables now */
784                                         if (sw->eval) 
785                                                 pbx_substitute_variables_helper(chan, sw->data, sw->tmpdata, SWITCH_DATA_LENGTH - 1);
786                                         if (action == HELPER_CANMATCH)
787                                                 res = asw->canmatch ? asw->canmatch(chan, context, exten, priority, callerid, sw->eval ? sw->tmpdata : sw->data) : 0;
788                                         else if (action == HELPER_MATCHMORE)
789                                                 res = asw->matchmore ? asw->matchmore(chan, context, exten, priority, callerid, sw->eval ? sw->tmpdata : sw->data) : 0;
790                                         else
791                                                 res = asw->exists ? asw->exists(chan, context, exten, priority, callerid, sw->eval ? sw->tmpdata : sw->data) : 0;
792                                         if (res) {
793                                                 /* Got a match */
794                                                 *swo = asw;
795                                                 *data = sw->eval ? sw->tmpdata : sw->data;
796                                                 *foundcontext = context;
797                                                 return NULL;
798                                         }
799                                 } else {
800                                         ast_log(LOG_WARNING, "No such switch '%s'\n", sw->name);
801                                 }
802                         }
803                         /* Setup the stack */
804                         incstack[*stacklen] = tmp->name;
805                         (*stacklen)++;
806                         /* Now try any includes we have in this context */
807                         for (i = tmp->includes; i; i = i->next) {
808                                 if (include_valid(i)) {
809                                         if ((e = pbx_find_extension(chan, bypass, i->rname, exten, priority, label, callerid, action, incstack, stacklen, status, swo, data, foundcontext))) 
810                                                 return e;
811                                         if (*swo) 
812                                                 return NULL;
813                                 }
814                         }
815                         break;
816                 }
817         }
818         return NULL;
819 }
820
821 /* Note that it's negative -- that's important later. */
822 #define DONT_HAVE_LENGTH        0x80000000
823
824 static int parse_variable_name(char *var, int *offset, int *length, int *isfunc)
825 {
826         char *varchar, *offsetchar = NULL;
827         int parens=0;
828
829         *offset = 0;
830         *length = DONT_HAVE_LENGTH;
831         *isfunc = 0;
832         for (varchar = var; *varchar; varchar++) {
833                 switch (*varchar) {
834                 case '(':
835                         (*isfunc)++;
836                         parens++;
837                         break;
838                 case ')':
839                         parens--;
840                         break;
841                 case ':':
842                         if (parens == 0) {
843                                 offsetchar = varchar + 1;
844                                 *varchar = '\0';
845                                 goto pvn_endfor;
846                         }
847                 }
848         }
849 pvn_endfor:
850         if (offsetchar) {
851                 sscanf(offsetchar, "%d:%d", offset, length);
852                 return 1;
853         } else {
854                 return 0;
855         }
856 }
857
858 static char *substring(char *value, int offset, int length, char *workspace, size_t workspace_len)
859 {
860         char *ret = workspace;
861
862         /* No need to do anything */
863         if (offset == 0 && length==-1) {
864                 return value;
865         }
866
867         ast_copy_string(workspace, value, workspace_len);
868
869         if (abs(offset) > strlen(ret)) {        /* Offset beyond string */
870                 if (offset >= 0) 
871                         offset = strlen(ret);
872                 else 
873                         offset =- strlen(ret);  
874         }
875
876         /* Detect too-long length */
877         if ((offset < 0 && length > -offset) || (offset >= 0 && offset+length > strlen(ret))) {
878                 if (offset >= 0) 
879                         length = strlen(ret)-offset;
880                 else 
881                         length = strlen(ret)+offset;
882         }
883
884         /* Bounce up to the right offset */
885         if (offset >= 0)
886                 ret += offset;
887         else
888                 ret += strlen(ret)+offset;
889
890         /* Chop off at the requisite length */
891         if (length >= 0)
892                 ret[length] = '\0';
893
894         return ret;
895 }
896
897 /*! \brief  pbx_retrieve_variable: Support for Asterisk built-in variables and
898       functions in the dialplan
899   ---*/
900 void pbx_retrieve_variable(struct ast_channel *c, const char *var, char **ret, char *workspace, int workspacelen, struct varshead *headp)
901 {
902         char tmpvar[80];
903         time_t thistime;
904         struct tm brokentime;
905         int offset, offset2, isfunc;
906         struct ast_var_t *variables;
907         char *deprecated = NULL;
908
909         if (c) 
910                 headp=&c->varshead;
911         *ret=NULL;
912         ast_copy_string(tmpvar, var, sizeof(tmpvar));
913         if (parse_variable_name(tmpvar, &offset, &offset2, &isfunc)) {
914                 pbx_retrieve_variable(c, tmpvar, ret, workspace, workspacelen, headp);
915                 if (!(*ret)) 
916                         return;
917                 *ret = substring(*ret, offset, offset2, workspace, workspacelen);
918         } else if (c && !strncmp(var, "CALL", 4)) {
919                 if (!strncmp(var + 4, "ER", 2)) {
920                         if (!strncmp(var + 6, "ID", 2)) {
921                                 if (!var[8]) {                  /* CALLERID */
922                                         if (c->cid.cid_num) {
923                                                 if (c->cid.cid_name) {
924                                                         snprintf(workspace, workspacelen, "\"%s\" <%s>", c->cid.cid_name, c->cid.cid_num);
925                                                 } else {
926                                                         ast_copy_string(workspace, c->cid.cid_num, workspacelen);
927                                                 }
928                                                 *ret = workspace;
929                                         } else if (c->cid.cid_name) {
930                                                 ast_copy_string(workspace, c->cid.cid_name, workspacelen);
931                                                 *ret = workspace;
932                                         } else
933                                                 *ret = NULL;
934                                         deprecated = "CALLERID(all)";
935                                 } else if (!strcmp(var + 8, "NUM")) {
936                                         /* CALLERIDNUM */
937                                         if (c->cid.cid_num) {
938                                                 ast_copy_string(workspace, c->cid.cid_num, workspacelen);
939                                                 *ret = workspace;
940                                         } else
941                                                 *ret = NULL;
942                                         deprecated = "CALLERID(num)";
943                                 } else if (!strcmp(var + 8, "NAME")) {
944                                         /* CALLERIDNAME */
945                                         if (c->cid.cid_name) {
946                                                 ast_copy_string(workspace, c->cid.cid_name, workspacelen);
947                                                 *ret = workspace;
948                                         } else
949                                                 *ret = NULL;
950                                         deprecated = "CALLERID(name)";
951                                 } else
952                                         goto icky;
953                         } else if (!strcmp(var + 6, "ANI")) {
954                                 /* CALLERANI */
955                                 if (c->cid.cid_ani) {
956                                         ast_copy_string(workspace, c->cid.cid_ani, workspacelen);
957                                         *ret = workspace;
958                                 } else
959                                         *ret = NULL;
960                                 deprecated = "CALLERID(ANI)";
961                         } else
962                                 goto icky;
963                 } else if (!strncmp(var + 4, "ING", 3)) {
964                         if (!strcmp(var + 7, "PRES")) {
965                                 /* CALLINGPRES */
966                                 snprintf(workspace, workspacelen, "%d", c->cid.cid_pres);
967                                 *ret = workspace;
968                         } else if (!strcmp(var + 7, "ANI2")) {
969                                 /* CALLINGANI2 */
970                                 snprintf(workspace, workspacelen, "%d", c->cid.cid_ani2);
971                                 *ret = workspace;
972                         } else if (!strcmp(var + 7, "TON")) {
973                                 /* CALLINGTON */
974                                 snprintf(workspace, workspacelen, "%d", c->cid.cid_ton);
975                                 *ret = workspace;
976                         } else if (!strcmp(var + 7, "TNS")) {
977                                 /* CALLINGTNS */
978                                 snprintf(workspace, workspacelen, "%d", c->cid.cid_tns);
979                                 *ret = workspace;
980                         } else
981                                 goto icky;
982                 } else
983                         goto icky;
984         } else if (c && !strcmp(var, "DNID")) {
985                 if (c->cid.cid_dnid) {
986                         ast_copy_string(workspace, c->cid.cid_dnid, workspacelen);
987                         *ret = workspace;
988                 } else
989                         *ret = NULL;
990                 deprecated = "CALLERID(DNID)";
991         } else if (c && !strcmp(var, "HINT")) {
992                 if (!ast_get_hint(workspace, workspacelen, NULL, 0, c, c->context, c->exten))
993                         *ret = NULL;
994                 else
995                         *ret = workspace;
996         } else if (c && !strcmp(var, "HINTNAME")) {
997                 if (!ast_get_hint(NULL, 0, workspace, workspacelen, c, c->context, c->exten))
998                         *ret = NULL;
999                 else
1000                         *ret = workspace;
1001         } else if (c && !strcmp(var, "EXTEN")) {
1002                 ast_copy_string(workspace, c->exten, workspacelen);
1003                 *ret = workspace;
1004         } else if (c && !strcmp(var, "RDNIS")) {
1005                 if (c->cid.cid_rdnis) {
1006                         ast_copy_string(workspace, c->cid.cid_rdnis, workspacelen);
1007                         *ret = workspace;
1008                 } else
1009                         *ret = NULL;
1010                 deprecated = "CALLERID(RDNIS)";
1011         } else if (c && !strcmp(var, "CONTEXT")) {
1012                 ast_copy_string(workspace, c->context, workspacelen);
1013                 *ret = workspace;
1014         } else if (c && !strcmp(var, "PRIORITY")) {
1015                 snprintf(workspace, workspacelen, "%d", c->priority);
1016                 *ret = workspace;
1017         } else if (c && !strcmp(var, "CHANNEL")) {
1018                 ast_copy_string(workspace, c->name, workspacelen);
1019                 *ret = workspace;
1020         } else if (!strcmp(var, "EPOCH")) {
1021                 snprintf(workspace, workspacelen, "%u",(int)time(NULL));
1022                 *ret = workspace;
1023         } else if (!strcmp(var, "DATETIME")) {
1024                 thistime=time(NULL);
1025                 localtime_r(&thistime, &brokentime);
1026                 snprintf(workspace, workspacelen, "%02d%02d%04d-%02d:%02d:%02d",
1027                         brokentime.tm_mday,
1028                         brokentime.tm_mon+1,
1029                         brokentime.tm_year+1900,
1030                         brokentime.tm_hour,
1031                         brokentime.tm_min,
1032                         brokentime.tm_sec
1033                 );
1034                 *ret = workspace;
1035                 deprecated = "STRFTIME(${EPOCH},,\%m\%d\%Y-\%H:\%M:\%S)";
1036         } else if (!strcmp(var, "TIMESTAMP")) {
1037                 thistime=time(NULL);
1038                 localtime_r(&thistime, &brokentime);
1039                 /* 20031130-150612 */
1040                 snprintf(workspace, workspacelen, "%04d%02d%02d-%02d%02d%02d",
1041                         brokentime.tm_year+1900,
1042                         brokentime.tm_mon+1,
1043                         brokentime.tm_mday,
1044                         brokentime.tm_hour,
1045                         brokentime.tm_min,
1046                         brokentime.tm_sec
1047                 );
1048                 *ret = workspace;
1049                 deprecated = "STRFTIME(${EPOCH},,\%Y\%m\%d-\%H\%M\%S)";
1050         } else if (c && !strcmp(var, "UNIQUEID")) {
1051                 snprintf(workspace, workspacelen, "%s", c->uniqueid);
1052                 *ret = workspace;
1053         } else if (c && !strcmp(var, "HANGUPCAUSE")) {
1054                 snprintf(workspace, workspacelen, "%d", c->hangupcause);
1055                 *ret = workspace;
1056         } else if (c && !strcmp(var, "ACCOUNTCODE")) {
1057                 ast_copy_string(workspace, c->accountcode, workspacelen);
1058                 *ret = workspace;
1059                 deprecated = "CDR(accountcode)";
1060         } else if (c && !strcmp(var, "LANGUAGE")) {
1061                 ast_copy_string(workspace, c->language, workspacelen);
1062                 *ret = workspace;
1063                 deprecated = "LANGUAGE()";
1064         } else {
1065 icky:
1066                 if (headp) {
1067                         AST_LIST_TRAVERSE(headp,variables,entries) {
1068 #if 0
1069                                 ast_log(LOG_WARNING,"Comparing variable '%s' with '%s'\n",var,ast_var_name(variables));
1070 #endif
1071                                 if (strcasecmp(ast_var_name(variables),var)==0) {
1072                                         const char *s = ast_var_value(variables);
1073                                         if (s) {
1074                                                 ast_copy_string(workspace, s, workspacelen);
1075                                                 *ret = workspace;
1076                                         }
1077                                         break;
1078                                 }
1079                         }
1080                 }
1081                 if (!(*ret)) {
1082                         /* Try globals */
1083                         AST_LIST_TRAVERSE(&globals,variables,entries) {
1084 #if 0
1085                                 ast_log(LOG_WARNING,"Comparing variable '%s' with '%s'\n",var,ast_var_name(variables));
1086 #endif
1087                                 if (strcasecmp(ast_var_name(variables),var)==0) {
1088                                         const char *s = ast_var_value(variables);
1089                                         if (s) {
1090                                                 ast_copy_string(workspace, s, workspacelen);
1091                                                 *ret = workspace;
1092                                         }
1093                                 }
1094                         }
1095                 }
1096         }
1097         if (deprecated) {
1098                 ast_log(LOG_WARNING, "${%s} is deprecated.  Please use ${%s} instead.\n", var, deprecated);
1099         }
1100 }
1101
1102 /*! \brief CLI function to show installed custom functions 
1103     \addtogroup CLI_functions
1104  */
1105 static int handle_show_functions(int fd, int argc, char *argv[])
1106 {
1107         struct ast_custom_function *acf;
1108         int count_acf = 0;
1109         int print_acf = 0;
1110         int like = 0;
1111
1112         if (argc == 4 && (!strcmp(argv[2], "like")) ) {
1113                 like = 1;
1114         } else if (argc != 2) {
1115                 return RESULT_SHOWUSAGE;
1116         }
1117
1118         ast_cli(fd, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like ? "Matching" : "Installed");
1119         
1120         for (acf = acf_root ; acf; acf = acf->next) {
1121                 print_acf = 0;
1122                 if (like) {
1123                         if (strstr(acf->name, argv[3])) {
1124                                 print_acf = 1;
1125                                 count_acf++;
1126                         }
1127                 } else {
1128                         print_acf = 1;
1129                         count_acf++;
1130                 } 
1131
1132                 if (print_acf) {
1133                         ast_cli(fd, "%-20.20s  %-35.35s  %s\n", acf->name, acf->syntax, acf->synopsis);
1134                 }
1135         }
1136
1137         ast_cli(fd, "%d %scustom functions installed.\n", count_acf, like ? "matching " : "");
1138
1139         return 0;
1140 }
1141
1142 static int handle_show_function(int fd, int argc, char *argv[])
1143 {
1144         struct ast_custom_function *acf;
1145         /* Maximum number of characters added by terminal coloring is 22 */
1146         char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40];
1147         char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL;
1148         char stxtitle[40], *syntax = NULL;
1149         int synopsis_size, description_size, syntax_size;
1150
1151         if (argc < 3) return RESULT_SHOWUSAGE;
1152
1153         if (!(acf = ast_custom_function_find(argv[2]))) {
1154                 ast_cli(fd, "No function by that name registered.\n");
1155                 return RESULT_FAILURE;
1156
1157         }
1158
1159         if (acf->synopsis)
1160                 synopsis_size = strlen(acf->synopsis) + 23;
1161         else
1162                 synopsis_size = strlen("Not available") + 23;
1163         synopsis = alloca(synopsis_size);
1164         
1165         if (acf->desc)
1166                 description_size = strlen(acf->desc) + 23;
1167         else
1168                 description_size = strlen("Not available") + 23;
1169         description = alloca(description_size);
1170
1171         if (acf->syntax)
1172                 syntax_size = strlen(acf->syntax) + 23;
1173         else
1174                 syntax_size = strlen("Not available") + 23;
1175         syntax = alloca(syntax_size);
1176
1177         snprintf(info, 64 + AST_MAX_APP, "\n  -= Info about function '%s' =- \n\n", acf->name);
1178         term_color(infotitle, info, COLOR_MAGENTA, 0, 64 + AST_MAX_APP + 22);
1179         term_color(stxtitle, "[Syntax]\n", COLOR_MAGENTA, 0, 40);
1180         term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
1181         term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
1182         term_color(syntax,
1183                    acf->syntax ? acf->syntax : "Not available",
1184                    COLOR_CYAN, 0, syntax_size);
1185         term_color(synopsis,
1186                    acf->synopsis ? acf->synopsis : "Not available",
1187                    COLOR_CYAN, 0, synopsis_size);
1188         term_color(description,
1189                    acf->desc ? acf->desc : "Not available",
1190                    COLOR_CYAN, 0, description_size);
1191         
1192         ast_cli(fd,"%s%s%s\n\n%s%s\n\n%s%s\n", infotitle, stxtitle, syntax, syntitle, synopsis, destitle, description);
1193
1194         return RESULT_SUCCESS;
1195 }
1196
1197 static char *complete_show_function(char *line, char *word, int pos, int state)
1198 {
1199         struct ast_custom_function *acf;
1200         char *ret = NULL;
1201         int which = 0;
1202         int wordlen = strlen(word);
1203
1204         /* try to lock functions list ... */
1205         if (ast_mutex_lock(&acflock)) {
1206                 ast_log(LOG_ERROR, "Unable to lock function list\n");
1207                 return NULL;
1208         }
1209
1210         for (acf = acf_root; acf; acf = acf->next) {
1211                 if (!strncasecmp(word, acf->name, wordlen)) {
1212                         if (++which > state) {
1213                                 ret = strdup(acf->name);
1214                                 break;
1215                         }
1216                 }
1217         }
1218
1219         ast_mutex_unlock(&acflock);
1220
1221         return ret; 
1222 }
1223
1224 struct ast_custom_function* ast_custom_function_find(const char *name) 
1225 {
1226         struct ast_custom_function *acfptr;
1227
1228         /* try to lock functions list ... */
1229         if (ast_mutex_lock(&acflock)) {
1230                 ast_log(LOG_ERROR, "Unable to lock function list\n");
1231                 return NULL;
1232         }
1233
1234         for (acfptr = acf_root; acfptr; acfptr = acfptr->next) {
1235                 if (!strcmp(name, acfptr->name)) {
1236                         break;
1237                 }
1238         }
1239
1240         ast_mutex_unlock(&acflock);
1241         
1242         return acfptr;
1243 }
1244
1245 int ast_custom_function_unregister(struct ast_custom_function *acf) 
1246 {
1247         struct ast_custom_function *acfptr, *lastacf = NULL;
1248         int res = -1;
1249
1250         if (!acf)
1251                 return -1;
1252
1253         /* try to lock functions list ... */
1254         if (ast_mutex_lock(&acflock)) {
1255                 ast_log(LOG_ERROR, "Unable to lock function list\n");
1256                 return -1;
1257         }
1258
1259         for (acfptr = acf_root; acfptr; acfptr = acfptr->next) {
1260                 if (acfptr == acf) {
1261                         if (lastacf) {
1262                                 lastacf->next = acf->next;
1263                         } else {
1264                                 acf_root = acf->next;
1265                         }
1266                         res = 0;
1267                         break;
1268                 }
1269                 lastacf = acfptr;
1270         }
1271
1272         ast_mutex_unlock(&acflock);
1273
1274         if (!res && (option_verbose > 1))
1275                 ast_verbose(VERBOSE_PREFIX_2 "Unregistered custom function %s\n", acf->name);
1276
1277         return res;
1278 }
1279
1280 int ast_custom_function_register(struct ast_custom_function *acf) 
1281 {
1282         struct ast_custom_function *cur, *last = NULL;
1283         int found = 0;
1284
1285         if (!acf)
1286                 return -1;
1287
1288         /* try to lock functions list ... */
1289         if (ast_mutex_lock(&acflock)) {
1290                 ast_log(LOG_ERROR, "Unable to lock function list. Failed registering function %s\n", acf->name);
1291                 return -1;
1292         }
1293
1294         if (ast_custom_function_find(acf->name)) {
1295                 ast_log(LOG_ERROR, "Function %s already registered.\n", acf->name);
1296                 ast_mutex_unlock(&acflock);
1297                 return -1;
1298         }
1299
1300         for (cur = acf_root; cur; cur = cur->next) {
1301                 if (strcmp(acf->name, cur->name) < 0) {
1302                         found = 1;
1303                         if (last) {
1304                                 acf->next = cur;
1305                                 last->next = acf;
1306                         } else {
1307                                 acf->next = acf_root;
1308                                 acf_root = acf;
1309                         }
1310                         break;
1311                 }
1312                 last = cur;
1313         }
1314
1315         /* Wasn't before anything else, put it at the end */
1316         if (!found) {
1317                 if (last)
1318                         last->next = acf;
1319                 else
1320                         acf_root = acf;
1321                 acf->next = NULL;
1322         }
1323
1324         ast_mutex_unlock(&acflock);
1325
1326         if (option_verbose > 1)
1327                 ast_verbose(VERBOSE_PREFIX_2 "Registered custom function %s\n", acf->name);
1328
1329         return 0;
1330 }
1331
1332 char *ast_func_read(struct ast_channel *chan, const char *in, char *workspace, size_t len)
1333 {
1334         char *args = NULL, *function, *p;
1335         char *ret = "0";
1336         struct ast_custom_function *acfptr;
1337
1338         function = ast_strdupa(in);
1339         if (!function) {
1340                 ast_log(LOG_ERROR, "Out of memory\n");
1341                 return ret;
1342         }
1343         if ((args = strchr(function, '('))) {
1344                 *args = '\0';
1345                 args++;
1346                 if ((p = strrchr(args, ')'))) {
1347                         *p = '\0';
1348                 } else {
1349                         ast_log(LOG_WARNING, "Can't find trailing parenthesis?\n");
1350                 }
1351         } else {
1352                 ast_log(LOG_WARNING, "Function doesn't contain parentheses.  Assuming null argument.\n");
1353         }
1354
1355         if ((acfptr = ast_custom_function_find(function))) {
1356                 /* run the custom function */
1357                 if (acfptr->read) {
1358                         return acfptr->read(chan, function, args, workspace, len);
1359                 } else {
1360                         ast_log(LOG_ERROR, "Function %s cannot be read\n", function);
1361                 }
1362         } else {
1363                 ast_log(LOG_ERROR, "Function %s not registered\n", function);
1364         }
1365         return ret;
1366 }
1367
1368 void ast_func_write(struct ast_channel *chan, const char *in, const char *value)
1369 {
1370         char *args = NULL, *function, *p;
1371         struct ast_custom_function *acfptr;
1372
1373         function = ast_strdupa(in);
1374         if (!function) {
1375                 ast_log(LOG_ERROR, "Out of memory\n");
1376                 return;
1377         }
1378         if ((args = strchr(function, '('))) {
1379                 *args = '\0';
1380                 args++;
1381                 if ((p = strrchr(args, ')'))) {
1382                         *p = '\0';
1383                 } else {
1384                         ast_log(LOG_WARNING, "Can't find trailing parenthesis?\n");
1385                 }
1386         } else {
1387                 ast_log(LOG_WARNING, "Function doesn't contain parentheses.  Assuming null argument.\n");
1388         }
1389
1390         if ((acfptr = ast_custom_function_find(function))) {
1391                 /* run the custom function */
1392                 if (acfptr->write) {
1393                         acfptr->write(chan, function, args, value);
1394                 } else {
1395                         ast_log(LOG_ERROR, "Function %s is read-only, it cannot be written to\n", function);
1396                 }
1397         } else {
1398                 ast_log(LOG_ERROR, "Function %s not registered\n", function);
1399         }
1400 }
1401
1402 static void pbx_substitute_variables_helper_full(struct ast_channel *c, struct varshead *headp, const char *cp1, char *cp2, int count)
1403 {
1404         char *cp4;
1405         const char *tmp, *whereweare;
1406         int length, offset, offset2, isfunction;
1407         char *workspace = NULL;
1408         char *ltmp = NULL, *var = NULL;
1409         char *nextvar, *nextexp, *nextthing;
1410         char *vars, *vare;
1411         int pos, brackets, needsub, len;
1412         
1413         /* Substitutes variables into cp2, based on string cp1, and assuming cp2 to be
1414            zero-filled */
1415         whereweare=tmp=cp1;
1416         while(!ast_strlen_zero(whereweare) && count) {
1417                 /* Assume we're copying the whole remaining string */
1418                 pos = strlen(whereweare);
1419                 nextvar = NULL;
1420                 nextexp = NULL;
1421                 nextthing = strchr(whereweare, '$');
1422                 if (nextthing) {
1423                         switch(nextthing[1]) {
1424                         case '{':
1425                                 nextvar = nextthing;
1426                                 pos = nextvar - whereweare;
1427                                 break;
1428                         case '[':
1429                                 nextexp = nextthing;
1430                                 pos = nextexp - whereweare;
1431                                 break;
1432                         }
1433                 }
1434
1435                 if (pos) {
1436                         /* Can't copy more than 'count' bytes */
1437                         if (pos > count)
1438                                 pos = count;
1439                         
1440                         /* Copy that many bytes */
1441                         memcpy(cp2, whereweare, pos);
1442                         
1443                         count -= pos;
1444                         cp2 += pos;
1445                         whereweare += pos;
1446                 }
1447                 
1448                 if (nextvar) {
1449                         /* We have a variable.  Find the start and end, and determine
1450                            if we are going to have to recursively call ourselves on the
1451                            contents */
1452                         vars = vare = nextvar + 2;
1453                         brackets = 1;
1454                         needsub = 0;
1455
1456                         /* Find the end of it */
1457                         while(brackets && *vare) {
1458                                 if ((vare[0] == '$') && (vare[1] == '{')) {
1459                                         needsub++;
1460                                         brackets++;
1461                                 } else if (vare[0] == '}') {
1462                                         brackets--;
1463                                 } else if ((vare[0] == '$') && (vare[1] == '['))
1464                                         needsub++;
1465                                 vare++;
1466                         }
1467                         if (brackets)
1468                                 ast_log(LOG_NOTICE, "Error in extension logic (missing '}')\n");
1469                         len = vare - vars - 1;
1470
1471                         /* Skip totally over variable string */
1472                         whereweare += (len + 3);
1473
1474                         if (!var)
1475                                 var = alloca(VAR_BUF_SIZE);
1476
1477                         /* Store variable name (and truncate) */
1478                         ast_copy_string(var, vars, len + 1);
1479
1480                         /* Substitute if necessary */
1481                         if (needsub) {
1482                                 if (!ltmp)
1483                                         ltmp = alloca(VAR_BUF_SIZE);
1484
1485                                 memset(ltmp, 0, VAR_BUF_SIZE);
1486                                 pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
1487                                 vars = ltmp;
1488                         } else {
1489                                 vars = var;
1490                         }
1491
1492                         if (!workspace)
1493                                 workspace = alloca(VAR_BUF_SIZE);
1494
1495                         workspace[0] = '\0';
1496
1497                         parse_variable_name(vars, &offset, &offset2, &isfunction);
1498                         if (isfunction) {
1499                                 /* Evaluate function */
1500                                 cp4 = ast_func_read(c, vars, workspace, VAR_BUF_SIZE);
1501
1502                                 ast_log(LOG_DEBUG, "Function result is '%s'\n", cp4 ? cp4 : "(null)");
1503                         } else {
1504                                 /* Retrieve variable value */
1505                                 pbx_retrieve_variable(c, vars, &cp4, workspace, VAR_BUF_SIZE, headp);
1506                         }
1507                         if (cp4) {
1508                                 cp4 = substring(cp4, offset, offset2, workspace, VAR_BUF_SIZE);
1509
1510                                 length = strlen(cp4);
1511                                 if (length > count)
1512                                         length = count;
1513                                 memcpy(cp2, cp4, length);
1514                                 count -= length;
1515                                 cp2 += length;
1516                         }
1517                 } else if (nextexp) {
1518                         /* We have an expression.  Find the start and end, and determine
1519                            if we are going to have to recursively call ourselves on the
1520                            contents */
1521                         vars = vare = nextexp + 2;
1522                         brackets = 1;
1523                         needsub = 0;
1524
1525                         /* Find the end of it */
1526                         while(brackets && *vare) {
1527                                 if ((vare[0] == '$') && (vare[1] == '[')) {
1528                                         needsub++;
1529                                         brackets++;
1530                                         vare++;
1531                                 } else if (vare[0] == '[') {
1532                                         brackets++;
1533                                 } else if (vare[0] == ']') {
1534                                         brackets--;
1535                                 } else if ((vare[0] == '$') && (vare[1] == '{')) {
1536                                         needsub++;
1537                                         vare++;
1538                                 }
1539                                 vare++;
1540                         }
1541                         if (brackets)
1542                                 ast_log(LOG_NOTICE, "Error in extension logic (missing ']')\n");
1543                         len = vare - vars - 1;
1544                         
1545                         /* Skip totally over expression */
1546                         whereweare += (len + 3);
1547                         
1548                         if (!var)
1549                                 var = alloca(VAR_BUF_SIZE);
1550
1551                         /* Store variable name (and truncate) */
1552                         ast_copy_string(var, vars, len + 1);
1553                         
1554                         /* Substitute if necessary */
1555                         if (needsub) {
1556                                 if (!ltmp)
1557                                         ltmp = alloca(VAR_BUF_SIZE);
1558
1559                                 memset(ltmp, 0, VAR_BUF_SIZE);
1560                                 pbx_substitute_variables_helper_full(c, headp, var, ltmp, VAR_BUF_SIZE - 1);
1561                                 vars = ltmp;
1562                         } else {
1563                                 vars = var;
1564                         }
1565
1566                         length = ast_expr(vars, cp2, count);
1567
1568                         if (length) {
1569                                 ast_log(LOG_DEBUG, "Expression result is '%s'\n", cp2);
1570                                 count -= length;
1571                                 cp2 += length;
1572                         }
1573                 } else
1574                         break;
1575         }
1576 }
1577
1578 void pbx_substitute_variables_helper(struct ast_channel *c, const char *cp1, char *cp2, int count)
1579 {
1580         pbx_substitute_variables_helper_full(c, (c) ? &c->varshead : NULL, cp1, cp2, count);
1581 }
1582
1583 void pbx_substitute_variables_varshead(struct varshead *headp, const char *cp1, char *cp2, int count)
1584 {
1585         pbx_substitute_variables_helper_full(NULL, headp, cp1, cp2, count);
1586 }
1587
1588 static void pbx_substitute_variables(char *passdata, int datalen, struct ast_channel *c, struct ast_exten *e)
1589 {
1590         memset(passdata, 0, datalen);
1591                 
1592         /* No variables or expressions in e->data, so why scan it? */
1593         if (!strchr(e->data, '$') && !strstr(e->data,"${") && !strstr(e->data,"$[") && !strstr(e->data,"$(")) {
1594                 ast_copy_string(passdata, e->data, datalen);
1595                 return;
1596         }
1597         
1598         pbx_substitute_variables_helper(c, e->data, passdata, datalen - 1);
1599 }                                                               
1600
1601 static int pbx_extension_helper(struct ast_channel *c, struct ast_context *con, const char *context, const char *exten, int priority, const char *label, const char *callerid, int action) 
1602 {
1603         struct ast_exten *e;
1604         struct ast_app *app;
1605         struct ast_switch *sw;
1606         char *data;
1607         const char *foundcontext=NULL;
1608         int newstack = 0;
1609         int res;
1610         int status = 0;
1611         char *incstack[AST_PBX_MAX_STACK];
1612         char passdata[EXT_DATA_SIZE];
1613         int stacklen = 0;
1614         char tmp[80];
1615         char tmp2[80];
1616         char tmp3[EXT_DATA_SIZE];
1617         char atmp[80];
1618         char atmp2[EXT_DATA_SIZE+100];
1619
1620         if (ast_mutex_lock(&conlock)) {
1621                 ast_log(LOG_WARNING, "Unable to obtain lock\n");
1622                 if ((action == HELPER_EXISTS) || (action == HELPER_CANMATCH) || (action == HELPER_MATCHMORE))
1623                         return 0;
1624                 else
1625                         return -1;
1626         }
1627         e = pbx_find_extension(c, con, context, exten, priority, label, callerid, action, incstack, &stacklen, &status, &sw, &data, &foundcontext);
1628         if (e) {
1629                 switch(action) {
1630                 case HELPER_CANMATCH:
1631                         ast_mutex_unlock(&conlock);
1632                         return -1;
1633                 case HELPER_EXISTS:
1634                         ast_mutex_unlock(&conlock);
1635                         return -1;
1636                 case HELPER_FINDLABEL:
1637                         res = e->priority;
1638                         ast_mutex_unlock(&conlock);
1639                         return res;
1640                 case HELPER_MATCHMORE:
1641                         ast_mutex_unlock(&conlock);
1642                         return -1;
1643                 case HELPER_SPAWN:
1644                         newstack++;
1645                         /* Fall through */
1646                 case HELPER_EXEC:
1647                         app = pbx_findapp(e->app);
1648                         ast_mutex_unlock(&conlock);
1649                         if (app) {
1650                                 if (c->context != context)
1651                                         ast_copy_string(c->context, context, sizeof(c->context));
1652                                 if (c->exten != exten)
1653                                         ast_copy_string(c->exten, exten, sizeof(c->exten));
1654                                 c->priority = priority;
1655                                 pbx_substitute_variables(passdata, sizeof(passdata), c, e);
1656                                 if (option_debug) {
1657                                                 ast_log(LOG_DEBUG, "Launching '%s'\n", app->name);
1658                                                 snprintf(atmp, 80, "STACK-%s-%s-%d", context, exten, priority);
1659                                                 snprintf(atmp2, EXT_DATA_SIZE+100, "%s(\"%s\", \"%s\") %s", app->name, c->name, passdata, (newstack ? "in new stack" : "in same stack"));
1660                                                 pbx_builtin_setvar_helper(c, atmp, atmp2);
1661                                 }
1662                                 if (option_verbose > 2)
1663                                                 ast_verbose( VERBOSE_PREFIX_3 "Executing %s(\"%s\", \"%s\") %s\n", 
1664                                                                 term_color(tmp, app->name, COLOR_BRCYAN, 0, sizeof(tmp)),
1665                                                                 term_color(tmp2, c->name, COLOR_BRMAGENTA, 0, sizeof(tmp2)),
1666                                                                 term_color(tmp3, passdata, COLOR_BRMAGENTA, 0, sizeof(tmp3)),
1667                                                                 (newstack ? "in new stack" : "in same stack"));
1668                                 manager_event(EVENT_FLAG_CALL, "Newexten", 
1669                                         "Channel: %s\r\n"
1670                                         "Context: %s\r\n"
1671                                         "Extension: %s\r\n"
1672                                         "Priority: %d\r\n"
1673                                         "Application: %s\r\n"
1674                                         "AppData: %s\r\n"
1675                                         "Uniqueid: %s\r\n",
1676                                         c->name, c->context, c->exten, c->priority, app->name, passdata, c->uniqueid);
1677                                 res = pbx_exec(c, app, passdata, newstack);
1678                                 return res;
1679                         } else {
1680                                 ast_log(LOG_WARNING, "No application '%s' for extension (%s, %s, %d)\n", e->app, context, exten, priority);
1681                                 return -1;
1682                         }
1683                 default:
1684                         ast_log(LOG_WARNING, "Huh (%d)?\n", action);
1685                         return -1;
1686                 }
1687         } else if (sw) {
1688                 switch(action) {
1689                 case HELPER_CANMATCH:
1690                         ast_mutex_unlock(&conlock);
1691                         return -1;
1692                 case HELPER_EXISTS:
1693                         ast_mutex_unlock(&conlock);
1694                         return -1;
1695                 case HELPER_MATCHMORE:
1696                         ast_mutex_unlock(&conlock);
1697                         return -1;
1698                 case HELPER_FINDLABEL:
1699                         ast_mutex_unlock(&conlock);
1700                         return -1;
1701                 case HELPER_SPAWN:
1702                         newstack++;
1703                         /* Fall through */
1704                 case HELPER_EXEC:
1705                         ast_mutex_unlock(&conlock);
1706                         if (sw->exec)
1707                                 res = sw->exec(c, foundcontext ? foundcontext : context, exten, priority, callerid, newstack, data);
1708                         else {
1709                                 ast_log(LOG_WARNING, "No execution engine for switch %s\n", sw->name);
1710                                 res = -1;
1711                         }
1712                         return res;
1713                 default:
1714                         ast_log(LOG_WARNING, "Huh (%d)?\n", action);
1715                         return -1;
1716                 }
1717         } else {
1718                 ast_mutex_unlock(&conlock);
1719                 switch(status) {
1720                 case STATUS_NO_CONTEXT:
1721                         if ((action != HELPER_EXISTS) && (action != HELPER_MATCHMORE))
1722                                 ast_log(LOG_NOTICE, "Cannot find extension context '%s'\n", context);
1723                         break;
1724                 case STATUS_NO_EXTENSION:
1725                         if ((action != HELPER_EXISTS) && (action !=  HELPER_CANMATCH) && (action != HELPER_MATCHMORE))
1726                                 ast_log(LOG_NOTICE, "Cannot find extension '%s' in context '%s'\n", exten, context);
1727                         break;
1728                 case STATUS_NO_PRIORITY:
1729                         if ((action != HELPER_EXISTS) && (action !=  HELPER_CANMATCH) && (action != HELPER_MATCHMORE))
1730                                 ast_log(LOG_NOTICE, "No such priority %d in extension '%s' in context '%s'\n", priority, exten, context);
1731                         break;
1732                 case STATUS_NO_LABEL:
1733                         if (context)
1734                                 ast_log(LOG_NOTICE, "No such label '%s' in extension '%s' in context '%s'\n", label, exten, context);
1735                         break;
1736                 default:
1737                         ast_log(LOG_DEBUG, "Shouldn't happen!\n");
1738                 }
1739                 
1740                 if ((action != HELPER_EXISTS) && (action != HELPER_CANMATCH) && (action != HELPER_MATCHMORE))
1741                         return -1;
1742                 else
1743                         return 0;
1744         }
1745
1746 }
1747
1748 /*! \brief  ast_hint_extension: Find hint for given extension in context */
1749 static struct ast_exten *ast_hint_extension(struct ast_channel *c, const char *context, const char *exten)
1750 {
1751         struct ast_exten *e;
1752         struct ast_switch *sw;
1753         char *data;
1754         const char *foundcontext = NULL;
1755         int status = 0;
1756         char *incstack[AST_PBX_MAX_STACK];
1757         int stacklen = 0;
1758
1759         if (ast_mutex_lock(&conlock)) {
1760                 ast_log(LOG_WARNING, "Unable to obtain lock\n");
1761                 return NULL;
1762         }
1763         e = pbx_find_extension(c, NULL, context, exten, PRIORITY_HINT, NULL, "", HELPER_EXISTS, incstack, &stacklen, &status, &sw, &data, &foundcontext);
1764         ast_mutex_unlock(&conlock);     
1765         return e;
1766 }
1767
1768 /*! \brief  ast_extensions_state2: Check state of extension by using hints */
1769 static int ast_extension_state2(struct ast_exten *e)
1770 {
1771         char hint[AST_MAX_EXTENSION] = "";    
1772         char *cur, *rest;
1773         int res = -1;
1774         int allunavailable = 1, allbusy = 1, allfree = 1;
1775         int busy = 0, inuse = 0, ring = 0;
1776
1777         if (!e)
1778                 return -1;
1779
1780         ast_copy_string(hint, ast_get_extension_app(e), sizeof(hint));
1781
1782         cur = hint;     /* On or more devices separated with a & character */
1783         do {
1784                 rest = strchr(cur, '&');
1785                 if (rest) {
1786                         *rest = 0;
1787                         rest++;
1788                 }
1789         
1790                 res = ast_device_state(cur);
1791                 switch (res) {
1792                 case AST_DEVICE_NOT_INUSE:
1793                         allunavailable = 0;
1794                         allbusy = 0;
1795                         break;
1796                 case AST_DEVICE_INUSE:
1797                         inuse = 1;
1798                         allunavailable = 0;
1799                         allfree = 0;
1800                         break;
1801                 case AST_DEVICE_RINGING:
1802                         ring = 1;
1803                         allunavailable = 0;
1804                         allfree = 0;
1805                         break;
1806                 case AST_DEVICE_BUSY:
1807                         allunavailable = 0;
1808                         allfree = 0;
1809                         busy = 1;
1810                         break;
1811                 case AST_DEVICE_UNAVAILABLE:
1812                 case AST_DEVICE_INVALID:
1813                         allbusy = 0;
1814                         allfree = 0;
1815                         break;
1816                 default:
1817                         allunavailable = 0;
1818                         allbusy = 0;
1819                         allfree = 0;
1820                 }
1821                 cur = rest;
1822         } while (cur);
1823
1824         if (!inuse && ring)
1825                 return AST_EXTENSION_RINGING;
1826         if (inuse && ring)
1827                 return (AST_EXTENSION_INUSE | AST_EXTENSION_RINGING);
1828         if (inuse)
1829                 return AST_EXTENSION_INUSE;
1830         if (allfree)
1831                 return AST_EXTENSION_NOT_INUSE;
1832         if (allbusy)            
1833                 return AST_EXTENSION_BUSY;
1834         if (allunavailable)
1835                 return AST_EXTENSION_UNAVAILABLE;
1836         if (busy) 
1837                 return AST_EXTENSION_INUSE;
1838         
1839         return AST_EXTENSION_NOT_INUSE;
1840 }
1841
1842 /*! \brief  ast_extension_state2str: Return extension_state as string */
1843 const char *ast_extension_state2str(int extension_state)
1844 {
1845         int i;
1846
1847         for (i = 0; (i < (sizeof(extension_states) / sizeof(extension_states[0]))); i++) {
1848                 if (extension_states[i].extension_state == extension_state) {
1849                         return extension_states[i].text;
1850                 }
1851         }
1852         return "Unknown";       
1853 }
1854
1855 /*! \brief  ast_extension_state: Check extension state for an extension by using hint */
1856 int ast_extension_state(struct ast_channel *c, char *context, char *exten)
1857 {
1858         struct ast_exten *e;
1859
1860         e = ast_hint_extension(c, context, exten);      /* Do we have a hint for this extension ? */ 
1861         if (!e) 
1862                 return -1;                              /* No hint, return -1 */
1863
1864         return ast_extension_state2(e);                 /* Check all devices in the hint */
1865 }
1866
1867 void ast_hint_state_changed(const char *device)
1868 {
1869         struct ast_hint *hint;
1870         struct ast_state_cb *cblist;
1871         char buf[AST_MAX_EXTENSION];
1872         char *parse;
1873         char *cur;
1874         int state;
1875
1876         ast_mutex_lock(&hintlock);
1877
1878         for (hint = hints; hint; hint = hint->next) {
1879                 ast_copy_string(buf, ast_get_extension_app(hint->exten), sizeof(buf));
1880                 parse = buf;
1881                 for (cur = strsep(&parse, "&"); cur; cur = strsep(&parse, "&")) {
1882                         if (strcasecmp(cur, device))
1883                                 continue;
1884
1885                         /* Get device state for this hint */
1886                         state = ast_extension_state2(hint->exten);
1887                         
1888                         if ((state == -1) || (state == hint->laststate))
1889                                 continue;
1890
1891                         /* Device state changed since last check - notify the watchers */
1892                         
1893                         /* For general callbacks */
1894                         for (cblist = statecbs; cblist; cblist = cblist->next)
1895                                 cblist->callback(hint->exten->parent->name, hint->exten->exten, state, cblist->data);
1896                         
1897                         /* For extension callbacks */
1898                         for (cblist = hint->callbacks; cblist; cblist = cblist->next)
1899                                 cblist->callback(hint->exten->parent->name, hint->exten->exten, state, cblist->data);
1900                         
1901                         hint->laststate = state;
1902                         break;
1903                 }
1904         }
1905
1906         ast_mutex_unlock(&hintlock);
1907 }
1908                         
1909 /*! \brief  ast_extension_state_add: Add watcher for extension states */
1910 int ast_extension_state_add(const char *context, const char *exten, 
1911                             ast_state_cb_type callback, void *data)
1912 {
1913         struct ast_hint *list;
1914         struct ast_state_cb *cblist;
1915         struct ast_exten *e;
1916
1917         /* If there's no context and extension:  add callback to statecbs list */
1918         if (!context && !exten) {
1919                 ast_mutex_lock(&hintlock);
1920
1921                 for (cblist = statecbs; cblist; cblist = cblist->next) {
1922                         if (cblist->callback == callback) {
1923                                 cblist->data = data;
1924                                 ast_mutex_unlock(&hintlock);
1925                                 return 0;
1926                         }
1927                 }
1928         
1929                 /* Now insert the callback */
1930                 cblist = calloc(1, sizeof(struct ast_state_cb));
1931                 if (!cblist) {
1932                         ast_mutex_unlock(&hintlock);
1933                         return -1;
1934                 }
1935                 cblist->id = 0;
1936                 cblist->callback = callback;
1937                 cblist->data = data;
1938         
1939                 cblist->next = statecbs;
1940                 statecbs = cblist;
1941
1942                 ast_mutex_unlock(&hintlock);
1943                 return 0;
1944         }
1945
1946         if (!context || !exten)
1947                 return -1;
1948
1949         /* This callback type is for only one hint, so get the hint */
1950         e = ast_hint_extension(NULL, context, exten);    
1951         if (!e) {
1952                 return -1;
1953         }
1954
1955         /* Find the hint in the list of hints */
1956         ast_mutex_lock(&hintlock);
1957         
1958         for (list = hints; list; list = list->next) {
1959                 if (list->exten == e)
1960                         break;      
1961         }
1962
1963         if (!list) {
1964                 /* We have no hint, sorry */
1965                 ast_mutex_unlock(&hintlock);
1966                 return -1;
1967         }
1968
1969         /* Now insert the callback in the callback list  */
1970         cblist = calloc(1, sizeof(struct ast_state_cb));
1971         if (!cblist) {
1972                 ast_mutex_unlock(&hintlock);
1973                 return -1;
1974         }
1975         cblist->id = stateid++;         /* Unique ID for this callback */
1976         cblist->callback = callback;    /* Pointer to callback routine */
1977         cblist->data = data;            /* Data for the callback */
1978
1979         cblist->next = list->callbacks;
1980         list->callbacks = cblist;
1981
1982         ast_mutex_unlock(&hintlock);
1983         return cblist->id;
1984 }
1985
1986 /*! \brief  ast_extension_state_del: Remove a watcher from the callback list */
1987 int ast_extension_state_del(int id, ast_state_cb_type callback)
1988 {
1989         struct ast_hint *list;
1990         struct ast_state_cb *cblist, *cbprev;
1991
1992         if (!id && !callback)
1993                 return -1;
1994
1995         ast_mutex_lock(&hintlock);
1996
1997         /* id is zero is a callback without extension */
1998         if (!id) {
1999                 cbprev = NULL;
2000                 for (cblist = statecbs; cblist; cblist = cblist->next) {
2001                         if (cblist->callback == callback) {
2002                                 if (!cbprev)
2003                                         statecbs = cblist->next;
2004                                 else
2005                                         cbprev->next = cblist->next;
2006
2007                                 free(cblist);
2008
2009                                 ast_mutex_unlock(&hintlock);
2010                                 return 0;
2011                         }
2012                         cbprev = cblist;
2013                 }
2014
2015                 ast_mutex_lock(&hintlock);
2016                 return -1;
2017         }
2018
2019         /* id greater than zero is a callback with extension */
2020         /* Find the callback based on ID */
2021         for (list = hints; list; list = list->next) {
2022                 cbprev = NULL;
2023                 for (cblist = list->callbacks; cblist; cblist = cblist->next) {
2024                         if (cblist->id==id) {
2025                                 if (!cbprev)
2026                                         list->callbacks = cblist->next;         
2027                                 else
2028                                         cbprev->next = cblist->next;
2029                 
2030                                 free(cblist);
2031                 
2032                                 ast_mutex_unlock(&hintlock);
2033                                 return 0;               
2034                         }               
2035                         cbprev = cblist;                                
2036                 }
2037         }
2038
2039         ast_mutex_unlock(&hintlock);
2040         return -1;
2041 }
2042
2043 /*! \brief  ast_add_hint: Add hint to hint list, check initial extension state */
2044 static int ast_add_hint(struct ast_exten *e)
2045 {
2046         struct ast_hint *list;
2047
2048         if (!e) 
2049                 return -1;
2050
2051         ast_mutex_lock(&hintlock);
2052
2053         /* Search if hint exists, do nothing */
2054         for (list = hints; list; list = list->next) {
2055                 if (list->exten == e) {
2056                         ast_mutex_unlock(&hintlock);
2057                         if (option_debug > 1)
2058                                 ast_log(LOG_DEBUG, "HINTS: Not re-adding existing hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e));
2059                         return -1;
2060                 }
2061         }
2062
2063         if (option_debug > 1)
2064                 ast_log(LOG_DEBUG, "HINTS: Adding hint %s: %s\n", ast_get_extension_name(e), ast_get_extension_app(e));
2065
2066         list = calloc(1, sizeof(struct ast_hint));
2067         if (!list) {
2068                 ast_mutex_unlock(&hintlock);
2069                 if (option_debug > 1)
2070                         ast_log(LOG_DEBUG, "HINTS: Out of memory...\n");
2071                 return -1;
2072         }
2073         /* Initialize and insert new item at the top */
2074         list->exten = e;
2075         list->laststate = ast_extension_state2(e);
2076         list->next = hints;
2077         hints = list;
2078
2079         ast_mutex_unlock(&hintlock);
2080         return 0;
2081 }
2082
2083 /*! \brief  ast_change_hint: Change hint for an extension */
2084 static int ast_change_hint(struct ast_exten *oe, struct ast_exten *ne)
2085
2086         struct ast_hint *list;
2087
2088         ast_mutex_lock(&hintlock);
2089
2090         for (list = hints; list; list = list->next) {
2091                 if (list->exten == oe) {
2092                         list->exten = ne;
2093                         ast_mutex_unlock(&hintlock);    
2094                         return 0;
2095                 }
2096         }
2097
2098         ast_mutex_unlock(&hintlock);
2099
2100         return -1;
2101 }
2102
2103 /*! \brief  ast_remove_hint: Remove hint from extension */
2104 static int ast_remove_hint(struct ast_exten *e)
2105 {
2106         /* Cleanup the Notifys if hint is removed */
2107         struct ast_hint *list, *prev = NULL;
2108         struct ast_state_cb *cblist, *cbprev;
2109
2110         if (!e) 
2111                 return -1;
2112
2113         ast_mutex_lock(&hintlock);
2114
2115         for (list = hints; list; list = list->next) {
2116                 if (list->exten == e) {
2117                         cbprev = NULL;
2118                         cblist = list->callbacks;
2119                         while (cblist) {
2120                                 /* Notify with -1 and remove all callbacks */
2121                                 cbprev = cblist;            
2122                                 cblist = cblist->next;
2123                                 cbprev->callback(list->exten->parent->name, list->exten->exten, AST_EXTENSION_DEACTIVATED, cbprev->data);
2124                                 free(cbprev);
2125                         }
2126                         list->callbacks = NULL;
2127
2128                         if (!prev)
2129                                 hints = list->next;
2130                         else
2131                                 prev->next = list->next;
2132                         free(list);
2133             
2134                         ast_mutex_unlock(&hintlock);
2135                         return 0;
2136                 }
2137                 prev = list;
2138         }
2139
2140         ast_mutex_unlock(&hintlock);
2141         return -1;
2142 }
2143
2144
2145 /*! \brief  ast_get_hint: Get hint for channel */
2146 int ast_get_hint(char *hint, int hintsize, char *name, int namesize, struct ast_channel *c, const char *context, const char *exten)
2147 {
2148         struct ast_exten *e;
2149         void *tmp;
2150
2151         e = ast_hint_extension(c, context, exten);
2152         if (e) {
2153                 if (hint) 
2154                     ast_copy_string(hint, ast_get_extension_app(e), hintsize);
2155                 if (name) {
2156                         tmp = ast_get_extension_app_data(e);
2157                         if (tmp)
2158                                 ast_copy_string(name, (char *) tmp, namesize);
2159                 }
2160                 return -1;
2161         }
2162         return 0;       
2163 }
2164
2165 int ast_exists_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid) 
2166 {
2167         return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, HELPER_EXISTS);
2168 }
2169
2170 int ast_findlabel_extension(struct ast_channel *c, const char *context, const char *exten, const char *label, const char *callerid) 
2171 {
2172         return pbx_extension_helper(c, NULL, context, exten, 0, label, callerid, HELPER_FINDLABEL);
2173 }
2174
2175 int ast_findlabel_extension2(struct ast_channel *c, struct ast_context *con, const char *exten, const char *label, const char *callerid) 
2176 {
2177         return pbx_extension_helper(c, con, NULL, exten, 0, label, callerid, HELPER_FINDLABEL);
2178 }
2179
2180 int ast_canmatch_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
2181 {
2182         return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, HELPER_CANMATCH);
2183 }
2184
2185 int ast_matchmore_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid)
2186 {
2187         return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, HELPER_MATCHMORE);
2188 }
2189
2190 int ast_spawn_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid) 
2191 {
2192         return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, HELPER_SPAWN);
2193 }
2194
2195 int ast_exec_extension(struct ast_channel *c, const char *context, const char *exten, int priority, const char *callerid) 
2196 {
2197         return pbx_extension_helper(c, NULL, context, exten, priority, NULL, callerid, HELPER_EXEC);
2198 }
2199
2200 static int __ast_pbx_run(struct ast_channel *c)
2201 {
2202         int firstpass = 1;
2203         int digit;
2204         char exten[256];
2205         int pos;
2206         int waittime;
2207         int res=0;
2208         int autoloopflag;
2209
2210         /* A little initial setup here */
2211         if (c->pbx)
2212                 ast_log(LOG_WARNING, "%s already has PBX structure??\n", c->name);
2213         c->pbx = calloc(1, sizeof(struct ast_pbx));
2214         if (!c->pbx) {
2215                 ast_log(LOG_ERROR, "Out of memory\n");
2216                 return -1;
2217         }
2218         if (c->amaflags) {
2219                 if (!c->cdr) {
2220                         c->cdr = ast_cdr_alloc();
2221                         if (!c->cdr) {
2222                                 ast_log(LOG_WARNING, "Unable to create Call Detail Record\n");
2223                                 free(c->pbx);
2224                                 return -1;
2225                         }
2226                         ast_cdr_init(c->cdr, c);
2227                 }
2228         }
2229         /* Set reasonable defaults */
2230         c->pbx->rtimeout = 10;
2231         c->pbx->dtimeout = 5;
2232
2233         autoloopflag = ast_test_flag(c, AST_FLAG_IN_AUTOLOOP);
2234         ast_set_flag(c, AST_FLAG_IN_AUTOLOOP);
2235
2236         /* Start by trying whatever the channel is set to */
2237         if (!ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
2238                 /* If not successful fall back to 's' */
2239                 if (option_verbose > 1)
2240                         ast_verbose( VERBOSE_PREFIX_2 "Starting %s at %s,%s,%d failed so falling back to exten 's'\n", c->name, c->context, c->exten, c->priority);
2241                 ast_copy_string(c->exten, "s", sizeof(c->exten));
2242                 if (!ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
2243                         /* JK02: And finally back to default if everything else failed */
2244                         if (option_verbose > 1)
2245                                 ast_verbose( VERBOSE_PREFIX_2 "Starting %s at %s,%s,%d still failed so falling back to context 'default'\n", c->name, c->context, c->exten, c->priority);
2246                         ast_copy_string(c->context, "default", sizeof(c->context));
2247                 }
2248                 c->priority = 1;
2249         }
2250         if (c->cdr && !c->cdr->start.tv_sec && !c->cdr->start.tv_usec)
2251                 ast_cdr_start(c->cdr);
2252         for (;;) {
2253                 pos = 0;
2254                 digit = 0;
2255                 while (ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
2256                         memset(exten, 0, sizeof(exten));
2257                         if ((res = ast_spawn_extension(c, c->context, c->exten, c->priority, c->cid.cid_num))) {
2258                                 /* Something bad happened, or a hangup has been requested. */
2259                                 if (((res >= '0') && (res <= '9')) || ((res >= 'A') && (res <= 'F')) ||
2260                                         (res == '*') || (res == '#')) {
2261                                         ast_log(LOG_DEBUG, "Oooh, got something to jump out with ('%c')!\n", res);
2262                                         memset(exten, 0, sizeof(exten));
2263                                         pos = 0;
2264                                         exten[pos++] = digit = res;
2265                                         break;
2266                                 }
2267                                 switch(res) {
2268                                 case AST_PBX_KEEPALIVE:
2269                                         if (option_debug)
2270                                                 ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited KEEPALIVE on '%s'\n", c->context, c->exten, c->priority, c->name);
2271                                         else if (option_verbose > 1)
2272                                                 ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited KEEPALIVE on '%s'\n", c->context, c->exten, c->priority, c->name);
2273                                         goto out;
2274                                         break;
2275                                 default:
2276                                         if (option_debug)
2277                                                 ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
2278                                         else if (option_verbose > 1)
2279                                                 ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
2280                                         if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
2281                                                 c->_softhangup =0;
2282                                                 break;
2283                                         }
2284                                         /* atimeout */
2285                                         if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT) {
2286                                                 break;
2287                                         }
2288
2289                                         if (c->cdr) {
2290                                                 ast_cdr_update(c);
2291                                         }
2292                                         goto out;
2293                                 }
2294                         }
2295                         if ((c->_softhangup == AST_SOFTHANGUP_TIMEOUT) && (ast_exists_extension(c,c->context,"T",1,c->cid.cid_num))) {
2296                                 ast_copy_string(c->exten, "T", sizeof(c->exten));
2297                                 /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
2298                                 c->whentohangup = 0;
2299                                 c->priority = 0;
2300                                 c->_softhangup &= ~AST_SOFTHANGUP_TIMEOUT;
2301                         } else if (c->_softhangup) {
2302                                 ast_log(LOG_DEBUG, "Extension %s, priority %d returned normally even though call was hung up\n",
2303                                         c->exten, c->priority);
2304                                 goto out;
2305                         }
2306                         firstpass = 0;
2307                         c->priority++;
2308                 }
2309                 if (!ast_exists_extension(c, c->context, c->exten, 1, c->cid.cid_num)) {
2310                         /* It's not a valid extension anymore */
2311                         if (ast_exists_extension(c, c->context, "i", 1, c->cid.cid_num)) {
2312                                 if (option_verbose > 2)
2313                                         ast_verbose(VERBOSE_PREFIX_3 "Sent into invalid extension '%s' in context '%s' on %s\n", c->exten, c->context, c->name);
2314                                 pbx_builtin_setvar_helper(c, "INVALID_EXTEN", c->exten);
2315                                 ast_copy_string(c->exten, "i", sizeof(c->exten));
2316                                 c->priority = 1;
2317                         } else {
2318                                 ast_log(LOG_WARNING, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n",
2319                                         c->name, c->exten, c->context);
2320                                 goto out;
2321                         }
2322                 } else if (c->_softhangup == AST_SOFTHANGUP_TIMEOUT) {
2323                         /* If we get this far with AST_SOFTHANGUP_TIMEOUT, then we know that the "T" extension is next. */
2324                         c->_softhangup = 0;
2325                 } else {
2326                         /* Done, wait for an extension */
2327                         waittime = 0;
2328                         if (digit)
2329                                 waittime = c->pbx->dtimeout;
2330                         else if (!autofallthrough)
2331                                 waittime = c->pbx->rtimeout;
2332                         if (waittime) {
2333                                 while (ast_matchmore_extension(c, c->context, exten, 1, c->cid.cid_num)) {
2334                                         /* As long as we're willing to wait, and as long as it's not defined, 
2335                                            keep reading digits until we can't possibly get a right answer anymore.  */
2336                                         digit = ast_waitfordigit(c, waittime * 1000);
2337                                         if (c->_softhangup == AST_SOFTHANGUP_ASYNCGOTO) {
2338                                                 c->_softhangup = 0;
2339                                         } else {
2340                                                 if (!digit)
2341                                                         /* No entry */
2342                                                         break;
2343                                                 if (digit < 0)
2344                                                         /* Error, maybe a  hangup */
2345                                                         goto out;
2346                                                 exten[pos++] = digit;
2347                                                 waittime = c->pbx->dtimeout;
2348                                         }
2349                                 }
2350                                 if (ast_exists_extension(c, c->context, exten, 1, c->cid.cid_num)) {
2351                                         /* Prepare the next cycle */
2352                                         ast_copy_string(c->exten, exten, sizeof(c->exten));
2353                                         c->priority = 1;
2354                                 } else {
2355                                         /* No such extension */
2356                                         if (!ast_strlen_zero(exten)) {
2357                                                 /* An invalid extension */
2358                                                 if (ast_exists_extension(c, c->context, "i", 1, c->cid.cid_num)) {
2359                                                         if (option_verbose > 2)
2360                                                                 ast_verbose( VERBOSE_PREFIX_3 "Invalid extension '%s' in context '%s' on %s\n", exten, c->context, c->name);
2361                                                         pbx_builtin_setvar_helper(c, "INVALID_EXTEN", exten);
2362                                                         ast_copy_string(c->exten, "i", sizeof(c->exten));
2363                                                         c->priority = 1;
2364                                                 } else {
2365                                                         ast_log(LOG_WARNING, "Invalid extension '%s', but no rule 'i' in context '%s'\n", exten, c->context);
2366                                                         goto out;
2367                                                 }
2368                                         } else {
2369                                                 /* A simple timeout */
2370                                                 if (ast_exists_extension(c, c->context, "t", 1, c->cid.cid_num)) {
2371                                                         if (option_verbose > 2)
2372                                                                 ast_verbose( VERBOSE_PREFIX_3 "Timeout on %s\n", c->name);
2373                                                         ast_copy_string(c->exten, "t", sizeof(c->exten));
2374                                                         c->priority = 1;
2375                                                 } else {
2376                                                         ast_log(LOG_WARNING, "Timeout, but no rule 't' in context '%s'\n", c->context);
2377                                                         goto out;
2378                                                 }
2379                                         }       
2380                                 }
2381                                 if (c->cdr) {
2382                                         if (option_verbose > 2)
2383                                                 ast_verbose(VERBOSE_PREFIX_2 "CDR updated on %s\n",c->name);    
2384                                         ast_cdr_update(c);
2385                             }
2386                         } else {
2387                                 const char *status;
2388
2389                                 status = pbx_builtin_getvar_helper(c, "DIALSTATUS");
2390                                 if (!status)
2391                                         status = "UNKNOWN";
2392                                 if (option_verbose > 2)
2393                                         ast_verbose(VERBOSE_PREFIX_2 "Auto fallthrough, channel '%s' status is '%s'\n", c->name, status);
2394                                 if (!strcasecmp(status, "CONGESTION"))
2395                                         res = pbx_builtin_congestion(c, "10");
2396                                 else if (!strcasecmp(status, "CHANUNAVAIL"))
2397                                         res = pbx_builtin_congestion(c, "10");
2398                                 else if (!strcasecmp(status, "BUSY"))
2399                                         res = pbx_builtin_busy(c, "10");
2400                                 goto out;
2401                         }
2402                 }
2403         }
2404         if (firstpass) 
2405                 ast_log(LOG_WARNING, "Don't know what to do with '%s'\n", c->name);
2406 out:
2407         if ((res != AST_PBX_KEEPALIVE) && ast_exists_extension(c, c->context, "h", 1, c->cid.cid_num)) {
2408                 c->exten[0] = 'h';
2409                 c->exten[1] = '\0';
2410                 c->priority = 1;
2411                 while(ast_exists_extension(c, c->context, c->exten, c->priority, c->cid.cid_num)) {
2412                         if ((res = ast_spawn_extension(c, c->context, c->exten, c->priority, c->cid.cid_num))) {
2413                                 /* Something bad happened, or a hangup has been requested. */
2414                                 if (option_debug)
2415                                         ast_log(LOG_DEBUG, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
2416                                 else if (option_verbose > 1)
2417                                         ast_verbose( VERBOSE_PREFIX_2 "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c->context, c->exten, c->priority, c->name);
2418                                 break;
2419                         }
2420                         c->priority++;
2421                 }
2422         }
2423         ast_set2_flag(c, autoloopflag, AST_FLAG_IN_AUTOLOOP);
2424
2425         pbx_destroy(c->pbx);
2426         c->pbx = NULL;
2427         if (res != AST_PBX_KEEPALIVE)
2428                 ast_hangup(c);
2429         return 0;
2430 }
2431
2432 /* Returns 0 on success, non-zero if call limit was reached */
2433 static int increase_call_count(const struct ast_channel *c)
2434 {
2435         int failed = 0;
2436         double curloadavg;
2437         ast_mutex_lock(&maxcalllock);
2438         if (option_maxcalls) {
2439                 if (countcalls >= option_maxcalls) {
2440                         ast_log(LOG_NOTICE, "Maximum call limit of %d calls exceeded by '%s'!\n", option_maxcalls, c->name);
2441                         failed = -1;
2442                 }
2443         }
2444         if (option_maxload) {
2445                 getloadavg(&curloadavg, 1);
2446                 if (curloadavg >= option_maxload) {
2447                         ast_log(LOG_NOTICE, "Maximum loadavg limit of %f load exceeded by '%s' (currently %f)!\n", option_maxload, c->name, curloadavg);
2448                         failed = -1;
2449                 }
2450         }
2451         if (!failed)
2452                 countcalls++;   
2453         ast_mutex_unlock(&maxcalllock);
2454
2455         return failed;
2456 }
2457
2458 static void decrease_call_count(void)
2459 {
2460         ast_mutex_lock(&maxcalllock);
2461         if (countcalls > 0)
2462                 countcalls--;
2463         ast_mutex_unlock(&maxcalllock);
2464 }
2465
2466 static void *pbx_thread(void *data)
2467 {
2468         /* Oh joyeous kernel, we're a new thread, with nothing to do but
2469            answer this channel and get it going.
2470         */
2471         /* NOTE:
2472            The launcher of this function _MUST_ increment 'countcalls'
2473            before invoking the function; it will be decremented when the
2474            PBX has finished running on the channel
2475          */
2476         struct ast_channel *c = data;
2477
2478         __ast_pbx_run(c);
2479         decrease_call_count();
2480
2481         pthread_exit(NULL);
2482
2483         return NULL;
2484 }
2485
2486 enum ast_pbx_result ast_pbx_start(struct ast_channel *c)
2487 {
2488         pthread_t t;
2489         pthread_attr_t attr;
2490
2491         if (!c) {
2492                 ast_log(LOG_WARNING, "Asked to start thread on NULL channel?\n");
2493                 return AST_PBX_FAILED;
2494         }
2495            
2496         if (increase_call_count(c))
2497                 return AST_PBX_CALL_LIMIT;
2498
2499         /* Start a new thread, and get something handling this channel. */
2500         pthread_attr_init(&attr);
2501         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
2502         if (ast_pthread_create(&t, &attr, pbx_thread, c)) {
2503                 ast_log(LOG_WARNING, "Failed to create new channel thread\n");
2504                 return AST_PBX_FAILED;
2505         }
2506
2507         return AST_PBX_SUCCESS;
2508 }
2509
2510 enum ast_pbx_result ast_pbx_run(struct ast_channel *c)
2511 {
2512         enum ast_pbx_result res = AST_PBX_SUCCESS;
2513
2514         if (increase_call_count(c))
2515                 return AST_PBX_CALL_LIMIT;
2516
2517         res = __ast_pbx_run(c);
2518         decrease_call_count();
2519
2520         return res;
2521 }
2522
2523 int ast_active_calls(void)
2524 {
2525         return countcalls;
2526 }
2527
2528 int pbx_set_autofallthrough(int newval)
2529 {
2530         int oldval;
2531         oldval = autofallthrough;
2532         if (oldval != newval)
2533                 autofallthrough = newval;
2534         return oldval;
2535 }
2536
2537 /*
2538  * This function locks contexts list by &conlist, search for the right context
2539  * structure, leave context list locked and call ast_context_remove_include2
2540  * which removes include, unlock contexts list and return ...
2541  */
2542 int ast_context_remove_include(const char *context, const char *include, const char *registrar)
2543 {
2544         struct ast_context *c = NULL;
2545
2546         if (ast_lock_contexts())
2547                 return -1;
2548
2549         /* walk contexts and search for the right one ...*/
2550         while ( (c = ast_walk_contexts(c)) ) {
2551                 /* we found one ... */
2552                 if (!strcmp(ast_get_context_name(c), context)) {
2553                         int ret;
2554                         /* remove include from this context ... */      
2555                         ret = ast_context_remove_include2(c, include, registrar);
2556
2557                         ast_unlock_contexts();
2558
2559                         /* ... return results */
2560                         return ret;
2561                 }
2562         }
2563
2564         /* we can't find the right one context */
2565         ast_unlock_contexts();
2566         return -1;
2567 }
2568
2569 /*
2570  * When we call this function, &conlock lock must be locked, because when
2571  * we giving *con argument, some process can remove/change this context
2572  * and after that there can be segfault.
2573  *
2574  * This function locks given context, removes include, unlock context and
2575  * return.
2576  */
2577 int ast_context_remove_include2(struct ast_context *con, const char *include, const char *registrar)
2578 {
2579         struct ast_include *i, *pi = NULL;
2580
2581         if (ast_mutex_lock(&con->lock)) return -1;
2582
2583         /* walk includes */
2584         for (i = con->includes; i; i = i->next) {
2585                 /* find our include */
2586                 if (!strcmp(i->name, include) && 
2587                         (!registrar || !strcmp(i->registrar, registrar))) {
2588                         /* remove from list */
2589                         if (pi)
2590                                 pi->next = i->next;
2591                         else
2592                                 con->includes = i->next;
2593                         /* free include and return */
2594                         free(i);
2595                         ast_mutex_unlock(&con->lock);
2596                         return 0;
2597                 }
2598                 pi = i;
2599         }
2600
2601         /* we can't find the right include */
2602         ast_mutex_unlock(&con->lock);
2603         return -1;
2604 }
2605
2606 /*!
2607  * \note This function locks contexts list by &conlist, search for the rigt context
2608  * structure, leave context list locked and call ast_context_remove_switch2
2609  * which removes switch, unlock contexts list and return ...
2610  */
2611 int ast_context_remove_switch(const char *context, const char *sw, const char *data, const char *registrar)
2612 {
2613         struct ast_context *c = NULL;
2614         int ret = -1; /* default error return */
2615
2616         if (ast_lock_contexts())
2617                 return -1;
2618
2619         /* walk contexts and search for the right one ...*/
2620         while ( (c = ast_walk_contexts(c)) ) {
2621                 /* we found one ... */
2622                 if (!strcmp(ast_get_context_name(c), context)) {
2623                         /* remove switch from this context ... */       
2624                         ret = ast_context_remove_switch2(c, sw, data, registrar);
2625                         break;
2626                 }
2627         }
2628
2629         /* found or error */
2630         ast_unlock_contexts();
2631         return ret;
2632 }
2633
2634 /*!
2635  * \brief This function locks given context, removes switch, unlock context and
2636  * return.
2637  * \note When we call this function, &conlock lock must be locked, because when
2638  * we giving *con argument, some process can remove/change this context
2639  * and after that there can be segfault.
2640  *
2641  */
2642 int ast_context_remove_switch2(struct ast_context *con, const char *sw, const char *data, const char *registrar)
2643 {
2644         struct ast_sw *i, *pi = NULL;
2645
2646         if (ast_mutex_lock(&con->lock)) return -1;
2647
2648         /* walk switchs */
2649         for (i = con->alts; i; i = i->next) {
2650                 /* find our switch */
2651                 if (!strcmp(i->name, sw) && !strcmp(i->data, data) && 
2652                         (!registrar || !strcmp(i->registrar, registrar))) {
2653                         /* remove from list */
2654                         if (pi)
2655                                 pi->next = i->next;
2656                         else
2657                                 con->alts = i->next;
2658                         /* free switch and return */
2659                         free(i);
2660                         ast_mutex_unlock(&con->lock);
2661                         return 0;
2662                 }
2663                 pi = i;
2664         }
2665
2666         /* we can't find the right switch */
2667         ast_mutex_unlock(&con->lock);
2668         return -1;
2669 }
2670
2671 /*
2672  * \note This functions lock contexts list, search for the right context,
2673  * call ast_context_remove_extension2, unlock contexts list and return.
2674  * In this function we are using
2675  */
2676 int ast_context_remove_extension(const char *context, const char *extension, int priority, const char *registrar)
2677 {
2678         struct ast_context *c = NULL;
2679         int ret = -1; /* default error return */
2680
2681         if (ast_lock_contexts())
2682                 return -1;
2683
2684         /* walk contexts ... */
2685         while ( (c = ast_walk_contexts(c)) ) {
2686                 /* ... search for the right one ... */
2687                 if (!strcmp(ast_get_context_name(c), context)) {
2688                         /* ... remove extension ... */
2689                         ret = ast_context_remove_extension2(c, extension, priority,
2690                                 registrar);
2691                         break;
2692                 }
2693         }
2694         /* found or error */
2695         ast_unlock_contexts();
2696         return ret;
2697 }
2698
2699 /*!
2700  * \brief This functionc locks given context, search for the right extension and
2701  * fires out all peer in this extensions with given priority. If priority
2702  * is set to 0, all peers are removed. After that, unlock context and
2703  * return.
2704  * \note When do you want to call this function, make sure that &conlock is locked,
2705  * because some process can handle with your *con context before you lock
2706  * it.
2707  *
2708  */
2709 int ast_context_remove_extension2(struct ast_context *con, const char *extension, int priority, const char *registrar)
2710 {
2711         struct ast_exten *exten, *prev_exten = NULL;
2712
2713         if (ast_mutex_lock(&con->lock)) return -1;
2714
2715         /* go through all extensions in context and search the right one ... */
2716         exten = con->root;
2717         while (exten) {
2718
2719                 /* look for right extension */
2720                 if (!strcmp(exten->exten, extension) &&
2721                         (!registrar || !strcmp(exten->registrar, registrar))) {
2722                         struct ast_exten *peer;
2723
2724                         /* should we free all peers in this extension? (priority == 0)? */
2725                         if (priority == 0) {
2726                                 /* remove this extension from context list */
2727                                 if (prev_exten)
2728                                         prev_exten->next = exten->next;
2729                                 else
2730                                         con->root = exten->next;
2731
2732                                 /* fire out all peers */
2733                                 peer = exten; 
2734                                 while (peer) {
2735                                         exten = peer->peer;
2736                                         
2737                                         if (!peer->priority==PRIORITY_HINT) 
2738                                             ast_remove_hint(peer);
2739
2740                                         peer->datad(peer->data);
2741                                         free(peer);
2742
2743                                         peer = exten;
2744                                 }
2745
2746                                 ast_mutex_unlock(&con->lock);
2747                                 return 0;
2748                         } else {
2749                                 /* remove only extension with exten->priority == priority */
2750                                 struct ast_exten *previous_peer = NULL;
2751
2752                                 peer = exten;
2753                                 while (peer) {
2754                                         /* is this our extension? */
2755                                         if (peer->priority == priority &&
2756                                                 (!registrar || !strcmp(peer->registrar, registrar) )) {
2757                                                 /* we are first priority extension? */
2758                                                 if (!previous_peer) {
2759                                                         /* exists previous extension here? */
2760                                                         if (prev_exten) {
2761                                                                 /* yes, so we must change next pointer in
2762                                                                  * previous connection to next peer
2763                                                                  */
2764                                                                 if (peer->peer) {
2765                                                                         prev_exten->next = peer->peer;
2766                                                                         peer->peer->next = exten->next;
2767                                                                 } else
2768                                                                         prev_exten->next = exten->next;
2769                                                         } else {
2770                                                                 /* no previous extension, we are first
2771                                                                  * extension, so change con->root ...
2772                                                                  */
2773                                                                 if (peer->peer)
2774                                                                         con->root = peer->peer;
2775                                                                 else
2776                                                                         con->root = exten->next; 
2777                                                         }
2778                                                 } else {
2779                                                         /* we are not first priority in extension */
2780                                                         previous_peer->peer = peer->peer;
2781                                                 }
2782
2783                                                 /* now, free whole priority extension */
2784                                                 if (peer->priority==PRIORITY_HINT)
2785                                                     ast_remove_hint(peer);
2786                                                 peer->datad(peer->data);
2787                                                 free(peer);
2788
2789                                                 ast_mutex_unlock(&con->lock);
2790                                                 return 0;
2791                                         } else {
2792                                                 /* this is not right extension, skip to next peer */
2793                                                 previous_peer = peer;
2794                                                 peer = peer->peer;
2795                                         }
2796                                 }
2797
2798                                 ast_mutex_unlock(&con->lock);
2799                                 return -1;
2800                         }
2801                 }
2802
2803                 prev_exten = exten;
2804                 exten = exten->next;
2805         }
2806
2807         /* we can't find right extension */
2808         ast_mutex_unlock(&con->lock);
2809         return -1;
2810 }
2811
2812
2813 /*! \brief Dynamically register a new dial plan application */
2814 int ast_register_application(const char *app, int (*execute)(struct ast_channel *, void *), const char *synopsis, const char *description)
2815 {
2816         struct ast_app *tmp, *prev, *cur;
2817         char tmps[80];
2818         int length;
2819         length = sizeof(struct ast_app);
2820         length += strlen(app) + 1;
2821         if (ast_mutex_lock(&applock)) {
2822                 ast_log(LOG_ERROR, "Unable to lock application list\n");
2823                 return -1;
2824         }
2825         for (tmp = apps; tmp; tmp = tmp->next) {
2826                 if (!strcasecmp(app, tmp->name)) {
2827                         ast_log(LOG_WARNING, "Already have an application '%s'\n", app);
2828                         ast_mutex_unlock(&applock);
2829                         return -1;
2830                 }
2831         }
2832         
2833         tmp = calloc(1, length);
2834         if (!tmp) {
2835                 ast_log(LOG_ERROR, "Out of memory\n");
2836                 ast_mutex_unlock(&applock);
2837                 return -1;
2838         }
2839
2840         strcpy(tmp->name, app);
2841         tmp->execute = execute;
2842         tmp->synopsis = synopsis;
2843         tmp->description = description;
2844         /* Store in alphabetical order */
2845         prev = NULL;
2846         for (cur = apps; cur; cur = cur->next) {
2847                 if (strcasecmp(tmp->name, cur->name) < 0)
2848                         break;
2849                 prev = cur;
2850         }
2851         if (prev) {
2852                 tmp->next = prev->next;
2853                 prev->next = tmp;
2854         } else {
2855                 tmp->next = apps;
2856                 apps = tmp;
2857         }
2858         
2859         if (option_verbose > 1)
2860                 ast_verbose( VERBOSE_PREFIX_2 "Registered application '%s'\n", term_color(tmps, tmp->name, COLOR_BRCYAN, 0, sizeof(tmps)));
2861         ast_mutex_unlock(&applock);
2862         return 0;
2863 }
2864
2865 int ast_register_switch(struct ast_switch *sw)
2866 {
2867         struct ast_switch *tmp, *prev=NULL;
2868         if (ast_mutex_lock(&switchlock)) {
2869                 ast_log(LOG_ERROR, "Unable to lock switch lock\n");
2870                 return -1;
2871         }
2872         for (tmp = switches; tmp; tmp = tmp->next) {
2873                 if (!strcasecmp(tmp->name, sw->name))
2874                         break;
2875                 prev = tmp;
2876         }
2877         if (tmp) {      
2878                 ast_mutex_unlock(&switchlock);
2879                 ast_log(LOG_WARNING, "Switch '%s' already found\n", sw->name);
2880                 return -1;
2881         }
2882         sw->next = NULL;
2883         if (prev) 
2884                 prev->next = sw;
2885         else
2886                 switches = sw;
2887         ast_mutex_unlock(&switchlock);
2888         return 0;
2889 }
2890
2891 void ast_unregister_switch(struct ast_switch *sw)
2892 {
2893         struct ast_switch *tmp, *prev=NULL;
2894         if (ast_mutex_lock(&switchlock)) {
2895                 ast_log(LOG_ERROR, "Unable to lock switch lock\n");
2896                 return;
2897         }
2898         for (tmp = switches; tmp; tmp = tmp->next) {
2899                 if (tmp == sw) {
2900                         if (prev)
2901                                 prev->next = tmp->next;
2902                         else
2903                                 switches = tmp->next;
2904                         tmp->next = NULL;
2905                         break;                  
2906                 }
2907                 prev = tmp;
2908         }
2909         ast_mutex_unlock(&switchlock);
2910 }
2911
2912 /*
2913  * Help for CLI commands ...
2914  */
2915 static char show_application_help[] = 
2916 "Usage: show application <application> [<application> [<application> [...]]]\n"
2917 "       Describes a particular application.\n";
2918
2919 static char show_functions_help[] =
2920 "Usage: show functions [like <text>]\n"
2921 "       List builtin functions, optionally only those matching a given string\n";
2922
2923 static char show_function_help[] =
2924 "Usage: show function <function>\n"
2925 "       Describe a particular dialplan function.\n";
2926
2927 static char show_applications_help[] =
2928 "Usage: show applications [{like|describing} <text>]\n"
2929 "       List applications which are currently available.\n"
2930 "       If 'like', <text> will be a substring of the app name\n"
2931 "       If 'describing', <text> will be a substring of the description\n";
2932
2933 static char show_dialplan_help[] =
2934 "Usage: show dialplan [exten@][context]\n"
2935 "       Show dialplan\n";
2936
2937 static char show_switches_help[] = 
2938 "Usage: show switches\n"
2939 "       Show registered switches\n";
2940
2941 static char show_hints_help[] = 
2942 "Usage: show hints\n"
2943 "       Show registered hints\n";
2944
2945
2946 /*
2947  * IMPLEMENTATION OF CLI FUNCTIONS IS IN THE SAME ORDER AS COMMANDS HELPS
2948  *
2949  */
2950
2951 /*
2952  * \brief 'show application' CLI command implementation functions ...
2953  */
2954
2955 /*
2956  * There is a possibility to show informations about more than one
2957  * application at one time. You can type 'show application Dial Echo' and
2958  * you will see informations about these two applications ...
2959  */
2960 static char *complete_show_application(char *line, char *word, int pos, int state)
2961 {
2962         struct ast_app *a;
2963         char *ret = NULL;
2964         int which = 0;
2965         int wordlen = strlen(word);
2966
2967         /* try to lock applications list ... */
2968         if (ast_mutex_lock(&applock)) {
2969                 ast_log(LOG_ERROR, "Unable to lock application list\n");
2970                 return NULL;
2971         }
2972
2973         /* ... walk all applications ... */
2974         for (a = apps; a; a = a->next) {
2975                 /* ... check if word matches this application ... */
2976                 if (!strncasecmp(word, a->name, wordlen)) {
2977                         /* ... if this is right app serve it ... */
2978                         if (++which > state) {
2979                                 ret = strdup(a->name);
2980                                 break;
2981                         }
2982                 }
2983         }
2984
2985         ast_mutex_unlock(&applock);
2986
2987         return ret; 
2988 }
2989
2990 static int handle_show_application(int fd, int argc, char *argv[])
2991 {
2992         struct ast_app *a;
2993         int app, no_registered_app = 1;
2994
2995         if (argc < 3) return RESULT_SHOWUSAGE;
2996
2997         /* try to lock applications list ... */
2998         if (ast_mutex_lock(&applock)) {
2999                 ast_log(LOG_ERROR, "Unable to lock application list\n");
3000                 return -1;
3001         }
3002
3003         /* ... go through all applications ... */
3004         for (a = apps; a; a = a->next) {
3005                 /* ... compare this application name with all arguments given
3006                  * to 'show application' command ... */
3007                 for (app = 2; app < argc; app++) {
3008                         if (!strcasecmp(a->name, argv[app])) {
3009                                 /* Maximum number of characters added by terminal coloring is 22 */
3010                                 char infotitle[64 + AST_MAX_APP + 22], syntitle[40], destitle[40];
3011                                 char info[64 + AST_MAX_APP], *synopsis = NULL, *description = NULL;
3012                                 int synopsis_size, description_size;
3013
3014                                 no_registered_app = 0;
3015
3016                                 if (a->synopsis)
3017                                         synopsis_size = strlen(a->synopsis) + 23;
3018                                 else
3019                                         synopsis_size = strlen("Not available") + 23;
3020                                 synopsis = alloca(synopsis_size);
3021
3022                                 if (a->description)
3023                                         description_size = strlen(a->description) + 23;
3024                                 else
3025                                         description_size = strlen("Not available") + 23;
3026                                 description = alloca(description_size);
3027
3028                                 if (synopsis && description) {
3029                                         snprintf(info, 64 + AST_MAX_APP, "\n  -= Info about application '%s' =- \n\n", a->name);
3030                                         term_color(infotitle, info, COLOR_MAGENTA, 0, 64 + AST_MAX_APP + 22);
3031                                         term_color(syntitle, "[Synopsis]\n", COLOR_MAGENTA, 0, 40);
3032                                         term_color(destitle, "[Description]\n", COLOR_MAGENTA, 0, 40);
3033                                         term_color(synopsis,
3034                                                                         a->synopsis ? a->synopsis : "Not available",
3035                                                                         COLOR_CYAN, 0, synopsis_size);
3036                                         term_color(description,
3037                                                                         a->description ? a->description : "Not available",
3038                                                                         COLOR_CYAN, 0, description_size);
3039
3040                                         ast_cli(fd,"%s%s%s\n\n%s%s\n", infotitle, syntitle, synopsis, destitle, description);
3041                                 } else {
3042                                         /* ... one of our applications, show info ...*/
3043                                         ast_cli(fd,"\n  -= Info about application '%s' =- \n\n"
3044                                                 "[Synopsis]\n  %s\n\n"
3045                                                 "[Description]\n%s\n",
3046                                                 a->name,
3047                                                 a->synopsis ? a->synopsis : "Not available",
3048                                                 a->description ? a->description : "Not available");
3049                                 }
3050                         }
3051                 }
3052         }
3053
3054         ast_mutex_unlock(&applock);
3055
3056         /* we found at least one app? no? */
3057         if (no_registered_app) {
3058                 ast_cli(fd, "Your application(s) is (are) not registered\n");
3059                 return RESULT_FAILURE;
3060         }
3061
3062         return RESULT_SUCCESS;
3063 }
3064
3065 /*! \brief  handle_show_hints: CLI support for listing registred dial plan hints */
3066 static int handle_show_hints(int fd, int argc, char *argv[])
3067 {
3068         struct ast_hint *hint;
3069         int num = 0;
3070         int watchers;
3071         struct ast_state_cb *watcher;
3072
3073         if (!hints) {
3074                 ast_cli(fd, "There are no registered dialplan hints\n");
3075                 return RESULT_SUCCESS;
3076         }
3077         /* ... we have hints ... */
3078         ast_cli(fd, "\n    -= Registered Asterisk Dial Plan Hints =-\n");
3079         if (ast_mutex_lock(&hintlock)) {
3080                 ast_log(LOG_ERROR, "Unable to lock hints\n");
3081                 return -1;
3082         }
3083         for (hint = hints; hint; hint = hint->next) {
3084                 watchers = 0;
3085                 for (watcher = hint->callbacks; watcher; watcher = watcher->next)
3086                         watchers++;
3087                 ast_cli(fd, "   %-20.20s: %-20.20s  State:%-15.15s Watchers %2d\n",
3088                         ast_get_extension_name(hint->exten), ast_get_extension_app(hint->exten),
3089                         ast_extension_state2str(hint->laststate), watchers);
3090                 num++;
3091         }
3092         ast_cli(fd, "----------------\n");
3093         ast_cli(fd, "- %d hints registered\n", num);
3094         ast_mutex_unlock(&hintlock);
3095         return RESULT_SUCCESS;
3096 }
3097
3098 /*! \brief  handle_show_switches: CLI support for listing registred dial plan switches */
3099 static int handle_show_switches(int fd, int argc, char *argv[])
3100 {
3101         struct ast_switch *sw;
3102         if (!switches) {
3103                 ast_cli(fd, "There are no registered alternative switches\n");
3104                 return RESULT_SUCCESS;
3105         }
3106         /* ... we have applications ... */
3107         ast_cli(fd, "\n    -= Registered Asterisk Alternative Switches =-\n");
3108         if (ast_mutex_lock(&switchlock)) {
3109                 ast_log(LOG_ERROR, "Unable to lock switches\n");
3110                 return -1;
3111         }
3112         for (sw = switches; sw; sw = sw->next) {
3113                 ast_cli(fd, "%s: %s\n", sw->name, sw->description);
3114         }
3115         ast_mutex_unlock(&switchlock);
3116         return RESULT_SUCCESS;
3117 }
3118
3119 /*
3120  * 'show applications' CLI command implementation functions ...
3121  */
3122 static int handle_show_applications(int fd, int argc, char *argv[])
3123 {
3124         struct ast_app *a;
3125         int like = 0, describing = 0;
3126         int total_match = 0;    /* Number of matches in like clause */
3127         int total_apps = 0;     /* Number of apps registered */
3128         
3129         /* try to lock applications list ... */
3130         if (ast_mutex_lock(&applock)) {
3131                 ast_log(LOG_ERROR, "Unable to lock application list\n");
3132                 return -1;
3133         }
3134
3135         /* ... have we got at least one application (first)? no? */
3136         if (!apps) {
3137                 ast_cli(fd, "There are no registered applications\n");
3138                 ast_mutex_unlock(&applock);
3139                 return -1;
3140         }
3141
3142         /* show applications like <keyword> */
3143         if ((argc == 4) && (!strcmp(argv[2], "like"))) {
3144                 like = 1;
3145         } else if ((argc > 3) && (!strcmp(argv[2], "describing"))) {
3146                 describing = 1;
3147         }
3148
3149         /* show applications describing <keyword1> [<keyword2>] [...] */
3150         if ((!like) && (!describing)) {
3151                 ast_cli(fd, "    -= Registered Asterisk Applications =-\n");
3152         } else {
3153                 ast_cli(fd, "    -= Matching Asterisk Applications =-\n");
3154         }
3155
3156         /* ... go through all applications ... */
3157         for (a = apps; a; a = a->next) {
3158                 /* ... show informations about applications ... */
3159                 int printapp=0;
3160                 total_apps++;
3161                 if (like) {
3162                         if (strcasestr(a->name, argv[3])) {
3163                                 printapp = 1;
3164                                 total_match++;
3165                         }
3166                 } else if (describing) {
3167                         if (a->description) {
3168                                 /* Match all words on command line */
3169                                 int i;
3170                                 printapp = 1;
3171                                 for (i = 3; i < argc; i++) {
3172                                         if (!strcasestr(a->description, argv[i])) {
3173                                                 printapp = 0;
3174                                         } else {
3175                                                 total_match++;
3176                                         }
3177                                 }
3178                         }
3179                 } else {
3180                         printapp = 1;
3181                 }
3182
3183                 if (printapp) {
3184                         ast_cli(fd,"  %20s: %s\n", a->name, a->synopsis ? a->synopsis : "<Synopsis not available>");
3185                 }
3186         }
3187         if ((!like) && (!describing)) {
3188                 ast_cli(fd, "    -= %d Applications Registered =-\n",total_apps);
3189         } else {
3190                 ast_cli(fd, "    -= %d Applications Matching =-\n",total_match);
3191         }
3192         
3193         /* ... unlock and return */
3194         ast_mutex_unlock(&applock);
3195
3196         return RESULT_SUCCESS;
3197 }
3198
3199 static char *complete_show_applications(char *line, char *word, int pos, int state)
3200 {
3201         int wordlen = strlen(word);
3202
3203         if (pos == 2) {
3204                 if (ast_strlen_zero(word)) {
3205                         switch (state) {
3206                         case 0:
3207                                 return strdup("like");
3208                         case 1:
3209                                 return strdup("describing");
3210                         default:
3211                                 return NULL;
3212                         }
3213                 } else if (! strncasecmp(word, "like", wordlen)) {
3214                         if (state == 0) {
3215                                 return strdup("like");
3216                         } else {
3217                                 return NULL;
3218                         }
3219                 } else if (! strncasecmp(word, "describing", wordlen)) {
3220                         if (state == 0) {
3221                                 return strdup("describing");
3222                         } else {
3223                                 return NULL;
3224                         }
3225                 }
3226         }
3227         return NULL;
3228 }
3229
3230 /*
3231  * 'show dialplan' CLI command implementation functions ...
3232  */
3233 static char *complete_show_dialplan_context(char *line, char *word, int pos,
3234         int state)
3235 {
3236         struct ast_context *c = NULL;
3237         char *ret = NULL;
3238         int which = 0;
3239         int wordlen;
3240
3241         /* we are do completion of [exten@]context on second position only */
3242         if (pos != 2)
3243                 return NULL;
3244
3245         /* try to lock contexts list ... */
3246         if (ast_lock_contexts()) {
3247                 ast_log(LOG_ERROR, "Unable to lock context list\n");
3248                 return NULL;
3249         }
3250
3251         wordlen = strlen(word);
3252
3253         /* ... walk through all contexts ... */
3254         while ( (c = ast_walk_contexts(c)) ) {
3255                 /* ... word matches context name? yes? ... */
3256                 if (!strncasecmp(word, ast_get_context_name(c), wordlen)) {
3257                         /* ... for serve? ... */
3258                         if (++which > state) {
3259                                 /* ... yes, serve this context name ... */
3260                                 ret = strdup(ast_get_context_name(c));
3261                                 break;
3262                         }
3263                 }
3264         }
3265
3266         /* ... unlock and return */
3267         ast_unlock_contexts();
3268         return ret;
3269 }
3270
3271 struct dialplan_counters {
3272         int total_context;
3273         int total_exten;
3274         int total_prio;
3275         int context_existence;
3276         int extension_existence;
3277 };
3278
3279 static int show_dialplan_helper(int fd, char *context, char *exten, struct dialplan_counters *dpc, struct ast_include *rinclude, int includecount, char *includes[])
3280 {
3281         struct ast_context *c = NULL;
3282         int res = 0, old_total_exten = dpc->total_exten;
3283
3284         /* try to lock contexts */
3285         if (ast_lock_contexts()) {
3286                 ast_log(LOG_WARNING, "Failed to lock contexts list\n");
3287                 return -1;
3288         }
3289
3290         /* walk all contexts ... */
3291         while ( (c = ast_walk_contexts(c)) ) {
3292                 /* show this context? */
3293                 if (!context ||
3294                         !strcmp(ast_get_context_name(c), context)) {
3295                         dpc->context_existence = 1;
3296
3297                         /* try to lock context before walking in ... */
3298                         if (!ast_lock_context(c)) {
3299                                 struct ast_exten *e;
3300                                 struct ast_include *i;
3301                                 struct ast_ignorepat *ip;
3302                                 struct ast_sw *sw;
3303                                 char buf[256], buf2[256];
3304                                 int context_info_printed = 0;
3305
3306                                 /* are we looking for exten too? if yes, we print context
3307                                  * if we our extension only
3308                                  */
3309                                 if (!exten) {
3310                                         dpc->total_context++;
3311                                         ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
3312                                                 ast_get_context_name(c), ast_get_context_registrar(c));
3313                                         context_info_printed = 1;
3314                                 }
3315
3316                                 /* walk extensions ... */
3317                                 for (e = ast_walk_context_extensions(c, NULL); e; e = ast_walk_context_extensions(c, e)) {
3318                                         struct ast_exten *p;
3319                                         int prio;
3320
3321                                         /* looking for extension? is this our extension? */
3322                                         if (exten &&
3323                                                 !ast_extension_match(ast_get_extension_name(e), exten))
3324                                         {
3325                                                 /* we are looking for extension and it's not our
3326                                                  * extension, so skip to next extension */
3327                                                 continue;
3328                                         }
3329
3330                                         dpc->extension_existence = 1;
3331
3332                                         /* may we print context info? */        
3333                                         if (!context_info_printed) {
3334                                                 dpc->total_context++;
3335                                                 if (rinclude) {
3336                                                         /* TODO Print more info about rinclude */
3337                                                         ast_cli(fd, "[ Included context '%s' created by '%s' ]\n",
3338                                                                 ast_get_context_name(c),
3339                                                                 ast_get_context_registrar(c));
3340                                                 } else {
3341                                                         ast_cli(fd, "[ Context '%s' created by '%s' ]\n",
3342                                                                 ast_get_context_name(c),
3343                                                                 ast_get_context_registrar(c));
3344                                                 }
3345                                                 context_info_printed = 1;
3346                                         }
3347                                         dpc->total_prio++;
3348
3349                                         /* write extension name and first peer */       
3350                                         bzero(buf, sizeof(buf));                
3351                                         snprintf(buf, sizeof(buf), "'%s' =>",
3352                                                 ast_get_extension_name(e));
3353
3354                                         prio = ast_get_extension_priority(e);
3355                                         if (prio == PRIORITY_HINT) {
3356                                                 snprintf(buf2, sizeof(buf2),
3357                                                         "hint: %s",
3358                                                         ast_get_extension_app(e));
3359                                         } else {
3360                                                 snprintf(buf2, sizeof(buf2),
3361                                                         "%d. %s(%s)",
3362                                                         prio,
3363                                                         ast_get_extension_app(e),
3364                                                         (char *)ast_get_extension_app_data(e));
3365                                         }
3366
3367                                         ast_cli(fd, "  %-17s %-45s [%s]\n", buf, buf2,
3368                                                 ast_get_extension_registrar(e));
3369
3370                                         dpc->total_exten++;
3371                                         /* walk next extension peers */
3372                                         for (p=ast_walk_extension_priorities(e, e); p; p=ast_walk_extension_priorities(e, p)) {
3373                                                 dpc->total_prio++;
3374                                                 bzero((void *)buf2, sizeof(buf2));
3375                                                 bzero((void *)buf, sizeof(buf));
3376                                                 if (ast_get_extension_label(p))
3377                                                         snprintf(buf, sizeof(buf), "   [%s]", ast_get_extension_label(p));
3378                                                 prio = ast_get_extension_priority(p);
3379                                                 if (prio == PRIORITY_HINT) {
3380                                                         snprintf(buf2, sizeof(buf2),
3381                                                                 "hint: %s",
3382                                                                 ast_get_extension_app(p));
3383                                                 } else {
3384                                                         snprintf(buf2, sizeof(buf2),
3385                                                                 "%d. %s(%s)",
3386                                                                 prio,
3387                                                                 ast_get_extension_app(p),
3388                                                                 (char *)ast_get_extension_app_data(p));
3389                                                 }
3390
3391                                                 ast_cli(fd,"  %-17s %-45s [%s]\n",
3392                                                         buf, buf2,
3393                                                         ast_get_extension_registrar(p));
3394                                         }
3395                                 }
3396
3397                                 /* walk included and write info ... */
3398                                 for (i = ast_walk_context_includes(c, NULL); i; i = ast_walk_context_includes(c, i)) {
3399                                         bzero(buf, sizeof(buf));
3400                                         snprintf(buf, sizeof(buf), "'%s'",
3401                                                 ast_get_include_name(i));
3402                                         if (exten) {
3403                                                 /* Check all includes for the requested extension */
3404                                                 if (includecount >= AST_PBX_MAX_STACK) {
3405                                                         ast_log(LOG_NOTICE, "Maximum include depth exceeded!\n");
3406                                                 } else {
3407                                                         int dupe=0;
3408                                                         int x;
3409                                                         for (x=0;x<includecount;x++) {
3410                                                                 if (!strcasecmp(includes[x], ast_get_include_name(i))) {
3411                                                                         dupe++;
3412                                                                         break;
3413                                                                 }
3414                                                         }
3415                                                         if (!dupe) {
3416                                                                 includes[includecount] = (char *)ast_get_include_name(i);
3417                                                                 show_dialplan_helper(fd, (char *)ast_get_include_name(i), exten, dpc, i, includecount + 1, includes);
3418                                                         } else {
3419                                                                 ast_log(LOG_WARNING, "Avoiding circular include of %s within %s\n", ast_get_include_name(i), context);
3420                                                         }
3421                                                 }
3422                                         } else {
3423                                                 ast_cli(fd, "  Include =>        %-45s [%s]\n",