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