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