2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (c) 2004-2006 Tilghman Lesher <app_stack_v003@the-tilghman.com>.
6 * This code is released by the author with no restrictions on usage.
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 Stack applications Gosub, Return, etc.
23 * \author Tilghman Lesher <app_stack_v003@the-tilghman.com>
25 * \ingroup applications
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
36 #include "asterisk/pbx.h"
37 #include "asterisk/module.h"
38 #include "asterisk/app.h"
39 #include "asterisk/manager.h"
40 #include "asterisk/channel.h"
42 /* usage of AGI is optional, so indicate that to the header file */
43 #define ASTERISK_AGI_OPTIONAL
44 #include "asterisk/agi.h"
47 <application name="Gosub" language="en_US">
49 Jump to label, saving return address.
52 <parameter name="context" />
53 <parameter name="exten" />
54 <parameter name="priority" required="true" hasparams="optional">
55 <argument name="arg1" multiple="true" required="true" />
56 <argument name="argN" />
60 <para>Jumps to the label specified, saving the return address.</para>
63 <ref type="application">GosubIf</ref>
64 <ref type="application">Macro</ref>
65 <ref type="application">Goto</ref>
66 <ref type="application">Return</ref>
67 <ref type="application">StackPop</ref>
70 <application name="GosubIf" language="en_US">
72 Conditionally jump to label, saving return address.
75 <parameter name="condition" required="true" />
76 <parameter name="destination" required="true" argsep=":">
77 <argument name="labeliftrue" hasparams="optional">
78 <argument name="arg1" required="true" multiple="true" />
79 <argument name="argN" />
81 <argument name="labeliffalse" hasparams="optional">
82 <argument name="arg1" required="true" multiple="true" />
83 <argument name="argN" />
88 <para>If the condition is true, then jump to labeliftrue. If false, jumps to
89 labeliffalse, if specified. In either case, a jump saves the return point
90 in the dialplan, to be returned to with a Return.</para>
93 <ref type="application">Gosub</ref>
94 <ref type="application">Return</ref>
95 <ref type="application">MacroIf</ref>
96 <ref type="function">IF</ref>
97 <ref type="application">GotoIf</ref>
100 <application name="Return" language="en_US">
102 Return from gosub routine.
105 <parameter name="value">
106 <para>Return value.</para>
110 <para>Jumps to the last label on the stack, removing it. The return <replaceable>value</replaceable>, if
111 any, is saved in the channel variable <variable>GOSUB_RETVAL</variable>.</para>
114 <ref type="application">Gosub</ref>
115 <ref type="application">StackPop</ref>
118 <application name="StackPop" language="en_US">
120 Remove one address from gosub stack.
124 <para>Removes last label on the stack, discarding it.</para>
127 <ref type="application">Return</ref>
128 <ref type="application">Gosub</ref>
131 <function name="LOCAL" language="en_US">
133 Manage variables local to the gosub stack frame.
136 <parameter name="varname" required="true" />
139 <para>Read and write a variable local to the gosub stack frame, once we Return() it will be lost
140 (or it will go back to whatever value it had before the Gosub()).</para>
143 <ref type="application">Gosub</ref>
144 <ref type="application">GosubIf</ref>
145 <ref type="application">Return</ref>
150 static const char *app_gosub = "Gosub";
151 static const char *app_gosubif = "GosubIf";
152 static const char *app_return = "Return";
153 static const char *app_pop = "StackPop";
155 static void gosub_free(void *data);
157 static struct ast_datastore_info stack_info = {
159 .destroy = gosub_free,
162 struct gosub_stack_frame {
163 AST_LIST_ENTRY(gosub_stack_frame) entries;
164 /* 100 arguments is all that we support anyway, but this will handle up to 255 */
165 unsigned char arguments;
166 struct varshead varshead;
172 static int frame_set_var(struct ast_channel *chan, struct gosub_stack_frame *frame, const char *var, const char *value)
174 struct ast_var_t *variables;
177 /* Does this variable already exist? */
178 AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
179 if (!strcmp(var, ast_var_name(variables))) {
185 if (!ast_strlen_zero(value)) {
187 variables = ast_var_assign(var, "");
188 AST_LIST_INSERT_HEAD(&frame->varshead, variables, entries);
189 pbx_builtin_pushvar_helper(chan, var, value);
191 pbx_builtin_setvar_helper(chan, var, value);
193 manager_event(EVENT_FLAG_DIALPLAN, "VarSet",
195 "Variable: LOCAL(%s)\r\n"
198 chan->name, var, value, chan->uniqueid);
203 static void gosub_release_frame(struct ast_channel *chan, struct gosub_stack_frame *frame)
205 struct ast_var_t *vardata;
207 /* If chan is not defined, then we're calling it as part of gosub_free,
208 * and the channel variables will be deallocated anyway. Otherwise, we're
209 * just releasing a single frame, so we need to clean up the arguments for
210 * that frame, so that we re-expose the variables from the previous frame
211 * that were hidden by this one.
213 while ((vardata = AST_LIST_REMOVE_HEAD(&frame->varshead, entries))) {
215 pbx_builtin_setvar_helper(chan, ast_var_name(vardata), NULL);
216 ast_var_delete(vardata);
222 static struct gosub_stack_frame *gosub_allocate_frame(const char *context, const char *extension, int priority, unsigned char arguments)
224 struct gosub_stack_frame *new = NULL;
225 int len_extension = strlen(extension), len_context = strlen(context);
227 if ((new = ast_calloc(1, sizeof(*new) + 2 + len_extension + len_context))) {
228 AST_LIST_HEAD_INIT_NOLOCK(&new->varshead);
229 strcpy(new->extension, extension);
230 new->context = new->extension + len_extension + 1;
231 strcpy(new->context, context);
232 new->priority = priority;
233 new->arguments = arguments;
238 static void gosub_free(void *data)
240 AST_LIST_HEAD(, gosub_stack_frame) *oldlist = data;
241 struct gosub_stack_frame *oldframe;
242 AST_LIST_LOCK(oldlist);
243 while ((oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
244 gosub_release_frame(NULL, oldframe);
246 AST_LIST_UNLOCK(oldlist);
247 AST_LIST_HEAD_DESTROY(oldlist);
251 static int pop_exec(struct ast_channel *chan, void *data)
253 struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
254 struct gosub_stack_frame *oldframe;
255 AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
258 ast_log(LOG_WARNING, "%s called with no gosub stack allocated.\n", app_pop);
262 oldlist = stack_store->data;
263 AST_LIST_LOCK(oldlist);
264 oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
265 AST_LIST_UNLOCK(oldlist);
268 gosub_release_frame(chan, oldframe);
270 ast_debug(1, "%s called with an empty gosub stack\n", app_pop);
275 static int return_exec(struct ast_channel *chan, void *data)
277 struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
278 struct gosub_stack_frame *oldframe;
279 AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
283 ast_log(LOG_ERROR, "Return without Gosub: stack is unallocated\n");
287 oldlist = stack_store->data;
288 AST_LIST_LOCK(oldlist);
289 oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
290 AST_LIST_UNLOCK(oldlist);
293 ast_log(LOG_ERROR, "Return without Gosub: stack is empty\n");
297 ast_explicit_goto(chan, oldframe->context, oldframe->extension, oldframe->priority);
298 gosub_release_frame(chan, oldframe);
300 /* Set a return value, if any */
301 pbx_builtin_setvar_helper(chan, "GOSUB_RETVAL", S_OR(retval, ""));
305 static int gosub_exec(struct ast_channel *chan, void *data)
307 struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
308 AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
309 struct gosub_stack_frame *newframe;
310 char argname[15], *tmp = ast_strdupa(data), *label, *endparen;
312 AST_DECLARE_APP_ARGS(args2,
313 AST_APP_ARG(argval)[100];
316 if (ast_strlen_zero(data)) {
317 ast_log(LOG_ERROR, "%s requires an argument: %s([[context,]exten,]priority[(arg1[,...][,argN])])\n", app_gosub, app_gosub);
322 ast_debug(1, "Channel %s has no datastore, so we're allocating one.\n", chan->name);
323 stack_store = ast_datastore_alloc(&stack_info, NULL);
325 ast_log(LOG_ERROR, "Unable to allocate new datastore. Gosub will fail.\n");
329 oldlist = ast_calloc(1, sizeof(*oldlist));
331 ast_log(LOG_ERROR, "Unable to allocate datastore list head. Gosub will fail.\n");
332 ast_datastore_free(stack_store);
336 stack_store->data = oldlist;
337 AST_LIST_HEAD_INIT(oldlist);
338 ast_channel_datastore_add(chan, stack_store);
341 /* Separate the arguments from the label */
342 /* NOTE: you cannot use ast_app_separate_args for this, because '(' cannot be used as a delimiter. */
343 label = strsep(&tmp, "(");
345 endparen = strrchr(tmp, ')');
349 ast_log(LOG_WARNING, "Ouch. No closing paren: '%s'?\n", (char *)data);
350 AST_STANDARD_APP_ARGS(args2, tmp);
354 /* Create the return address, but don't save it until we know that the Gosub destination exists */
355 newframe = gosub_allocate_frame(chan->context, chan->exten, chan->priority + 1, args2.argc);
360 if (ast_parseable_goto(chan, label)) {
361 ast_log(LOG_ERROR, "Gosub address is invalid: '%s'\n", (char *)data);
366 /* Now that we know for certain that we're going to a new location, set our arguments */
367 for (i = 0; i < args2.argc; i++) {
368 snprintf(argname, sizeof(argname), "ARG%d", i + 1);
369 frame_set_var(chan, newframe, argname, args2.argval[i]);
370 ast_debug(1, "Setting '%s' to '%s'\n", argname, args2.argval[i]);
372 snprintf(argname, sizeof(argname), "%d", args2.argc);
373 frame_set_var(chan, newframe, "ARGC", argname);
375 /* And finally, save our return address */
376 oldlist = stack_store->data;
377 AST_LIST_LOCK(oldlist);
378 AST_LIST_INSERT_HEAD(oldlist, newframe, entries);
379 AST_LIST_UNLOCK(oldlist);
384 static int gosubif_exec(struct ast_channel *chan, void *data)
388 AST_DECLARE_APP_ARGS(cond,
392 AST_DECLARE_APP_ARGS(label,
394 AST_APP_ARG(iffalse);
397 if (ast_strlen_zero(data)) {
398 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
402 args = ast_strdupa(data);
403 AST_NONSTANDARD_APP_ARGS(cond, args, '?');
404 if (cond.argc != 2) {
405 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
409 AST_NONSTANDARD_APP_ARGS(label, cond.labels, ':');
411 if (pbx_checkcondition(cond.ition)) {
412 if (!ast_strlen_zero(label.iftrue))
413 res = gosub_exec(chan, label.iftrue);
414 } else if (!ast_strlen_zero(label.iffalse)) {
415 res = gosub_exec(chan, label.iffalse);
421 static int local_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
423 struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
424 AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
425 struct gosub_stack_frame *frame;
426 struct ast_var_t *variables;
431 oldlist = stack_store->data;
432 AST_LIST_LOCK(oldlist);
433 frame = AST_LIST_FIRST(oldlist);
434 AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
435 if (!strcmp(data, ast_var_name(variables))) {
437 ast_channel_lock(chan);
438 tmp = pbx_builtin_getvar_helper(chan, data);
439 ast_copy_string(buf, S_OR(tmp, ""), len);
440 ast_channel_unlock(chan);
444 AST_LIST_UNLOCK(oldlist);
448 static int local_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
450 struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
451 AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
452 struct gosub_stack_frame *frame;
455 ast_log(LOG_ERROR, "Tried to set LOCAL(%s), but we aren't within a Gosub routine\n", var);
459 oldlist = stack_store->data;
460 AST_LIST_LOCK(oldlist);
461 frame = AST_LIST_FIRST(oldlist);
464 frame_set_var(chan, frame, var, value);
466 AST_LIST_UNLOCK(oldlist);
471 static struct ast_custom_function local_function = {
473 .write = local_write,
477 static int handle_gosub(struct ast_channel *chan, AGI *agi, int argc, char **argv)
479 int old_priority, priority;
480 char old_context[AST_MAX_CONTEXT], old_extension[AST_MAX_EXTENSION];
481 struct ast_app *theapp;
484 if (argc < 4 || argc > 5) {
485 return RESULT_SHOWUSAGE;
488 ast_debug(1, "Gosub called with %d arguments: 0:%s 1:%s 2:%s 3:%s 4:%s\n", argc, argv[0], argv[1], argv[2], argv[3], argc == 5 ? argv[4] : "");
490 if (sscanf(argv[3], "%d", &priority) != 1 || priority < 1) {
491 /* Lookup the priority label */
492 if ((priority = ast_findlabel_extension(chan, argv[1], argv[2], argv[3], chan->cid.cid_num)) < 0) {
493 ast_log(LOG_ERROR, "Priority '%s' not found in '%s@%s'\n", argv[3], argv[2], argv[1]);
494 ast_agi_fdprintf(chan, agi->fd, "200 result=-1 Gosub label not found\n");
495 return RESULT_FAILURE;
497 } else if (!ast_exists_extension(chan, argv[1], argv[2], priority, chan->cid.cid_num)) {
498 ast_agi_fdprintf(chan, agi->fd, "200 result=-1 Gosub label not found\n");
499 return RESULT_FAILURE;
502 /* Save previous location, since we're going to change it */
503 ast_copy_string(old_context, chan->context, sizeof(old_context));
504 ast_copy_string(old_extension, chan->exten, sizeof(old_extension));
505 old_priority = chan->priority;
507 if (!(theapp = pbx_findapp("Gosub"))) {
508 ast_log(LOG_ERROR, "Gosub() cannot be found in the list of loaded applications\n");
509 ast_agi_fdprintf(chan, agi->fd, "503 result=-2 Gosub is not loaded\n");
510 return RESULT_FAILURE;
513 /* Apparently, if you run ast_pbx_run on a channel that already has a pbx
514 * structure, you need to add 1 to the priority to get it to go to the
515 * right place. But if it doesn't have a pbx structure, then leaving off
516 * the 1 is the right thing to do. See how this code differs when we
517 * call a Gosub for the CALLEE channel in Dial or Queue.
520 if (asprintf(&gosub_args, "%s,%s,%d(%s)", argv[1], argv[2], priority + 1, argv[4]) < 0) {
521 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
525 if (asprintf(&gosub_args, "%s,%s,%d", argv[1], argv[2], priority + 1) < 0) {
526 ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
534 ast_debug(1, "Trying gosub with arguments '%s'\n", gosub_args);
535 ast_copy_string(chan->context, "app_stack_gosub_virtual_context", sizeof(chan->context));
536 ast_copy_string(chan->exten, "s", sizeof(chan->exten));
539 if ((res = pbx_exec(chan, theapp, gosub_args)) == 0) {
540 struct ast_pbx *pbx = chan->pbx;
541 /* Suppress warning about PBX already existing */
543 ast_agi_fdprintf(chan, agi->fd, "100 result=0 Trying...\n");
545 ast_agi_fdprintf(chan, agi->fd, "200 result=0 Gosub complete\n");
551 ast_agi_fdprintf(chan, agi->fd, "200 result=%d Gosub failed\n", res);
553 ast_free(gosub_args);
555 ast_agi_fdprintf(chan, agi->fd, "503 result=-2 Memory allocation failure\n");
556 return RESULT_FAILURE;
559 /* Restore previous location */
560 ast_copy_string(chan->context, old_context, sizeof(chan->context));
561 ast_copy_string(chan->exten, old_extension, sizeof(chan->exten));
562 chan->priority = old_priority;
564 return RESULT_SUCCESS;
567 static char usage_gosub[] =
568 " Usage: GOSUB <context> <extension> <priority> [<optional-argument>]\n"
569 " Cause the channel to execute the specified dialplan subroutine, returning\n"
570 " to the dialplan with execution of a Return()\n";
572 struct agi_command gosub_agi_command =
573 { { "gosub", NULL }, handle_gosub, "Execute a dialplan subroutine", usage_gosub , 0 };
575 static int unload_module(void)
577 struct ast_context *con;
579 if (ast_agi_unregister) {
580 ast_agi_unregister(ast_module_info->self, &gosub_agi_command);
582 if ((con = ast_context_find("app_stack_gosub_virtual_context"))) {
583 ast_context_remove_extension2(con, "s", 1, NULL, 0);
584 ast_context_destroy(con, "app_stack"); /* leave nothing behind */
588 ast_unregister_application(app_return);
589 ast_unregister_application(app_pop);
590 ast_unregister_application(app_gosubif);
591 ast_unregister_application(app_gosub);
592 ast_custom_function_unregister(&local_function);
597 static int load_module(void)
599 struct ast_context *con;
601 /* usage of AGI is optional, so check to see if the ast_agi_register()
602 function is available; if so, use it.
604 if (ast_agi_register) {
605 con = ast_context_find_or_create(NULL, NULL, "app_stack_gosub_virtual_context", "app_stack");
607 ast_log(LOG_ERROR, "Virtual context 'app_stack_gosub_virtual_context' does not exist and unable to create\n");
608 return AST_MODULE_LOAD_DECLINE;
610 ast_add_extension2(con, 1, "s", 1, NULL, NULL, "KeepAlive", ast_strdup(""), ast_free_ptr, "app_stack");
613 ast_agi_register(ast_module_info->self, &gosub_agi_command);
616 ast_register_application_xml(app_pop, pop_exec);
617 ast_register_application_xml(app_return, return_exec);
618 ast_register_application_xml(app_gosubif, gosubif_exec);
619 ast_register_application_xml(app_gosub, gosub_exec);
620 ast_custom_function_register(&local_function);
625 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan subroutines (Gosub, Return, etc)");