beeea30f638b17e7456c878ae3a716c636df24db
[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         </application>
63         <application name="GosubIf" language="en_US">
64                 <synopsis>
65                         Conditionally jump to label, saving return address.
66                 </synopsis>
67                 <syntax argsep="?">
68                         <parameter name="condition" required="true" />
69                         <parameter name="destination" required="true" argsep=":">
70                                 <argument name="labeliftrue" hasparams="optional">
71                                         <argument name="arg1" required="true" multiple="true" />
72                                         <argument name="argN" />
73                                 </argument>
74                                 <argument name="labeliffalse" hasparams="optional">
75                                         <argument name="arg1" required="true" multiple="true" />
76                                         <argument name="argN" />
77                                 </argument>
78                         </parameter>
79                 </syntax>
80                 <description>
81                         <para>If the condition is true, then jump to labeliftrue.  If false, jumps to
82                         labeliffalse, if specified.  In either case, a jump saves the return point
83                         in the dialplan, to be returned to with a Return.</para>
84                 </description>
85         </application>
86         <application name="Return" language="en_US">
87                 <synopsis>
88                         Return from gosub routine.
89                 </synopsis>
90                 <syntax>
91                         <parameter name="value">
92                                 <para>Return value.</para>
93                         </parameter>
94                 </syntax>
95                 <description>
96                         <para>Jumps to the last label on the stack, removing it. The return <replaceable>value</replaceable>, if
97                         any, is saved in the channel variable <variable>GOSUB_RETVAL</variable>.</para>
98                 </description>
99         </application>
100         <application name="StackPop" language="en_US">
101                 <synopsis>
102                         Remove one address from gosub stack.
103                 </synopsis>
104                 <syntax />
105                 <description>
106                         <para>Removes last label on the stack, discarding it.</para>
107                 </description>
108         </application>
109         <function name="LOCAL" language="en_US">
110                 <synopsis>
111                         Manage variables local to the gosub stack frame.
112                 </synopsis>
113                 <syntax>
114                         <parameter name="varname" required="true" />
115                 </syntax>
116                 <description>
117                         <para>Read and write a variable local to the gosub stack frame, once we Return() it will be lost
118                         (or it will go back to whatever value it had before the Gosub()).</para>
119                 </description>
120                 <see-also>
121                         <ref type="application">Gosub</ref>
122                         <ref type="application">GosubIf</ref>
123                         <ref type="application">Return</ref>
124                 </see-also>
125         </function>
126  ***/
127
128 static const char *app_gosub = "Gosub";
129 static const char *app_gosubif = "GosubIf";
130 static const char *app_return = "Return";
131 static const char *app_pop = "StackPop";
132
133 static void gosub_free(void *data);
134
135 static struct ast_datastore_info stack_info = {
136         .type = "GOSUB",
137         .destroy = gosub_free,
138 };
139
140 struct gosub_stack_frame {
141         AST_LIST_ENTRY(gosub_stack_frame) entries;
142         /* 100 arguments is all that we support anyway, but this will handle up to 255 */
143         unsigned char arguments;
144         struct varshead varshead;
145         int priority;
146         char *context;
147         char extension[0];
148 };
149
150 static int frame_set_var(struct ast_channel *chan, struct gosub_stack_frame *frame, const char *var, const char *value)
151 {
152         struct ast_var_t *variables;
153         int found = 0;
154
155         /* Does this variable already exist? */
156         AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
157                 if (!strcmp(var, ast_var_name(variables))) {
158                         found = 1;
159                         break;
160                 }
161         }
162
163         if (!ast_strlen_zero(value)) {
164                 if (!found) {
165                         variables = ast_var_assign(var, "");
166                         AST_LIST_INSERT_HEAD(&frame->varshead, variables, entries);
167                         pbx_builtin_pushvar_helper(chan, var, value);
168                 } else
169                         pbx_builtin_setvar_helper(chan, var, value);
170
171                 manager_event(EVENT_FLAG_DIALPLAN, "VarSet", 
172                         "Channel: %s\r\n"
173                         "Variable: LOCAL(%s)\r\n"
174                         "Value: %s\r\n"
175                         "Uniqueid: %s\r\n", 
176                         chan->name, var, value, chan->uniqueid);
177         }
178         return 0;
179 }
180
181 static void gosub_release_frame(struct ast_channel *chan, struct gosub_stack_frame *frame)
182 {
183         struct ast_var_t *vardata;
184
185         /* If chan is not defined, then we're calling it as part of gosub_free,
186          * and the channel variables will be deallocated anyway.  Otherwise, we're
187          * just releasing a single frame, so we need to clean up the arguments for
188          * that frame, so that we re-expose the variables from the previous frame
189          * that were hidden by this one.
190          */
191         while ((vardata = AST_LIST_REMOVE_HEAD(&frame->varshead, entries))) {
192                 if (chan)
193                         pbx_builtin_setvar_helper(chan, ast_var_name(vardata), NULL);   
194                 ast_var_delete(vardata);
195         }
196
197         ast_free(frame);
198 }
199
200 static struct gosub_stack_frame *gosub_allocate_frame(const char *context, const char *extension, int priority, unsigned char arguments)
201 {
202         struct gosub_stack_frame *new = NULL;
203         int len_extension = strlen(extension), len_context = strlen(context);
204
205         if ((new = ast_calloc(1, sizeof(*new) + 2 + len_extension + len_context))) {
206                 AST_LIST_HEAD_INIT_NOLOCK(&new->varshead);
207                 strcpy(new->extension, extension);
208                 new->context = new->extension + len_extension + 1;
209                 strcpy(new->context, context);
210                 new->priority = priority;
211                 new->arguments = arguments;
212         }
213         return new;
214 }
215
216 static void gosub_free(void *data)
217 {
218         AST_LIST_HEAD(, gosub_stack_frame) *oldlist = data;
219         struct gosub_stack_frame *oldframe;
220         AST_LIST_LOCK(oldlist);
221         while ((oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
222                 gosub_release_frame(NULL, oldframe);
223         }
224         AST_LIST_UNLOCK(oldlist);
225         AST_LIST_HEAD_DESTROY(oldlist);
226         ast_free(oldlist);
227 }
228
229 static int pop_exec(struct ast_channel *chan, void *data)
230 {
231         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
232         struct gosub_stack_frame *oldframe;
233         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
234
235         if (!stack_store) {
236                 ast_log(LOG_WARNING, "%s called with no gosub stack allocated.\n", app_pop);
237                 return 0;
238         }
239
240         oldlist = stack_store->data;
241         AST_LIST_LOCK(oldlist);
242         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
243         AST_LIST_UNLOCK(oldlist);
244
245         if (oldframe) {
246                 gosub_release_frame(chan, oldframe);
247         } else {
248                 ast_debug(1, "%s called with an empty gosub stack\n", app_pop);
249         }
250         return 0;
251 }
252
253 static int return_exec(struct ast_channel *chan, void *data)
254 {
255         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
256         struct gosub_stack_frame *oldframe;
257         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
258         char *retval = data;
259
260         if (!stack_store) {
261                 ast_log(LOG_ERROR, "Return without Gosub: stack is unallocated\n");
262                 return -1;
263         }
264
265         oldlist = stack_store->data;
266         AST_LIST_LOCK(oldlist);
267         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
268         AST_LIST_UNLOCK(oldlist);
269
270         if (!oldframe) {
271                 ast_log(LOG_ERROR, "Return without Gosub: stack is empty\n");
272                 return -1;
273         }
274
275         ast_explicit_goto(chan, oldframe->context, oldframe->extension, oldframe->priority);
276         gosub_release_frame(chan, oldframe);
277
278         /* Set a return value, if any */
279         pbx_builtin_setvar_helper(chan, "GOSUB_RETVAL", S_OR(retval, ""));
280         return 0;
281 }
282
283 static int gosub_exec(struct ast_channel *chan, void *data)
284 {
285         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
286         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
287         struct gosub_stack_frame *newframe;
288         char argname[15], *tmp = ast_strdupa(data), *label, *endparen;
289         int i;
290         AST_DECLARE_APP_ARGS(args2,
291                 AST_APP_ARG(argval)[100];
292         );
293
294         if (ast_strlen_zero(data)) {
295                 ast_log(LOG_ERROR, "%s requires an argument: %s([[context,]exten,]priority[(arg1[,...][,argN])])\n", app_gosub, app_gosub);
296                 return -1;
297         }
298
299         if (!stack_store) {
300                 ast_debug(1, "Channel %s has no datastore, so we're allocating one.\n", chan->name);
301                 stack_store = ast_datastore_alloc(&stack_info, NULL);
302                 if (!stack_store) {
303                         ast_log(LOG_ERROR, "Unable to allocate new datastore.  Gosub will fail.\n");
304                         return -1;
305                 }
306
307                 oldlist = ast_calloc(1, sizeof(*oldlist));
308                 if (!oldlist) {
309                         ast_log(LOG_ERROR, "Unable to allocate datastore list head.  Gosub will fail.\n");
310                         ast_datastore_free(stack_store);
311                         return -1;
312                 }
313
314                 stack_store->data = oldlist;
315                 AST_LIST_HEAD_INIT(oldlist);
316                 ast_channel_datastore_add(chan, stack_store);
317         }
318
319         /* Separate the arguments from the label */
320         /* NOTE:  you cannot use ast_app_separate_args for this, because '(' cannot be used as a delimiter. */
321         label = strsep(&tmp, "(");
322         if (tmp) {
323                 endparen = strrchr(tmp, ')');
324                 if (endparen)
325                         *endparen = '\0';
326                 else
327                         ast_log(LOG_WARNING, "Ouch.  No closing paren: '%s'?\n", (char *)data);
328                 AST_STANDARD_APP_ARGS(args2, tmp);
329         } else
330                 args2.argc = 0;
331
332         /* Create the return address, but don't save it until we know that the Gosub destination exists */
333         newframe = gosub_allocate_frame(chan->context, chan->exten, chan->priority + 1, args2.argc);
334
335         if (!newframe)
336                 return -1;
337
338         if (ast_parseable_goto(chan, label)) {
339                 ast_log(LOG_ERROR, "Gosub address is invalid: '%s'\n", (char *)data);
340                 ast_free(newframe);
341                 return -1;
342         }
343
344         /* Now that we know for certain that we're going to a new location, set our arguments */
345         for (i = 0; i < args2.argc; i++) {
346                 snprintf(argname, sizeof(argname), "ARG%d", i + 1);
347                 frame_set_var(chan, newframe, argname, args2.argval[i]);
348                 ast_debug(1, "Setting '%s' to '%s'\n", argname, args2.argval[i]);
349         }
350         snprintf(argname, sizeof(argname), "%d", args2.argc);
351         frame_set_var(chan, newframe, "ARGC", argname);
352
353         /* And finally, save our return address */
354         oldlist = stack_store->data;
355         AST_LIST_LOCK(oldlist);
356         AST_LIST_INSERT_HEAD(oldlist, newframe, entries);
357         AST_LIST_UNLOCK(oldlist);
358
359         return 0;
360 }
361
362 static int gosubif_exec(struct ast_channel *chan, void *data)
363 {
364         char *args;
365         int res=0;
366         AST_DECLARE_APP_ARGS(cond,
367                 AST_APP_ARG(ition);
368                 AST_APP_ARG(labels);
369         );
370         AST_DECLARE_APP_ARGS(label,
371                 AST_APP_ARG(iftrue);
372                 AST_APP_ARG(iffalse);
373         );
374
375         if (ast_strlen_zero(data)) {
376                 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
377                 return 0;
378         }
379
380         args = ast_strdupa(data);
381         AST_NONSTANDARD_APP_ARGS(cond, args, '?');
382         if (cond.argc != 2) {
383                 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
384                 return 0;
385         }
386
387         AST_NONSTANDARD_APP_ARGS(label, cond.labels, ':');
388
389         if (pbx_checkcondition(cond.ition)) {
390                 if (!ast_strlen_zero(label.iftrue))
391                         res = gosub_exec(chan, label.iftrue);
392         } else if (!ast_strlen_zero(label.iffalse)) {
393                 res = gosub_exec(chan, label.iffalse);
394         }
395
396         return res;
397 }
398
399 static int local_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
400 {
401         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
402         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
403         struct gosub_stack_frame *frame;
404         struct ast_var_t *variables;
405
406         if (!stack_store)
407                 return -1;
408
409         oldlist = stack_store->data;
410         AST_LIST_LOCK(oldlist);
411         frame = AST_LIST_FIRST(oldlist);
412         AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
413                 if (!strcmp(data, ast_var_name(variables))) {
414                         const char *tmp;
415                         ast_channel_lock(chan);
416                         tmp = pbx_builtin_getvar_helper(chan, data);
417                         ast_copy_string(buf, S_OR(tmp, ""), len);
418                         ast_channel_unlock(chan);
419                         break;
420                 }
421         }
422         AST_LIST_UNLOCK(oldlist);
423         return 0;
424 }
425
426 static int local_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
427 {
428         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
429         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
430         struct gosub_stack_frame *frame;
431
432         if (!stack_store) {
433                 ast_log(LOG_ERROR, "Tried to set LOCAL(%s), but we aren't within a Gosub routine\n", var);
434                 return -1;
435         }
436
437         oldlist = stack_store->data;
438         AST_LIST_LOCK(oldlist);
439         frame = AST_LIST_FIRST(oldlist);
440
441         if (frame)
442                 frame_set_var(chan, frame, var, value);
443
444         AST_LIST_UNLOCK(oldlist);
445
446         return 0;
447 }
448
449 static struct ast_custom_function local_function = {
450         .name = "LOCAL",
451         .write = local_write,
452         .read = local_read,
453 };
454
455 static int handle_gosub(struct ast_channel *chan, AGI *agi, int argc, char **argv)
456 {
457         int old_priority, priority;
458         char old_context[AST_MAX_CONTEXT], old_extension[AST_MAX_EXTENSION];
459         struct ast_app *theapp;
460         char *gosub_args;
461
462         if (argc < 4 || argc > 5) {
463                 return RESULT_SHOWUSAGE;
464         }
465
466         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] : "");
467
468         if (sscanf(argv[3], "%d", &priority) != 1 || priority < 1) {
469                 /* Lookup the priority label */
470                 if ((priority = ast_findlabel_extension(chan, argv[1], argv[2], argv[3], chan->cid.cid_num)) < 0) {
471                         ast_log(LOG_ERROR, "Priority '%s' not found in '%s@%s'\n", argv[3], argv[2], argv[1]);
472                         ast_agi_fdprintf(chan, agi->fd, "200 result=-1 Gosub label not found\n");
473                         return RESULT_FAILURE;
474                 }
475         } else if (!ast_exists_extension(chan, argv[1], argv[2], priority, chan->cid.cid_num)) {
476                 ast_agi_fdprintf(chan, agi->fd, "200 result=-1 Gosub label not found\n");
477                 return RESULT_FAILURE;
478         }
479
480         /* Save previous location, since we're going to change it */
481         ast_copy_string(old_context, chan->context, sizeof(old_context));
482         ast_copy_string(old_extension, chan->exten, sizeof(old_extension));
483         old_priority = chan->priority;
484
485         if (!(theapp = pbx_findapp("Gosub"))) {
486                 ast_log(LOG_ERROR, "Gosub() cannot be found in the list of loaded applications\n");
487                 ast_agi_fdprintf(chan, agi->fd, "503 result=-2 Gosub is not loaded\n");
488                 return RESULT_FAILURE;
489         }
490
491         /* Apparently, if you run ast_pbx_run on a channel that already has a pbx
492          * structure, you need to add 1 to the priority to get it to go to the
493          * right place.  But if it doesn't have a pbx structure, then leaving off
494          * the 1 is the right thing to do.  See how this code differs when we
495          * call a Gosub for the CALLEE channel in Dial or Queue.
496          */
497         if (argc == 5) {
498                 if (asprintf(&gosub_args, "%s,%s,%d(%s)", argv[1], argv[2], priority + 1, argv[4]) < 0) {
499                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
500                         gosub_args = NULL;
501                 }
502         } else {
503                 if (asprintf(&gosub_args, "%s,%s,%d", argv[1], argv[2], priority + 1) < 0) {
504                         ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
505                         gosub_args = NULL;
506                 }
507         }
508
509         if (gosub_args) {
510                 int res;
511
512                 ast_debug(1, "Trying gosub with arguments '%s'\n", gosub_args);
513                 ast_copy_string(chan->context, "app_stack_gosub_virtual_context", sizeof(chan->context));
514                 ast_copy_string(chan->exten, "s", sizeof(chan->exten));
515                 chan->priority = 0;
516
517                 if ((res = pbx_exec(chan, theapp, gosub_args)) == 0) {
518                         struct ast_pbx *pbx = chan->pbx;
519                         /* Suppress warning about PBX already existing */
520                         chan->pbx = NULL;
521                         ast_agi_fdprintf(chan, agi->fd, "100 result=0 Trying...\n");
522                         ast_pbx_run(chan);
523                         ast_agi_fdprintf(chan, agi->fd, "200 result=0 Gosub complete\n");
524                         if (chan->pbx) {
525                                 ast_free(chan->pbx);
526                         }
527                         chan->pbx = pbx;
528                 } else {
529                         ast_agi_fdprintf(chan, agi->fd, "200 result=%d Gosub failed\n", res);
530                 }
531                 ast_free(gosub_args);
532         } else {
533                 ast_agi_fdprintf(chan, agi->fd, "503 result=-2 Memory allocation failure\n");
534                 return RESULT_FAILURE;
535         }
536
537         /* Restore previous location */
538         ast_copy_string(chan->context, old_context, sizeof(chan->context));
539         ast_copy_string(chan->exten, old_extension, sizeof(chan->exten));
540         chan->priority = old_priority;
541
542         return RESULT_SUCCESS;
543 }
544
545 static char usage_gosub[] =
546 " Usage: GOSUB <context> <extension> <priority> [<optional-argument>]\n"
547 "   Cause the channel to execute the specified dialplan subroutine, returning\n"
548 " to the dialplan with execution of a Return()\n";
549
550 struct agi_command gosub_agi_command =
551         { { "gosub", NULL }, handle_gosub, "Execute a dialplan subroutine", usage_gosub , 0 };
552
553 static int unload_module(void)
554 {
555         struct ast_context *con;
556
557         if (ast_agi_unregister) {
558                 ast_agi_unregister(ast_module_info->self, &gosub_agi_command);
559
560                 if ((con = ast_context_find("app_stack_gosub_virtual_context"))) {
561                         ast_context_remove_extension2(con, "s", 1, NULL, 0);
562                         ast_context_destroy(con, "app_stack"); /* leave nothing behind */
563                 }
564         }
565
566         ast_unregister_application(app_return);
567         ast_unregister_application(app_pop);
568         ast_unregister_application(app_gosubif);
569         ast_unregister_application(app_gosub);
570         ast_custom_function_unregister(&local_function);
571
572         return 0;
573 }
574
575 static int load_module(void)
576 {
577         struct ast_context *con;
578
579         /* usage of AGI is optional, so check to see if the ast_agi_register()
580            function is available; if so, use it.
581         */
582         if (ast_agi_register) {
583                 con = ast_context_find_or_create(NULL, NULL, "app_stack_gosub_virtual_context", "app_stack");
584                 if (!con) {
585                         ast_log(LOG_ERROR, "Virtual context 'app_stack_gosub_virtual_context' does not exist and unable to create\n");
586                         return AST_MODULE_LOAD_DECLINE;
587                 } else {
588                         ast_add_extension2(con, 1, "s", 1, NULL, NULL, "KeepAlive", ast_strdup(""), ast_free_ptr, "app_stack");
589                 }
590
591                 ast_agi_register(ast_module_info->self, &gosub_agi_command);
592         }
593
594         ast_register_application_xml(app_pop, pop_exec);
595         ast_register_application_xml(app_return, return_exec);
596         ast_register_application_xml(app_gosubif, gosubif_exec);
597         ast_register_application_xml(app_gosub, gosub_exec);
598         ast_custom_function_register(&local_function);
599
600         return 0;
601 }
602
603 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan subroutines (Gosub, Return, etc)");