Fix several interrelated issues dealing with the holding bridge technology.
[asterisk/asterisk.git] / main / features.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2012, Digium, Inc.
5  * Copyright (C) 2012, Russell Bryant
6  *
7  * Mark Spencer <markster@digium.com>
8  *
9  * See http://www.asterisk.org for more information about
10  * the Asterisk project. Please do not directly contact
11  * any of the maintainers of this project for assistance;
12  * the project provides a web site, mailing lists and IRC
13  * channels for your use.
14  *
15  * This program is free software, distributed under the terms of
16  * the GNU General Public License Version 2. See the LICENSE file
17  * at the top of the source tree.
18  */
19
20 /*! \file
21  *
22  * \brief Routines implementing call features as call pickup, parking and transfer
23  *
24  * \author Mark Spencer <markster@digium.com>
25  */
26
27 /*! \li \ref features.c uses the configuration file \ref features.conf
28  * \addtogroup configuration_file Configuration Files
29  */
30
31 /*!
32  * \page features.conf features.conf
33  * \verbinclude features.conf.sample
34  */
35
36 /*** MODULEINFO
37         <support_level>core</support_level>
38  ***/
39
40 #include "asterisk.h"
41
42 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
43
44 #include "asterisk/_private.h"
45
46 #include <pthread.h>
47 #include <signal.h>
48 #include <sys/time.h>
49 #include <sys/signal.h>
50 #include <netinet/in.h>
51
52 #include "asterisk/lock.h"
53 #include "asterisk/file.h"
54 #include "asterisk/channel.h"
55 #include "asterisk/pbx.h"
56 #include "asterisk/causes.h"
57 #include "asterisk/module.h"
58 #include "asterisk/translate.h"
59 #include "asterisk/app.h"
60 #include "asterisk/say.h"
61 #include "asterisk/features.h"
62 #include "asterisk/musiconhold.h"
63 #include "asterisk/config.h"
64 #include "asterisk/cli.h"
65 #include "asterisk/manager.h"
66 #include "asterisk/utils.h"
67 #include "asterisk/adsi.h"
68 #include "asterisk/devicestate.h"
69 #include "asterisk/monitor.h"
70 #include "asterisk/audiohook.h"
71 #include "asterisk/global_datastores.h"
72 #include "asterisk/astobj2.h"
73 #include "asterisk/test.h"
74 #include "asterisk/bridge.h"
75 #include "asterisk/bridge_features.h"
76 #include "asterisk/bridge_basic.h"
77 #include "asterisk/bridge_after.h"
78 #include "asterisk/stasis.h"
79 #include "asterisk/stasis_channels.h"
80 #include "asterisk/features_config.h"
81
82 /*** DOCUMENTATION
83         <application name="Bridge" language="en_US">
84                 <synopsis>
85                         Bridge two channels.
86                 </synopsis>
87                 <syntax>
88                         <parameter name="channel" required="true">
89                                 <para>The current channel is bridged to the specified <replaceable>channel</replaceable>.</para>
90                         </parameter>
91                         <parameter name="options">
92                                 <optionlist>
93                                         <option name="p">
94                                                 <para>Play a courtesy tone to <replaceable>channel</replaceable>.</para>
95                                         </option>
96                                         <option name="F" argsep="^">
97                                                 <argument name="context" required="false" />
98                                                 <argument name="exten" required="false" />
99                                                 <argument name="priority" required="true" />
100                                                 <para>When the bridger hangs up, transfer the <emphasis>bridged</emphasis> party
101                                                 to the specified destination and <emphasis>start</emphasis> execution at that location.</para>
102                                                 <note>
103                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
104                                                         prefixed with one or two underbars ('_').</para>
105                                                 </note>
106                                                 <note>
107                                                         <para>This option will override the 'x' option</para>
108                                                 </note>
109                                         </option>
110                                         <option name="F">
111                                                 <para>When the bridger hangs up, transfer the <emphasis>bridged</emphasis> party
112                                                 to the next priority of the current extension and <emphasis>start</emphasis> execution
113                                                 at that location.</para>
114                                                 <note>
115                                                         <para>Any channel variables you want the called channel to inherit from the caller channel must be
116                                                         prefixed with one or two underbars ('_').</para>
117                                                 </note>
118                                                 <note>
119                                                         <para>Using this option from a Macro() or GoSub() might not make sense as there would be no return points.</para>
120                                                 </note>
121                                                 <note>
122                                                         <para>This option will override the 'x' option</para>
123                                                 </note>
124                                         </option>
125
126                                         <option name="h">
127                                                 <para>Allow the called party to hang up by sending the
128                                                 <replaceable>*</replaceable> DTMF digit.</para>
129                                         </option>
130                                         <option name="H">
131                                                 <para>Allow the calling party to hang up by pressing the
132                                                 <replaceable>*</replaceable> DTMF digit.</para>
133                                         </option>
134                                         <option name="k">
135                                                 <para>Allow the called party to enable parking of the call by sending
136                                                 the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
137                                         </option>
138                                         <option name="K">
139                                                 <para>Allow the calling party to enable parking of the call by sending
140                                                  the DTMF sequence defined for call parking in <filename>features.conf</filename>.</para>
141                                         </option>
142                                         <option name="L(x[:y][:z])">
143                                                 <para>Limit the call to <replaceable>x</replaceable> ms. Play a warning
144                                                 when <replaceable>y</replaceable> ms are left. Repeat the warning every
145                                                 <replaceable>z</replaceable> ms. The following special variables can be
146                                                 used with this option:</para>
147                                                 <variablelist>
148                                                         <variable name="LIMIT_PLAYAUDIO_CALLER">
149                                                                 <para>Play sounds to the caller. yes|no (default yes)</para>
150                                                         </variable>
151                                                         <variable name="LIMIT_PLAYAUDIO_CALLEE">
152                                                                 <para>Play sounds to the callee. yes|no</para>
153                                                         </variable>
154                                                         <variable name="LIMIT_TIMEOUT_FILE">
155                                                                 <para>File to play when time is up.</para>
156                                                         </variable>
157                                                         <variable name="LIMIT_CONNECT_FILE">
158                                                                 <para>File to play when call begins.</para>
159                                                         </variable>
160                                                         <variable name="LIMIT_WARNING_FILE">
161                                                                 <para>File to play as warning if <replaceable>y</replaceable> is
162                                                                 defined. The default is to say the time remaining.</para>
163                                                         </variable>
164                                                 </variablelist>
165                                         </option>
166                                         <option name="S(x)">
167                                                 <para>Hang up the call after <replaceable>x</replaceable> seconds *after* the called party has answered the call.</para>
168                                         </option>
169                                         <option name="t">
170                                                 <para>Allow the called party to transfer the calling party by sending the
171                                                 DTMF sequence defined in <filename>features.conf</filename>.</para>
172                                         </option>
173                                         <option name="T">
174                                                 <para>Allow the calling party to transfer the called party by sending the
175                                                 DTMF sequence defined in <filename>features.conf</filename>.</para>
176                                         </option>
177                                         <option name="w">
178                                                 <para>Allow the called party to enable recording of the call by sending
179                                                 the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
180                                         </option>
181                                         <option name="W">
182                                                 <para>Allow the calling party to enable recording of the call by sending
183                                                 the DTMF sequence defined for one-touch recording in <filename>features.conf</filename>.</para>
184                                         </option>
185                                         <option name="x">
186                                                 <para>Cause the called party to be hung up after the bridge, instead of being
187                                                 restarted in the dialplan.</para>
188                                         </option>
189                                 </optionlist>
190                         </parameter>
191                 </syntax>
192                 <description>
193                         <para>Allows the ability to bridge two channels via the dialplan.</para>
194                         <para>This application sets the following channel variable upon completion:</para>
195                         <variablelist>
196                                 <variable name="BRIDGERESULT">
197                                         <para>The result of the bridge attempt as a text string.</para>
198                                         <value name="SUCCESS" />
199                                         <value name="FAILURE" />
200                                         <value name="LOOP" />
201                                         <value name="NONEXISTENT" />
202                                         <value name="INCOMPATIBLE" />
203                                 </variable>
204                         </variablelist>
205                 </description>
206         </application>
207         <manager name="Bridge" language="en_US">
208                 <synopsis>
209                         Bridge two channels already in the PBX.
210                 </synopsis>
211                 <syntax>
212                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
213                         <parameter name="Channel1" required="true">
214                                 <para>Channel to Bridge to Channel2.</para>
215                         </parameter>
216                         <parameter name="Channel2" required="true">
217                                 <para>Channel to Bridge to Channel1.</para>
218                         </parameter>
219                         <parameter name="Tone">
220                                 <para>Play courtesy tone to Channel 2.</para>
221                                 <enumlist>
222                                         <enum name="no" />
223                                         <enum name="Channel1" />
224                                         <enum name="Channel2" />
225                                         <enum name="Both" />
226                                 </enumlist>
227                         </parameter>
228                 </syntax>
229                 <description>
230                         <para>Bridge together two channels already in the PBX.</para>
231                 </description>
232         </manager>
233  ***/
234
235 typedef enum {
236         FEATURE_INTERPRET_DETECT, /* Used by ast_feature_detect */
237         FEATURE_INTERPRET_DO,     /* Used by feature_interpret */
238         FEATURE_INTERPRET_CHECK,  /* Used by feature_check */
239 } feature_interpret_op;
240
241 struct ast_dial_features {
242         /*! Channel's feature flags. */
243         struct ast_flags my_features;
244         /*! Bridge peer's feature flags. */
245         struct ast_flags peer_features;
246 };
247
248 static void *dial_features_duplicate(void *data)
249 {
250         struct ast_dial_features *df = data, *df_copy;
251
252         if (!(df_copy = ast_calloc(1, sizeof(*df)))) {
253                 return NULL;
254         }
255
256         memcpy(df_copy, df, sizeof(*df));
257
258         return df_copy;
259 }
260
261 static const struct ast_datastore_info dial_features_info = {
262         .type = "dial-features",
263         .destroy = ast_free_ptr,
264         .duplicate = dial_features_duplicate,
265 };
266
267 /*!
268  * \internal
269  * \brief Set the features datastore if it doesn't exist.
270  *
271  * \param chan Channel to add features datastore
272  * \param my_features The channel's feature flags
273  * \param peer_features The channel's bridge peer feature flags
274  *
275  * \retval TRUE if features datastore already existed.
276  */
277 static int add_features_datastore(struct ast_channel *chan, const struct ast_flags *my_features, const struct ast_flags *peer_features)
278 {
279         struct ast_datastore *datastore;
280         struct ast_dial_features *dialfeatures;
281
282         ast_channel_lock(chan);
283         datastore = ast_channel_datastore_find(chan, &dial_features_info, NULL);
284         ast_channel_unlock(chan);
285         if (datastore) {
286                 /* Already exists. */
287                 return 1;
288         }
289
290         /* Create a new datastore with specified feature flags. */
291         datastore = ast_datastore_alloc(&dial_features_info, NULL);
292         if (!datastore) {
293                 ast_log(LOG_WARNING, "Unable to create channel features datastore.\n");
294                 return 0;
295         }
296         dialfeatures = ast_calloc(1, sizeof(*dialfeatures));
297         if (!dialfeatures) {
298                 ast_log(LOG_WARNING, "Unable to allocate memory for feature flags.\n");
299                 ast_datastore_free(datastore);
300                 return 0;
301         }
302         ast_copy_flags(&dialfeatures->my_features, my_features, AST_FLAGS_ALL);
303         ast_copy_flags(&dialfeatures->peer_features, peer_features, AST_FLAGS_ALL);
304         datastore->inheritance = DATASTORE_INHERIT_FOREVER;
305         datastore->data = dialfeatures;
306         ast_channel_lock(chan);
307         ast_channel_datastore_add(chan, datastore);
308         ast_channel_unlock(chan);
309         return 0;
310 }
311
312 struct ast_bridge_thread_obj
313 {
314         struct ast_bridge_config bconfig;
315         struct ast_channel *chan;
316         struct ast_channel *peer;
317         struct ast_callid *callid;                             /*<! callid pointer (Only used to bind thread) */
318         unsigned int return_to_pbx:1;
319 };
320
321 static const struct ast_datastore_info channel_app_data_datastore = {
322         .type = "Channel appdata datastore",
323         .destroy = ast_free_ptr,
324 };
325
326 /*
327  * \internal
328  * \brief Get the extension for a given builtin feature
329  *
330  * \pre expects features_lock to be readlocked
331  *
332  * \retval 0 success
333  * \retval non-zero failiure
334  */
335 static int builtin_feature_get_exten(struct ast_channel *chan, const char *feature_name,
336                 char *buf, size_t len)
337 {
338         SCOPED_CHANNELLOCK(lock, chan);
339
340         return ast_get_builtin_feature(chan, feature_name, buf, len);
341 }
342
343 static void set_config_flags(struct ast_channel *chan, struct ast_bridge_config *config)
344 {
345         ast_clear_flag(config, AST_FLAGS_ALL);
346
347         if (ast_test_flag(&config->features_caller, AST_FEATURE_DTMF_MASK)) {
348                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
349         }
350         if (ast_test_flag(&config->features_callee, AST_FEATURE_DTMF_MASK)) {
351                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
352         }
353
354         if (!(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
355                 RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
356
357                 ast_channel_lock(chan);
358                 applicationmap = ast_get_chan_applicationmap(chan);
359                 ast_channel_unlock(chan);
360
361                 if (!applicationmap) {
362                         return;
363                 }
364
365                 /* If an applicationmap exists for this channel at all, then the channel needs the DTMF flag set */
366                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
367         }
368 }
369
370 void ast_channel_log(char *title, struct ast_channel *chan);
371
372 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
373 {
374         ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long) chan);
375         ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
376                 ast_channel_name(chan), ast_channel_appl(chan), ast_channel_data(chan),
377                 ast_channel_context(chan), ast_channel_exten(chan), ast_channel_priority(chan));
378         ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
379                 ast_channel_accountcode(chan), ast_channel_dialcontext(chan), ast_channel_amaflags(chan),
380                 ast_channel_macrocontext(chan), ast_channel_macroexten(chan), ast_channel_macropriority(chan));
381         ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; uniqueID: %s; linkedID:%s\n",
382                 ast_channel_masq(chan), ast_channel_masqr(chan),
383                 ast_channel_uniqueid(chan), ast_channel_linkedid(chan));
384         if (ast_channel_masqr(chan)) {
385                 ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
386                         ast_channel_name(ast_channel_masqr(chan)), ast_channel_cdr(ast_channel_masqr(chan)));
387         }
388
389         ast_log(LOG_NOTICE, "===== done ====\n");
390 }
391
392 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
393 {
394         const char *feature;
395
396         if (ast_strlen_zero(features)) {
397                 return;
398         }
399
400         for (feature = features; *feature; feature++) {
401                 struct ast_flags *party;
402
403                 if (isupper(*feature)) {
404                         party = &config->features_caller;
405                 } else {
406                         party = &config->features_callee;
407                 }
408
409                 switch (tolower(*feature)) {
410                 case 't' :
411                         ast_set_flag(party, AST_FEATURE_REDIRECT);
412                         break;
413                 case 'k' :
414                         ast_set_flag(party, AST_FEATURE_PARKCALL);
415                         break;
416                 case 'h' :
417                         ast_set_flag(party, AST_FEATURE_DISCONNECT);
418                         break;
419                 case 'w' :
420                         ast_set_flag(party, AST_FEATURE_AUTOMON);
421                         break;
422                 case 'x' :
423                         ast_set_flag(party, AST_FEATURE_AUTOMIXMON);
424                         break;
425                 default :
426                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
427                         break;
428                 }
429         }
430 }
431
432 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
433 {
434         if (add_features_datastore(caller, &config->features_caller, &config->features_callee)) {
435                 /*
436                  * If we don't return here, then when we do a builtin_atxfer we
437                  * will copy the disconnect flags over from the atxfer to the
438                  * callee (Party C).
439                  */
440                 return;
441         }
442
443         add_features_datastore(callee, &config->features_callee, &config->features_caller);
444 }
445
446 static void clear_dialed_interfaces(struct ast_channel *chan)
447 {
448         struct ast_datastore *di_datastore;
449
450         ast_channel_lock(chan);
451         if ((di_datastore = ast_channel_datastore_find(chan, &dialed_interface_info, NULL))) {
452                 if (option_debug) {
453                         ast_log(LOG_DEBUG, "Removing dialed interfaces datastore on %s since we're bridging\n", ast_channel_name(chan));
454                 }
455                 if (!ast_channel_datastore_remove(chan, di_datastore)) {
456                         ast_datastore_free(di_datastore);
457                 }
458         }
459         ast_channel_unlock(chan);
460 }
461
462 /*!
463  * \internal
464  * \brief Helper to add a builtin DTMF feature hook to the features struct.
465  * \since 12.0.0
466  *
467  * \param features Bridge features to setup.
468  * \param chan Get features from this channel.
469  * \param flags Feature flags on the channel.
470  * \param feature_flag Feature flag to test.
471  * \param feature_name features.conf name of feature.
472  * \param feature_bridge Bridge feature enum to get hook callback.
473  *
474  * \retval 0 on success.
475  * \retval -1 on error.
476  */
477 static int builtin_features_helper(struct ast_bridge_features *features, struct ast_channel *chan,
478         struct ast_flags *flags, unsigned int feature_flag, const char *feature_name, enum ast_bridge_builtin_feature feature_bridge)
479 {
480         char dtmf[AST_FEATURE_MAX_LEN];
481         int res;
482
483         res = 0;
484         if (ast_test_flag(flags, feature_flag)
485                 && !builtin_feature_get_exten(chan, feature_name, dtmf, sizeof(dtmf))
486                 && !ast_strlen_zero(dtmf)) {
487                 res = ast_bridge_features_enable(features, feature_bridge, dtmf, NULL, NULL,
488                         AST_BRIDGE_HOOK_REMOVE_ON_PULL | AST_BRIDGE_HOOK_REMOVE_ON_PERSONALITY_CHANGE);
489                 if (res) {
490                         ast_log(LOG_ERROR, "Channel %s: Requested DTMF feature %s not available.\n",
491                                 ast_channel_name(chan), feature_name);
492                 }
493         }
494
495         return res;
496 }
497
498 /*!
499  * \internal
500  * \brief Setup bridge builtin features.
501  * \since 12.0.0
502  *
503  * \param features Bridge features to setup.
504  * \param chan Get features from this channel.
505  *
506  * \retval 0 on success.
507  * \retval -1 on error.
508  */
509 static int setup_bridge_features_builtin(struct ast_bridge_features *features, struct ast_channel *chan)
510 {
511         struct ast_flags *flags;
512         int res;
513
514         ast_channel_lock(chan);
515         flags = ast_bridge_features_ds_get(chan);
516         ast_channel_unlock(chan);
517         if (!flags) {
518                 return 0;
519         }
520
521         res = 0;
522         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "blindxfer", AST_BRIDGE_BUILTIN_BLINDTRANSFER);
523         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_REDIRECT, "atxfer", AST_BRIDGE_BUILTIN_ATTENDEDTRANSFER);
524         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_DISCONNECT, "disconnect", AST_BRIDGE_BUILTIN_HANGUP);
525         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_PARKCALL, "parkcall", AST_BRIDGE_BUILTIN_PARKCALL);
526         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMON, "automon", AST_BRIDGE_BUILTIN_AUTOMON);
527         res |= builtin_features_helper(features, chan, flags, AST_FEATURE_AUTOMIXMON, "automixmon", AST_BRIDGE_BUILTIN_AUTOMIXMON);
528
529         return res ? -1 : 0;
530 }
531
532 struct dynamic_dtmf_hook_run {
533         /*! Offset into app_name[] where the channel name that activated the hook starts. */
534         int activated_offset;
535         /*! Offset into app_name[] where the dynamic feature name starts. */
536         int feature_offset;
537         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
538         int moh_offset;
539         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
540         int app_args_offset;
541         /*! Application name to run. */
542         char app_name[0];
543 };
544
545 static void dynamic_dtmf_hook_callback(struct ast_bridge_channel *bridge_channel,
546         const void *payload, size_t payload_size)
547 {
548         struct ast_channel *chan = bridge_channel->chan;
549         const struct dynamic_dtmf_hook_run *run_data = payload;
550
551         pbx_builtin_setvar_helper(chan, "DYNAMIC_FEATURENAME",
552                 &run_data->app_name[run_data->feature_offset]);
553         pbx_builtin_setvar_helper(chan, "DYNAMIC_WHO_ACTIVATED",
554                 &run_data->app_name[run_data->activated_offset]);
555
556         ast_bridge_channel_run_app(bridge_channel, run_data->app_name,
557                 run_data->app_args_offset ? &run_data->app_name[run_data->app_args_offset] : NULL,
558                 run_data->moh_offset ? &run_data->app_name[run_data->moh_offset] : NULL);
559 }
560
561 struct dynamic_dtmf_hook_data {
562         /*! Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER) */
563         unsigned int flags;
564         /*! Offset into app_name[] where the dynamic feature name starts. */
565         int feature_offset;
566         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
567         int moh_offset;
568         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
569         int app_args_offset;
570         /*! Application name to run. */
571         char app_name[0];
572 };
573
574 /*!
575  * \internal
576  * \brief Activated dynamic DTMF feature hook.
577  * \since 12.0.0
578  *
579  * \param bridge_channel Channel executing the feature
580  * \param hook_pvt Private data passed in when the hook was created
581  *
582  * \retval 0 Keep the callback hook.
583  * \retval -1 Remove the callback hook.
584  */
585 static int dynamic_dtmf_hook_trip(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
586 {
587         struct dynamic_dtmf_hook_data *pvt = hook_pvt;
588         struct dynamic_dtmf_hook_run *run_data;
589         const char *activated_name;
590         size_t len_name;
591         size_t len_args;
592         size_t len_moh;
593         size_t len_feature;
594         size_t len_activated;
595         size_t len_data;
596
597         /* Determine lengths of things. */
598         len_name = strlen(pvt->app_name) + 1;
599         len_args = pvt->app_args_offset ? strlen(&pvt->app_name[pvt->app_args_offset]) + 1 : 0;
600         len_moh = pvt->moh_offset ? strlen(&pvt->app_name[pvt->moh_offset]) + 1 : 0;
601         len_feature = strlen(&pvt->app_name[pvt->feature_offset]) + 1;
602         ast_channel_lock(bridge_channel->chan);
603         activated_name = ast_strdupa(ast_channel_name(bridge_channel->chan));
604         ast_channel_unlock(bridge_channel->chan);
605         len_activated = strlen(activated_name) + 1;
606         len_data = sizeof(*run_data) + len_name + len_args + len_moh + len_feature + len_activated;
607
608         /* Fill in dynamic feature run hook data. */
609         run_data = ast_alloca(len_data);
610         run_data->app_args_offset = len_args ? len_name : 0;
611         run_data->moh_offset = len_moh ? len_name + len_args : 0;
612         run_data->feature_offset = len_name + len_args + len_moh;
613         run_data->activated_offset = len_name + len_args + len_moh + len_feature;
614         strcpy(run_data->app_name, pvt->app_name);/* Safe */
615         if (len_args) {
616                 strcpy(&run_data->app_name[run_data->app_args_offset],
617                         &pvt->app_name[pvt->app_args_offset]);/* Safe */
618         }
619         if (len_moh) {
620                 strcpy(&run_data->app_name[run_data->moh_offset],
621                         &pvt->app_name[pvt->moh_offset]);/* Safe */
622         }
623         strcpy(&run_data->app_name[run_data->feature_offset],
624                 &pvt->app_name[pvt->feature_offset]);/* Safe */
625         strcpy(&run_data->app_name[run_data->activated_offset], activated_name);/* Safe */
626
627         if (ast_test_flag(pvt, AST_FEATURE_FLAG_ONPEER)) {
628                 ast_bridge_channel_write_callback(bridge_channel,
629                         AST_BRIDGE_CHANNEL_CB_OPTION_MEDIA,
630                         dynamic_dtmf_hook_callback, run_data, len_data);
631         } else {
632                 dynamic_dtmf_hook_callback(bridge_channel, run_data, len_data);
633         }
634         return 0;
635 }
636
637 /*!
638  * \internal
639  * \brief Add a dynamic DTMF feature hook to the bridge features.
640  * \since 12.0.0
641  *
642  * \param features Bridge features to setup.
643  * \param flags Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER).
644  * \param dtmf DTMF trigger sequence.
645  * \param feature_name Name of the dynamic feature.
646  * \param app_name Dialplan application name to run.
647  * \param app_args Dialplan application arguments. (Empty or NULL if no arguments)
648  * \param moh_class MOH class to play to peer. (Empty or NULL if no MOH played)
649  *
650  * \retval 0 on success.
651  * \retval -1 on error.
652  */
653 static int dynamic_dtmf_hook_add(struct ast_bridge_features *features, unsigned int flags, const char *dtmf, const char *feature_name, const char *app_name, const char *app_args, const char *moh_class)
654 {
655         struct dynamic_dtmf_hook_data *hook_data;
656         size_t len_name = strlen(app_name) + 1;
657         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
658         size_t len_moh = ast_strlen_zero(moh_class) ? 0 : strlen(moh_class) + 1;
659         size_t len_feature = strlen(feature_name) + 1;
660         size_t len_data = sizeof(*hook_data) + len_name + len_args + len_moh + len_feature;
661         int res;
662
663         /* Fill in application run hook data. */
664         hook_data = ast_malloc(len_data);
665         if (!hook_data) {
666                 return -1;
667         }
668         hook_data->flags = flags;
669         hook_data->app_args_offset = len_args ? len_name : 0;
670         hook_data->moh_offset = len_moh ? len_name + len_args : 0;
671         hook_data->feature_offset = len_name + len_args + len_moh;
672         strcpy(hook_data->app_name, app_name);/* Safe */
673         if (len_args) {
674                 strcpy(&hook_data->app_name[hook_data->app_args_offset], app_args);/* Safe */
675         }
676         if (len_moh) {
677                 strcpy(&hook_data->app_name[hook_data->moh_offset], moh_class);/* Safe */
678         }
679         strcpy(&hook_data->app_name[hook_data->feature_offset], feature_name);/* Safe */
680
681         res = ast_bridge_dtmf_hook(features, dtmf, dynamic_dtmf_hook_trip, hook_data,
682                 ast_free_ptr, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
683         if (res) {
684                 ast_free(hook_data);
685         }
686         return res;
687 }
688
689 static int setup_dynamic_feature(void *obj, void *arg, void *data, int flags)
690 {
691         struct ast_applicationmap_item *item = obj;
692         struct ast_bridge_features *features = arg;
693         int *res = data;
694
695         *res |= dynamic_dtmf_hook_add(features,
696                 item->activate_on_self ? AST_FEATURE_FLAG_ONSELF : AST_FEATURE_FLAG_ONPEER,
697                 item->dtmf, item->name, item->app, item->app_data, item->moh_class);
698
699         return 0;
700 }
701
702 /*!
703  * \internal
704  * \brief Setup bridge dynamic features.
705  * \since 12.0.0
706  *
707  * \param features Bridge features to setup.
708  * \param chan Get features from this channel.
709  *
710  * \retval 0 on success.
711  * \retval -1 on error.
712  */
713 static int setup_bridge_features_dynamic(struct ast_bridge_features *features, struct ast_channel *chan)
714 {
715         RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
716         int res = 0;
717
718         ast_channel_lock(chan);
719         applicationmap = ast_get_chan_applicationmap(chan);
720         ast_channel_unlock(chan);
721         if (!applicationmap) {
722                 return 0;
723         }
724
725         ao2_callback_data(applicationmap, 0, setup_dynamic_feature, features, &res);
726
727         return res;
728 }
729
730 /* BUGBUG this really should be made a private function of bridge_basic.c after struct ast_call_feature is made an ao2 object. */
731 int ast_bridge_channel_setup_features(struct ast_bridge_channel *bridge_channel)
732 {
733         int res = 0;
734
735         res |= setup_bridge_features_builtin(bridge_channel->features, bridge_channel->chan);
736         res |= setup_bridge_features_dynamic(bridge_channel->features, bridge_channel->chan);
737
738         return res;
739 }
740
741 static void bridge_config_set_limits_warning_values(struct ast_bridge_config *config, struct ast_bridge_features_limits *limits)
742 {
743         if (config->end_sound) {
744                 ast_string_field_set(limits, duration_sound, config->end_sound);
745         }
746
747         if (config->warning_sound) {
748                 ast_string_field_set(limits, warning_sound, config->warning_sound);
749         }
750
751         if (config->start_sound) {
752                 ast_string_field_set(limits, connect_sound, config->start_sound);
753         }
754
755         limits->frequency = config->warning_freq;
756         limits->warning = config->play_warning;
757 }
758
759 /*!
760  * \internal brief Setup limit hook structures on calls that need limits
761  *
762  * \param config ast_bridge_config which provides the limit data
763  * \param caller_limits pointer to an ast_bridge_features_limits struct which will store the caller side limits
764  * \param callee_limits pointer to an ast_bridge_features_limits struct which will store the callee side limits
765  */
766 static void bridge_config_set_limits(struct ast_bridge_config *config, struct ast_bridge_features_limits *caller_limits, struct ast_bridge_features_limits *callee_limits)
767 {
768         if (ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING)) {
769                 bridge_config_set_limits_warning_values(config, caller_limits);
770         }
771
772         if (ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING)) {
773                 bridge_config_set_limits_warning_values(config, callee_limits);
774         }
775
776         caller_limits->duration = config->timelimit;
777         callee_limits->duration = config->timelimit;
778 }
779
780 /*!
781  * \internal
782  * \brief Check if Monitor needs to be started on a channel.
783  * \since 12.0.0
784  *
785  * \param chan The bridge considers this channel the caller.
786  * \param peer The bridge considers this channel the callee.
787  *
788  * \return Nothing
789  */
790 static void bridge_check_monitor(struct ast_channel *chan, struct ast_channel *peer)
791 {
792         const char *value;
793         const char *monitor_args = NULL;
794         struct ast_channel *monitor_chan = NULL;
795
796         ast_channel_lock(chan);
797         value = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR");
798         if (!ast_strlen_zero(value)) {
799                 monitor_args = ast_strdupa(value);
800                 monitor_chan = chan;
801         }
802         ast_channel_unlock(chan);
803         if (!monitor_chan) {
804                 ast_channel_lock(peer);
805                 value = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR");
806                 if (!ast_strlen_zero(value)) {
807                         monitor_args = ast_strdupa(value);
808                         monitor_chan = peer;
809                 }
810                 ast_channel_unlock(peer);
811         }
812         if (monitor_chan) {
813                 struct ast_app *monitor_app;
814
815                 monitor_app = pbx_findapp("Monitor");
816                 if (monitor_app) {
817                         pbx_exec(monitor_chan, monitor_app, monitor_args);
818                 }
819         }
820 }
821
822 /*!
823  * \internal
824  * \brief Send the peer channel on its way on bridge start failure.
825  * \since 12.0.0
826  *
827  * \param chan Chan to put into autoservice.
828  * \param peer Chan to send to after bridge goto or run hangup handlers and hangup.
829  *
830  * \return Nothing
831  */
832 static void bridge_failed_peer_goto(struct ast_channel *chan, struct ast_channel *peer)
833 {
834         if (ast_bridge_setup_after_goto(peer)
835                 || ast_pbx_start(peer)) {
836                 ast_autoservice_chan_hangup_peer(chan, peer);
837         }
838 }
839
840 static int pre_bridge_setup(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config,
841                 struct ast_bridge_features *chan_features, struct ast_bridge_features *peer_features)
842 {
843         int res;
844
845         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
846         add_features_datastores(chan, peer, config);
847
848         /*
849          * This is an interesting case.  One example is if a ringing
850          * channel gets redirected to an extension that picks up a
851          * parked call.  This will make sure that the call taken out of
852          * parking gets told that the channel it just got bridged to is
853          * still ringing.
854          */
855         if (ast_channel_state(chan) == AST_STATE_RINGING
856                 && ast_channel_visible_indication(peer) != AST_CONTROL_RINGING) {
857                 ast_indicate(peer, AST_CONTROL_RINGING);
858         }
859
860         bridge_check_monitor(chan, peer);
861
862         set_config_flags(chan, config);
863
864         /* Answer if need be */
865         if (ast_channel_state(chan) != AST_STATE_UP) {
866                 if (ast_raw_answer(chan)) {
867                         return -1;
868                 }
869         }
870
871 #ifdef FOR_DEBUG
872         /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
873         ast_channel_log("Pre-bridge CHAN Channel info", chan);
874         ast_channel_log("Pre-bridge PEER Channel info", peer);
875 #endif
876
877         /*
878          * If we are bridging a call, stop worrying about forwarding
879          * loops.  We presume that if a call is being bridged, that the
880          * humans in charge know what they're doing.  If they don't,
881          * well, what can we do about that?
882          */
883         clear_dialed_interfaces(chan);
884         clear_dialed_interfaces(peer);
885
886         res = 0;
887         ast_channel_lock(chan);
888         res |= ast_bridge_features_ds_append(chan, &config->features_caller);
889         ast_channel_unlock(chan);
890         ast_channel_lock(peer);
891         res |= ast_bridge_features_ds_append(peer, &config->features_callee);
892         ast_channel_unlock(peer);
893
894         if (res) {
895                 return -1;
896         }
897
898         if (config->timelimit) {
899                 struct ast_bridge_features_limits call_duration_limits_chan;
900                 struct ast_bridge_features_limits call_duration_limits_peer;
901                 int abandon_call = 0; /* TRUE if set limits fails so we can abandon the call. */
902
903                 if (ast_bridge_features_limits_construct(&call_duration_limits_chan)) {
904                         ast_log(LOG_ERROR, "Could not construct caller duration limits. Bridge canceled.\n");
905
906                         return -1;
907                 }
908
909                 if (ast_bridge_features_limits_construct(&call_duration_limits_peer)) {
910                         ast_log(LOG_ERROR, "Could not construct callee duration limits. Bridge canceled.\n");
911                         ast_bridge_features_limits_destroy(&call_duration_limits_chan);
912
913                         return -1;
914                 }
915
916                 bridge_config_set_limits(config, &call_duration_limits_chan, &call_duration_limits_peer);
917
918                 if (ast_bridge_features_set_limits(chan_features, &call_duration_limits_chan, 0)) {
919                         abandon_call = 1;
920                 }
921                 if (ast_bridge_features_set_limits(peer_features, &call_duration_limits_peer, 0)) {
922                         abandon_call = 1;
923                 }
924
925                 /* At this point we are done with the limits structs since they have been copied to the individual feature sets. */
926                 ast_bridge_features_limits_destroy(&call_duration_limits_chan);
927                 ast_bridge_features_limits_destroy(&call_duration_limits_peer);
928
929                 if (abandon_call) {
930                         ast_log(LOG_ERROR, "Could not set duration limits on one or more sides of the call. Bridge canceled.\n");
931                         return -1;
932                 }
933         }
934
935         return 0;
936 }
937
938 /*!
939  * \brief bridge the call and set CDR
940  *
941  * \param chan The bridge considers this channel the caller.
942  * \param peer The bridge considers this channel the callee.
943  * \param config Configuration for this bridge.
944  *
945  * Set start time, check for two channels,check if monitor on
946  * check for feature activation, create new CDR
947  * \retval res on success.
948  * \retval -1 on failure to bridge.
949  */
950 int ast_bridge_call(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
951 {
952         int res;
953         struct ast_bridge *bridge;
954         struct ast_bridge_features chan_features;
955         struct ast_bridge_features *peer_features;
956
957         /* Setup features. */
958         res = ast_bridge_features_init(&chan_features);
959         peer_features = ast_bridge_features_new();
960         if (res || !peer_features) {
961                 ast_bridge_features_destroy(peer_features);
962                 ast_bridge_features_cleanup(&chan_features);
963                 bridge_failed_peer_goto(chan, peer);
964                 return -1;
965         }
966
967         if (pre_bridge_setup(chan, peer, config, &chan_features, peer_features)) {
968                 ast_bridge_features_destroy(peer_features);
969                 ast_bridge_features_cleanup(&chan_features);
970                 bridge_failed_peer_goto(chan, peer);
971                 return -1;
972         }
973
974         /* Create bridge */
975         bridge = ast_bridge_basic_new();
976         if (!bridge) {
977                 ast_bridge_features_destroy(peer_features);
978                 ast_bridge_features_cleanup(&chan_features);
979                 bridge_failed_peer_goto(chan, peer);
980                 return -1;
981         }
982
983         /* Put peer into the bridge */
984         if (ast_bridge_impart(bridge, peer, NULL, peer_features, 1)) {
985                 ast_bridge_destroy(bridge);
986                 ast_bridge_features_cleanup(&chan_features);
987                 bridge_failed_peer_goto(chan, peer);
988                 return -1;
989         }
990
991         /* Join bridge */
992         ast_bridge_join(bridge, chan, NULL, &chan_features, NULL, 1);
993
994         /*
995          * If the bridge was broken for a hangup that isn't real, then
996          * don't run the h extension, because the channel isn't really
997          * hung up.  This should really only happen with
998          * AST_SOFTHANGUP_ASYNCGOTO.
999          */
1000         res = -1;
1001         ast_channel_lock(chan);
1002         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
1003                 res = 0;
1004         }
1005         ast_channel_unlock(chan);
1006
1007         ast_bridge_features_cleanup(&chan_features);
1008
1009         if (res && config->end_bridge_callback) {
1010                 config->end_bridge_callback(config->end_bridge_callback_data);
1011         }
1012
1013         return res;
1014 }
1015
1016 enum play_tone_action {
1017         PLAYTONE_NONE = 0,
1018         PLAYTONE_CHANNEL1 = (1 << 0),
1019         PLAYTONE_CHANNEL2 = (1 << 1),
1020         PLAYTONE_BOTH = PLAYTONE_CHANNEL1 | PLAYTONE_CHANNEL2,
1021 };
1022
1023 static enum play_tone_action parse_playtone(const char *playtone_val)
1024 {
1025         if (ast_strlen_zero(playtone_val) || ast_false(playtone_val)) {
1026                 return PLAYTONE_NONE;
1027         } if (!strcasecmp(playtone_val, "channel1")) {
1028                 return PLAYTONE_CHANNEL1;
1029         } else if (!strcasecmp(playtone_val, "channel2") || ast_true(playtone_val)) {
1030                 return PLAYTONE_CHANNEL2;
1031         } else if (!strcasecmp(playtone_val, "both")) {
1032                 return PLAYTONE_BOTH;
1033         } else {
1034                 /* Invalid input. Assume none */
1035                 return PLAYTONE_NONE;
1036         }
1037 }
1038
1039 /*!
1040  * \brief Bridge channels together
1041  * \param s
1042  * \param m
1043  *
1044  * Make sure valid channels were specified,
1045  * send errors if any of the channels could not be found/locked, answer channels if needed,
1046  * create the placeholder channels and grab the other channels
1047  * make the channels compatible, send error if we fail doing so
1048  * setup the bridge thread object and start the bridge.
1049  *
1050  * \retval 0
1051  */
1052 static int action_bridge(struct mansession *s, const struct message *m)
1053 {
1054         const char *channela = astman_get_header(m, "Channel1");
1055         const char *channelb = astman_get_header(m, "Channel2");
1056         enum play_tone_action playtone = parse_playtone(astman_get_header(m, "Tone"));
1057         RAII_VAR(struct ast_channel *, chana, NULL, ao2_cleanup);
1058         RAII_VAR(struct ast_channel *, chanb, NULL, ao2_cleanup);
1059         const char *chana_exten;
1060         const char *chana_context;
1061         int chana_priority;
1062         const char *chanb_exten;
1063         const char *chanb_context;
1064         int chanb_priority;
1065         struct ast_bridge *bridge;
1066         char buf[256];
1067         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_a, NULL, ao2_cleanup);
1068         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_b, NULL, ao2_cleanup);
1069
1070         /* make sure valid channels were specified */
1071         if (ast_strlen_zero(channela) || ast_strlen_zero(channelb)) {
1072                 astman_send_error(s, m, "Missing channel parameter in request");
1073                 return 0;
1074         }
1075
1076         ast_debug(1, "Performing Bridge action on %s and %s\n", channela, channelb);
1077
1078         /* Start with chana */
1079         chana = ast_channel_get_by_name_prefix(channela, strlen(channela));
1080         if (!chana) {
1081                 snprintf(buf, sizeof(buf), "Channel1 does not exist: %s", channela);
1082                 astman_send_error(s, m, buf);
1083                 return 0;
1084         }
1085         xfer_cfg_a = ast_get_chan_features_xfer_config(chana);
1086         ast_channel_lock(chana);
1087         chana_exten = ast_strdupa(ast_channel_exten(chana));
1088         chana_context = ast_strdupa(ast_channel_context(chana));
1089         chana_priority = ast_channel_priority(chana);
1090         if (!ast_test_flag(ast_channel_flags(chana), AST_FLAG_IN_AUTOLOOP)) {
1091                 chana_priority++;
1092         }
1093         ast_channel_unlock(chana);
1094
1095         chanb = ast_channel_get_by_name_prefix(channelb, strlen(channelb));
1096         if (!chanb) {
1097                 snprintf(buf, sizeof(buf), "Channel2 does not exist: %s", channelb);
1098                 astman_send_error(s, m, buf);
1099                 return 0;
1100         }
1101         xfer_cfg_b = ast_get_chan_features_xfer_config(chanb);
1102         ast_channel_lock(chanb);
1103         chanb_exten = ast_strdupa(ast_channel_exten(chanb));
1104         chanb_context = ast_strdupa(ast_channel_context(chanb));
1105         chanb_priority = ast_channel_priority(chanb);
1106         if (!ast_test_flag(ast_channel_flags(chanb), AST_FLAG_IN_AUTOLOOP)) {
1107                 chanb_priority++;
1108         }
1109         ast_channel_unlock(chanb);
1110
1111         bridge = ast_bridge_basic_new();
1112         if (!bridge) {
1113                 astman_send_error(s, m, "Unable to create bridge\n");
1114                 return 0;
1115         }
1116
1117         ast_bridge_set_after_go_on(chana, chana_context, chana_exten, chana_priority, NULL);
1118         if (ast_bridge_add_channel(bridge, chana, NULL, playtone & PLAYTONE_CHANNEL1, xfer_cfg_a ? xfer_cfg_a->xfersound : NULL)) {
1119                 snprintf(buf, sizeof(buf), "Unable to add Channel1 to bridge: %s", ast_channel_name(chana));
1120                 astman_send_error(s, m, buf);
1121                 ast_bridge_destroy(bridge);
1122                 return 0;
1123         }
1124
1125         ast_bridge_set_after_go_on(chanb, chanb_context, chanb_exten, chanb_priority, NULL);
1126         if (ast_bridge_add_channel(bridge, chanb, NULL, playtone & PLAYTONE_CHANNEL2, xfer_cfg_b ? xfer_cfg_b->xfersound : NULL)) {
1127                 snprintf(buf, sizeof(buf), "Unable to add Channel2 to bridge: %s", ast_channel_name(chanb));
1128                 astman_send_error(s, m, buf);
1129                 ast_bridge_destroy(bridge);
1130                 return 0;
1131         }
1132
1133         astman_send_ack(s, m, "Channels have been bridged");
1134
1135         return 0;
1136 }
1137
1138 static char *app_bridge = "Bridge";
1139
1140 enum {
1141         BRIDGE_OPT_PLAYTONE = (1 << 0),
1142         OPT_CALLEE_HANGUP =     (1 << 1),
1143         OPT_CALLER_HANGUP =     (1 << 2),
1144         OPT_DURATION_LIMIT = (1 << 3),
1145         OPT_DURATION_STOP =     (1 << 4),
1146         OPT_CALLEE_TRANSFER = (1 << 5),
1147         OPT_CALLER_TRANSFER = (1 << 6),
1148         OPT_CALLEE_MONITOR = (1 << 7),
1149         OPT_CALLER_MONITOR = (1 << 8),
1150         OPT_CALLEE_PARK = (1 << 9),
1151         OPT_CALLER_PARK = (1 << 10),
1152         OPT_CALLEE_KILL = (1 << 11),
1153         OPT_CALLEE_GO_ON = (1 << 12),
1154 };
1155
1156 enum {
1157         OPT_ARG_DURATION_LIMIT = 0,
1158         OPT_ARG_DURATION_STOP,
1159         OPT_ARG_CALLEE_GO_ON,
1160         /* note: this entry _MUST_ be the last one in the enum */
1161         OPT_ARG_ARRAY_SIZE,
1162 };
1163
1164 AST_APP_OPTIONS(bridge_exec_options, BEGIN_OPTIONS
1165         AST_APP_OPTION('p', BRIDGE_OPT_PLAYTONE),
1166         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
1167         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
1168         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
1169         AST_APP_OPTION('k', OPT_CALLEE_PARK),
1170         AST_APP_OPTION('K', OPT_CALLER_PARK),
1171         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
1172         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
1173         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
1174         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
1175         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
1176         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
1177         AST_APP_OPTION('x', OPT_CALLEE_KILL),
1178 END_OPTIONS );
1179
1180 int ast_bridge_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
1181         char *parse, struct timeval *calldurationlimit)
1182 {
1183         char *stringp = ast_strdupa(parse);
1184         char *limit_str, *warning_str, *warnfreq_str;
1185         const char *var;
1186         int play_to_caller = 0, play_to_callee = 0;
1187         int delta;
1188
1189         limit_str = strsep(&stringp, ":");
1190         warning_str = strsep(&stringp, ":");
1191         warnfreq_str = strsep(&stringp, ":");
1192
1193         config->timelimit = atol(limit_str);
1194         if (warning_str)
1195                 config->play_warning = atol(warning_str);
1196         if (warnfreq_str)
1197                 config->warning_freq = atol(warnfreq_str);
1198
1199         if (!config->timelimit) {
1200                 ast_log(LOG_WARNING, "Bridge does not accept L(%s), hanging up.\n", limit_str);
1201                 config->timelimit = config->play_warning = config->warning_freq = 0;
1202                 config->warning_sound = NULL;
1203                 return -1; /* error */
1204         } else if ( (delta = config->play_warning - config->timelimit) > 0) {
1205                 int w = config->warning_freq;
1206
1207                 /*
1208                  * If the first warning is requested _after_ the entire call
1209                  * would end, and no warning frequency is requested, then turn
1210                  * off the warning. If a warning frequency is requested, reduce
1211                  * the 'first warning' time by that frequency until it falls
1212                  * within the call's total time limit.
1213                  *
1214                  * Graphically:
1215                  *                timelim->|    delta        |<-playwarning
1216                  *      0__________________|_________________|
1217                  *                       | w  |    |    |    |
1218                  *
1219                  * so the number of intervals to cut is 1+(delta-1)/w
1220                  */
1221                 if (w == 0) {
1222                         config->play_warning = 0;
1223                 } else {
1224                         config->play_warning -= w * ( 1 + (delta-1)/w );
1225                         if (config->play_warning < 1)
1226                                 config->play_warning = config->warning_freq = 0;
1227                 }
1228         }
1229
1230         ast_channel_lock(chan);
1231
1232         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
1233         play_to_caller = var ? ast_true(var) : 1;
1234
1235         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
1236         play_to_callee = var ? ast_true(var) : 0;
1237
1238         if (!play_to_caller && !play_to_callee)
1239                 play_to_caller = 1;
1240
1241         var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
1242         config->warning_sound = !ast_strlen_zero(var) ? ast_strdup(var) : ast_strdup("timeleft");
1243
1244         /* The code looking at config wants a NULL, not just "", to decide
1245          * that the message should not be played, so we replace "" with NULL.
1246          * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
1247          * not found.
1248          */
1249
1250         var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
1251         config->end_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
1252
1253         var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
1254         config->start_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
1255
1256         ast_channel_unlock(chan);
1257
1258         /* undo effect of S(x) in case they are both used */
1259         calldurationlimit->tv_sec = 0;
1260         calldurationlimit->tv_usec = 0;
1261
1262         /* more efficient to do it like S(x) does since no advanced opts */
1263         if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
1264                 calldurationlimit->tv_sec = config->timelimit / 1000;
1265                 calldurationlimit->tv_usec = (config->timelimit % 1000) * 1000;
1266                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n",
1267                         calldurationlimit->tv_sec + calldurationlimit->tv_usec / 1000000.0);
1268                 play_to_caller = 0;
1269                 play_to_callee = 0;
1270                 config->timelimit = 0;
1271                 config->play_warning = 0;
1272                 config->warning_freq = 0;
1273         } else {
1274                 ast_verb(4, "Limit Data for this call:\n");
1275                 ast_verb(4, "timelimit      = %ld ms (%.3lf s)\n", config->timelimit, config->timelimit / 1000.0);
1276                 ast_verb(4, "play_warning   = %ld ms (%.3lf s)\n", config->play_warning, config->play_warning / 1000.0);
1277                 ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
1278                 ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
1279                 ast_verb(4, "warning_freq   = %ld ms (%.3lf s)\n", config->warning_freq, config->warning_freq / 1000.0);
1280                 ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
1281                 ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
1282                 ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
1283         }
1284         if (play_to_caller)
1285                 ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
1286         if (play_to_callee)
1287                 ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
1288         return 0;
1289 }
1290
1291
1292 /*!
1293  * \brief Bridge channels
1294  * \param chan
1295  * \param data channel to bridge with.
1296  *
1297  * Split data, check we aren't bridging with ourself, check valid channel,
1298  * answer call if not already, check compatible channels, setup bridge config
1299  * now bridge call, if transfered party hangs up return to PBX extension.
1300  */
1301 static int bridge_exec(struct ast_channel *chan, const char *data)
1302 {
1303         RAII_VAR(struct ast_channel *, current_dest_chan, NULL, ao2_cleanup);
1304         char *tmp_data  = NULL;
1305         struct ast_flags opts = { 0, };
1306         struct ast_bridge_config bconfig = { { 0, }, };
1307         char *opt_args[OPT_ARG_ARRAY_SIZE];
1308         struct timeval calldurationlimit = { 0, };
1309         const char *context;
1310         const char *extension;
1311         int priority;
1312         struct ast_bridge_features chan_features;
1313         struct ast_bridge_features *peer_features;
1314         struct ast_bridge *bridge;
1315         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
1316
1317         AST_DECLARE_APP_ARGS(args,
1318                 AST_APP_ARG(dest_chan);
1319                 AST_APP_ARG(options);
1320         );
1321
1322         if (ast_strlen_zero(data)) {
1323                 ast_log(LOG_WARNING, "Bridge require at least 1 argument specifying the other end of the bridge\n");
1324                 return -1;
1325         }
1326
1327         tmp_data = ast_strdupa(data);
1328         AST_STANDARD_APP_ARGS(args, tmp_data);
1329         if (!ast_strlen_zero(args.options))
1330                 ast_app_parse_options(bridge_exec_options, &opts, opt_args, args.options);
1331
1332         /* make sure we have a valid end point */
1333         if (!(current_dest_chan = ast_channel_get_by_name_prefix(args.dest_chan,
1334                         strlen(args.dest_chan)))) {
1335                 ast_log(LOG_WARNING, "Bridge failed because channel %s does not exist\n",
1336                         args.dest_chan);
1337                 return 0;
1338         }
1339
1340         /* avoid bridge with ourselves */
1341         if (chan == current_dest_chan) {
1342                 ast_log(LOG_WARNING, "Unable to bridge channel %s with itself\n", ast_channel_name(chan));
1343                 return 0;
1344         }
1345
1346         if (ast_test_flag(&opts, OPT_DURATION_LIMIT)
1347                 && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])
1348                 && ast_bridge_timelimit(chan, &bconfig, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit)) {
1349                 pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "FAILURE");
1350                 goto done;
1351         }
1352
1353         if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER))
1354                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_REDIRECT);
1355         if (ast_test_flag(&opts, OPT_CALLER_TRANSFER))
1356                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_REDIRECT);
1357         if (ast_test_flag(&opts, OPT_CALLEE_HANGUP))
1358                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
1359         if (ast_test_flag(&opts, OPT_CALLER_HANGUP))
1360                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
1361         if (ast_test_flag(&opts, OPT_CALLEE_MONITOR))
1362                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_AUTOMON);
1363         if (ast_test_flag(&opts, OPT_CALLER_MONITOR))
1364                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_AUTOMON);
1365         if (ast_test_flag(&opts, OPT_CALLEE_PARK))
1366                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_PARKCALL);
1367         if (ast_test_flag(&opts, OPT_CALLER_PARK))
1368                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_PARKCALL);
1369
1370         /* Setup after bridge goto location. */
1371         if (ast_test_flag(&opts, OPT_CALLEE_GO_ON)) {
1372                 ast_channel_lock(chan);
1373                 context = ast_strdupa(ast_channel_context(chan));
1374                 extension = ast_strdupa(ast_channel_exten(chan));
1375                 priority = ast_channel_priority(chan);
1376                 ast_channel_unlock(chan);
1377                 ast_bridge_set_after_go_on(current_dest_chan, context, extension, priority,
1378                         opt_args[OPT_ARG_CALLEE_GO_ON]);
1379         } else if (!ast_test_flag(&opts, OPT_CALLEE_KILL)) {
1380                 ast_channel_lock(current_dest_chan);
1381                 context = ast_strdupa(ast_channel_context(current_dest_chan));
1382                 extension = ast_strdupa(ast_channel_exten(current_dest_chan));
1383                 priority = ast_channel_priority(current_dest_chan);
1384                 ast_channel_unlock(current_dest_chan);
1385                 ast_bridge_set_after_goto(current_dest_chan, context, extension, priority);
1386         }
1387
1388         if (ast_bridge_features_init(&chan_features)) {
1389                 ast_bridge_features_cleanup(&chan_features);
1390                 goto done;
1391         }
1392
1393         peer_features = ast_bridge_features_new();
1394         if (!peer_features) {
1395                 ast_bridge_features_cleanup(&chan_features);
1396                 goto done;
1397         }
1398
1399         if (pre_bridge_setup(chan, current_dest_chan, &bconfig, &chan_features, peer_features)) {
1400                 ast_bridge_features_destroy(peer_features);
1401                 ast_bridge_features_cleanup(&chan_features);
1402                 goto done;
1403         }
1404
1405         bridge = ast_bridge_basic_new();
1406         if (!bridge) {
1407                 ast_bridge_features_destroy(peer_features);
1408                 ast_bridge_features_cleanup(&chan_features);
1409                 goto done;
1410         }
1411
1412         xfer_cfg = ast_get_chan_features_xfer_config(current_dest_chan);
1413         if (ast_bridge_add_channel(bridge, current_dest_chan, peer_features,
1414                 ast_test_flag(&opts, BRIDGE_OPT_PLAYTONE), xfer_cfg ? xfer_cfg->xfersound : NULL)) {
1415                 ast_bridge_features_destroy(peer_features);
1416                 ast_bridge_features_cleanup(&chan_features);
1417                 ast_bridge_destroy(bridge);
1418                 goto done;
1419         }
1420
1421         ast_bridge_join(bridge, chan, NULL, &chan_features, NULL, 1);
1422
1423         ast_bridge_features_cleanup(&chan_features);
1424
1425         /* The bridge has ended, set BRIDGERESULT to SUCCESS. */
1426         pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "SUCCESS");
1427 done:
1428         ast_free((char *) bconfig.warning_sound);
1429         ast_free((char *) bconfig.end_sound);
1430         ast_free((char *) bconfig.start_sound);
1431
1432         return 0;
1433 }
1434
1435 /*!
1436  * \internal
1437  * \brief Clean up resources on Asterisk shutdown
1438  */
1439 static void features_shutdown(void)
1440 {
1441         ast_features_config_shutdown();
1442
1443         ast_manager_unregister("Bridge");
1444
1445         ast_unregister_application(app_bridge);
1446
1447 }
1448
1449 int ast_features_init(void)
1450 {
1451         int res;
1452
1453         res = ast_features_config_init();
1454         if (res) {
1455                 return res;
1456         }
1457         res |= ast_register_application2(app_bridge, bridge_exec, NULL, NULL, NULL);
1458         res |= ast_manager_register_xml_core("Bridge", EVENT_FLAG_CALL, action_bridge);
1459
1460         if (res) {
1461                 features_shutdown();
1462         } else {
1463                 ast_register_atexit(features_shutdown);
1464         }
1465
1466         return res;
1467 }