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