2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2008, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
21 * \brief Core PBX routines.
23 * \author Mark Spencer <markster@digium.com>
28 ASTERISK_FILE_VERSION(__FILE__
, "$Revision$")
30 #include "asterisk/_private.h"
31 #include "asterisk/paths.h" /* use ast_config_AST_SYSTEM_NAME */
35 #if defined(HAVE_SYSINFO)
36 #include <sys/sysinfo.h>
39 #include <sys/loadavg.h>
42 #include "asterisk/lock.h"
43 #include "asterisk/cli.h"
44 #include "asterisk/pbx.h"
45 #include "asterisk/channel.h"
46 #include "asterisk/file.h"
47 #include "asterisk/callerid.h"
48 #include "asterisk/cdr.h"
49 #include "asterisk/config.h"
50 #include "asterisk/term.h"
51 #include "asterisk/time.h"
52 #include "asterisk/manager.h"
53 #include "asterisk/ast_expr.h"
54 #include "asterisk/linkedlists.h"
55 #define SAY_STUBS /* generate declarations and stubs for say methods */
56 #include "asterisk/say.h"
57 #include "asterisk/utils.h"
58 #include "asterisk/causes.h"
59 #include "asterisk/musiconhold.h"
60 #include "asterisk/app.h"
61 #include "asterisk/devicestate.h"
62 #include "asterisk/stringfields.h"
63 #include "asterisk/event.h"
64 #include "asterisk/hashtab.h"
65 #include "asterisk/module.h"
66 #include "asterisk/indications.h"
67 #include "asterisk/taskprocessor.h"
70 * \note I M P O R T A N T :
72 * The speed of extension handling will likely be among the most important
73 * aspects of this PBX. The switching scheme as it exists right now isn't
74 * terribly bad (it's O(N+M), where N is the # of extensions and M is the avg #
75 * of priorities, but a constant search time here would be great ;-)
77 * A new algorithm to do searching based on a 'compiled' pattern tree is introduced
78 * here, and shows a fairly flat (constant) search time, even for over
81 * Also, using a hash table for context/priority name lookup can help prevent
82 * the find_extension routines from absorbing exponential cpu cycles as the number
83 * of contexts/priorities grow. I've previously tested find_extension with red-black trees,
84 * which have O(log2(n)) speed. Right now, I'm using hash tables, which do
85 * searches (ideally) in O(1) time. While these techniques do not yield much
86 * speed in small dialplans, they are worth the trouble in large dialplans.
91 #define EXT_DATA_SIZE 256
93 #define EXT_DATA_SIZE 8192
96 #define SWITCH_DATA_LENGTH 256
98 #define VAR_BUF_SIZE 4096
101 #define VAR_SOFTTRAN 2
102 #define VAR_HARDTRAN 3
104 #define BACKGROUND_SKIP (1 << 0)
105 #define BACKGROUND_NOANSWER (1 << 1)
106 #define BACKGROUND_MATCHEXTEN (1 << 2)
107 #define BACKGROUND_PLAYBACK (1 << 3)
109 AST_APP_OPTIONS(background_opts
, {
110 AST_APP_OPTION('s', BACKGROUND_SKIP
),
111 AST_APP_OPTION('n', BACKGROUND_NOANSWER
),
112 AST_APP_OPTION('m', BACKGROUND_MATCHEXTEN
),
113 AST_APP_OPTION('p', BACKGROUND_PLAYBACK
),
116 #define WAITEXTEN_MOH (1 << 0)
117 #define WAITEXTEN_DIALTONE (1 << 1)
119 AST_APP_OPTIONS(waitexten_opts
, {
120 AST_APP_OPTION_ARG('m', WAITEXTEN_MOH
, 0),
121 AST_APP_OPTION_ARG('d', WAITEXTEN_DIALTONE
, 0),
127 static struct ast_taskprocessor
*device_state_tps
;
129 AST_THREADSTORAGE(switch_data
);
132 \brief ast_exten: An extension
133 The dialplan is saved as a linked list with each context
134 having it's own linked list of extensions - one item per
138 char *exten
; /*!< Extension name */
139 int matchcid
; /*!< Match caller id ? */
140 const char *cidmatch
; /*!< Caller id to match for this extension */
141 int priority
; /*!< Priority */
142 const char *label
; /*!< Label */
143 struct ast_context
*parent
; /*!< The context this extension belongs to */
144 const char *app
; /*!< Application to execute */
145 struct ast_app
*cached_app
; /*!< Cached location of application */
146 void *data
; /*!< Data to use (arguments) */
147 void (*datad
)(void *); /*!< Data destructor */
148 struct ast_exten
*peer
; /*!< Next higher priority with our extension */
149 struct ast_hashtab
*peer_table
; /*!< Priorities list in hashtab form -- only on the head of the peer list */
150 struct ast_hashtab
*peer_label_table
; /*!< labeled priorities in the peers -- only on the head of the peer list */
151 const char *registrar
; /*!< Registrar */
152 struct ast_exten
*next
; /*!< Extension with a greater ID */
156 /*! \brief ast_include: include= support in extensions.conf */
159 const char *rname
; /*!< Context to include */
160 const char *registrar
; /*!< Registrar */
161 int hastime
; /*!< If time construct exists */
162 struct ast_timing timing
; /*!< time construct */
163 struct ast_include
*next
; /*!< Link them together */
167 /*! \brief ast_sw: Switch statement in extensions.conf */
170 const char *registrar
; /*!< Registrar */
171 char *data
; /*!< Data load */
173 AST_LIST_ENTRY(ast_sw
) list
;
177 /*! \brief ast_ignorepat: Ignore patterns in dial plan */
178 struct ast_ignorepat
{
179 const char *registrar
;
180 struct ast_ignorepat
*next
;
181 const char pattern
[0];
184 /*! \brief match_char: forms a syntax tree for quick matching of extension patterns */
187 int is_pattern
; /* the pattern started with '_' */
188 int deleted
; /* if this is set, then... don't return it */
189 char *x
; /* the pattern itself-- matches a single char */
190 int specificity
; /* simply the strlen of x, or 10 for X, 9 for Z, and 8 for N; and '.' and '!' will add 11 ? */
191 struct match_char
*alt_char
;
192 struct match_char
*next_char
;
193 struct ast_exten
*exten
; /* attached to last char of a pattern for exten */
196 struct scoreboard
/* make sure all fields are 0 before calling new_find_extension */
198 int total_specificity
;
200 char last_char
; /* set to ! or . if they are the end of the pattern */
201 int canmatch
; /* if the string to match was just too short */
202 struct match_char
*node
;
203 struct ast_exten
*canmatch_exten
;
204 struct ast_exten
*exten
;
207 /*! \brief ast_context: An extension context */
209 ast_rwlock_t lock
; /*!< A lock to prevent multiple threads from clobbering the context */
210 struct ast_exten
*root
; /*!< The root of the list of extensions */
211 struct ast_hashtab
*root_table
; /*!< For exact matches on the extensions in the pattern tree, and for traversals of the pattern_tree */
212 struct match_char
*pattern_tree
; /*!< A tree to speed up extension pattern matching */
213 struct ast_context
*next
; /*!< Link them together */
214 struct ast_include
*includes
; /*!< Include other contexts */
215 struct ast_ignorepat
*ignorepats
; /*!< Patterns for which to continue playing dialtone */
216 const char *registrar
; /*!< Registrar */
217 int refcount
; /*!< each module that would have created this context should inc/dec this as appropriate */
218 AST_LIST_HEAD_NOLOCK(, ast_sw
) alts
; /*!< Alternative switches */
219 ast_mutex_t macrolock
; /*!< A lock to implement "exclusive" macros - held whilst a call is executing in the macro */
220 char name
[0]; /*!< Name of the context */
224 /*! \brief ast_app: A registered application */
226 int (*execute
)(struct ast_channel
*chan
, void *data
);
227 const char *synopsis
; /*!< Synopsis text for 'show applications' */
228 const char *description
; /*!< Description (help text) for 'show application <name>' */
229 AST_RWLIST_ENTRY(ast_app
) list
; /*!< Next app in list */
230 struct ast_module
*module
; /*!< Module this app belongs to */
231 char name
[0]; /*!< Name of the application */
234 /*! \brief ast_state_cb: An extension state notify register item */
235 struct ast_state_cb
{
238 ast_state_cb_type callback
;
239 AST_LIST_ENTRY(ast_state_cb
) entry
;
242 /*! \brief Structure for dial plan hints
244 \note Hints are pointers from an extension in the dialplan to one or
245 more devices (tech/name)
246 - See \ref AstExtState
249 struct ast_exten
*exten
; /*!< Extension */
250 int laststate
; /*!< Last known state */
251 AST_LIST_HEAD_NOLOCK(, ast_state_cb
) callbacks
; /*!< Callback list for this extension */
252 AST_RWLIST_ENTRY(ast_hint
) list
;/*!< Pointer to next hint in list */
255 static const struct cfextension_states
{
257 const char * const text
;
258 } extension_states
[] = {
259 { AST_EXTENSION_NOT_INUSE
, "Idle" },
260 { AST_EXTENSION_INUSE
, "InUse" },
261 { AST_EXTENSION_BUSY
, "Busy" },
262 { AST_EXTENSION_UNAVAILABLE
, "Unavailable" },
263 { AST_EXTENSION_RINGING
, "Ringing" },
264 { AST_EXTENSION_INUSE
| AST_EXTENSION_RINGING
, "InUse&Ringing" },
265 { AST_EXTENSION_ONHOLD
, "Hold" },
266 { AST_EXTENSION_INUSE
| AST_EXTENSION_ONHOLD
, "InUse&Hold" }
270 AST_LIST_ENTRY(statechange
) entry
;
274 struct pbx_exception
{
275 AST_DECLARE_STRING_FIELDS(
276 AST_STRING_FIELD(context
); /*!< Context associated with this exception */
277 AST_STRING_FIELD(exten
); /*!< Exten associated with this exception */
278 AST_STRING_FIELD(reason
); /*!< The exception reason */
281 int priority
; /*!< Priority associated with this exception */
284 static int pbx_builtin_answer(struct ast_channel
*, void *);
285 static int pbx_builtin_goto(struct ast_channel
*, void *);
286 static int pbx_builtin_hangup(struct ast_channel
*, void *);
287 static int pbx_builtin_background(struct ast_channel
*, void *);
288 static int pbx_builtin_wait(struct ast_channel
*, void *);
289 static int pbx_builtin_waitexten(struct ast_channel
*, void *);
290 static int pbx_builtin_incomplete(struct ast_channel
*, void *);
291 static int pbx_builtin_keepalive(struct ast_channel
*, void *);
292 static int pbx_builtin_resetcdr(struct ast_channel
*, void *);
293 static int pbx_builtin_setamaflags(struct ast_channel
*, void *);
294 static int pbx_builtin_ringing(struct ast_channel
*, void *);
295 static int pbx_builtin_progress(struct ast_channel
*, void *);
296 static int pbx_builtin_congestion(struct ast_channel
*, void *);
297 static int pbx_builtin_busy(struct ast_channel
*, void *);
298 static int pbx_builtin_noop(struct ast_channel
*, void *);
299 static int pbx_builtin_gotoif(struct ast_channel
*, void *);
300 static int pbx_builtin_gotoiftime(struct ast_channel
*, void *);
301 static int pbx_builtin_execiftime(struct ast_channel
*, void *);
302 static int pbx_builtin_saynumber(struct ast_channel
*, void *);
303 static int pbx_builtin_saydigits(struct ast_channel
*, void *);
304 static int pbx_builtin_saycharacters(struct ast_channel
*, void *);
305 static int pbx_builtin_sayphonetic(struct ast_channel
*, void *);
306 static int matchcid(const char *cidpattern
, const char *callerid
);
307 int pbx_builtin_setvar(struct ast_channel
*, void *);
308 void log_match_char_tree(struct match_char
*node
, char *prefix
); /* for use anywhere */
309 int pbx_builtin_setvar_multiple(struct ast_channel
*, void *);
310 static int pbx_builtin_importvar(struct ast_channel
*, void *);
311 static void set_ext_pri(struct ast_channel
*c
, const char *exten
, int pri
);
312 static void new_find_extension(const char *str
, struct scoreboard
*score
, struct match_char
*tree
, int length
, int spec
, const char *callerid
, const char *label
, enum ext_match_t action
);
313 static struct match_char
*already_in_tree(struct match_char
*current
, char *pat
);
314 static struct match_char
*add_exten_to_pattern_tree(struct ast_context
*con
, struct ast_exten
*e1
, int findonly
);
315 static struct match_char
*add_pattern_node(struct ast_context
*con
, struct match_char
*current
, char *pattern
, int is_pattern
, int already
, int specificity
, struct match_char
**parent
);
316 static void create_match_char_tree(struct ast_context
*con
);
317 static struct ast_exten
*get_canmatch_exten(struct match_char
*node
);
318 static void destroy_pattern_tree(struct match_char
*pattern_tree
);
319 int ast_hashtab_compare_contexts(const void *ah_a
, const void *ah_b
);
320 static int hashtab_compare_extens(const void *ha_a
, const void *ah_b
);
321 static int hashtab_compare_exten_numbers(const void *ah_a
, const void *ah_b
);
322 static int hashtab_compare_exten_labels(const void *ah_a
, const void *ah_b
);
323 unsigned int ast_hashtab_hash_contexts(const void *obj
);
324 static unsigned int hashtab_hash_extens(const void *obj
);
325 static unsigned int hashtab_hash_priority(const void *obj
);
326 static unsigned int hashtab_hash_labels(const void *obj
);
327 static void __ast_internal_context_destroy( struct ast_context
*con
);
329 /* a func for qsort to use to sort a char array */
330 static int compare_char(const void *a
, const void *b
)
336 else if ((*ac
) == (*bc
))
342 /* labels, contexts are case sensitive priority numbers are ints */
343 int ast_hashtab_compare_contexts(const void *ah_a
, const void *ah_b
)
345 const struct ast_context
*ac
= ah_a
;
346 const struct ast_context
*bc
= ah_b
;
347 /* assume context names are registered in a string table! */
348 return strcmp(ac
->name
, bc
->name
);
351 static int hashtab_compare_extens(const void *ah_a
, const void *ah_b
)
353 const struct ast_exten
*ac
= ah_a
;
354 const struct ast_exten
*bc
= ah_b
;
355 int x
= strcmp(ac
->exten
, bc
->exten
);
356 if (x
) /* if exten names are diff, then return */
358 /* but if they are the same, do the cidmatch values match? */
359 if (ac
->matchcid
&& bc
->matchcid
) {
360 return strcmp(ac
->cidmatch
,bc
->cidmatch
);
361 } else if (!ac
->matchcid
&& !bc
->matchcid
) {
362 return 0; /* if there's no matchcid on either side, then this is a match */
364 return 1; /* if there's matchcid on one but not the other, they are different */
368 static int hashtab_compare_exten_numbers(const void *ah_a
, const void *ah_b
)
370 const struct ast_exten
*ac
= ah_a
;
371 const struct ast_exten
*bc
= ah_b
;
372 return ac
->priority
!= bc
->priority
;
375 static int hashtab_compare_exten_labels(const void *ah_a
, const void *ah_b
)
377 const struct ast_exten
*ac
= ah_a
;
378 const struct ast_exten
*bc
= ah_b
;
379 return strcmp(ac
->label
, bc
->label
);
382 unsigned int ast_hashtab_hash_contexts(const void *obj
)
384 const struct ast_context
*ac
= obj
;
385 return ast_hashtab_hash_string(ac
->name
);
388 static unsigned int hashtab_hash_extens(const void *obj
)
390 const struct ast_exten
*ac
= obj
;
391 unsigned int x
= ast_hashtab_hash_string(ac
->exten
);
394 y
= ast_hashtab_hash_string(ac
->cidmatch
);
398 static unsigned int hashtab_hash_priority(const void *obj
)
400 const struct ast_exten
*ac
= obj
;
401 return ast_hashtab_hash_int(ac
->priority
);
404 static unsigned int hashtab_hash_labels(const void *obj
)
406 const struct ast_exten
*ac
= obj
;
407 return ast_hashtab_hash_string(ac
->label
);
411 AST_RWLOCK_DEFINE_STATIC(globalslock
);
412 static struct varshead globals
= AST_LIST_HEAD_NOLOCK_INIT_VALUE
;
414 static int autofallthrough
= 1;
415 static int extenpatternmatchnew
= 0;
416 static char *overrideswitch
= NULL
;
418 /*! \brief Subscription for device state change events */
419 static struct ast_event_sub
*device_state_sub
;
421 AST_MUTEX_DEFINE_STATIC(maxcalllock
);
422 static int countcalls
;
423 static int totalcalls
;
425 static AST_RWLIST_HEAD_STATIC(acf_root
, ast_custom_function
);
427 /*! \brief Declaration of builtin applications */
428 static struct pbx_builtin
{
429 char name
[AST_MAX_APP
];
430 int (*execute
)(struct ast_channel
*chan
, void *data
);
435 /* These applications are built into the PBX core and do not
436 need separate modules */
438 { "Answer", pbx_builtin_answer
,
439 "Answer a channel if ringing",
440 " Answer([delay]): If the call has not been answered, this application will\n"
441 "answer it. Otherwise, it has no effect on the call. If a delay is specified,\n"
442 "Asterisk will wait this number of milliseconds before returning to\n"
443 "the dialplan after answering the call.\n"
446 { "BackGround", pbx_builtin_background
,
447 "Play an audio file while waiting for digits of an extension to go to.",
448 " Background(filename1[&filename2...][,options[,langoverride][,context]]):\n"
449 "This application will play the given list of files (do not put extension)\n"
450 "while waiting for an extension to be dialed by the calling channel. To\n"
451 "continue waiting for digits after this application has finished playing\n"
452 "files, the WaitExten application should be used. The 'langoverride' option\n"
453 "explicitly specifies which language to attempt to use for the requested sound\n"
454 "files. If a 'context' is specified, this is the dialplan context that this\n"
455 "application will use when exiting to a dialed extension."
456 " If one of the requested sound files does not exist, call processing will be\n"
459 " s - Causes the playback of the message to be skipped\n"
460 " if the channel is not in the 'up' state (i.e. it\n"
461 " hasn't been answered yet). If this happens, the\n"
462 " application will return immediately.\n"
463 " n - Don't answer the channel before playing the files.\n"
464 " m - Only break if a digit hit matches a one digit\n"
465 " extension in the destination context.\n"
466 "This application sets the following channel variable upon completion:\n"
467 " BACKGROUNDSTATUS The status of the background attempt as a text string, one of\n"
468 " SUCCESS | FAILED\n"
469 "See Also: Playback (application) -- Play sound file(s) to the channel,\n"
470 " that cannot be interrupted\n"
473 { "Busy", pbx_builtin_busy
,
474 "Indicate the Busy condition",
475 " Busy([timeout]): This application will indicate the busy condition to\n"
476 "the calling channel. If the optional timeout is specified, the calling channel\n"
477 "will be hung up after the specified number of seconds. Otherwise, this\n"
478 "application will wait until the calling channel hangs up.\n"
481 { "Congestion", pbx_builtin_congestion
,
482 "Indicate the Congestion condition",
483 " Congestion([timeout]): This application will indicate the congestion\n"
484 "condition to the calling channel. If the optional timeout is specified, the\n"
485 "calling channel will be hung up after the specified number of seconds.\n"
486 "Otherwise, this application will wait until the calling channel hangs up.\n"
489 { "ExecIfTime", pbx_builtin_execiftime
,
490 "Conditional application execution based on the current time",
491 " ExecIfTime(<times>,<weekdays>,<mdays>,<months>?appname[(appargs)]):\n"
492 "This application will execute the specified dialplan application, with optional\n"
493 "arguments, if the current time matches the given time specification.\n"
496 { "Goto", pbx_builtin_goto
,
497 "Jump to a particular priority, extension, or context",
498 " Goto([[context,]extension,]priority): This application will set the current\n"
499 "context, extension, and priority in the channel structure. After it completes, the\n"
500 "pbx engine will continue dialplan execution at the specified location.\n"
501 "If no specific extension, or extension and context, are specified, then this\n"
502 "application will just set the specified priority of the current extension.\n"
503 " At least a priority is required as an argument, or the goto will return a -1,\n"
504 "and the channel and call will be terminated.\n"
505 " If the location that is put into the channel information is bogus, and asterisk cannot\n"
506 "find that location in the dialplan,\n"
507 "then the execution engine will try to find and execute the code in the 'i' (invalid)\n"
508 "extension in the current context. If that does not exist, it will try to execute the\n"
509 "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
510 "channel is hung up, and the execution of instructions on the channel is terminated.\n"
511 "What this means is that, for example, you specify a context that does not exist, then\n"
512 "it will not be possible to find the 'h' or 'i' extensions, and the call will terminate!\n"
515 { "GotoIf", pbx_builtin_gotoif
,
517 " GotoIf(condition?[labeliftrue]:[labeliffalse]): This application will set the current\n"
518 "context, extension, and priority in the channel structure based on the evaluation of\n"
519 "the given condition. After this application completes, the\n"
520 "pbx engine will continue dialplan execution at the specified location in the dialplan.\n"
521 "The channel will continue at\n"
522 "'labeliftrue' if the condition is true, or 'labeliffalse' if the condition is\n"
523 "false. The labels are specified with the same syntax as used within the Goto\n"
524 "application. If the label chosen by the condition is omitted, no jump is\n"
525 "performed, and the execution passes to the next instruction.\n"
526 "If the target location is bogus, and does not exist, the execution engine will try \n"
527 "to find and execute the code in the 'i' (invalid)\n"
528 "extension in the current context. If that does not exist, it will try to execute the\n"
529 "'h' extension. If either or neither the 'h' or 'i' extensions have been defined, the\n"
530 "channel is hung up, and the execution of instructions on the channel is terminated.\n"
531 "Remember that this command can set the current context, and if the context specified\n"
532 "does not exist, then it will not be able to find any 'h' or 'i' extensions there, and\n"
533 "the channel and call will both be terminated!\n"
536 { "GotoIfTime", pbx_builtin_gotoiftime
,
537 "Conditional Goto based on the current time",
538 " GotoIfTime(<times>,<weekdays>,<mdays>,<months>?[labeliftrue]:[labeliffalse]):\n"
539 "This application will set the context, extension, and priority in the channel structure\n"
540 "based on the evaluation of the given time specification. After this application completes,\n"
541 "the pbx engine will continue dialplan execution at the specified location in the dialplan.\n"
542 "If the current time is within the given time specification, the channel will continue at\n"
543 "'labeliftrue'. Otherwise the channel will continue at 'labeliffalse'. If the label chosen\n"
544 "by the condition is omitted, no jump is performed, and execution passes to the next\n"
545 "instruction. If the target jump location is bogus, the same actions would be taken as for\n"
547 "Further information on the time specification can be found in examples\n"
548 "illustrating how to do time-based context includes in the dialplan.\n"
551 { "ImportVar", pbx_builtin_importvar
,
552 "Import a variable from a channel into a new variable",
553 " ImportVar(newvar=channelname,variable): This application imports a variable\n"
554 "from the specified channel (as opposed to the current one) and stores it as\n"
555 "a variable in the current channel (the channel that is calling this\n"
556 "application). Variables created by this application have the same inheritance\n"
557 "properties as those created with the Set application. See the documentation for\n"
558 "Set for more information.\n"
561 { "Hangup", pbx_builtin_hangup
,
562 "Hang up the calling channel",
563 " Hangup([causecode]): This application will hang up the calling channel.\n"
564 "If a causecode is given the channel's hangup cause will be set to the given\n"
568 { "Incomplete", pbx_builtin_incomplete
,
569 "returns AST_PBX_INCOMPLETE value",
570 " Incomplete([n]): Signals the PBX routines that the previous matched extension\n"
571 "is incomplete and that further input should be allowed before matching can\n"
572 "be considered to be complete. Can be used within a pattern match when\n"
573 "certain criteria warrants a longer match.\n"
574 " If the 'n' option is specified, then Incomplete will not attempt to answer\n"
575 "the channel first. Note that most channel types need to be in Answer state\n"
576 "in order to receive DTMF.\n"
579 { "KeepAlive", pbx_builtin_keepalive
,
580 "returns AST_PBX_KEEPALIVE value",
581 " KeepAlive(): This application is chiefly meant for internal use with Gosubs.\n"
582 "Please do not run it alone from the dialplan!\n"
585 { "NoOp", pbx_builtin_noop
,
586 "Do Nothing (No Operation)",
587 " NoOp(): This application does nothing. However, it is useful for debugging\n"
588 "purposes. Any text that is provided as arguments to this application can be\n"
589 "viewed at the Asterisk CLI. This method can be used to see the evaluations of\n"
590 "variables or functions without having any effect. Alternatively, see the\n"
591 "Verbose() application for finer grain control of output at custom verbose levels.\n"
594 { "Progress", pbx_builtin_progress
,
596 " Progress(): This application will request that in-band progress information\n"
597 "be provided to the calling channel.\n"
600 { "RaiseException", pbx_builtin_raise_exception
,
601 "Handle an exceptional condition",
602 " RaiseException(<reason>): This application will jump to the \"e\" extension\n"
603 "in the current context, setting the dialplan function EXCEPTION(). If the \"e\"\n"
604 "extension does not exist, the call will hangup.\n"
607 { "ResetCDR", pbx_builtin_resetcdr
,
608 "Resets the Call Data Record",
609 " ResetCDR([options]): This application causes the Call Data Record to be\n"
612 " w -- Store the current CDR record before resetting it.\n"
613 " a -- Store any stacked records.\n"
614 " v -- Save CDR variables.\n"
615 " e -- Enable CDR only (negate effects of NoCDR).\n"
618 { "Ringing", pbx_builtin_ringing
,
619 "Indicate ringing tone",
620 " Ringing(): This application will request that the channel indicate a ringing\n"
621 "tone to the user.\n"
624 { "SayAlpha", pbx_builtin_saycharacters
,
626 " SayAlpha(string): This application will play the sounds that correspond to\n"
627 "the letters of the given string.\n"
630 { "SayDigits", pbx_builtin_saydigits
,
632 " SayDigits(digits): This application will play the sounds that correspond\n"
633 "to the digits of the given number. This will use the language that is currently\n"
634 "set for the channel. See the LANGUAGE function for more information on setting\n"
635 "the language for the channel.\n"
638 { "SayNumber", pbx_builtin_saynumber
,
640 " SayNumber(digits[,gender]): This application will play the sounds that\n"
641 "correspond to the given number. Optionally, a gender may be specified.\n"
642 "This will use the language that is currently set for the channel. See the\n"
643 "LANGUAGE function for more information on setting the language for the channel.\n"
646 { "SayPhonetic", pbx_builtin_sayphonetic
,
648 " SayPhonetic(string): This application will play the sounds from the phonetic\n"
649 "alphabet that correspond to the letters in the given string.\n"
652 { "Set", pbx_builtin_setvar
,
653 "Set channel variable or function value",
655 "This function can be used to set the value of channel variables or dialplan\n"
656 "functions. When setting variables, if the variable name is prefixed with _,\n"
657 "the variable will be inherited into channels created from the current\n"
658 "channel. If the variable name is prefixed with __, the variable will be\n"
659 "inherited into channels created from the current channel and all children\n"
663 { "MSet", pbx_builtin_setvar_multiple
,
664 "Set channel variable(s) or function value(s)",
665 " MSet(name1=value1,name2=value2,...)\n"
666 "This function can be used to set the value of channel variables or dialplan\n"
667 "functions. When setting variables, if the variable name is prefixed with _,\n"
668 "the variable will be inherited into channels created from the current\n"
669 "channel. If the variable name is prefixed with __, the variable will be\n"
670 "inherited into channels created from the current channel and all children\n"
672 "MSet behaves in a similar fashion to the way Set worked in 1.2/1.4 and is thus\n"
673 "prone to doing things that you may not expect. Avoid its use if possible.\n"
676 { "SetAMAFlags", pbx_builtin_setamaflags
,
678 " SetAMAFlags([flag]): This application will set the channel's AMA Flags for\n"
679 " billing purposes.\n"
682 { "Wait", pbx_builtin_wait
,
683 "Waits for some time",
684 " Wait(seconds): This application waits for a specified number of seconds.\n"
685 "Then, dialplan execution will continue at the next priority.\n"
686 " Note that the seconds can be passed with fractions of a second. For example,\n"
687 "'1.5' will ask the application to wait for 1.5 seconds.\n"
690 { "WaitExten", pbx_builtin_waitexten
,
691 "Waits for an extension to be entered",
692 " WaitExten([seconds][,options]): This application waits for the user to enter\n"
693 "a new extension for a specified number of seconds.\n"
694 " Note that the seconds can be passed with fractions of a second. For example,\n"
695 "'1.5' will ask the application to wait for 1.5 seconds.\n"
697 " m[(x)] - Provide music on hold to the caller while waiting for an extension.\n"
698 " Optionally, specify the class for music on hold within parenthesis.\n"
699 "See Also: Playback(application), Background(application).\n"
704 static struct ast_context
*contexts
;
705 static struct ast_hashtab
*contexts_table
= NULL
;
707 AST_RWLOCK_DEFINE_STATIC(conlock
); /*!< Lock for the ast_context list */
709 static AST_RWLIST_HEAD_STATIC(apps
, ast_app
);
711 static AST_RWLIST_HEAD_STATIC(switches
, ast_switch
);
713 static int stateid
= 1;
715 When holding this list's lock, do _not_ do anything that will cause conlock
716 to be taken, unless you _already_ hold it. The ast_merge_contexts_and_delete
717 function will take the locks in conlock/hints order, so any other
718 paths that require both locks must also take them in that order.
720 static AST_RWLIST_HEAD_STATIC(hints
, ast_hint
);
722 static AST_LIST_HEAD_NOLOCK_STATIC(statecbs
, ast_state_cb
);
725 \note This function is special. It saves the stack so that no matter
726 how many times it is called, it returns to the same place */
727 int pbx_exec(struct ast_channel
*c
, /*!< Channel */
728 struct ast_app
*app
, /*!< Application */
729 void *data
) /*!< Data for execution */
732 struct ast_module_user
*u
= NULL
;
733 const char *saved_c_appl
;
734 const char *saved_c_data
;
736 if (c
->cdr
&& !ast_check_hangup(c
))
737 ast_cdr_setapp(c
->cdr
, app
->name
, data
);
739 /* save channel values */
740 saved_c_appl
= c
->appl
;
741 saved_c_data
= c
->data
;
746 u
= __ast_module_user_add(app
->module
, c
);
747 res
= app
->execute(c
, S_OR(data
, ""));
748 if (app
->module
&& u
)
749 __ast_module_user_remove(app
->module
, u
);
750 /* restore channel values */
751 c
->appl
= saved_c_appl
;
752 c
->data
= saved_c_data
;
757 /*! Go no deeper than this through includes (not counting loops) */
758 #define AST_PBX_MAX_STACK 128
760 /*! \brief Find application handle in linked list
762 struct ast_app
*pbx_findapp(const char *app
)
766 AST_RWLIST_RDLOCK(&apps
);
767 AST_RWLIST_TRAVERSE(&apps
, tmp
, list
) {
768 if (!strcasecmp(tmp
->name
, app
))
771 AST_RWLIST_UNLOCK(&apps
);
776 static struct ast_switch
*pbx_findswitch(const char *sw
)
778 struct ast_switch
*asw
;
780 AST_RWLIST_RDLOCK(&switches
);
781 AST_RWLIST_TRAVERSE(&switches
, asw
, list
) {
782 if (!strcasecmp(asw
->name
, sw
))
785 AST_RWLIST_UNLOCK(&switches
);
790 static inline int include_valid(struct ast_include
*i
)
795 return ast_check_timing(&(i
->timing
));
798 static void pbx_destroy(struct ast_pbx
*p
)
803 /* form a tree that fully describes all the patterns in a context's extensions
804 * in this tree, a "node" represents an individual character or character set
805 * meant to match the corresponding character in a dial string. The tree
806 * consists of a series of match_char structs linked in a chain
807 * via the alt_char pointers. More than one pattern can share the same parts of the
808 * tree as other extensions with the same pattern to that point.
809 * My first attempt to duplicate the finding of the 'best' pattern was flawed in that
810 * I misunderstood the general algorithm. I thought that the 'best' pattern
811 * was the one with lowest total score. This was not true. Thus, if you have
812 * patterns "1XXXXX" and "X11111", you would be tempted to say that "X11111" is
813 * the "best" match because it has fewer X's, and is therefore more specific,
814 * but this is not how the old algorithm works. It sorts matching patterns
815 * in a similar collating sequence as sorting alphabetic strings, from left to
816 * right. Thus, "1XXXXX" comes before "X11111", and would be the "better" match,
817 * because "1" is more specific than "X".
818 * So, to accomodate this philosophy, I sort the tree branches along the alt_char
819 * line so they are lowest to highest in specificity numbers. This way, as soon
820 * as we encounter our first complete match, we automatically have the "best"
821 * match and can stop the traversal immediately. Same for CANMATCH/MATCHMORE.
822 * If anyone would like to resurrect the "wrong" pattern trie searching algorithm,
823 * they are welcome to revert pbx to before 1 Apr 2008.
824 * As an example, consider these 4 extensions:
830 * In the above, between (a) and (d), (a) is a more specific pattern than (d), and would win over
831 * most numbers. For all numbers beginning with 307754, (b) should always win.
833 * These pattern should form a (sorted) tree that looks like this:
834 * { "3" } --next--> { "0" } --next--> { "7" } --next--> { "7" } --next--> { "5" } ... blah ... --> { "X" exten_match: (b) }
838 * { "f" } --next--> { "a" } --next--> { "x" exten_match: (c) }
839 * { "N" } --next--> { "X" } --next--> { "X" } --next--> { "N" } --next--> { "X" } ... blah ... --> { "X" exten_match: (a) }
843 * | { "X" } --next--> { "X" } ... blah ... --> { "X" exten_match: (d) }
847 * In the above, I could easily turn "N" into "23456789", but I think that a quick "if( *z >= '2' && *z <= '9' )" might take
848 * fewer CPU cycles than a call to index("23456789",*z), where *z is the char to match...
850 * traversal is pretty simple: one routine merely traverses the alt list, and for each matching char in the pattern, it calls itself
851 * on the corresponding next pointer, incrementing also the pointer of the string to be matched, and passing the total specificity and length.
852 * We pass a pointer to a scoreboard down through, also.
853 * The scoreboard isn't as necessary to the revised algorithm, but I kept it as a handy way to return the matched extension.
854 * The first complete match ends the traversal, which should make this version of the pattern matcher faster
855 * the previous. The same goes for "CANMATCH" or "MATCHMORE"; the first such match ends the traversal. In both
856 * these cases, the reason we can stop immediately, is because the first pattern match found will be the "best"
857 * according to the sort criteria.
858 * Hope the limit on stack depth won't be a problem... this routine should
859 * be pretty lean as far a stack usage goes. Any non-match terminates the recursion down a branch.
861 * In the above example, with the number "3077549999" as the pattern, the traversor could match extensions a, b and d. All are
862 * of length 10; they have total specificities of 24580, 10246, and 25090, respectively, not that this matters
863 * at all. (b) wins purely because the first character "3" is much more specific (lower specificity) than "N". I have
864 * left the specificity totals in the code as an artifact; at some point, I will strip it out.
866 * Just how much time this algorithm might save over a plain linear traversal over all possible patterns is unknown,
867 * because it's a function of how many extensions are stored in a context. With thousands of extensions, the speedup
868 * can be very noticeable. The new matching algorithm can run several hundreds of times faster, if not a thousand or
869 * more times faster in extreme cases.
871 * MatchCID patterns are also supported, and stored in the tree just as the extension pattern is. Thus, you
872 * can have patterns in your CID field as well.
877 static void update_scoreboard(struct scoreboard
*board
, int length
, int spec
, struct ast_exten
*exten
, char last
, const char *callerid
, int deleted
, struct match_char
*node
)
879 /* if this extension is marked as deleted, then skip this -- if it never shows
880 on the scoreboard, it will never be found, nor will halt the traversal. */
883 board
->total_specificity
= spec
;
884 board
->total_length
= length
;
885 board
->exten
= exten
;
886 board
->last_char
= last
;
888 #ifdef NEED_DEBUG_HERE
889 ast_log(LOG_NOTICE
,"Scoreboarding (LONGER) %s, len=%d, score=%d\n", exten
->exten
, length
, spec
);
893 void log_match_char_tree(struct match_char
*node
, char *prefix
)
896 struct ast_str
*my_prefix
= ast_str_alloca(1024);
900 if (node
&& node
->exten
&& node
->exten
)
901 snprintf(extenstr
, sizeof(extenstr
), "(%p)", node
->exten
);
903 if (strlen(node
->x
) > 1) {
904 ast_debug(1, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix
, node
->x
, node
->is_pattern
? 'Y':'N',
905 node
->deleted
? 'D':'-', node
->specificity
, node
->exten
? "EXTEN:":"",
906 node
->exten
? node
->exten
->exten
: "", extenstr
);
908 ast_debug(1, "%s%s:%c:%c:%d:%s%s%s\n", prefix
, node
->x
, node
->is_pattern
? 'Y':'N',
909 node
->deleted
? 'D':'-', node
->specificity
, node
->exten
? "EXTEN:":"",
910 node
->exten
? node
->exten
->exten
: "", extenstr
);
913 ast_str_set(&my_prefix
, 0, "%s+ ", prefix
);
916 log_match_char_tree(node
->next_char
, my_prefix
->str
);
919 log_match_char_tree(node
->alt_char
, prefix
);
922 static void cli_match_char_tree(struct match_char
*node
, char *prefix
, int fd
)
925 struct ast_str
*my_prefix
= ast_str_alloca(1024);
929 if (node
&& node
->exten
&& node
->exten
)
930 snprintf(extenstr
, sizeof(extenstr
), "(%p)", node
->exten
);
932 if (strlen(node
->x
) > 1) {
933 ast_cli(fd
, "%s[%s]:%c:%c:%d:%s%s%s\n", prefix
, node
->x
, node
->is_pattern
? 'Y' : 'N',
934 node
->deleted
? 'D' : '-', node
->specificity
, node
->exten
? "EXTEN:" : "",
935 node
->exten
? node
->exten
->exten
: "", extenstr
);
937 ast_cli(fd
, "%s%s:%c:%c:%d:%s%s%s\n", prefix
, node
->x
, node
->is_pattern
? 'Y' : 'N',
938 node
->deleted
? 'D' : '-', node
->specificity
, node
->exten
? "EXTEN:" : "",
939 node
->exten
? node
->exten
->exten
: "", extenstr
);
942 ast_str_set(&my_prefix
, 0, "%s+ ", prefix
);
945 cli_match_char_tree(node
->next_char
, my_prefix
->str
, fd
);
948 cli_match_char_tree(node
->alt_char
, prefix
, fd
);
951 static struct ast_exten
*get_canmatch_exten(struct match_char
*node
)
953 /* find the exten at the end of the rope */
954 struct match_char
*node2
= node
;
956 for (node2
= node
; node2
; node2
= node2
->next_char
) {
958 #ifdef NEED_DEBUG_HERE
959 ast_log(LOG_NOTICE
,"CanMatch_exten returns exten %s(%p)\n", node2
->exten
->exten
, node2
->exten
);
964 #ifdef NEED_DEBUG_HERE
965 ast_log(LOG_NOTICE
,"CanMatch_exten returns NULL, match_char=%s\n", node
->x
);
970 static struct ast_exten
*trie_find_next_match(struct match_char
*node
)
972 struct match_char
*m3
;
973 struct match_char
*m4
;
974 struct ast_exten
*e3
;
976 if (node
&& node
->x
[0] == '.' && !node
->x
[1]) /* dot and ! will ALWAYS be next match in a matchmore */
979 if (node
&& node
->x
[0] == '!' && !node
->x
[1])
982 if (!node
|| !node
->next_char
)
985 m3
= node
->next_char
;
989 for(m4
=m3
->alt_char
; m4
; m4
= m4
->alt_char
) {
993 for(m4
=m3
; m4
; m4
= m4
->alt_char
) {
994 e3
= trie_find_next_match(m3
);
1002 static char *action2str(enum ext_match_t action
)
1023 static void new_find_extension(const char *str
, struct scoreboard
*score
, struct match_char
*tree
, int length
, int spec
, const char *label
, const char *callerid
, enum ext_match_t action
)
1025 struct match_char
*p
; /* note minimal stack storage requirements */
1026 struct ast_exten pattern
= { .label
= label
};
1029 ast_log(LOG_NOTICE
,"new_find_extension called with %s on (sub)tree %s action=%s\n", str
, tree
->x
, action2str(action
));
1031 ast_log(LOG_NOTICE
,"new_find_extension called with %s on (sub)tree NULL action=%s\n", str
, action2str(action
));
1033 for (p
=tree
; p
; p
=p
->alt_char
) {
1034 if (p
->x
[0] == 'N') {
1035 if (p
->x
[1] == 0 && *str
>= '2' && *str
<= '9' ) {
1036 #define NEW_MATCHER_CHK_MATCH \
1037 if (p->exten && !(*(str+1))) { /* if a shorter pattern matches along the way, might as well report it */ \
1038 if (action == E_MATCH || action == E_SPAWN || action == E_FINDLABEL) { /* if in CANMATCH/MATCHMORE, don't let matches get in the way */ \
1039 update_scoreboard(score, length+1, spec+p->specificity, p->exten,0,callerid, p->deleted, p); \
1040 if (!p->deleted) { \
1041 if (action == E_FINDLABEL) { \
1042 if (ast_hashtab_lookup(score->exten->peer_label_table, &pattern)) { \
1043 ast_debug(4, "Found label in preferred extension\n"); \
1047 ast_debug(4,"returning an exact match-- first found-- %s\n", p->exten->exten); \
1048 return; /* the first match, by definition, will be the best, because of the sorted tree */ \
1054 #define NEW_MATCHER_RECURSE \
1055 if (p->next_char && ( *(str+1) || (p->next_char->x[0] == '/' && p->next_char->x[1] == 0) \
1056 || p->next_char->x[0] == '!')) { \
1057 if (*(str+1) || p->next_char->x[0] == '!') { \
1058 new_find_extension(str+1, score, p->next_char, length+1, spec+p->specificity, callerid, label, action); \
1059 if (score->exten) { \
1060 ast_debug(4,"returning an exact match-- %s\n", score->exten->exten); \
1061 return; /* the first match is all we need */ \
1064 new_find_extension("/", score, p->next_char, length+1, spec+p->specificity, callerid, label, action); \
1065 if (score->exten || ((action == E_CANMATCH || action == E_MATCHMORE) && score->canmatch)) { \
1066 ast_debug(4,"returning a (can/more) match--- %s\n", score->exten ? score->exten->exten : \
1068 return; /* the first match is all we need */ \
1071 } else if (p->next_char && !*(str+1)) { \
1072 score->canmatch = 1; \
1073 score->canmatch_exten = get_canmatch_exten(p); \
1074 if (action == E_CANMATCH || action == E_MATCHMORE) { \
1075 ast_debug(4,"returning a canmatch/matchmore--- str=%s\n", str); \
1080 NEW_MATCHER_CHK_MATCH
;
1081 NEW_MATCHER_RECURSE
;
1083 } else if (p
->x
[0] == 'Z') {
1084 if (p
->x
[1] == 0 && *str
>= '1' && *str
<= '9' ) {
1085 NEW_MATCHER_CHK_MATCH
;
1086 NEW_MATCHER_RECURSE
;
1088 } else if (p
->x
[0] == 'X') {
1089 if (p
->x
[1] == 0 && *str
>= '0' && *str
<= '9' ) {
1090 NEW_MATCHER_CHK_MATCH
;
1091 NEW_MATCHER_RECURSE
;
1093 } else if (p
->x
[0] == '.' && p
->x
[1] == 0) {
1094 /* how many chars will the . match against? */
1096 const char *str2
= str
;
1097 while (*str2
&& *str2
!= '/') {
1101 if (p
->exten
&& *str2
!= '/') {
1102 update_scoreboard(score
, length
+i
, spec
+(i
*p
->specificity
), p
->exten
, '.', callerid
, p
->deleted
, p
);
1104 ast_debug(4,"return because scoreboard has a match with '/'--- %s\n", score
->exten
->exten
);
1105 return; /* the first match is all we need */
1108 if (p
->next_char
&& p
->next_char
->x
[0] == '/' && p
->next_char
->x
[1] == 0) {
1109 new_find_extension("/", score
, p
->next_char
, length
+i
, spec
+(p
->specificity
*i
), callerid
, label
, action
);
1110 if (score
->exten
|| ((action
== E_CANMATCH
|| action
== E_MATCHMORE
) && score
->canmatch
)) {
1111 ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set--- %s\n", score
->exten
? score
->exten
->exten
: "NULL");
1112 return; /* the first match is all we need */
1115 } else if (p
->x
[0] == '!' && p
->x
[1] == 0) {
1116 /* how many chars will the . match against? */
1118 const char *str2
= str
;
1119 while (*str2
&& *str2
!= '/') {
1123 if (p
->exten
&& *str2
!= '/') {
1124 update_scoreboard(score
, length
+1, spec
+(p
->specificity
*i
), p
->exten
, '!', callerid
, p
->deleted
, p
);
1126 ast_debug(4,"return because scoreboard has a '!' match--- %s\n", score
->exten
->exten
);
1127 return; /* the first match is all we need */
1130 if (p
->next_char
&& p
->next_char
->x
[0] == '/' && p
->next_char
->x
[1] == 0) {
1131 new_find_extension("/", score
, p
->next_char
, length
+i
, spec
+(p
->specificity
*i
), callerid
, label
, action
);
1132 if (score
->exten
|| ((action
== E_CANMATCH
|| action
== E_MATCHMORE
) && score
->canmatch
)) {
1133 ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/' and '!'--- %s\n", score
->exten
? score
->exten
->exten
: "NULL");
1134 return; /* the first match is all we need */
1137 } else if (p
->x
[0] == '/' && p
->x
[1] == 0) {
1138 /* the pattern in the tree includes the cid match! */
1139 if (p
->next_char
&& callerid
&& *callerid
) {
1140 new_find_extension(callerid
, score
, p
->next_char
, length
+1, spec
, callerid
, label
, action
);
1141 if (score
->exten
|| ((action
== E_CANMATCH
|| action
== E_MATCHMORE
) && score
->canmatch
)) {
1142 ast_debug(4,"return because scoreboard has exact match OR CANMATCH/MATCHMORE & canmatch set with '/'--- %s\n", score
->exten
? score
->exten
->exten
: "NULL");
1143 return; /* the first match is all we need */
1146 } else if (index(p
->x
, *str
)) {
1147 ast_debug(4, "Nothing strange about this match\n");
1148 NEW_MATCHER_CHK_MATCH
;
1149 NEW_MATCHER_RECURSE
;
1152 ast_debug(4,"return at end of func\n");
1155 /* the algorithm for forming the extension pattern tree is also a bit simple; you
1156 * traverse all the extensions in a context, and for each char of the extension,
1157 * you see if it exists in the tree; if it doesn't, you add it at the appropriate
1158 * spot. What more can I say? At the end of each exten, you cap it off by adding the
1159 * address of the extension involved. Duplicate patterns will be complained about.
1161 * Ideally, this would be done for each context after it is created and fully
1162 * filled. It could be done as a finishing step after extensions.conf or .ael is
1163 * loaded, or it could be done when the first search is encountered. It should only
1164 * have to be done once, until the next unload or reload.
1166 * I guess forming this pattern tree would be analogous to compiling a regex. Except
1167 * that a regex only handles 1 pattern, really. This trie holds any number
1168 * of patterns. Well, really, it **could** be considered a single pattern,
1169 * where the "|" (or) operator is allowed, I guess, in a way, sort of...
1172 static struct match_char
*already_in_tree(struct match_char
*current
, char *pat
)
1174 struct match_char
*t
;
1179 for (t
= current
; t
; t
= t
->alt_char
) {
1180 if (!strcmp(pat
, t
->x
)) /* uh, we may want to sort exploded [] contents to make matching easy */
1187 /* The first arg is the location of the tree ptr, or the
1188 address of the next_char ptr in the node, so we can mess
1189 with it, if we need to insert at the beginning of the list */
1191 static void insert_in_next_chars_alt_char_list(struct match_char
**parent_ptr
, struct match_char
*node
)
1193 struct match_char
*curr
, *lcurr
;
1195 /* insert node into the tree at "current", so the alt_char list from current is
1196 sorted in increasing value as you go to the leaves */
1197 if (!(*parent_ptr
)) {
1200 if ((*parent_ptr
)->specificity
> node
->specificity
){
1201 /* insert at head */
1202 node
->alt_char
= (*parent_ptr
);
1205 lcurr
= *parent_ptr
;
1206 for (curr
=(*parent_ptr
)->alt_char
; curr
; curr
= curr
->alt_char
) {
1207 if (curr
->specificity
> node
->specificity
) {
1208 node
->alt_char
= curr
;
1209 lcurr
->alt_char
= node
;
1216 lcurr
->alt_char
= node
;
1224 static struct match_char
*add_pattern_node(struct ast_context
*con
, struct match_char
*current
, char *pattern
, int is_pattern
, int already
, int specificity
, struct match_char
**nextcharptr
)
1226 struct match_char
*m
;
1228 if (!(m
= ast_calloc(1, sizeof(*m
))))
1231 if (!(m
->x
= ast_strdup(pattern
))) {
1236 /* the specificity scores are the same as used in the old
1238 m
->is_pattern
= is_pattern
;
1239 if (specificity
== 1 && is_pattern
&& pattern
[0] == 'N')
1240 m
->specificity
= 0x0802;
1241 else if (specificity
== 1 && is_pattern
&& pattern
[0] == 'Z')
1242 m
->specificity
= 0x0901;
1243 else if (specificity
== 1 && is_pattern
&& pattern
[0] == 'X')
1244 m
->specificity
= 0x0a00;
1245 else if (specificity
== 1 && is_pattern
&& pattern
[0] == '.')
1246 m
->specificity
= 0x10000;
1247 else if (specificity
== 1 && is_pattern
&& pattern
[0] == '!')
1248 m
->specificity
= 0x20000;
1250 m
->specificity
= specificity
;
1252 if (!con
->pattern_tree
) {
1253 insert_in_next_chars_alt_char_list(&con
->pattern_tree
, m
);
1255 if (already
) { /* switch to the new regime (traversing vs appending)*/
1256 insert_in_next_chars_alt_char_list(nextcharptr
, m
);
1258 insert_in_next_chars_alt_char_list(¤t
->next_char
, m
);
1265 static struct match_char
*add_exten_to_pattern_tree(struct ast_context
*con
, struct ast_exten
*e1
, int findonly
)
1267 struct match_char
*m1
= NULL
, *m2
= NULL
, **m0
;
1273 char *s1
= extenbuf
;
1274 int l1
= strlen(e1
->exten
) + strlen(e1
->cidmatch
) + 2;
1277 strncpy(extenbuf
,e1
->exten
,sizeof(extenbuf
));
1278 if (e1
->matchcid
&& l1
<= sizeof(extenbuf
)) {
1279 strcat(extenbuf
,"/");
1280 strcat(extenbuf
,e1
->cidmatch
);
1281 } else if (l1
> sizeof(extenbuf
)) {
1282 ast_log(LOG_ERROR
,"The pattern %s/%s is too big to deal with: it will be ignored! Disaster!\n", e1
->exten
, e1
->cidmatch
);
1286 ast_log(LOG_DEBUG
,"Adding exten %s%c%s to tree\n", s1
, e1
->matchcid
? '/':' ', e1
->matchcid
? e1
->cidmatch
: "");
1288 m1
= con
->pattern_tree
; /* each pattern starts over at the root of the pattern tree */
1289 m0
= &con
->pattern_tree
;
1297 if (pattern
&& *s1
== '[' && *(s1
-1) != '\\') {
1300 s1
++; /* get past the '[' */
1301 while (*s1
!= ']' && *(s1
-1) != '\\' ) {
1303 if (*(s1
+1) == ']') {
1306 } else if (*(s1
+1) == '\\') {
1309 } else if (*(s1
+1) == '-') {
1312 } else if (*(s1
+1) == '[') {
1316 } else if (*s1
== '-') { /* remember to add some error checking to all this! */
1319 for (s3
++; s3
<= s4
; s3
++) {
1327 *s2
= 0; /* null terminate the exploded range */
1328 /* sort the characters */
1330 specif
= strlen(buf
);
1331 qsort(buf
, specif
, 1, compare_char
);
1341 if (*s1
== 'n') /* make sure n,x,z patterns are canonicalized to N,X,Z */
1343 else if (*s1
== 'x')
1345 else if (*s1
== 'z')
1354 if (already
&& (m2
=already_in_tree(m1
,buf
)) && m2
->next_char
) {
1355 if (!(*(s1
+1))) { /* if this is the end of the pattern, but not the end of the tree, then mark this node with the exten...
1356 a shorter pattern might win if the longer one doesn't match */
1360 m1
= m2
->next_char
; /* m1 points to the node to compare against */
1361 m0
= &m2
->next_char
; /* m0 points to the ptr that points to m1 */
1362 } else { /* not already OR not m2 OR nor m2->next_char */
1366 m1
= m2
; /* while m0 stays the same */
1370 m1
= add_pattern_node(con
, m1
, buf
, pattern
, already
,specif
, m0
); /* m1 is the node just added */
1371 m0
= &m1
->next_char
;
1381 s1
++; /* advance to next char */
1386 static void create_match_char_tree(struct ast_context
*con
)
1388 struct ast_hashtab_iter
*t1
;
1389 struct ast_exten
*e1
;
1391 int biggest_bucket
, resizes
, numobjs
, numbucks
;
1393 ast_log(LOG_DEBUG
,"Creating Extension Trie for context %s\n", con
->name
);
1394 ast_hashtab_get_stats(con
->root_table
, &biggest_bucket
, &resizes
, &numobjs
, &numbucks
);
1395 ast_log(LOG_DEBUG
,"This tree has %d objects in %d bucket lists, longest list=%d objects, and has resized %d times\n",
1396 numobjs
, numbucks
, biggest_bucket
, resizes
);
1398 t1
= ast_hashtab_start_traversal(con
->root_table
);
1399 while( (e1
= ast_hashtab_next(t1
)) ) {
1401 add_exten_to_pattern_tree(con
, e1
, 0);
1403 ast_log(LOG_ERROR
,"Attempt to create extension with no extension name.\n");
1405 ast_hashtab_end_traversal(t1
);
1408 static void destroy_pattern_tree(struct match_char
*pattern_tree
) /* pattern tree is a simple binary tree, sort of, so the proper way to destroy it is... recursively! */
1410 /* destroy all the alternates */
1411 if (pattern_tree
->alt_char
) {
1412 destroy_pattern_tree(pattern_tree
->alt_char
);
1413 pattern_tree
->alt_char
= 0;
1415 /* destroy all the nexts */
1416 if (pattern_tree
->next_char
) {
1417 destroy_pattern_tree(pattern_tree
->next_char
);
1418 pattern_tree
->next_char
= 0;
1420 pattern_tree
->exten
= 0; /* never hurts to make sure there's no pointers laying around */
1421 if (pattern_tree
->x
)
1422 free(pattern_tree
->x
);
1427 * Special characters used in patterns:
1428 * '_' underscore is the leading character of a pattern.
1429 * In other position it is treated as a regular char.
1430 * ' ' '-' space and '-' are separator and ignored.
1431 * . one or more of any character. Only allowed at the end of
1433 * ! zero or more of anything. Also impacts the result of CANMATCH
1434 * and MATCHMORE. Only allowed at the end of a pattern.
1435 * In the core routine, ! causes a match with a return code of 2.
1436 * In turn, depending on the search mode: (XXX check if it is implemented)
1437 * - E_MATCH retuns 1 (does match)
1438 * - E_MATCHMORE returns 0 (no match)
1439 * - E_CANMATCH returns 1 (does match)
1441 * / should not appear as it is considered the separator of the CID info.
1442 * XXX at the moment we may stop on this char.
1444 * X Z N match ranges 0-9, 1-9, 2-9 respectively.
1445 * [ denotes the start of a set of character. Everything inside
1446 * is considered literally. We can have ranges a-d and individual
1447 * characters. A '[' and '-' can be considered literally if they
1448 * are just before ']'.
1449 * XXX currently there is no way to specify ']' in a range, nor \ is
1450 * considered specially.
1452 * When we compare a pattern with a specific extension, all characters in the extension
1453 * itself are considered literally with the only exception of '-' which is considered
1454 * as a separator and thus ignored.
1455 * XXX do we want to consider space as a separator as well ?
1456 * XXX do we want to consider the separators in non-patterns as well ?
1460 * \brief helper functions to sort extensions and patterns in the desired way,
1461 * so that more specific patterns appear first.
1463 * ext_cmp1 compares individual characters (or sets of), returning
1464 * an int where bits 0-7 are the ASCII code of the first char in the set,
1465 * while bit 8-15 are the cardinality of the set minus 1.
1466 * This way more specific patterns (smaller cardinality) appear first.
1467 * Wildcards have a special value, so that we can directly compare them to
1468 * sets by subtracting the two values. In particular:
1469 * 0x000xx one character, xx
1470 * 0x0yyxx yy character set starting with xx
1471 * 0x10000 '.' (one or more of anything)
1472 * 0x20000 '!' (zero or more of anything)
1473 * 0x30000 NUL (end of string)
1474 * 0x40000 error in set.
1475 * The pointer to the string is advanced according to needs.
1477 * 1. the empty set is equivalent to NUL.
1478 * 2. given that a full set has always 0 as the first element,
1479 * we could encode the special cases as 0xffXX where XX
1480 * is 1, 2, 3, 4 as used above.
1482 static int ext_cmp1(const char **p
)
1485 int c
, cmin
= 0xff, count
= 0;
1488 /* load, sign extend and advance pointer until we find
1489 * a valid character.
1491 while ( (c
= *(*p
)++) && (c
== ' ' || c
== '-') )
1492 ; /* ignore some characters */
1494 /* always return unless we have a set of chars */
1495 switch (toupper(c
)) {
1496 default: /* ordinary character */
1497 return 0x0000 | (c
& 0xff);
1499 case 'N': /* 2..9 */
1500 return 0x0700 | '2' ;
1502 case 'X': /* 0..9 */
1503 return 0x0900 | '0';
1505 case 'Z': /* 1..9 */
1506 return 0x0800 | '1';
1508 case '.': /* wildcard */
1511 case '!': /* earlymatch */
1512 return 0x20000; /* less specific than NULL */
1514 case '\0': /* empty string */
1518 case '[': /* pattern */
1521 /* locate end of set */
1522 end
= strchr(*p
, ']');
1525 ast_log(LOG_WARNING
, "Wrong usage of [] in the extension\n");
1526 return 0x40000; /* XXX make this entry go last... */
1529 bzero(chars
, sizeof(chars
)); /* clear all chars in the set */
1530 for (; *p
< end
; (*p
)++) {
1531 unsigned char c1
, c2
; /* first-last char in range */
1532 c1
= (unsigned char)((*p
)[0]);
1533 if (*p
+ 2 < end
&& (*p
)[1] == '-') { /* this is a range */
1534 c2
= (unsigned char)((*p
)[2]);
1535 *p
+= 2; /* skip a total of 3 chars */
1536 } else /* individual character */
1540 for (; c1
<= c2
; c1
++) {
1541 uint32_t mask
= 1 << (c1
% 32);
1542 if ( (chars
[ c1
/ 32 ] & mask
) == 0)
1544 chars
[ c1
/ 32 ] |= mask
;
1548 return count
== 0 ? 0x30000 : (count
| cmin
);
1552 * \brief the full routine to compare extensions in rules.
1554 static int ext_cmp(const char *a
, const char *b
)
1556 /* make sure non-patterns come first.
1557 * If a is not a pattern, it either comes first or
1558 * we use strcmp to compare the strings.
1563 return (b
[0] == '_') ? -1 : strcmp(a
, b
);
1565 /* Now we know a is a pattern; if b is not, a comes first */
1568 #if 0 /* old mode for ext matching */
1569 return strcmp(a
, b
);
1571 /* ok we need full pattern sorting routine */
1572 while (!ret
&& a
&& b
)
1573 ret
= ext_cmp1(&a
) - ext_cmp1(&b
);
1577 return (ret
> 0) ? 1 : -1;
1580 int ast_extension_cmp(const char *a
, const char *b
)
1582 return ext_cmp(a
, b
);
1587 * \brief used ast_extension_{match|close}
1588 * mode is as follows:
1589 * E_MATCH success only on exact match
1590 * E_MATCHMORE success only on partial match (i.e. leftover digits in pattern)
1591 * E_CANMATCH either of the above.
1592 * \retval 0 on no-match
1593 * \retval 1 on match
1594 * \retval 2 on early match.
1597 static int _extension_match_core(const char *pattern
, const char *data
, enum ext_match_t mode
)
1599 mode
&= E_MATCH_MASK
; /* only consider the relevant bits */
1601 #ifdef NEED_DEBUG_HERE
1602 ast_log(LOG_NOTICE
,"match core: pat: '%s', dat: '%s', mode=%d\n", pattern
, data
, (int)mode
);
1605 if ( (mode
== E_MATCH
) && (pattern
[0] == '_') && (!strcasecmp(pattern
,data
)) ) { /* note: if this test is left out, then _x. will not match _x. !!! */
1606 #ifdef NEED_DEBUG_HERE
1607 ast_log(LOG_NOTICE
,"return (1) - pattern matches pattern\n");
1612 if (pattern
[0] != '_') { /* not a pattern, try exact or partial match */
1613 int ld
= strlen(data
), lp
= strlen(pattern
);
1615 if (lp
< ld
) { /* pattern too short, cannot match */
1616 #ifdef NEED_DEBUG_HERE
1617 ast_log(LOG_NOTICE
,"return (0) - pattern too short, cannot match\n");
1621 /* depending on the mode, accept full or partial match or both */
1622 if (mode
== E_MATCH
) {
1623 #ifdef NEED_DEBUG_HERE
1624 ast_log(LOG_NOTICE
,"return (!strcmp(%s,%s) when mode== E_MATCH)\n", pattern
, data
);
1626 return !strcmp(pattern
, data
); /* 1 on match, 0 on fail */
1628 if (ld
== 0 || !strncasecmp(pattern
, data
, ld
)) { /* partial or full match */
1629 #ifdef NEED_DEBUG_HERE
1630 ast_log(LOG_NOTICE
,"return (mode(%d) == E_MATCHMORE ? lp(%d) > ld(%d) : 1)\n", mode
, lp
, ld
);
1632 return (mode
== E_MATCHMORE
) ? lp
> ld
: 1; /* XXX should consider '!' and '/' ? */
1634 #ifdef NEED_DEBUG_HERE
1635 ast_log(LOG_NOTICE
,"return (0) when ld(%d) > 0 && pattern(%s) != data(%s)\n", ld
, pattern
, data
);
1640 pattern
++; /* skip leading _ */
1642 * XXX below we stop at '/' which is a separator for the CID info. However we should
1643 * not store '/' in the pattern at all. When we insure it, we can remove the checks.
1645 while (*data
&& *pattern
&& *pattern
!= '/') {
1648 if (*data
== '-') { /* skip '-' in data (just a separator) */
1652 switch (toupper(*pattern
)) {
1653 case '[': /* a range */
1654 end
= strchr(pattern
+1, ']'); /* XXX should deal with escapes ? */
1656 ast_log(LOG_WARNING
, "Wrong usage of [] in the extension\n");
1657 return 0; /* unconditional failure */
1659 for (pattern
++; pattern
!= end
; pattern
++) {
1660 if (pattern
+2 < end
&& pattern
[1] == '-') { /* this is a range */
1661 if (*data
>= pattern
[0] && *data
<= pattern
[2])
1662 break; /* match found */
1664 pattern
+= 2; /* skip a total of 3 chars */
1667 } else if (*data
== pattern
[0])
1668 break; /* match found */
1670 if (pattern
== end
) {
1671 #ifdef NEED_DEBUG_HERE
1672 ast_log(LOG_NOTICE
,"return (0) when pattern==end\n");
1676 pattern
= end
; /* skip and continue */
1679 if (*data
< '2' || *data
> '9') {
1680 #ifdef NEED_DEBUG_HERE
1681 ast_log(LOG_NOTICE
,"return (0) N is matched\n");
1687 if (*data
< '0' || *data
> '9') {
1688 #ifdef NEED_DEBUG_HERE
1689 ast_log(LOG_NOTICE
,"return (0) X is matched\n");
1695 if (*data
< '1' || *data
> '9') {
1696 #ifdef NEED_DEBUG_HERE
1697 ast_log(LOG_NOTICE
,"return (0) Z is matched\n");
1702 case '.': /* Must match, even with more digits */
1703 #ifdef NEED_DEBUG_HERE
1704 ast_log(LOG_NOTICE
,"return (1) when '.' is matched\n");
1707 case '!': /* Early match */
1708 #ifdef NEED_DEBUG_HERE
1709 ast_log(LOG_NOTICE
,"return (2) when '!' is matched\n");
1713 case '-': /* Ignore these in patterns */
1714 data
--; /* compensate the final data++ */
1717 if (*data
!= *pattern
) {
1718 #ifdef NEED_DEBUG_HERE
1719 ast_log(LOG_NOTICE
,"return (0) when *data(%c) != *pattern(%c)\n", *data
, *pattern
);
1728 if (*data
) /* data longer than pattern, no match */ {
1729 #ifdef NEED_DEBUG_HERE
1730 ast_log(LOG_NOTICE
,"return (0) when data longer than pattern\n");
1736 * match so far, but ran off the end of the data.
1737 * Depending on what is next, determine match or not.
1739 if (*pattern
== '\0' || *pattern
== '/') { /* exact match */
1740 #ifdef NEED_DEBUG_HERE
1741 ast_log(LOG_NOTICE
,"at end, return (%d) in 'exact match'\n", (mode
==E_MATCHMORE
) ? 0 : 1);
1743 return (mode
== E_MATCHMORE
) ? 0 : 1; /* this is a failure for E_MATCHMORE */
1744 } else if (*pattern
== '!') { /* early match */
1745 #ifdef NEED_DEBUG_HERE
1746 ast_log(LOG_NOTICE
,"at end, return (2) when '!' is matched\n");
1749 } else { /* partial match */
1750 #ifdef NEED_DEBUG_HERE
1751 ast_log(LOG_NOTICE
,"at end, return (%d) which deps on E_MATCH\n", (mode
== E_MATCH
) ? 0 : 1);
1753 return (mode
== E_MATCH
) ? 0 : 1; /* this is a failure for E_MATCH */
1758 * Wrapper around _extension_match_core() to do performance measurement
1759 * using the profiling code.
1761 static int extension_match_core(const char *pattern
, const char *data
, enum ext_match_t mode
)
1764 static int prof_id
= -2; /* marker for 'unallocated' id */
1766 prof_id
= ast_add_profile("ext_match", 0);
1767 ast_mark(prof_id
, 1);
1768 i
= _extension_match_core(pattern
, data
, mode
);
1769 ast_mark(prof_id
, 0);
1773 int ast_extension_match(const char *pattern
, const char *data
)
1775 return extension_match_core(pattern
, data
, E_MATCH
);
1778 int ast_extension_close(const char *pattern
, const char *data
, int needmore
)
1780 if (needmore
!= E_MATCHMORE
&& needmore
!= E_CANMATCH
)
1781 ast_log(LOG_WARNING
, "invalid argument %d\n", needmore
);
1782 return extension_match_core(pattern
, data
, needmore
);
1785 struct fake_context
/* this struct is purely for matching in the hashtab */
1788 struct ast_exten
*root
;
1789 struct ast_hashtab
*root_table
;
1790 struct match_char
*pattern_tree
;
1791 struct ast_context
*next
;
1792 struct ast_include
*includes
;
1793 struct ast_ignorepat
*ignorepats
;
1794 const char *registrar
;
1796 AST_LIST_HEAD_NOLOCK(, ast_sw
) alts
;
1797 ast_mutex_t macrolock
;
1801 struct ast_context
*ast_context_find(const char *name
)
1803 struct ast_context
*tmp
= NULL
;
1804 struct fake_context item
;
1805 strncpy(item
.name
,name
,256);
1806 ast_rdlock_contexts();
1807 if( contexts_table
) {
1808 tmp
= ast_hashtab_lookup(contexts_table
,&item
);
1810 while ( (tmp
= ast_walk_contexts(tmp
)) ) {
1811 if (!name
|| !strcasecmp(name
, tmp
->name
))
1815 ast_unlock_contexts();
1819 #define STATUS_NO_CONTEXT 1
1820 #define STATUS_NO_EXTENSION 2
1821 #define STATUS_NO_PRIORITY 3
1822 #define STATUS_NO_LABEL 4
1823 #define STATUS_SUCCESS 5
1825 static int matchcid(const char *cidpattern
, const char *callerid
)
1827 /* If the Caller*ID pattern is empty, then we're matching NO Caller*ID, so
1828 failing to get a number should count as a match, otherwise not */
1830 if (ast_strlen_zero(callerid
))
1831 return ast_strlen_zero(cidpattern
) ? 1 : 0;
1833 return ast_extension_match(cidpattern
, callerid
);
1836 struct ast_exten
*pbx_find_extension(struct ast_channel
*chan
,
1837 struct ast_context
*bypass
, struct pbx_find_info
*q
,
1838 const char *context
, const char *exten
, int priority
,
1839 const char *label
, const char *callerid
, enum ext_match_t action
)
1842 struct ast_context
*tmp
= NULL
;
1843 struct ast_exten
*e
= NULL
, *eroot
= NULL
;
1844 struct ast_include
*i
= NULL
;
1845 struct ast_sw
*sw
= NULL
;
1846 struct ast_exten pattern
= {NULL
, };
1847 struct scoreboard score
= {0, };
1848 struct ast_str
*tmpdata
= NULL
;
1850 pattern
.label
= label
;
1851 pattern
.priority
= priority
;
1852 #ifdef NEED_DEBUG_HERE
1853 ast_log(LOG_NOTICE
,"Looking for cont/ext/prio/label/action = %s/%s/%d/%s/%d\n", context
, exten
, priority
, label
, (int)action
);
1856 if (ast_strlen_zero(exten
))
1859 /* Initialize status if appropriate */
1860 if (q
->stacklen
== 0) {
1861 q
->status
= STATUS_NO_CONTEXT
;
1864 q
->foundcontext
= NULL
;
1865 } else if (q
->stacklen
>= AST_PBX_MAX_STACK
) {
1866 ast_log(LOG_WARNING
, "Maximum PBX stack exceeded\n");
1870 /* Check first to see if we've already been checked */
1871 for (x
= 0; x
< q
->stacklen
; x
++) {
1872 if (!strcasecmp(q
->incstack
[x
], context
))
1876 if (bypass
) /* bypass means we only look there */
1878 else { /* look in contexts */
1879 struct fake_context item
;
1880 strncpy(item
.name
,context
,256);
1881 tmp
= ast_hashtab_lookup(contexts_table
,&item
);
1884 while ((tmp
= ast_walk_contexts(tmp
)) ) {
1885 if (!strcmp(tmp
->name
, context
))
1894 if (q
->status
< STATUS_NO_EXTENSION
)
1895 q
->status
= STATUS_NO_EXTENSION
;
1897 /* Do a search for matching extension */
1900 score
.total_specificity
= 0;
1902 score
.total_length
= 0;
1903 if (!tmp
->pattern_tree
&& tmp
->root_table
)
1905 create_match_char_tree(tmp
);
1907 ast_log(LOG_DEBUG
,"Tree Created in context %s:\n", context
);
1908 log_match_char_tree(tmp
->pattern_tree
," ");
1912 ast_log(LOG_NOTICE
,"The Trie we are searching in:\n");
1913 log_match_char_tree(tmp
->pattern_tree
, ":: ");
1917 if (!ast_strlen_zero(overrideswitch
)) {
1918 char *osw
= ast_strdupa(overrideswitch
), *name
;
1919 struct ast_switch
*asw
;
1920 ast_switch_f
*aswf
= NULL
;
1924 name
= strsep(&osw
, "/");
1925 asw
= pbx_findswitch(name
);
1928 ast_log(LOG_WARNING
, "No such switch '%s'\n", name
);
1932 if (osw
&& strchr(osw
, '$')) {
1936 if (eval
&& !(tmpdata
= ast_str_thread_get(&switch_data
, 512))) {
1937 ast_log(LOG_WARNING
, "Can't evaluate overrideswitch?!");
1940 /* Substitute variables now */
1941 pbx_substitute_variables_helper(chan
, osw
, tmpdata
->str
, tmpdata
->len
);
1942 datap
= tmpdata
->str
;
1947 /* equivalent of extension_match_core() at the switch level */
1948 if (action
== E_CANMATCH
)
1949 aswf
= asw
->canmatch
;
1950 else if (action
== E_MATCHMORE
)
1951 aswf
= asw
->matchmore
;
1952 else /* action == E_MATCH */
1958 ast_autoservice_start(chan
);
1960 res
= aswf(chan
, context
, exten
, priority
, callerid
, datap
);
1962 ast_autoservice_stop(chan
);
1965 if (res
) { /* Got a match */
1968 q
->foundcontext
= context
;
1969 /* XXX keep status = STATUS_NO_CONTEXT ? */
1975 if (extenpatternmatchnew
) {
1976 new_find_extension(exten
, &score
, tmp
->pattern_tree
, 0, 0, callerid
, label
, action
);
1977 eroot
= score
.exten
;
1979 if (score
.last_char
== '!' && action
== E_MATCHMORE
) {
1980 /* We match an extension ending in '!'.
1981 * The decision in this case is final and is NULL (no match).
1983 #ifdef NEED_DEBUG_HERE
1984 ast_log(LOG_NOTICE
,"Returning MATCHMORE NULL with exclamation point.\n");
1989 if (!eroot
&& (action
== E_CANMATCH
|| action
== E_MATCHMORE
) && score
.canmatch_exten
) {
1990 q
->status
= STATUS_SUCCESS
;
1991 #ifdef NEED_DEBUG_HERE
1992 ast_log(LOG_NOTICE
,"Returning CANMATCH exten %s\n", score
.canmatch_exten
->exten
);
1994 return score
.canmatch_exten
;
1997 if ((action
== E_MATCHMORE
|| action
== E_CANMATCH
) && eroot
) {
1999 struct ast_exten
*z
= trie_find_next_match(score
.node
);
2001 #ifdef NEED_DEBUG_HERE
2002 ast_log(LOG_NOTICE
,"Returning CANMATCH/MATCHMORE next_match exten %s\n", z
->exten
);
2005 if (score
.canmatch_exten
) {
2006 #ifdef NEED_DEBUG_HERE
2007 ast_log(LOG_NOTICE
,"Returning CANMATCH/MATCHMORE canmatchmatch exten %s(%p)\n", score
.canmatch_exten
->exten
, score
.canmatch_exten
);
2009 return score
.canmatch_exten
;
2011 #ifdef NEED_DEBUG_HERE
2012 ast_log(LOG_NOTICE
,"Returning CANMATCH/MATCHMORE next_match exten NULL\n");
2018 #ifdef NEED_DEBUG_HERE
2019 ast_log(LOG_NOTICE
,"Returning CANMATCH/MATCHMORE NULL (no next_match)\n");
2021 return NULL
; /* according to the code, complete matches are null matches in MATCHMORE mode */
2025 /* found entry, now look for the right priority */
2026 if (q
->status
< STATUS_NO_PRIORITY
)
2027 q
->status
= STATUS_NO_PRIORITY
;
2029 if (action
== E_FINDLABEL
&& label
) {
2030 if (q
->status
< STATUS_NO_LABEL
)
2031 q
->status
= STATUS_NO_LABEL
;
2032 e
= ast_hashtab_lookup(eroot
->peer_label_table
, &pattern
);
2034 e
= ast_hashtab_lookup(eroot
->peer_table
, &pattern
);
2036 if (e
) { /* found a valid match */
2037 q
->status
= STATUS_SUCCESS
;
2038 q
->foundcontext
= context
;
2039 #ifdef NEED_DEBUG_HERE
2040 ast_log(LOG_NOTICE
,"Returning complete match of exten %s\n", e
->exten
);
2045 } else { /* the old/current default exten pattern match algorithm */
2047 /* scan the list trying to match extension and CID */
2049 while ( (eroot
= ast_walk_context_extensions(tmp
, eroot
)) ) {
2050 int match
= extension_match_core(eroot
->exten
, exten
, action
);
2051 /* 0 on fail, 1 on match, 2 on earlymatch */
2053 if (!match
|| (eroot
->matchcid
&& !matchcid(eroot
->cidmatch
, callerid
)))
2054 continue; /* keep trying */
2055 if (match
== 2 && action
== E_MATCHMORE
) {
2056 /* We match an extension ending in '!'.
2057 * The decision in this case is final and is NULL (no match).
2061 /* found entry, now look for the right priority */
2062 if (q
->status
< STATUS_NO_PRIORITY
)
2063 q
->status
= STATUS_NO_PRIORITY
;
2065 if (action
== E_FINDLABEL
&& label
) {
2066 if (q
->status
< STATUS_NO_LABEL
)
2067 q
->status
= STATUS_NO_LABEL
;
2068 e
= ast_hashtab_lookup(eroot
->peer_label_table
, &pattern
);
2070 e
= ast_hashtab_lookup(eroot
->peer_table
, &pattern
);
2073 while ( (e
= ast_walk_extension_priorities(eroot
, e
)) ) {
2074 /* Match label or priority */
2075 if (action
== E_FINDLABEL
) {
2076 if (q
->status
< STATUS_NO_LABEL
)
2077 q
->status
= STATUS_NO_LABEL
;
2078 if (label
&& e
->label
&& !strcmp(label
, e
->label
))
2079 break; /* found it */
2080 } else if (e
->priority
== priority
) {
2081 break; /* found it */
2082 } /* else keep searching */
2085 if (e
) { /* found a valid match */
2086 q
->status
= STATUS_SUCCESS
;
2087 q
->foundcontext
= context
;
2094 /* Check alternative switches */
2095 AST_LIST_TRAVERSE(&tmp
->alts
, sw
, list
) {
2096 struct ast_switch
*asw
= pbx_findswitch(sw
->name
);
2097 ast_switch_f
*aswf
= NULL
;
2101 ast_log(LOG_WARNING
, "No such switch '%s'\n", sw
->name
);
2104 /* Substitute variables now */
2107 if (!(tmpdata
= ast_str_thread_get(&switch_data
, 512))) {
2108 ast_log(LOG_WARNING
, "Can't evaluate switch?!");
2111 pbx_substitute_variables_helper(chan
, sw
->data
, tmpdata
->str
, tmpdata
->len
);
2114 /* equivalent of extension_match_core() at the switch level */
2115 if (action
== E_CANMATCH
)
2116 aswf
= asw
->canmatch
;
2117 else if (action
== E_MATCHMORE
)
2118 aswf
= asw
->matchmore
;
2119 else /* action == E_MATCH */
2121 datap
= sw
->eval
? tmpdata
->str
: sw
->data
;
2126 ast_autoservice_start(chan
);
2127 res
= aswf(chan
, context
, exten
, priority
, callerid
, datap
);
2129 ast_autoservice_stop(chan
);
2131 if (res
) { /* Got a match */
2134 q
->foundcontext
= context
;
2135 /* XXX keep status = STATUS_NO_CONTEXT ? */
2139 q
->incstack
[q
->stacklen
++] = tmp
->name
; /* Setup the stack */
2140 /* Now try any includes we have in this context */
2141 for (i
= tmp
->includes
; i
; i
= i
->next
) {
2142 if (include_valid(i
)) {
2143 if ((e
= pbx_find_extension(chan
, bypass
, q
, i
->rname
, exten
, priority
, label
, callerid
, action
))) {
2144 #ifdef NEED_DEBUG_HERE
2145 ast_log(LOG_NOTICE
,"Returning recursive match of %s\n", e
->exten
);
2157 * \brief extract offset:length from variable name.
2158 * \return 1 if there is a offset:length part, which is
2159 * trimmed off (values go into variables)
2161 static int parse_variable_name(char *var
, int *offset
, int *length
, int *isfunc
)
2168 for (; *var
; var
++) {
2172 } else if (*var
== ')') {
2174 } else if (*var
== ':' && parens
== 0) {
2176 sscanf(var
, "%d:%d", offset
, length
);
2177 return 1; /* offset:length valid */
2184 *\brief takes a substring. It is ok to call with value == workspace.
2186 * \param offset < 0 means start from the end of the string and set the beginning
2187 * to be that many characters back.
2188 * \param length is the length of the substring, a value less than 0 means to leave
2189 * that many off the end.
2191 * \param workspace_len
2192 * Always return a copy in workspace.
2194 static char *substring(const char *value
, int offset
, int length
, char *workspace
, size_t workspace_len
)
2196 char *ret
= workspace
;
2197 int lr
; /* length of the input string after the copy */
2199 ast_copy_string(workspace
, value
, workspace_len
); /* always make a copy */
2201 lr
= strlen(ret
); /* compute length after copy, so we never go out of the workspace */
2203 /* Quick check if no need to do anything */
2204 if (offset
== 0 && length
>= lr
) /* take the whole string */
2207 if (offset
< 0) { /* translate negative offset into positive ones */
2208 offset
= lr
+ offset
;
2209 if (offset
< 0) /* If the negative offset was greater than the length of the string, just start at the beginning */
2213 /* too large offset result in empty string so we know what to return */
2215 return ret
+ lr
; /* the final '\0' */
2217 ret
+= offset
; /* move to the start position */
2218 if (length
>= 0 && length
< lr
- offset
) /* truncate if necessary */
2220 else if (length
< 0) {
2221 if (lr
> offset
- length
) /* After we remove from the front and from the rear, is there anything left? */
2222 ret
[lr
+ length
- offset
] = '\0';
2230 /*! \brief Support for Asterisk built-in variables in the dialplan
2233 - \ref AstVar Channel variables
2234 - \ref AstCauses The HANGUPCAUSE variable
2236 void pbx_retrieve_variable(struct ast_channel
*c
, const char *var
, char **ret
, char *workspace
, int workspacelen
, struct varshead
*headp
)
2238 const char not_found
= '\0';
2240 const char *s
; /* the result */
2242 int i
, need_substring
;
2243 struct varshead
*places
[2] = { headp
, &globals
}; /* list of places where we may look */
2246 ast_channel_lock(c
);
2247 places
[0] = &c
->varshead
;
2250 * Make a copy of var because parse_variable_name() modifies the string.
2251 * Then if called directly, we might need to run substring() on the result;
2252 * remember this for later in 'need_substring', 'offset' and 'length'
2254 tmpvar
= ast_strdupa(var
); /* parse_variable_name modifies the string */
2255 need_substring
= parse_variable_name(tmpvar
, &offset
, &length
, &i
/* ignored */);
2258 * Look first into predefined variables, then into variable lists.
2259 * Variable 's' points to the result, according to the following rules:
2260 * s == ¬_found (set at the beginning) means that we did not find a
2261 * matching variable and need to look into more places.
2262 * If s != ¬_found, s is a valid result string as follows:
2263 * s = NULL if the variable does not have a value;
2264 * you typically do this when looking for an unset predefined variable.
2265 * s = workspace if the result has been assembled there;
2266 * typically done when the result is built e.g. with an snprintf(),
2267 * so we don't need to do an additional copy.
2268 * s != workspace in case we have a string, that needs to be copied
2269 * (the ast_copy_string is done once for all at the end).
2270 * Typically done when the result is already available in some string.
2272 s
= ¬_found
; /* default value */
2273 if (c
) { /* This group requires a valid channel */
2274 /* Names with common parts are looked up a piece at a time using strncmp. */
2275 if (!strncmp(var
, "CALL", 4)) {
2276 if (!strncmp(var
+ 4, "ING", 3)) {
2277 if (!strcmp(var
+ 7, "PRES")) { /* CALLINGPRES */
2278 snprintf(workspace
, workspacelen
, "%d", c
->cid
.cid_pres
);
2280 } else if (!strcmp(var
+ 7, "ANI2")) { /* CALLINGANI2 */
2281 snprintf(workspace
, workspacelen
, "%d", c
->cid
.cid_ani2
);
2283 } else if (!strcmp(var
+ 7, "TON")) { /* CALLINGTON */
2284 snprintf(workspace
, workspacelen
, "%d", c
->cid
.cid_ton
);
2286 } else if (!strcmp(var
+ 7, "TNS")) { /* CALLINGTNS */
2287 snprintf(workspace
, workspacelen
, "%d", c
->cid
.cid_tns
);
2291 } else if (!strcmp(var
, "HINT")) {
2292 s
= ast_get_hint(workspace
, workspacelen
, NULL
, 0, c
, c
->context
, c
->exten
) ? workspace
: NULL
;
2293 } else if (!strcmp(var
, "HINTNAME")) {
2294 s
= ast_get_hint(NULL
, 0, workspace
, workspacelen
, c
, c
->context
, c
->exten
) ? workspace
: NULL
;
2295 } else if (!strcmp(var
, "EXTEN")) {
2297 } else if (!strcmp(var
, "CONTEXT")) {
2299 } else if (!strcmp(var
, "PRIORITY")) {
2300 snprintf(workspace
, workspacelen
, "%d", c
->priority
);
2302 } else if (!strcmp(var
, "CHANNEL")) {
2304 } else if (!strcmp(var
, "UNIQUEID")) {
2306 } else if (!strcmp(var
, "HANGUPCAUSE")) {
2307 snprintf(workspace
, workspacelen
, "%d", c
->hangupcause
);
2311 if (s
== ¬_found
) { /* look for more */
2312 if (!strcmp(var
, "EPOCH")) {
2313 snprintf(workspace
, workspacelen
, "%u",(int)time(NULL
));
2315 } else if (!strcmp(var
, "SYSTEMNAME")) {
2316 s
= ast_config_AST_SYSTEM_NAME
;
2317 } else if (!strcmp(var
, "ENTITYID")) {
2318 ast_eid_to_str(workspace
, workspacelen
, &g_eid
);
2322 /* if not found, look into chanvars or global vars */
2323 for (i
= 0; s
== ¬_found
&& i
< (sizeof(places
) / sizeof(places
[0])); i
++) {
2324 struct ast_var_t
*variables
;
2327 if (places
[i
] == &globals
)
2328 ast_rwlock_rdlock(&globalslock
);
2329 AST_LIST_TRAVERSE(places
[i
], variables
, entries
) {
2330 if (!strcasecmp(ast_var_name(variables
), var
)) {
2331 s
= ast_var_value(variables
);
2335 if (places
[i
] == &globals
)
2336 ast_rwlock_unlock(&globalslock
);
2338 if (s
== ¬_found
|| s
== NULL
)
2342 ast_copy_string(workspace
, s
, workspacelen
);
2345 *ret
= substring(*ret
, offset
, length
, workspace
, workspacelen
);
2349 ast_channel_unlock(c
);
2352 static void exception_store_free(void *data
)
2354 struct pbx_exception
*exception
= data
;
2355 ast_string_field_free_memory(exception
);
2356 ast_free(exception
);
2359 static struct ast_datastore_info exception_store_info
= {
2360 .type
= "EXCEPTION",
2361 .destroy
= exception_store_free
,
2364 int pbx_builtin_raise_exception(struct ast_channel
*chan
, void *vreason
)
2366 const char *reason
= vreason
;
2367 struct ast_datastore
*ds
= ast_channel_datastore_find(chan
, &exception_store_info
, NULL
);
2368 struct pbx_exception
*exception
= NULL
;
2371 ds
= ast_channel_datastore_alloc(&exception_store_info
, NULL
);
2374 exception
= ast_calloc(1, sizeof(struct pbx_exception
));
2376 ast_channel_datastore_free(ds
);
2379 if (ast_string_field_init(exception
, 128)) {
2380 ast_free(exception
);
2381 ast_channel_datastore_free(ds
);
2384 ds
->data
= exception
;
2385 ast_channel_datastore_add(chan
, ds
);
2387 exception
= ds
->data
;
2389 ast_string_field_set(exception
, reason
, reason
);
2390 ast_string_field_set(exception
, context
, chan
->context
);
2391 ast_string_field_set(exception
, exten
, chan
->exten
);
2392 exception
->priority
= chan
->priority
;
2393 set_ext_pri(chan
, "e", 0);
2397 static int acf_exception_read(struct ast_channel
*chan
, const char *name
, char *data
, char *buf
, size_t buflen
)
2399 struct ast_datastore
*ds
= ast_channel_datastore_find(chan
, &exception_store_info
, NULL
);
2400 struct pbx_exception
*exception
= NULL
;
2401 if (!ds
|| !ds
->data
)
2403 exception
= ds
->data
;
2404 if (!strcasecmp(data
, "REASON"))
2405 ast_copy_string(buf
, exception
->reason
, buflen
);
2406 else if (!strcasecmp(data
, "CONTEXT"))
2407 ast_copy_string(buf
, exception
->context
, buflen
);
2408 else if (!strncasecmp(data
, "EXTEN", 5))
2409 ast_copy_string(buf
, exception
->exten
, buflen
);
2410 else if (!strcasecmp(data
, "PRIORITY"))
2411 snprintf(buf
, buflen
, "%d", exception
->priority
);
2417 static struct ast_custom_function exception_function
= {
2418 .name
= "EXCEPTION",
2419 .synopsis
= "Retrieve the details of the current dialplan exception",
2421 "The following fields are available for retrieval:\n"
2422 " reason INVALID, ERROR, RESPONSETIMEOUT, ABSOLUTETIMEOUT, or custom\n"
2423 " value set by the RaiseException() application\n"
2424 " context The context executing when the exception occurred\n"
2425 " exten The extension executing when the exception occurred\n"
2426 " priority The numeric priority executing when the exception occurred\n",
2427 .syntax
= "EXCEPTION(<field>)",
2428 .read
= acf_exception_read
,
2431 static char *handle_show_functions(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2433 struct ast_custom_function
*acf
;
2439 e
->command
= "core show functions [like]";
2441 "Usage: core show functions [like <text>]\n"
2442 " List builtin functions, optionally only those matching a given string\n";
2448 if (a
->argc
== 5 && (!strcmp(a
->argv
[3], "like")) ) {
2450 } else if (a
->argc
!= 3) {
2451 return CLI_SHOWUSAGE
;
2454 ast_cli(a
->fd
, "%s Custom Functions:\n--------------------------------------------------------------------------------\n", like
? "Matching" : "Installed");
2456 AST_RWLIST_RDLOCK(&acf_root
);
2457 AST_RWLIST_TRAVERSE(&acf_root
, acf
, acflist
) {
2458 if (!like
|| strstr(acf
->name
, a
->argv
[4])) {
2460 ast_cli(a
->fd
, "%-20.20s %-35.35s %s\n", acf
->name
, acf
->syntax
, acf
->synopsis
);
2463 AST_RWLIST_UNLOCK(&acf_root
);
2465 ast_cli(a
->fd
, "%d %scustom functions installed.\n", count_acf
, like
? "matching " : "");
2470 static char *handle_show_function(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
2472 struct ast_custom_function
*acf
;
2473 /* Maximum number of characters added by terminal coloring is 22 */
2474 char infotitle
[64 + AST_MAX_APP
+ 22], syntitle
[40], destitle
[40];
2475 char info
[64 + AST_MAX_APP
], *synopsis
= NULL
, *description
= NULL
;
2476 char stxtitle
[40], *syntax
= NULL
;
2477 int synopsis_size
, description_size
, syntax_size
;
2484 e
->command
= "core show function";
2486 "Usage: core show function <function>\n"
2487 " Describe a particular dialplan function.\n";
2490 wordlen
= strlen(a
->word
);
2491 /* case-insensitive for convenience in this 'complete' function */
2492 AST_RWLIST_RDLOCK(&acf_root
);
2493 AST_RWLIST_TRAVERSE(&acf_root
, acf
, acflist
) {
2494 if (!strncasecmp(a
->word
, acf
->name
, wordlen
) && ++which
> a
->n
) {
2495 ret
= ast_strdup(acf
->name
);
2499 AST_RWLIST_UNLOCK(&acf_root
);
2505 return CLI_SHOWUSAGE
;
2507 if (!(acf
= ast_custom_function_find(a
->argv
[3]))) {
2508 ast_cli(a
->fd
, "No function by that name registered.\n");
2514 synopsis_size
= strlen(acf
->synopsis
) + 23;
2516 synopsis_size
= strlen("Not available") + 23;
2517 synopsis
= alloca(synopsis_size
);
2520 description_size
= strlen(acf
->desc
) + 23;
2522 description_size
= strlen("Not available") + 23;
2523 description
= alloca(description_size
);
2526 syntax_size
= strlen(acf
->syntax
) + 23;
2528 syntax_size
= strlen("Not available") + 23;
2529 syntax
= alloca(syntax_size
);
2531 snprintf(info
, 64 + AST_MAX_APP
, "\n -= Info about function '%s' =- \n\n", acf
->name
);
2532 term_color(infotitle
, info
, COLOR_MAGENTA
, 0, 64 + AST_MAX_APP
+ 22);
2533 term_color(stxtitle
, "[Syntax]\n", COLOR_MAGENTA
, 0, 40);
2534 term_color(syntitle
, "[Synopsis]\n", COLOR_MAGENTA
, 0, 40);
2535 term_color(destitle
, "[Description]\n", COLOR_MAGENTA
, 0, 40);
2537 acf
->syntax
? acf
->syntax
: "Not available",
2538 COLOR_CYAN
, 0, syntax_size
);
2539 term_color(synopsis
,
2540 acf
->synopsis
? acf
->synopsis
: "Not available",
2541 COLOR_CYAN
, 0, synopsis_size
);
2542 term_color(description
,
2543 acf
->desc
? acf
->desc
: "Not available",
2544 COLOR_CYAN
, 0, description_size
);
2546 ast_cli(a
->fd
,"%s%s%s\n\n%s%s\n\n%s%s\n", infotitle
, stxtitle
, syntax
, syntitle
, synopsis
, destitle
, description
);
2551 struct ast_custom_function
*ast_custom_function_find(const char *name
)
2553 struct ast_custom_function
*acf
= NULL
;
2555 AST_RWLIST_RDLOCK(&acf_root
);
2556 AST_RWLIST_TRAVERSE(&acf_root
, acf
, acflist
) {
2557 if (!strcmp(name
, acf
->name
))
2560 AST_RWLIST_UNLOCK(&acf_root
);
2565 int ast_custom_function_unregister(struct ast_custom_function
*acf
)
2567 struct ast_custom_function
*cur
;
2572 AST_RWLIST_WRLOCK(&acf_root
);
2573 if ((cur
= AST_RWLIST_REMOVE(&acf_root
, acf
, acflist
)))
2574 ast_verb(2, "Unregistered custom function %s\n", cur
->name
);
2575 AST_RWLIST_UNLOCK(&acf_root
);
2577 return cur
? 0 : -1;
2580 int __ast_custom_function_register(struct ast_custom_function
*acf
, struct ast_module
*mod
)
2582 struct ast_custom_function
*cur
;
2590 AST_RWLIST_WRLOCK(&acf_root
);
2592 AST_RWLIST_TRAVERSE(&acf_root
, cur
, acflist
) {
2593 if (!strcmp(acf
->name
, cur
->name
)) {
2594 ast_log(LOG_ERROR
, "Function %s already registered.\n", acf
->name
);
2595 AST_RWLIST_UNLOCK(&acf_root
);
2600 /* Store in alphabetical order */
2601 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&acf_root
, cur
, acflist
) {
2602 if (strcasecmp(acf
->name
, cur
->name
) < 0) {
2603 AST_RWLIST_INSERT_BEFORE_CURRENT(acf
, acflist
);
2607 AST_RWLIST_TRAVERSE_SAFE_END
;
2609 AST_RWLIST_INSERT_TAIL(&acf_root
, acf
, acflist
);
2611 AST_RWLIST_UNLOCK(&acf_root
);
2613 ast_verb(2, "Registered custom function '%s'\n", term_color(tmps
, acf
->name
, COLOR_BRCYAN
, 0, sizeof(tmps
)));
2618 /*! \brief return a pointer to the arguments of the function,
2619 * and terminates the function name with '\\0'
2621 static char *func_args(char *function
)
2623 char *args
= strchr(function
, '(');
2626 ast_log(LOG_WARNING
, "Function doesn't contain parentheses. Assuming null argument.\n");
2630 if ((p
= strrchr(args
, ')')) )
2633 ast_log(LOG_WARNING
, "Can't find trailing parenthesis?\n");
2638 int ast_func_read(struct ast_channel
*chan
, const char *function
, char *workspace
, size_t len
)
2640 char *copy
= ast_strdupa(function
);
2641 char *args
= func_args(copy
);
2642 struct ast_custom_function
*acfptr
= ast_custom_function_find(copy
);
2645 ast_log(LOG_ERROR
, "Function %s not registered\n", copy
);
2646 else if (!acfptr
->read
)
2647 ast_log(LOG_ERROR
, "Function %s cannot be read\n", copy
);
2650 struct ast_module_user
*u
= NULL
;
2652 u
= __ast_module_user_add(acfptr
->mod
, chan
);
2653 res
= acfptr
->read(chan
, copy
, args
, workspace
, len
);
2654 if (acfptr
->mod
&& u
)
2655 __ast_module_user_remove(acfptr
->mod
, u
);
2661 int ast_func_write(struct ast_channel
*chan
, const char *function
, const char *value
)
2663 char *copy
= ast_strdupa(function
);
2664 char *args
= func_args(copy
);
2665 struct ast_custom_function
*acfptr
= ast_custom_function_find(copy
);
2668 ast_log(LOG_ERROR
, "Function %s not registered\n", copy
);
2669 else if (!acfptr
->write
)
2670 ast_log(LOG_ERROR
, "Function %s cannot be written to\n", copy
);
2673 struct ast_module_user
*u
= NULL
;
2675 u
= __ast_module_user_add(acfptr
->mod
, chan
);
2676 res
= acfptr
->write(chan
, copy
, args
, value
);
2677 if (acfptr
->mod
&& u
)
2678 __ast_module_user_remove(acfptr
->mod
, u
);
2685 static void pbx_substitute_variables_helper_full(struct ast_channel
*c
, struct varshead
*headp
, const char *cp1
, char *cp2
, int count
)
2687 /* Substitutes variables into cp2, based on string cp1, cp2 NO LONGER NEEDS TO BE ZEROED OUT!!!! */
2689 const char *tmp
, *whereweare
;
2690 int length
, offset
, offset2
, isfunction
;
2691 char *workspace
= NULL
;
2692 char *ltmp
= NULL
, *var
= NULL
;
2693 char *nextvar
, *nextexp
, *nextthing
;
2695 int pos
, brackets
, needsub
, len
;
2697 *cp2
= 0; /* just in case nothing ends up there */
2699 while (!ast_strlen_zero(whereweare
) && count
) {
2700 /* Assume we're copying the whole remaining string */
2701 pos
= strlen(whereweare
);
2704 nextthing
= strchr(whereweare
, '$');
2706 switch (nextthing
[1]) {
2708 nextvar
= nextthing
;
2709 pos
= nextvar
- whereweare
;
2712 nextexp
= nextthing
;
2713 pos
= nextexp
- whereweare
;
2721 /* Can't copy more than 'count' bytes */
2725 /* Copy that many bytes */
2726 memcpy(cp2
, whereweare
, pos
);
2735 /* We have a variable. Find the start and end, and determine
2736 if we are going to have to recursively call ourselves on the
2738 vars
= vare
= nextvar
+ 2;
2742 /* Find the end of it */
2743 while (brackets
&& *vare
) {
2744 if ((vare
[0] == '$') && (vare
[1] == '{')) {
2746 } else if (vare
[0] == '{') {
2748 } else if (vare
[0] == '}') {
2750 } else if ((vare
[0] == '$') && (vare
[1] == '['))
2755 ast_log(LOG_WARNING
, "Error in extension logic (missing '}')\n");
2756 len
= vare
- vars
- 1;
2758 /* Skip totally over variable string */
2759 whereweare
+= (len
+ 3);
2762 var
= alloca(VAR_BUF_SIZE
);
2764 /* Store variable name (and truncate) */
2765 ast_copy_string(var
, vars
, len
+ 1);
2767 /* Substitute if necessary */
2770 ltmp
= alloca(VAR_BUF_SIZE
);
2772 pbx_substitute_variables_helper_full(c
, headp
, var
, ltmp
, VAR_BUF_SIZE
- 1);
2779 workspace
= alloca(VAR_BUF_SIZE
);
2781 workspace
[0] = '\0';
2783 parse_variable_name(vars
, &offset
, &offset2
, &isfunction
);
2785 /* Evaluate function */
2787 cp4
= ast_func_read(c
, vars
, workspace
, VAR_BUF_SIZE
) ? NULL
: workspace
;
2789 struct varshead old
;
2790 struct ast_channel
*c
= ast_channel_alloc(0, 0, "", "", "", "", "", 0, "Bogus/%p", vars
);
2792 memcpy(&old
, &c
->varshead
, sizeof(old
));
2793 memcpy(&c
->varshead
, headp
, sizeof(c
->varshead
));
2794 cp4
= ast_func_read(c
, vars
, workspace
, VAR_BUF_SIZE
) ? NULL
: workspace
;
2795 /* Don't deallocate the varshead that was passed in */
2796 memcpy(&c
->varshead
, &old
, sizeof(c
->varshead
));
2797 ast_channel_free(c
);
2799 ast_log(LOG_ERROR
, "Unable to allocate bogus channel for variable substitution. Function results may be blank.\n");
2801 ast_debug(2, "Function result is '%s'\n", cp4
? cp4
: "(null)");
2803 /* Retrieve variable value */
2804 pbx_retrieve_variable(c
, vars
, &cp4
, workspace
, VAR_BUF_SIZE
, headp
);
2807 cp4
= substring(cp4
, offset
, offset2
, workspace
, VAR_BUF_SIZE
);
2809 length
= strlen(cp4
);
2812 memcpy(cp2
, cp4
, length
);
2817 } else if (nextexp
) {
2818 /* We have an expression. Find the start and end, and determine
2819 if we are going to have to recursively call ourselves on the
2821 vars
= vare
= nextexp
+ 2;
2825 /* Find the end of it */
2826 while (brackets
&& *vare
) {
2827 if ((vare
[0] == '$') && (vare
[1] == '[')) {
2831 } else if (vare
[0] == '[') {
2833 } else if (vare
[0] == ']') {
2835 } else if ((vare
[0] == '$') && (vare
[1] == '{')) {
2842 ast_log(LOG_WARNING
, "Error in extension logic (missing ']')\n");
2843 len
= vare
- vars
- 1;
2845 /* Skip totally over expression */
2846 whereweare
+= (len
+ 3);
2849 var
= alloca(VAR_BUF_SIZE
);
2851 /* Store variable name (and truncate) */
2852 ast_copy_string(var
, vars
, len
+ 1);
2854 /* Substitute if necessary */
2857 ltmp
= alloca(VAR_BUF_SIZE
);
2859 pbx_substitute_variables_helper_full(c
, headp
, var
, ltmp
, VAR_BUF_SIZE
- 1);
2865 length
= ast_expr(vars
, cp2
, count
, c
);
2868 ast_debug(1, "Expression result is '%s'\n", cp2
);
2877 void pbx_substitute_variables_helper(struct ast_channel
*c
, const char *cp1
, char *cp2
, int count
)
2879 pbx_substitute_variables_helper_full(c
, (c
) ? &c
->varshead
: NULL
, cp1
, cp2
, count
);
2882 void pbx_substitute_variables_varshead(struct varshead
*headp
, const char *cp1
, char *cp2
, int count
)
2884 pbx_substitute_variables_helper_full(NULL
, headp
, cp1
, cp2
, count
);
2887 static void pbx_substitute_variables(char *passdata
, int datalen
, struct ast_channel
*c
, struct ast_exten
*e
)
2891 /* Nothing more to do */
2895 /* No variables or expressions in e->data, so why scan it? */
2896 if ((!(tmp
= strchr(e
->data
, '$'))) || (!strstr(tmp
, "${") && !strstr(tmp
, "$["))) {
2897 ast_copy_string(passdata
, e
->data
, datalen
);
2901 pbx_substitute_variables_helper(c
, e
->data
, passdata
, datalen
- 1);
2905 * \brief The return value depends on the action:
2907 * E_MATCH, E_CANMATCH, E_MATCHMORE require a real match,
2908 * and return 0 on failure, -1 on match;
2909 * E_FINDLABEL maps the label to a priority, and returns
2910 * the priority on success, ... XXX
2911 * E_SPAWN, spawn an application,
2913 * \retval 0 on success.
2914 * \retval -1 on failure.
2916 * \note The channel is auto-serviced in this function, because doing an extension
2917 * match may block for a long time. For example, if the lookup has to use a network
2918 * dialplan switch, such as DUNDi or IAX2, it may take a while. However, the channel
2919 * auto-service code will queue up any important signalling frames to be processed
2920 * after this is done.
2922 static int pbx_extension_helper(struct ast_channel
*c
, struct ast_context
*con
,
2923 const char *context
, const char *exten
, int priority
,
2924 const char *label
, const char *callerid
, enum ext_match_t action
, int *found
, int combined_find_spawn
)
2926 struct ast_exten
*e
;
2927 struct ast_app
*app
;
2929 struct pbx_find_info q
= { .stacklen
= 0 }; /* the rest is reset in pbx_find_extension */
2930 char passdata
[EXT_DATA_SIZE
];
2932 int matching_action
= (action
== E_MATCH
|| action
== E_CANMATCH
|| action
== E_MATCHMORE
);
2934 ast_rdlock_contexts();
2938 e
= pbx_find_extension(c
, con
, &q
, context
, exten
, priority
, label
, callerid
, action
);
2942 if (matching_action
) {
2943 ast_unlock_contexts();
2944 return -1; /* success, we found it */
2945 } else if (action
== E_FINDLABEL
) { /* map the label to a priority */
2947 ast_unlock_contexts();
2948 return res
; /* the priority we were looking for */
2949 } else { /* spawn */
2951 e
->cached_app
= pbx_findapp(e
->app
);
2952 app
= e
->cached_app
;
2953 ast_unlock_contexts();
2955 ast_log(LOG_WARNING
, "No application '%s' for extension (%s, %s, %d)\n", e
->app
, context
, exten
, priority
);
2958 if (c
->context
!= context
)
2959 ast_copy_string(c
->context
, context
, sizeof(c
->context
));
2960 if (c
->exten
!= exten
)
2961 ast_copy_string(c
->exten
, exten
, sizeof(c
->exten
));
2962 c
->priority
= priority
;
2963 pbx_substitute_variables(passdata
, sizeof(passdata
), c
, e
);
2964 #ifdef CHANNEL_TRACE
2965 ast_channel_trace_update(c
);
2967 ast_debug(1, "Launching '%s'\n", app
->name
);
2968 if (VERBOSITY_ATLEAST(3)) {
2969 char tmp
[80], tmp2
[80], tmp3
[EXT_DATA_SIZE
];
2970 ast_verb(3, "Executing [%s@%s:%d] %s(\"%s\", \"%s\") %s\n",
2971 exten
, context
, priority
,
2972 term_color(tmp
, app
->name
, COLOR_BRCYAN
, 0, sizeof(tmp
)),
2973 term_color(tmp2
, c
->name
, COLOR_BRMAGENTA
, 0, sizeof(tmp2
)),
2974 term_color(tmp3
, passdata
, COLOR_BRMAGENTA
, 0, sizeof(tmp3
)),
2977 manager_event(EVENT_FLAG_DIALPLAN
, "Newexten",
2982 "Application: %s\r\n"
2985 c
->name
, c
->context
, c
->exten
, c
->priority
, app
->name
, passdata
, c
->uniqueid
);
2986 return pbx_exec(c
, app
, passdata
); /* 0 on success, -1 on failure */
2988 } else if (q
.swo
) { /* not found here, but in another switch */
2989 ast_unlock_contexts();
2990 if (matching_action
) {
2994 ast_log(LOG_WARNING
, "No execution engine for switch %s\n", q
.swo
->name
);
2997 return q
.swo
->exec(c
, q
.foundcontext
? q
.foundcontext
: context
, exten
, priority
, callerid
, q
.data
);
2999 } else { /* not found anywhere, see what happened */
3000 ast_unlock_contexts();
3002 case STATUS_NO_CONTEXT
:
3003 if (!matching_action
&& !combined_find_spawn
)
3004 ast_log(LOG_NOTICE
, "Cannot find extension context '%s'\n", context
);
3006 case STATUS_NO_EXTENSION
:
3007 if (!matching_action
&& !combined_find_spawn
)
3008 ast_log(LOG_NOTICE
, "Cannot find extension '%s' in context '%s'\n", exten
, context
);
3010 case STATUS_NO_PRIORITY
:
3011 if (!matching_action
&& !combined_find_spawn
)
3012 ast_log(LOG_NOTICE
, "No such priority %d in extension '%s' in context '%s'\n", priority
, exten
, context
);
3014 case STATUS_NO_LABEL
:
3015 if (context
&& !combined_find_spawn
)
3016 ast_log(LOG_NOTICE
, "No such label '%s' in extension '%s' in context '%s'\n", label
, exten
, context
);
3019 ast_debug(1, "Shouldn't happen!\n");
3022 return (matching_action
) ? 0 : -1;
3026 /*! \brief Find hint for given extension in context */
3027 static struct ast_exten
*ast_hint_extension(struct ast_channel
*c
, const char *context
, const char *exten
)
3029 struct ast_exten
*e
;
3030 struct pbx_find_info q
= { .stacklen
= 0 }; /* the rest is set in pbx_find_context */
3032 ast_rdlock_contexts();
3033 e
= pbx_find_extension(c
, NULL
, &q
, context
, exten
, PRIORITY_HINT
, NULL
, "", E_MATCH
);
3034 ast_unlock_contexts();
3039 /*! \brief Check state of extension by using hints */
3040 static int ast_extension_state2(struct ast_exten
*e
)
3042 char hint
[AST_MAX_EXTENSION
] = "";
3044 struct ast_devstate_aggregate agg
;
3045 enum ast_device_state state
;
3050 ast_devstate_aggregate_init(&agg
);
3052 ast_copy_string(hint
, ast_get_extension_app(e
), sizeof(hint
));
3054 rest
= hint
; /* One or more devices separated with a & character */
3056 while ( (cur
= strsep(&rest
, "&")) )
3057 ast_devstate_aggregate_add(&agg
, ast_device_state(cur
));
3059 state
= ast_devstate_aggregate_result(&agg
);
3062 case AST_DEVICE_ONHOLD
:
3063 return AST_EXTENSION_ONHOLD
;
3064 case AST_DEVICE_BUSY
:
3065 return AST_EXTENSION_BUSY
;
3066 case AST_DEVICE_UNAVAILABLE
:
3067 return AST_EXTENSION_UNAVAILABLE
;
3068 case AST_DEVICE_RINGINUSE
:
3069 return (AST_EXTENSION_INUSE
| AST_EXTENSION_RINGING
);
3070 case AST_DEVICE_RINGING
:
3071 return AST_EXTENSION_RINGING
;
3072 case AST_DEVICE_INUSE
:
3073 return AST_EXTENSION_INUSE
;
3074 case AST_DEVICE_UNKNOWN
:
3075 case AST_DEVICE_INVALID
:
3076 case AST_DEVICE_NOT_INUSE
:
3077 return AST_EXTENSION_NOT_INUSE
;
3080 return AST_EXTENSION_NOT_INUSE
;
3083 /*! \brief Return extension_state as string */
3084 const char *ast_extension_state2str(int extension_state
)
3088 for (i
= 0; (i
< (sizeof(extension_states
) / sizeof(extension_states
[0]))); i
++) {
3089 if (extension_states
[i
].extension_state
== extension_state
)
3090 return extension_states
[i
].text
;
3095 /*! \brief Check extension state for an extension by using hint */
3096 int ast_extension_state(struct ast_channel
*c
, const char *context
, const char *exten
)
3098 struct ast_exten
*e
;
3100 e
= ast_hint_extension(c
, context
, exten
); /* Do we have a hint for this extension ? */
3102 return -1; /* No hint, return -1 */
3104 return ast_extension_state2(e
); /* Check all devices in the hint */
3107 static int handle_statechange(void *datap
)
3109 struct ast_hint
*hint
;
3110 struct statechange
*sc
= datap
;
3111 AST_RWLIST_RDLOCK(&hints
);
3113 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
3114 struct ast_state_cb
*cblist
;
3115 char buf
[AST_MAX_EXTENSION
];
3120 ast_copy_string(buf
, ast_get_extension_app(hint
->exten
), sizeof(buf
));
3121 while ( (cur
= strsep(&parse
, "&")) ) {
3122 if (!strcasecmp(cur
, sc
->dev
))
3128 /* Get device state for this hint */
3129 state
= ast_extension_state2(hint
->exten
);
3131 if ((state
== -1) || (state
== hint
->laststate
))
3134 /* Device state changed since last check - notify the watchers */
3136 /* For general callbacks */
3137 AST_LIST_TRAVERSE(&statecbs
, cblist
, entry
) {
3138 cblist
->callback(hint
->exten
->parent
->name
, hint
->exten
->exten
, state
, cblist
->data
);
3141 /* For extension callbacks */
3142 AST_LIST_TRAVERSE(&hint
->callbacks
, cblist
, entry
) {
3143 cblist
->callback(hint
->exten
->parent
->name
, hint
->exten
->exten
, state
, cblist
->data
);
3146 hint
->laststate
= state
; /* record we saw the change */
3148 AST_RWLIST_UNLOCK(&hints
);
3153 /*! \brief Add watcher for extension states */
3154 int ast_extension_state_add(const char *context
, const char *exten
,
3155 ast_state_cb_type callback
, void *data
)
3157 struct ast_hint
*hint
;
3158 struct ast_state_cb
*cblist
;
3159 struct ast_exten
*e
;
3161 /* If there's no context and extension: add callback to statecbs list */
3162 if (!context
&& !exten
) {
3163 AST_RWLIST_WRLOCK(&hints
);
3165 AST_LIST_TRAVERSE(&statecbs
, cblist
, entry
) {
3166 if (cblist
->callback
== callback
) {
3167 cblist
->data
= data
;
3168 AST_RWLIST_UNLOCK(&hints
);
3173 /* Now insert the callback */
3174 if (!(cblist
= ast_calloc(1, sizeof(*cblist
)))) {
3175 AST_RWLIST_UNLOCK(&hints
);
3179 cblist
->callback
= callback
;
3180 cblist
->data
= data
;
3182 AST_LIST_INSERT_HEAD(&statecbs
, cblist
, entry
);
3184 AST_RWLIST_UNLOCK(&hints
);
3189 if (!context
|| !exten
)
3192 /* This callback type is for only one hint, so get the hint */
3193 e
= ast_hint_extension(NULL
, context
, exten
);
3198 /* If this is a pattern, dynamically create a new extension for this
3199 * particular match. Note that this will only happen once for each
3200 * individual extension, because the pattern will no longer match first.
3202 if (e
->exten
[0] == '_') {
3203 ast_add_extension(e
->parent
->name
, 0, exten
, e
->priority
, e
->label
,
3204 e
->cidmatch
, e
->app
, strdup(e
->data
), free
,
3206 e
= ast_hint_extension(NULL
, context
, exten
);
3207 if (!e
|| e
->exten
[0] == '_') {
3212 /* Find the hint in the list of hints */
3213 AST_RWLIST_WRLOCK(&hints
);
3215 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
3216 if (hint
->exten
== e
)
3221 /* We have no hint, sorry */
3222 AST_RWLIST_UNLOCK(&hints
);
3226 /* Now insert the callback in the callback list */
3227 if (!(cblist
= ast_calloc(1, sizeof(*cblist
)))) {
3228 AST_RWLIST_UNLOCK(&hints
);
3232 cblist
->id
= stateid
++; /* Unique ID for this callback */
3233 cblist
->callback
= callback
; /* Pointer to callback routine */
3234 cblist
->data
= data
; /* Data for the callback */
3236 AST_LIST_INSERT_HEAD(&hint
->callbacks
, cblist
, entry
);
3238 AST_RWLIST_UNLOCK(&hints
);
3243 /*! \brief Remove a watcher from the callback list */
3244 int ast_extension_state_del(int id
, ast_state_cb_type callback
)
3246 struct ast_state_cb
*p_cur
= NULL
;
3249 if (!id
&& !callback
)
3252 AST_RWLIST_WRLOCK(&hints
);
3254 if (!id
) { /* id == 0 is a callback without extension */
3255 AST_LIST_TRAVERSE_SAFE_BEGIN(&statecbs
, p_cur
, entry
) {
3256 if (p_cur
->callback
== callback
) {
3257 AST_LIST_REMOVE_CURRENT(entry
);
3261 AST_LIST_TRAVERSE_SAFE_END
3262 } else { /* callback with extension, find the callback based on ID */
3263 struct ast_hint
*hint
;
3264 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
3265 AST_LIST_TRAVERSE_SAFE_BEGIN(&hint
->callbacks
, p_cur
, entry
) {
3266 if (p_cur
->id
== id
) {
3267 AST_LIST_REMOVE_CURRENT(entry
);
3271 AST_LIST_TRAVERSE_SAFE_END
3282 AST_RWLIST_UNLOCK(&hints
);
3287 /*! \brief Add hint to hint list, check initial extension state */
3288 static int ast_add_hint(struct ast_exten
*e
)
3290 struct ast_hint
*hint
;
3295 AST_RWLIST_WRLOCK(&hints
);
3297 /* Search if hint exists, do nothing */
3298 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
3299 if (hint
->exten
== e
) {
3300 AST_RWLIST_UNLOCK(&hints
);
3301 ast_debug(2, "HINTS: Not re-adding existing hint %s: %s\n", ast_get_extension_name(e
), ast_get_extension_app(e
));
3306 ast_debug(2, "HINTS: Adding hint %s: %s\n", ast_get_extension_name(e
), ast_get_extension_app(e
));
3308 if (!(hint
= ast_calloc(1, sizeof(*hint
)))) {
3309 AST_RWLIST_UNLOCK(&hints
);
3312 /* Initialize and insert new item at the top */
3314 hint
->laststate
= ast_extension_state2(e
);
3315 AST_RWLIST_INSERT_HEAD(&hints
, hint
, list
);
3317 AST_RWLIST_UNLOCK(&hints
);
3321 /*! \brief Change hint for an extension */
3322 static int ast_change_hint(struct ast_exten
*oe
, struct ast_exten
*ne
)
3324 struct ast_hint
*hint
;
3327 AST_RWLIST_WRLOCK(&hints
);
3328 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
3329 if (hint
->exten
== oe
) {
3335 AST_RWLIST_UNLOCK(&hints
);
3340 /*! \brief Remove hint from extension */
3341 static int ast_remove_hint(struct ast_exten
*e
)
3343 /* Cleanup the Notifys if hint is removed */
3344 struct ast_hint
*hint
;
3345 struct ast_state_cb
*cblist
;
3351 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&hints
, hint
, list
) {
3352 if (hint
->exten
!= e
)
3355 while ((cblist
= AST_LIST_REMOVE_HEAD(&hint
->callbacks
, entry
))) {
3356 /* Notify with -1 and remove all callbacks */
3357 cblist
->callback(hint
->exten
->parent
->name
, hint
->exten
->exten
,
3358 AST_EXTENSION_DEACTIVATED
, cblist
->data
);
3362 AST_RWLIST_REMOVE_CURRENT(list
);
3369 AST_RWLIST_TRAVERSE_SAFE_END
;
3375 /*! \brief Get hint for channel */
3376 int ast_get_hint(char *hint
, int hintsize
, char *name
, int namesize
, struct ast_channel
*c
, const char *context
, const char *exten
)
3378 struct ast_exten
*e
= ast_hint_extension(c
, context
, exten
);
3382 ast_copy_string(hint
, ast_get_extension_app(e
), hintsize
);
3384 const char *tmp
= ast_get_extension_app_data(e
);
3386 ast_copy_string(name
, tmp
, namesize
);
3393 int ast_exists_extension(struct ast_channel
*c
, const char *context
, const char *exten
, int priority
, const char *callerid
)
3395 return pbx_extension_helper(c
, NULL
, context
, exten
, priority
, NULL
, callerid
, E_MATCH
, 0, 0);
3398 int ast_findlabel_extension(struct ast_channel
*c
, const char *context
, const char *exten
, const char *label
, const char *callerid
)
3400 return pbx_extension_helper(c
, NULL
, context
, exten
, 0, label
, callerid
, E_FINDLABEL
, 0, 0);
3403 int ast_findlabel_extension2(struct ast_channel
*c
, struct ast_context
*con
, const char *exten
, const char *label
, const char *callerid
)
3405 return pbx_extension_helper(c
, con
, NULL
, exten
, 0, label
, callerid
, E_FINDLABEL
, 0, 0);
3408 int ast_canmatch_extension(struct ast_channel
*c
, const char *context
, const char *exten
, int priority
, const char *callerid
)
3410 return pbx_extension_helper(c
, NULL
, context
, exten
, priority
, NULL
, callerid
, E_CANMATCH
, 0, 0);
3413 int ast_matchmore_extension(struct ast_channel
*c
, const char *context
, const char *exten
, int priority
, const char *callerid
)
3415 return pbx_extension_helper(c
, NULL
, context
, exten
, priority
, NULL
, callerid
, E_MATCHMORE
, 0, 0);
3418 int ast_spawn_extension(struct ast_channel
*c
, const char *context
, const char *exten
, int priority
, const char *callerid
, int *found
, int combined_find_spawn
)
3420 return pbx_extension_helper(c
, NULL
, context
, exten
, priority
, NULL
, callerid
, E_SPAWN
, found
, combined_find_spawn
);
3423 /*! helper function to set extension and priority */
3424 static void set_ext_pri(struct ast_channel
*c
, const char *exten
, int pri
)
3426 ast_channel_lock(c
);
3427 ast_copy_string(c
->exten
, exten
, sizeof(c
->exten
));
3429 ast_channel_unlock(c
);
3433 * \brief collect digits from the channel into the buffer.
3434 * \retval 0 on timeout or done.
3435 * \retval -1 on error.
3437 static int collect_digits(struct ast_channel
*c
, int waittime
, char *buf
, int buflen
, int pos
)
3441 buf
[pos
] = '\0'; /* make sure it is properly terminated */
3442 while (ast_matchmore_extension(c
, c
->context
, buf
, 1, c
->cid
.cid_num
)) {
3443 /* As long as we're willing to wait, and as long as it's not defined,
3444 keep reading digits until we can't possibly get a right answer anymore. */
3445 digit
= ast_waitfordigit(c
, waittime
* 1000);
3446 if (c
->_softhangup
== AST_SOFTHANGUP_ASYNCGOTO
) {
3449 if (!digit
) /* No entry */
3451 if (digit
< 0) /* Error, maybe a hangup */
3453 if (pos
< buflen
- 1) { /* XXX maybe error otherwise ? */
3457 waittime
= c
->pbx
->dtimeoutms
;
3463 static int __ast_pbx_run(struct ast_channel
*c
)
3465 int found
= 0; /* set if we find at least one match */
3468 int error
= 0; /* set an error conditions */
3470 /* A little initial setup here */
3472 ast_log(LOG_WARNING
, "%s already has PBX structure??\n", c
->name
);
3473 /* XXX and now what ? */
3476 if (!(c
->pbx
= ast_calloc(1, sizeof(*c
->pbx
))))
3480 c
->cdr
= ast_cdr_alloc();
3482 ast_log(LOG_WARNING
, "Unable to create Call Detail Record\n");
3486 ast_cdr_init(c
->cdr
, c
);
3489 /* Set reasonable defaults */
3490 c
->pbx
->rtimeoutms
= 10000;
3491 c
->pbx
->dtimeoutms
= 5000;
3493 autoloopflag
= ast_test_flag(c
, AST_FLAG_IN_AUTOLOOP
); /* save value to restore at the end */
3494 ast_set_flag(c
, AST_FLAG_IN_AUTOLOOP
);
3496 /* Start by trying whatever the channel is set to */
3497 if (!ast_exists_extension(c
, c
->context
, c
->exten
, c
->priority
, c
->cid
.cid_num
)) {
3498 /* If not successful fall back to 's' */
3499 ast_verb(2, "Starting %s at %s,%s,%d failed so falling back to exten 's'\n", c
->name
, c
->context
, c
->exten
, c
->priority
);
3500 /* XXX the original code used the existing priority in the call to
3501 * ast_exists_extension(), and reset it to 1 afterwards.
3502 * I believe the correct thing is to set it to 1 immediately.
3504 set_ext_pri(c
, "s", 1);
3505 if (!ast_exists_extension(c
, c
->context
, c
->exten
, c
->priority
, c
->cid
.cid_num
)) {
3506 /* JK02: And finally back to default if everything else failed */
3507 ast_verb(2, "Starting %s at %s,%s,%d still failed so falling back to context 'default'\n", c
->name
, c
->context
, c
->exten
, c
->priority
);
3508 ast_copy_string(c
->context
, "default", sizeof(c
->context
));
3511 if (c
->cdr
&& ast_tvzero(c
->cdr
->start
))
3512 ast_cdr_start(c
->cdr
);
3514 char dst_exten
[256]; /* buffer to accumulate digits */
3515 int pos
= 0; /* XXX should check bounds */
3520 /* loop on priorities in this context/exten */
3521 while ( !(res
= ast_spawn_extension(c
, c
->context
, c
->exten
, c
->priority
, c
->cid
.cid_num
, &found
,1))) {
3522 if (c
->_softhangup
== AST_SOFTHANGUP_TIMEOUT
&& ast_exists_extension(c
, c
->context
, "T", 1, c
->cid
.cid_num
)) {
3523 set_ext_pri(c
, "T", 0); /* 0 will become 1 with the c->priority++; at the end */
3524 /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
3525 memset(&c
->whentohangup
, 0, sizeof(c
->whentohangup
));
3526 c
->_softhangup
&= ~AST_SOFTHANGUP_TIMEOUT
;
3527 } else if (c
->_softhangup
== AST_SOFTHANGUP_TIMEOUT
&& ast_exists_extension(c
, c
->context
, "e", 1, c
->cid
.cid_num
)) {
3528 pbx_builtin_raise_exception(c
, "ABSOLUTETIMEOUT");
3529 /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
3530 memset(&c
->whentohangup
, 0, sizeof(c
->whentohangup
));
3531 c
->_softhangup
&= ~AST_SOFTHANGUP_TIMEOUT
;
3532 } else if (c
->_softhangup
== AST_SOFTHANGUP_ASYNCGOTO
) {
3535 } else if (ast_check_hangup(c
)) {
3536 ast_debug(1, "Extension %s, priority %d returned normally even though call was hung up\n",
3537 c
->exten
, c
->priority
);
3542 } /* end while - from here on we can use 'break' to go out */
3544 /* Something bad happened, or a hangup has been requested. */
3545 if (strchr("0123456789ABCDEF*#", res
)) {
3546 ast_debug(1, "Oooh, got something to jump out with ('%c')!\n", res
);
3548 dst_exten
[pos
++] = digit
= res
;
3549 dst_exten
[pos
] = '\0';
3550 } else if (res
== AST_PBX_KEEPALIVE
) {
3551 ast_debug(1, "Spawn extension (%s,%s,%d) exited KEEPALIVE on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3552 ast_verb(2, "Spawn extension (%s, %s, %d) exited KEEPALIVE on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3554 } else if (res
== AST_PBX_INCOMPLETE
) {
3555 ast_debug(1, "Spawn extension (%s,%s,%d) exited INCOMPLETE on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3556 ast_verb(2, "Spawn extension (%s, %s, %d) exited INCOMPLETE on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3558 /* Don't cycle on incomplete - this will happen if the only extension that matches is our "incomplete" extension */
3559 if (!ast_matchmore_extension(c
, c
->context
, c
->exten
, c
->priority
, c
->cid
.cid_num
)) {
3562 ast_copy_string(dst_exten
, c
->exten
, sizeof(dst_exten
));
3564 pos
= strlen(dst_exten
);
3567 ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3568 ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3570 if ((res
== AST_PBX_ERROR
) && ast_exists_extension(c
, c
->context
, "e", 1, c
->cid
.cid_num
)) {
3571 /* if we are already on the 'e' exten, don't jump to it again */
3572 if (!strcmp(c
->exten
, "e")) {
3573 ast_verb(2, "Spawn extension (%s, %s, %d) exited ERROR while already on 'e' exten on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3576 pbx_builtin_raise_exception(c
, "ERROR");
3581 if (c
->_softhangup
== AST_SOFTHANGUP_ASYNCGOTO
) {
3584 } else if (c
->_softhangup
== AST_SOFTHANGUP_TIMEOUT
&& ast_exists_extension(c
, c
->context
, "T", 1, c
->cid
.cid_num
)) {
3585 set_ext_pri(c
, "T", 1);
3586 /* If the AbsoluteTimeout is not reset to 0, we'll get an infinite loop */
3587 memset(&c
->whentohangup
, 0, sizeof(c
->whentohangup
));
3588 c
->_softhangup
&= ~AST_SOFTHANGUP_TIMEOUT
;
3602 * We get here on a failure of some kind: non-existing extension or
3603 * hangup. We have options, here. We can either catch the failure
3604 * and continue, or we can drop out entirely. */
3606 if (invalid
|| !ast_exists_extension(c
, c
->context
, c
->exten
, 1, c
->cid
.cid_num
)) {
3608 * If there is no match at priority 1, it is not a valid extension anymore.
3609 * Try to continue at "i" (for invalid) or "e" (for exception) or exit if
3612 if (ast_exists_extension(c
, c
->context
, "i", 1, c
->cid
.cid_num
)) {
3613 ast_verb(3, "Sent into invalid extension '%s' in context '%s' on %s\n", c
->exten
, c
->context
, c
->name
);
3614 pbx_builtin_setvar_helper(c
, "INVALID_EXTEN", c
->exten
);
3615 set_ext_pri(c
, "i", 1);
3616 } else if (ast_exists_extension(c
, c
->context
, "e", 1, c
->cid
.cid_num
)) {
3617 pbx_builtin_raise_exception(c
, "INVALID");
3619 ast_log(LOG_WARNING
, "Channel '%s' sent into invalid extension '%s' in context '%s', but no invalid handler\n",
3620 c
->name
, c
->exten
, c
->context
);
3621 error
= 1; /* we know what to do with it */
3624 } else if (c
->_softhangup
== AST_SOFTHANGUP_TIMEOUT
) {
3625 /* If we get this far with AST_SOFTHANGUP_TIMEOUT, then we know that the "T" extension is next. */
3627 } else { /* keypress received, get more digits for a full extension */
3630 waittime
= c
->pbx
->dtimeoutms
;
3631 else if (!autofallthrough
)
3632 waittime
= c
->pbx
->rtimeoutms
;
3634 const char *status
= pbx_builtin_getvar_helper(c
, "DIALSTATUS");
3637 ast_verb(3, "Auto fallthrough, channel '%s' status is '%s'\n", c
->name
, status
);
3638 if (!strcasecmp(status
, "CONGESTION"))
3639 res
= pbx_builtin_congestion(c
, "10");
3640 else if (!strcasecmp(status
, "CHANUNAVAIL"))
3641 res
= pbx_builtin_congestion(c
, "10");
3642 else if (!strcasecmp(status
, "BUSY"))
3643 res
= pbx_builtin_busy(c
, "10");
3644 error
= 1; /* XXX disable message */
3645 break; /* exit from the 'for' loop */
3648 if (collect_digits(c
, waittime
, dst_exten
, sizeof(dst_exten
), pos
))
3650 if (res
== AST_PBX_INCOMPLETE
&& ast_strlen_zero(&dst_exten
[pos
]))
3652 if (!timeout
&& ast_exists_extension(c
, c
->context
, dst_exten
, 1, c
->cid
.cid_num
)) /* Prepare the next cycle */
3653 set_ext_pri(c
, dst_exten
, 1);
3655 /* No such extension */
3656 if (!timeout
&& !ast_strlen_zero(dst_exten
)) {
3657 /* An invalid extension */
3658 if (ast_exists_extension(c
, c
->context
, "i", 1, c
->cid
.cid_num
)) {
3659 ast_verb(3, "Invalid extension '%s' in context '%s' on %s\n", dst_exten
, c
->context
, c
->name
);
3660 pbx_builtin_setvar_helper(c
, "INVALID_EXTEN", dst_exten
);
3661 set_ext_pri(c
, "i", 1);
3662 } else if (ast_exists_extension(c
, c
->context
, "e", 1, c
->cid
.cid_num
)) {
3663 pbx_builtin_raise_exception(c
, "INVALID");
3665 ast_log(LOG_WARNING
, "Invalid extension '%s', but no rule 'i' in context '%s'\n", dst_exten
, c
->context
);
3666 found
= 1; /* XXX disable message */
3670 /* A simple timeout */
3671 if (ast_exists_extension(c
, c
->context
, "t", 1, c
->cid
.cid_num
)) {
3672 ast_verb(3, "Timeout on %s\n", c
->name
);
3673 set_ext_pri(c
, "t", 1);
3674 } else if (ast_exists_extension(c
, c
->context
, "e", 1, c
->cid
.cid_num
)) {
3675 pbx_builtin_raise_exception(c
, "RESPONSETIMEOUT");
3677 ast_log(LOG_WARNING
, "Timeout, but no rule 't' in context '%s'\n", c
->context
);
3678 found
= 1; /* XXX disable message */
3684 ast_verb(2, "CDR updated on %s\n",c
->name
);
3689 if (!found
&& !error
)
3690 ast_log(LOG_WARNING
, "Don't know what to do with '%s'\n", c
->name
);
3691 if (res
!= AST_PBX_KEEPALIVE
)
3692 ast_softhangup(c
, c
->hangupcause
? c
->hangupcause
: AST_CAUSE_NORMAL_CLEARING
);
3693 if ((res
!= AST_PBX_KEEPALIVE
) && ast_exists_extension(c
, c
->context
, "h", 1, c
->cid
.cid_num
)) {
3694 if (c
->cdr
&& ast_opt_end_cdr_before_h_exten
)
3695 ast_cdr_end(c
->cdr
);
3696 set_ext_pri(c
, "h", 1);
3697 while ((res
= ast_spawn_extension(c
, c
->context
, c
->exten
, c
->priority
, c
->cid
.cid_num
, &found
, 1)) == 0) {
3701 /* Something bad happened, or a hangup has been requested. */
3702 ast_debug(1, "Spawn extension (%s,%s,%d) exited non-zero on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3703 ast_verb(2, "Spawn extension (%s, %s, %d) exited non-zero on '%s'\n", c
->context
, c
->exten
, c
->priority
, c
->name
);
3706 ast_set2_flag(c
, autoloopflag
, AST_FLAG_IN_AUTOLOOP
);
3708 pbx_destroy(c
->pbx
);
3710 if (res
!= AST_PBX_KEEPALIVE
)
3716 * \brief Increase call count for channel
3717 * \retval 0 on success
3718 * \retval non-zero if a configured limit (maxcalls, maxload, minmemfree) was reached
3720 static int increase_call_count(const struct ast_channel
*c
)
3724 #if defined(HAVE_SYSINFO)
3726 struct sysinfo sys_info
;
3729 ast_mutex_lock(&maxcalllock
);
3730 if (option_maxcalls
) {
3731 if (countcalls
>= option_maxcalls
) {
3732 ast_log(LOG_WARNING
, "Maximum call limit of %d calls exceeded by '%s'!\n", option_maxcalls
, c
->name
);
3736 if (option_maxload
) {
3737 getloadavg(&curloadavg
, 1);
3738 if (curloadavg
>= option_maxload
) {
3739 ast_log(LOG_WARNING
, "Maximum loadavg limit of %f load exceeded by '%s' (currently %f)!\n", option_maxload
, c
->name
, curloadavg
);
3743 #if defined(HAVE_SYSINFO)
3744 if (option_minmemfree
) {
3745 if (!sysinfo(&sys_info
)) {
3746 /* make sure that the free system memory is above the configured low watermark
3747 * convert the amount of freeram from mem_units to MB */
3748 curfreemem
= sys_info
.freeram
/ sys_info
.mem_unit
;
3749 curfreemem
/= 1024*1024;
3750 if (curfreemem
< option_minmemfree
) {
3751 ast_log(LOG_WARNING
, "Available system memory (~%ldMB) is below the configured low watermark (%ldMB)\n", curfreemem
, option_minmemfree
);
3762 ast_mutex_unlock(&maxcalllock
);
3767 static void decrease_call_count(void)
3769 ast_mutex_lock(&maxcalllock
);
3772 ast_mutex_unlock(&maxcalllock
);
3775 static void destroy_exten(struct ast_exten
*e
)
3777 if (e
->priority
== PRIORITY_HINT
)
3781 ast_hashtab_destroy(e
->peer_table
,0);
3782 if (e
->peer_label_table
)
3783 ast_hashtab_destroy(e
->peer_label_table
, 0);
3789 static void *pbx_thread(void *data
)
3791 /* Oh joyeous kernel, we're a new thread, with nothing to do but
3792 answer this channel and get it going.
3795 The launcher of this function _MUST_ increment 'countcalls'
3796 before invoking the function; it will be decremented when the
3797 PBX has finished running on the channel
3799 struct ast_channel
*c
= data
;
3802 decrease_call_count();
3809 enum ast_pbx_result
ast_pbx_start(struct ast_channel
*c
)
3814 ast_log(LOG_WARNING
, "Asked to start thread on NULL channel?\n");
3815 return AST_PBX_FAILED
;
3818 if (increase_call_count(c
))
3819 return AST_PBX_CALL_LIMIT
;
3821 /* Start a new thread, and get something handling this channel. */
3822 if (ast_pthread_create_detached(&t
, NULL
, pbx_thread
, c
)) {
3823 ast_log(LOG_WARNING
, "Failed to create new channel thread\n");
3824 return AST_PBX_FAILED
;
3827 return AST_PBX_SUCCESS
;
3830 enum ast_pbx_result
ast_pbx_run(struct ast_channel
*c
)
3832 enum ast_pbx_result res
= AST_PBX_SUCCESS
;
3834 if (increase_call_count(c
))
3835 return AST_PBX_CALL_LIMIT
;
3837 res
= __ast_pbx_run(c
);
3838 decrease_call_count();
3843 int ast_active_calls(void)
3848 int ast_processed_calls(void)
3853 int pbx_set_autofallthrough(int newval
)
3855 int oldval
= autofallthrough
;
3856 autofallthrough
= newval
;
3860 int pbx_set_extenpatternmatchnew(int newval
)
3862 int oldval
= extenpatternmatchnew
;
3863 extenpatternmatchnew
= newval
;
3867 void pbx_set_overrideswitch(const char *newval
)
3869 if (overrideswitch
) {
3870 ast_free(overrideswitch
);
3872 if (!ast_strlen_zero(newval
)) {
3873 overrideswitch
= ast_strdup(newval
);
3875 overrideswitch
= NULL
;
3880 * \brief lookup for a context with a given name,
3881 * \retval with conlock held if found.
3882 * \retval NULL if not found.
3884 static struct ast_context
*find_context_locked(const char *context
)
3886 struct ast_context
*c
= NULL
;
3887 struct fake_context item
;
3889 ast_copy_string(item
.name
, context
, sizeof(item
.name
));
3891 ast_rdlock_contexts();
3892 c
= ast_hashtab_lookup(contexts_table
,&item
);
3896 while ( (c
= ast_walk_contexts(c
)) ) {
3897 if (!strcmp(ast_get_context_name(c
), context
))
3902 ast_unlock_contexts();
3908 * \brief Remove included contexts.
3909 * This function locks contexts list by &conlist, search for the right context
3910 * structure, leave context list locked and call ast_context_remove_include2
3911 * which removes include, unlock contexts list and return ...
3913 int ast_context_remove_include(const char *context
, const char *include
, const char *registrar
)
3916 struct ast_context
*c
= find_context_locked(context
);
3919 /* found, remove include from this context ... */
3920 ret
= ast_context_remove_include2(c
, include
, registrar
);
3921 ast_unlock_contexts();
3927 * \brief Locks context, remove included contexts, unlocks context.
3928 * When we call this function, &conlock lock must be locked, because when
3929 * we giving *con argument, some process can remove/change this context
3930 * and after that there can be segfault.
3932 * \retval 0 on success.
3933 * \retval -1 on failure.
3935 int ast_context_remove_include2(struct ast_context
*con
, const char *include
, const char *registrar
)
3937 struct ast_include
*i
, *pi
= NULL
;
3940 ast_wrlock_context(con
);
3942 /* find our include */
3943 for (i
= con
->includes
; i
; pi
= i
, i
= i
->next
) {
3944 if (!strcmp(i
->name
, include
) &&
3945 (!registrar
|| !strcmp(i
->registrar
, registrar
))) {
3946 /* remove from list */
3950 con
->includes
= i
->next
;
3951 /* free include and return */
3958 ast_unlock_context(con
);
3964 * \note This function locks contexts list by &conlist, search for the rigt context
3965 * structure, leave context list locked and call ast_context_remove_switch2
3966 * which removes switch, unlock contexts list and return ...
3968 int ast_context_remove_switch(const char *context
, const char *sw
, const char *data
, const char *registrar
)
3970 int ret
= -1; /* default error return */
3971 struct ast_context
*c
= find_context_locked(context
);
3974 /* remove switch from this context ... */
3975 ret
= ast_context_remove_switch2(c
, sw
, data
, registrar
);
3976 ast_unlock_contexts();
3982 * \brief This function locks given context, removes switch, unlock context and
3984 * \note When we call this function, &conlock lock must be locked, because when
3985 * we giving *con argument, some process can remove/change this context
3986 * and after that there can be segfault.
3989 int ast_context_remove_switch2(struct ast_context
*con
, const char *sw
, const char *data
, const char *registrar
)
3994 ast_wrlock_context(con
);
3997 AST_LIST_TRAVERSE_SAFE_BEGIN(&con
->alts
, i
, list
) {
3998 if (!strcmp(i
->name
, sw
) && !strcmp(i
->data
, data
) &&
3999 (!registrar
|| !strcmp(i
->registrar
, registrar
))) {
4000 /* found, remove from list */
4001 AST_LIST_REMOVE_CURRENT(list
);
4002 ast_free(i
); /* free switch and return */
4007 AST_LIST_TRAVERSE_SAFE_END
;
4009 ast_unlock_context(con
);
4015 * \note This functions lock contexts list, search for the right context,
4016 * call ast_context_remove_extension2, unlock contexts list and return.
4017 * In this function we are using
4019 int ast_context_remove_extension(const char *context
, const char *extension
, int priority
, const char *registrar
)
4021 int ret
= -1; /* default error return */
4022 struct ast_context
*c
= find_context_locked(context
);
4024 if (c
) { /* ... remove extension ... */
4025 ret
= ast_context_remove_extension2(c
, extension
, priority
, registrar
, 1);
4026 ast_unlock_contexts();
4032 * \brief This functionc locks given context, search for the right extension and
4033 * fires out all peer in this extensions with given priority. If priority
4034 * is set to 0, all peers are removed. After that, unlock context and
4036 * \note When do you want to call this function, make sure that &conlock is locked,
4037 * because some process can handle with your *con context before you lock
4041 int ast_context_remove_extension2(struct ast_context
*con
, const char *extension
, int priority
, const char *registrar
, int already_locked
)
4043 struct ast_exten
*exten
, *prev_exten
= NULL
;
4044 struct ast_exten
*peer
;
4045 struct ast_exten ex
, *exten2
, *exten3
;
4046 char dummy_name
[1024];
4048 if (!already_locked
)
4049 ast_wrlock_context(con
);
4051 /* Handle this is in the new world */
4054 ast_verb(3,"Removing %s/%s/%d from trees, registrar=%s\n", con
->name
, extension
, priority
, registrar
);
4056 /* find this particular extension */
4057 ex
.exten
= dummy_name
;
4059 ast_copy_string(dummy_name
,extension
, sizeof(dummy_name
));
4060 exten
= ast_hashtab_lookup(con
->root_table
, &ex
);
4064 exten2
= ast_hashtab_remove_this_object(con
->root_table
, exten
);
4066 ast_log(LOG_ERROR
,"Trying to delete the exten %s from context %s, but could not remove from the root_table\n", extension
, con
->name
);
4067 if (con
->pattern_tree
) {
4069 struct match_char
*x
= add_exten_to_pattern_tree(con
, exten
, 1);
4071 if (x
->exten
) { /* this test for safety purposes */
4072 x
->deleted
= 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
4073 x
->exten
= 0; /* get rid of what will become a bad pointer */
4075 ast_log(LOG_WARNING
,"Trying to delete an exten from a context, but the pattern tree node returned isn't a full extension\n");
4079 ex
.priority
= priority
;
4080 exten2
= ast_hashtab_lookup(exten
->peer_table
, &ex
);
4083 if (exten2
->label
) { /* if this exten has a label, remove that, too */
4084 exten3
= ast_hashtab_remove_this_object(exten
->peer_label_table
,exten2
);
4086 ast_log(LOG_ERROR
,"Did not remove this priority label (%d/%s) from the peer_label_table of context %s, extension %s!\n", priority
, exten2
->label
, con
->name
, exten2
->exten
);
4089 exten3
= ast_hashtab_remove_this_object(exten
->peer_table
, exten2
);
4091 ast_log(LOG_ERROR
,"Did not remove this priority (%d) from the peer_table of context %s, extension %s!\n", priority
, con
->name
, exten2
->exten
);
4092 if (exten2
== exten
&& exten2
->peer
) {
4093 exten2
= ast_hashtab_remove_this_object(con
->root_table
, exten
);
4094 ast_hashtab_insert_immediate(con
->root_table
, exten2
->peer
);
4096 if (ast_hashtab_size(exten
->peer_table
) == 0) {
4097 /* well, if the last priority of an exten is to be removed,
4098 then, the extension is removed, too! */
4099 exten3
= ast_hashtab_remove_this_object(con
->root_table
, exten
);
4101 ast_log(LOG_ERROR
,"Did not remove this exten (%s) from the context root_table (%s) (priority %d)\n", exten
->exten
, con
->name
, priority
);
4102 if (con
->pattern_tree
) {
4103 struct match_char
*x
= add_exten_to_pattern_tree(con
, exten
, 1);
4104 if (x
->exten
) { /* this test for safety purposes */
4105 x
->deleted
= 1; /* with this marked as deleted, it will never show up in the scoreboard, and therefore never be found */
4106 x
->exten
= 0; /* get rid of what will become a bad pointer */
4111 ast_log(LOG_ERROR
,"Could not find priority %d of exten %s in context %s!\n",
4112 priority
, exten
->exten
, con
->name
);
4116 /* hmmm? this exten is not in this pattern tree? */
4117 ast_log(LOG_WARNING
,"Cannot find extension %s in root_table in context %s\n",
4118 extension
, con
->name
);
4121 if (con
->pattern_tree
) {
4122 ast_log(LOG_NOTICE
,"match char tree after exten removal:\n");
4123 log_match_char_tree(con
->pattern_tree
, " ");
4128 /* scan the extension list to find matching extension-registrar */
4129 for (exten
= con
->root
; exten
; prev_exten
= exten
, exten
= exten
->next
) {
4130 if (!strcmp(exten
->exten
, extension
) &&
4131 (!registrar
|| !strcmp(exten
->registrar
, registrar
)))
4135 /* we can't find right extension */
4136 if (!already_locked
)
4137 ast_unlock_context(con
);
4141 /* should we free all peers in this extension? (priority == 0)? */
4142 if (priority
== 0) {
4143 /* remove this extension from context list */
4145 prev_exten
->next
= exten
->next
;
4147 con
->root
= exten
->next
;
4149 /* fire out all peers */
4150 while ( (peer
= exten
) ) {
4151 exten
= peer
->peer
; /* prepare for next entry */
4152 destroy_exten(peer
);
4155 /* scan the priority list to remove extension with exten->priority == priority */
4156 struct ast_exten
*previous_peer
= NULL
;
4158 for (peer
= exten
; peer
; previous_peer
= peer
, peer
= peer
->peer
) {
4159 if (peer
->priority
== priority
&&
4160 (!registrar
|| !strcmp(peer
->registrar
, registrar
) ))
4161 break; /* found our priority */
4163 if (!peer
) { /* not found */
4164 if (!already_locked
)
4165 ast_unlock_context(con
);
4168 /* we are first priority extension? */
4169 if (!previous_peer
) {
4171 * We are first in the priority chain, so must update the extension chain.
4172 * The next node is either the next priority or the next extension
4174 struct ast_exten
*next_node
= peer
->peer
? peer
->peer
: peer
->next
;
4175 if (next_node
&& next_node
== peer
->peer
) {
4176 next_node
->peer_table
= exten
->peer_table
; /* move the priority hash tabs over */
4177 exten
->peer_table
= 0;
4178 next_node
->peer_label_table
= exten
->peer_label_table
;
4179 exten
->peer_label_table
= 0;
4181 if (!prev_exten
) { /* change the root... */
4182 con
->root
= next_node
;
4184 prev_exten
->next
= next_node
; /* unlink */
4186 if (peer
->peer
) { /* XXX update the new head of the pri list */
4187 peer
->peer
->next
= peer
->next
;
4190 } else { /* easy, we are not first priority in extension */
4191 previous_peer
->peer
= peer
->peer
;
4194 /* now, free whole priority extension */
4195 destroy_exten(peer
);
4196 /* XXX should we return -1 ? */
4198 if (!already_locked
)
4199 ast_unlock_context(con
);
4205 * \note This function locks contexts list by &conlist, searches for the right context
4206 * structure, and locks the macrolock mutex in that context.
4207 * macrolock is used to limit a macro to be executed by one call at a time.
4209 int ast_context_lockmacro(const char *context
)
4211 struct ast_context
*c
= NULL
;
4213 struct fake_context item
;
4215 ast_rdlock_contexts();
4217 strncpy(item
.name
,context
,256);
4218 c
= ast_hashtab_lookup(contexts_table
,&item
);
4225 while ((c
= ast_walk_contexts(c
))) {
4226 if (!strcmp(ast_get_context_name(c
), context
)) {
4233 ast_unlock_contexts();
4235 /* if we found context, lock macrolock */
4237 ret
= ast_mutex_lock(&c
->macrolock
);
4243 * \note This function locks contexts list by &conlist, searches for the right context
4244 * structure, and unlocks the macrolock mutex in that context.
4245 * macrolock is used to limit a macro to be executed by one call at a time.
4247 int ast_context_unlockmacro(const char *context
)
4249 struct ast_context
*c
= NULL
;
4251 struct fake_context item
;
4253 ast_rdlock_contexts();
4255 strncpy(item
.name
, context
, 256);
4256 c
= ast_hashtab_lookup(contexts_table
,&item
);
4261 while ((c
= ast_walk_contexts(c
))) {
4262 if (!strcmp(ast_get_context_name(c
), context
)) {
4269 ast_unlock_contexts();
4271 /* if we found context, unlock macrolock */
4273 ret
= ast_mutex_unlock(&c
->macrolock
);
4278 /*! \brief Dynamically register a new dial plan application */
4279 int ast_register_application2(const char *app
, int (*execute
)(struct ast_channel
*, void *), const char *synopsis
, const char *description
, void *mod
)
4281 struct ast_app
*tmp
, *cur
= NULL
;
4285 AST_RWLIST_WRLOCK(&apps
);
4286 AST_RWLIST_TRAVERSE(&apps
, tmp
, list
) {
4287 if (!(res
= strcasecmp(app
, tmp
->name
))) {
4288 ast_log(LOG_WARNING
, "Already have an application '%s'\n", app
);
4289 AST_RWLIST_UNLOCK(&apps
);
4295 length
= sizeof(*tmp
) + strlen(app
) + 1;
4297 if (!(tmp
= ast_calloc(1, length
))) {
4298 AST_RWLIST_UNLOCK(&apps
);
4302 strcpy(tmp
->name
, app
);
4303 tmp
->execute
= execute
;
4304 tmp
->synopsis
= synopsis
;
4305 tmp
->description
= description
;
4308 /* Store in alphabetical order */
4309 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps
, cur
, list
) {
4310 if (strcasecmp(tmp
->name
, cur
->name
) < 0) {
4311 AST_RWLIST_INSERT_BEFORE_CURRENT(tmp
, list
);
4315 AST_RWLIST_TRAVERSE_SAFE_END
;
4317 AST_RWLIST_INSERT_TAIL(&apps
, tmp
, list
);
4319 ast_verb(2, "Registered application '%s'\n", term_color(tmps
, tmp
->name
, COLOR_BRCYAN
, 0, sizeof(tmps
)));
4321 AST_RWLIST_UNLOCK(&apps
);
4327 * Append to the list. We don't have a tail pointer because we need
4328 * to scan the list anyways to check for duplicates during insertion.
4330 int ast_register_switch(struct ast_switch
*sw
)
4332 struct ast_switch
*tmp
;
4334 AST_RWLIST_WRLOCK(&switches
);
4335 AST_RWLIST_TRAVERSE(&switches
, tmp
, list
) {
4336 if (!strcasecmp(tmp
->name
, sw
->name
)) {
4337 AST_RWLIST_UNLOCK(&switches
);
4338 ast_log(LOG_WARNING
, "Switch '%s' already found\n", sw
->name
);
4342 AST_RWLIST_INSERT_TAIL(&switches
, sw
, list
);
4343 AST_RWLIST_UNLOCK(&switches
);
4348 void ast_unregister_switch(struct ast_switch
*sw
)
4350 AST_RWLIST_WRLOCK(&switches
);
4351 AST_RWLIST_REMOVE(&switches
, sw
, list
);
4352 AST_RWLIST_UNLOCK(&switches
);
4356 * Help for CLI commands ...
4360 * \brief 'show application' CLI command implementation function...
4362 static char *handle_show_application(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4365 int app
, no_registered_app
= 1;
4372 e
->command
= "core show application";
4374 "Usage: core show application <application> [<application> [<application> [...]]]\n"
4375 " Describes a particular application.\n";
4379 * There is a possibility to show informations about more than one
4380 * application at one time. You can type 'show application Dial Echo' and
4381 * you will see informations about these two applications ...
4383 wordlen
= strlen(a
->word
);
4384 /* return the n-th [partial] matching entry */
4385 AST_RWLIST_RDLOCK(&apps
);
4386 AST_RWLIST_TRAVERSE(&apps
, aa
, list
) {
4387 if (!strncasecmp(a
->word
, aa
->name
, wordlen
) && ++which
> a
->n
) {
4388 ret
= ast_strdup(aa
->name
);
4392 AST_RWLIST_UNLOCK(&apps
);
4398 return CLI_SHOWUSAGE
;
4400 /* ... go through all applications ... */
4401 AST_RWLIST_RDLOCK(&apps
);
4402 AST_RWLIST_TRAVERSE(&apps
, aa
, list
) {
4403 /* ... compare this application name with all arguments given
4404 * to 'show application' command ... */
4405 for (app
= 3; app
< a
->argc
; app
++) {
4406 if (!strcasecmp(aa
->name
, a
->argv
[app
])) {
4407 /* Maximum number of characters added by terminal coloring is 22 */
4408 char infotitle
[64 + AST_MAX_APP
+ 22], syntitle
[40], destitle
[40];
4409 char info
[64 + AST_MAX_APP
], *synopsis
= NULL
, *description
= NULL
;
4410 int synopsis_size
, description_size
;
4412 no_registered_app
= 0;
4415 synopsis_size
= strlen(aa
->synopsis
) + 23;
4417 synopsis_size
= strlen("Not available") + 23;
4418 synopsis
= alloca(synopsis_size
);
4420 if (aa
->description
)
4421 description_size
= strlen(aa
->description
) + 23;
4423 description_size
= strlen("Not available") + 23;
4424 description
= alloca(description_size
);
4426 if (synopsis
&& description
) {
4427 snprintf(info
, 64 + AST_MAX_APP
, "\n -= Info about application '%s' =- \n\n", aa
->name
);
4428 term_color(infotitle
, info
, COLOR_MAGENTA
, 0, 64 + AST_MAX_APP
+ 22);
4429 term_color(syntitle
, "[Synopsis]\n", COLOR_MAGENTA
, 0, 40);
4430 term_color(destitle
, "[Description]\n", COLOR_MAGENTA
, 0, 40);
4431 term_color(synopsis
,
4432 aa
->synopsis
? aa
->synopsis
: "Not available",
4433 COLOR_CYAN
, 0, synopsis_size
);
4434 term_color(description
,
4435 aa
->description
? aa
->description
: "Not available",
4436 COLOR_CYAN
, 0, description_size
);
4438 ast_cli(a
->fd
,"%s%s%s\n\n%s%s\n", infotitle
, syntitle
, synopsis
, destitle
, description
);
4440 /* ... one of our applications, show info ...*/
4441 ast_cli(a
->fd
,"\n -= Info about application '%s' =- \n\n"
4442 "[Synopsis]\n %s\n\n"
4443 "[Description]\n%s\n",
4445 aa
->synopsis
? aa
->synopsis
: "Not available",
4446 aa
->description
? aa
->description
: "Not available");
4451 AST_RWLIST_UNLOCK(&apps
);
4453 /* we found at least one app? no? */
4454 if (no_registered_app
) {
4455 ast_cli(a
->fd
, "Your application(s) is (are) not registered\n");
4462 /*! \brief handle_show_hints: CLI support for listing registered dial plan hints */
4463 static char *handle_show_hints(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4465 struct ast_hint
*hint
;
4468 struct ast_state_cb
*watcher
;
4472 e
->command
= "core show hints";
4474 "Usage: core show hints\n"
4475 " List registered hints\n";
4481 AST_RWLIST_RDLOCK(&hints
);
4482 if (AST_RWLIST_EMPTY(&hints
)) {
4483 ast_cli(a
->fd
, "There are no registered dialplan hints\n");
4484 AST_RWLIST_UNLOCK(&hints
);
4487 /* ... we have hints ... */
4488 ast_cli(a
->fd
, "\n -= Registered Asterisk Dial Plan Hints =-\n");
4489 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
4491 AST_LIST_TRAVERSE(&hint
->callbacks
, watcher
, entry
) {
4494 ast_cli(a
->fd
, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n",
4495 ast_get_extension_name(hint
->exten
),
4496 ast_get_context_name(ast_get_extension_context(hint
->exten
)),
4497 ast_get_extension_app(hint
->exten
),
4498 ast_extension_state2str(hint
->laststate
), watchers
);
4501 ast_cli(a
->fd
, "----------------\n");
4502 ast_cli(a
->fd
, "- %d hints registered\n", num
);
4503 AST_RWLIST_UNLOCK(&hints
);
4507 /*! \brief autocomplete for CLI command 'core show hint' */
4508 static char *complete_core_show_hint(const char *line
, const char *word
, int pos
, int state
)
4510 struct ast_hint
*hint
;
4518 wordlen
= strlen(word
);
4520 AST_RWLIST_RDLOCK(&hints
);
4521 /* walk through all hints */
4522 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
4523 if (!strncasecmp(word
, ast_get_extension_name(hint
->exten
), wordlen
) && ++which
> state
) {
4524 ret
= ast_strdup(ast_get_extension_name(hint
->exten
));
4528 AST_RWLIST_UNLOCK(&hints
);
4533 /*! \brief handle_show_hint: CLI support for listing registered dial plan hint */
4534 static char *handle_show_hint(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4536 struct ast_hint
*hint
;
4538 int num
= 0, extenlen
;
4539 struct ast_state_cb
*watcher
;
4543 e
->command
= "core show hint";
4545 "Usage: core show hint <exten>\n"
4546 " List registered hint\n";
4549 return complete_core_show_hint(a
->line
, a
->word
, a
->pos
, a
->n
);
4553 return CLI_SHOWUSAGE
;
4555 AST_RWLIST_RDLOCK(&hints
);
4556 if (AST_RWLIST_EMPTY(&hints
)) {
4557 ast_cli(a
->fd
, "There are no registered dialplan hints\n");
4558 AST_RWLIST_UNLOCK(&hints
);
4561 extenlen
= strlen(a
->argv
[3]);
4562 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
4563 if (!strncasecmp(ast_get_extension_name(hint
->exten
), a
->argv
[3], extenlen
)) {
4565 AST_LIST_TRAVERSE(&hint
->callbacks
, watcher
, entry
) {
4568 ast_cli(a
->fd
, " %20s@%-20.20s: %-20.20s State:%-15.15s Watchers %2d\n",
4569 ast_get_extension_name(hint
->exten
),
4570 ast_get_context_name(ast_get_extension_context(hint
->exten
)),
4571 ast_get_extension_app(hint
->exten
),
4572 ast_extension_state2str(hint
->laststate
), watchers
);
4576 AST_RWLIST_UNLOCK(&hints
);
4578 ast_cli(a
->fd
, "No hints matching extension %s\n", a
->argv
[3]);
4580 ast_cli(a
->fd
, "%d hint%s matching extension %s\n", num
, (num
!=1 ? "s":""), a
->argv
[3]);
4585 /*! \brief handle_show_switches: CLI support for listing registered dial plan switches */
4586 static char *handle_show_switches(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4588 struct ast_switch
*sw
;
4592 e
->command
= "core show switches";
4594 "Usage: core show switches\n"
4595 " List registered switches\n";
4601 AST_RWLIST_RDLOCK(&switches
);
4603 if (AST_RWLIST_EMPTY(&switches
)) {
4604 AST_RWLIST_UNLOCK(&switches
);
4605 ast_cli(a
->fd
, "There are no registered alternative switches\n");
4609 ast_cli(a
->fd
, "\n -= Registered Asterisk Alternative Switches =-\n");
4610 AST_RWLIST_TRAVERSE(&switches
, sw
, list
)
4611 ast_cli(a
->fd
, "%s: %s\n", sw
->name
, sw
->description
);
4613 AST_RWLIST_UNLOCK(&switches
);
4618 static char *handle_show_applications(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4621 int like
= 0, describing
= 0;
4622 int total_match
= 0; /* Number of matches in like clause */
4623 int total_apps
= 0; /* Number of apps registered */
4624 static char* choices
[] = { "like", "describing", NULL
};
4628 e
->command
= "core show applications [like|describing]";
4630 "Usage: core show applications [{like|describing} <text>]\n"
4631 " List applications which are currently available.\n"
4632 " If 'like', <text> will be a substring of the app name\n"
4633 " If 'describing', <text> will be a substring of the description\n";
4636 return (a
->pos
!= 3) ? NULL
: ast_cli_complete(a
->word
, choices
, a
->n
);
4639 AST_RWLIST_RDLOCK(&apps
);
4641 if (AST_RWLIST_EMPTY(&apps
)) {
4642 ast_cli(a
->fd
, "There are no registered applications\n");
4643 AST_RWLIST_UNLOCK(&apps
);
4647 /* core list applications like <keyword> */
4648 if ((a
->argc
== 5) && (!strcmp(a
->argv
[3], "like"))) {
4650 } else if ((a
->argc
> 4) && (!strcmp(a
->argv
[3], "describing"))) {
4654 /* core list applications describing <keyword1> [<keyword2>] [...] */
4655 if ((!like
) && (!describing
)) {
4656 ast_cli(a
->fd
, " -= Registered Asterisk Applications =-\n");
4658 ast_cli(a
->fd
, " -= Matching Asterisk Applications =-\n");
4661 AST_RWLIST_TRAVERSE(&apps
, aa
, list
) {
4665 if (strcasestr(aa
->name
, a
->argv
[4])) {
4669 } else if (describing
) {
4670 if (aa
->description
) {
4671 /* Match all words on command line */
4674 for (i
= 4; i
< a
->argc
; i
++) {
4675 if (!strcasestr(aa
->description
, a
->argv
[i
])) {
4687 ast_cli(a
->fd
," %20s: %s\n", aa
->name
, aa
->synopsis
? aa
->synopsis
: "<Synopsis not available>");
4690 if ((!like
) && (!describing
)) {
4691 ast_cli(a
->fd
, " -= %d Applications Registered =-\n",total_apps
);
4693 ast_cli(a
->fd
, " -= %d Applications Matching =-\n",total_match
);
4696 AST_RWLIST_UNLOCK(&apps
);
4702 * 'show dialplan' CLI command implementation functions ...
4704 static char *complete_show_dialplan_context(const char *line
, const char *word
, int pos
,
4707 struct ast_context
*c
= NULL
;
4712 /* we are do completion of [exten@]context on second position only */
4716 ast_rdlock_contexts();
4718 wordlen
= strlen(word
);
4720 /* walk through all contexts and return the n-th match */
4721 while ( (c
= ast_walk_contexts(c
)) ) {
4722 if (!strncasecmp(word
, ast_get_context_name(c
), wordlen
) && ++which
> state
) {
4723 ret
= ast_strdup(ast_get_context_name(c
));
4728 ast_unlock_contexts();
4733 /*! \brief Counters for the show dialplan manager command */
4734 struct dialplan_counters
{
4739 int context_existence
;
4740 int extension_existence
;
4743 /*! \brief helper function to print an extension */
4744 static void print_ext(struct ast_exten
*e
, char * buf
, int buflen
)
4746 int prio
= ast_get_extension_priority(e
);
4747 if (prio
== PRIORITY_HINT
) {
4748 snprintf(buf
, buflen
, "hint: %s",
4749 ast_get_extension_app(e
));
4751 snprintf(buf
, buflen
, "%d. %s(%s)",
4752 prio
, ast_get_extension_app(e
),
4753 (!ast_strlen_zero(ast_get_extension_app_data(e
)) ? (char *)ast_get_extension_app_data(e
) : ""));
4757 /* XXX not verified */
4758 static int show_dialplan_helper(int fd
, const char *context
, const char *exten
, struct dialplan_counters
*dpc
, struct ast_include
*rinclude
, int includecount
, const char *includes
[])
4760 struct ast_context
*c
= NULL
;
4761 int res
= 0, old_total_exten
= dpc
->total_exten
;
4763 ast_rdlock_contexts();
4765 /* walk all contexts ... */
4766 while ( (c
= ast_walk_contexts(c
)) ) {
4767 struct ast_exten
*e
;
4768 struct ast_include
*i
;
4769 struct ast_ignorepat
*ip
;
4770 char buf
[256], buf2
[256];
4771 int context_info_printed
= 0;
4773 if (context
&& strcmp(ast_get_context_name(c
), context
))
4774 continue; /* skip this one, name doesn't match */
4776 dpc
->context_existence
= 1;
4778 ast_rdlock_context(c
);
4780 /* are we looking for exten too? if yes, we print context
4781 * only if we find our extension.
4782 * Otherwise print context even if empty ?
4783 * XXX i am not sure how the rinclude is handled.
4784 * I think it ought to go inside.
4787 dpc
->total_context
++;
4788 ast_cli(fd
, "[ Context '%s' created by '%s' ]\n",
4789 ast_get_context_name(c
), ast_get_context_registrar(c
));
4790 context_info_printed
= 1;
4793 /* walk extensions ... */
4795 while ( (e
= ast_walk_context_extensions(c
, e
)) ) {
4796 struct ast_exten
*p
;
4798 if (exten
&& !ast_extension_match(ast_get_extension_name(e
), exten
))
4799 continue; /* skip, extension match failed */
4801 dpc
->extension_existence
= 1;
4803 /* may we print context info? */
4804 if (!context_info_printed
) {
4805 dpc
->total_context
++;
4806 if (rinclude
) { /* TODO Print more info about rinclude */
4807 ast_cli(fd
, "[ Included context '%s' created by '%s' ]\n",
4808 ast_get_context_name(c
), ast_get_context_registrar(c
));
4810 ast_cli(fd
, "[ Context '%s' created by '%s' ]\n",
4811 ast_get_context_name(c
), ast_get_context_registrar(c
));
4813 context_info_printed
= 1;
4817 /* write extension name and first peer */
4819 snprintf(buf
, sizeof(buf
), "'%s' (CID match '%s') => ", ast_get_extension_name(e
), e
->cidmatch
);
4821 snprintf(buf
, sizeof(buf
), "'%s' =>", ast_get_extension_name(e
));
4823 print_ext(e
, buf2
, sizeof(buf2
));
4825 ast_cli(fd
, " %-17s %-45s [%s]\n", buf
, buf2
,
4826 ast_get_extension_registrar(e
));
4829 /* walk next extension peers */
4830 p
= e
; /* skip the first one, we already got it */
4831 while ( (p
= ast_walk_extension_priorities(e
, p
)) ) {
4832 const char *el
= ast_get_extension_label(p
);
4835 snprintf(buf
, sizeof(buf
), " [%s]", el
);
4838 print_ext(p
, buf2
, sizeof(buf2
));
4840 ast_cli(fd
," %-17s %-45s [%s]\n", buf
, buf2
,
4841 ast_get_extension_registrar(p
));
4845 /* walk included and write info ... */
4847 while ( (i
= ast_walk_context_includes(c
, i
)) ) {
4848 snprintf(buf
, sizeof(buf
), "'%s'", ast_get_include_name(i
));
4850 /* Check all includes for the requested extension */
4851 if (includecount
>= AST_PBX_MAX_STACK
) {
4852 ast_log(LOG_WARNING
, "Maximum include depth exceeded!\n");
4856 for (x
= 0; x
< includecount
; x
++) {
4857 if (!strcasecmp(includes
[x
], ast_get_include_name(i
))) {
4863 includes
[includecount
] = ast_get_include_name(i
);
4864 show_dialplan_helper(fd
, ast_get_include_name(i
), exten
, dpc
, i
, includecount
+ 1, includes
);
4866 ast_log(LOG_WARNING
, "Avoiding circular include of %s within %s\n", ast_get_include_name(i
), context
);
4870 ast_cli(fd
, " Include => %-45s [%s]\n",
4871 buf
, ast_get_include_registrar(i
));
4875 /* walk ignore patterns and write info ... */
4877 while ( (ip
= ast_walk_context_ignorepats(c
, ip
)) ) {
4878 const char *ipname
= ast_get_ignorepat_name(ip
);
4879 char ignorepat
[AST_MAX_EXTENSION
];
4880 snprintf(buf
, sizeof(buf
), "'%s'", ipname
);
4881 snprintf(ignorepat
, sizeof(ignorepat
), "_%s.", ipname
);
4882 if (!exten
|| ast_extension_match(ignorepat
, exten
)) {
4883 ast_cli(fd
, " Ignore pattern => %-45s [%s]\n",
4884 buf
, ast_get_ignorepat_registrar(ip
));
4888 struct ast_sw
*sw
= NULL
;
4889 while ( (sw
= ast_walk_context_switches(c
, sw
)) ) {
4890 snprintf(buf
, sizeof(buf
), "'%s/%s'",
4891 ast_get_switch_name(sw
),
4892 ast_get_switch_data(sw
));
4893 ast_cli(fd
, " Alt. Switch => %-45s [%s]\n",
4894 buf
, ast_get_switch_registrar(sw
));
4898 if (option_debug
&& c
->pattern_tree
)
4900 ast_cli(fd
,"\r\n In-mem exten Trie for Fast Extension Pattern Matching:\r\n\r\n");
4902 ast_cli(fd
,"\r\n Explanation: Node Contents Format = <char(s) to match>:<pattern?>:<specif>:[matched extension]\r\n");
4903 ast_cli(fd
, " Where <char(s) to match> is a set of chars, any one of which should match the current character\r\n");
4904 ast_cli(fd
, " <pattern?>: Y if this a pattern match (eg. _XZN[5-7]), N otherwise\r\n");
4905 ast_cli(fd
, " <specif>: an assigned 'exactness' number for this matching char. The lower the number, the more exact the match\r\n");
4906 ast_cli(fd
, " [matched exten]: If all chars matched to this point, which extension this matches. In form: EXTEN:<exten string> \r\n");
4907 ast_cli(fd
, " In general, you match a trie node to a string character, from left to right. All possible matching chars\r\n");
4908 ast_cli(fd
, " are in a string vertically, separated by an unbroken string of '+' characters.\r\n\r\n");
4909 cli_match_char_tree(c
->pattern_tree
, " ", fd
);
4912 ast_unlock_context(c
);
4914 /* if we print something in context, make an empty line */
4915 if (context_info_printed
)
4916 ast_cli(fd
, "\r\n");
4918 ast_unlock_contexts();
4920 return (dpc
->total_exten
== old_total_exten
) ? -1 : res
;
4923 static char *handle_show_dialplan(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
4925 char *exten
= NULL
, *context
= NULL
;
4926 /* Variables used for different counters */
4927 struct dialplan_counters counters
;
4928 const char *incstack
[AST_PBX_MAX_STACK
];
4932 e
->command
= "dialplan show";
4934 "Usage: dialplan show [[exten@]context]\n"
4938 return complete_show_dialplan_context(a
->line
, a
->word
, a
->pos
, a
->n
);
4941 memset(&counters
, 0, sizeof(counters
));
4943 if (a
->argc
!= 2 && a
->argc
!= 3)
4944 return CLI_SHOWUSAGE
;
4946 /* we obtain [exten@]context? if yes, split them ... */
4948 if (strchr(a
->argv
[2], '@')) { /* split into exten & context */
4949 context
= ast_strdupa(a
->argv
[2]);
4950 exten
= strsep(&context
, "@");
4951 /* change empty strings to NULL */
4952 if (ast_strlen_zero(exten
))
4954 } else { /* no '@' char, only context given */
4955 context
= a
->argv
[2];
4957 if (ast_strlen_zero(context
))
4960 /* else Show complete dial plan, context and exten are NULL */
4961 show_dialplan_helper(a
->fd
, context
, exten
, &counters
, NULL
, 0, incstack
);
4963 /* check for input failure and throw some error messages */
4964 if (context
&& !counters
.context_existence
) {
4965 ast_cli(a
->fd
, "There is no existence of '%s' context\n", context
);
4969 if (exten
&& !counters
.extension_existence
) {
4971 ast_cli(a
->fd
, "There is no existence of %s@%s extension\n",
4975 "There is no existence of '%s' extension in all contexts\n",
4980 ast_cli(a
->fd
,"-= %d %s (%d %s) in %d %s. =-\n",
4981 counters
.total_exten
, counters
.total_exten
== 1 ? "extension" : "extensions",
4982 counters
.total_prio
, counters
.total_prio
== 1 ? "priority" : "priorities",
4983 counters
.total_context
, counters
.total_context
== 1 ? "context" : "contexts");
4989 /*! \brief Send ack once */
4990 static void manager_dpsendack(struct mansession
*s
, const struct message
*m
)
4992 astman_send_listack(s
, m
, "DialPlan list will follow", "start");
4995 /*! \brief Show dialplan extensions
4996 * XXX this function is similar but not exactly the same as the CLI's
4997 * show dialplan. Must check whether the difference is intentional or not.
4999 static int manager_show_dialplan_helper(struct mansession
*s
, const struct message
*m
,
5000 const char *actionidtext
, const char *context
,
5001 const char *exten
, struct dialplan_counters
*dpc
,
5002 struct ast_include
*rinclude
)
5004 struct ast_context
*c
;
5005 int res
= 0, old_total_exten
= dpc
->total_exten
;
5007 if (ast_strlen_zero(exten
))
5009 if (ast_strlen_zero(context
))
5012 ast_debug(3, "manager_show_dialplan: Context: -%s- Extension: -%s-\n", context
, exten
);
5014 /* try to lock contexts */
5015 if (ast_rdlock_contexts()) {
5016 astman_send_error(s
, m
, "Failed to lock contexts\r\n");
5017 ast_log(LOG_WARNING
, "Failed to lock contexts list for manager: listdialplan\n");
5021 c
= NULL
; /* walk all contexts ... */
5022 while ( (c
= ast_walk_contexts(c
)) ) {
5023 struct ast_exten
*e
;
5024 struct ast_include
*i
;
5025 struct ast_ignorepat
*ip
;
5027 if (context
&& strcmp(ast_get_context_name(c
), context
) != 0)
5028 continue; /* not the name we want */
5030 dpc
->context_existence
= 1;
5032 ast_debug(3, "manager_show_dialplan: Found Context: %s \n", ast_get_context_name(c
));
5034 if (ast_rdlock_context(c
)) { /* failed to lock */
5035 ast_debug(3, "manager_show_dialplan: Failed to lock context\n");
5039 /* XXX note- an empty context is not printed */
5040 e
= NULL
; /* walk extensions in context */
5041 while ( (e
= ast_walk_context_extensions(c
, e
)) ) {
5042 struct ast_exten
*p
;
5044 /* looking for extension? is this our extension? */
5045 if (exten
&& !ast_extension_match(ast_get_extension_name(e
), exten
)) {
5046 /* not the one we are looking for, continue */
5047 ast_debug(3, "manager_show_dialplan: Skipping extension %s\n", ast_get_extension_name(e
));
5050 ast_debug(3, "manager_show_dialplan: Found Extension: %s \n", ast_get_extension_name(e
));
5052 dpc
->extension_existence
= 1;
5054 /* may we print context info? */
5055 dpc
->total_context
++;
5058 p
= NULL
; /* walk next extension peers */
5059 while ( (p
= ast_walk_extension_priorities(e
, p
)) ) {
5060 int prio
= ast_get_extension_priority(p
);
5063 if (!dpc
->total_items
++)
5064 manager_dpsendack(s
, m
);
5065 astman_append(s
, "Event: ListDialplan\r\n%s", actionidtext
);
5066 astman_append(s
, "Context: %s\r\nExtension: %s\r\n", ast_get_context_name(c
), ast_get_extension_name(e
) );
5068 /* XXX maybe make this conditional, if p != e ? */
5069 if (ast_get_extension_label(p
))
5070 astman_append(s
, "ExtensionLabel: %s\r\n", ast_get_extension_label(p
));
5072 if (prio
== PRIORITY_HINT
) {
5073 astman_append(s
, "Priority: hint\r\nApplication: %s\r\n", ast_get_extension_app(p
));
5075 astman_append(s
, "Priority: %d\r\nApplication: %s\r\nAppData: %s\r\n", prio
, ast_get_extension_app(p
), (char *) ast_get_extension_app_data(p
));
5077 astman_append(s
, "Registrar: %s\r\n\r\n", ast_get_extension_registrar(e
));
5081 i
= NULL
; /* walk included and write info ... */
5082 while ( (i
= ast_walk_context_includes(c
, i
)) ) {
5084 /* Check all includes for the requested extension */
5085 manager_show_dialplan_helper(s
, m
, actionidtext
, ast_get_include_name(i
), exten
, dpc
, i
);
5087 if (!dpc
->total_items
++)
5088 manager_dpsendack(s
, m
);
5089 astman_append(s
, "Event: ListDialplan\r\n%s", actionidtext
);
5090 astman_append(s
, "Context: %s\r\nIncludeContext: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c
), ast_get_include_name(i
), ast_get_include_registrar(i
));
5091 astman_append(s
, "\r\n");
5092 ast_debug(3, "manager_show_dialplan: Found Included context: %s \n", ast_get_include_name(i
));
5096 ip
= NULL
; /* walk ignore patterns and write info ... */
5097 while ( (ip
= ast_walk_context_ignorepats(c
, ip
)) ) {
5098 const char *ipname
= ast_get_ignorepat_name(ip
);
5099 char ignorepat
[AST_MAX_EXTENSION
];
5101 snprintf(ignorepat
, sizeof(ignorepat
), "_%s.", ipname
);
5102 if (!exten
|| ast_extension_match(ignorepat
, exten
)) {
5103 if (!dpc
->total_items
++)
5104 manager_dpsendack(s
, m
);
5105 astman_append(s
, "Event: ListDialplan\r\n%s", actionidtext
);
5106 astman_append(s
, "Context: %s\r\nIgnorePattern: %s\r\nRegistrar: %s\r\n", ast_get_context_name(c
), ipname
, ast_get_ignorepat_registrar(ip
));
5107 astman_append(s
, "\r\n");
5111 struct ast_sw
*sw
= NULL
;
5112 while ( (sw
= ast_walk_context_switches(c
, sw
)) ) {
5113 if (!dpc
->total_items
++)
5114 manager_dpsendack(s
, m
);
5115 astman_append(s
, "Event: ListDialplan\r\n%s", actionidtext
);
5116 astman_append(s
, "Context: %s\r\nSwitch: %s/%s\r\nRegistrar: %s\r\n", ast_get_context_name(c
), ast_get_switch_name(sw
), ast_get_switch_data(sw
), ast_get_switch_registrar(sw
));
5117 astman_append(s
, "\r\n");
5118 ast_debug(3, "manager_show_dialplan: Found Switch : %s \n", ast_get_switch_name(sw
));
5122 ast_unlock_context(c
);
5124 ast_unlock_contexts();
5126 if (dpc
->total_exten
== old_total_exten
) {
5127 ast_debug(3, "manager_show_dialplan: Found nothing new\n");
5128 /* Nothing new under the sun */
5135 /*! \brief Manager listing of dial plan */
5136 static int manager_show_dialplan(struct mansession
*s
, const struct message
*m
)
5138 const char *exten
, *context
;
5139 const char *id
= astman_get_header(m
, "ActionID");
5143 /* Variables used for different counters */
5144 struct dialplan_counters counters
;
5146 if (!ast_strlen_zero(id
))
5147 snprintf(idtext
, sizeof(idtext
), "ActionID: %s\r\n", id
);
5151 memset(&counters
, 0, sizeof(counters
));
5153 exten
= astman_get_header(m
, "Extension");
5154 context
= astman_get_header(m
, "Context");
5156 res
= manager_show_dialplan_helper(s
, m
, idtext
, context
, exten
, &counters
, NULL
);
5158 if (context
&& !counters
.context_existence
) {
5159 char errorbuf
[BUFSIZ
];
5161 snprintf(errorbuf
, sizeof(errorbuf
), "Did not find context %s\r\n", context
);
5162 astman_send_error(s
, m
, errorbuf
);
5165 if (exten
&& !counters
.extension_existence
) {
5166 char errorbuf
[BUFSIZ
];
5169 snprintf(errorbuf
, sizeof(errorbuf
), "Did not find extension %s@%s\r\n", exten
, context
);
5171 snprintf(errorbuf
, sizeof(errorbuf
), "Did not find extension %s in any context\r\n", exten
);
5172 astman_send_error(s
, m
, errorbuf
);
5176 manager_event(EVENT_FLAG_CONFIG
, "ShowDialPlanComplete",
5177 "EventList: Complete\r\n"
5179 "ListExtensions: %d\r\n"
5180 "ListPriorities: %d\r\n"
5181 "ListContexts: %d\r\n"
5183 "\r\n", counters
.total_items
, counters
.total_exten
, counters
.total_prio
, counters
.total_context
, idtext
);
5189 static char mandescr_show_dialplan
[] =
5190 "Description: Show dialplan contexts and extensions.\n"
5191 "Be aware that showing the full dialplan may take a lot of capacity\n"
5193 " ActionID: <id> Action ID for this AMI transaction (optional)\n"
5194 " Extension: <extension> Extension (Optional)\n"
5195 " Context: <context> Context (Optional)\n"
5199 /*! \brief CLI support for listing global variables in a parseable way */
5200 static char *handle_show_globals(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5203 struct ast_var_t
*newvariable
;
5207 e
->command
= "core show globals";
5209 "Usage: core show globals\n"
5210 " List current global dialplan variables and their values\n";
5216 ast_rwlock_rdlock(&globalslock
);
5217 AST_LIST_TRAVERSE (&globals
, newvariable
, entries
) {
5219 ast_cli(a
->fd
, " %s=%s\n", ast_var_name(newvariable
), ast_var_value(newvariable
));
5221 ast_rwlock_unlock(&globalslock
);
5222 ast_cli(a
->fd
, "\n -- %d variables\n", i
);
5227 static char *handle_set_global(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5231 e
->command
= "core set global";
5233 "Usage: core set global <name> <value>\n"
5234 " Set global dialplan variable <name> to <value>\n";
5240 if (a
->argc
!= e
->args
+ 2)
5241 return CLI_SHOWUSAGE
;
5243 pbx_builtin_setvar_helper(NULL
, a
->argv
[3], a
->argv
[4]);
5244 ast_cli(a
->fd
, "\n -- Global variable %s set to %s\n", a
->argv
[3], a
->argv
[4]);
5249 static char *handle_set_chanvar(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5251 struct ast_channel
*chan
;
5252 const char *chan_name
, *var_name
, *var_value
;
5256 e
->command
= "core set chanvar";
5258 "Usage: core set chanvar <channel> <varname> <value>\n"
5259 " Set channel variable <varname> to <value>\n";
5262 return ast_complete_channels(a
->line
, a
->word
, a
->pos
, a
->n
, 3);
5265 if (a
->argc
!= e
->args
+ 3)
5266 return CLI_SHOWUSAGE
;
5268 chan_name
= a
->argv
[e
->args
];
5269 var_name
= a
->argv
[e
->args
+ 1];
5270 var_value
= a
->argv
[e
->args
+ 2];
5272 if (!(chan
= ast_get_channel_by_name_locked(chan_name
))) {
5273 ast_cli(a
->fd
, "Channel '%s' not found\n", chan_name
);
5277 pbx_builtin_setvar_helper(chan
, var_name
, var_value
);
5279 ast_channel_unlock(chan
);
5281 ast_cli(a
->fd
, "\n -- Channel variable '%s' set to '%s' for '%s'\n",
5282 var_name
, var_value
, chan_name
);
5287 static char *handle_set_extenpatternmatchnew(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5293 e
->command
= "dialplan set extenpatternmatchnew true";
5295 "Usage: dialplan set extenpatternmatchnew true|false\n"
5296 " Use the NEW extension pattern matching algorithm, true or false.\n";
5303 return CLI_SHOWUSAGE
;
5305 oldval
= pbx_set_extenpatternmatchnew(1);
5308 ast_cli(a
->fd
, "\n -- Still using the NEW pattern match algorithm for extension names in the dialplan.\n");
5310 ast_cli(a
->fd
, "\n -- Switched to using the NEW pattern match algorithm for extension names in the dialplan.\n");
5315 static char *handle_unset_extenpatternmatchnew(struct ast_cli_entry
*e
, int cmd
, struct ast_cli_args
*a
)
5321 e
->command
= "dialplan set extenpatternmatchnew false";
5323 "Usage: dialplan set extenpatternmatchnew true|false\n"
5324 " Use the NEW extension pattern matching algorithm, true or false.\n";
5331 return CLI_SHOWUSAGE
;
5333 oldval
= pbx_set_extenpatternmatchnew(0);
5336 ast_cli(a
->fd
, "\n -- Still using the OLD pattern match algorithm for extension names in the dialplan.\n");
5338 ast_cli(a
->fd
, "\n -- Switched to using the OLD pattern match algorithm for extension names in the dialplan.\n");
5344 * CLI entries for upper commands ...
5346 static struct ast_cli_entry pbx_cli
[] = {
5347 AST_CLI_DEFINE(handle_show_applications
, "Shows registered dialplan applications"),
5348 AST_CLI_DEFINE(handle_show_functions
, "Shows registered dialplan functions"),
5349 AST_CLI_DEFINE(handle_show_switches
, "Show alternative switches"),
5350 AST_CLI_DEFINE(handle_show_hints
, "Show dialplan hints"),
5351 AST_CLI_DEFINE(handle_show_hint
, "Show dialplan hint"),
5352 AST_CLI_DEFINE(handle_show_globals
, "Show global dialplan variables"),
5353 AST_CLI_DEFINE(handle_show_function
, "Describe a specific dialplan function"),
5354 AST_CLI_DEFINE(handle_show_application
, "Describe a specific dialplan application"),
5355 AST_CLI_DEFINE(handle_set_global
, "Set global dialplan variable"),
5356 AST_CLI_DEFINE(handle_set_chanvar
, "Set a channel variable"),
5357 AST_CLI_DEFINE(handle_show_dialplan
, "Show dialplan"),
5358 AST_CLI_DEFINE(handle_unset_extenpatternmatchnew
, "Use the Old extension pattern matching algorithm."),
5359 AST_CLI_DEFINE(handle_set_extenpatternmatchnew
, "Use the New extension pattern matching algorithm."),
5362 static void unreference_cached_app(struct ast_app
*app
)
5364 struct ast_context
*context
= NULL
;
5365 struct ast_exten
*eroot
= NULL
, *e
= NULL
;
5367 ast_rdlock_contexts();
5368 while ((context
= ast_walk_contexts(context
))) {
5369 while ((eroot
= ast_walk_context_extensions(context
, eroot
))) {
5370 while ((e
= ast_walk_extension_priorities(eroot
, e
))) {
5371 if (e
->cached_app
== app
)
5372 e
->cached_app
= NULL
;
5376 ast_unlock_contexts();
5381 int ast_unregister_application(const char *app
)
5383 struct ast_app
*tmp
;
5385 AST_RWLIST_WRLOCK(&apps
);
5386 AST_RWLIST_TRAVERSE_SAFE_BEGIN(&apps
, tmp
, list
) {
5387 if (!strcasecmp(app
, tmp
->name
)) {
5388 unreference_cached_app(tmp
);
5389 AST_RWLIST_REMOVE_CURRENT(list
);
5390 ast_verb(2, "Unregistered application '%s'\n", tmp
->name
);
5395 AST_RWLIST_TRAVERSE_SAFE_END
;
5396 AST_RWLIST_UNLOCK(&apps
);
5398 return tmp
? 0 : -1;
5401 struct ast_context
*ast_context_find_or_create(struct ast_context
**extcontexts
, struct ast_hashtab
*exttable
, const char *name
, const char *registrar
)
5403 struct ast_context
*tmp
, **local_contexts
;
5404 struct fake_context search
;
5405 int length
= sizeof(struct ast_context
) + strlen(name
) + 1;
5407 if (!contexts_table
) {
5408 contexts_table
= ast_hashtab_create(17,
5409 ast_hashtab_compare_contexts
,
5410 ast_hashtab_resize_java
,
5411 ast_hashtab_newsize_java
,
5412 ast_hashtab_hash_contexts
,
5416 strncpy(search
.name
,name
,sizeof(search
.name
));
5418 ast_rdlock_contexts();
5419 local_contexts
= &contexts
;
5420 tmp
= ast_hashtab_lookup(contexts_table
, &search
);
5421 ast_unlock_contexts();
5426 } else { /* local contexts just in a linked list; search there for the new context; slow, linear search, but not frequent */
5427 local_contexts
= extcontexts
;
5428 tmp
= ast_hashtab_lookup(exttable
, &search
);
5435 if ((tmp
= ast_calloc(1, length
))) {
5436 ast_rwlock_init(&tmp
->lock
);
5437 ast_mutex_init(&tmp
->macrolock
);
5438 strcpy(tmp
->name
, name
);
5440 tmp
->root_table
= NULL
;
5441 tmp
->registrar
= registrar
;
5442 tmp
->includes
= NULL
;
5443 tmp
->ignorepats
= NULL
;
5446 ast_log(LOG_ERROR
, "Danger! We failed to allocate a context for %s!\n", name
);
5451 ast_wrlock_contexts();
5452 tmp
->next
= *local_contexts
;
5453 *local_contexts
= tmp
;
5454 ast_hashtab_insert_safe(contexts_table
, tmp
); /*put this context into the tree */
5455 ast_unlock_contexts();
5457 tmp
->next
= *local_contexts
;
5459 ast_hashtab_insert_immediate(exttable
, tmp
); /*put this context into the tree */
5460 *local_contexts
= tmp
;
5462 ast_debug(1, "Registered context '%s'\n", tmp
->name
);
5463 ast_verb(3, "Registered extension context '%s'\n", tmp
->name
);
5467 void __ast_context_destroy(struct ast_context
*list
, struct ast_hashtab
*contexttab
, struct ast_context
*con
, const char *registrar
);
5472 AST_LIST_HEAD_NOLOCK(, ast_state_cb
) callbacks
;
5474 AST_LIST_ENTRY(store_hint
) list
;
5478 AST_LIST_HEAD(store_hints
, store_hint
);
5480 static void context_merge_incls_swits_igps_other_registrars(struct ast_context
*new, struct ast_context
*old
, const char *registrar
)
5482 struct ast_include
*i
;
5483 struct ast_ignorepat
*ip
;
5486 /* copy in the includes, switches, and ignorepats */
5487 /* walk through includes */
5488 for (i
= NULL
; (i
= ast_walk_context_includes(old
, i
)) ; ) {
5489 if (strcmp(ast_get_include_registrar(i
), registrar
) == 0)
5490 continue; /* not mine */
5491 ast_context_add_include2(new, ast_get_include_name(i
), ast_get_include_registrar(i
));
5494 /* walk through switches */
5495 for (sw
= NULL
; (sw
= ast_walk_context_switches(old
, sw
)) ; ) {
5496 if (strcmp(ast_get_switch_registrar(sw
), registrar
) == 0)
5497 continue; /* not mine */
5498 ast_context_add_switch2(new, ast_get_switch_name(sw
), ast_get_switch_data(sw
), ast_get_switch_eval(sw
), ast_get_switch_registrar(sw
));
5501 /* walk thru ignorepats ... */
5502 for (ip
= NULL
; (ip
= ast_walk_context_ignorepats(old
, ip
)); ) {
5503 if (strcmp(ast_get_ignorepat_registrar(ip
), registrar
) == 0)
5504 continue; /* not mine */
5505 ast_context_add_ignorepat2(new, ast_get_ignorepat_name(ip
), ast_get_ignorepat_registrar(ip
));
5510 /* the purpose of this routine is to duplicate a context, with all its substructure,
5511 except for any extens that have a matching registrar */
5512 static void context_merge(struct ast_context
**extcontexts
, struct ast_hashtab
*exttable
, struct ast_context
*context
, const char *registrar
)
5514 struct ast_context
*new = ast_hashtab_lookup(exttable
, context
); /* is there a match in the new set? */
5515 struct ast_exten
*exten_item
, *prio_item
, *new_exten_item
, *new_prio_item
;
5516 struct ast_hashtab_iter
*exten_iter
;
5517 struct ast_hashtab_iter
*prio_iter
;
5518 int insert_count
= 0;
5520 /* We'll traverse all the extensions/prios, and see which are not registrar'd with
5521 the current registrar, and copy them to the new context. If the new context does not
5522 exist, we'll create it "on demand". If no items are in this context to copy, then we'll
5523 only create the empty matching context if the old one meets the criteria */
5524 if (context
->root_table
) {
5525 exten_iter
= ast_hashtab_start_traversal(context
->root_table
);
5526 while ((exten_item
=ast_hashtab_next(exten_iter
))) {
5528 new_exten_item
= ast_hashtab_lookup(new->root_table
, exten_item
);
5530 new_exten_item
= NULL
;
5532 prio_iter
= ast_hashtab_start_traversal(exten_item
->peer_table
);
5533 while ((prio_item
=ast_hashtab_next(prio_iter
))) {
5536 if (new_exten_item
) {
5537 new_prio_item
= ast_hashtab_lookup(new_exten_item
->peer_table
, prio_item
);
5539 new_prio_item
= NULL
;
5541 if (strcmp(prio_item
->registrar
,registrar
) == 0) {
5544 /* make sure the new context exists, so we have somewhere to stick this exten/prio */
5546 new = ast_context_find_or_create(extcontexts
, exttable
, context
->name
, prio_item
->registrar
); /* a new context created via priority from a different context in the old dialplan, gets its registrar from the prio's registrar */
5548 /* copy in the includes, switches, and ignorepats */
5549 context_merge_incls_swits_igps_other_registrars(new, context
, registrar
);
5552 ast_log(LOG_ERROR
,"Could not allocate a new context for %s in merge_and_delete! Danger!\n", context
->name
);
5553 return; /* no sense continuing. */
5555 /* we will not replace existing entries in the new context with stuff from the old context.
5556 but, if this is because of some sort of registrar conflict, we ought to say something... */
5557 res1
= ast_add_extension2(new, 0, prio_item
->exten
, prio_item
->priority
, prio_item
->label
,
5558 prio_item
->cidmatch
, prio_item
->app
, prio_item
->data
, prio_item
->datad
, prio_item
->registrar
);
5559 if (!res1
&& new_exten_item
&& new_prio_item
){
5560 ast_verb(3,"Dropping old dialplan item %s/%s/%d [%s(%s)] (registrar=%s) due to conflict with new dialplan\n",
5561 context
->name
, prio_item
->exten
, prio_item
->priority
, prio_item
->app
, (char*)prio_item
->data
, prio_item
->registrar
);
5563 prio_item
->data
= NULL
; /* we pass the priority data from the old to the new */
5567 ast_hashtab_end_traversal(prio_iter
);
5569 ast_hashtab_end_traversal(exten_iter
);
5572 if (!insert_count
&& !new && (strcmp(context
->registrar
, registrar
) != 0 ||
5573 (strcmp(context
->registrar
, registrar
) == 0 && context
->refcount
> 1))) {
5575 /* we could have given it the registrar of the other module who incremented the refcount,
5576 but that's not available, so we give it the registrar we know about */
5577 new = ast_context_find_or_create(extcontexts
, exttable
, context
->name
, context
->registrar
);
5579 /* copy in the includes, switches, and ignorepats */
5580 context_merge_incls_swits_igps_other_registrars(new, context
, registrar
);
5585 /* XXX this does not check that multiple contexts are merged */
5586 void ast_merge_contexts_and_delete(struct ast_context
**extcontexts
, struct ast_hashtab
*exttable
, const char *registrar
)
5589 struct ast_context
*tmp
, *oldcontextslist
;
5590 struct ast_hashtab
*oldtable
;
5591 struct store_hints store
= AST_LIST_HEAD_INIT_VALUE
;
5592 struct store_hint
*this;
5593 struct ast_hint
*hint
;
5594 struct ast_exten
*exten
;
5596 struct ast_state_cb
*thiscb
;
5597 struct ast_hashtab_iter
*iter
;
5599 /* it is very important that this function hold the hint list lock _and_ the conlock
5600 during its operation; not only do we need to ensure that the list of contexts
5601 and extensions does not change, but also that no hint callbacks (watchers) are
5602 added or removed during the merge/delete process
5604 in addition, the locks _must_ be taken in this order, because there are already
5605 other code paths that use this order
5608 struct timeval begintime
, writelocktime
, endlocktime
, enddeltime
;
5611 begintime
= ast_tvnow();
5612 ast_rdlock_contexts();
5613 iter
= ast_hashtab_start_traversal(contexts_table
);
5614 while ((tmp
= ast_hashtab_next(iter
))) {
5615 context_merge(extcontexts
, exttable
, tmp
, registrar
);
5617 ast_hashtab_end_traversal(iter
);
5618 wrlock_ver
= ast_wrlock_contexts_version();
5620 ast_unlock_contexts(); /* this feels real retarded, but you must do
5621 what you must do If this isn't done, the following
5622 wrlock is a guraranteed deadlock */
5623 ast_wrlock_contexts();
5624 if (ast_wrlock_contexts_version() > wrlock_ver
+1) {
5625 ast_log(LOG_WARNING
,"Something changed the contexts in the middle of merging contexts!\n");
5628 AST_RWLIST_WRLOCK(&hints
);
5629 writelocktime
= ast_tvnow();
5631 /* preserve all watchers for hints associated with this registrar */
5632 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
5633 if (!AST_LIST_EMPTY(&hint
->callbacks
) && !strcmp(registrar
, hint
->exten
->parent
->registrar
)) {
5634 length
= strlen(hint
->exten
->exten
) + strlen(hint
->exten
->parent
->name
) + 2 + sizeof(*this);
5635 if (!(this = ast_calloc(1, length
)))
5637 AST_LIST_APPEND_LIST(&this->callbacks
, &hint
->callbacks
, entry
);
5638 this->laststate
= hint
->laststate
;
5639 this->context
= this->data
;
5640 strcpy(this->data
, hint
->exten
->parent
->name
);
5641 this->exten
= this->data
+ strlen(this->context
) + 1;
5642 strcpy(this->exten
, hint
->exten
->exten
);
5643 AST_LIST_INSERT_HEAD(&store
, this, list
);
5647 /* save the old table and list */
5648 oldtable
= contexts_table
;
5649 oldcontextslist
= contexts
;
5651 /* move in the new table and list */
5652 contexts_table
= exttable
;
5653 contexts
= *extcontexts
;
5655 /* restore the watchers for hints that can be found; notify those that
5658 while ((this = AST_LIST_REMOVE_HEAD(&store
, list
))) {
5659 struct pbx_find_info q
= { .stacklen
= 0 };
5660 exten
= pbx_find_extension(NULL
, NULL
, &q
, this->context
, this->exten
, PRIORITY_HINT
, NULL
, "", E_MATCH
);
5661 /* If this is a pattern, dynamically create a new extension for this
5662 * particular match. Note that this will only happen once for each
5663 * individual extension, because the pattern will no longer match first.
5665 if (exten
&& exten
->exten
[0] == '_') {
5666 ast_add_extension(exten
->parent
->name
, 0, this->exten
, PRIORITY_HINT
, NULL
,
5667 0, exten
->app
, strdup(exten
->data
), free
, registrar
);
5668 exten
= ast_hint_extension(NULL
, this->context
, this->exten
);
5671 /* Find the hint in the list of hints */
5672 AST_RWLIST_TRAVERSE(&hints
, hint
, list
) {
5673 if (hint
->exten
== exten
)
5676 if (!exten
|| !hint
) {
5677 /* this hint has been removed, notify the watchers */
5678 while ((thiscb
= AST_LIST_REMOVE_HEAD(&this->callbacks
, entry
))) {
5679 thiscb
->callback(this->context
, this->exten
, AST_EXTENSION_REMOVED
, thiscb
->data
);
5683 AST_LIST_APPEND_LIST(&hint
->callbacks
, &this->callbacks
, entry
);
5684 hint
->laststate
= this->laststate
;
5689 AST_RWLIST_UNLOCK(&hints
);
5690 ast_unlock_contexts();
5691 endlocktime
= ast_tvnow();
5693 /* the old list and hashtab no longer are relevant, delete them while the rest of asterisk
5694 is now freely using the new stuff instead */
5696 ast_hashtab_destroy(oldtable
, NULL
);
5698 for (tmp
= oldcontextslist
; tmp
; ) {
5699 struct ast_context
*next
; /* next starting point */
5701 __ast_internal_context_destroy(tmp
);
5704 enddeltime
= ast_tvnow();
5706 ft
= ast_tvdiff_us(writelocktime
, begintime
);
5708 ast_verb(3,"Time to scan old dialplan and merge leftovers back into the new: %8.6f sec\n", ft
);
5710 ft
= ast_tvdiff_us(endlocktime
, writelocktime
);
5712 ast_verb(3,"Time to restore hints and swap in new dialplan: %8.6f sec\n", ft
);
5714 ft
= ast_tvdiff_us(enddeltime
, endlocktime
);
5716 ast_verb(3,"Time to delete the old dialplan: %8.6f sec\n", ft
);
5718 ft
= ast_tvdiff_us(enddeltime
, begintime
);
5720 ast_verb(3,"Total time merge_contexts_delete: %8.6f sec\n", ft
);
5726 * EBUSY - can't lock
5727 * ENOENT - no existence of context
5729 int ast_context_add_include(const char *context
, const char *include
, const char *registrar
)
5732 struct ast_context
*c
= find_context_locked(context
);
5735 ret
= ast_context_add_include2(c
, include
, registrar
);
5736 ast_unlock_contexts();
5741 /*! \brief Helper for get_range.
5742 * return the index of the matching entry, starting from 1.
5743 * If names is not supplied, try numeric values.
5745 static int lookup_name(const char *s
, char *const names
[], int max
)
5750 for (i
= 0; names
[i
]; i
++) {
5751 if (!strcasecmp(s
, names
[i
]))
5754 } else if (sscanf(s
, "%d", &i
) == 1 && i
>= 1 && i
<= max
) {
5757 return 0; /* error return */
5760 /*! \brief helper function to return a range up to max (7, 12, 31 respectively).
5761 * names, if supplied, is an array of names that should be mapped to numbers.
5763 static unsigned get_range(char *src
, int max
, char *const names
[], const char *msg
)
5765 int s
, e
; /* start and ending position */
5766 unsigned int mask
= 0;
5768 /* Check for whole range */
5769 if (ast_strlen_zero(src
) || !strcmp(src
, "*")) {
5773 /* Get start and ending position */
5774 char *c
= strchr(src
, '-');
5777 /* Find the start */
5778 s
= lookup_name(src
, names
, max
);
5780 ast_log(LOG_WARNING
, "Invalid %s '%s', assuming none\n", msg
, src
);
5784 if (c
) { /* find end of range */
5785 e
= lookup_name(c
, names
, max
);
5787 ast_log(LOG_WARNING
, "Invalid end %s '%s', assuming none\n", msg
, c
);
5794 /* Fill the mask. Remember that ranges are cyclic */
5795 mask
= 1 << e
; /* initialize with last element */
5808 /*! \brief store a bitmask of valid times, one bit each 2 minute */
5809 static void get_timerange(struct ast_timing
*i
, char *times
)
5817 /* start disabling all times, fill the fields with 0's, as they may contain garbage */
5818 memset(i
->minmask
, 0, sizeof(i
->minmask
));
5820 /* 2-minutes per bit, since the mask has only 32 bits :( */
5821 /* Star is all times */
5822 if (ast_strlen_zero(times
) || !strcmp(times
, "*")) {
5823 for (x
= 0; x
< 24; x
++)
5824 i
->minmask
[x
] = 0x3fffffff; /* 30 bits */
5827 /* Otherwise expect a range */
5828 e
= strchr(times
, '-');
5830 ast_log(LOG_WARNING
, "Time range is not valid. Assuming no restrictions based on time.\n");
5834 /* XXX why skip non digits ? */
5835 while (*e
&& !isdigit(*e
))
5838 ast_log(LOG_WARNING
, "Invalid time range. Assuming no restrictions based on time.\n");
5841 if (sscanf(times
, "%d:%d", &s1
, &s2
) != 2) {
5842 ast_log(LOG_WARNING
, "%s isn't a time. Assuming no restrictions based on time.\n", times
);
5845 if (sscanf(e
, "%d:%d", &e1
, &e2
) != 2) {
5846 ast_log(LOG_WARNING
, "%s isn't a time. Assuming no restrictions based on time.\n", e
);
5849 /* XXX this needs to be optimized */
5851 s1
= s1
* 30 + s2
/2;
5852 if ((s1
< 0) || (s1
>= 24*30)) {
5853 ast_log(LOG_WARNING
, "%s isn't a valid start time. Assuming no time.\n", times
);
5856 e1
= e1
* 30 + e2
/2;
5857 if ((e1
< 0) || (e1
>= 24*30)) {
5858 ast_log(LOG_WARNING
, "%s isn't a valid end time. Assuming no time.\n", e
);
5861 /* Go through the time and enable each appropriate bit */
5862 for (x
=s1
;x
!= e1
;x
= (x
+ 1) % (24 * 30)) {
5863 i
->minmask
[x
/30] |= (1 << (x
% 30));
5865 /* Do the last one */
5866 i
->minmask
[x
/30] |= (1 << (x
% 30));
5868 for (cth
= 0; cth
< 24; cth
++) {
5869 /* Initialize masks to blank */
5870 i
->minmask
[cth
] = 0;
5871 for (ctm
= 0; ctm
< 30; ctm
++) {
5873 /* First hour with more than one hour */
5874 (((cth
== s1
) && (ctm
>= s2
)) &&
5877 || (((cth
== s1
) && (ctm
>= s2
)) &&
5878 ((cth
== e1
) && (ctm
<= e2
)))
5879 /* In between first and last hours (more than 2 hours) */
5882 /* Last hour with more than one hour */
5884 ((cth
== e1
) && (ctm
<= e2
)))
5886 i
->minmask
[cth
] |= (1 << (ctm
/ 2));
5894 static char *days
[] =
5906 static char *months
[] =
5923 int ast_build_timing(struct ast_timing
*i
, const char *info_in
)
5925 char info_save
[256];
5928 /* Check for empty just in case */
5929 if (ast_strlen_zero(info_in
))
5931 /* make a copy just in case we were passed a static string */
5932 ast_copy_string(info_save
, info_in
, sizeof(info_save
));
5934 /* Assume everything except time */
5935 i
->monthmask
= 0xfff; /* 12 bits */
5936 i
->daymask
= 0x7fffffffU
; /* 31 bits */
5937 i
->dowmask
= 0x7f; /* 7 bits */
5938 /* on each call, use strsep() to move info to the next argument */
5939 get_timerange(i
, strsep(&info
, "|,"));
5941 i
->dowmask
= get_range(strsep(&info
, "|,"), 7, days
, "day of week");
5943 i
->daymask
= get_range(strsep(&info
, "|,"), 31, NULL
, "day");
5945 i
->monthmask
= get_range(strsep(&info
, "|,"), 12, months
, "month");
5949 int ast_check_timing(const struct ast_timing
*i
)
5952 struct timeval tv
= ast_tvnow();
5954 ast_localtime(&tv
, &tm
, NULL
);
5956 /* If it's not the right month, return */
5957 if (!(i
->monthmask
& (1 << tm
.tm_mon
)))
5960 /* If it's not that time of the month.... */
5961 /* Warning, tm_mday has range 1..31! */
5962 if (!(i
->daymask
& (1 << (tm
.tm_mday
-1))))
5965 /* If it's not the right day of the week */
5966 if (!(i
->dowmask
& (1 << tm
.tm_wday
)))
5969 /* Sanity check the hour just to be safe */
5970 if ((tm
.tm_hour
< 0) || (tm
.tm_hour
> 23)) {
5971 ast_log(LOG_WARNING
, "Insane time...\n");
5975 /* Now the tough part, we calculate if it fits
5976 in the right time based on min/hour */
5977 if (!(i
->minmask
[tm
.tm_hour
] & (1 << (tm
.tm_min
/ 2))))
5980 /* If we got this far, then we're good */
5986 * ENOMEM - out of memory
5987 * EBUSY - can't lock
5988 * EEXIST - already included
5989 * EINVAL - there is no existence of context for inclusion
5991 int ast_context_add_include2(struct ast_context
*con
, const char *value
,
5992 const char *registrar
)
5994 struct ast_include
*new_include
;
5996 struct ast_include
*i
, *il
= NULL
; /* include, include_last */
6000 length
= sizeof(struct ast_include
);
6001 length
+= 2 * (strlen(value
) + 1);
6003 /* allocate new include structure ... */
6004 if (!(new_include
= ast_calloc(1, length
)))
6006 /* Fill in this structure. Use 'p' for assignments, as the fields
6007 * in the structure are 'const char *'
6009 p
= new_include
->stuff
;
6010 new_include
->name
= p
;
6012 p
+= strlen(value
) + 1;
6013 new_include
->rname
= p
;
6015 /* Strip off timing info, and process if it is there */
6016 if ( (c
= strchr(p
, ',')) ) {
6018 new_include
->hastime
= ast_build_timing(&(new_include
->timing
), c
);
6020 new_include
->next
= NULL
;
6021 new_include
->registrar
= registrar
;
6023 ast_wrlock_context(con
);
6025 /* ... go to last include and check if context is already included too... */
6026 for (i
= con
->includes
; i
; i
= i
->next
) {
6027 if (!strcasecmp(i
->name
, new_include
->name
)) {
6028 ast_free(new_include
);
6029 ast_unlock_context(con
);
6036 /* ... include new context into context list, unlock, return */
6038 il
->next
= new_include
;
6040 con
->includes
= new_include
;
6041 ast_verb(3, "Including context '%s' in context '%s'\n", new_include
->name
, ast_get_context_name(con
));
6043 ast_unlock_context(con
);
6050 * EBUSY - can't lock
6051 * ENOENT - no existence of context
6053 int ast_context_add_switch(const char *context
, const char *sw
, const char *data
, int eval
, const char *registrar
)
6056 struct ast_context
*c
= find_context_locked(context
);
6058 if (c
) { /* found, add switch to this context */
6059 ret
= ast_context_add_switch2(c
, sw
, data
, eval
, registrar
);
6060 ast_unlock_contexts();
6067 * ENOMEM - out of memory
6068 * EBUSY - can't lock
6069 * EEXIST - already included
6070 * EINVAL - there is no existence of context for inclusion
6072 int ast_context_add_switch2(struct ast_context
*con
, const char *value
,
6073 const char *data
, int eval
, const char *registrar
)
6075 struct ast_sw
*new_sw
;
6080 length
= sizeof(struct ast_sw
);
6081 length
+= strlen(value
) + 1;
6083 length
+= strlen(data
);
6086 /* allocate new sw structure ... */
6087 if (!(new_sw
= ast_calloc(1, length
)))
6089 /* ... fill in this structure ... */
6092 strcpy(new_sw
->name
, value
);
6093 p
+= strlen(value
) + 1;
6096 strcpy(new_sw
->data
, data
);
6097 p
+= strlen(data
) + 1;
6099 strcpy(new_sw
->data
, "");
6102 new_sw
->eval
= eval
;
6103 new_sw
->registrar
= registrar
;
6105 /* ... try to lock this context ... */
6106 ast_wrlock_context(con
);
6108 /* ... go to last sw and check if context is already swd too... */
6109 AST_LIST_TRAVERSE(&con
->alts
, i
, list
) {
6110 if (!strcasecmp(i
->name
, new_sw
->name
) && !strcasecmp(i
->data
, new_sw
->data
)) {
6112 ast_unlock_context(con
);
6118 /* ... sw new context into context list, unlock, return */
6119 AST_LIST_INSERT_TAIL(&con
->alts
, new_sw
, list
);
6121 ast_verb(3, "Including switch '%s/%s' in context '%s'\n", new_sw
->name
, new_sw
->data
, ast_get_context_name(con
));
6123 ast_unlock_context(con
);
6129 * EBUSY - can't lock
6130 * ENOENT - there is not context existence
6132 int ast_context_remove_ignorepat(const char *context
, const char *ignorepat
, const char *registrar
)
6135 struct ast_context
*c
= find_context_locked(context
);
6138 ret
= ast_context_remove_ignorepat2(c
, ignorepat
, registrar
);
6139 ast_unlock_contexts();
6144 int ast_context_remove_ignorepat2(struct ast_context
*con
, const char *ignorepat
, const char *registrar
)
6146 struct ast_ignorepat
*ip
, *ipl
= NULL
;
6148 ast_wrlock_context(con
);
6150 for (ip
= con
->ignorepats
; ip
; ip
= ip
->next
) {
6151 if (!strcmp(ip
->pattern
, ignorepat
) &&
6152 (!registrar
|| (registrar
== ip
->registrar
))) {
6154 ipl
->next
= ip
->next
;
6157 con
->ignorepats
= ip
->next
;
6160 ast_unlock_context(con
);
6166 ast_unlock_context(con
);
6172 * EBUSY - can't lock
6173 * ENOENT - there is no existence of context
6175 int ast_context_add_ignorepat(const char *context
, const char *value
, const char *registrar
)
6178 struct ast_context
*c
= find_context_locked(context
);
6181 ret
= ast_context_add_ignorepat2(c
, value
, registrar
);
6182 ast_unlock_contexts();
6187 int ast_context_add_ignorepat2(struct ast_context
*con
, const char *value
, const char *registrar
)
6189 struct ast_ignorepat
*ignorepat
, *ignorepatc
, *ignorepatl
= NULL
;
6191 length
= sizeof(struct ast_ignorepat
);
6192 length
+= strlen(value
) + 1;
6193 if (!(ignorepat
= ast_calloc(1, length
)))
6195 /* The cast to char * is because we need to write the initial value.
6196 * The field is not supposed to be modified otherwise
6198 strcpy((char *)ignorepat
->pattern
, value
);
6199 ignorepat
->next
= NULL
;
6200 ignorepat
->registrar
= registrar
;
6201 ast_wrlock_context(con
);
6202 for (ignorepatc
= con
->ignorepats
; ignorepatc
; ignorepatc
= ignorepatc
->next
) {
6203 ignorepatl
= ignorepatc
;
6204 if (!strcasecmp(ignorepatc
->pattern
, value
)) {
6206 ast_unlock_context(con
);
6212 ignorepatl
->next
= ignorepat
;
6214 con
->ignorepats
= ignorepat
;
6215 ast_unlock_context(con
);
6220 int ast_ignore_pattern(const char *context
, const char *pattern
)
6222 struct ast_context
*con
= ast_context_find(context
);
6224 struct ast_ignorepat
*pat
;
6225 for (pat
= con
->ignorepats
; pat
; pat
= pat
->next
) {
6226 if (ast_extension_match(pat
->pattern
, pattern
))
6235 * EBUSY - can't lock
6236 * ENOENT - no existence of context
6239 int ast_add_extension(const char *context
, int replace
, const char *extension
,
6240 int priority
, const char *label
, const char *callerid
,
6241 const char *application
, void *data
, void (*datad
)(void *), const char *registrar
)
6244 struct ast_context
*c
= find_context_locked(context
);
6247 ret
= ast_add_extension2(c
, replace
, extension
, priority
, label
, callerid
,
6248 application
, data
, datad
, registrar
);
6249 ast_unlock_contexts();
6255 int ast_explicit_goto(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
)
6260 ast_channel_lock(chan
);
6262 if (!ast_strlen_zero(context
))
6263 ast_copy_string(chan
->context
, context
, sizeof(chan
->context
));
6264 if (!ast_strlen_zero(exten
))
6265 ast_copy_string(chan
->exten
, exten
, sizeof(chan
->exten
));
6266 if (priority
> -1) {
6267 chan
->priority
= priority
;
6268 /* see flag description in channel.h for explanation */
6269 if (ast_test_flag(chan
, AST_FLAG_IN_AUTOLOOP
))
6273 ast_channel_unlock(chan
);
6278 int ast_async_goto(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
)
6282 ast_channel_lock(chan
);
6284 if (chan
->pbx
) { /* This channel is currently in the PBX */
6285 ast_explicit_goto(chan
, context
, exten
, priority
+ 1);
6286 ast_softhangup_nolock(chan
, AST_SOFTHANGUP_ASYNCGOTO
);
6288 /* In order to do it when the channel doesn't really exist within
6289 the PBX, we have to make a new channel, masquerade, and start the PBX
6290 at the new location */
6291 struct ast_channel
*tmpchan
= ast_channel_alloc(0, chan
->_state
, 0, 0, chan
->accountcode
, chan
->exten
, chan
->context
, chan
->amaflags
, "AsyncGoto/%s", chan
->name
);
6296 ast_cdr_discard(tmpchan
->cdr
);
6297 tmpchan
->cdr
= ast_cdr_dup(chan
->cdr
); /* share the love */
6299 /* Make formats okay */
6300 tmpchan
->readformat
= chan
->readformat
;
6301 tmpchan
->writeformat
= chan
->writeformat
;
6302 /* Setup proper location */
6303 ast_explicit_goto(tmpchan
,
6304 S_OR(context
, chan
->context
), S_OR(exten
, chan
->exten
), priority
);
6306 /* Masquerade into temp channel */
6307 ast_channel_masquerade(tmpchan
, chan
);
6309 /* Grab the locks and get going */
6310 ast_channel_lock(tmpchan
);
6311 ast_do_masquerade(tmpchan
);
6312 ast_channel_unlock(tmpchan
);
6313 /* Start the PBX going on our stolen channel */
6314 if (ast_pbx_start(tmpchan
)) {
6315 ast_log(LOG_WARNING
, "Unable to start PBX on %s\n", tmpchan
->name
);
6316 ast_hangup(tmpchan
);
6321 ast_channel_unlock(chan
);
6325 int ast_async_goto_by_name(const char *channame
, const char *context
, const char *exten
, int priority
)
6327 struct ast_channel
*chan
;
6330 chan
= ast_get_channel_by_name_locked(channame
);
6332 res
= ast_async_goto(chan
, context
, exten
, priority
);
6333 ast_channel_unlock(chan
);
6338 /*! \brief copy a string skipping whitespace */
6339 static int ext_strncpy(char *dst
, const char *src
, int len
)
6343 while (*src
&& (count
< len
- 1)) {
6346 /* otherwise exten => [a-b],1,... doesn't work */
6363 * \brief add the extension in the priority chain.
6364 * \retval 0 on success.
6365 * \retval -1 on failure.
6367 static int add_pri(struct ast_context
*con
, struct ast_exten
*tmp
,
6368 struct ast_exten
*el
, struct ast_exten
*e
, int replace
)
6370 struct ast_exten
*ep
;
6371 struct ast_exten
*eh
=e
;
6373 for (ep
= NULL
; e
; ep
= e
, e
= e
->peer
) {
6374 if (e
->priority
>= tmp
->priority
)
6377 if (!e
) { /* go at the end, and ep is surely set because the list is not empty */
6378 ast_hashtab_insert_safe(eh
->peer_table
, tmp
);
6380 ast_hashtab_insert_safe(eh
->peer_label_table
, tmp
);
6382 return 0; /* success */
6384 if (e
->priority
== tmp
->priority
) {
6385 /* Can't have something exactly the same. Is this a
6386 replacement? If so, replace, otherwise, bonk. */
6388 ast_log(LOG_WARNING
, "Unable to register extension '%s', priority %d in '%s', already in use\n", tmp
->exten
, tmp
->priority
, con
->name
);
6390 tmp
->datad(tmp
->data
);
6394 /* we are replacing e, so copy the link fields and then update
6395 * whoever pointed to e to point to us
6397 tmp
->next
= e
->next
; /* not meaningful if we are not first in the peer list */
6398 tmp
->peer
= e
->peer
; /* always meaningful */
6399 if (ep
) { /* We're in the peer list, just insert ourselves */
6400 ast_hashtab_remove_object_via_lookup(eh
->peer_table
,e
);
6402 ast_hashtab_remove_object_via_lookup(eh
->peer_label_table
,e
);
6403 ast_hashtab_insert_safe(eh
->peer_table
,tmp
);
6405 ast_hashtab_insert_safe(eh
->peer_label_table
,tmp
);
6407 } else if (el
) { /* We're the first extension. Take over e's functions */
6408 struct match_char
*x
= add_exten_to_pattern_tree(con
, e
, 1);
6409 tmp
->peer_table
= e
->peer_table
;
6410 tmp
->peer_label_table
= e
->peer_label_table
;
6411 ast_hashtab_remove_object_via_lookup(tmp
->peer_table
,e
);
6412 ast_hashtab_insert_safe(tmp
->peer_table
,tmp
);
6414 ast_hashtab_remove_object_via_lookup(tmp
->peer_label_table
, e
);
6416 ast_hashtab_insert_safe(tmp
->peer_label_table
, tmp
);
6417 ast_hashtab_remove_object_via_lookup(con
->root_table
, e
);
6418 ast_hashtab_insert_safe(con
->root_table
, tmp
);
6420 /* The pattern trie points to this exten; replace the pointer,
6421 and all will be well */
6422 if (x
) { /* if the trie isn't formed yet, don't sweat this */
6423 if (x
->exten
) { /* this test for safety purposes */
6424 x
->exten
= tmp
; /* replace what would become a bad pointer */
6426 ast_log(LOG_ERROR
,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
6429 } else { /* We're the very first extension. */
6430 struct match_char
*x
= add_exten_to_pattern_tree(con
, e
, 1);
6431 ast_hashtab_remove_object_via_lookup(con
->root_table
, e
);
6432 ast_hashtab_insert_safe(con
->root_table
, tmp
);
6433 tmp
->peer_table
= e
->peer_table
;
6434 tmp
->peer_label_table
= e
->peer_label_table
;
6435 ast_hashtab_remove_object_via_lookup(tmp
->peer_table
, e
);
6436 ast_hashtab_insert_safe(tmp
->peer_table
, tmp
);
6438 ast_hashtab_remove_object_via_lookup(tmp
->peer_label_table
, e
);
6440 ast_hashtab_insert_safe(tmp
->peer_label_table
, tmp
);
6441 ast_hashtab_remove_object_via_lookup(con
->root_table
, e
);
6442 ast_hashtab_insert_safe(con
->root_table
, tmp
);
6444 /* The pattern trie points to this exten; replace the pointer,
6445 and all will be well */
6446 if (x
) { /* if the trie isn't formed yet; no problem */
6447 if (x
->exten
) { /* this test for safety purposes */
6448 x
->exten
= tmp
; /* replace what would become a bad pointer */
6450 ast_log(LOG_ERROR
,"Trying to delete an exten from a context, but the pattern tree node returned isn't an extension\n");
6454 if (tmp
->priority
== PRIORITY_HINT
)
6455 ast_change_hint(e
,tmp
);
6456 /* Destroy the old one */
6460 } else { /* Slip ourselves in just before e */
6462 tmp
->next
= e
->next
; /* extension chain, or NULL if e is not the first extension */
6463 if (ep
) { /* Easy enough, we're just in the peer list */
6465 ast_hashtab_insert_safe(eh
->peer_label_table
, tmp
);
6466 ast_hashtab_insert_safe(eh
->peer_table
, tmp
);
6468 } else { /* we are the first in some peer list, so link in the ext list */
6469 tmp
->peer_table
= e
->peer_table
;
6470 tmp
->peer_label_table
= e
->peer_label_table
;
6472 e
->peer_label_table
= 0;
6473 ast_hashtab_insert_safe(tmp
->peer_table
, tmp
);
6475 ast_hashtab_insert_safe(tmp
->peer_label_table
, tmp
);
6477 ast_hashtab_remove_object_via_lookup(con
->root_table
, e
);
6478 ast_hashtab_insert_safe(con
->root_table
, tmp
);
6480 el
->next
= tmp
; /* in the middle... */
6482 con
->root
= tmp
; /* ... or at the head */
6483 e
->next
= NULL
; /* e is no more at the head, so e->next must be reset */
6485 /* And immediately return success. */
6486 if (tmp
->priority
== PRIORITY_HINT
)
6493 * Main interface to add extensions to the list for out context.
6495 * We sort extensions in order of matching preference, so that we can
6496 * stop the search as soon as we find a suitable match.
6497 * This ordering also takes care of wildcards such as '.' (meaning
6498 * "one or more of any character") and '!' (which is 'earlymatch',
6499 * meaning "zero or more of any character" but also impacts the
6500 * return value from CANMATCH and EARLYMATCH.
6502 * The extension match rules defined in the devmeeting 2006.05.05 are
6503 * quite simple: WE SELECT THE LONGEST MATCH.
6504 * In detail, "longest" means the number of matched characters in
6505 * the extension. In case of ties (e.g. _XXX and 333) in the length
6506 * of a pattern, we give priority to entries with the smallest cardinality
6507 * (e.g, [5-9] comes before [2-8] before the former has only 5 elements,
6508 * while the latter has 7, etc.
6509 * In case of same cardinality, the first element in the range counts.
6510 * If we still have a tie, any final '!' will make this as a possibly
6511 * less specific pattern.
6513 * EBUSY - can't lock
6514 * EEXIST - extension with the same priority exist and no replace is set
6517 int ast_add_extension2(struct ast_context
*con
,
6518 int replace
, const char *extension
, int priority
, const char *label
, const char *callerid
,
6519 const char *application
, void *data
, void (*datad
)(void *),
6520 const char *registrar
)
6523 * Sort extensions (or patterns) according to the rules indicated above.
6524 * These are implemented by the function ext_cmp()).
6525 * All priorities for the same ext/pattern/cid are kept in a list,
6526 * using the 'peer' field as a link field..
6528 struct ast_exten
*tmp
, *tmp2
, *e
, *el
= NULL
;
6532 char expand_buf
[VAR_BUF_SIZE
];
6533 struct ast_exten dummy_exten
= {0};
6534 char dummy_name
[1024];
6536 /* If we are adding a hint evalulate in variables and global variables */
6537 if (priority
== PRIORITY_HINT
&& strstr(application
, "${") && !strstr(extension
, "_")) {
6538 struct ast_channel c
= {0, };
6540 /* Start out with regular variables */
6541 ast_copy_string(c
.exten
, extension
, sizeof(c
.exten
));
6542 ast_copy_string(c
.context
, con
->name
, sizeof(c
.context
));
6543 pbx_substitute_variables_helper(&c
, application
, expand_buf
, sizeof(expand_buf
));
6545 /* Move on to global variables if they exist */
6546 ast_rwlock_rdlock(&globalslock
);
6547 if (AST_LIST_FIRST(&globals
)) {
6548 pbx_substitute_variables_varshead(&globals
, application
, expand_buf
, sizeof(expand_buf
));
6549 application
= expand_buf
;
6551 ast_rwlock_unlock(&globalslock
);
6554 length
= sizeof(struct ast_exten
);
6555 length
+= strlen(extension
) + 1;
6556 length
+= strlen(application
) + 1;
6558 length
+= strlen(label
) + 1;
6560 length
+= strlen(callerid
) + 1;
6562 length
++; /* just the '\0' */
6564 /* Be optimistic: Build the extension structure first */
6565 if (!(tmp
= ast_calloc(1, length
)))
6568 if (ast_strlen_zero(label
)) /* let's turn empty labels to a null ptr */
6571 /* use p as dst in assignments, as the fields are const char * */
6576 p
+= strlen(label
) + 1;
6579 p
+= ext_strncpy(p
, extension
, strlen(extension
) + 1) + 1;
6580 tmp
->priority
= priority
;
6581 tmp
->cidmatch
= p
; /* but use p for assignments below */
6582 if (!ast_strlen_zero(callerid
)) {
6583 p
+= ext_strncpy(p
, callerid
, strlen(callerid
) + 1) + 1;
6590 strcpy(p
, application
);
6594 tmp
->registrar
= registrar
;
6596 ast_wrlock_context(con
);
6598 if (con
->pattern_tree
) { /* usually, on initial load, the pattern_tree isn't formed until the first find_exten; so if we are adding
6599 an extension, and the trie exists, then we need to incrementally add this pattern to it. */
6600 strncpy(dummy_name
,extension
,sizeof(dummy_name
));
6601 dummy_exten
.exten
= dummy_name
;
6602 dummy_exten
.matchcid
= 0;
6603 dummy_exten
.cidmatch
= 0;
6604 tmp2
= ast_hashtab_lookup(con
->root_table
, &dummy_exten
);
6606 /* hmmm, not in the trie; */
6607 add_exten_to_pattern_tree(con
, tmp
, 0);
6608 ast_hashtab_insert_safe(con
->root_table
, tmp
); /* for the sake of completeness */
6611 res
= 0; /* some compilers will think it is uninitialized otherwise */
6612 for (e
= con
->root
; e
; el
= e
, e
= e
->next
) { /* scan the extension list */
6613 res
= ext_cmp(e
->exten
, extension
);
6614 if (res
== 0) { /* extension match, now look at cidmatch */
6615 if (!e
->matchcid
&& !tmp
->matchcid
)
6617 else if (tmp
->matchcid
&& !e
->matchcid
)
6619 else if (e
->matchcid
&& !tmp
->matchcid
)
6622 res
= strcasecmp(e
->cidmatch
, tmp
->cidmatch
);
6627 if (e
&& res
== 0) { /* exact match, insert in the pri chain */
6628 res
= add_pri(con
, tmp
, el
, e
, replace
);
6629 ast_unlock_context(con
);
6631 errno
= EEXIST
; /* XXX do we care ? */
6632 return 0; /* XXX should we return -1 maybe ? */
6636 * not an exact match, this is the first entry with this pattern,
6637 * so insert in the main list right before 'e' (if any)
6640 if (el
) { /* there is another exten already in this context */
6642 tmp
->peer_table
= ast_hashtab_create(13,
6643 hashtab_compare_exten_numbers
,
6644 ast_hashtab_resize_java
,
6645 ast_hashtab_newsize_java
,
6646 hashtab_hash_priority
,
6648 tmp
->peer_label_table
= ast_hashtab_create(7,
6649 hashtab_compare_exten_labels
,
6650 ast_hashtab_resize_java
,
6651 ast_hashtab_newsize_java
,
6652 hashtab_hash_labels
,
6655 ast_hashtab_insert_safe(tmp
->peer_label_table
, tmp
);
6656 ast_hashtab_insert_safe(tmp
->peer_table
, tmp
);
6658 } else { /* this is the first exten in this context */
6659 if (!con
->root_table
)
6660 con
->root_table
= ast_hashtab_create(27,
6661 hashtab_compare_extens
,
6662 ast_hashtab_resize_java
,
6663 ast_hashtab_newsize_java
,
6664 hashtab_hash_extens
,
6667 con
->root
->peer_table
= ast_hashtab_create(13,
6668 hashtab_compare_exten_numbers
,
6669 ast_hashtab_resize_java
,
6670 ast_hashtab_newsize_java
,
6671 hashtab_hash_priority
,
6673 con
->root
->peer_label_table
= ast_hashtab_create(7,
6674 hashtab_compare_exten_labels
,
6675 ast_hashtab_resize_java
,
6676 ast_hashtab_newsize_java
,
6677 hashtab_hash_labels
,
6680 ast_hashtab_insert_safe(con
->root
->peer_label_table
, tmp
);
6681 ast_hashtab_insert_safe(con
->root
->peer_table
, tmp
);
6683 ast_hashtab_insert_safe(con
->root_table
, tmp
);
6684 ast_unlock_context(con
);
6685 if (tmp
->priority
== PRIORITY_HINT
)
6689 if (tmp
->matchcid
) {
6690 ast_debug(1, "Added extension '%s' priority %d (CID match '%s') to %s\n",
6691 tmp
->exten
, tmp
->priority
, tmp
->cidmatch
, con
->name
);
6693 ast_debug(1, "Added extension '%s' priority %d to %s\n",
6694 tmp
->exten
, tmp
->priority
, con
->name
);
6698 if (tmp
->matchcid
) {
6699 ast_verb(3, "Added extension '%s' priority %d (CID match '%s') to %s\n",
6700 tmp
->exten
, tmp
->priority
, tmp
->cidmatch
, con
->name
);
6702 ast_verb(3, "Added extension '%s' priority %d to %s\n",
6703 tmp
->exten
, tmp
->priority
, con
->name
);
6711 struct ast_channel
*chan
;
6712 char context
[AST_MAX_CONTEXT
];
6713 char exten
[AST_MAX_EXTENSION
];
6716 char app
[AST_MAX_EXTENSION
];
6720 static void *async_wait(void *data
)
6722 struct async_stat
*as
= data
;
6723 struct ast_channel
*chan
= as
->chan
;
6724 int timeout
= as
->timeout
;
6726 struct ast_frame
*f
;
6727 struct ast_app
*app
;
6729 while (timeout
&& (chan
->_state
!= AST_STATE_UP
)) {
6730 res
= ast_waitfor(chan
, timeout
);
6738 if (f
->frametype
== AST_FRAME_CONTROL
) {
6739 if ((f
->subclass
== AST_CONTROL_BUSY
) ||
6740 (f
->subclass
== AST_CONTROL_CONGESTION
) ) {
6747 if (chan
->_state
== AST_STATE_UP
) {
6748 if (!ast_strlen_zero(as
->app
)) {
6749 app
= pbx_findapp(as
->app
);
6751 ast_verb(3, "Launching %s(%s) on %s\n", as
->app
, as
->appdata
, chan
->name
);
6752 pbx_exec(chan
, app
, as
->appdata
);
6754 ast_log(LOG_WARNING
, "No such application '%s'\n", as
->app
);
6756 if (!ast_strlen_zero(as
->context
))
6757 ast_copy_string(chan
->context
, as
->context
, sizeof(chan
->context
));
6758 if (!ast_strlen_zero(as
->exten
))
6759 ast_copy_string(chan
->exten
, as
->exten
, sizeof(chan
->exten
));
6760 if (as
->priority
> 0)
6761 chan
->priority
= as
->priority
;
6763 if (ast_pbx_run(chan
)) {
6764 ast_log(LOG_ERROR
, "Failed to start PBX on %s\n", chan
->name
);
6766 /* PBX will have taken care of this */
6778 * \brief Function to post an empty cdr after a spool call fails.
6779 * \note This function posts an empty cdr for a failed spool call
6781 static int ast_pbx_outgoing_cdr_failed(void)
6783 /* allocate a channel */
6784 struct ast_channel
*chan
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, "", "", "", 0, 0);
6787 return -1; /* failure */
6790 /* allocation of the cdr failed */
6791 ast_channel_free(chan
); /* free the channel */
6792 return -1; /* return failure */
6795 /* allocation of the cdr was successful */
6796 ast_cdr_init(chan
->cdr
, chan
); /* initialize our channel's cdr */
6797 ast_cdr_start(chan
->cdr
); /* record the start and stop time */
6798 ast_cdr_end(chan
->cdr
);
6799 ast_cdr_failed(chan
->cdr
); /* set the status to failed */
6800 ast_cdr_detach(chan
->cdr
); /* post and free the record */
6801 ast_channel_free(chan
); /* free the channel */
6803 return 0; /* success */
6806 int ast_pbx_outgoing_exten(const char *type
, int format
, void *data
, int timeout
, const char *context
, const char *exten
, int priority
, int *reason
, int sync
, const char *cid_num
, const char *cid_name
, struct ast_variable
*vars
, const char *account
, struct ast_channel
**channel
)
6808 struct ast_channel
*chan
;
6809 struct async_stat
*as
;
6810 int res
= -1, cdr_res
= -1;
6811 struct outgoing_helper oh
;
6814 oh
.context
= context
;
6816 oh
.priority
= priority
;
6817 oh
.cid_num
= cid_num
;
6818 oh
.cid_name
= cid_name
;
6819 oh
.account
= account
;
6821 oh
.parent_channel
= NULL
;
6823 chan
= __ast_request_and_dial(type
, format
, data
, timeout
, reason
, cid_num
, cid_name
, &oh
);
6827 ast_channel_lock(chan
);
6830 if (chan
->_state
== AST_STATE_UP
) {
6832 ast_verb(4, "Channel %s was answered.\n", chan
->name
);
6836 ast_channel_unlock(chan
);
6837 if (ast_pbx_run(chan
)) {
6838 ast_log(LOG_ERROR
, "Unable to run PBX on %s\n", chan
->name
);
6846 if (ast_pbx_start(chan
)) {
6847 ast_log(LOG_ERROR
, "Unable to start PBX on %s\n", chan
->name
);
6850 ast_channel_unlock(chan
);
6858 ast_verb(4, "Channel %s was never answered.\n", chan
->name
);
6860 if (chan
->cdr
) { /* update the cdr */
6861 /* here we update the status of the call, which sould be busy.
6862 * if that fails then we set the status to failed */
6863 if (ast_cdr_disposition(chan
->cdr
, chan
->hangupcause
))
6864 ast_cdr_failed(chan
->cdr
);
6869 ast_channel_unlock(chan
);
6876 if (res
< 0) { /* the call failed for some reason */
6877 if (*reason
== 0) { /* if the call failed (not busy or no answer)
6878 * update the cdr with the failed message */
6879 cdr_res
= ast_pbx_outgoing_cdr_failed();
6882 goto outgoing_exten_cleanup
;
6886 /* create a fake channel and execute the "failed" extension (if it exists) within the requested context */
6887 /* check if "failed" exists */
6888 if (ast_exists_extension(chan
, context
, "failed", 1, NULL
)) {
6889 chan
= ast_channel_alloc(0, AST_STATE_DOWN
, 0, 0, "", "", "", 0, "OutgoingSpoolFailed");
6891 char failed_reason
[4] = "";
6892 if (!ast_strlen_zero(context
))
6893 ast_copy_string(chan
->context
, context
, sizeof(chan
->context
));
6894 set_ext_pri(chan
, "failed", 1);
6895 ast_set_variables(chan
, vars
);
6896 snprintf(failed_reason
, sizeof(failed_reason
), "%d", *reason
);
6897 pbx_builtin_setvar_helper(chan
, "REASON", failed_reason
);
6899 ast_cdr_setaccount(chan
, account
);
6900 if (ast_pbx_run(chan
)) {
6901 ast_log(LOG_ERROR
, "Unable to run PBX on %s\n", chan
->name
);
6909 if (!(as
= ast_calloc(1, sizeof(*as
)))) {
6911 goto outgoing_exten_cleanup
;
6913 chan
= ast_request_and_dial(type
, format
, data
, timeout
, reason
, cid_num
, cid_name
);
6917 ast_channel_lock(chan
);
6922 goto outgoing_exten_cleanup
;
6925 ast_copy_string(as
->context
, context
, sizeof(as
->context
));
6926 set_ext_pri(as
->chan
, exten
, priority
);
6927 as
->timeout
= timeout
;
6928 ast_set_variables(chan
, vars
);
6930 ast_cdr_setaccount(chan
, account
);
6931 if (ast_pthread_create_detached(&as
->p
, NULL
, async_wait
, as
)) {
6932 ast_log(LOG_WARNING
, "Failed to start async wait\n");
6936 ast_channel_unlock(chan
);
6940 goto outgoing_exten_cleanup
;
6944 outgoing_exten_cleanup
:
6945 ast_variables_destroy(vars
);
6952 struct ast_channel
*chan
;
6956 /*! \brief run the application and free the descriptor once done */
6957 static void *ast_pbx_run_app(void *data
)
6959 struct app_tmp
*tmp
= data
;
6960 struct ast_app
*app
;
6961 app
= pbx_findapp(tmp
->app
);
6963 ast_verb(4, "Launching %s(%s) on %s\n", tmp
->app
, tmp
->data
, tmp
->chan
->name
);
6964 pbx_exec(tmp
->chan
, app
, tmp
->data
);
6966 ast_log(LOG_WARNING
, "No such application '%s'\n", tmp
->app
);
6967 ast_hangup(tmp
->chan
);
6972 int ast_pbx_outgoing_app(const char *type
, int format
, void *data
, int timeout
, const char *app
, const char *appdata
, int *reason
, int sync
, const char *cid_num
, const char *cid_name
, struct ast_variable
*vars
, const char *account
, struct ast_channel
**locked_channel
)
6974 struct ast_channel
*chan
;
6975 struct app_tmp
*tmp
;
6976 int res
= -1, cdr_res
= -1;
6977 struct outgoing_helper oh
;
6979 memset(&oh
, 0, sizeof(oh
));
6981 oh
.account
= account
;
6984 *locked_channel
= NULL
;
6985 if (ast_strlen_zero(app
)) {
6987 goto outgoing_app_cleanup
;
6990 chan
= __ast_request_and_dial(type
, format
, data
, timeout
, reason
, cid_num
, cid_name
, &oh
);
6992 if (!chan
->cdr
) { /* check if the channel already has a cdr record, if not give it one */
6993 chan
->cdr
= ast_cdr_alloc(); /* allocate a cdr for the channel */
6995 /* allocation of the cdr failed */
6996 ast_free(chan
->pbx
);
6998 goto outgoing_app_cleanup
;
7000 /* allocation of the cdr was successful */
7001 ast_cdr_init(chan
->cdr
, chan
); /* initialize our channel's cdr */
7002 ast_cdr_start(chan
->cdr
);
7004 ast_set_variables(chan
, vars
);
7006 ast_cdr_setaccount(chan
, account
);
7007 if (chan
->_state
== AST_STATE_UP
) {
7009 ast_verb(4, "Channel %s was answered.\n", chan
->name
);
7010 tmp
= ast_calloc(1, sizeof(*tmp
));
7014 ast_copy_string(tmp
->app
, app
, sizeof(tmp
->app
));
7016 ast_copy_string(tmp
->data
, appdata
, sizeof(tmp
->data
));
7020 ast_channel_unlock(chan
);
7021 ast_pbx_run_app(tmp
);
7024 ast_channel_lock(chan
);
7025 if (ast_pthread_create_detached(&tmp
->t
, NULL
, ast_pbx_run_app
, tmp
)) {
7026 ast_log(LOG_WARNING
, "Unable to spawn execute thread on %s: %s\n", chan
->name
, strerror(errno
));
7029 ast_channel_unlock(chan
);
7034 *locked_channel
= chan
;
7039 ast_verb(4, "Channel %s was never answered.\n", chan
->name
);
7040 if (chan
->cdr
) { /* update the cdr */
7041 /* here we update the status of the call, which sould be busy.
7042 * if that fails then we set the status to failed */
7043 if (ast_cdr_disposition(chan
->cdr
, chan
->hangupcause
))
7044 ast_cdr_failed(chan
->cdr
);
7050 if (res
< 0) { /* the call failed for some reason */
7051 if (*reason
== 0) { /* if the call failed (not busy or no answer)
7052 * update the cdr with the failed message */
7053 cdr_res
= ast_pbx_outgoing_cdr_failed();
7056 goto outgoing_app_cleanup
;
7062 struct async_stat
*as
;
7063 if (!(as
= ast_calloc(1, sizeof(*as
)))) {
7065 goto outgoing_app_cleanup
;
7067 chan
= __ast_request_and_dial(type
, format
, data
, timeout
, reason
, cid_num
, cid_name
, &oh
);
7071 goto outgoing_app_cleanup
;
7074 ast_copy_string(as
->app
, app
, sizeof(as
->app
));
7076 ast_copy_string(as
->appdata
, appdata
, sizeof(as
->appdata
));
7077 as
->timeout
= timeout
;
7078 ast_set_variables(chan
, vars
);
7080 ast_cdr_setaccount(chan
, account
);
7081 /* Start a new thread, and get something handling this channel. */
7083 ast_channel_lock(chan
);
7084 if (ast_pthread_create_detached(&as
->p
, NULL
, async_wait
, as
)) {
7085 ast_log(LOG_WARNING
, "Failed to start async wait\n");
7088 ast_channel_unlock(chan
);
7091 goto outgoing_app_cleanup
;
7094 *locked_channel
= chan
;
7098 outgoing_app_cleanup
:
7099 ast_variables_destroy(vars
);
7103 /* this is the guts of destroying a context --
7104 freeing up the structure, traversing and destroying the
7105 extensions, switches, ignorepats, includes, etc. etc. */
7107 static void __ast_internal_context_destroy( struct ast_context
*con
)
7109 struct ast_include
*tmpi
;
7111 struct ast_exten
*e
, *el
, *en
;
7112 struct ast_ignorepat
*ipi
;
7113 struct ast_context
*tmp
= con
;
7115 for (tmpi
= tmp
->includes
; tmpi
; ) { /* Free includes */
7116 struct ast_include
*tmpil
= tmpi
;
7120 for (ipi
= tmp
->ignorepats
; ipi
; ) { /* Free ignorepats */
7121 struct ast_ignorepat
*ipl
= ipi
;
7125 /* destroy the hash tabs */
7126 if (tmp
->root_table
) {
7127 ast_hashtab_destroy(tmp
->root_table
, 0);
7129 /* and destroy the pattern tree */
7130 if (tmp
->pattern_tree
)
7131 destroy_pattern_tree(tmp
->pattern_tree
);
7133 while ((sw
= AST_LIST_REMOVE_HEAD(&tmp
->alts
, list
)))
7135 for (e
= tmp
->root
; e
;) {
7136 for (en
= e
->peer
; en
;) {
7146 ast_rwlock_destroy(&tmp
->lock
);
7151 void __ast_context_destroy(struct ast_context
*list
, struct ast_hashtab
*contexttab
, struct ast_context
*con
, const char *registrar
)
7153 struct ast_context
*tmp
, *tmpl
=NULL
;
7154 struct ast_exten
*exten_item
, *prio_item
;
7156 for (tmp
= list
; tmp
; ) {
7157 struct ast_context
*next
= NULL
; /* next starting point */
7158 for (; tmp
; tmpl
= tmp
, tmp
= tmp
->next
) {
7159 ast_debug(1, "check ctx %s %s\n", tmp
->name
, tmp
->registrar
);
7160 if ( (registrar
&& !strcasecmp(tmp
->registrar
, registrar
)) || (con
&& !strcasecmp(tmp
->name
, con
->name
)) ) {
7161 break; /* found it */
7164 if (!tmp
) /* not found, we are done */
7166 ast_wrlock_context(tmp
);
7169 /* then search thru and remove any extens that match registrar. */
7170 struct ast_hashtab_iter
*exten_iter
;
7171 struct ast_hashtab_iter
*prio_iter
;
7173 if (tmp
->root_table
) { /* it is entirely possible that the context is EMPTY */
7174 exten_iter
= ast_hashtab_start_traversal(tmp
->root_table
);
7175 while ((exten_item
=ast_hashtab_next(exten_iter
))) {
7176 prio_iter
= ast_hashtab_start_traversal(exten_item
->peer_table
);
7177 while ((prio_item
=ast_hashtab_next(prio_iter
))) {
7178 if (strcmp(prio_item
->registrar
, registrar
) != 0) {
7181 ast_verb(3, "Remove %s/%s/%d, registrar=%s; con=%s(%p); con->root=%p\n",
7182 tmp
->name
, prio_item
->exten
, prio_item
->priority
, registrar
, con
? con
->name
: "<nil>", con
, con
? con
->root_table
: NULL
);
7184 ast_context_remove_extension2(tmp
, prio_item
->exten
, prio_item
->priority
, registrar
, 1);
7186 ast_hashtab_end_traversal(prio_iter
);
7188 ast_hashtab_end_traversal(exten_iter
);
7191 /* delete the context if it's registrar matches, is empty, has refcount of 1, */
7192 if (strcmp(tmp
->registrar
, registrar
) == 0 && tmp
->refcount
< 2 && !tmp
->root
) {
7193 ast_debug(1, "delete ctx %s %s\n", tmp
->name
, tmp
->registrar
);
7194 ast_hashtab_remove_this_object(contexttab
, tmp
);
7201 /* Okay, now we're safe to let it go -- in a sense, we were
7202 ready to let it go as soon as we locked it. */
7203 ast_unlock_context(tmp
);
7204 __ast_internal_context_destroy(tmp
);
7206 ast_unlock_context(tmp
);
7209 ast_verb(3, "Deleting context %s registrar=%s\n", tmp
->name
, tmp
->registrar
);
7210 ast_debug(1, "delete ctx %s %s\n", tmp
->name
, tmp
->registrar
);
7211 ast_hashtab_remove_this_object(contexttab
, tmp
);
7218 /* Okay, now we're safe to let it go -- in a sense, we were
7219 ready to let it go as soon as we locked it. */
7220 ast_unlock_context(tmp
);
7221 __ast_internal_context_destroy(tmp
);
7224 /* if we have a specific match, we are done, otherwise continue */
7225 tmp
= con
? NULL
: next
;
7229 void ast_context_destroy(struct ast_context
*con
, const char *registrar
)
7231 ast_wrlock_contexts();
7232 __ast_context_destroy(contexts
, contexts_table
, con
,registrar
);
7233 ast_unlock_contexts();
7236 static void wait_for_hangup(struct ast_channel
*chan
, void *data
)
7239 struct ast_frame
*f
;
7243 if (ast_strlen_zero(data
) || (sscanf(data
, "%lg", &waitsec
) != 1) || (waitsec
< 0))
7246 waittime
= waitsec
* 1000.0;
7247 ast_safe_sleep(chan
, waittime
);
7249 res
= ast_waitfor(chan
, -1);
7259 * \ingroup applications
7261 static int pbx_builtin_progress(struct ast_channel
*chan
, void *data
)
7263 ast_indicate(chan
, AST_CONTROL_PROGRESS
);
7268 * \ingroup applications
7270 static int pbx_builtin_ringing(struct ast_channel
*chan
, void *data
)
7272 ast_indicate(chan
, AST_CONTROL_RINGING
);
7277 * \ingroup applications
7279 static int pbx_builtin_busy(struct ast_channel
*chan
, void *data
)
7281 ast_indicate(chan
, AST_CONTROL_BUSY
);
7282 /* Don't change state of an UP channel, just indicate
7284 if (chan
->_state
!= AST_STATE_UP
)
7285 ast_setstate(chan
, AST_STATE_BUSY
);
7286 wait_for_hangup(chan
, data
);
7291 * \ingroup applications
7293 static int pbx_builtin_congestion(struct ast_channel
*chan
, void *data
)
7295 ast_indicate(chan
, AST_CONTROL_CONGESTION
);
7296 /* Don't change state of an UP channel, just indicate
7297 congestion in audio */
7298 if (chan
->_state
!= AST_STATE_UP
)
7299 ast_setstate(chan
, AST_STATE_BUSY
);
7300 wait_for_hangup(chan
, data
);
7305 * \ingroup applications
7307 static int pbx_builtin_answer(struct ast_channel
*chan
, void *data
)
7311 if ((chan
->_state
!= AST_STATE_UP
) && !ast_strlen_zero(data
))
7314 return __ast_answer(chan
, delay
);
7317 static int pbx_builtin_keepalive(struct ast_channel
*chan
, void *data
)
7319 return AST_PBX_KEEPALIVE
;
7322 static int pbx_builtin_incomplete(struct ast_channel
*chan
, void *data
)
7324 char *options
= data
;
7327 /* Some channels can receive DTMF in unanswered state; some cannot */
7328 if (!ast_strlen_zero(options
) && strchr(options
, 'n')) {
7332 /* If the channel is hungup, stop waiting */
7333 if (ast_check_hangup(chan
)) {
7335 } else if (chan
->_state
!= AST_STATE_UP
&& answer
) {
7336 __ast_answer(chan
, 0);
7339 return AST_PBX_INCOMPLETE
;
7342 AST_APP_OPTIONS(resetcdr_opts
, {
7343 AST_APP_OPTION('w', AST_CDR_FLAG_POSTED
),
7344 AST_APP_OPTION('a', AST_CDR_FLAG_LOCKED
),
7345 AST_APP_OPTION('v', AST_CDR_FLAG_KEEP_VARS
),
7346 AST_APP_OPTION('e', AST_CDR_FLAG_POST_ENABLE
),
7350 * \ingroup applications
7352 static int pbx_builtin_resetcdr(struct ast_channel
*chan
, void *data
)
7355 struct ast_flags flags
= { 0 };
7357 if (!ast_strlen_zero(data
)) {
7358 args
= ast_strdupa(data
);
7359 ast_app_parse_options(resetcdr_opts
, &flags
, NULL
, args
);
7362 ast_cdr_reset(chan
->cdr
, &flags
);
7368 * \ingroup applications
7370 static int pbx_builtin_setamaflags(struct ast_channel
*chan
, void *data
)
7372 /* Copy the AMA Flags as specified */
7373 ast_cdr_setamaflags(chan
, data
? data
: "");
7378 * \ingroup applications
7380 static int pbx_builtin_hangup(struct ast_channel
*chan
, void *data
)
7382 if (!ast_strlen_zero(data
)) {
7386 if ((cause
= ast_str2cause(data
)) > -1) {
7387 chan
->hangupcause
= cause
;
7391 cause
= strtol((const char *) data
, &endptr
, 10);
7392 if (cause
!= 0 || (data
!= endptr
)) {
7393 chan
->hangupcause
= cause
;
7397 ast_log(LOG_WARNING
, "Invalid cause given to Hangup(): \"%s\"\n", (char *) data
);
7400 if (!chan
->hangupcause
) {
7401 chan
->hangupcause
= AST_CAUSE_NORMAL_CLEARING
;
7408 * \ingroup applications
7410 static int pbx_builtin_gotoiftime(struct ast_channel
*chan
, void *data
)
7412 char *s
, *ts
, *branch1
, *branch2
, *branch
;
7413 struct ast_timing timing
;
7415 if (ast_strlen_zero(data
)) {
7416 ast_log(LOG_WARNING
, "GotoIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>?'labeliftrue':'labeliffalse'\n");
7420 ts
= s
= ast_strdupa(data
);
7422 /* Separate the Goto path */
7424 branch1
= strsep(&ts
,":");
7425 branch2
= strsep(&ts
,"");
7427 /* struct ast_include include contained garbage here, fixed by zeroing it on get_timerange */
7428 if (ast_build_timing(&timing
, s
) && ast_check_timing(&timing
))
7433 if (ast_strlen_zero(branch
)) {
7434 ast_debug(1, "Not taking any branch\n");
7438 return pbx_builtin_goto(chan
, branch
);
7442 * \ingroup applications
7444 static int pbx_builtin_execiftime(struct ast_channel
*chan
, void *data
)
7447 struct ast_timing timing
;
7448 struct ast_app
*app
;
7449 static const char *usage
= "ExecIfTime requires an argument:\n <time range>,<days of week>,<days of month>,<months>?<appname>[(<appargs>)]";
7451 if (ast_strlen_zero(data
)) {
7452 ast_log(LOG_WARNING
, "%s\n", usage
);
7456 appname
= ast_strdupa(data
);
7458 s
= strsep(&appname
, "?"); /* Separate the timerange and application name/data */
7459 if (!appname
) { /* missing application */
7460 ast_log(LOG_WARNING
, "%s\n", usage
);
7464 if (!ast_build_timing(&timing
, s
)) {
7465 ast_log(LOG_WARNING
, "Invalid Time Spec: %s\nCorrect usage: %s\n", s
, usage
);
7469 if (!ast_check_timing(&timing
)) /* outside the valid time window, just return */
7472 /* now split appname(appargs) */
7473 if ((s
= strchr(appname
, '('))) {
7476 if ((e
= strrchr(s
, ')')))
7479 ast_log(LOG_WARNING
, "Failed to find closing parenthesis\n");
7483 if ((app
= pbx_findapp(appname
))) {
7484 return pbx_exec(chan
, app
, S_OR(s
, ""));
7486 ast_log(LOG_WARNING
, "Cannot locate application %s\n", appname
);
7492 * \ingroup applications
7494 static int pbx_builtin_wait(struct ast_channel
*chan
, void *data
)
7499 /* Wait for "n" seconds */
7500 if (data
&& (s
= atof(data
)) > 0.0) {
7502 return ast_safe_sleep(chan
, ms
);
7508 * \ingroup applications
7510 static int pbx_builtin_waitexten(struct ast_channel
*chan
, void *data
)
7514 struct ast_flags flags
= {0};
7515 char *opts
[1] = { NULL
};
7517 AST_DECLARE_APP_ARGS(args
,
7518 AST_APP_ARG(timeout
);
7519 AST_APP_ARG(options
);
7522 if (!ast_strlen_zero(data
)) {
7523 parse
= ast_strdupa(data
);
7524 AST_STANDARD_APP_ARGS(args
, parse
);
7526 memset(&args
, 0, sizeof(args
));
7529 ast_app_parse_options(waitexten_opts
, &flags
, opts
, args
.options
);
7531 if (ast_test_flag(&flags
, WAITEXTEN_MOH
) && !opts
[0] ) {
7532 ast_log(LOG_WARNING
, "The 'm' option has been specified for WaitExten without a class.\n");
7533 } else if (ast_test_flag(&flags
, WAITEXTEN_MOH
)) {
7534 ast_indicate_data(chan
, AST_CONTROL_HOLD
, opts
[0], strlen(opts
[0]));
7535 } else if (ast_test_flag(&flags
, WAITEXTEN_DIALTONE
)) {
7536 const struct ind_tone_zone_sound
*ts
= ast_get_indication_tone(chan
->zone
, "dial");
7538 ast_playtones_start(chan
, 0, ts
->data
, 0);
7540 ast_tonepair_start(chan
, 350, 440, 0, 0);
7542 /* Wait for "n" seconds */
7543 if (args
.timeout
&& (s
= atof(args
.timeout
)) > 0)
7546 ms
= chan
->pbx
->rtimeoutms
;
7550 res
= ast_waitfordigit(chan
, ms
);
7552 if (ast_exists_extension(chan
, chan
->context
, chan
->exten
, chan
->priority
+ 1, chan
->cid
.cid_num
)) {
7553 ast_verb(3, "Timeout on %s, continuing...\n", chan
->name
);
7554 } else if (chan
->_softhangup
== AST_SOFTHANGUP_TIMEOUT
) {
7555 ast_verb(3, "Call timeout on %s, checking for 'T'\n", chan
->name
);
7557 } else if (ast_exists_extension(chan
, chan
->context
, "t", 1, chan
->cid
.cid_num
)) {
7558 ast_verb(3, "Timeout on %s, going to 't'\n", chan
->name
);
7559 set_ext_pri(chan
, "t", 0); /* 0 will become 1, next time through the loop */
7561 ast_log(LOG_WARNING
, "Timeout but no rule 't' in context '%s'\n", chan
->context
);
7566 if (ast_test_flag(&flags
, WAITEXTEN_MOH
))
7567 ast_indicate(chan
, AST_CONTROL_UNHOLD
);
7568 else if (ast_test_flag(&flags
, WAITEXTEN_DIALTONE
))
7569 ast_playtones_stop(chan
);
7575 * \ingroup applications
7577 static int pbx_builtin_background(struct ast_channel
*chan
, void *data
)
7581 struct ast_flags flags
= {0};
7583 AST_DECLARE_APP_ARGS(args
,
7584 AST_APP_ARG(filename
);
7585 AST_APP_ARG(options
);
7587 AST_APP_ARG(context
);
7590 if (ast_strlen_zero(data
)) {
7591 ast_log(LOG_WARNING
, "Background requires an argument (filename)\n");
7595 parse
= ast_strdupa(data
);
7597 AST_STANDARD_APP_ARGS(args
, parse
);
7599 if (ast_strlen_zero(args
.lang
))
7600 args
.lang
= (char *)chan
->language
; /* XXX this is const */
7602 if (ast_strlen_zero(args
.context
))
7603 args
.context
= chan
->context
;
7606 if (!strcasecmp(args
.options
, "skip"))
7607 flags
.flags
= BACKGROUND_SKIP
;
7608 else if (!strcasecmp(args
.options
, "noanswer"))
7609 flags
.flags
= BACKGROUND_NOANSWER
;
7611 ast_app_parse_options(background_opts
, &flags
, NULL
, args
.options
);
7614 /* Answer if need be */
7615 if (chan
->_state
!= AST_STATE_UP
) {
7616 if (ast_test_flag(&flags
, BACKGROUND_SKIP
)) {
7618 } else if (!ast_test_flag(&flags
, BACKGROUND_NOANSWER
)) {
7619 res
= ast_answer(chan
);
7624 char *back
= args
.filename
;
7627 ast_stopstream(chan
); /* Stop anything playing */
7628 /* Stream the list of files */
7629 while (!res
&& (front
= strsep(&back
, "&")) ) {
7630 if ( (res
= ast_streamfile(chan
, front
, args
.lang
)) ) {
7631 ast_log(LOG_WARNING
, "ast_streamfile failed on %s for %s\n", chan
->name
, (char*)data
);
7636 if (ast_test_flag(&flags
, BACKGROUND_PLAYBACK
)) {
7637 res
= ast_waitstream(chan
, "");
7638 } else if (ast_test_flag(&flags
, BACKGROUND_MATCHEXTEN
)) {
7639 res
= ast_waitstream_exten(chan
, args
.context
);
7641 res
= ast_waitstream(chan
, AST_DIGIT_ANY
);
7643 ast_stopstream(chan
);
7646 if (args
.context
!= chan
->context
&& res
) {
7647 snprintf(chan
->exten
, sizeof(chan
->exten
), "%c", res
);
7648 ast_copy_string(chan
->context
, args
.context
, sizeof(chan
->context
));
7653 pbx_builtin_setvar_helper(chan
, "BACKGROUNDSTATUS", mres
? "FAILED" : "SUCCESS");
7658 * \ingroup applications
7660 static int pbx_builtin_goto(struct ast_channel
*chan
, void *data
)
7662 int res
= ast_parseable_goto(chan
, data
);
7664 ast_verb(3, "Goto (%s,%s,%d)\n", chan
->context
, chan
->exten
, chan
->priority
+ 1);
7669 int pbx_builtin_serialize_variables(struct ast_channel
*chan
, struct ast_str
**buf
)
7671 struct ast_var_t
*variables
;
7672 const char *var
, *val
;
7679 (*buf
)->str
[0] = '\0';
7681 ast_channel_lock(chan
);
7683 AST_LIST_TRAVERSE(&chan
->varshead
, variables
, entries
) {
7684 if ((var
= ast_var_name(variables
)) && (val
= ast_var_value(variables
))
7685 /* && !ast_strlen_zero(var) && !ast_strlen_zero(val) */
7687 if (ast_str_append(buf
, 0, "%s=%s\n", var
, val
) < 0) {
7688 ast_log(LOG_ERROR
, "Data Buffer Size Exceeded!\n");
7696 ast_channel_unlock(chan
);
7701 const char *pbx_builtin_getvar_helper(struct ast_channel
*chan
, const char *name
)
7703 struct ast_var_t
*variables
;
7704 const char *ret
= NULL
;
7706 struct varshead
*places
[2] = { NULL
, &globals
};
7712 ast_channel_lock(chan
);
7713 places
[0] = &chan
->varshead
;
7716 for (i
= 0; i
< 2; i
++) {
7719 if (places
[i
] == &globals
)
7720 ast_rwlock_rdlock(&globalslock
);
7721 AST_LIST_TRAVERSE(places
[i
], variables
, entries
) {
7722 if (!strcmp(name
, ast_var_name(variables
))) {
7723 ret
= ast_var_value(variables
);
7727 if (places
[i
] == &globals
)
7728 ast_rwlock_unlock(&globalslock
);
7734 ast_channel_unlock(chan
);
7739 void pbx_builtin_pushvar_helper(struct ast_channel
*chan
, const char *name
, const char *value
)
7741 struct ast_var_t
*newvariable
;
7742 struct varshead
*headp
;
7744 if (name
[strlen(name
)-1] == ')') {
7745 char *function
= ast_strdupa(name
);
7747 ast_log(LOG_WARNING
, "Cannot push a value onto a function\n");
7748 ast_func_write(chan
, function
, value
);
7753 ast_channel_lock(chan
);
7754 headp
= &chan
->varshead
;
7756 ast_rwlock_wrlock(&globalslock
);
7761 if (headp
== &globals
)
7762 ast_verb(2, "Setting global variable '%s' to '%s'\n", name
, value
);
7763 newvariable
= ast_var_assign(name
, value
);
7764 AST_LIST_INSERT_HEAD(headp
, newvariable
, entries
);
7768 ast_channel_unlock(chan
);
7770 ast_rwlock_unlock(&globalslock
);
7773 void pbx_builtin_setvar_helper(struct ast_channel
*chan
, const char *name
, const char *value
)
7775 struct ast_var_t
*newvariable
;
7776 struct varshead
*headp
;
7777 const char *nametail
= name
;
7779 if (name
[strlen(name
) - 1] == ')') {
7780 char *function
= ast_strdupa(name
);
7782 ast_func_write(chan
, function
, value
);
7787 ast_channel_lock(chan
);
7788 headp
= &chan
->varshead
;
7790 ast_rwlock_wrlock(&globalslock
);
7794 /* For comparison purposes, we have to strip leading underscores */
7795 if (*nametail
== '_') {
7797 if (*nametail
== '_')
7801 AST_LIST_TRAVERSE (headp
, newvariable
, entries
) {
7802 if (strcasecmp(ast_var_name(newvariable
), nametail
) == 0) {
7803 /* there is already such a variable, delete it */
7804 AST_LIST_REMOVE(headp
, newvariable
, entries
);
7805 ast_var_delete(newvariable
);
7811 if (headp
== &globals
)
7812 ast_verb(2, "Setting global variable '%s' to '%s'\n", name
, value
);
7813 newvariable
= ast_var_assign(name
, value
);
7814 AST_LIST_INSERT_HEAD(headp
, newvariable
, entries
);
7815 manager_event(EVENT_FLAG_DIALPLAN
, "VarSet",
7820 chan
? chan
->name
: "none", name
, value
,
7821 chan
? chan
->uniqueid
: "none");
7825 ast_channel_unlock(chan
);
7827 ast_rwlock_unlock(&globalslock
);
7830 int pbx_builtin_setvar(struct ast_channel
*chan
, void *data
)
7832 char *name
, *value
, *mydata
;
7834 if (ast_compat_app_set
) {
7835 return pbx_builtin_setvar_multiple(chan
, data
);
7838 if (ast_strlen_zero(data
)) {
7839 ast_log(LOG_WARNING
, "Set requires one variable name/value pair.\n");
7843 mydata
= ast_strdupa(data
);
7844 name
= strsep(&mydata
, "=");
7846 if (strchr(name
, ' '))
7847 ast_log(LOG_WARNING
, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", name
, mydata
);
7849 pbx_builtin_setvar_helper(chan
, name
, value
);
7853 int pbx_builtin_setvar_multiple(struct ast_channel
*chan
, void *vdata
)
7857 AST_DECLARE_APP_ARGS(args
,
7858 AST_APP_ARG(pair
)[24];
7860 AST_DECLARE_APP_ARGS(pair
,
7865 if (ast_strlen_zero(vdata
)) {
7866 ast_log(LOG_WARNING
, "MSet requires at least one variable name/value pair.\n");
7870 data
= ast_strdupa(vdata
);
7871 AST_STANDARD_APP_ARGS(args
, data
);
7873 for (x
= 0; x
< args
.argc
; x
++) {
7874 AST_NONSTANDARD_APP_ARGS(pair
, args
.pair
[x
], '=');
7875 if (pair
.argc
== 2) {
7876 pbx_builtin_setvar_helper(chan
, pair
.name
, pair
.value
);
7877 if (strchr(pair
.name
, ' '))
7878 ast_log(LOG_WARNING
, "Please avoid unnecessary spaces on variables as it may lead to unexpected results ('%s' set to '%s').\n", pair
.name
, pair
.value
);
7880 ast_log(LOG_WARNING
, "MSet: ignoring entry '%s' with no '='\n", pair
.name
);
7882 ast_log(LOG_WARNING
, "MSet: ignoring entry '%s' with no '=' (in %s@%s:%d\n", pair
.name
, chan
->exten
, chan
->context
, chan
->priority
);
7889 int pbx_builtin_importvar(struct ast_channel
*chan
, void *data
)
7894 char tmp
[VAR_BUF_SIZE
];
7895 static int deprecation_warning
= 0;
7897 if (ast_strlen_zero(data
)) {
7898 ast_log(LOG_WARNING
, "Ignoring, since there is no variable to set\n");
7902 if (!deprecation_warning
) {
7903 ast_log(LOG_WARNING
, "ImportVar is deprecated. Please use Set(varname=${IMPORT(channel,variable)}) instead.\n");
7904 deprecation_warning
= 1;
7907 value
= ast_strdupa(data
);
7908 name
= strsep(&value
,"=");
7909 channel
= strsep(&value
,",");
7910 if (channel
&& value
&& name
) { /*! \todo XXX should do !ast_strlen_zero(..) of the args ? */
7911 struct ast_channel
*chan2
= ast_get_channel_by_name_locked(channel
);
7913 char *s
= alloca(strlen(value
) + 4);
7915 sprintf(s
, "${%s}", value
);
7916 pbx_substitute_variables_helper(chan2
, s
, tmp
, sizeof(tmp
) - 1);
7918 ast_channel_unlock(chan2
);
7920 pbx_builtin_setvar_helper(chan
, name
, tmp
);
7926 static int pbx_builtin_noop(struct ast_channel
*chan
, void *data
)
7931 void pbx_builtin_clear_globals(void)
7933 struct ast_var_t
*vardata
;
7935 ast_rwlock_wrlock(&globalslock
);
7936 while ((vardata
= AST_LIST_REMOVE_HEAD(&globals
, entries
)))
7937 ast_var_delete(vardata
);
7938 ast_rwlock_unlock(&globalslock
);
7941 int pbx_checkcondition(const char *condition
)
7944 if (ast_strlen_zero(condition
)) { /* NULL or empty strings are false */
7946 } else if (sscanf(condition
, "%d", &res
) == 1) { /* Numbers are evaluated for truth */
7948 } else { /* Strings are true */
7953 static int pbx_builtin_gotoif(struct ast_channel
*chan
, void *data
)
7955 char *condition
, *branch1
, *branch2
, *branch
;
7958 if (ast_strlen_zero(data
)) {
7959 ast_log(LOG_WARNING
, "Ignoring, since there is no variable to check\n");
7963 stringp
= ast_strdupa(data
);
7964 condition
= strsep(&stringp
,"?");
7965 branch1
= strsep(&stringp
,":");
7966 branch2
= strsep(&stringp
,"");
7967 branch
= pbx_checkcondition(condition
) ? branch1
: branch2
;
7969 if (ast_strlen_zero(branch
)) {
7970 ast_debug(1, "Not taking any branch\n");
7974 return pbx_builtin_goto(chan
, branch
);
7977 static int pbx_builtin_saynumber(struct ast_channel
*chan
, void *data
)
7983 if (ast_strlen_zero(data
)) {
7984 ast_log(LOG_WARNING
, "SayNumber requires an argument (number)\n");
7987 ast_copy_string(tmp
, data
, sizeof(tmp
));
7988 strsep(&number
, ",");
7989 options
= strsep(&number
, ",");
7991 if ( strcasecmp(options
, "f") && strcasecmp(options
, "m") &&
7992 strcasecmp(options
, "c") && strcasecmp(options
, "n") ) {
7993 ast_log(LOG_WARNING
, "SayNumber gender option is either 'f', 'm', 'c' or 'n'\n");
7998 if (ast_say_number(chan
, atoi(tmp
), "", chan
->language
, options
)) {
7999 ast_log(LOG_WARNING
, "We were unable to say the number %s, is it too large?\n", tmp
);
8005 static int pbx_builtin_saydigits(struct ast_channel
*chan
, void *data
)
8010 res
= ast_say_digit_str(chan
, data
, "", chan
->language
);
8014 static int pbx_builtin_saycharacters(struct ast_channel
*chan
, void *data
)
8019 res
= ast_say_character_str(chan
, data
, "", chan
->language
);
8023 static int pbx_builtin_sayphonetic(struct ast_channel
*chan
, void *data
)
8028 res
= ast_say_phonetic_str(chan
, data
, "", chan
->language
);
8032 static void device_state_cb(const struct ast_event
*event
, void *unused
)
8035 struct statechange
*sc
;
8037 device
= ast_event_get_ie_str(event
, AST_EVENT_IE_DEVICE
);
8038 if (ast_strlen_zero(device
)) {
8039 ast_log(LOG_ERROR
, "Received invalid event that had no device IE\n");
8043 if (!(sc
= ast_calloc(1, sizeof(*sc
) + strlen(device
) + 1)))
8045 strcpy(sc
->dev
, device
);
8046 if (ast_taskprocessor_push(device_state_tps
, handle_statechange
, sc
) < 0) {
8055 /* Initialize the PBX */
8056 ast_verb(1, "Asterisk PBX Core Initializing\n");
8057 if (!(device_state_tps
= ast_taskprocessor_get("pbx-core", 0))) {
8058 ast_log(LOG_WARNING
, "failed to create pbx-core taskprocessor\n");
8061 ast_verb(1, "Registering builtin applications:\n");
8062 ast_cli_register_multiple(pbx_cli
, sizeof(pbx_cli
) / sizeof(struct ast_cli_entry
));
8063 __ast_custom_function_register(&exception_function
, NULL
);
8065 /* Register builtin applications */
8066 for (x
= 0; x
< sizeof(builtins
) / sizeof(struct pbx_builtin
); x
++) {
8067 ast_verb(1, "[%s]\n", builtins
[x
].name
);
8068 if (ast_register_application2(builtins
[x
].name
, builtins
[x
].execute
, builtins
[x
].synopsis
, builtins
[x
].description
, NULL
)) {
8069 ast_log(LOG_ERROR
, "Unable to register builtin application '%s'\n", builtins
[x
].name
);
8074 /* Register manager application */
8075 ast_manager_register2("ShowDialPlan", EVENT_FLAG_CONFIG
| EVENT_FLAG_REPORTING
, manager_show_dialplan
, "List dialplan", mandescr_show_dialplan
);
8077 if (!(device_state_sub
= ast_event_subscribe(AST_EVENT_DEVICE_STATE_CHANGE
, device_state_cb
, NULL
,
8078 AST_EVENT_IE_END
))) {
8084 static int conlock_wrlock_version
= 0;
8086 int ast_wrlock_contexts_version(void)
8088 return conlock_wrlock_version
;
8092 * Lock context list functions ...
8094 int ast_wrlock_contexts()
8096 int res
= ast_rwlock_wrlock(&conlock
);
8098 ast_atomic_fetchadd_int(&conlock_wrlock_version
, 1);
8102 int ast_rdlock_contexts()
8104 return ast_rwlock_rdlock(&conlock
);
8107 int ast_unlock_contexts()
8109 return ast_rwlock_unlock(&conlock
);
8115 int ast_wrlock_context(struct ast_context
*con
)
8117 return ast_rwlock_wrlock(&con
->lock
);
8120 int ast_rdlock_context(struct ast_context
*con
)
8122 return ast_rwlock_rdlock(&con
->lock
);
8125 int ast_unlock_context(struct ast_context
*con
)
8127 return ast_rwlock_unlock(&con
->lock
);
8131 * Name functions ...
8133 const char *ast_get_context_name(struct ast_context
*con
)
8135 return con
? con
->name
: NULL
;
8138 struct ast_context
*ast_get_extension_context(struct ast_exten
*exten
)
8140 return exten
? exten
->parent
: NULL
;
8143 const char *ast_get_extension_name(struct ast_exten
*exten
)
8145 return exten
? exten
->exten
: NULL
;
8148 const char *ast_get_extension_label(struct ast_exten
*exten
)
8150 return exten
? exten
->label
: NULL
;
8153 const char *ast_get_include_name(struct ast_include
*inc
)
8155 return inc
? inc
->name
: NULL
;
8158 const char *ast_get_ignorepat_name(struct ast_ignorepat
*ip
)
8160 return ip
? ip
->pattern
: NULL
;
8163 int ast_get_extension_priority(struct ast_exten
*exten
)
8165 return exten
? exten
->priority
: -1;
8169 * Registrar info functions ...
8171 const char *ast_get_context_registrar(struct ast_context
*c
)
8173 return c
? c
->registrar
: NULL
;
8176 const char *ast_get_extension_registrar(struct ast_exten
*e
)
8178 return e
? e
->registrar
: NULL
;
8181 const char *ast_get_include_registrar(struct ast_include
*i
)
8183 return i
? i
->registrar
: NULL
;
8186 const char *ast_get_ignorepat_registrar(struct ast_ignorepat
*ip
)
8188 return ip
? ip
->registrar
: NULL
;
8191 int ast_get_extension_matchcid(struct ast_exten
*e
)
8193 return e
? e
->matchcid
: 0;
8196 const char *ast_get_extension_cidmatch(struct ast_exten
*e
)
8198 return e
? e
->cidmatch
: NULL
;
8201 const char *ast_get_extension_app(struct ast_exten
*e
)
8203 return e
? e
->app
: NULL
;
8206 void *ast_get_extension_app_data(struct ast_exten
*e
)
8208 return e
? e
->data
: NULL
;
8211 const char *ast_get_switch_name(struct ast_sw
*sw
)
8213 return sw
? sw
->name
: NULL
;
8216 const char *ast_get_switch_data(struct ast_sw
*sw
)
8218 return sw
? sw
->data
: NULL
;
8221 int ast_get_switch_eval(struct ast_sw
*sw
)
8226 const char *ast_get_switch_registrar(struct ast_sw
*sw
)
8228 return sw
? sw
->registrar
: NULL
;
8232 * Walking functions ...
8234 struct ast_context
*ast_walk_contexts(struct ast_context
*con
)
8236 return con
? con
->next
: contexts
;
8239 struct ast_exten
*ast_walk_context_extensions(struct ast_context
*con
,
8240 struct ast_exten
*exten
)
8243 return con
? con
->root
: NULL
;
8248 struct ast_sw
*ast_walk_context_switches(struct ast_context
*con
,
8252 return con
? AST_LIST_FIRST(&con
->alts
) : NULL
;
8254 return AST_LIST_NEXT(sw
, list
);
8257 struct ast_exten
*ast_walk_extension_priorities(struct ast_exten
*exten
,
8258 struct ast_exten
*priority
)
8260 return priority
? priority
->peer
: exten
;
8263 struct ast_include
*ast_walk_context_includes(struct ast_context
*con
,
8264 struct ast_include
*inc
)
8267 return con
? con
->includes
: NULL
;
8272 struct ast_ignorepat
*ast_walk_context_ignorepats(struct ast_context
*con
,
8273 struct ast_ignorepat
*ip
)
8276 return con
? con
->ignorepats
: NULL
;
8281 int ast_context_verify_includes(struct ast_context
*con
)
8283 struct ast_include
*inc
= NULL
;
8286 while ( (inc
= ast_walk_context_includes(con
, inc
)) ) {
8287 if (ast_context_find(inc
->rname
))
8291 ast_log(LOG_WARNING
, "Context '%s' tries to include nonexistent context '%s'\n",
8292 ast_get_context_name(con
), inc
->rname
);
8300 static int __ast_goto_if_exists(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
, int async
)
8302 int (*goto_func
)(struct ast_channel
*chan
, const char *context
, const char *exten
, int priority
);
8307 if (context
== NULL
)
8308 context
= chan
->context
;
8310 exten
= chan
->exten
;
8312 goto_func
= (async
) ? ast_async_goto
: ast_explicit_goto
;
8313 if (ast_exists_extension(chan
, context
, exten
, priority
, chan
->cid
.cid_num
))
8314 return goto_func(chan
, context
, exten
, priority
);
8319 int ast_goto_if_exists(struct ast_channel
*chan
, const char* context
, const char *exten
, int priority
)
8321 return __ast_goto_if_exists(chan
, context
, exten
, priority
, 0);
8324 int ast_async_goto_if_exists(struct ast_channel
*chan
, const char * context
, const char *exten
, int priority
)
8326 return __ast_goto_if_exists(chan
, context
, exten
, priority
, 1);
8329 static int pbx_parseable_goto(struct ast_channel
*chan
, const char *goto_string
, int async
)
8331 char *exten
, *pri
, *context
;
8336 if (ast_strlen_zero(goto_string
)) {
8337 ast_log(LOG_WARNING
, "Goto requires an argument ([[context,]extension,]priority)\n");
8340 stringp
= ast_strdupa(goto_string
);
8341 context
= strsep(&stringp
, ","); /* guaranteed non-null */
8342 exten
= strsep(&stringp
, ",");
8343 pri
= strsep(&stringp
, ",");
8344 if (!exten
) { /* Only a priority in this one */
8348 } else if (!pri
) { /* Only an extension and priority in this one */
8356 } else if (*pri
== '-') {
8360 if (sscanf(pri
, "%d", &ipri
) != 1) {
8361 if ((ipri
= ast_findlabel_extension(chan
, context
? context
: chan
->context
, exten
? exten
: chan
->exten
,
8362 pri
, chan
->cid
.cid_num
)) < 1) {
8363 ast_log(LOG_WARNING
, "Priority '%s' must be a number > 0, or valid label\n", pri
);
8368 /* At this point we have a priority and maybe an extension and a context */
8371 ipri
= chan
->priority
+ (ipri
* mode
);
8374 ast_async_goto(chan
, context
, exten
, ipri
);
8376 ast_explicit_goto(chan
, context
, exten
, ipri
);
8378 ast_cdr_update(chan
);
8383 int ast_parseable_goto(struct ast_channel
*chan
, const char *goto_string
)
8385 return pbx_parseable_goto(chan
, goto_string
, 0);
8388 int ast_async_parseable_goto(struct ast_channel
*chan
, const char *goto_string
)
8390 return pbx_parseable_goto(chan
, goto_string
, 1);