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