Doxygen comment tweaks.
[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 static int dynamic_dtmf_hook_run_callback(struct ast_bridge_channel *bridge_channel,
562         ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size)
563 {
564         callback(bridge_channel, payload, payload_size);
565         return 0;
566 }
567
568 struct dynamic_dtmf_hook_data {
569         /*! Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER) */
570         unsigned int flags;
571         /*! Offset into app_name[] where the dynamic feature name starts. */
572         int feature_offset;
573         /*! Offset into app_name[] where the MOH class name starts.  (zero if no MOH) */
574         int moh_offset;
575         /*! Offset into app_name[] where the application argument string starts. (zero if no arguments) */
576         int app_args_offset;
577         /*! Application name to run. */
578         char app_name[0];
579 };
580
581 /*!
582  * \internal
583  * \brief Activated dynamic DTMF feature hook.
584  * \since 12.0.0
585  *
586  * \param bridge_channel Channel executing the feature
587  * \param hook_pvt Private data passed in when the hook was created
588  *
589  * \retval 0 Keep the callback hook.
590  * \retval -1 Remove the callback hook.
591  */
592 static int dynamic_dtmf_hook_trip(struct ast_bridge_channel *bridge_channel, void *hook_pvt)
593 {
594         struct dynamic_dtmf_hook_data *pvt = hook_pvt;
595         int (*run_it)(struct ast_bridge_channel *bridge_channel, ast_bridge_custom_callback_fn callback, const void *payload, size_t payload_size);
596         struct dynamic_dtmf_hook_run *run_data;
597         const char *activated_name;
598         size_t len_name;
599         size_t len_args;
600         size_t len_moh;
601         size_t len_feature;
602         size_t len_activated;
603         size_t len_data;
604
605         /* Determine lengths of things. */
606         len_name = strlen(pvt->app_name) + 1;
607         len_args = pvt->app_args_offset ? strlen(&pvt->app_name[pvt->app_args_offset]) + 1 : 0;
608         len_moh = pvt->moh_offset ? strlen(&pvt->app_name[pvt->moh_offset]) + 1 : 0;
609         len_feature = strlen(&pvt->app_name[pvt->feature_offset]) + 1;
610         ast_channel_lock(bridge_channel->chan);
611         activated_name = ast_strdupa(ast_channel_name(bridge_channel->chan));
612         ast_channel_unlock(bridge_channel->chan);
613         len_activated = strlen(activated_name) + 1;
614         len_data = sizeof(*run_data) + len_name + len_args + len_moh + len_feature + len_activated;
615
616         /* Fill in dynamic feature run hook data. */
617         run_data = ast_alloca(len_data);
618         run_data->app_args_offset = len_args ? len_name : 0;
619         run_data->moh_offset = len_moh ? len_name + len_args : 0;
620         run_data->feature_offset = len_name + len_args + len_moh;
621         run_data->activated_offset = len_name + len_args + len_moh + len_feature;
622         strcpy(run_data->app_name, pvt->app_name);/* Safe */
623         if (len_args) {
624                 strcpy(&run_data->app_name[run_data->app_args_offset],
625                         &pvt->app_name[pvt->app_args_offset]);/* Safe */
626         }
627         if (len_moh) {
628                 strcpy(&run_data->app_name[run_data->moh_offset],
629                         &pvt->app_name[pvt->moh_offset]);/* Safe */
630         }
631         strcpy(&run_data->app_name[run_data->feature_offset],
632                 &pvt->app_name[pvt->feature_offset]);/* Safe */
633         strcpy(&run_data->app_name[run_data->activated_offset], activated_name);/* Safe */
634
635         if (ast_test_flag(pvt, AST_FEATURE_FLAG_ONPEER)) {
636                 run_it = ast_bridge_channel_write_callback;
637         } else {
638                 run_it = dynamic_dtmf_hook_run_callback;
639         }
640         run_it(bridge_channel, dynamic_dtmf_hook_callback, run_data, len_data);
641         return 0;
642 }
643
644 /*!
645  * \internal
646  * \brief Add a dynamic DTMF feature hook to the bridge features.
647  * \since 12.0.0
648  *
649  * \param features Bridge features to setup.
650  * \param flags Which side of bridge to run app (AST_FEATURE_FLAG_ONSELF/AST_FEATURE_FLAG_ONPEER).
651  * \param dtmf DTMF trigger sequence.
652  * \param feature_name Name of the dynamic feature.
653  * \param app_name Dialplan application name to run.
654  * \param app_args Dialplan application arguments. (Empty or NULL if no arguments)
655  * \param moh_class MOH class to play to peer. (Empty or NULL if no MOH played)
656  *
657  * \retval 0 on success.
658  * \retval -1 on error.
659  */
660 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)
661 {
662         struct dynamic_dtmf_hook_data *hook_data;
663         size_t len_name = strlen(app_name) + 1;
664         size_t len_args = ast_strlen_zero(app_args) ? 0 : strlen(app_args) + 1;
665         size_t len_moh = ast_strlen_zero(moh_class) ? 0 : strlen(moh_class) + 1;
666         size_t len_feature = strlen(feature_name) + 1;
667         size_t len_data = sizeof(*hook_data) + len_name + len_args + len_moh + len_feature;
668         int res;
669
670         /* Fill in application run hook data. */
671         hook_data = ast_malloc(len_data);
672         if (!hook_data) {
673                 return -1;
674         }
675         hook_data->flags = flags;
676         hook_data->app_args_offset = len_args ? len_name : 0;
677         hook_data->moh_offset = len_moh ? len_name + len_args : 0;
678         hook_data->feature_offset = len_name + len_args + len_moh;
679         strcpy(hook_data->app_name, app_name);/* Safe */
680         if (len_args) {
681                 strcpy(&hook_data->app_name[hook_data->app_args_offset], app_args);/* Safe */
682         }
683         if (len_moh) {
684                 strcpy(&hook_data->app_name[hook_data->moh_offset], moh_class);/* Safe */
685         }
686         strcpy(&hook_data->app_name[hook_data->feature_offset], feature_name);/* Safe */
687
688         res = ast_bridge_dtmf_hook(features, dtmf, dynamic_dtmf_hook_trip, hook_data,
689                 ast_free_ptr, AST_BRIDGE_HOOK_REMOVE_ON_PULL);
690         if (res) {
691                 ast_free(hook_data);
692         }
693         return res;
694 }
695
696 static int setup_dynamic_feature(void *obj, void *arg, void *data, int flags)
697 {
698         struct ast_applicationmap_item *item = obj;
699         struct ast_bridge_features *features = arg;
700         int *res = data;
701
702         *res |= dynamic_dtmf_hook_add(features,
703                 item->activate_on_self ? AST_FEATURE_FLAG_ONSELF : AST_FEATURE_FLAG_ONPEER,
704                 item->dtmf, item->name, item->app, item->app_data, item->moh_class);
705
706         return 0;
707 }
708
709 /*!
710  * \internal
711  * \brief Setup bridge dynamic features.
712  * \since 12.0.0
713  *
714  * \param features Bridge features to setup.
715  * \param chan Get features from this channel.
716  *
717  * \retval 0 on success.
718  * \retval -1 on error.
719  */
720 static int setup_bridge_features_dynamic(struct ast_bridge_features *features, struct ast_channel *chan)
721 {
722         RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
723         int res = 0;
724
725         ast_channel_lock(chan);
726         applicationmap = ast_get_chan_applicationmap(chan);
727         ast_channel_unlock(chan);
728         if (!applicationmap) {
729                 return 0;
730         }
731
732         ao2_callback_data(applicationmap, 0, setup_dynamic_feature, features, &res);
733
734         return res;
735 }
736
737 /* BUGBUG this really should be made a private function of bridge_basic.c after struct ast_call_feature is made an ao2 object. */
738 int ast_bridge_channel_setup_features(struct ast_bridge_channel *bridge_channel)
739 {
740         int res = 0;
741
742         res |= setup_bridge_features_builtin(bridge_channel->features, bridge_channel->chan);
743         res |= setup_bridge_features_dynamic(bridge_channel->features, bridge_channel->chan);
744
745         return res;
746 }
747
748 static void bridge_config_set_limits_warning_values(struct ast_bridge_config *config, struct ast_bridge_features_limits *limits)
749 {
750         if (config->end_sound) {
751                 ast_string_field_set(limits, duration_sound, config->end_sound);
752         }
753
754         if (config->warning_sound) {
755                 ast_string_field_set(limits, warning_sound, config->warning_sound);
756         }
757
758         if (config->start_sound) {
759                 ast_string_field_set(limits, connect_sound, config->start_sound);
760         }
761
762         limits->frequency = config->warning_freq;
763         limits->warning = config->play_warning;
764 }
765
766 /*!
767  * \internal brief Setup limit hook structures on calls that need limits
768  *
769  * \param config ast_bridge_config which provides the limit data
770  * \param caller_limits pointer to an ast_bridge_features_limits struct which will store the caller side limits
771  * \param callee_limits pointer to an ast_bridge_features_limits struct which will store the callee side limits
772  */
773 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)
774 {
775         if (ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING)) {
776                 bridge_config_set_limits_warning_values(config, caller_limits);
777         }
778
779         if (ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING)) {
780                 bridge_config_set_limits_warning_values(config, callee_limits);
781         }
782
783         caller_limits->duration = config->timelimit;
784         callee_limits->duration = config->timelimit;
785 }
786
787 /*!
788  * \internal
789  * \brief Check if Monitor needs to be started on a channel.
790  * \since 12.0.0
791  *
792  * \param chan The bridge considers this channel the caller.
793  * \param peer The bridge considers this channel the callee.
794  *
795  * \return Nothing
796  */
797 static void bridge_check_monitor(struct ast_channel *chan, struct ast_channel *peer)
798 {
799         const char *value;
800         const char *monitor_args = NULL;
801         struct ast_channel *monitor_chan = NULL;
802
803         ast_channel_lock(chan);
804         value = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR");
805         if (!ast_strlen_zero(value)) {
806                 monitor_args = ast_strdupa(value);
807                 monitor_chan = chan;
808         }
809         ast_channel_unlock(chan);
810         if (!monitor_chan) {
811                 ast_channel_lock(peer);
812                 value = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR");
813                 if (!ast_strlen_zero(value)) {
814                         monitor_args = ast_strdupa(value);
815                         monitor_chan = peer;
816                 }
817                 ast_channel_unlock(peer);
818         }
819         if (monitor_chan) {
820                 struct ast_app *monitor_app;
821
822                 monitor_app = pbx_findapp("Monitor");
823                 if (monitor_app) {
824                         pbx_exec(monitor_chan, monitor_app, monitor_args);
825                 }
826         }
827 }
828
829 /*!
830  * \internal
831  * \brief Send the peer channel on its way on bridge start failure.
832  * \since 12.0.0
833  *
834  * \param chan Chan to put into autoservice.
835  * \param peer Chan to send to after bridge goto or run hangup handlers and hangup.
836  *
837  * \return Nothing
838  */
839 static void bridge_failed_peer_goto(struct ast_channel *chan, struct ast_channel *peer)
840 {
841         if (ast_bridge_setup_after_goto(peer)
842                 || ast_pbx_start(peer)) {
843                 ast_autoservice_chan_hangup_peer(chan, peer);
844         }
845 }
846
847 static int pre_bridge_setup(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config,
848                 struct ast_bridge_features *chan_features, struct ast_bridge_features *peer_features)
849 {
850         int res;
851
852         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
853         add_features_datastores(chan, peer, config);
854
855         /*
856          * This is an interesting case.  One example is if a ringing
857          * channel gets redirected to an extension that picks up a
858          * parked call.  This will make sure that the call taken out of
859          * parking gets told that the channel it just got bridged to is
860          * still ringing.
861          */
862         if (ast_channel_state(chan) == AST_STATE_RINGING
863                 && ast_channel_visible_indication(peer) != AST_CONTROL_RINGING) {
864                 ast_indicate(peer, AST_CONTROL_RINGING);
865         }
866
867         bridge_check_monitor(chan, peer);
868
869         set_config_flags(chan, config);
870
871         /* Answer if need be */
872         if (ast_channel_state(chan) != AST_STATE_UP) {
873                 if (ast_raw_answer(chan)) {
874                         return -1;
875                 }
876         }
877
878 #ifdef FOR_DEBUG
879         /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
880         ast_channel_log("Pre-bridge CHAN Channel info", chan);
881         ast_channel_log("Pre-bridge PEER Channel info", peer);
882 #endif
883
884         /*
885          * If we are bridging a call, stop worrying about forwarding
886          * loops.  We presume that if a call is being bridged, that the
887          * humans in charge know what they're doing.  If they don't,
888          * well, what can we do about that?
889          */
890         clear_dialed_interfaces(chan);
891         clear_dialed_interfaces(peer);
892
893         res = 0;
894         ast_channel_lock(chan);
895         res |= ast_bridge_features_ds_append(chan, &config->features_caller);
896         ast_channel_unlock(chan);
897         ast_channel_lock(peer);
898         res |= ast_bridge_features_ds_append(peer, &config->features_callee);
899         ast_channel_unlock(peer);
900
901         if (res) {
902                 return -1;
903         }
904
905         if (config->timelimit) {
906                 struct ast_bridge_features_limits call_duration_limits_chan;
907                 struct ast_bridge_features_limits call_duration_limits_peer;
908                 int abandon_call = 0; /* TRUE if set limits fails so we can abandon the call. */
909
910                 if (ast_bridge_features_limits_construct(&call_duration_limits_chan)) {
911                         ast_log(LOG_ERROR, "Could not construct caller duration limits. Bridge canceled.\n");
912
913                         return -1;
914                 }
915
916                 if (ast_bridge_features_limits_construct(&call_duration_limits_peer)) {
917                         ast_log(LOG_ERROR, "Could not construct callee duration limits. Bridge canceled.\n");
918                         ast_bridge_features_limits_destroy(&call_duration_limits_chan);
919
920                         return -1;
921                 }
922
923                 bridge_config_set_limits(config, &call_duration_limits_chan, &call_duration_limits_peer);
924
925                 if (ast_bridge_features_set_limits(chan_features, &call_duration_limits_chan, 0)) {
926                         abandon_call = 1;
927                 }
928                 if (ast_bridge_features_set_limits(peer_features, &call_duration_limits_peer, 0)) {
929                         abandon_call = 1;
930                 }
931
932                 /* At this point we are done with the limits structs since they have been copied to the individual feature sets. */
933                 ast_bridge_features_limits_destroy(&call_duration_limits_chan);
934                 ast_bridge_features_limits_destroy(&call_duration_limits_peer);
935
936                 if (abandon_call) {
937                         ast_log(LOG_ERROR, "Could not set duration limits on one or more sides of the call. Bridge canceled.\n");
938                         return -1;
939                 }
940         }
941
942         return 0;
943 }
944
945 /*!
946  * \brief bridge the call and set CDR
947  *
948  * \param chan The bridge considers this channel the caller.
949  * \param peer The bridge considers this channel the callee.
950  * \param config Configuration for this bridge.
951  *
952  * Set start time, check for two channels,check if monitor on
953  * check for feature activation, create new CDR
954  * \retval res on success.
955  * \retval -1 on failure to bridge.
956  */
957 int ast_bridge_call(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
958 {
959         int res;
960         struct ast_bridge *bridge;
961         struct ast_bridge_features chan_features;
962         struct ast_bridge_features *peer_features;
963
964         /* Setup features. */
965         res = ast_bridge_features_init(&chan_features);
966         peer_features = ast_bridge_features_new();
967         if (res || !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         if (pre_bridge_setup(chan, peer, config, &chan_features, peer_features)) {
975                 ast_bridge_features_destroy(peer_features);
976                 ast_bridge_features_cleanup(&chan_features);
977                 bridge_failed_peer_goto(chan, peer);
978                 return -1;
979         }
980
981         /* Create bridge */
982         bridge = ast_bridge_basic_new();
983         if (!bridge) {
984                 ast_bridge_features_destroy(peer_features);
985                 ast_bridge_features_cleanup(&chan_features);
986                 bridge_failed_peer_goto(chan, peer);
987                 return -1;
988         }
989
990         /* Put peer into the bridge */
991         if (ast_bridge_impart(bridge, peer, NULL, peer_features, 1)) {
992                 ast_bridge_destroy(bridge);
993                 ast_bridge_features_cleanup(&chan_features);
994                 bridge_failed_peer_goto(chan, peer);
995                 return -1;
996         }
997
998         /* Join bridge */
999         ast_bridge_join(bridge, chan, NULL, &chan_features, NULL, 1);
1000
1001         /*
1002          * If the bridge was broken for a hangup that isn't real, then
1003          * don't run the h extension, because the channel isn't really
1004          * hung up.  This should really only happen with
1005          * AST_SOFTHANGUP_ASYNCGOTO.
1006          */
1007         res = -1;
1008         ast_channel_lock(chan);
1009         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
1010                 res = 0;
1011         }
1012         ast_channel_unlock(chan);
1013
1014         ast_bridge_features_cleanup(&chan_features);
1015
1016         if (res && config->end_bridge_callback) {
1017                 config->end_bridge_callback(config->end_bridge_callback_data);
1018         }
1019
1020         return res;
1021 }
1022
1023 enum play_tone_action {
1024         PLAYTONE_NONE = 0,
1025         PLAYTONE_CHANNEL1 = (1 << 0),
1026         PLAYTONE_CHANNEL2 = (1 << 1),
1027         PLAYTONE_BOTH = PLAYTONE_CHANNEL1 | PLAYTONE_CHANNEL2,
1028 };
1029
1030 static enum play_tone_action parse_playtone(const char *playtone_val)
1031 {
1032         if (ast_strlen_zero(playtone_val) || ast_false(playtone_val)) {
1033                 return PLAYTONE_NONE;
1034         } if (!strcasecmp(playtone_val, "channel1")) {
1035                 return PLAYTONE_CHANNEL1;
1036         } else if (!strcasecmp(playtone_val, "channel2") || ast_true(playtone_val)) {
1037                 return PLAYTONE_CHANNEL2;
1038         } else if (!strcasecmp(playtone_val, "both")) {
1039                 return PLAYTONE_BOTH;
1040         } else {
1041                 /* Invalid input. Assume none */
1042                 return PLAYTONE_NONE;
1043         }
1044 }
1045
1046 /*!
1047  * \brief Bridge channels together
1048  * \param s
1049  * \param m
1050  *
1051  * Make sure valid channels were specified,
1052  * send errors if any of the channels could not be found/locked, answer channels if needed,
1053  * create the placeholder channels and grab the other channels
1054  * make the channels compatible, send error if we fail doing so
1055  * setup the bridge thread object and start the bridge.
1056  *
1057  * \retval 0
1058  */
1059 static int action_bridge(struct mansession *s, const struct message *m)
1060 {
1061         const char *channela = astman_get_header(m, "Channel1");
1062         const char *channelb = astman_get_header(m, "Channel2");
1063         enum play_tone_action playtone = parse_playtone(astman_get_header(m, "Tone"));
1064         RAII_VAR(struct ast_channel *, chana, NULL, ao2_cleanup);
1065         RAII_VAR(struct ast_channel *, chanb, NULL, ao2_cleanup);
1066         const char *chana_exten;
1067         const char *chana_context;
1068         int chana_priority;
1069         const char *chanb_exten;
1070         const char *chanb_context;
1071         int chanb_priority;
1072         struct ast_bridge *bridge;
1073         char buf[256];
1074         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_a, NULL, ao2_cleanup);
1075         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_b, NULL, ao2_cleanup);
1076
1077         /* make sure valid channels were specified */
1078         if (ast_strlen_zero(channela) || ast_strlen_zero(channelb)) {
1079                 astman_send_error(s, m, "Missing channel parameter in request");
1080                 return 0;
1081         }
1082
1083         ast_debug(1, "Performing Bridge action on %s and %s\n", channela, channelb);
1084
1085         /* Start with chana */
1086         chana = ast_channel_get_by_name_prefix(channela, strlen(channela));
1087         if (!chana) {
1088                 snprintf(buf, sizeof(buf), "Channel1 does not exist: %s", channela);
1089                 astman_send_error(s, m, buf);
1090                 return 0;
1091         }
1092         xfer_cfg_a = ast_get_chan_features_xfer_config(chana);
1093         ast_channel_lock(chana);
1094         chana_exten = ast_strdupa(ast_channel_exten(chana));
1095         chana_context = ast_strdupa(ast_channel_context(chana));
1096         chana_priority = ast_channel_priority(chana);
1097         if (!ast_test_flag(ast_channel_flags(chana), AST_FLAG_IN_AUTOLOOP)) {
1098                 chana_priority++;
1099         }
1100         ast_channel_unlock(chana);
1101
1102         chanb = ast_channel_get_by_name_prefix(channelb, strlen(channelb));
1103         if (!chanb) {
1104                 snprintf(buf, sizeof(buf), "Channel2 does not exist: %s", channelb);
1105                 astman_send_error(s, m, buf);
1106                 return 0;
1107         }
1108         xfer_cfg_b = ast_get_chan_features_xfer_config(chanb);
1109         ast_channel_lock(chanb);
1110         chanb_exten = ast_strdupa(ast_channel_exten(chanb));
1111         chanb_context = ast_strdupa(ast_channel_context(chanb));
1112         chanb_priority = ast_channel_priority(chanb);
1113         if (!ast_test_flag(ast_channel_flags(chanb), AST_FLAG_IN_AUTOLOOP)) {
1114                 chanb_priority++;
1115         }
1116         ast_channel_unlock(chanb);
1117
1118         bridge = ast_bridge_basic_new();
1119         if (!bridge) {
1120                 astman_send_error(s, m, "Unable to create bridge\n");
1121                 return 0;
1122         }
1123
1124         ast_bridge_set_after_go_on(chana, chana_context, chana_exten, chana_priority, NULL);
1125         if (ast_bridge_add_channel(bridge, chana, NULL, playtone & PLAYTONE_CHANNEL1, xfer_cfg_a ? xfer_cfg_a->xfersound : NULL)) {
1126                 snprintf(buf, sizeof(buf), "Unable to add Channel1 to bridge: %s", ast_channel_name(chana));
1127                 astman_send_error(s, m, buf);
1128                 ast_bridge_destroy(bridge);
1129                 return 0;
1130         }
1131
1132         ast_bridge_set_after_go_on(chanb, chanb_context, chanb_exten, chanb_priority, NULL);
1133         if (ast_bridge_add_channel(bridge, chanb, NULL, playtone & PLAYTONE_CHANNEL2, xfer_cfg_b ? xfer_cfg_b->xfersound : NULL)) {
1134                 snprintf(buf, sizeof(buf), "Unable to add Channel2 to bridge: %s", ast_channel_name(chanb));
1135                 astman_send_error(s, m, buf);
1136                 ast_bridge_destroy(bridge);
1137                 return 0;
1138         }
1139
1140         astman_send_ack(s, m, "Channels have been bridged");
1141
1142         return 0;
1143 }
1144
1145 static char *app_bridge = "Bridge";
1146
1147 enum {
1148         BRIDGE_OPT_PLAYTONE = (1 << 0),
1149         OPT_CALLEE_HANGUP =     (1 << 1),
1150         OPT_CALLER_HANGUP =     (1 << 2),
1151         OPT_DURATION_LIMIT = (1 << 3),
1152         OPT_DURATION_STOP =     (1 << 4),
1153         OPT_CALLEE_TRANSFER = (1 << 5),
1154         OPT_CALLER_TRANSFER = (1 << 6),
1155         OPT_CALLEE_MONITOR = (1 << 7),
1156         OPT_CALLER_MONITOR = (1 << 8),
1157         OPT_CALLEE_PARK = (1 << 9),
1158         OPT_CALLER_PARK = (1 << 10),
1159         OPT_CALLEE_KILL = (1 << 11),
1160         OPT_CALLEE_GO_ON = (1 << 12),
1161 };
1162
1163 enum {
1164         OPT_ARG_DURATION_LIMIT = 0,
1165         OPT_ARG_DURATION_STOP,
1166         OPT_ARG_CALLEE_GO_ON,
1167         /* note: this entry _MUST_ be the last one in the enum */
1168         OPT_ARG_ARRAY_SIZE,
1169 };
1170
1171 AST_APP_OPTIONS(bridge_exec_options, BEGIN_OPTIONS
1172         AST_APP_OPTION('p', BRIDGE_OPT_PLAYTONE),
1173         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
1174         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
1175         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
1176         AST_APP_OPTION('k', OPT_CALLEE_PARK),
1177         AST_APP_OPTION('K', OPT_CALLER_PARK),
1178         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
1179         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
1180         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
1181         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
1182         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
1183         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
1184         AST_APP_OPTION('x', OPT_CALLEE_KILL),
1185 END_OPTIONS );
1186
1187 int ast_bridge_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
1188         char *parse, struct timeval *calldurationlimit)
1189 {
1190         char *stringp = ast_strdupa(parse);
1191         char *limit_str, *warning_str, *warnfreq_str;
1192         const char *var;
1193         int play_to_caller = 0, play_to_callee = 0;
1194         int delta;
1195
1196         limit_str = strsep(&stringp, ":");
1197         warning_str = strsep(&stringp, ":");
1198         warnfreq_str = strsep(&stringp, ":");
1199
1200         config->timelimit = atol(limit_str);
1201         if (warning_str)
1202                 config->play_warning = atol(warning_str);
1203         if (warnfreq_str)
1204                 config->warning_freq = atol(warnfreq_str);
1205
1206         if (!config->timelimit) {
1207                 ast_log(LOG_WARNING, "Bridge does not accept L(%s), hanging up.\n", limit_str);
1208                 config->timelimit = config->play_warning = config->warning_freq = 0;
1209                 config->warning_sound = NULL;
1210                 return -1; /* error */
1211         } else if ( (delta = config->play_warning - config->timelimit) > 0) {
1212                 int w = config->warning_freq;
1213
1214                 /*
1215                  * If the first warning is requested _after_ the entire call
1216                  * would end, and no warning frequency is requested, then turn
1217                  * off the warning. If a warning frequency is requested, reduce
1218                  * the 'first warning' time by that frequency until it falls
1219                  * within the call's total time limit.
1220                  *
1221                  * Graphically:
1222                  *                timelim->|    delta        |<-playwarning
1223                  *      0__________________|_________________|
1224                  *                       | w  |    |    |    |
1225                  *
1226                  * so the number of intervals to cut is 1+(delta-1)/w
1227                  */
1228                 if (w == 0) {
1229                         config->play_warning = 0;
1230                 } else {
1231                         config->play_warning -= w * ( 1 + (delta-1)/w );
1232                         if (config->play_warning < 1)
1233                                 config->play_warning = config->warning_freq = 0;
1234                 }
1235         }
1236
1237         ast_channel_lock(chan);
1238
1239         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
1240         play_to_caller = var ? ast_true(var) : 1;
1241
1242         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
1243         play_to_callee = var ? ast_true(var) : 0;
1244
1245         if (!play_to_caller && !play_to_callee)
1246                 play_to_caller = 1;
1247
1248         var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
1249         config->warning_sound = !ast_strlen_zero(var) ? ast_strdup(var) : ast_strdup("timeleft");
1250
1251         /* The code looking at config wants a NULL, not just "", to decide
1252          * that the message should not be played, so we replace "" with NULL.
1253          * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
1254          * not found.
1255          */
1256
1257         var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
1258         config->end_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
1259
1260         var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
1261         config->start_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
1262
1263         ast_channel_unlock(chan);
1264
1265         /* undo effect of S(x) in case they are both used */
1266         calldurationlimit->tv_sec = 0;
1267         calldurationlimit->tv_usec = 0;
1268
1269         /* more efficient to do it like S(x) does since no advanced opts */
1270         if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
1271                 calldurationlimit->tv_sec = config->timelimit / 1000;
1272                 calldurationlimit->tv_usec = (config->timelimit % 1000) * 1000;
1273                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n",
1274                         calldurationlimit->tv_sec + calldurationlimit->tv_usec / 1000000.0);
1275                 play_to_caller = 0;
1276                 play_to_callee = 0;
1277                 config->timelimit = 0;
1278                 config->play_warning = 0;
1279                 config->warning_freq = 0;
1280         } else {
1281                 ast_verb(4, "Limit Data for this call:\n");
1282                 ast_verb(4, "timelimit      = %ld ms (%.3lf s)\n", config->timelimit, config->timelimit / 1000.0);
1283                 ast_verb(4, "play_warning   = %ld ms (%.3lf s)\n", config->play_warning, config->play_warning / 1000.0);
1284                 ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
1285                 ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
1286                 ast_verb(4, "warning_freq   = %ld ms (%.3lf s)\n", config->warning_freq, config->warning_freq / 1000.0);
1287                 ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
1288                 ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
1289                 ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
1290         }
1291         if (play_to_caller)
1292                 ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
1293         if (play_to_callee)
1294                 ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
1295         return 0;
1296 }
1297
1298
1299 /*!
1300  * \brief Bridge channels
1301  * \param chan
1302  * \param data channel to bridge with.
1303  *
1304  * Split data, check we aren't bridging with ourself, check valid channel,
1305  * answer call if not already, check compatible channels, setup bridge config
1306  * now bridge call, if transfered party hangs up return to PBX extension.
1307  */
1308 static int bridge_exec(struct ast_channel *chan, const char *data)
1309 {
1310         RAII_VAR(struct ast_channel *, current_dest_chan, NULL, ao2_cleanup);
1311         char *tmp_data  = NULL;
1312         struct ast_flags opts = { 0, };
1313         struct ast_bridge_config bconfig = { { 0, }, };
1314         char *opt_args[OPT_ARG_ARRAY_SIZE];
1315         struct timeval calldurationlimit = { 0, };
1316         const char *context;
1317         const char *extension;
1318         int priority;
1319         struct ast_bridge_features chan_features;
1320         struct ast_bridge_features *peer_features;
1321         struct ast_bridge *bridge;
1322         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg, NULL, ao2_cleanup);
1323
1324         AST_DECLARE_APP_ARGS(args,
1325                 AST_APP_ARG(dest_chan);
1326                 AST_APP_ARG(options);
1327         );
1328
1329         if (ast_strlen_zero(data)) {
1330                 ast_log(LOG_WARNING, "Bridge require at least 1 argument specifying the other end of the bridge\n");
1331                 return -1;
1332         }
1333
1334         tmp_data = ast_strdupa(data);
1335         AST_STANDARD_APP_ARGS(args, tmp_data);
1336         if (!ast_strlen_zero(args.options))
1337                 ast_app_parse_options(bridge_exec_options, &opts, opt_args, args.options);
1338
1339         /* make sure we have a valid end point */
1340         if (!(current_dest_chan = ast_channel_get_by_name_prefix(args.dest_chan,
1341                         strlen(args.dest_chan)))) {
1342                 ast_log(LOG_WARNING, "Bridge failed because channel %s does not exist\n",
1343                         args.dest_chan);
1344                 return 0;
1345         }
1346
1347         /* avoid bridge with ourselves */
1348         if (chan == current_dest_chan) {
1349                 ast_log(LOG_WARNING, "Unable to bridge channel %s with itself\n", ast_channel_name(chan));
1350                 return 0;
1351         }
1352
1353         if (ast_test_flag(&opts, OPT_DURATION_LIMIT)
1354                 && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])
1355                 && ast_bridge_timelimit(chan, &bconfig, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit)) {
1356                 pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "FAILURE");
1357                 goto done;
1358         }
1359
1360         if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER))
1361                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_REDIRECT);
1362         if (ast_test_flag(&opts, OPT_CALLER_TRANSFER))
1363                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_REDIRECT);
1364         if (ast_test_flag(&opts, OPT_CALLEE_HANGUP))
1365                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
1366         if (ast_test_flag(&opts, OPT_CALLER_HANGUP))
1367                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
1368         if (ast_test_flag(&opts, OPT_CALLEE_MONITOR))
1369                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_AUTOMON);
1370         if (ast_test_flag(&opts, OPT_CALLER_MONITOR))
1371                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_AUTOMON);
1372         if (ast_test_flag(&opts, OPT_CALLEE_PARK))
1373                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_PARKCALL);
1374         if (ast_test_flag(&opts, OPT_CALLER_PARK))
1375                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_PARKCALL);
1376
1377         /* Setup after bridge goto location. */
1378         if (ast_test_flag(&opts, OPT_CALLEE_GO_ON)) {
1379                 ast_channel_lock(chan);
1380                 context = ast_strdupa(ast_channel_context(chan));
1381                 extension = ast_strdupa(ast_channel_exten(chan));
1382                 priority = ast_channel_priority(chan);
1383                 ast_channel_unlock(chan);
1384                 ast_bridge_set_after_go_on(current_dest_chan, context, extension, priority,
1385                         opt_args[OPT_ARG_CALLEE_GO_ON]);
1386         } else if (!ast_test_flag(&opts, OPT_CALLEE_KILL)) {
1387                 ast_channel_lock(current_dest_chan);
1388                 context = ast_strdupa(ast_channel_context(current_dest_chan));
1389                 extension = ast_strdupa(ast_channel_exten(current_dest_chan));
1390                 priority = ast_channel_priority(current_dest_chan);
1391                 ast_channel_unlock(current_dest_chan);
1392                 ast_bridge_set_after_goto(current_dest_chan, context, extension, priority);
1393         }
1394
1395         if (ast_bridge_features_init(&chan_features)) {
1396                 ast_bridge_features_cleanup(&chan_features);
1397                 goto done;
1398         }
1399
1400         peer_features = ast_bridge_features_new();
1401         if (!peer_features) {
1402                 ast_bridge_features_cleanup(&chan_features);
1403                 goto done;
1404         }
1405
1406         if (pre_bridge_setup(chan, current_dest_chan, &bconfig, &chan_features, peer_features)) {
1407                 ast_bridge_features_destroy(peer_features);
1408                 ast_bridge_features_cleanup(&chan_features);
1409                 goto done;
1410         }
1411
1412         bridge = ast_bridge_basic_new();
1413         if (!bridge) {
1414                 ast_bridge_features_destroy(peer_features);
1415                 ast_bridge_features_cleanup(&chan_features);
1416                 goto done;
1417         }
1418
1419         xfer_cfg = ast_get_chan_features_xfer_config(current_dest_chan);
1420         if (ast_bridge_add_channel(bridge, current_dest_chan, peer_features,
1421                 ast_test_flag(&opts, BRIDGE_OPT_PLAYTONE), xfer_cfg ? xfer_cfg->xfersound : NULL)) {
1422                 ast_bridge_features_destroy(peer_features);
1423                 ast_bridge_features_cleanup(&chan_features);
1424                 ast_bridge_destroy(bridge);
1425                 goto done;
1426         }
1427
1428         ast_bridge_join(bridge, chan, NULL, &chan_features, NULL, 1);
1429
1430         ast_bridge_features_cleanup(&chan_features);
1431
1432         /* The bridge has ended, set BRIDGERESULT to SUCCESS. */
1433         pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "SUCCESS");
1434 done:
1435         ast_free((char *) bconfig.warning_sound);
1436         ast_free((char *) bconfig.end_sound);
1437         ast_free((char *) bconfig.start_sound);
1438
1439         return 0;
1440 }
1441
1442 /*!
1443  * \internal
1444  * \brief Clean up resources on Asterisk shutdown
1445  */
1446 static void features_shutdown(void)
1447 {
1448         ast_features_config_shutdown();
1449
1450         ast_manager_unregister("Bridge");
1451
1452         ast_unregister_application(app_bridge);
1453
1454 }
1455
1456 int ast_features_init(void)
1457 {
1458         int res;
1459
1460         res = ast_features_config_init();
1461         if (res) {
1462                 return res;
1463         }
1464         res |= ast_register_application2(app_bridge, bridge_exec, NULL, NULL, NULL);
1465         res |= ast_manager_register_xml_core("Bridge", EVENT_FLAG_CALL, action_bridge);
1466
1467         if (res) {
1468                 features_shutdown();
1469         } else {
1470                 ast_register_atexit(features_shutdown);
1471         }
1472
1473         return res;
1474 }