Error message fix.
[asterisk/asterisk.git] / apps / app_stack.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (c) 2004-2006 Tilghman Lesher <app_stack_v003@the-tilghman.com>.
5  *
6  * This code is released by the author with no restrictions on usage.
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief Stack applications Gosub, Return, etc.
22  *
23  * \author Tilghman Lesher <app_stack_v003@the-tilghman.com>
24  * 
25  * \ingroup applications
26  */
27
28 /*** MODULEINFO
29         <use>res_agi</use>
30  ***/
31
32 #include "asterisk.h"
33  
34 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
35
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"
41 #include "asterisk/agi.h"
42
43 /*** DOCUMENTATION
44         <application name="Gosub" language="en_US">
45                 <synopsis>
46                         Jump to label, saving return address.
47                 </synopsis>
48                 <syntax>
49                         <parameter name="context" />
50                         <parameter name="exten" />
51                         <parameter name="priority" required="true" hasparams="optional">
52                                 <argument name="arg1" multiple="true" required="true" />
53                                 <argument name="argN" />
54                         </parameter>
55                 </syntax>
56                 <description>
57                         <para>Jumps to the label specified, saving the return address.</para>
58                 </description>
59                 <see-also>
60                         <ref type="application">GosubIf</ref>
61                         <ref type="application">Macro</ref>
62                         <ref type="application">Goto</ref>
63                         <ref type="application">Return</ref>
64                         <ref type="application">StackPop</ref>
65                 </see-also>
66         </application>
67         <application name="GosubIf" language="en_US">
68                 <synopsis>
69                         Conditionally jump to label, saving return address.
70                 </synopsis>
71                 <syntax argsep="?">
72                         <parameter name="condition" required="true" />
73                         <parameter name="destination" required="true" argsep=":">
74                                 <argument name="labeliftrue" hasparams="optional">
75                                         <argument name="arg1" required="true" multiple="true" />
76                                         <argument name="argN" />
77                                 </argument>
78                                 <argument name="labeliffalse" hasparams="optional">
79                                         <argument name="arg1" required="true" multiple="true" />
80                                         <argument name="argN" />
81                                 </argument>
82                         </parameter>
83                 </syntax>
84                 <description>
85                         <para>If the condition is true, then jump to labeliftrue.  If false, jumps to
86                         labeliffalse, if specified.  In either case, a jump saves the return point
87                         in the dialplan, to be returned to with a Return.</para>
88                 </description>
89                 <see-also>
90                         <ref type="application">Gosub</ref>
91                         <ref type="application">Return</ref>
92                         <ref type="application">MacroIf</ref>
93                         <ref type="function">IF</ref>
94                         <ref type="application">GotoIf</ref>
95                 </see-also>
96         </application>
97         <application name="Return" language="en_US">
98                 <synopsis>
99                         Return from gosub routine.
100                 </synopsis>
101                 <syntax>
102                         <parameter name="value">
103                                 <para>Return value.</para>
104                         </parameter>
105                 </syntax>
106                 <description>
107                         <para>Jumps to the last label on the stack, removing it. The return <replaceable>value</replaceable>, if
108                         any, is saved in the channel variable <variable>GOSUB_RETVAL</variable>.</para>
109                 </description>
110                 <see-also>
111                         <ref type="application">Gosub</ref>
112                         <ref type="application">StackPop</ref>
113                 </see-also>
114         </application>
115         <application name="StackPop" language="en_US">
116                 <synopsis>
117                         Remove one address from gosub stack.
118                 </synopsis>
119                 <syntax />
120                 <description>
121                         <para>Removes last label on the stack, discarding it.</para>
122                 </description>
123                 <see-also>
124                         <ref type="application">Return</ref>
125                         <ref type="application">Gosub</ref>
126                 </see-also>
127         </application>
128         <function name="LOCAL" language="en_US">
129                 <synopsis>
130                         Manage variables local to the gosub stack frame.
131                 </synopsis>
132                 <syntax>
133                         <parameter name="varname" required="true" />
134                 </syntax>
135                 <description>
136                         <para>Read and write a variable local to the gosub stack frame, once we Return() it will be lost
137                         (or it will go back to whatever value it had before the Gosub()).</para>
138                 </description>
139                 <see-also>
140                         <ref type="application">Gosub</ref>
141                         <ref type="application">GosubIf</ref>
142                         <ref type="application">Return</ref>
143                 </see-also>
144         </function>
145         <function name="LOCAL_PEEK" language="en_US">
146                 <synopsis>
147                         Retrieve variables hidden by the local gosub stack frame.
148                 </synopsis>
149                 <syntax>
150                         <parameter name="n" required="true" />
151                         <parameter name="varname" required="true" />
152                 </syntax>
153                 <description>
154                         <para>Read a variable <replaceable>varname</replaceable> hidden by
155                         <replaceable>n</replaceable> levels of gosub stack frames.  Note that ${LOCAL_PEEK(0,foo)}
156                         is the same as <variable>foo</variable>, since the value of <replaceable>n</replaceable>
157                         peeks under 0 levels of stack frames; in other words, 0 is the current level.  If
158                         <replaceable>n</replaceable> exceeds the available number of stack frames, then an empty
159                         string is returned.</para>
160                 </description>
161                 <see-also>
162                         <ref type="application">Gosub</ref>
163                         <ref type="application">GosubIf</ref>
164                         <ref type="application">Return</ref>
165                 </see-also>
166         </function>
167         <agi name="gosub" language="en_US">
168                 <synopsis>
169                         Cause the channel to execute the specified dialplan subroutine.
170                 </synopsis>
171                 <syntax>
172                         <parameter name="context" required="true" />
173                         <parameter name="extension" required="true" />
174                         <parameter name="priority" required="true" />
175                         <parameter name="optional-argument" />
176                 </syntax>
177                 <description>
178                         <para>Cause the channel to execute the specified dialplan subroutine,
179                         returning to the dialplan with execution of a Return().</para>
180                 </description>
181         </agi>
182  ***/
183
184 static const char * const app_gosub = "Gosub";
185 static const char * const app_gosubif = "GosubIf";
186 static const char * const app_return = "Return";
187 static const char * const app_pop = "StackPop";
188
189 static void gosub_free(void *data);
190
191 static struct ast_datastore_info stack_info = {
192         .type = "GOSUB",
193         .destroy = gosub_free,
194 };
195
196 struct gosub_stack_frame {
197         AST_LIST_ENTRY(gosub_stack_frame) entries;
198         /* 100 arguments is all that we support anyway, but this will handle up to 255 */
199         unsigned char arguments;
200         struct varshead varshead;
201         int priority;
202         unsigned int is_agi:1;
203         char *context;
204         char extension[0];
205 };
206
207 static int frame_set_var(struct ast_channel *chan, struct gosub_stack_frame *frame, const char *var, const char *value)
208 {
209         struct ast_var_t *variables;
210         int found = 0;
211
212         /* Does this variable already exist? */
213         AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
214                 if (!strcmp(var, ast_var_name(variables))) {
215                         found = 1;
216                         break;
217                 }
218         }
219
220         if (!found) {
221                 variables = ast_var_assign(var, "");
222                 AST_LIST_INSERT_HEAD(&frame->varshead, variables, entries);
223                 pbx_builtin_pushvar_helper(chan, var, value);
224         } else {
225                 pbx_builtin_setvar_helper(chan, var, value);
226         }
227
228         manager_event(EVENT_FLAG_DIALPLAN, "VarSet",
229                 "Channel: %s\r\n"
230                 "Variable: LOCAL(%s)\r\n"
231                 "Value: %s\r\n"
232                 "Uniqueid: %s\r\n",
233                 chan->name, var, value, chan->uniqueid);
234         return 0;
235 }
236
237 static void gosub_release_frame(struct ast_channel *chan, struct gosub_stack_frame *frame)
238 {
239         struct ast_var_t *vardata;
240
241         /* If chan is not defined, then we're calling it as part of gosub_free,
242          * and the channel variables will be deallocated anyway.  Otherwise, we're
243          * just releasing a single frame, so we need to clean up the arguments for
244          * that frame, so that we re-expose the variables from the previous frame
245          * that were hidden by this one.
246          */
247         while ((vardata = AST_LIST_REMOVE_HEAD(&frame->varshead, entries))) {
248                 if (chan)
249                         pbx_builtin_setvar_helper(chan, ast_var_name(vardata), NULL);   
250                 ast_var_delete(vardata);
251         }
252
253         ast_free(frame);
254 }
255
256 static struct gosub_stack_frame *gosub_allocate_frame(const char *context, const char *extension, int priority, unsigned char arguments)
257 {
258         struct gosub_stack_frame *new = NULL;
259         int len_extension = strlen(extension), len_context = strlen(context);
260
261         if ((new = ast_calloc(1, sizeof(*new) + 2 + len_extension + len_context))) {
262                 AST_LIST_HEAD_INIT_NOLOCK(&new->varshead);
263                 strcpy(new->extension, extension);
264                 new->context = new->extension + len_extension + 1;
265                 strcpy(new->context, context);
266                 new->priority = priority;
267                 new->arguments = arguments;
268         }
269         return new;
270 }
271
272 static void gosub_free(void *data)
273 {
274         AST_LIST_HEAD(, gosub_stack_frame) *oldlist = data;
275         struct gosub_stack_frame *oldframe;
276         AST_LIST_LOCK(oldlist);
277         while ((oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
278                 gosub_release_frame(NULL, oldframe);
279         }
280         AST_LIST_UNLOCK(oldlist);
281         AST_LIST_HEAD_DESTROY(oldlist);
282         ast_free(oldlist);
283 }
284
285 static int pop_exec(struct ast_channel *chan, const char *data)
286 {
287         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
288         struct gosub_stack_frame *oldframe;
289         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
290
291         if (!stack_store) {
292                 ast_log(LOG_WARNING, "%s called with no gosub stack allocated.\n", app_pop);
293                 return 0;
294         }
295
296         oldlist = stack_store->data;
297         AST_LIST_LOCK(oldlist);
298         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
299         AST_LIST_UNLOCK(oldlist);
300
301         if (oldframe) {
302                 gosub_release_frame(chan, oldframe);
303         } else {
304                 ast_debug(1, "%s called with an empty gosub stack\n", app_pop);
305         }
306         return 0;
307 }
308
309 static int return_exec(struct ast_channel *chan, const char *data)
310 {
311         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
312         struct gosub_stack_frame *oldframe;
313         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
314         const char *retval = data;
315         int res = 0;
316
317         if (!stack_store) {
318                 ast_log(LOG_ERROR, "Return without Gosub: stack is unallocated\n");
319                 return -1;
320         }
321
322         oldlist = stack_store->data;
323         AST_LIST_LOCK(oldlist);
324         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
325         AST_LIST_UNLOCK(oldlist);
326
327         if (!oldframe) {
328                 ast_log(LOG_ERROR, "Return without Gosub: stack is empty\n");
329                 return -1;
330         } else if (oldframe->is_agi) {
331                 /* Exit from AGI */
332                 res = -1;
333         }
334
335         ast_explicit_goto(chan, oldframe->context, oldframe->extension, oldframe->priority);
336         gosub_release_frame(chan, oldframe);
337
338         /* Set a return value, if any */
339         pbx_builtin_setvar_helper(chan, "GOSUB_RETVAL", S_OR(retval, ""));
340         return res;
341 }
342
343 static int gosub_exec(struct ast_channel *chan, const char *data)
344 {
345         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
346         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
347         struct gosub_stack_frame *newframe, *lastframe;
348         char argname[15], *tmp = ast_strdupa(data), *label, *endparen;
349         int i, max_argc = 0;
350         AST_DECLARE_APP_ARGS(args2,
351                 AST_APP_ARG(argval)[100];
352         );
353
354         if (ast_strlen_zero(data)) {
355                 ast_log(LOG_ERROR, "%s requires an argument: %s([[context,]exten,]priority[(arg1[,...][,argN])])\n", app_gosub, app_gosub);
356                 return -1;
357         }
358
359         if (!stack_store) {
360                 ast_debug(1, "Channel %s has no datastore, so we're allocating one.\n", chan->name);
361                 stack_store = ast_datastore_alloc(&stack_info, NULL);
362                 if (!stack_store) {
363                         ast_log(LOG_ERROR, "Unable to allocate new datastore.  Gosub will fail.\n");
364                         return -1;
365                 }
366
367                 oldlist = ast_calloc(1, sizeof(*oldlist));
368                 if (!oldlist) {
369                         ast_log(LOG_ERROR, "Unable to allocate datastore list head.  Gosub will fail.\n");
370                         ast_datastore_free(stack_store);
371                         return -1;
372                 }
373
374                 stack_store->data = oldlist;
375                 AST_LIST_HEAD_INIT(oldlist);
376                 ast_channel_datastore_add(chan, stack_store);
377         } else {
378                 oldlist = stack_store->data;
379         }
380
381         if ((lastframe = AST_LIST_FIRST(oldlist))) {
382                 max_argc = lastframe->arguments;
383         }
384
385         /* Separate the arguments from the label */
386         /* NOTE:  you cannot use ast_app_separate_args for this, because '(' cannot be used as a delimiter. */
387         label = strsep(&tmp, "(");
388         if (tmp) {
389                 endparen = strrchr(tmp, ')');
390                 if (endparen)
391                         *endparen = '\0';
392                 else
393                         ast_log(LOG_WARNING, "Ouch.  No closing paren: '%s'?\n", (char *)data);
394                 AST_STANDARD_RAW_ARGS(args2, tmp);
395         } else
396                 args2.argc = 0;
397
398         /* Mask out previous arguments in this invocation */
399         if (args2.argc > max_argc) {
400                 max_argc = args2.argc;
401         }
402
403         /* Create the return address, but don't save it until we know that the Gosub destination exists */
404         newframe = gosub_allocate_frame(chan->context, chan->exten, chan->priority + 1, max_argc);
405
406         if (!newframe) {
407                 return -1;
408         }
409
410         if (ast_parseable_goto(chan, label)) {
411                 ast_log(LOG_ERROR, "Gosub address is invalid: '%s'\n", (char *)data);
412                 ast_free(newframe);
413                 return -1;
414         }
415
416         if (!ast_exists_extension(chan, chan->context, chan->exten, ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP) ? chan->priority + 1 : chan->priority, chan->cid.cid_num)) {
417                 ast_log(LOG_ERROR, "Attempt to reach a non-existent destination for gosub: (Context:%s, Extension:%s, Priority:%d)\n",
418                                 chan->context, chan->exten, ast_test_flag(chan, AST_FLAG_IN_AUTOLOOP) ? chan->priority + 1 : chan->priority);
419                 ast_copy_string(chan->context, newframe->context, sizeof(chan->context));
420                 ast_copy_string(chan->exten, newframe->extension, sizeof(chan->exten));
421                 chan->priority = newframe->priority;
422                 ast_free(newframe);
423                 return -1;
424         }
425
426         /* Now that we know for certain that we're going to a new location, set our arguments */
427         for (i = 0; i < max_argc; i++) {
428                 snprintf(argname, sizeof(argname), "ARG%d", i + 1);
429                 frame_set_var(chan, newframe, argname, i < args2.argc ? args2.argval[i] : "");
430                 ast_debug(1, "Setting '%s' to '%s'\n", argname, i < args2.argc ? args2.argval[i] : "");
431         }
432         snprintf(argname, sizeof(argname), "%d", args2.argc);
433         frame_set_var(chan, newframe, "ARGC", argname);
434
435         /* And finally, save our return address */
436         oldlist = stack_store->data;
437         AST_LIST_LOCK(oldlist);
438         AST_LIST_INSERT_HEAD(oldlist, newframe, entries);
439         AST_LIST_UNLOCK(oldlist);
440
441         return 0;
442 }
443
444 static int gosubif_exec(struct ast_channel *chan, const char *data)
445 {
446         char *args;
447         int res=0;
448         AST_DECLARE_APP_ARGS(cond,
449                 AST_APP_ARG(ition);
450                 AST_APP_ARG(labels);
451         );
452         AST_DECLARE_APP_ARGS(label,
453                 AST_APP_ARG(iftrue);
454                 AST_APP_ARG(iffalse);
455         );
456
457         if (ast_strlen_zero(data)) {
458                 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
459                 return 0;
460         }
461
462         args = ast_strdupa(data);
463         AST_NONSTANDARD_RAW_ARGS(cond, args, '?');
464         if (cond.argc != 2) {
465                 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
466                 return 0;
467         }
468
469         AST_NONSTANDARD_RAW_ARGS(label, cond.labels, ':');
470
471         if (pbx_checkcondition(cond.ition)) {
472                 if (!ast_strlen_zero(label.iftrue))
473                         res = gosub_exec(chan, label.iftrue);
474         } else if (!ast_strlen_zero(label.iffalse)) {
475                 res = gosub_exec(chan, label.iffalse);
476         }
477
478         return res;
479 }
480
481 static int local_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
482 {
483         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
484         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
485         struct gosub_stack_frame *frame;
486         struct ast_var_t *variables;
487
488         if (!stack_store)
489                 return -1;
490
491         oldlist = stack_store->data;
492         AST_LIST_LOCK(oldlist);
493         if (!(frame = AST_LIST_FIRST(oldlist))) {
494                 /* Not within a Gosub routine */
495                 AST_LIST_UNLOCK(oldlist);
496                 return -1;
497         }
498
499         AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
500                 if (!strcmp(data, ast_var_name(variables))) {
501                         const char *tmp;
502                         ast_channel_lock(chan);
503                         tmp = pbx_builtin_getvar_helper(chan, data);
504                         ast_copy_string(buf, S_OR(tmp, ""), len);
505                         ast_channel_unlock(chan);
506                         break;
507                 }
508         }
509         AST_LIST_UNLOCK(oldlist);
510         return 0;
511 }
512
513 static int local_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
514 {
515         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
516         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
517         struct gosub_stack_frame *frame;
518
519         if (!stack_store) {
520                 ast_log(LOG_ERROR, "Tried to set LOCAL(%s), but we aren't within a Gosub routine\n", var);
521                 return -1;
522         }
523
524         oldlist = stack_store->data;
525         AST_LIST_LOCK(oldlist);
526         frame = AST_LIST_FIRST(oldlist);
527
528         if (frame)
529                 frame_set_var(chan, frame, var, value);
530
531         AST_LIST_UNLOCK(oldlist);
532
533         return 0;
534 }
535
536 static struct ast_custom_function local_function = {
537         .name = "LOCAL",
538         .write = local_write,
539         .read = local_read,
540 };
541
542 static int peek_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
543 {
544         int found = 0, n;
545         struct ast_var_t *variables;
546         AST_DECLARE_APP_ARGS(args,
547                 AST_APP_ARG(n);
548                 AST_APP_ARG(name);
549         );
550
551         if (!chan) {
552                 ast_log(LOG_ERROR, "LOCAL_PEEK must be called on an active channel\n");
553                 return -1;
554         }
555
556         AST_STANDARD_RAW_ARGS(args, data);
557         n = atoi(args.n);
558         *buf = '\0';
559
560         ast_channel_lock(chan);
561         AST_LIST_TRAVERSE(&chan->varshead, variables, entries) {
562                 if (!strcmp(args.name, ast_var_name(variables)) && ++found > n) {
563                         ast_copy_string(buf, ast_var_value(variables), len);
564                         break;
565                 }
566         }
567         ast_channel_unlock(chan);
568         return 0;
569 }
570
571 static struct ast_custom_function peek_function = {
572         .name = "LOCAL_PEEK",
573         .read = peek_read,
574 };
575
576 static int handle_gosub(struct ast_channel *chan, AGI *agi, int argc, const char * const *argv)
577 {
578         int old_priority, priority;
579         char old_context[AST_MAX_CONTEXT], old_extension[AST_MAX_EXTENSION];
580         struct ast_app *theapp;
581         char *gosub_args;
582
583         if (argc < 4 || argc > 5) {
584                 return RESULT_SHOWUSAGE;
585         }
586
587         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] : "");
588
589         if (sscanf(argv[3], "%30d", &priority) != 1 || priority < 1) {
590                 /* Lookup the priority label */
591                 if ((priority = ast_findlabel_extension(chan, argv[1], argv[2], argv[3], chan->cid.cid_num)) < 0) {
592                         ast_log(LOG_ERROR, "Priority '%s' not found in '%s@%s'\n", argv[3], argv[2], argv[1]);
593                         ast_agi_send(agi->fd, chan, "200 result=-1 Gosub label not found\n");
594                         return RESULT_FAILURE;
595                 }
596         } else if (!ast_exists_extension(chan, argv[1], argv[2], priority, chan->cid.cid_num)) {
597                 ast_agi_send(agi->fd, chan, "200 result=-1 Gosub label not found\n");
598                 return RESULT_FAILURE;
599         }
600
601         /* Save previous location, since we're going to change it */
602         ast_copy_string(old_context, chan->context, sizeof(old_context));
603         ast_copy_string(old_extension, chan->exten, sizeof(old_extension));
604         old_priority = chan->priority;
605
606         if (!(theapp = pbx_findapp("Gosub"))) {
607                 ast_log(LOG_ERROR, "Gosub() cannot be found in the list of loaded applications\n");
608                 ast_agi_send(agi->fd, chan, "503 result=-2 Gosub is not loaded\n");
609                 return RESULT_FAILURE;
610         }
611
612         /* Apparently, if you run ast_pbx_run on a channel that already has a pbx
613          * structure, you need to add 1 to the priority to get it to go to the
614          * right place.  But if it doesn't have a pbx structure, then leaving off
615          * the 1 is the right thing to do.  See how this code differs when we
616          * call a Gosub for the CALLEE channel in Dial or Queue.
617          */
618         if (argc == 5) {
619                 if (asprintf(&gosub_args, "%s,%s,%d(%s)", argv[1], argv[2], priority + (chan->pbx ? 1 : 0), argv[4]) < 0) {
620                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
621                         gosub_args = NULL;
622                 }
623         } else {
624                 if (asprintf(&gosub_args, "%s,%s,%d", argv[1], argv[2], priority + (chan->pbx ? 1 : 0)) < 0) {
625                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
626                         gosub_args = NULL;
627                 }
628         }
629
630         if (gosub_args) {
631                 int res;
632
633                 ast_debug(1, "Trying gosub with arguments '%s'\n", gosub_args);
634
635                 if ((res = pbx_exec(chan, theapp, gosub_args)) == 0) {
636                         struct ast_pbx *pbx = chan->pbx;
637                         struct ast_pbx_args args;
638                         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
639                         AST_LIST_HEAD(, gosub_stack_frame) *oldlist = stack_store->data;
640                         struct gosub_stack_frame *cur = AST_LIST_FIRST(oldlist);
641                         cur->is_agi = 1;
642
643                         memset(&args, 0, sizeof(args));
644                         args.no_hangup_chan = 1;
645                         /* Suppress warning about PBX already existing */
646                         chan->pbx = NULL;
647                         ast_agi_send(agi->fd, chan, "100 result=0 Trying...\n");
648                         ast_pbx_run_args(chan, &args);
649                         ast_agi_send(agi->fd, chan, "200 result=0 Gosub complete\n");
650                         if (chan->pbx) {
651                                 ast_free(chan->pbx);
652                         }
653                         chan->pbx = pbx;
654                 } else {
655                         ast_agi_send(agi->fd, chan, "200 result=%d Gosub failed\n", res);
656                 }
657                 ast_free(gosub_args);
658         } else {
659                 ast_agi_send(agi->fd, chan, "503 result=-2 Memory allocation failure\n");
660                 return RESULT_FAILURE;
661         }
662
663         /* Restore previous location */
664         ast_copy_string(chan->context, old_context, sizeof(chan->context));
665         ast_copy_string(chan->exten, old_extension, sizeof(chan->exten));
666         chan->priority = old_priority;
667
668         return RESULT_SUCCESS;
669 }
670
671 static struct agi_command gosub_agi_command =
672         { { "gosub", NULL }, handle_gosub, NULL, NULL, 0 };
673
674 static int unload_module(void)
675 {
676         ast_agi_unregister(ast_module_info->self, &gosub_agi_command);
677
678         ast_unregister_application(app_return);
679         ast_unregister_application(app_pop);
680         ast_unregister_application(app_gosubif);
681         ast_unregister_application(app_gosub);
682         ast_custom_function_unregister(&local_function);
683         ast_custom_function_unregister(&peek_function);
684
685         return 0;
686 }
687
688 static int load_module(void)
689 {
690         ast_agi_register(ast_module_info->self, &gosub_agi_command);
691
692         ast_register_application_xml(app_pop, pop_exec);
693         ast_register_application_xml(app_return, return_exec);
694         ast_register_application_xml(app_gosubif, gosubif_exec);
695         ast_register_application_xml(app_gosub, gosub_exec);
696         ast_custom_function_register(&local_function);
697         ast_custom_function_register(&peek_function);
698
699         return 0;
700 }
701
702 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan subroutines (Gosub, Return, etc)");