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