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