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