4e4d78aec1fef217942729447d8ebfcf8e746ea4
[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 #include "asterisk.h"
29  
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <unistd.h>
35 #include <string.h>
36
37 #include "asterisk/options.h"
38 #include "asterisk/logger.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/chanvars.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/module.h"
43 #include "asterisk/config.h"
44 #include "asterisk/app.h"
45 #include "asterisk/manager.h"
46
47 static const char *app_gosub = "Gosub";
48 static const char *app_gosubif = "GosubIf";
49 static const char *app_return = "Return";
50 static const char *app_pop = "StackPop";
51
52 static const char *gosub_synopsis = "Jump to label, saving return address";
53 static const char *gosubif_synopsis = "Conditionally jump to label, saving return address";
54 static const char *return_synopsis = "Return from gosub routine";
55 static const char *pop_synopsis = "Remove one address from gosub stack";
56
57 static const char *gosub_descrip =
58 "Gosub([[context|]exten|]priority[(arg1[|...][|argN])])\n"
59 "  Jumps to the label specified, saving the return address.\n";
60 static const char *gosubif_descrip =
61 "GosubIf(condition?labeliftrue[(arg1[|...])][:labeliffalse[(arg1[|...])]])\n"
62 "  If the condition is true, then jump to labeliftrue.  If false, jumps to\n"
63 "labeliffalse, if specified.  In either case, a jump saves the return point\n"
64 "in the dialplan, to be returned to with a Return.\n";
65 static const char *return_descrip =
66 "Return([return-value])\n"
67 "  Jumps to the last label on the stack, removing it.  The return value, if\n"
68 "any, is saved in the channel variable GOSUB_RETVAL.\n";
69 static const char *pop_descrip =
70 "StackPop()\n"
71 "  Removes last label on the stack, discarding it.\n";
72
73
74 static void gosub_free(void *data);
75
76 static struct ast_datastore_info stack_info = {
77         .type = "GOSUB",
78         .destroy = gosub_free,
79 };
80
81 struct gosub_stack_frame {
82         AST_LIST_ENTRY(gosub_stack_frame) entries;
83         /* 100 arguments is all that we support anyway, but this will handle up to 255 */
84         unsigned char arguments;
85         struct varshead varshead;
86         int priority;
87         char *context;
88         char extension[0];
89 };
90
91 static int frame_set_var(struct ast_channel *chan, struct gosub_stack_frame *frame, const char *var, const char *value)
92 {
93         struct ast_var_t *variables;
94         int found = 0;
95
96         /* Does this variable already exist? */
97         AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
98                 if (!strcmp(var, ast_var_name(variables))) {
99                         found = 1;
100                         break;
101                 }
102         }
103
104         if (!ast_strlen_zero(value)) {
105                 if (!found) {
106                         variables = ast_var_assign(var, "");
107                         AST_LIST_INSERT_HEAD(&frame->varshead, variables, entries);
108                         pbx_builtin_pushvar_helper(chan, var, value);
109                 } else
110                         pbx_builtin_setvar_helper(chan, var, value);
111
112                 manager_event(EVENT_FLAG_CALL, "VarSet", 
113                         "Channel: %s\r\n"
114                         "Variable: LOCAL(%s)\r\n"
115                         "Value: %s\r\n"
116                         "Uniqueid: %s\r\n", 
117                         chan->name, var, value, chan->uniqueid);
118         }
119         return 0;
120 }
121
122 static void gosub_release_frame(struct ast_channel *chan, struct gosub_stack_frame *frame)
123 {
124         unsigned char i;
125         char argname[15];
126         struct ast_var_t *vardata;
127
128         /* If chan is not defined, then we're calling it as part of gosub_free,
129          * and the channel variables will be deallocated anyway.  Otherwise, we're
130          * just releasing a single frame, so we need to clean up the arguments for
131          * that frame, so that we re-expose the variables from the previous frame
132          * that were hidden by this one.
133          */
134         if (chan) {
135                 for (i = 1; i <= frame->arguments && i != 0; i++) {
136                         snprintf(argname, sizeof(argname), "ARG%hhd", i);
137                         pbx_builtin_setvar_helper(chan, argname, NULL);
138                 }
139         }
140
141         /* Delete local variables */
142         while ((vardata = AST_LIST_REMOVE_HEAD(&frame->varshead, entries))) {
143                 if (chan)
144                         pbx_builtin_setvar_helper(chan, ast_var_name(vardata), NULL);   
145                 ast_var_delete(vardata);
146         }
147
148         ast_free(frame);
149 }
150
151 static struct gosub_stack_frame *gosub_allocate_frame(const char *context, const char *extension, int priority, unsigned char arguments)
152 {
153         struct gosub_stack_frame *new = NULL;
154         int len_extension = strlen(extension), len_context = strlen(context);
155
156         if ((new = ast_calloc(1, sizeof(*new) + 2 + len_extension + len_context))) {
157                 AST_LIST_HEAD_INIT_NOLOCK(&new->varshead);
158                 strcpy(new->extension, extension);
159                 new->context = new->extension + len_extension + 1;
160                 strcpy(new->context, context);
161                 new->priority = priority;
162                 new->arguments = arguments;
163         }
164         return new;
165 }
166
167 static void gosub_free(void *data)
168 {
169         AST_LIST_HEAD(, gosub_stack_frame) *oldlist = data;
170         struct gosub_stack_frame *oldframe;
171         AST_LIST_LOCK(oldlist);
172         while ((oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries))) {
173                 gosub_release_frame(NULL, oldframe);
174         }
175         AST_LIST_UNLOCK(oldlist);
176         AST_LIST_HEAD_DESTROY(oldlist);
177         ast_free(oldlist);
178 }
179
180 static int pop_exec(struct ast_channel *chan, void *data)
181 {
182         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
183         struct gosub_stack_frame *oldframe;
184         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
185
186         if (!stack_store) {
187                 ast_log(LOG_WARNING, "%s called with no gosub stack allocated.\n", app_pop);
188                 return 0;
189         }
190
191         oldlist = stack_store->data;
192         AST_LIST_LOCK(oldlist);
193         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
194         AST_LIST_UNLOCK(oldlist);
195
196         if (oldframe) {
197                 gosub_release_frame(chan, oldframe);
198         } else {
199                 ast_debug(1, "%s called with an empty gosub stack\n", app_pop);
200         }
201         return 0;
202 }
203
204 static int return_exec(struct ast_channel *chan, void *data)
205 {
206         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
207         struct gosub_stack_frame *oldframe;
208         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
209         char *retval = data;
210
211         if (!stack_store) {
212                 ast_log(LOG_ERROR, "Return without Gosub: stack is unallocated\n");
213                 return -1;
214         }
215
216         oldlist = stack_store->data;
217         AST_LIST_LOCK(oldlist);
218         oldframe = AST_LIST_REMOVE_HEAD(oldlist, entries);
219         AST_LIST_UNLOCK(oldlist);
220
221         if (!oldframe) {
222                 ast_log(LOG_ERROR, "Return without Gosub: stack is empty\n");
223                 return -1;
224         }
225
226         ast_explicit_goto(chan, oldframe->context, oldframe->extension, oldframe->priority);
227         gosub_release_frame(chan, oldframe);
228
229         /* Set a return value, if any */
230         pbx_builtin_setvar_helper(chan, "GOSUB_RETVAL", S_OR(retval, ""));
231         return 0;
232 }
233
234 static int gosub_exec(struct ast_channel *chan, void *data)
235 {
236         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
237         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
238         struct gosub_stack_frame *newframe;
239         char argname[15], *tmp = ast_strdupa(data), *label, *endparen;
240         int i;
241         struct ast_module_user *u;
242         AST_DECLARE_APP_ARGS(args2,
243                 AST_APP_ARG(argval)[100];
244         );
245
246         if (ast_strlen_zero(data)) {
247                 ast_log(LOG_ERROR, "%s requires an argument: %s([[context|]exten|]priority[(arg1[|...][|argN])])\n", app_gosub, app_gosub);
248                 return -1;
249         }
250
251         u = ast_module_user_add(chan);
252
253         if (!stack_store) {
254                 ast_debug(1, "Channel %s has no datastore, so we're allocating one.\n", chan->name);
255                 stack_store = ast_channel_datastore_alloc(&stack_info, NULL);
256                 if (!stack_store) {
257                         ast_log(LOG_ERROR, "Unable to allocate new datastore.  Gosub will fail.\n");
258                         ast_module_user_remove(u);
259                         return -1;
260                 }
261
262                 oldlist = ast_calloc(1, sizeof(*oldlist));
263                 if (!oldlist) {
264                         ast_log(LOG_ERROR, "Unable to allocate datastore list head.  Gosub will fail.\n");
265                         ast_channel_datastore_free(stack_store);
266                         ast_module_user_remove(u);
267                         return -1;
268                 }
269
270                 stack_store->data = oldlist;
271                 AST_LIST_HEAD_INIT(oldlist);
272                 ast_channel_datastore_add(chan, stack_store);
273         }
274
275         /* Separate the arguments from the label */
276         /* NOTE:  you cannot use ast_app_separate_args for this, because '(' cannot be used as a delimiter. */
277         label = strsep(&tmp, "(");
278         if (tmp) {
279                 endparen = strrchr(tmp, ')');
280                 if (endparen)
281                         *endparen = '\0';
282                 else
283                         ast_log(LOG_WARNING, "Ouch.  No closing paren: '%s'?\n", (char *)data);
284                 AST_STANDARD_APP_ARGS(args2, tmp);
285         } else
286                 args2.argc = 0;
287
288         /* Create the return address, but don't save it until we know that the Gosub destination exists */
289         newframe = gosub_allocate_frame(chan->context, chan->exten, chan->priority + 1, args2.argc);
290
291         if (!newframe)
292                 return -1;
293
294         if (ast_parseable_goto(chan, label)) {
295                 ast_log(LOG_ERROR, "Gosub address is invalid: '%s'\n", (char *)data);
296                 ast_free(newframe);
297                 ast_module_user_remove(u);
298                 return -1;
299         }
300
301         /* Now that we know for certain that we're going to a new location, set our arguments */
302         for (i = 0; i < args2.argc; i++) {
303                 snprintf(argname, sizeof(argname), "ARG%d", i + 1);
304                 frame_set_var(chan, newframe, argname, args2.argval[i]);
305                 ast_debug(1, "Setting '%s' to '%s'\n", argname, args2.argval[i]);
306         }
307
308         /* And finally, save our return address */
309         oldlist = stack_store->data;
310         AST_LIST_LOCK(oldlist);
311         AST_LIST_INSERT_HEAD(oldlist, newframe, entries);
312         AST_LIST_UNLOCK(oldlist);
313
314         ast_module_user_remove(u);
315
316         return 0;
317 }
318
319 static int gosubif_exec(struct ast_channel *chan, void *data)
320 {
321         struct ast_module_user *u;
322         char *args;
323         int res=0;
324         AST_DECLARE_APP_ARGS(cond,
325                 AST_APP_ARG(ition);
326                 AST_APP_ARG(labels);
327         );
328         AST_DECLARE_APP_ARGS(label,
329                 AST_APP_ARG(iftrue);
330                 AST_APP_ARG(iffalse);
331         );
332
333         if (ast_strlen_zero(data)) {
334                 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
335                 return 0;
336         }
337
338         u = ast_module_user_add(chan);
339
340         args = ast_strdupa(data);
341         AST_NONSTANDARD_APP_ARGS(cond, args, '?');
342         if (cond.argc != 2) {
343                 ast_log(LOG_WARNING, "GosubIf requires an argument: GosubIf(cond?label1(args):label2(args)\n");
344                 ast_module_user_remove(u);
345                 return 0;
346         }
347
348         AST_NONSTANDARD_APP_ARGS(label, cond.labels, ':');
349
350         if (pbx_checkcondition(cond.ition)) {
351                 if (!ast_strlen_zero(label.iftrue))
352                         res = gosub_exec(chan, label.iftrue);
353         } else if (!ast_strlen_zero(label.iffalse)) {
354                 res = gosub_exec(chan, label.iffalse);
355         }
356
357         ast_module_user_remove(u);
358         return res;
359 }
360
361 static int local_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
362 {
363         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
364         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
365         struct gosub_stack_frame *frame;
366         struct ast_var_t *variables;
367
368         if (!stack_store)
369                 return -1;
370
371         oldlist = stack_store->data;
372         AST_LIST_LOCK(oldlist);
373         frame = AST_LIST_FIRST(oldlist);
374         AST_LIST_TRAVERSE(&frame->varshead, variables, entries) {
375                 if (!strcmp(data, ast_var_name(variables))) {
376                         const char *tmp = pbx_builtin_getvar_helper(chan, data);
377                         ast_copy_string(buf, S_OR(tmp, ""), len);
378                         break;
379                 }
380         }
381         AST_LIST_UNLOCK(oldlist);
382         return 0;
383 }
384
385 static int local_write(struct ast_channel *chan, const char *cmd, char *var, const char *value)
386 {
387         struct ast_datastore *stack_store = ast_channel_datastore_find(chan, &stack_info, NULL);
388         AST_LIST_HEAD(, gosub_stack_frame) *oldlist;
389         struct gosub_stack_frame *frame;
390
391         if (!stack_store) {
392                 ast_log(LOG_ERROR, "Tried to set LOCAL(%s), but we aren't within a Gosub routine\n", var);
393                 return -1;
394         }
395
396         oldlist = stack_store->data;
397         AST_LIST_LOCK(oldlist);
398         frame = AST_LIST_FIRST(oldlist);
399
400         if (frame)
401                 frame_set_var(chan, frame, var, value);
402
403         AST_LIST_UNLOCK(oldlist);
404
405         return 0;
406 }
407
408 static struct ast_custom_function local_function = {
409         .name = "LOCAL",
410         .synopsis = "Variables local to the gosub stack frame",
411         .syntax = "LOCAL(<varname>)",
412         .write = local_write,
413         .read = local_read,
414 };
415
416 static int unload_module(void)
417 {
418         ast_unregister_application(app_return);
419         ast_unregister_application(app_pop);
420         ast_unregister_application(app_gosubif);
421         ast_unregister_application(app_gosub);
422         ast_custom_function_unregister(&local_function);
423
424         return 0;
425 }
426
427 static int load_module(void)
428 {
429         ast_register_application(app_pop, pop_exec, pop_synopsis, pop_descrip);
430         ast_register_application(app_return, return_exec, return_synopsis, return_descrip);
431         ast_register_application(app_gosubif, gosubif_exec, gosubif_synopsis, gosubif_descrip);
432         ast_register_application(app_gosub, gosub_exec, gosub_synopsis, gosub_descrip);
433         ast_custom_function_register(&local_function);
434
435         return 0;
436 }
437
438 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Dialplan subroutines (Gosub, Return, etc)");