channel: Clear channel flag in error branch.
[asterisk/asterisk.git] / funcs / func_periodic_hook.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2014, Russell Bryant
5  *
6  * Russell Bryant <russell@russellbryant.net>
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 Periodic dialplan hooks.
22  *
23  * \author Russell Bryant <russell@russellbryant.net>
24  *
25  * \ingroup functions
26  */
27
28 /*** MODULEINFO
29         <support_level>core</support_level>
30         <depend>app_chanspy</depend>
31         <depend>func_cut</depend>
32         <depend>func_groupcount</depend>
33         <depend>func_uri</depend>
34  ***/
35
36 #include "asterisk.h"
37
38 #include "asterisk/module.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/app.h"
42 #include "asterisk/audiohook.h"
43 #define AST_API_MODULE
44 #include "asterisk/beep.h"
45
46 /*** DOCUMENTATION
47         <function name="PERIODIC_HOOK" language="en_US">
48                 <synopsis>
49                         Execute a periodic dialplan hook into the audio of a call.
50                 </synopsis>
51                 <syntax>
52                         <parameter name="context" required="true">
53                                 <para>(On Read Only) Context for the hook extension.</para>
54                         </parameter>
55                         <parameter name="extension" required="true">
56                                 <para>(On Read Only) The hook extension.</para>
57                         </parameter>
58                         <parameter name="interval" required="true">
59                                 <para>(On Read Only) Number of seconds in between hook runs.
60                                 Whole seconds only.</para>
61                         </parameter>
62                         <parameter name="hook_id" required="true">
63                                 <para>(On Write Only) The hook ID.</para>
64                         </parameter>
65                 </syntax>
66                 <description>
67                         <para>For example, you could use this function to enable playing
68                         a periodic <literal>beep</literal> sound in a call.</para>
69                         <para/>
70                         <para>To turn on:</para>
71                         <para>  Set(BEEPID=${PERIODIC_HOOK(hooks,beep,180)})</para>
72                         <para/>
73                         <para>To turn off:</para>
74                         <para>  Set(PERIODIC_HOOK(${BEEPID})=off)</para>
75                         <para/>
76                         <para>To turn back on again later:</para>
77                         <para>Set(PERIODIC_HOOK(${BEEPID})=on)</para>
78                         <para/>
79                         <para>It is important to note that the hook does not actually
80                         run on the channel itself.  It runs asynchronously on a new channel.
81                         Any audio generated by the hook gets injected into the call for
82                         the channel PERIODIC_HOOK() was set on.</para>
83                         <para/>
84                         <para>The hook dialplan will have two variables available.
85                         <variable>HOOK_CHANNEL</variable> is the channel the hook is
86                         enabled on.  <variable>HOOK_ID</variable> is the hook ID for
87                         enabling or disabling the hook.</para>
88                 </description>
89         </function>
90  ***/
91
92 static const char context_name[] = "__func_periodic_hook_context__";
93 static const char exten_name[] = "hook";
94 static const char full_exten_name[] = "hook@__func_periodic_hook_context__";
95
96 static const char beep_exten[] = "beep";
97
98 /*!
99  * \brief Last used hook ID
100  *
101  * This is incremented each time a hook is created to give each hook a unique
102  * ID.
103  */
104 static unsigned int global_hook_id;
105
106 /*! State put in a datastore to track the state of the hook */
107 struct hook_state {
108         /*!
109          * \brief audiohook used as a callback into this module
110          *
111          * \note The code assumes this is the first element in the struct
112          */
113         struct ast_audiohook audiohook;
114         /*! Seconds between each hook run */
115         unsigned int interval;
116         /*! The last time the hook ran */
117         struct timeval last_hook;
118         /*! Dialplan context for the hook */
119         char *context;
120         /*! Dialplan extension for the hook */
121         char *exten;
122         /*! Hook ID */
123         unsigned int hook_id;
124         /*! Non-zero if the hook is currently disabled */
125         unsigned char disabled;
126 };
127
128 static void hook_datastore_destroy_callback(void *data)
129 {
130         struct hook_state *state = data;
131
132         ast_audiohook_lock(&state->audiohook);
133         ast_audiohook_detach(&state->audiohook);
134         ast_audiohook_unlock(&state->audiohook);
135         ast_audiohook_destroy(&state->audiohook);
136
137         ast_free(state->context);
138         ast_free(state->exten);
139         ast_free(state);
140
141         ast_module_unref(ast_module_info->self);
142 }
143
144 static const struct ast_datastore_info hook_datastore = {
145         .type = AST_MODULE,
146         .destroy = hook_datastore_destroy_callback,
147 };
148
149 /*! Arguments to the thread that launches the hook */
150 struct hook_thread_arg {
151         /*! Hook ID */
152         char *hook_id;
153         /*! Name of the channel the hook was set on */
154         char *chan_name;
155         /*! Dialplan context for the hook */
156         char *context;
157         /*! Dialplan extension for the hook */
158         char *exten;
159 };
160
161 static void hook_thread_arg_destroy(struct hook_thread_arg *arg)
162 {
163         ast_free(arg->hook_id);
164         ast_free(arg->chan_name);
165         ast_free(arg->context);
166         ast_free(arg->exten);
167         ast_free(arg);
168 }
169
170 static void *hook_launch_thread(void *data)
171 {
172         struct hook_thread_arg *arg = data;
173         struct ast_variable hook_id = {
174                 .name = "HOOK_ID",
175                 .value = arg->hook_id,
176         };
177         struct ast_variable chan_name_var = {
178                 .name = "HOOK_CHANNEL",
179                 .value = arg->chan_name,
180                 .next = &hook_id,
181         };
182
183         ast_pbx_outgoing_exten("Local", NULL, full_exten_name, 60,
184                         arg->context, arg->exten, 1, NULL, AST_OUTGOING_NO_WAIT,
185                         NULL, NULL, &chan_name_var, NULL, NULL, 1, NULL);
186
187         hook_thread_arg_destroy(arg);
188
189         return NULL;
190 }
191
192 static struct hook_thread_arg *hook_thread_arg_alloc(struct ast_channel *chan,
193                 struct hook_state *state)
194 {
195         struct hook_thread_arg *arg;
196
197         if (!(arg = ast_calloc(1, sizeof(*arg)))) {
198                 return NULL;
199         }
200
201         ast_channel_lock(chan);
202         arg->chan_name = ast_strdup(ast_channel_name(chan));
203         ast_channel_unlock(chan);
204         if (!arg->chan_name) {
205                 hook_thread_arg_destroy(arg);
206                 return NULL;
207         }
208
209         if (ast_asprintf(&arg->hook_id, "%u", state->hook_id) == -1) {
210                 hook_thread_arg_destroy(arg);
211                 return NULL;
212         }
213
214         if (!(arg->context = ast_strdup(state->context))) {
215                 hook_thread_arg_destroy(arg);
216                 return NULL;
217         }
218
219         if (!(arg->exten = ast_strdup(state->exten))) {
220                 hook_thread_arg_destroy(arg);
221                 return NULL;
222         }
223
224         return arg;
225 }
226
227 static int do_hook(struct ast_channel *chan, struct hook_state *state)
228 {
229         pthread_t t;
230         struct hook_thread_arg *arg;
231         int res;
232
233         if (!(arg = hook_thread_arg_alloc(chan, state))) {
234                 return -1;
235         }
236
237         /*
238          * We don't want to block normal frame processing *at all* while we kick
239          * this off, so do it in a new thread.
240          */
241         res = ast_pthread_create_detached_background(&t, NULL, hook_launch_thread, arg);
242         if (res != 0) {
243                 hook_thread_arg_destroy(arg);
244         }
245
246         return res;
247 }
248
249 static int hook_callback(struct ast_audiohook *audiohook, struct ast_channel *chan,
250                 struct ast_frame *frame, enum ast_audiohook_direction direction)
251 {
252         struct hook_state *state = (struct hook_state *) audiohook; /* trust me. */
253         struct timeval now;
254         int res = 0;
255
256         if (audiohook->status == AST_AUDIOHOOK_STATUS_DONE || state->disabled) {
257                 return 0;
258         }
259
260         now = ast_tvnow();
261         if (ast_tvdiff_ms(now, state->last_hook) > state->interval * 1000) {
262                 if ((res = do_hook(chan, state))) {
263                         const char *name;
264                         ast_channel_lock(chan);
265                         name = ast_strdupa(ast_channel_name(chan));
266                         ast_channel_unlock(chan);
267                         ast_log(LOG_WARNING, "Failed to run hook on '%s'\n", name);
268                 }
269                 state->last_hook = now;
270         }
271
272         return res;
273 }
274
275 static struct hook_state *hook_state_alloc(const char *context, const char *exten,
276                 unsigned int interval, unsigned int hook_id)
277 {
278         struct hook_state *state;
279
280         if (!(state = ast_calloc(1, sizeof(*state)))) {
281                 return NULL;
282         }
283
284         state->context = ast_strdup(context);
285         state->exten = ast_strdup(exten);
286         state->interval = interval;
287         state->hook_id = hook_id;
288
289         ast_audiohook_init(&state->audiohook, AST_AUDIOHOOK_TYPE_MANIPULATE,
290                         AST_MODULE, AST_AUDIOHOOK_MANIPULATE_ALL_RATES);
291         state->audiohook.manipulate_callback = hook_callback;
292
293         return state;
294 }
295
296 static int init_hook(struct ast_channel *chan, const char *context, const char *exten,
297                 unsigned int interval, unsigned int hook_id)
298 {
299         struct hook_state *state;
300         struct ast_datastore *datastore;
301         char uid[32];
302
303         snprintf(uid, sizeof(uid), "%u", hook_id);
304
305         if (!(datastore = ast_datastore_alloc(&hook_datastore, uid))) {
306                 return -1;
307         }
308         ast_module_ref(ast_module_info->self);
309         if (!(state = hook_state_alloc(context, exten, interval, hook_id))) {
310                 ast_datastore_free(datastore);
311                 return -1;
312         }
313         datastore->data = state;
314
315         ast_channel_lock(chan);
316         ast_channel_datastore_add(chan, datastore);
317         ast_audiohook_attach(chan, &state->audiohook);
318         ast_channel_unlock(chan);
319
320         return 0;
321 }
322
323 static int hook_on(struct ast_channel *chan, const char *data, unsigned int hook_id)
324 {
325         char *parse = ast_strdupa(S_OR(data, ""));
326         AST_DECLARE_APP_ARGS(args,
327                 AST_APP_ARG(context);
328                 AST_APP_ARG(exten);
329                 AST_APP_ARG(interval);
330         );
331         unsigned int interval;
332
333         AST_STANDARD_APP_ARGS(args, parse);
334
335         if (ast_strlen_zero(args.interval) ||
336                         sscanf(args.interval, "%30u", &interval) != 1 || interval == 0) {
337                 ast_log(LOG_WARNING, "Invalid hook interval: '%s'\n", S_OR(args.interval, ""));
338                 return -1;
339         }
340
341         if (ast_strlen_zero(args.context) || ast_strlen_zero(args.exten)) {
342                 ast_log(LOG_WARNING, "A context and extension are required for PERIODIC_HOOK().\n");
343                 return -1;
344         }
345
346         ast_debug(1, "hook to %s@%s enabled on %s with interval of %u seconds\n",
347                         args.exten, args.context, ast_channel_name(chan), interval);
348
349         return init_hook(chan, args.context, args.exten, interval, hook_id);
350 }
351
352 static int hook_off(struct ast_channel *chan, const char *hook_id)
353 {
354         struct ast_datastore *datastore;
355         struct hook_state *state;
356
357         if (ast_strlen_zero(hook_id)) {
358                 return -1;
359         }
360
361         ast_channel_lock(chan);
362
363         if (!(datastore = ast_channel_datastore_find(chan, &hook_datastore, hook_id))) {
364                 ast_log(LOG_WARNING, "Hook with ID '%s' not found on channel '%s'\n", hook_id,
365                                 ast_channel_name(chan));
366                 ast_channel_unlock(chan);
367                 return -1;
368         }
369
370         state = datastore->data;
371         state->disabled = 1;
372
373         ast_channel_unlock(chan);
374
375         return 0;
376 }
377
378 static int hook_read(struct ast_channel *chan, const char *cmd, char *data,
379                char *buf, size_t len)
380 {
381         unsigned int hook_id;
382
383         if (!chan) {
384                 return -1;
385         }
386
387         hook_id = (unsigned int) ast_atomic_fetchadd_int((int *) &global_hook_id, 1);
388
389         snprintf(buf, len, "%u", hook_id);
390
391         return hook_on(chan, data, hook_id);
392 }
393
394 static int hook_re_enable(struct ast_channel *chan, const char *uid)
395 {
396         struct ast_datastore *datastore;
397         struct hook_state *state;
398
399         if (ast_strlen_zero(uid)) {
400                 return -1;
401         }
402
403         ast_channel_lock(chan);
404
405         if (!(datastore = ast_channel_datastore_find(chan, &hook_datastore, uid))) {
406                 ast_log(LOG_WARNING, "Hook with ID '%s' not found on '%s'\n",
407                                 uid, ast_channel_name(chan));
408                 ast_channel_unlock(chan);
409                 return -1;
410         }
411
412         state = datastore->data;
413         state->disabled = 0;
414
415         ast_channel_unlock(chan);
416
417         return 0;
418 }
419
420 static int hook_write(struct ast_channel *chan, const char *cmd, char *data,
421                 const char *value)
422 {
423         int res;
424
425         if (!chan) {
426                 return -1;
427         }
428
429         if (ast_false(value)) {
430                 res = hook_off(chan, data);
431         } else if (ast_true(value)) {
432                 res = hook_re_enable(chan, data);
433         } else {
434                 ast_log(LOG_WARNING, "Invalid value for PERIODIC_HOOK function: '%s'\n", value);
435                 res = -1;
436         }
437
438         return res;
439 }
440
441 static struct ast_custom_function hook_function = {
442         .name = "PERIODIC_HOOK",
443         .read = hook_read,
444         .write = hook_write,
445 };
446
447 static int unload_module(void)
448 {
449         ast_context_destroy(NULL, AST_MODULE);
450
451         return ast_custom_function_unregister(&hook_function);
452 }
453
454 static int load_module(void)
455 {
456         int res;
457
458         if (!ast_context_find_or_create(NULL, NULL, context_name, AST_MODULE)) {
459                 ast_log(LOG_ERROR, "Failed to create %s dialplan context.\n", context_name);
460                 return AST_MODULE_LOAD_DECLINE;
461         }
462
463         /*
464          * Based on a handy recipe from the Asterisk Cookbook.
465          */
466         ast_add_extension(context_name, 1, exten_name, 1, "", "",
467                         "Set", "EncodedChannel=${CUT(HOOK_CHANNEL,-,1-2)}",
468                         NULL, AST_MODULE);
469         ast_add_extension(context_name, 1, exten_name, 2, "", "",
470                         "Set", "GROUP_NAME=${EncodedChannel}${HOOK_ID}",
471                         NULL, AST_MODULE);
472         ast_add_extension(context_name, 1, exten_name, 3, "", "",
473                         "Set", "GROUP(periodic-hook)=${GROUP_NAME}",
474                         NULL, AST_MODULE);
475         ast_add_extension(context_name, 1, exten_name, 4, "", "", "ExecIf",
476                         "$[${GROUP_COUNT(${GROUP_NAME}@periodic-hook)} > 1]?Hangup()",
477                         NULL, AST_MODULE);
478         ast_add_extension(context_name, 1, exten_name, 5, "", "",
479                         "Set", "ChannelToSpy=${URIDECODE(${EncodedChannel})}",
480                         NULL, AST_MODULE);
481         ast_add_extension(context_name, 1, exten_name, 6, "", "",
482                         "ChanSpy", "${ChannelToSpy},qEB", NULL, AST_MODULE);
483
484         res = ast_add_extension(context_name, 1, beep_exten, 1, "", "",
485                         "Answer", "", NULL, AST_MODULE);
486         res |= ast_add_extension(context_name, 1, beep_exten, 2, "", "",
487                         "Playback", "beep", NULL, AST_MODULE);
488
489         res = ast_custom_function_register_escalating(&hook_function, AST_CFE_BOTH);
490
491         return res ? AST_MODULE_LOAD_DECLINE : AST_MODULE_LOAD_SUCCESS;
492 }
493
494 int AST_OPTIONAL_API_NAME(ast_beep_start)(struct ast_channel *chan,
495                 unsigned int interval, char *beep_id, size_t len)
496 {
497         char args[AST_MAX_EXTENSION + AST_MAX_CONTEXT + 32];
498
499         snprintf(args, sizeof(args), "%s,%s,%u",
500                         context_name, beep_exten, interval);
501
502         if (hook_read(chan, NULL, args, beep_id, len)) {
503                 ast_log(LOG_WARNING, "Failed to enable periodic beep.\n");
504                 return -1;
505         }
506
507         return 0;
508 }
509
510 int AST_OPTIONAL_API_NAME(ast_beep_stop)(struct ast_channel *chan, const char *beep_id)
511 {
512         return hook_write(chan, NULL, (char *) beep_id, "off");
513 }
514
515 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "Periodic dialplan hooks.",
516         .support_level = AST_MODULE_SUPPORT_CORE,
517         .load = load_module,
518         .unload = unload_module,
519 );