Fixes to include signal.h
[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_REGISTER_FILE()
43
44 #include "asterisk/_private.h"
45
46 #include <pthread.h>
47 #include <signal.h>
48 #include <sys/time.h>
49 #include <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/audiohook.h"
70 #include "asterisk/global_datastores.h"
71 #include "asterisk/astobj2.h"
72 #include "asterisk/test.h"
73 #include "asterisk/bridge.h"
74 #include "asterisk/bridge_features.h"
75 #include "asterisk/bridge_basic.h"
76 #include "asterisk/bridge_after.h"
77 #include "asterisk/stasis.h"
78 #include "asterisk/stasis_channels.h"
79 #include "asterisk/features_config.h"
80 #include "asterisk/max_forwards.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         unsigned int return_to_pbx:1;
318 };
319
320 static void set_config_flags(struct ast_channel *chan, struct ast_bridge_config *config)
321 {
322         ast_clear_flag(config, AST_FLAGS_ALL);
323
324         if (ast_test_flag(&config->features_caller, AST_FEATURE_DTMF_MASK)) {
325                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
326         }
327         if (ast_test_flag(&config->features_callee, AST_FEATURE_DTMF_MASK)) {
328                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_1);
329         }
330
331         if (!(ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_0) && ast_test_flag(config, AST_BRIDGE_DTMF_CHANNEL_1))) {
332                 RAII_VAR(struct ao2_container *, applicationmap, NULL, ao2_cleanup);
333
334                 ast_channel_lock(chan);
335                 applicationmap = ast_get_chan_applicationmap(chan);
336                 ast_channel_unlock(chan);
337
338                 if (!applicationmap) {
339                         return;
340                 }
341
342                 /* If an applicationmap exists for this channel at all, then the channel needs the DTMF flag set */
343                 ast_set_flag(config, AST_BRIDGE_DTMF_CHANNEL_0);
344         }
345 }
346
347 void ast_channel_log(char *title, struct ast_channel *chan);
348
349 void ast_channel_log(char *title, struct ast_channel *chan) /* for debug, this is handy enough to justify keeping it in the source */
350 {
351         ast_log(LOG_NOTICE, "______ %s (%lx)______\n", title, (unsigned long) chan);
352         ast_log(LOG_NOTICE, "CHAN: name: %s;  appl: %s; data: %s; contxt: %s;  exten: %s; pri: %d;\n",
353                 ast_channel_name(chan), ast_channel_appl(chan), ast_channel_data(chan),
354                 ast_channel_context(chan), ast_channel_exten(chan), ast_channel_priority(chan));
355         ast_log(LOG_NOTICE, "CHAN: acctcode: %s;  dialcontext: %s; amaflags: %x; maccontxt: %s;  macexten: %s; macpri: %d;\n",
356                 ast_channel_accountcode(chan), ast_channel_dialcontext(chan), ast_channel_amaflags(chan),
357                 ast_channel_macrocontext(chan), ast_channel_macroexten(chan), ast_channel_macropriority(chan));
358         ast_log(LOG_NOTICE, "CHAN: masq: %p;  masqr: %p; uniqueID: %s; linkedID:%s\n",
359                 ast_channel_masq(chan), ast_channel_masqr(chan),
360                 ast_channel_uniqueid(chan), ast_channel_linkedid(chan));
361         if (ast_channel_masqr(chan)) {
362                 ast_log(LOG_NOTICE, "CHAN: masquerading as: %s;  cdr: %p;\n",
363                         ast_channel_name(ast_channel_masqr(chan)), ast_channel_cdr(ast_channel_masqr(chan)));
364         }
365
366         ast_log(LOG_NOTICE, "===== done ====\n");
367 }
368
369 static void set_bridge_features_on_config(struct ast_bridge_config *config, const char *features)
370 {
371         const char *feature;
372
373         if (ast_strlen_zero(features)) {
374                 return;
375         }
376
377         for (feature = features; *feature; feature++) {
378                 struct ast_flags *party;
379
380                 if (isupper(*feature)) {
381                         party = &config->features_caller;
382                 } else {
383                         party = &config->features_callee;
384                 }
385
386                 switch (tolower(*feature)) {
387                 case 't' :
388                         ast_set_flag(party, AST_FEATURE_REDIRECT);
389                         break;
390                 case 'k' :
391                         ast_set_flag(party, AST_FEATURE_PARKCALL);
392                         break;
393                 case 'h' :
394                         ast_set_flag(party, AST_FEATURE_DISCONNECT);
395                         break;
396                 case 'w' :
397                         ast_set_flag(party, AST_FEATURE_AUTOMON);
398                         break;
399                 case 'x' :
400                         ast_set_flag(party, AST_FEATURE_AUTOMIXMON);
401                         break;
402                 default :
403                         ast_log(LOG_WARNING, "Skipping unknown feature code '%c'\n", *feature);
404                         break;
405                 }
406         }
407 }
408
409 static void add_features_datastores(struct ast_channel *caller, struct ast_channel *callee, struct ast_bridge_config *config)
410 {
411         if (add_features_datastore(caller, &config->features_caller, &config->features_callee)) {
412                 /*
413                  * If we don't return here, then when we do a builtin_atxfer we
414                  * will copy the disconnect flags over from the atxfer to the
415                  * callee (Party C).
416                  */
417                 return;
418         }
419
420         add_features_datastore(callee, &config->features_callee, &config->features_caller);
421 }
422
423 static void bridge_config_set_limits_warning_values(struct ast_bridge_config *config, struct ast_bridge_features_limits *limits)
424 {
425         if (config->end_sound) {
426                 ast_string_field_set(limits, duration_sound, config->end_sound);
427         }
428
429         if (config->warning_sound) {
430                 ast_string_field_set(limits, warning_sound, config->warning_sound);
431         }
432
433         if (config->start_sound) {
434                 ast_string_field_set(limits, connect_sound, config->start_sound);
435         }
436
437         limits->frequency = config->warning_freq;
438         limits->warning = config->play_warning;
439 }
440
441 /*!
442  * \internal brief Setup limit hook structures on calls that need limits
443  *
444  * \param config ast_bridge_config which provides the limit data
445  * \param caller_limits pointer to an ast_bridge_features_limits struct which will store the caller side limits
446  * \param callee_limits pointer to an ast_bridge_features_limits struct which will store the callee side limits
447  */
448 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)
449 {
450         if (ast_test_flag(&config->features_caller, AST_FEATURE_PLAY_WARNING)) {
451                 bridge_config_set_limits_warning_values(config, caller_limits);
452         }
453
454         if (ast_test_flag(&config->features_callee, AST_FEATURE_PLAY_WARNING)) {
455                 bridge_config_set_limits_warning_values(config, callee_limits);
456         }
457
458         caller_limits->duration = config->timelimit;
459         callee_limits->duration = config->timelimit;
460 }
461
462 /*!
463  * \internal
464  * \brief Check if Monitor needs to be started on a channel.
465  * \since 12.0.0
466  *
467  * \param chan The bridge considers this channel the caller.
468  * \param peer The bridge considers this channel the callee.
469  *
470  * \return Nothing
471  */
472 static void bridge_check_monitor(struct ast_channel *chan, struct ast_channel *peer)
473 {
474         const char *value;
475         const char *monitor_args = NULL;
476         struct ast_channel *monitor_chan = NULL;
477
478         ast_channel_lock(chan);
479         value = pbx_builtin_getvar_helper(chan, "AUTO_MONITOR");
480         if (!ast_strlen_zero(value)) {
481                 monitor_args = ast_strdupa(value);
482                 monitor_chan = chan;
483         }
484         ast_channel_unlock(chan);
485         if (!monitor_chan) {
486                 ast_channel_lock(peer);
487                 value = pbx_builtin_getvar_helper(peer, "AUTO_MONITOR");
488                 if (!ast_strlen_zero(value)) {
489                         monitor_args = ast_strdupa(value);
490                         monitor_chan = peer;
491                 }
492                 ast_channel_unlock(peer);
493         }
494         if (monitor_chan) {
495                 struct ast_app *monitor_app;
496
497                 monitor_app = pbx_findapp("Monitor");
498                 if (monitor_app) {
499                         pbx_exec(monitor_chan, monitor_app, monitor_args);
500                 }
501         }
502 }
503
504 /*!
505  * \internal
506  * \brief Send the peer channel on its way on bridge start failure.
507  * \since 12.0.0
508  *
509  * \param chan Chan to put into autoservice.
510  * \param peer Chan to send to after bridge goto or run hangup handlers and hangup.
511  *
512  * \return Nothing
513  */
514 static void bridge_failed_peer_goto(struct ast_channel *chan, struct ast_channel *peer)
515 {
516         if (ast_bridge_setup_after_goto(peer)
517                 || ast_pbx_start(peer)) {
518                 ast_autoservice_chan_hangup_peer(chan, peer);
519         }
520 }
521
522 static int pre_bridge_setup(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config,
523                 struct ast_bridge_features *chan_features, struct ast_bridge_features *peer_features)
524 {
525         int res;
526
527         set_bridge_features_on_config(config, pbx_builtin_getvar_helper(chan, "BRIDGE_FEATURES"));
528         add_features_datastores(chan, peer, config);
529
530         /*
531          * This is an interesting case.  One example is if a ringing
532          * channel gets redirected to an extension that picks up a
533          * parked call.  This will make sure that the call taken out of
534          * parking gets told that the channel it just got bridged to is
535          * still ringing.
536          */
537         if (ast_channel_state(chan) == AST_STATE_RINGING
538                 && ast_channel_visible_indication(peer) != AST_CONTROL_RINGING) {
539                 ast_indicate(peer, AST_CONTROL_RINGING);
540         }
541
542         bridge_check_monitor(chan, peer);
543
544         set_config_flags(chan, config);
545
546         /* Answer if need be */
547         if (ast_channel_state(chan) != AST_STATE_UP) {
548                 if (ast_raw_answer(chan)) {
549                         return -1;
550                 }
551         }
552
553 #ifdef FOR_DEBUG
554         /* show the two channels and cdrs involved in the bridge for debug & devel purposes */
555         ast_channel_log("Pre-bridge CHAN Channel info", chan);
556         ast_channel_log("Pre-bridge PEER Channel info", peer);
557 #endif
558
559         res = 0;
560         ast_channel_lock(chan);
561         ast_max_forwards_reset(chan);
562         res |= ast_bridge_features_ds_append(chan, &config->features_caller);
563         ast_channel_unlock(chan);
564         ast_channel_lock(peer);
565         ast_max_forwards_reset(peer);
566         res |= ast_bridge_features_ds_append(peer, &config->features_callee);
567         ast_channel_unlock(peer);
568
569         if (res) {
570                 return -1;
571         }
572
573         if (config->timelimit) {
574                 struct ast_bridge_features_limits call_duration_limits_chan;
575                 struct ast_bridge_features_limits call_duration_limits_peer;
576                 int abandon_call = 0; /* TRUE if set limits fails so we can abandon the call. */
577
578                 if (ast_bridge_features_limits_construct(&call_duration_limits_chan)) {
579                         ast_log(LOG_ERROR, "Could not construct caller duration limits. Bridge canceled.\n");
580
581                         return -1;
582                 }
583
584                 if (ast_bridge_features_limits_construct(&call_duration_limits_peer)) {
585                         ast_log(LOG_ERROR, "Could not construct callee duration limits. Bridge canceled.\n");
586                         ast_bridge_features_limits_destroy(&call_duration_limits_chan);
587
588                         return -1;
589                 }
590
591                 bridge_config_set_limits(config, &call_duration_limits_chan, &call_duration_limits_peer);
592
593                 if (ast_bridge_features_set_limits(chan_features, &call_duration_limits_chan, 0)) {
594                         abandon_call = 1;
595                 }
596                 if (ast_bridge_features_set_limits(peer_features, &call_duration_limits_peer, 0)) {
597                         abandon_call = 1;
598                 }
599
600                 /* At this point we are done with the limits structs since they have been copied to the individual feature sets. */
601                 ast_bridge_features_limits_destroy(&call_duration_limits_chan);
602                 ast_bridge_features_limits_destroy(&call_duration_limits_peer);
603
604                 if (abandon_call) {
605                         ast_log(LOG_ERROR, "Could not set duration limits on one or more sides of the call. Bridge canceled.\n");
606                         return -1;
607                 }
608         }
609
610         return 0;
611 }
612
613 int ast_bridge_call_with_flags(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config, unsigned int flags)
614 {
615         int res;
616         struct ast_bridge *bridge;
617         struct ast_bridge_features chan_features;
618         struct ast_bridge_features *peer_features;
619
620         /* Setup features. */
621         res = ast_bridge_features_init(&chan_features);
622         peer_features = ast_bridge_features_new();
623         if (res || !peer_features) {
624                 ast_bridge_features_destroy(peer_features);
625                 ast_bridge_features_cleanup(&chan_features);
626                 bridge_failed_peer_goto(chan, peer);
627                 return -1;
628         }
629
630         if (pre_bridge_setup(chan, peer, config, &chan_features, peer_features)) {
631                 ast_bridge_features_destroy(peer_features);
632                 ast_bridge_features_cleanup(&chan_features);
633                 bridge_failed_peer_goto(chan, peer);
634                 return -1;
635         }
636
637         /* Create bridge */
638         bridge = ast_bridge_basic_new();
639         if (!bridge) {
640                 ast_bridge_features_destroy(peer_features);
641                 ast_bridge_features_cleanup(&chan_features);
642                 bridge_failed_peer_goto(chan, peer);
643                 return -1;
644         }
645
646         ast_bridge_basic_set_flags(bridge, flags);
647
648         /* Put peer into the bridge */
649         if (ast_bridge_impart(bridge, peer, NULL, peer_features,
650                 AST_BRIDGE_IMPART_CHAN_INDEPENDENT | AST_BRIDGE_IMPART_INHIBIT_JOIN_COLP)) {
651                 ast_bridge_destroy(bridge, 0);
652                 ast_bridge_features_cleanup(&chan_features);
653                 bridge_failed_peer_goto(chan, peer);
654                 return -1;
655         }
656
657         /* Join bridge */
658         ast_bridge_join(bridge, chan, NULL, &chan_features, NULL,
659                 AST_BRIDGE_JOIN_PASS_REFERENCE | AST_BRIDGE_JOIN_INHIBIT_JOIN_COLP);
660
661         /*
662          * If the bridge was broken for a hangup that isn't real, then
663          * don't run the h extension, because the channel isn't really
664          * hung up.  This should really only happen with
665          * AST_SOFTHANGUP_ASYNCGOTO.
666          */
667         res = -1;
668         ast_channel_lock(chan);
669         if (ast_channel_softhangup_internal_flag(chan) & AST_SOFTHANGUP_ASYNCGOTO) {
670                 res = 0;
671         }
672         ast_channel_unlock(chan);
673
674         ast_bridge_features_cleanup(&chan_features);
675
676         if (res && config->end_bridge_callback) {
677                 config->end_bridge_callback(config->end_bridge_callback_data);
678         }
679
680         return res;
681 }
682
683 /*!
684  * \brief bridge the call and set CDR
685  *
686  * \param chan The bridge considers this channel the caller.
687  * \param peer The bridge considers this channel the callee.
688  * \param config Configuration for this bridge.
689  *
690  * Set start time, check for two channels,check if monitor on
691  * check for feature activation, create new CDR
692  * \retval res on success.
693  * \retval -1 on failure to bridge.
694  */
695 int ast_bridge_call(struct ast_channel *chan, struct ast_channel *peer, struct ast_bridge_config *config)
696 {
697         return ast_bridge_call_with_flags(chan, peer, config, 0);
698 }
699
700 enum play_tone_action {
701         PLAYTONE_NONE = 0,
702         PLAYTONE_CHANNEL1 = (1 << 0),
703         PLAYTONE_CHANNEL2 = (1 << 1),
704         PLAYTONE_BOTH = PLAYTONE_CHANNEL1 | PLAYTONE_CHANNEL2,
705 };
706
707 static enum play_tone_action parse_playtone(const char *playtone_val)
708 {
709         if (ast_strlen_zero(playtone_val) || ast_false(playtone_val)) {
710                 return PLAYTONE_NONE;
711         } if (!strcasecmp(playtone_val, "channel1")) {
712                 return PLAYTONE_CHANNEL1;
713         } else if (!strcasecmp(playtone_val, "channel2") || ast_true(playtone_val)) {
714                 return PLAYTONE_CHANNEL2;
715         } else if (!strcasecmp(playtone_val, "both")) {
716                 return PLAYTONE_BOTH;
717         } else {
718                 /* Invalid input. Assume none */
719                 return PLAYTONE_NONE;
720         }
721 }
722
723 /*!
724  * \brief Bridge channels together
725  * \param s
726  * \param m
727  *
728  * Make sure valid channels were specified,
729  * send errors if any of the channels could not be found/locked, answer channels if needed,
730  * create the placeholder channels and grab the other channels
731  * make the channels compatible, send error if we fail doing so
732  * setup the bridge thread object and start the bridge.
733  *
734  * \retval 0
735  */
736 static int action_bridge(struct mansession *s, const struct message *m)
737 {
738         const char *channela = astman_get_header(m, "Channel1");
739         const char *channelb = astman_get_header(m, "Channel2");
740         enum play_tone_action playtone = parse_playtone(astman_get_header(m, "Tone"));
741         RAII_VAR(struct ast_channel *, chana, NULL, ao2_cleanup);
742         RAII_VAR(struct ast_channel *, chanb, NULL, ao2_cleanup);
743         const char *chana_exten;
744         const char *chana_context;
745         int chana_priority;
746         const char *chanb_exten;
747         const char *chanb_context;
748         int chanb_priority;
749         struct ast_bridge *bridge;
750         char buf[256];
751         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_a, NULL, ao2_cleanup);
752         RAII_VAR(struct ast_features_xfer_config *, xfer_cfg_b, NULL, ao2_cleanup);
753
754         /* make sure valid channels were specified */
755         if (ast_strlen_zero(channela) || ast_strlen_zero(channelb)) {
756                 astman_send_error(s, m, "Missing channel parameter in request");
757                 return 0;
758         }
759
760         ast_debug(1, "Performing Bridge action on %s and %s\n", channela, channelb);
761
762         /* Start with chana */
763         chana = ast_channel_get_by_name_prefix(channela, strlen(channela));
764         if (!chana) {
765                 snprintf(buf, sizeof(buf), "Channel1 does not exist: %s", channela);
766                 astman_send_error(s, m, buf);
767                 return 0;
768         }
769         xfer_cfg_a = ast_get_chan_features_xfer_config(chana);
770         ast_channel_lock(chana);
771         chana_exten = ast_strdupa(ast_channel_exten(chana));
772         chana_context = ast_strdupa(ast_channel_context(chana));
773         chana_priority = ast_channel_priority(chana);
774         if (!ast_test_flag(ast_channel_flags(chana), AST_FLAG_IN_AUTOLOOP)) {
775                 chana_priority++;
776         }
777         ast_channel_unlock(chana);
778
779         chanb = ast_channel_get_by_name_prefix(channelb, strlen(channelb));
780         if (!chanb) {
781                 snprintf(buf, sizeof(buf), "Channel2 does not exist: %s", channelb);
782                 astman_send_error(s, m, buf);
783                 return 0;
784         }
785         xfer_cfg_b = ast_get_chan_features_xfer_config(chanb);
786         ast_channel_lock(chanb);
787         chanb_exten = ast_strdupa(ast_channel_exten(chanb));
788         chanb_context = ast_strdupa(ast_channel_context(chanb));
789         chanb_priority = ast_channel_priority(chanb);
790         if (!ast_test_flag(ast_channel_flags(chanb), AST_FLAG_IN_AUTOLOOP)) {
791                 chanb_priority++;
792         }
793         ast_channel_unlock(chanb);
794
795         bridge = ast_bridge_basic_new();
796         if (!bridge) {
797                 astman_send_error(s, m, "Unable to create bridge\n");
798                 return 0;
799         }
800
801         ast_bridge_set_after_go_on(chana, chana_context, chana_exten, chana_priority, NULL);
802         if (ast_bridge_add_channel(bridge, chana, NULL, playtone & PLAYTONE_CHANNEL1, xfer_cfg_a ? xfer_cfg_a->xfersound : NULL)) {
803                 snprintf(buf, sizeof(buf), "Unable to add Channel1 to bridge: %s", ast_channel_name(chana));
804                 astman_send_error(s, m, buf);
805                 ast_bridge_destroy(bridge, 0);
806                 return 0;
807         }
808
809         ast_bridge_set_after_go_on(chanb, chanb_context, chanb_exten, chanb_priority, NULL);
810         if (ast_bridge_add_channel(bridge, chanb, NULL, playtone & PLAYTONE_CHANNEL2, xfer_cfg_b ? xfer_cfg_b->xfersound : NULL)) {
811                 snprintf(buf, sizeof(buf), "Unable to add Channel2 to bridge: %s", ast_channel_name(chanb));
812                 astman_send_error(s, m, buf);
813                 ast_bridge_destroy(bridge, 0);
814                 return 0;
815         }
816
817         astman_send_ack(s, m, "Channels have been bridged");
818         ao2_cleanup(bridge);
819
820         return 0;
821 }
822
823 static char *app_bridge = "Bridge";
824
825 enum {
826         BRIDGE_OPT_PLAYTONE = (1 << 0),
827         OPT_CALLEE_HANGUP =     (1 << 1),
828         OPT_CALLER_HANGUP =     (1 << 2),
829         OPT_DURATION_LIMIT = (1 << 3),
830         OPT_DURATION_STOP =     (1 << 4),
831         OPT_CALLEE_TRANSFER = (1 << 5),
832         OPT_CALLER_TRANSFER = (1 << 6),
833         OPT_CALLEE_MONITOR = (1 << 7),
834         OPT_CALLER_MONITOR = (1 << 8),
835         OPT_CALLEE_PARK = (1 << 9),
836         OPT_CALLER_PARK = (1 << 10),
837         OPT_CALLEE_KILL = (1 << 11),
838         OPT_CALLEE_GO_ON = (1 << 12),
839 };
840
841 enum {
842         OPT_ARG_DURATION_LIMIT = 0,
843         OPT_ARG_DURATION_STOP,
844         OPT_ARG_CALLEE_GO_ON,
845         /* note: this entry _MUST_ be the last one in the enum */
846         OPT_ARG_ARRAY_SIZE,
847 };
848
849 AST_APP_OPTIONS(bridge_exec_options, BEGIN_OPTIONS
850         AST_APP_OPTION('p', BRIDGE_OPT_PLAYTONE),
851         AST_APP_OPTION_ARG('F', OPT_CALLEE_GO_ON, OPT_ARG_CALLEE_GO_ON),
852         AST_APP_OPTION('h', OPT_CALLEE_HANGUP),
853         AST_APP_OPTION('H', OPT_CALLER_HANGUP),
854         AST_APP_OPTION('k', OPT_CALLEE_PARK),
855         AST_APP_OPTION('K', OPT_CALLER_PARK),
856         AST_APP_OPTION_ARG('L', OPT_DURATION_LIMIT, OPT_ARG_DURATION_LIMIT),
857         AST_APP_OPTION_ARG('S', OPT_DURATION_STOP, OPT_ARG_DURATION_STOP),
858         AST_APP_OPTION('t', OPT_CALLEE_TRANSFER),
859         AST_APP_OPTION('T', OPT_CALLER_TRANSFER),
860         AST_APP_OPTION('w', OPT_CALLEE_MONITOR),
861         AST_APP_OPTION('W', OPT_CALLER_MONITOR),
862         AST_APP_OPTION('x', OPT_CALLEE_KILL),
863 END_OPTIONS );
864
865 int ast_bridge_timelimit(struct ast_channel *chan, struct ast_bridge_config *config,
866         char *parse, struct timeval *calldurationlimit)
867 {
868         char *stringp = ast_strdupa(parse);
869         char *limit_str, *warning_str, *warnfreq_str;
870         const char *var;
871         int play_to_caller = 0, play_to_callee = 0;
872         int delta;
873
874         limit_str = strsep(&stringp, ":");
875         warning_str = strsep(&stringp, ":");
876         warnfreq_str = strsep(&stringp, ":");
877
878         config->timelimit = atol(limit_str);
879         if (warning_str)
880                 config->play_warning = atol(warning_str);
881         if (warnfreq_str)
882                 config->warning_freq = atol(warnfreq_str);
883
884         if (!config->timelimit) {
885                 ast_log(LOG_WARNING, "Bridge does not accept L(%s), hanging up.\n", limit_str);
886                 config->timelimit = config->play_warning = config->warning_freq = 0;
887                 config->warning_sound = NULL;
888                 return -1; /* error */
889         } else if ( (delta = config->play_warning - config->timelimit) > 0) {
890                 int w = config->warning_freq;
891
892                 /*
893                  * If the first warning is requested _after_ the entire call
894                  * would end, and no warning frequency is requested, then turn
895                  * off the warning. If a warning frequency is requested, reduce
896                  * the 'first warning' time by that frequency until it falls
897                  * within the call's total time limit.
898                  *
899                  * Graphically:
900                  *                timelim->|    delta        |<-playwarning
901                  *      0__________________|_________________|
902                  *                       | w  |    |    |    |
903                  *
904                  * so the number of intervals to cut is 1+(delta-1)/w
905                  */
906                 if (w == 0) {
907                         config->play_warning = 0;
908                 } else {
909                         config->play_warning -= w * ( 1 + (delta-1)/w );
910                         if (config->play_warning < 1)
911                                 config->play_warning = config->warning_freq = 0;
912                 }
913         }
914
915         ast_channel_lock(chan);
916
917         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLER");
918         play_to_caller = var ? ast_true(var) : 1;
919
920         var = pbx_builtin_getvar_helper(chan, "LIMIT_PLAYAUDIO_CALLEE");
921         play_to_callee = var ? ast_true(var) : 0;
922
923         if (!play_to_caller && !play_to_callee)
924                 play_to_caller = 1;
925
926         var = pbx_builtin_getvar_helper(chan, "LIMIT_WARNING_FILE");
927         config->warning_sound = !ast_strlen_zero(var) ? ast_strdup(var) : ast_strdup("timeleft");
928
929         /* The code looking at config wants a NULL, not just "", to decide
930          * that the message should not be played, so we replace "" with NULL.
931          * Note, pbx_builtin_getvar_helper _can_ return NULL if the variable is
932          * not found.
933          */
934
935         var = pbx_builtin_getvar_helper(chan, "LIMIT_TIMEOUT_FILE");
936         config->end_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
937
938         var = pbx_builtin_getvar_helper(chan, "LIMIT_CONNECT_FILE");
939         config->start_sound = !ast_strlen_zero(var) ? ast_strdup(var) : NULL;
940
941         ast_channel_unlock(chan);
942
943         /* undo effect of S(x) in case they are both used */
944         calldurationlimit->tv_sec = 0;
945         calldurationlimit->tv_usec = 0;
946
947         /* more efficient to do it like S(x) does since no advanced opts */
948         if (!config->play_warning && !config->start_sound && !config->end_sound && config->timelimit) {
949                 calldurationlimit->tv_sec = config->timelimit / 1000;
950                 calldurationlimit->tv_usec = (config->timelimit % 1000) * 1000;
951                 ast_verb(3, "Setting call duration limit to %.3lf seconds.\n",
952                         calldurationlimit->tv_sec + calldurationlimit->tv_usec / 1000000.0);
953                 play_to_caller = 0;
954                 play_to_callee = 0;
955                 config->timelimit = 0;
956                 config->play_warning = 0;
957                 config->warning_freq = 0;
958         } else {
959                 ast_verb(4, "Limit Data for this call:\n");
960                 ast_verb(4, "timelimit      = %ld ms (%.3lf s)\n", config->timelimit, config->timelimit / 1000.0);
961                 ast_verb(4, "play_warning   = %ld ms (%.3lf s)\n", config->play_warning, config->play_warning / 1000.0);
962                 ast_verb(4, "play_to_caller = %s\n", play_to_caller ? "yes" : "no");
963                 ast_verb(4, "play_to_callee = %s\n", play_to_callee ? "yes" : "no");
964                 ast_verb(4, "warning_freq   = %ld ms (%.3lf s)\n", config->warning_freq, config->warning_freq / 1000.0);
965                 ast_verb(4, "start_sound    = %s\n", S_OR(config->start_sound, ""));
966                 ast_verb(4, "warning_sound  = %s\n", config->warning_sound);
967                 ast_verb(4, "end_sound      = %s\n", S_OR(config->end_sound, ""));
968         }
969         if (play_to_caller)
970                 ast_set_flag(&(config->features_caller), AST_FEATURE_PLAY_WARNING);
971         if (play_to_callee)
972                 ast_set_flag(&(config->features_callee), AST_FEATURE_PLAY_WARNING);
973         return 0;
974 }
975
976
977 /*!
978  * \brief Bridge channels
979  * \param chan
980  * \param data channel to bridge with.
981  *
982  * Split data, check we aren't bridging with ourself, check valid channel,
983  * answer call if not already, check compatible channels, setup bridge config
984  * now bridge call, if transferred party hangs up return to PBX extension.
985  */
986 static int bridge_exec(struct ast_channel *chan, const char *data)
987 {
988         struct ast_channel *current_dest_chan;
989         char *tmp_data  = NULL;
990         struct ast_flags opts = { 0, };
991         struct ast_bridge_config bconfig = { { 0, }, };
992         char *opt_args[OPT_ARG_ARRAY_SIZE];
993         struct timeval calldurationlimit = { 0, };
994         const char *context;
995         const char *extension;
996         int priority;
997         int bridge_add_failed;
998         struct ast_bridge_features chan_features;
999         struct ast_bridge_features *peer_features;
1000         struct ast_bridge *bridge;
1001         struct ast_features_xfer_config *xfer_cfg;
1002
1003         AST_DECLARE_APP_ARGS(args,
1004                 AST_APP_ARG(dest_chan);
1005                 AST_APP_ARG(options);
1006         );
1007
1008         if (ast_strlen_zero(data)) {
1009                 ast_log(LOG_WARNING, "Bridge require at least 1 argument specifying the other end of the bridge\n");
1010                 return -1;
1011         }
1012
1013         tmp_data = ast_strdupa(data);
1014         AST_STANDARD_APP_ARGS(args, tmp_data);
1015         if (!ast_strlen_zero(args.options))
1016                 ast_app_parse_options(bridge_exec_options, &opts, opt_args, args.options);
1017
1018         /* make sure we have a valid end point */
1019         current_dest_chan = ast_channel_get_by_name_prefix(args.dest_chan,
1020                 strlen(args.dest_chan));
1021         if (!current_dest_chan) {
1022                 ast_log(LOG_WARNING, "Bridge failed because channel %s does not exist\n",
1023                         args.dest_chan);
1024                 return 0;
1025         }
1026
1027         /* avoid bridge with ourselves */
1028         if (chan == current_dest_chan) {
1029                 ast_channel_unref(current_dest_chan);
1030                 ast_log(LOG_WARNING, "Unable to bridge channel %s with itself\n", ast_channel_name(chan));
1031                 return 0;
1032         }
1033
1034         if (ast_test_flag(&opts, OPT_DURATION_LIMIT)
1035                 && !ast_strlen_zero(opt_args[OPT_ARG_DURATION_LIMIT])
1036                 && ast_bridge_timelimit(chan, &bconfig, opt_args[OPT_ARG_DURATION_LIMIT], &calldurationlimit)) {
1037                 pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "FAILURE");
1038                 goto done;
1039         }
1040
1041         if (ast_test_flag(&opts, OPT_CALLEE_TRANSFER))
1042                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_REDIRECT);
1043         if (ast_test_flag(&opts, OPT_CALLER_TRANSFER))
1044                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_REDIRECT);
1045         if (ast_test_flag(&opts, OPT_CALLEE_HANGUP))
1046                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_DISCONNECT);
1047         if (ast_test_flag(&opts, OPT_CALLER_HANGUP))
1048                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_DISCONNECT);
1049         if (ast_test_flag(&opts, OPT_CALLEE_MONITOR))
1050                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_AUTOMON);
1051         if (ast_test_flag(&opts, OPT_CALLER_MONITOR))
1052                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_AUTOMON);
1053         if (ast_test_flag(&opts, OPT_CALLEE_PARK))
1054                 ast_set_flag(&(bconfig.features_callee), AST_FEATURE_PARKCALL);
1055         if (ast_test_flag(&opts, OPT_CALLER_PARK))
1056                 ast_set_flag(&(bconfig.features_caller), AST_FEATURE_PARKCALL);
1057
1058         /* Setup after bridge goto location. */
1059         if (ast_test_flag(&opts, OPT_CALLEE_GO_ON)) {
1060                 ast_channel_lock(chan);
1061                 context = ast_strdupa(ast_channel_context(chan));
1062                 extension = ast_strdupa(ast_channel_exten(chan));
1063                 priority = ast_channel_priority(chan);
1064                 ast_channel_unlock(chan);
1065                 ast_bridge_set_after_go_on(current_dest_chan, context, extension, priority,
1066                         opt_args[OPT_ARG_CALLEE_GO_ON]);
1067         } else if (!ast_test_flag(&opts, OPT_CALLEE_KILL)) {
1068                 ast_channel_lock(current_dest_chan);
1069                 context = ast_strdupa(ast_channel_context(current_dest_chan));
1070                 extension = ast_strdupa(ast_channel_exten(current_dest_chan));
1071                 priority = ast_channel_priority(current_dest_chan);
1072                 ast_channel_unlock(current_dest_chan);
1073                 ast_bridge_set_after_go_on(current_dest_chan, context, extension, priority, NULL);
1074         }
1075
1076         if (ast_bridge_features_init(&chan_features)) {
1077                 ast_bridge_features_cleanup(&chan_features);
1078                 goto done;
1079         }
1080
1081         peer_features = ast_bridge_features_new();
1082         if (!peer_features) {
1083                 ast_bridge_features_cleanup(&chan_features);
1084                 goto done;
1085         }
1086
1087         if (pre_bridge_setup(chan, current_dest_chan, &bconfig, &chan_features, peer_features)) {
1088                 ast_bridge_features_destroy(peer_features);
1089                 ast_bridge_features_cleanup(&chan_features);
1090                 goto done;
1091         }
1092
1093         bridge = ast_bridge_basic_new();
1094         if (!bridge) {
1095                 ast_bridge_features_destroy(peer_features);
1096                 ast_bridge_features_cleanup(&chan_features);
1097                 goto done;
1098         }
1099
1100         xfer_cfg = ast_get_chan_features_xfer_config(current_dest_chan);
1101         bridge_add_failed = ast_bridge_add_channel(bridge, current_dest_chan, peer_features,
1102                 ast_test_flag(&opts, BRIDGE_OPT_PLAYTONE),
1103                 xfer_cfg ? xfer_cfg->xfersound : NULL);
1104         ao2_cleanup(xfer_cfg);
1105         if (bridge_add_failed) {
1106                 ast_bridge_features_cleanup(&chan_features);
1107                 ast_bridge_destroy(bridge, 0);
1108                 goto done;
1109         }
1110
1111         /* Don't keep the channel ref in case it was not already in a bridge. */
1112         current_dest_chan = ast_channel_unref(current_dest_chan);
1113
1114         ast_bridge_join(bridge, chan, NULL, &chan_features, NULL,
1115                 AST_BRIDGE_JOIN_PASS_REFERENCE);
1116
1117         ast_bridge_features_cleanup(&chan_features);
1118
1119         /* The bridge has ended, set BRIDGERESULT to SUCCESS. */
1120         pbx_builtin_setvar_helper(chan, "BRIDGERESULT", "SUCCESS");
1121 done:
1122         ast_free((char *) bconfig.warning_sound);
1123         ast_free((char *) bconfig.end_sound);
1124         ast_free((char *) bconfig.start_sound);
1125
1126         ast_channel_cleanup(current_dest_chan);
1127         return 0;
1128 }
1129
1130 /*!
1131  * \internal
1132  * \brief Clean up resources on Asterisk shutdown
1133  */
1134 static void features_shutdown(void)
1135 {
1136         ast_features_config_shutdown();
1137
1138         ast_manager_unregister("Bridge");
1139
1140         ast_unregister_application(app_bridge);
1141
1142 }
1143
1144 int ast_features_init(void)
1145 {
1146         int res;
1147
1148         res = ast_features_config_init();
1149         if (res) {
1150                 return res;
1151         }
1152         res |= ast_register_application2(app_bridge, bridge_exec, NULL, NULL, NULL);
1153         res |= ast_manager_register_xml_core("Bridge", EVENT_FLAG_CALL, action_bridge);
1154
1155         if (res) {
1156                 features_shutdown();
1157         } else {
1158                 ast_register_cleanup(features_shutdown);
1159         }
1160
1161         return res;
1162 }