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