Fix several interrelated issues dealing with the holding bridge technology.
[asterisk/asterisk.git] / apps / app_bridgewait.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2013, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * Author: Jonathan Rose <jrose@digium.com>
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  * This program is free software, distributed under the terms of
17  * the GNU General Public License Version 2. See the LICENSE file
18  * at the top of the source tree.
19  */
20
21 /*! \file
22  *
23  * \brief Application to place the channel into a holding Bridge
24  *
25  * \author Jonathan Rose <jrose@digium.com>
26  *
27  * \ingroup applications
28  */
29
30 /*** MODULEINFO
31         <depend>bridge_holding</depend>
32         <support_level>core</support_level>
33  ***/
34
35 #include "asterisk.h"
36
37 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
38
39 #include "asterisk/file.h"
40 #include "asterisk/channel.h"
41 #include "asterisk/pbx.h"
42 #include "asterisk/module.h"
43 #include "asterisk/features.h"
44 #include "asterisk/say.h"
45 #include "asterisk/lock.h"
46 #include "asterisk/utils.h"
47 #include "asterisk/app.h"
48 #include "asterisk/bridge.h"
49 #include "asterisk/musiconhold.h"
50 #include "asterisk/astobj2.h"
51
52 /*** DOCUMENTATION
53         <application name="BridgeWait" language="en_US">
54                 <synopsis>
55                         Put a call into the holding bridge.
56                 </synopsis>
57                 <syntax>
58                         <parameter name="name">
59                                 <para>Name of the holding bridge to join. This is a handle for <literal>BridgeWait</literal>
60                                 only and does not affect the actual bridges that are created. If not provided,
61                                 the reserved name <literal>default</literal> will be used.
62                                 </para>
63                         </parameter>
64                         <parameter name="role" required="false">
65                                 <para>Defines the channel's purpose for entering the holding bridge. Values are case sensitive.
66                                 </para>
67                                 <enumlist>
68                                         <enum name="participant">
69                                                 <para>The channel will enter the holding bridge to be placed on hold
70                                                 until it is removed from the bridge for some reason. (default)</para>
71                                         </enum>
72                                         <enum name="announcer">
73                                                 <para>The channel will enter the holding bridge to make announcements
74                                                 to channels that are currently in the holding bridge. While an
75                                                 announcer is present, holding for the participants will be
76                                                 suspended.</para>
77                                         </enum>
78                                 </enumlist>
79                         </parameter>
80                         <parameter name="options">
81                                 <optionlist>
82                                         <option name="m">
83                                                 <argument name="class" required="true" />
84                                                 <para>The specified MOH class will be used/suggested for
85                                                 music on hold operations. This option will only be useful for
86                                                 entertainment modes that use it (m and h).</para>
87                                         </option>
88                                         <option name="e">
89                                                 <para>Which entertainment mechanism should be used while on hold
90                                                 in the holding bridge. Only the first letter is read.</para>
91                                                 <enumlist>
92                                                         <enum name="m"><para>Play music on hold (default)</para></enum>
93                                                         <enum name="r"><para>Ring without pause</para></enum>
94                                                         <enum name="s"><para>Generate silent audio</para></enum>
95                                                         <enum name="h"><para>Put the channel on hold</para></enum>
96                                                         <enum name="n"><para>No entertainment</para></enum>
97                                                 </enumlist>
98                                         </option>
99                                         <option name="S">
100                                                 <argument name="duration" required="true" />
101                                                 <para>Automatically exit the bridge and return to the PBX after
102                                                 <emphasis>duration</emphasis> seconds.</para>
103                                         </option>
104                                 </optionlist>
105                         </parameter>
106                 </syntax>
107                 <description>
108                         <para>This application places the incoming channel into a holding bridge.
109                         The channel will then wait in the holding bridge until some event occurs
110                         which removes it from the holding bridge.</para>
111                         <note><para>This application will answer calls which haven't already
112                         been answered.</para></note>
113                 </description>
114         </application>
115  ***/
116
117 #define APP_NAME "BridgeWait"
118 #define DEFAULT_BRIDGE_NAME "default"
119
120 static struct ao2_container *wait_bridge_wrappers;
121
122 struct wait_bridge_wrapper {
123         struct ast_bridge *bridge;     /*!< Bridge being wrapped by this wrapper */
124         char name[0];                  /*!< Name of the holding bridge wrapper */
125 };
126
127 static void wait_bridge_wrapper_destructor(void *obj)
128 {
129         struct wait_bridge_wrapper *wrapper = obj;
130         if (wrapper->bridge) {
131                 ast_bridge_destroy(wrapper->bridge);
132         }
133 }
134
135 static struct wait_bridge_wrapper *wait_bridge_wrapper_find_by_name(const char *bridge_name)
136 {
137         return ao2_find(wait_bridge_wrappers, bridge_name, OBJ_KEY);
138 }
139
140 static int wait_bridge_hash_fn(const void *obj, const int flags)
141 {
142         const struct wait_bridge_wrapper *entry;
143         const char *key;
144
145         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
146         case OBJ_KEY:
147                 key = obj;
148                 return ast_str_hash(key);
149         case OBJ_POINTER:
150                 entry = obj;
151                 return ast_str_hash(entry->name);
152         default:
153                 /* Hash can only work on something with a full key. */
154                 ast_assert(0);
155                 return 0;
156         }
157 }
158
159 static int wait_bridge_sort_fn(const void *obj_left, const void *obj_right, const int flags)
160 {
161         const struct wait_bridge_wrapper *left = obj_left;
162         const struct wait_bridge_wrapper *right = obj_right;
163         const char *right_key = obj_right;
164         int cmp;
165
166         switch (flags & (OBJ_POINTER | OBJ_KEY | OBJ_PARTIAL_KEY)) {
167         case OBJ_POINTER:
168                 right_key = right->name;
169                 /* Fall through */
170         case OBJ_KEY:
171                 cmp = strcmp(left->name, right_key);
172                 break;
173         case OBJ_PARTIAL_KEY:
174                 cmp = strncmp(left->name, right_key, strlen(right_key));
175                 break;
176         default:
177                 /* Sort can only work on something with a full or partial key. */
178                 ast_assert(0);
179                 cmp = 0;
180                 break;
181         }
182         return cmp;
183 }
184
185 enum bridgewait_flags {
186         MUXFLAG_MOHCLASS = (1 << 0),
187         MUXFLAG_ENTERTAINMENT = (1 << 1),
188         MUXFLAG_TIMEOUT = (1 << 2),
189 };
190
191 enum bridgewait_args {
192         OPT_ARG_ENTERTAINMENT,
193         OPT_ARG_MOHCLASS,
194         OPT_ARG_TIMEOUT,
195         OPT_ARG_ARRAY_SIZE, /* Always the last element of the enum */
196 };
197
198 AST_APP_OPTIONS(bridgewait_opts, {
199         AST_APP_OPTION_ARG('e', MUXFLAG_ENTERTAINMENT, OPT_ARG_ENTERTAINMENT),
200         AST_APP_OPTION_ARG('m', MUXFLAG_MOHCLASS, OPT_ARG_MOHCLASS),
201         AST_APP_OPTION_ARG('S', MUXFLAG_TIMEOUT, OPT_ARG_TIMEOUT),
202 });
203
204 static int bridgewait_timeout_callback(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
205 {
206         ast_verb(3, "Channel %s timed out.\n", ast_channel_name(bridge_channel->chan));
207         ast_bridge_channel_leave_bridge(bridge_channel, BRIDGE_CHANNEL_STATE_END);
208         return -1;
209 }
210
211 static int apply_option_timeout(struct ast_bridge_features *features, char *duration_arg)
212 {
213         unsigned int duration;
214
215         if (ast_strlen_zero(duration_arg)) {
216                 ast_log(LOG_ERROR, "Timeout option 'S': No value provided.\n");
217                 return -1;
218         }
219         if (sscanf(duration_arg, "%u", &duration) != 1 || duration == 0) {
220                 ast_log(LOG_ERROR, "Timeout option 'S': Invalid value provided '%s'.\n",
221                         duration_arg);
222                 return -1;
223         }
224
225         duration *= 1000;
226         if (ast_bridge_interval_hook(features, 0, duration, bridgewait_timeout_callback,
227                 NULL, NULL, AST_BRIDGE_HOOK_REMOVE_ON_PULL)) {
228                 ast_log(LOG_ERROR, "Timeout option 'S': Could not create timer.\n");
229                 return -1;
230         }
231
232         return 0;
233 }
234
235 static int apply_option_moh(struct ast_channel *chan, const char *class_arg)
236 {
237         return ast_channel_set_bridge_role_option(chan, "holding_participant", "moh_class", class_arg);
238 }
239
240 static int apply_option_entertainment(struct ast_channel *chan, const char *entertainment_arg)
241 {
242         char entertainment = entertainment_arg[0];
243
244         switch (entertainment) {
245         case 'm':
246                 return ast_channel_set_bridge_role_option(chan, "holding_participant", "idle_mode", "musiconhold");
247         case 'r':
248                 return ast_channel_set_bridge_role_option(chan, "holding_participant", "idle_mode", "ringing");
249         case 's':
250                 return ast_channel_set_bridge_role_option(chan, "holding_participant", "idle_mode", "silence");
251         case 'h':
252                 return ast_channel_set_bridge_role_option(chan, "holding_participant", "idle_mode", "hold");
253         case 'n':
254                 return ast_channel_set_bridge_role_option(chan, "holding_participant", "idle_mode", "none");
255         default:
256                 ast_log(LOG_ERROR, "Invalid argument for BridgeWait entertainment '%s'\n", entertainment_arg);
257                 return -1;
258         }
259 }
260
261 enum wait_bridge_roles {
262         ROLE_PARTICIPANT = 0,
263         ROLE_ANNOUNCER,
264         ROLE_INVALID,
265 };
266
267 static int process_options(struct ast_channel *chan, struct ast_flags *flags, char **opts, struct ast_bridge_features *features, enum wait_bridge_roles role)
268 {
269         if (ast_test_flag(flags, MUXFLAG_TIMEOUT)) {
270                 if (apply_option_timeout(features, opts[OPT_ARG_TIMEOUT])) {
271                         return -1;
272                 }
273         }
274
275         switch (role) {
276         case ROLE_PARTICIPANT:
277                 if (ast_channel_add_bridge_role(chan, "holding_participant")) {
278                         return -1;
279                 }
280
281                 if (ast_test_flag(flags, MUXFLAG_MOHCLASS)) {
282                         if (apply_option_moh(chan, opts[OPT_ARG_MOHCLASS])) {
283                                 return -1;
284                         }
285                 }
286
287                 if (ast_test_flag(flags, MUXFLAG_ENTERTAINMENT)) {
288                         if (apply_option_entertainment(chan, opts[OPT_ARG_ENTERTAINMENT])) {
289                                 return -1;
290                         }
291                 }
292
293                 break;
294         case ROLE_ANNOUNCER:
295                 if (ast_channel_add_bridge_role(chan, "announcer")) {
296                         return -1;
297                 }
298                 break;
299         case ROLE_INVALID:
300                 ast_assert(0);
301                 return -1;
302         }
303
304         return 0;
305 }
306
307 /*!
308  * \internal
309  * \since 12.0.0
310  * \brief Allocate a new holding bridge wrapper with the given bridge name and bridge ID.
311  *
312  * \param bridge_name name of the bridge wrapper
313  * \param bridge the bridge being wrapped
314  *
315  * \retval Pointer to the newly allocated holding bridge wrapper
316  * \retval NULL if allocation failed. The bridge will be destroyed if this function fails.
317  */
318 static struct wait_bridge_wrapper *wait_bridge_wrapper_alloc(const char *bridge_name, struct ast_bridge *bridge)
319 {
320         struct wait_bridge_wrapper *bridge_wrapper;
321
322         bridge_wrapper = ao2_alloc_options(sizeof(*bridge_wrapper) + strlen(bridge_name) + 1,
323                 wait_bridge_wrapper_destructor, AO2_ALLOC_OPT_LOCK_NOLOCK);
324
325         if (!bridge_wrapper) {
326                 ast_bridge_destroy(bridge);
327                 return NULL;
328         }
329
330         strcpy(bridge_wrapper->name, bridge_name);
331         bridge_wrapper->bridge = bridge;
332
333         if (!ao2_link(wait_bridge_wrappers, bridge_wrapper)) {
334                 ao2_cleanup(bridge_wrapper);
335                 return NULL;
336         }
337
338         return bridge_wrapper;
339 }
340
341 static struct wait_bridge_wrapper *get_wait_bridge_wrapper(const char *bridge_name)
342 {
343         struct wait_bridge_wrapper * wrapper;
344         struct ast_bridge *bridge = NULL;
345
346         SCOPED_AO2LOCK(lock, wait_bridge_wrappers);
347
348         if ((wrapper = wait_bridge_wrapper_find_by_name(bridge_name))) {
349                 return wrapper;
350         }
351
352         /*
353          * Holding bridges can allow local channel move/swap
354          * optimization to the bridge.  However, we cannot allow it for
355          * this holding bridge because the call will lose the channel
356          * roles and dialplan location as a result.
357          */
358         bridge = ast_bridge_base_new(AST_BRIDGE_CAPABILITY_HOLDING,
359                 AST_BRIDGE_FLAG_MERGE_INHIBIT_TO | AST_BRIDGE_FLAG_MERGE_INHIBIT_FROM
360                 | AST_BRIDGE_FLAG_SWAP_INHIBIT_TO | AST_BRIDGE_FLAG_SWAP_INHIBIT_FROM
361                 | AST_BRIDGE_FLAG_TRANSFER_PROHIBITED | AST_BRIDGE_FLAG_DISSOLVE_EMPTY);
362
363         if (!bridge) {
364                 return NULL;
365         }
366
367         /* The bridge reference is unconditionally passed. */
368         return wait_bridge_wrapper_alloc(bridge_name, bridge);
369 }
370
371 /*!
372  * \internal
373  * \since 12.0.0
374  * \brief If we are down to the last reference of a wrapper and it's still contained within the list, remove it from the list.
375  *
376  * \param wrapper reference to wait bridge wrapper being checked for list culling - will be cleared on exit
377  */
378 static void wait_wrapper_removal(struct wait_bridge_wrapper *wrapper)
379 {
380         if (!wrapper) {
381                 return;
382         }
383
384         ao2_lock(wait_bridge_wrappers);
385         if (ao2_ref(wrapper, 0) == 2) {
386                 /* Either we have the only real reference or else wrapper isn't in the container anyway. */
387                 ao2_unlink(wait_bridge_wrappers, wrapper);
388         }
389         ao2_unlock(wait_bridge_wrappers);
390
391         ao2_cleanup(wrapper);
392 }
393
394 /*!
395  * \internal
396  * \since 12.0.0
397  * \brief Application callback for the bridgewait application
398  *
399  * \param chan channel running the application
400  * \param data Arguments to the application
401  *
402  * \retval 0 Ran successfully and the call didn't hang up
403  * \retval -1 Failed or the call was hung up by the time the channel exited the holding bridge
404  */
405 static enum wait_bridge_roles validate_role(const char *role)
406 {
407         if (!strcmp(role, "participant")) {
408                 return ROLE_PARTICIPANT;
409         } else if (!strcmp(role, "announcer")) {
410                 return ROLE_ANNOUNCER;
411         } else {
412                 return ROLE_INVALID;
413         }
414 }
415
416 static int bridgewait_exec(struct ast_channel *chan, const char *data)
417 {
418         char *bridge_name = DEFAULT_BRIDGE_NAME;
419         struct ast_bridge_features chan_features;
420         struct ast_flags flags = { 0 };
421         char *parse;
422         int bridge_join_failed = 0;
423         enum wait_bridge_roles role = ROLE_PARTICIPANT;
424         char *opts[OPT_ARG_ARRAY_SIZE] = { NULL, };
425
426         AST_DECLARE_APP_ARGS(args,
427                 AST_APP_ARG(name);
428                 AST_APP_ARG(role);
429                 AST_APP_ARG(options);
430                 AST_APP_ARG(other);             /* Any remaining unused arguments */
431         );
432
433         parse = ast_strdupa(data);
434         AST_STANDARD_APP_ARGS(args, parse);
435
436         if (!ast_strlen_zero(args.name)) {
437                 bridge_name = args.name;
438         }
439
440         if (!ast_strlen_zero(args.role)) {
441                 role = validate_role(args.role);
442                 if (role == ROLE_INVALID) {
443                         ast_log(LOG_ERROR, "Requested waiting bridge role '%s' is invalid.\n", args.role);
444                         return -1;
445                 }
446         }
447
448         if (ast_bridge_features_init(&chan_features)) {
449                 ast_bridge_features_cleanup(&chan_features);
450                 ast_log(LOG_ERROR, "'%s' failed to enter the waiting bridge - could not set up channel features\n",
451                         ast_channel_name(chan));
452                 return -1;
453         }
454
455         if (args.options) {
456                 ast_app_parse_options(bridgewait_opts, &flags, opts, args.options);
457         }
458
459         /* Answer the channel if needed */
460         if (ast_channel_state(chan) != AST_STATE_UP) {
461                 ast_answer(chan);
462         }
463
464         if (process_options(chan, &flags, opts, &chan_features, role)) {
465                 ast_bridge_features_cleanup(&chan_features);
466                 return -1;
467         }
468
469         for (;;) {
470                 RAII_VAR(struct wait_bridge_wrapper *, bridge_wrapper, get_wait_bridge_wrapper(bridge_name), wait_wrapper_removal);
471
472                 if (!bridge_wrapper) {
473                         ast_log(LOG_WARNING, "Failed to find or create waiting bridge '%s' for '%s'.\n", bridge_name, ast_channel_name(chan));
474                         bridge_join_failed = 1;
475                         break;
476                 }
477
478                 ast_verb(3, "%s is entering waiting bridge %s:%s\n", ast_channel_name(chan), bridge_name, bridge_wrapper->bridge->uniqueid);
479
480                 if (ast_bridge_join(bridge_wrapper->bridge, chan, NULL, &chan_features, NULL, 0)) {
481                         /* It's possible for a holding bridge to vanish out from under us since we can't lock it.
482                          * Unlink the wrapper and then loop if the bridge we try to enter is dissolved. */
483                         ast_verb(3, "Waiting bridge '%s:%s' is no longer joinable. Creating new bridge and trying again.\n",
484                                 bridge_name, bridge_wrapper->bridge->uniqueid);
485                         ao2_unlink(wait_bridge_wrappers, bridge_wrapper);
486                         continue;
487                 }
488
489                 break;
490         }
491
492         ast_bridge_features_cleanup(&chan_features);
493
494         if (bridge_join_failed) {
495                 return -1;
496         }
497
498         return ast_check_hangup_locked(chan) ? -1 : 0;
499 }
500
501 static int unload_module(void)
502 {
503         ao2_cleanup(wait_bridge_wrappers);
504
505         return ast_unregister_application(APP_NAME);
506 }
507
508 static int load_module(void)
509 {
510         wait_bridge_wrappers = ao2_container_alloc_hash(
511                 AO2_ALLOC_OPT_LOCK_MUTEX, AO2_CONTAINER_ALLOC_OPT_DUPS_REJECT,
512                 37, wait_bridge_hash_fn, wait_bridge_sort_fn, NULL);
513
514         if (!wait_bridge_wrappers) {
515                 return -1;
516         }
517
518         return ast_register_application_xml(APP_NAME, bridgewait_exec);
519 }
520
521 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Place the channel into a holding bridge application");