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