- Add more <see-also> based on TFOT.
[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
42 /* usage of AGI is optional, so indicate that to the header file */
43 #define ASTERISK_AGI_OPTIONAL
44 #include "asterisk/agi.h"
45
46 /*** DOCUMENTATION
47         <application name="Gosub" language="en_US">
48                 <synopsis>
49                         Jump to label, saving return address.
50                 </synopsis>
51                 <syntax>
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" />
57                         </parameter>
58                 </syntax>
59                 <description>
60                         <para>Jumps to the label specified, saving the return address.</para>
61                 </description>
62                 <see-also>
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>
68                 </see-also>
69         </application>
70         <application name="GosubIf" language="en_US">
71                 <synopsis>
72                         Conditionally jump to label, saving return address.
73                 </synopsis>
74                 <syntax argsep="?">
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" />
80                                 </argument>
81                                 <argument name="labeliffalse" hasparams="optional">
82                                         <argument name="arg1" required="true" multiple="true" />
83                                         <argument name="argN" />
84                                 </argument>
85                         </parameter>
86                 </syntax>
87                 <description>
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>
91                 </description>
92                 <see-also>
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>
98                 </see-also>
99         </application>
100         <application name="Return" language="en_US">
101                 <synopsis>
102                         Return from gosub routine.
103                 </synopsis>
104                 <syntax>
105                         <parameter name="value">
106                                 <para>Return value.</para>
107                         </parameter>
108                 </syntax>
109                 <description>
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>
112                 </description>
113                 <see-also>
114                         <ref type="application">Gosub</ref>
115                         <ref type="application">StackPop</ref>
116                 </see-also>
117         </application>
118         <application name="StackPop" language="en_US">
119                 <synopsis>
120                         Remove one address from gosub stack.
121                 </synopsis>
122                 <syntax />
123                 <description>
124                         <para>Removes last label on the stack, discarding it.</para>
125                 </description>
126                 <see-also>
127                         <ref type="application">Return</ref>
128                         <ref type="application">Gosub</ref>
129                 </see-also>
130         </application>
131         <function name="LOCAL" language="en_US">
132                 <synopsis>
133                         Manage variables local to the gosub stack frame.
134                 </synopsis>
135                 <syntax>
136                         <parameter name="varname" required="true" />
137                 </syntax>
138                 <description>
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>
141                 </description>
142                 <see-also>
143                         <ref type="application">Gosub</ref>
144                         <ref type="application">GosubIf</ref>
145                         <ref type="application">Return</ref>
146                 </see-also>
147         </function>
148  ***/
149
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";
154
155 static void gosub_free(void *data);
156
157 static struct ast_datastore_info stack_info = {
158         .type = "GOSUB",
159         .destroy = gosub_free,
160 };
161
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;
167         int priority;
168         char *context;
169         char extension[0];
170 };
171
172 static int frame_set_var(struct ast_channel *chan, struct gosub_stack_frame *frame, const char *var, const char *value)
173 {
174         struct ast_var_t *variables;
175         int found = 0;
176
177         /* Does this variable already exist? */
178         AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
179                 if (!strcmp(var, ast_var_name(variables))) {
180                         found = 1;
181                         break;
182                 }
183         }
184
185         if (!ast_strlen_zero(value)) {
186                 if (!found) {
187                         variables = ast_var_assign(var, "");
188                         AST_LIST_INSERT_HEAD(&frame->varshead, variables, entries);
189                         pbx_builtin_pushvar_helper(chan, var, value);
190                 } else
191                         pbx_builtin_setvar_helper(chan, var, value);
192
193                 manager_event(EVENT_FLAG_DIALPLAN, "VarSet", 
194                         "Channel: %s\r\n"
195                         "Variable: LOCAL(%s)\r\n"
196                         "Value: %s\r\n"
197                         "Uniqueid: %s\r\n", 
198                         chan->name, var, value, chan->uniqueid);
199         }
200         return 0;
201 }
202
203 static void gosub_release_frame(struct ast_channel *chan, struct gosub_stack_frame *frame)
204 {
205         struct ast_var_t *vardata;
206
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.
212          */
213         while ((vardata = AST_LIST_REMOVE_HEAD(&frame->varshead, entries))) {
214                 if (chan)
215                         pbx_builtin_setvar_helper(chan, ast_var_name(vardata), NULL);   
216                 ast_var_delete(vardata);
217         }
218
219         ast_free(frame);
220 }
221
222 static struct gosub_stack_frame *gosub_allocate_frame(const char *context, const char *extension, int priority, unsigned char arguments)
223 {
224         struct gosub_stack_frame *new = NULL;
225         int len_extension = strlen(extension), len_context = strlen(context);
226
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;
234         }
235         return new;
236 }
237
238 static void gosub_free(void *data)
239 {
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);
245         }
246         AST_LIST_UNLOCK(oldlist);
247         AST_LIST_HEAD_DESTROY(oldlist);
248         ast_free(oldlist);
249 }
250
251 static int pop_exec(struct ast_channel *chan, void *data)
252 {
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;
256
257         if (!stack_store) {
258                 ast_log(LOG_WARNING, "%s called with no gosub stack allocated.\n", app_pop);
259                 return 0;
260         }
261
262         oldlist = stack_store->data;
263         AST_LIST_LOCK(oldlist);
264         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
265         AST_LIST_UNLOCK(oldlist);
266
267         if (oldframe) {
268                 gosub_release_frame(chan, oldframe);
269         } else {
270                 ast_debug(1, "%s called with an empty gosub stack\n", app_pop);
271         }
272         return 0;
273 }
274
275 static int return_exec(struct ast_channel *chan, void *data)
276 {
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;
280         char *retval = data;
281
282         if (!stack_store) {
283                 ast_log(LOG_ERROR, "Return without Gosub: stack is unallocated\n");
284                 return -1;
285         }
286
287         oldlist = stack_store->data;
288         AST_LIST_LOCK(oldlist);
289         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
290         AST_LIST_UNLOCK(oldlist);
291
292         if (!oldframe) {
293                 ast_log(LOG_ERROR, "Return without Gosub: stack is empty\n");
294                 return -1;
295         }
296
297         ast_explicit_goto(chan, oldframe->context, oldframe->extension, oldframe->priority);
298         gosub_release_frame(chan, oldframe);
299
300         /* Set a return value, if any */
301         pbx_builtin_setvar_helper(chan, "GOSUB_RETVAL", S_OR(retval, ""));
302         return 0;
303 }
304
305 static int gosub_exec(struct ast_channel *chan, void *data)
306 {
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;
311         int i;
312         AST_DECLARE_APP_ARGS(args2,
313                 AST_APP_ARG(argval)[100];
314         );
315
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);
318                 return -1;
319         }
320
321         if (!stack_store) {
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);
324                 if (!stack_store) {
325                         ast_log(LOG_ERROR, "Unable to allocate new datastore.  Gosub will fail.\n");
326                         return -1;
327                 }
328
329                 oldlist = ast_calloc(1, sizeof(*oldlist));
330                 if (!oldlist) {
331                         ast_log(LOG_ERROR, "Unable to allocate datastore list head.  Gosub will fail.\n");
332                         ast_datastore_free(stack_store);
333                         return -1;
334                 }
335
336                 stack_store->data = oldlist;
337                 AST_LIST_HEAD_INIT(oldlist);
338                 ast_channel_datastore_add(chan, stack_store);
339         }
340
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, "(");
344         if (tmp) {
345                 endparen = strrchr(tmp, ')');
346                 if (endparen)
347                         *endparen = '\0';
348                 else
349                         ast_log(LOG_WARNING, "Ouch.  No closing paren: '%s'?\n", (char *)data);
350                 AST_STANDARD_APP_ARGS(args2, tmp);
351         } else
352                 args2.argc = 0;
353
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);
356
357         if (!newframe)
358                 return -1;
359
360         if (ast_parseable_goto(chan, label)) {
361                 ast_log(LOG_ERROR, "Gosub address is invalid: '%s'\n", (char *)data);
362                 ast_free(newframe);
363                 return -1;
364         }
365
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]);
371         }
372         snprintf(argname, sizeof(argname), "%d", args2.argc);
373         frame_set_var(chan, newframe, "ARGC", argname);
374
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);
380
381         return 0;
382 }
383
384 static int gosubif_exec(struct ast_channel *chan, void *data)
385 {
386         char *args;
387         int res=0;
388         AST_DECLARE_APP_ARGS(cond,
389                 AST_APP_ARG(ition);
390                 AST_APP_ARG(labels);
391         );
392         AST_DECLARE_APP_ARGS(label,
393                 AST_APP_ARG(iftrue);
394                 AST_APP_ARG(iffalse);
395         );
396
397         if (ast_strlen_zero(data)) {
398                 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
399                 return 0;
400         }
401
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");
406                 return 0;
407         }
408
409         AST_NONSTANDARD_APP_ARGS(label, cond.labels, ':');
410
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);
416         }
417
418         return res;
419 }
420
421 static int local_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
422 {
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;
427
428         if (!stack_store)
429                 return -1;
430
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))) {
436                         const char *tmp;
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);
441                         break;
442                 }
443         }
444         AST_LIST_UNLOCK(oldlist);
445         return 0;
446 }
447
448 static int local_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
449 {
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;
453
454         if (!stack_store) {
455                 ast_log(LOG_ERROR, "Tried to set LOCAL(%s), but we aren't within a Gosub routine\n", var);
456                 return -1;
457         }
458
459         oldlist = stack_store->data;
460         AST_LIST_LOCK(oldlist);
461         frame = AST_LIST_FIRST(oldlist);
462
463         if (frame)
464                 frame_set_var(chan, frame, var, value);
465
466         AST_LIST_UNLOCK(oldlist);
467
468         return 0;
469 }
470
471 static struct ast_custom_function local_function = {
472         .name = "LOCAL",
473         .write = local_write,
474         .read = local_read,
475 };
476
477 static int handle_gosub(struct ast_channel *chan, AGI *agi, int argc, char **argv)
478 {
479         int old_priority, priority;
480         char old_context[AST_MAX_CONTEXT], old_extension[AST_MAX_EXTENSION];
481         struct ast_app *theapp;
482         char *gosub_args;
483
484         if (argc < 4 || argc > 5) {
485                 return RESULT_SHOWUSAGE;
486         }
487
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] : "");
489
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;
496                 }
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;
500         }
501
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;
506
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;
511         }
512
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.
518          */
519         if (argc == 5) {
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));
522                         gosub_args = NULL;
523                 }
524         } else {
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));
527                         gosub_args = NULL;
528                 }
529         }
530
531         if (gosub_args) {
532                 int res;
533
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));
537                 chan->priority = 0;
538
539                 if ((res = pbx_exec(chan, theapp, gosub_args)) == 0) {
540                         struct ast_pbx *pbx = chan->pbx;
541                         /* Suppress warning about PBX already existing */
542                         chan->pbx = NULL;
543                         ast_agi_fdprintf(chan, agi->fd, "100 result=0 Trying...\n");
544                         ast_pbx_run(chan);
545                         ast_agi_fdprintf(chan, agi->fd, "200 result=0 Gosub complete\n");
546                         if (chan->pbx) {
547                                 ast_free(chan->pbx);
548                         }
549                         chan->pbx = pbx;
550                 } else {
551                         ast_agi_fdprintf(chan, agi->fd, "200 result=%d Gosub failed\n", res);
552                 }
553                 ast_free(gosub_args);
554         } else {
555                 ast_agi_fdprintf(chan, agi->fd, "503 result=-2 Memory allocation failure\n");
556                 return RESULT_FAILURE;
557         }
558
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;
563
564         return RESULT_SUCCESS;
565 }
566
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";
571
572 struct agi_command gosub_agi_command =
573         { { "gosub", NULL }, handle_gosub, "Execute a dialplan subroutine", usage_gosub , 0 };
574
575 static int unload_module(void)
576 {
577         struct ast_context *con;
578
579         if (ast_agi_unregister) {
580                 ast_agi_unregister(ast_module_info->self, &gosub_agi_command);
581
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 */
585                 }
586         }
587
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);
593
594         return 0;
595 }
596
597 static int load_module(void)
598 {
599         struct ast_context *con;
600
601         /* usage of AGI is optional, so check to see if the ast_agi_register()
602            function is available; if so, use it.
603         */
604         if (ast_agi_register) {
605                 con = ast_context_find_or_create(NULL, NULL, "app_stack_gosub_virtual_context", "app_stack");
606                 if (!con) {
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;
609                 } else {
610                         ast_add_extension2(con, 1, "s", 1, NULL, NULL, "KeepAlive", ast_strdup(""), ast_free_ptr, "app_stack");
611                 }
612
613                 ast_agi_register(ast_module_info->self, &gosub_agi_command);
614         }
615
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);
621
622         return 0;
623 }
624
625 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan subroutines (Gosub, Return, etc)");