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