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