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